Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,187 +1,52 @@
|
|
1 |
import gradio as gr
|
2 |
-
import requests
|
3 |
-
import json
|
4 |
-
import os
|
5 |
from pydub import AudioSegment
|
6 |
-
|
7 |
-
|
8 |
-
# --- Configuration ---
|
9 |
-
TALKBOT_TTS_URL = "https://talkbot.ir/TTS-tkun"
|
10 |
-
TALKBOT_API_BASE_URL = "https://talkbot.ir/api/v1/chat/completions"
|
11 |
-
TALKBOT_API_KEY = "sk-4fb613f56acfccf731e801b904cd89f5" # Replace with your actual Talkbot API key
|
12 |
-
# TALKBOT_API_KEY = os.environ.get("TALKBOT_API_KEY", "YOUR_DEFAULT_API_KEY_HERE") # More secure way
|
13 |
-
MODEL_NAME = "deepseek-v3-0324"
|
14 |
-
|
15 |
-
# --- Functions ---
|
16 |
-
|
17 |
-
def get_tts_audio_link(text: str) -> str:
|
18 |
-
"""
|
19 |
-
Retrieves a WAV audio link for the given text using TalkBot TTS.
|
20 |
-
"""
|
21 |
-
params = {"text": text}
|
22 |
-
response = requests.get(TALKBOT_TTS_URL, params=params)
|
23 |
-
response.raise_for_status() # Raise an exception for HTTP errors
|
24 |
-
return response.url
|
25 |
-
|
26 |
-
def generate_podcast_script_ai(prompt: str) -> str:
|
27 |
-
"""
|
28 |
-
Generates a podcast script using TalkBot AI.
|
29 |
-
"""
|
30 |
-
headers = {
|
31 |
-
"Content-Type": "application/json",
|
32 |
-
"Authorization": f"Bearer {TALKBOT_API_KEY}"
|
33 |
-
}
|
34 |
-
|
35 |
-
data = {
|
36 |
-
"model": MODEL_NAME,
|
37 |
-
"messages": [
|
38 |
-
{"role": "system", "content": "شما یک هوش مصنوعی برای تولید متن پادکست هستید. خروجی شما باید متن پادکست باشد."},
|
39 |
-
{"role": "user", "content": prompt}
|
40 |
-
],
|
41 |
-
"temperature": 0.7,
|
42 |
-
"max_tokens": 1000
|
43 |
-
}
|
44 |
-
|
45 |
-
try:
|
46 |
-
response = requests.post(TALKBOT_API_BASE_URL, headers=headers, json=data)
|
47 |
-
response.raise_for_status()
|
48 |
-
result = response.json()
|
49 |
-
return result['choices'][0]['message']['content'].strip()
|
50 |
-
except requests.exceptions.RequestException as e:
|
51 |
-
return f"Error generating script: {e}"
|
52 |
-
except (KeyError, IndexError) as e:
|
53 |
-
return f"Error parsing AI response: {e}. Full response: {response.json()}"
|
54 |
-
|
55 |
-
def create_podcast(podcast_topic: str) -> tuple[str, str, gr.Audio | None]:
|
56 |
-
"""
|
57 |
-
Generates a podcast script using AI, then creates audio for two distinct voices,
|
58 |
-
and finally merges them into an MP3 file.
|
59 |
-
"""
|
60 |
-
if not TALKBOT_API_KEY or TALKBOT_API_KEY == "YOUR_DEFAULT_API_KEY_HERE":
|
61 |
-
return "خطا: کلید API Talkbot تنظیم نشده است. لطفاً آن را در کد وارد کنید.", None, None
|
62 |
-
|
63 |
-
# 1. Generate Podcast Script
|
64 |
-
gr.Info("در حال تولید متن پادکست توسط هوش مصنوعی...")
|
65 |
-
ai_prompt = f"یک متن پادکست کوتاه و جذاب در مورد '{podcast_topic}' با دو بخش مجزا برای دو گوینده (صدای اول و صدای دوم) بنویسید. هر بخش را با عنوان 'صدای اول:' و 'صدای دوم:' مشخص کنید. متن پادکست باید حدود 150-250 کلمه باشد."
|
66 |
-
|
67 |
-
generated_script = generate_podcast_script_ai(ai_prompt)
|
68 |
-
|
69 |
-
if "Error" in generated_script:
|
70 |
-
return generated_script, None, None
|
71 |
-
|
72 |
-
# 2. Extract Voices (simple split for demonstration)
|
73 |
-
gr.Info("در حال تفکیک و تولید صداها...")
|
74 |
-
|
75 |
-
voice1_text = ""
|
76 |
-
voice2_text = ""
|
77 |
-
|
78 |
-
# Simple parsing to get voice sections
|
79 |
-
script_lines = generated_script.split('\n')
|
80 |
-
current_voice = None
|
81 |
-
for line in script_lines:
|
82 |
-
if "صدای اول:" in line:
|
83 |
-
current_voice = 1
|
84 |
-
voice1_text += line.replace("صدای اول:", "").strip() + " "
|
85 |
-
elif "صدای دوم:" in line:
|
86 |
-
current_voice = 2
|
87 |
-
voice2_text += line.replace("صدای دوم:", "").strip() + " "
|
88 |
-
elif current_voice == 1:
|
89 |
-
voice1_text += line.strip() + " "
|
90 |
-
elif current_voice == 2:
|
91 |
-
voice2_text += line.strip() + " "
|
92 |
-
|
93 |
-
if not voice1_text or not voice2_text:
|
94 |
-
return f"خطا: متن پادکست تولید شده شامل 'صدای اول:' یا 'صدای دوم:' استاندارد نیست. متن کامل: \n{generated_script}", None, None
|
95 |
-
|
96 |
-
# 3. Generate Audio for each voice
|
97 |
-
try:
|
98 |
-
gr.Info("در حال دریافت صدای اول...")
|
99 |
-
voice1_wav_link = get_tts_audio_link(voice1_text.strip())
|
100 |
-
voice1_audio_response = requests.get(voice1_wav_link)
|
101 |
-
voice1_audio_response.raise_for_status()
|
102 |
-
|
103 |
-
with open("voice1.wav", "wb") as f:
|
104 |
-
f.write(voice1_audio_response.content)
|
105 |
-
|
106 |
-
gr.Info("در حال دریافت صدای دوم...")
|
107 |
-
voice2_wav_link = get_tts_audio_link(voice2_text.strip())
|
108 |
-
voice2_audio_response = requests.get(voice2_wav_link)
|
109 |
-
voice2_audio_response.raise_or_status()
|
110 |
-
|
111 |
-
with open("voice2.wav", "wb") as f:
|
112 |
-
f.write(voice2_audio_response.content)
|
113 |
-
|
114 |
-
except requests.exceptions.HTTPError as e:
|
115 |
-
return f"خطا در دریافت صدا از TTS: {e}. URL: {e.request.url}", None, None
|
116 |
-
except Exception as e:
|
117 |
-
return f"خطای unexpected در دریافت صدا: {e}", None, None
|
118 |
|
119 |
-
|
120 |
-
gr.Info("در حال ترکیب صداها و تولید فایل نهایی MP3...")
|
121 |
try:
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
# Simple alternating merge - adjust as needed for more complex dialogue
|
126 |
-
# For simplicity, let's just concatenate them here. A more sophisticated
|
127 |
-
# approach would involve splitting the script into turns and interleaving.
|
128 |
-
# Given the prompt, a simple concatenation of voice1's full speech then voice2's full speech might suffice as a starting point.
|
129 |
-
# Or, we can interleave by short segments if the AI output is structured that way.
|
130 |
|
131 |
-
#
|
132 |
-
|
133 |
|
134 |
-
#
|
135 |
-
|
136 |
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
# Clean up temporary WAV files
|
141 |
-
os.remove("voice1.wav")
|
142 |
-
os.remove("voice2.wav")
|
143 |
|
144 |
-
|
145 |
-
return generated_script, output_mp3_path, gr.Audio(output_mp3_path, type="filepath", label="پادکست نهایی")
|
146 |
-
|
147 |
except Exception as e:
|
148 |
-
return f"خطا در
|
149 |
-
|
150 |
-
# --- Gradio Interface ---
|
151 |
-
|
152 |
-
with gr.Blocks() as demo:
|
153 |
-
gr.Markdown(
|
154 |
-
"""
|
155 |
-
# تولیدکننده پادکست هوشمند 🎙️
|
156 |
-
با وارد کردن یک موضوع، هوش مصنوعی ما یک متن پادکست تولید میکند و سپس آن را با دو صدای مجزا به یک فایل MP3 پادکست تبدیل میکند.
|
157 |
-
"""
|
158 |
-
)
|
159 |
|
|
|
|
|
160 |
with gr.Row():
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
fn=on_generate_button_click,
|
182 |
-
inputs=topic_input,
|
183 |
-
outputs=[script_output, audio_output, download_link]
|
184 |
)
|
185 |
|
|
|
186 |
if __name__ == "__main__":
|
187 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
2 |
from pydub import AudioSegment
|
3 |
+
import os
|
4 |
+
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
+
def merge_mp3_files(file1, file2):
|
|
|
7 |
try:
|
8 |
+
# خواندن فایلهای صوتی
|
9 |
+
audio1 = AudioSegment.from_mp3(file1.name)
|
10 |
+
audio2 = AudioSegment.from_mp3(file2.name)
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
# ادغام فایلها
|
13 |
+
combined = audio1 + audio2
|
14 |
|
15 |
+
# ایجاد نام فایل خروجی منحصر به فرد
|
16 |
+
output_filename = f"merged_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp3"
|
17 |
|
18 |
+
# ذخیره فایل ادغام شده
|
19 |
+
combined.export(output_filename, format="mp3")
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
return output_filename, f"فایلها با موفقیت ادغام شدند. حجم فایل خروجی: {len(combined)} میلیثانیه"
|
|
|
|
|
22 |
except Exception as e:
|
23 |
+
return None, f"خطا در پردازش فایلها: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
+
# رابط Gradio
|
26 |
+
with gr.Blocks(title="ادغام کننده فایلهای MP3") as demo:
|
27 |
with gr.Row():
|
28 |
+
gr.Markdown("""
|
29 |
+
## برنامه ادغام فایلهای MP3
|
30 |
+
لطفاً دو فایل MP3 را برای ادغام انتخاب کنید.
|
31 |
+
""")
|
32 |
+
|
33 |
+
with gr.Row():
|
34 |
+
file1 = gr.File(label="فایل MP3 اول")
|
35 |
+
file2 = gr.File(label="فایل MP3 دوم")
|
36 |
+
|
37 |
+
with gr.Row():
|
38 |
+
merge_btn = gr.Button("ادغام فایلها")
|
39 |
+
|
40 |
+
with gr.Row():
|
41 |
+
output_file = gr.File(label="فایل ادغام شده", interactive=False)
|
42 |
+
output_message = gr.Textbox(label="پیام سیستم", interactive=False)
|
43 |
+
|
44 |
+
merge_btn.click(
|
45 |
+
fn=merge_mp3_files,
|
46 |
+
inputs=[file1, file2],
|
47 |
+
outputs=[output_file, output_message]
|
|
|
|
|
|
|
48 |
)
|
49 |
|
50 |
+
# اجرای برنامه
|
51 |
if __name__ == "__main__":
|
52 |
+
demo.launch()
|