-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
160 lines (129 loc) · 4.93 KB
/
app.py
File metadata and controls
160 lines (129 loc) · 4.93 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
"""Flask web interface for PDF Merger"""
import os
import tempfile
import shutil
import traceback
from pathlib import Path
from flask import Flask, render_template, request, jsonify, send_file, flash, redirect, url_for
from flask_cors import CORS
from werkzeug.utils import secure_filename
from pdfmerger import PdfTool
app = Flask(__name__)
app.secret_key = os.urandom(24)
CORS(app)
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB max upload
UPLOAD_FOLDER = Path(tempfile.gettempdir()) / 'pdfmerger_uploads'
OUTPUT_FOLDER = Path(tempfile.gettempdir()) / 'pdfmerger_outputs'
UPLOAD_FOLDER.mkdir(exist_ok=True)
OUTPUT_FOLDER.mkdir(exist_ok=True)
ALLOWED_EXTENSIONS = {'pdf'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('index.html')
@app.route('/merge', methods=['POST'])
def merge():
if 'files' not in request.files:
return jsonify({'error': 'Nessun file caricato'}), 400
files = request.files.getlist('files')
if not files or all(f.filename == '' for f in files):
return jsonify({'error': 'Nessun file selezionato'}), 400
pdf_files = []
for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = UPLOAD_FOLDER / filename
file.save(filepath)
pdf_files.append(str(filepath))
if len(pdf_files) < 2:
return jsonify({'error': 'Carica almeno 2 PDF'}), 400
try:
output_filename = f"merged_{tempfile._RandomNameSequence().rng.getrandbits(128)}.pdf"
output_path = OUTPUT_FOLDER / output_filename
merger = PdfTool()
merger.do_ask = False
merger.operation_cat(
[(f, None) for f in pdf_files],
str(output_path)
)
return jsonify({
'success': True,
'download_url': f'/download/{output_filename}'
})
except Exception as e:
return jsonify({'error': str(e)}), 500
finally:
for f in pdf_files:
try:
os.unlink(f)
except:
pass
@app.route('/split', methods=['POST'])
def split():
if 'file' not in request.files:
return jsonify({'error': 'Nessun file caricato'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'Nessun file selezionato'}), 400
if not allowed_file(file.filename):
return jsonify({'error': 'File non valido'}), 400
try:
filename = secure_filename(file.filename)
filepath = UPLOAD_FOLDER / filename
file.save(filepath)
output_dir = OUTPUT_FOLDER / f"split_{tempfile._RandomNameSequence().rng.getrandbits(64)}"
output_dir.mkdir(exist_ok=True)
merger = PdfTool()
merger.do_ask = False
# Salva nella directory corrente per operation_burst, poi sposta i file
old_cwd = os.getcwd()
os.chdir(str(output_dir))
try:
merger.operation_burst(str(filepath), "page_%04d.pdf")
except SystemExit:
# PdfTool chiama sys.exit() in caso di errore
raise RuntimeError("Errore durante la divisione del PDF")
finally:
os.chdir(old_cwd)
# Crea un archivio ZIP con tutti i file
import zipfile
zip_path = OUTPUT_FOLDER / f"{output_dir.name}.zip"
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for pdf_file in output_dir.glob("*.pdf"):
zipf.write(pdf_file, pdf_file.name)
# Pulisci la directory dei file singoli
shutil.rmtree(output_dir)
return jsonify({
'success': True,
'message': f'PDF diviso in {len(list(zip_path.parent.glob("*.pdf")))} pagine',
'download_url': f'/download/{zip_path.name}'
})
except Exception as e:
print(f"Errore split: {str(e)}")
print(traceback.format_exc())
return jsonify({'error': str(e)}), 500
@app.route('/download/<filename>')
def download(filename):
filepath = OUTPUT_FOLDER / filename
if not filepath.exists():
return jsonify({'error': 'File non trovato'}), 404
return send_file(filepath, as_attachment=True)
@app.route('/cleanup', methods=['POST'])
def cleanup():
"""Pulisce i file temporanei"""
try:
for folder in [UPLOAD_FOLDER, OUTPUT_FOLDER]:
for f in folder.iterdir():
try:
if f.is_file():
f.unlink()
elif f.is_dir():
shutil.rmtree(f)
except:
pass
return jsonify({'success': True, 'message': 'File temporanei puliti'})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)