-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileConversion.py
More file actions
126 lines (103 loc) · 4.24 KB
/
FileConversion.py
File metadata and controls
126 lines (103 loc) · 4.24 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
import os, sys, io, zipfile, threading, warnings
from flask import Flask, request, send_file
from flask_cors import CORS
from PIL import Image, UnidentifiedImageError, ImageFile
from pillow_heif import register_heif_opener
import fitz # PyMuPDF
from werkzeug.utils import secure_filename
from pdf2docx import Converter
from docx2pdf import convert as docx_to_pdf
# Enable HEIC support in PIL
register_heif_opener()
# Allow loading large images
ImageFile.LOAD_TRUNCATED_IMAGES = True
warnings.simplefilter('ignore', Image.DecompressionBombWarning)
# ---------- Helper for exe-friendly base path ----------
def get_app_base():
"""Return base folder whether running as script or frozen exe."""
if getattr(sys, "frozen", False): # running in PyInstaller bundle
return os.path.dirname(sys.executable)
return os.path.abspath(os.path.dirname(__file__))
BASE_DIR = get_app_base()
UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads")
CONVERTED_FOLDER = os.path.join(BASE_DIR, "converted")
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(CONVERTED_FOLDER, exist_ok=True)
# ---------- Flask App ----------
app = Flask(__name__, static_folder=None)
CORS(app)
# Serve the frontend HTML
@app.route("/", methods=["GET"])
def index():
html_path = os.path.join(BASE_DIR, "FileConversion.html")
return send_file(html_path)
# ---------- Utility ----------
def clear_folder(path):
for file in os.listdir(path):
try:
os.remove(os.path.join(path, file))
except Exception:
pass
# ---------- Conversion Logic ----------
def convert_file(conversion_type, filepath, name, ext):
try:
if conversion_type == "heic_to_jpg" and ext == ".heic":
img = Image.open(filepath).convert("RGB")
output_path = os.path.join(CONVERTED_FOLDER, f"{name}.jpg")
img.save(output_path, "JPEG")
elif conversion_type == "image_to_pdf" and ext in [".jpg", ".jpeg", ".png"]:
img = Image.open(filepath).convert("RGB")
output_path = os.path.join(CONVERTED_FOLDER, f"{name}.pdf")
img.save(output_path, "PDF")
elif conversion_type == "pdf_to_jpg" and ext == ".pdf":
doc = fitz.open(filepath)
for page_number in range(len(doc)):
pix = doc.load_page(page_number).get_pixmap()
output_path = os.path.join(CONVERTED_FOLDER, f"{name}_page{page_number+1}.jpg")
pix.save(output_path)
elif conversion_type == "pdf_to_word" and ext == ".pdf":
output_path = os.path.join(CONVERTED_FOLDER, f"{name}.docx")
converter = Converter(filepath)
converter.convert(output_path)
converter.close()
elif conversion_type == "word_to_pdf" and ext == ".docx":
output_path = os.path.join(CONVERTED_FOLDER, f"{name}.pdf")
docx_to_pdf(filepath, output_path)
else:
print(f"[SKIPPED] Unsupported file: {filepath}")
except (UnidentifiedImageError, Exception) as e:
print(f"[ERROR] {filepath}: {e}")
# ---------- Routes ----------
@app.route("/convert", methods=["POST"])
def convert_files():
clear_folder(UPLOAD_FOLDER)
clear_folder(CONVERTED_FOLDER)
conversion_type = request.form.get("conversion_type")
files = request.files.getlist("files")
threads = []
for file in files:
filename = secure_filename(file.filename)
filepath = os.path.join(UPLOAD_FOLDER, filename)
file.save(filepath)
name, ext = os.path.splitext(filename.lower())
thread = threading.Thread(
target=convert_file, args=(conversion_type, filepath, name, ext)
)
thread.start()
threads.append(thread)
for t in threads:
t.join()
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
for filename in os.listdir(CONVERTED_FOLDER):
zipf.write(os.path.join(CONVERTED_FOLDER, filename), filename)
zip_buffer.seek(0)
return send_file(
zip_buffer,
mimetype="application/zip",
as_attachment=True,
download_name="converted_files.zip",
)
# ---------- Entry ----------
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000, debug=False, threaded=True)