Spaces:
Sleeping
Sleeping
Update pdf_compressor_app.py
Browse files- pdf_compressor_app.py +86 -0
pdf_compressor_app.py
CHANGED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import subprocess
|
| 4 |
+
from flask import Flask, render_template, request, send_file, Response
|
| 5 |
+
|
| 6 |
+
app = Flask(__name__)
|
| 7 |
+
|
| 8 |
+
# --- CONFIGURACI脫N DE GHOSTSCRIPT ---
|
| 9 |
+
# Definici贸n del tama帽o objetivo en Bytes (18 MB, solo como referencia de la agresividad)
|
| 10 |
+
TARGET_SIZE_BYTES = 18 * 1024 * 1024
|
| 11 |
+
|
| 12 |
+
def compress_pdf_with_ghostscript(input_stream: io.BytesIO, quality: str) -> io.BytesIO:
|
| 13 |
+
"""
|
| 14 |
+
Comprime un PDF usando Ghostscript.
|
| 15 |
+
Aplica una compresi贸n agresiva de im谩genes y metadatos del PDF.
|
| 16 |
+
"""
|
| 17 |
+
output_stream = io.BytesIO()
|
| 18 |
+
input_stream.seek(0)
|
| 19 |
+
|
| 20 |
+
# Argumentos de Ghostscript para compresi贸n
|
| 21 |
+
gs_command = [
|
| 22 |
+
"gs",
|
| 23 |
+
"-sDEVICE=pdfwrite",
|
| 24 |
+
"-dCompatibilityLevel=1.4",
|
| 25 |
+
"-dPDFSETTINGS=/" + quality, # Usar谩 'screen', 'ebook', etc.
|
| 26 |
+
"-dNOPAUSE", "-dBATCH", "-dQUIET",
|
| 27 |
+
"-sOutputFile=-", # Salida a stdout
|
| 28 |
+
"-" # Entrada desde stdin
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
# Ejecutar el comando Ghostscript
|
| 33 |
+
process = subprocess.run(
|
| 34 |
+
gs_command,
|
| 35 |
+
input=input_stream.read(),
|
| 36 |
+
capture_output=True,
|
| 37 |
+
check=True
|
| 38 |
+
)
|
| 39 |
+
output_stream.write(process.stdout)
|
| 40 |
+
output_stream.seek(0)
|
| 41 |
+
return output_stream
|
| 42 |
+
except subprocess.CalledProcessError as e:
|
| 43 |
+
raise Exception(f"Error de Ghostscript: {e.stderr.decode()}")
|
| 44 |
+
except FileNotFoundError:
|
| 45 |
+
raise Exception("Ghostscript no est谩 instalado en el servidor. (Verifica el Dockerfile)")
|
| 46 |
+
except Exception as e:
|
| 47 |
+
raise Exception(f"Error desconocido durante la compresi贸n: {e}")
|
| 48 |
+
|
| 49 |
+
# --- RUTAS ---
|
| 50 |
+
@app.route('/')
|
| 51 |
+
def index():
|
| 52 |
+
"""Muestra la interfaz del compresor."""
|
| 53 |
+
# Aseg煤rate de crear la carpeta templates/ y poner el HTML dentro
|
| 54 |
+
return render_template('compressor_index.html')
|
| 55 |
+
|
| 56 |
+
@app.route('/compress', methods=['POST'])
|
| 57 |
+
def compress_pdf_file():
|
| 58 |
+
"""Ruta para recibir y comprimir el PDF subido."""
|
| 59 |
+
if 'pdf_file' not in request.files:
|
| 60 |
+
return Response('No se seleccion贸 ning煤n archivo PDF', status=400)
|
| 61 |
+
|
| 62 |
+
pdf_file = request.files['pdf_file']
|
| 63 |
+
quality_setting = request.form.get('quality', 'screen')
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
input_stream = io.BytesIO(pdf_file.read())
|
| 67 |
+
original_size = len(input_stream.getvalue())
|
| 68 |
+
|
| 69 |
+
# 1. Comprimir el PDF subido
|
| 70 |
+
compressed_stream = compress_pdf_with_ghostscript(input_stream, quality_setting)
|
| 71 |
+
|
| 72 |
+
# 2. Devolver el archivo comprimido
|
| 73 |
+
return send_file(
|
| 74 |
+
compressed_stream,
|
| 75 |
+
as_attachment=True,
|
| 76 |
+
download_name=f"comprimido_{pdf_file.filename}",
|
| 77 |
+
mimetype='application/pdf'
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return Response(f"Error en la compresi贸n: {str(e)}", status=500)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == '__main__':
|
| 85 |
+
port = int(os.environ.get('PORT', 7860))
|
| 86 |
+
app.run(host='0.0.0.0', port=port, debug=False)
|