Skip to content

Commit 719484a

Browse files
committed
Primera versión del compresor web
0 parents  commit 719484a

33 files changed

+324
-0
lines changed

.DS_Store

6 KB
Binary file not shown.
2.99 KB
Binary file not shown.

app.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from flask import Flask, request, send_from_directory, render_template
2+
from werkzeug.utils import secure_filename
3+
from PIL import Image
4+
from moviepy.editor import VideoFileClip
5+
import os
6+
from comprimirpdf import compress
7+
8+
app = Flask(__name__)
9+
10+
UPLOAD_FOLDER = 'uploads'
11+
DOWNLOAD_FOLDER = 'downloads'
12+
13+
if not os.path.exists(UPLOAD_FOLDER):
14+
os.makedirs(UPLOAD_FOLDER)
15+
16+
if not os.path.exists(DOWNLOAD_FOLDER):
17+
os.makedirs(DOWNLOAD_FOLDER)
18+
19+
def compress_file(file_path, scale, quality):
20+
if file_path:
21+
file_name, file_extension = os.path.splitext(os.path.basename(file_path))
22+
save_path = os.path.join(DOWNLOAD_FOLDER, f"{file_name}-compressed{file_extension}")
23+
24+
if file_extension.lower() in [".jpg", ".jpeg", ".png"]:
25+
image = Image.open(file_path)
26+
width, height = image.size
27+
new_width = int(width * scale / 100)
28+
new_height = int(height * scale / 100)
29+
new_image = image.resize((new_width, new_height))
30+
new_image.save(save_path, optimize=True, quality=quality)
31+
elif file_extension.lower() in [".mp4", ".avi", ".mov"]:
32+
video = VideoFileClip(file_path)
33+
new_width = int(video.w * scale / 100)
34+
new_height = int(video.h * scale / 100)
35+
new_video = video.resize(width=new_width, height=new_height)
36+
if file_extension.lower() == ".mov":
37+
save_path = f"{file_name}-compressed.mp4"
38+
new_video.write_videofile(save_path)
39+
elif file_extension.lower() == ".pdf":
40+
compress_quality = quality
41+
compress_quality //= 25
42+
compress(file_path, save_path, compress_quality)
43+
44+
return save_path
45+
46+
@app.route('/', methods=['GET', 'POST'])
47+
def home():
48+
if request.method == 'POST':
49+
file = request.files['file']
50+
filename = secure_filename(file.filename)
51+
filepath = os.path.join(UPLOAD_FOLDER, filename)
52+
file.save(filepath)
53+
54+
scale = request.form.get('scale', type=int)
55+
if scale is None:
56+
scale = 50
57+
58+
quality = request.form.get('quality', type=int)
59+
if quality is None:
60+
quality = 85
61+
62+
output_file = compress_file(filepath, scale, quality)
63+
return os.path.basename(output_file)
64+
65+
return render_template('index.html')
66+
67+
@app.route('/downloads/<filename>', methods=['GET'])
68+
def download_file(filename):
69+
return send_from_directory(DOWNLOAD_FOLDER, filename, as_attachment=True)
70+
71+
if __name__ == '__main__':
72+
app.run(debug=True)
73+

comprimirpdf.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Script de Python que utiliza ghoscript para comprimir ficheros PDF.
4+
Niveles de compresión:
5+
0: defecto
6+
1: prepress
7+
2: printer
8+
3: ebook
9+
4: screen
10+
Dependencias: Ghostscript.
11+
En MacOSX aplica la siguiente línea `brew install ghostscript`.
12+
"""
13+
import argparse
14+
import subprocess
15+
import os.path
16+
import sys
17+
import shutil
18+
19+
def compress(input_file_path, output_file_path, power=0):
20+
"""Función para comprimir PDF via Ghostscript """
21+
quality = {
22+
0: '/default',
23+
1: '/prepress',
24+
2: '/printer',
25+
3: '/ebook',
26+
4: '/screen'
27+
}
28+
29+
# Comprovamos si existe el fichero
30+
if not os.path.isfile(input_file_path):
31+
print("Error: invalid path for input PDF file")
32+
sys.exit(1)
33+
34+
#Comprobamos si es un pdf
35+
if input_file_path.split('.')[-1].lower() != 'pdf':
36+
print("Error: input file is not a PDF")
37+
sys.exit(1)
38+
39+
gs = get_ghostscript_path()
40+
print("Compress PDF...")
41+
initial_size = os.path.getsize(input_file_path)
42+
subprocess.call([gs, '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4',
43+
'-dPDFSETTINGS={}'.format(quality[power]),
44+
'-dNOPAUSE', '-dQUIET', '-dBATCH',
45+
'-sOutputFile={}'.format(output_file_path),
46+
input_file_path]
47+
)
48+
final_size = os.path.getsize(output_file_path)
49+
ratio = 1 - (final_size / initial_size)
50+
print("Compression by {0:.0%}.".format(ratio))
51+
print("Final file size is {0:.1f}MB".format(final_size / 1000000))
52+
print("Done.")
53+
54+
55+
def get_ghostscript_path():
56+
gs_names = ['gs', 'gswin32', 'gswin64']
57+
for name in gs_names:
58+
if shutil.which(name):
59+
return shutil.which(name)
60+
raise FileNotFoundError(f'No GhostScript executable was found on path ({"/".join(gs_names)})')

downloads/.DS_Store

6 KB
Binary file not shown.
39.7 KB
Loading
39.7 KB
Loading

downloads/Cat-cool2-compressed.png

83.2 KB
Loading

downloads/Cat-cool4-compressed.png

67.4 KB
Loading

downloads/IMG_0001-compressed.JPG

34.5 KB
Loading

0 commit comments

Comments
 (0)