|
| 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 | + |
0 commit comments