-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
190 lines (148 loc) · 5.69 KB
/
Copy pathapp.py
File metadata and controls
190 lines (148 loc) · 5.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""
This module provides a Flask web application for uploading PDF files,
extracting HTML and PDF attachments, and downloading the extracted files.
"""
import os
from flask import Flask, request, render_template, send_file, after_this_request
from werkzeug.utils import secure_filename
import fitz # PyMuPDF
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = os.path.join(BASE_DIR, "uploads")
app.config["DOWNLOAD_FOLDER"] = os.path.join(BASE_DIR, "downloads")
app.config["ALLOWED_EXTENSIONS"] = {"pdf"}
# Create the upload folder if it doesn't exist
if not os.path.exists(app.config["UPLOAD_FOLDER"]):
os.makedirs(app.config["UPLOAD_FOLDER"])
# Create the download folder if it doesn't exist
if not os.path.exists(app.config["DOWNLOAD_FOLDER"]):
os.makedirs(app.config["DOWNLOAD_FOLDER"])
# Check if file is a PDF
def allowed_file(filename):
"""
Check if the file is a PDF.
Args:
filename (str): The name of the file.
Returns:
bool: True if the file is a PDF, False otherwise.
"""
return (
"." in filename
and filename.rsplit(".", 1)[1].lower() in app.config["ALLOWED_EXTENSIONS"]
)
# Try decoding with different encodings
def try_decoding(data):
"""
Try decoding the data with different encodings.
Args:
data (bytes): The data to decode.
Returns:
tuple: A tuple containing the decoded data and an error message (if any).
"""
encodings = ["utf-8", "iso-8859-2", "windows-1250"]
for encoding in encodings:
try:
return data.decode(encoding), None
except UnicodeDecodeError:
continue
return None, "Unable to decode with common encodings."
# Extract all HTML and PDF attachments
def extract_content(file_path, password=None):
"""
Extract all HTML and PDF attachments from the given PDF file.
Args:
file_path (str): The path to the PDF file.
password (str, optional): The password for the PDF file. Defaults to None.
Returns:
tuple: A tuple containing the extracted attachments and an error message (if any).
"""
doc: fitz.Document = fitz.open(file_path)
if doc.needs_pass:
if not password or not doc.authenticate(password):
return None, "Incorrect password!"
attachments = []
for i, _ in enumerate(doc.embfile_names()):
attachment_data = doc.embfile_get(i)
if attachment_data[:4] == b"%PDF":
# Save the PDF attachment to a temporary file in downloads folder
temp_file_path = os.path.join(
app.config["DOWNLOAD_FOLDER"], f"attachment_{i}.pdf"
)
with open(temp_file_path, "wb") as f:
f.write(attachment_data)
attachments.append((temp_file_path, "pdf", None))
else:
# Try to decode the attachment using common encodings
content, error = try_decoding(attachment_data)
if error:
attachments.append((None, None, error))
else:
attachments.append((content, "html", None))
doc.close()
if attachments:
return attachments
return None, "No HTML or PDF attachments found!"
# Route for uploading files
@app.route("/", methods=["GET", "POST"])
def upload_file():
"""
Route for uploading files.
Returns:
str: The response to the client.
"""
if request.method == "POST":
# Check if the post request has the file part
if "file" not in request.files:
return "No file part"
file = request.files["file"]
password = request.form.get("password", "")
# If user does not select a file
if file.filename == "":
return "No selected file"
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(filepath)
# Extract attachments using the provided password
attachments = extract_content(filepath, password)
if attachments[0] is None:
return attachments[1]
# Display all attachments
response = ""
for attachment in attachments:
if attachment[1] == "pdf":
att = os.path.basename(attachment[0])
response += f'<a href="/download/{att}">Download PDF Attachment {att}</a><br>'
elif attachment[1] == "html":
response += f"HTML Attachment content:<br>{attachment[0]}<br>"
else:
response += f"Error: {attachment[2]}<br>"
# Delete the uploaded PDF immediately
os.remove(filepath)
return response
return render_template("upload.html")
@app.route("/download/<filename>")
def download_file(filename):
"""
Route for downloading files.
Args:
filename (str): The name of the file to download.
Returns:
Response: The response to the client.
"""
filepath = os.path.join(app.config["DOWNLOAD_FOLDER"], filename)
if os.path.exists(filepath):
@after_this_request
def delete_file(response):
try:
os.remove(filepath) # Delete the file after sending
except OSError as e:
print(f"Error while deleting file: {e}")
return response
return send_file(filepath, as_attachment=True)
return "File not found", 404
# Main function
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
debug = os.environ.get("DEBUG") == "TRUE"
app.run(host="127.0.0.1", port=port, debug=debug)