File size: 4,604 Bytes
c20726b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

@app.route('/convert', methods=['POST'])
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)