Spaces:
Runtime error
Runtime error
| from flask import Flask, request, send_file | |
| import os | |
| import zipfile | |
| import tempfile | |
| import shutil | |
| import rarfile | |
| from werkzeug.utils import secure_filename | |
| from pdf2image import convert_from_path | |
| from PIL import Image | |
| from moviepy.editor import VideoFileClip | |
| from pydub import AudioSegment | |
| app = Flask(__name__) | |
| ALLOWED_EXTENSIONS = {'zip', 'rar', 'pdf', 'wav', 'mp4', 'jpg', 'png', 'jpeg'} | |
| def allowed_file(filename): | |
| return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | |
| def convert_single_file(input_path): | |
| base_name, ext = os.path.splitext(input_path) | |
| if ext.lower() == '.pdf': | |
| # PDF تبدیل به WEBP سپس به PDF | |
| images = convert_from_path(input_path) | |
| output_path = f"{base_name}_converted.pdf" | |
| webp_images = [] | |
| for i, image in enumerate(images): | |
| webp_path = f"{base_name}_page_{i+1}.webp" | |
| image.save(webp_path, 'WEBP') | |
| webp_images.append(Image.open(webp_path)) | |
| webp_images[0].save(output_path, 'PDF', save_all=True, append_images=webp_images[1:]) | |
| return output_path | |
| elif ext.lower() == '.mp4': | |
| # MP4 تبدیل به MKV | |
| output_path = f"{base_name}.mkv" | |
| VideoFileClip(input_path).write_videofile(output_path, codec='libx264') | |
| return output_path | |
| elif ext.lower() == '.wav': | |
| # WAV تبدیل به MP3 | |
| output_path = f"{base_name}.mp3" | |
| AudioSegment.from_wav(input_path).export(output_path, format='mp3') | |
| return output_path | |
| elif ext.lower() in {'.png', '.jpg', '.jpeg'}: | |
| # تصویر تبدیل به WEBP | |
| output_path = f"{base_name}.webp" | |
| Image.open(input_path).save(output_path, 'WEBP') | |
| return output_path | |
| # در صورت نداشتن تغییر، همان مسیر بازگردانده میشود. | |
| return input_path | |
| def handle_conversion(): | |
| if 'file' not in request.files: | |
| return {"error": "No file uploaded"}, 400 | |
| file = request.files['file'] | |
| if not file or file.filename == '': | |
| return {"error": "Empty filename"}, 400 | |
| if not allowed_file(file.filename): | |
| return {"error": "Unsupported file type"}, 400 | |
| try: | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| filename = secure_filename(file.filename) | |
| upload_path = os.path.join(temp_dir, filename) | |
| file.save(upload_path) | |
| file_ext = filename.split('.')[-1].lower() | |
| # اگر فایل تکی باشد، عملیات تبدیل روی همان فایل اعمال شود. | |
| if file_ext in {'pdf', 'wav', 'mp4', 'jpg', 'png', 'jpeg'}: | |
| converted_path = convert_single_file(upload_path) | |
| converted_filename = os.path.basename(converted_path) | |
| return send_file( | |
| converted_path, | |
| as_attachment=True, | |
| download_name=converted_filename | |
| ) | |
| # در صورتی که فایل آرشیو باشد: ابتدا استخراج شود | |
| if filename.endswith('.zip'): | |
| with zipfile.ZipFile(upload_path, 'r') as z: | |
| z.extractall(temp_dir) | |
| else: | |
| with rarfile.RarFile(upload_path, 'r') as r: | |
| r.extractall(temp_dir) | |
| # تبدیل تمام فایلهای موجود در آرشیو | |
| for root, _, files in os.walk(temp_dir): | |
| for f in files: | |
| if f != filename: | |
| input_file = os.path.join(root, f) | |
| convert_single_file(input_file) | |
| # ایجاد فایل آرشیو خروجی | |
| output_path = os.path.join(temp_dir, "converted.zip") | |
| with zipfile.ZipFile(output_path, 'w') as z: | |
| for root, _, files in os.walk(temp_dir): | |
| for f in files: | |
| if f != filename: | |
| full_path = os.path.join(root, f) | |
| z.write(full_path, arcname=f) | |
| return send_file( | |
| output_path, | |
| as_attachment=True, | |
| download_name="converted_files.zip" | |
| ) | |
| except Exception as e: | |
| return {"error": f"Processing failed: {str(e)}"}, 500 | |
| finally: | |
| try: | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| except Exception: | |
| pass | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) | |