File size: 5,769 Bytes
319ea69
c296f8a
cd88e5f
39ac26a
defad0a
319ea69
defad0a
 
 
 
cd88e5f
defad0a
 
9ddae4b
defad0a
 
cd88e5f
 
defad0a
 
cd88e5f
defad0a
 
cd88e5f
 
defad0a
cd88e5f
defad0a
cd88e5f
defad0a
 
cd88e5f
defad0a
 
 
 
 
 
 
 
 
 
 
 
c296f8a
defad0a
 
319ea69
defad0a
 
 
 
 
cd88e5f
defad0a
cd88e5f
defad0a
 
cd88e5f
defad0a
 
cd88e5f
defad0a
 
 
cd88e5f
defad0a
 
cd88e5f
defad0a
 
 
 
 
 
 
cd88e5f
defad0a
 
cd88e5f
defad0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd88e5f
3a12f33
defad0a
 
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
128
129
import gradio as gr
from pydub import AudioSegment
import requests
import os
import uuid # برای تولید نام فایل منحصر به فرد

# مسیر ذخیره فایل‌های موقت
TEMP_DIR = "temp_audio"
if not os.path.exists(TEMP_DIR):
    os.makedirs(TEMP_DIR)

def download_file(url, output_path):
    """فایل را از یک URL دانلود می‌کند."""
    try:
        response = requests.get(url, stream=True)
        response.raise_for_status()  # خطایی رخ داد، آن را بالا ببر
        with open(output_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        return True
    except requests.exceptions.RequestException as e:
        print(f"Error downloading {url}: {e}")
        return False
    except Exception as e:
        print(f"An unexpected error occurred during download of {url}: {e}")
        return False

def get_audio_from_input(input_source):
    """
    منبع ورودی را پردازش کرده و یک شی AudioSegment برمی‌گرداند.
    می‌تواند یک فایل محلی یا یک URL باشد.
    """
    unique_filename = os.path.join(TEMP_DIR, str(uuid.uuid4()))
    
    if input_source.startswith("http://") or input_source.startswith("https://"):
        # این یک URL است، دانلودش کن
        temp_filepath = unique_filename + "_downloaded" + os.path.splitext(input_source)[1].split("?")[0]
        if not download_file(input_source, temp_filepath):
            return None, f"خطا در دانلود فایل از لینک: {input_source}"
        audio_path = temp_filepath
    else:
        # فرض می‌شود یک مسیر فایل محلی است
        audio_path = input_source
    
    try:
        audio = AudioSegment.from_file(audio_path)
        return audio, None
    except Exception as e:
        return None, f"خطا در بارگذاری فایل صوتی ({audio_path}): {e}. مطمئن شوید فایل MP3 یا WAV معتبر است."
    finally:
        # اگر فایل از URL دانلود شده بود، آن را پاک کن
        if 'temp_filepath' in locals() and os.path.exists(temp_filepath):
            os.remove(temp_filepath)

def merge_audio_files(input_sources):
    """
    چندین فایل صوتی را (از لینک یا فایل) ادغام می‌کند و یک فایل MP3 خروجی می‌دهد.
    input_sources: یک رشته حاوی لینک‌ها یا مسیرهای فایل‌ها که با خط جدید جدا شده‌اند.
    """
    if not input_sources.strip():
        return None, "لطفاً حداقل یک لینک یا مسیر فایل وارد کنید."

    sources = [s.strip() for s in input_sources.split('\n') if s.strip()]
    if not sources:
        return None, "خطا: لیست ورودی‌ها خالی است."

    combined_audio = AudioSegment.empty()
    errors = []

    for source in sources:
        audio_segment, error = get_audio_from_input(source)
        if audio_segment:
            combined_audio += audio_segment
        else:
            errors.append(error)
            print(f"Skipping {source} due to error: {error}") # برای debugging کنسول

    if not combined_audio.duration_seconds > 0:
        return None, "هیچ فایل صوتی معتبری برای ادغام پیدا نشد. " + "\n".join(errors) if errors else ""

    output_filename = os.path.join(TEMP_DIR, f"merged_audio_{uuid.uuid4()}.mp3")
    try:
        combined_audio.export(output_filename, format="mp3")
        return output_filename, "عملیات موفقیت آمیز بود!"
    except Exception as e:
        return None, f"خطا در ذخیره فایل خروجی: {e}"

# ایجاد رابط کاربری Gradio
with gr.Blocks() as demo:
    gr.Markdown(
        """
        # ابزار ادغام فایل‌های صوتی (MP3/WAV)
        در اینجا می‌توانید لینک چندین فایل صوتی (MP3 یا WAV) را وارد کنید (هر لینک در یک خط جدید).
        این ابزار تمام فایل‌ها را دانلود کرده و به یک فایل MP3 واحد ادغام می‌کند.
        **نکته:** برای لینک‌های دانلود، مطمئن شوید قابلیت دانلود مستقیم دارند (نه صفحات وب).
        """
    )

    audio_links_input = gr.Textbox(
        label="لینک یا مسیر فایل‌های صوتی (هر کدام در یک خط جدید)",
        placeholder="مثال:\nhttps://example.com/audio1.mp3\n./local_audio.wav\nhttps://example.com/audio2.wav",
        lines=10
    )

    output_message = gr.Textbox(label="پیام", interactive=False)
    output_audio = gr.Audio(label="فایل صوتی ادغام شده", type="filepath")

    merge_button = gr.Button("ادغام فایل‌ها")

    merge_button.click(
        fn=merge_audio_files,
        inputs=[audio_links_input],
        outputs=[output_audio, output_message]
    )
    
    gr.Examples(
        examples=[
            ["https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3\nhttps://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"],
            # اگر فایل‌های واقعی داشته باشید، می‌توانید این خط را فعال کنید:
            # ["./path/to/your/local_audio.mp3\n./path/to/another/local_audio.wav"]
        ],
        inputs=audio_links_input,
        label="نمونه‌ها"
    )

if __name__ == "__main__":
    demo.launch() # برای اجرا در لوکال
    # demo.launch(share=True) # برای اشتراک‌گذاری موقت در یک لینک عمومی (برای هوش مصنوعی)