Spaces:
Running
Running
Upload app.py
Browse files
app.py
CHANGED
@@ -1,600 +1,170 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
|
3 |
-
|
4 |
-
from
|
5 |
-
import json
|
6 |
-
import
|
7 |
-
import
|
8 |
-
import
|
9 |
-
import
|
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 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
},
|
172 |
-
{
|
173 |
-
"speaker": 2,
|
174 |
-
"line": "So it's less about preventing some kind of sci-fi robot apocalypse and more about making sure we're steering this technology in the right direction from the get-go."
|
175 |
-
},
|
176 |
-
{
|
177 |
-
"speaker": 1,
|
178 |
-
"line": "Exactly, AGI has the potential to be incredibly beneficial, but it's not going to magically solve all our problems. It's on us to make sure we're using it for good."
|
179 |
-
},
|
180 |
-
{
|
181 |
-
"speaker": 2,
|
182 |
-
"line": "It's like you said earlier, it's about shaping the future of intelligence."
|
183 |
-
},
|
184 |
-
{
|
185 |
-
"speaker": 1,
|
186 |
-
"line": "I like that. It really is."
|
187 |
-
},
|
188 |
-
{
|
189 |
-
"speaker": 2,
|
190 |
-
"line": "And honestly, that's a responsibility that extends beyond just the researchers and the policymakers."
|
191 |
-
},
|
192 |
-
{
|
193 |
-
"speaker": 1,
|
194 |
-
"line": "100%"
|
195 |
-
},
|
196 |
-
{
|
197 |
-
"speaker": 2,
|
198 |
-
"line": "So to everyone listening out there I'll leave you with this. As AGI continues to develop, what role do you want to play in shaping its future?"
|
199 |
-
},
|
200 |
-
{
|
201 |
-
"speaker": 1,
|
202 |
-
"line": "That's a question worth pondering."
|
203 |
-
},
|
204 |
-
{
|
205 |
-
"speaker": 2,
|
206 |
-
"line": "It certainly is and on that note, we'll wrap up this deep dive. Thanks for listening, everyone."
|
207 |
-
},
|
208 |
-
{
|
209 |
-
"speaker": 1,
|
210 |
-
"line": "Peace."
|
211 |
-
}
|
212 |
-
]
|
213 |
-
}
|
214 |
-
"""
|
215 |
-
|
216 |
-
if language == "Auto Detect":
|
217 |
-
language_instruction = "- The podcast MUST be in the same language as the user input."
|
218 |
-
else:
|
219 |
-
language_instruction = f"- The podcast MUST be in {language} language"
|
220 |
-
|
221 |
-
system_prompt = f"""
|
222 |
-
You are a professional podcast generator. Your task is to generate a professional podcast script based on the user input.
|
223 |
-
{language_instruction}
|
224 |
-
- The podcast should have 2 speakers.
|
225 |
-
- The podcast should be long.
|
226 |
-
- Do not use names for the speakers.
|
227 |
-
- The podcast should be interesting, lively, and engaging, and hook the listener from the start.
|
228 |
-
- The input text might be disorganized or unformatted, originating from sources like PDFs or text files. Ignore any formatting inconsistencies or irrelevant details; your task is to distill the essential points, identify key definitions, and highlight intriguing facts that would be suitable for discussion in a podcast.
|
229 |
-
- The script must be in JSON format.
|
230 |
-
Follow this example structure:
|
231 |
-
{example}
|
232 |
-
"""
|
233 |
-
user_prompt = ""
|
234 |
-
if prompt and file_obj:
|
235 |
-
user_prompt = f"Please generate a podcast script based on the uploaded file following user input:\n{prompt}"
|
236 |
-
elif prompt:
|
237 |
-
user_prompt = f"Please generate a podcast script based on the following user input:\n{prompt}"
|
238 |
-
else:
|
239 |
-
user_prompt = "Please generate a podcast script based on the uploaded file."
|
240 |
-
|
241 |
-
messages = []
|
242 |
-
|
243 |
-
# If file is provided, add it to the messages
|
244 |
-
if file_obj:
|
245 |
-
file_data = await self._read_file_bytes(file_obj)
|
246 |
-
mime_type = self._get_mime_type(file_obj.name)
|
247 |
-
|
248 |
-
messages.append(
|
249 |
-
types.Content(
|
250 |
-
role="user",
|
251 |
-
parts=[
|
252 |
-
types.Part.from_bytes(
|
253 |
-
data=file_data,
|
254 |
-
mime_type=mime_type,
|
255 |
-
)
|
256 |
-
],
|
257 |
-
)
|
258 |
-
)
|
259 |
-
|
260 |
-
# Add text prompt
|
261 |
-
messages.append(
|
262 |
-
types.Content(
|
263 |
-
role="user",
|
264 |
-
parts=[
|
265 |
-
types.Part.from_text(text=user_prompt)
|
266 |
-
],
|
267 |
-
)
|
268 |
-
)
|
269 |
-
|
270 |
-
client = genai.Client(api_key=api_key)
|
271 |
-
|
272 |
-
safety_settings = [
|
273 |
-
{
|
274 |
-
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
275 |
-
"threshold": "BLOCK_NONE"
|
276 |
-
},
|
277 |
-
{
|
278 |
-
"category": "HARM_CATEGORY_HARASSMENT",
|
279 |
-
"threshold": "BLOCK_NONE"
|
280 |
-
},
|
281 |
-
{
|
282 |
-
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
283 |
-
"threshold": "BLOCK_NONE"
|
284 |
-
},
|
285 |
-
{
|
286 |
-
"category": "HARM_CATEGORY_HATE_SPEECH",
|
287 |
-
"threshold": "BLOCK_NONE"
|
288 |
-
}
|
289 |
-
]
|
290 |
-
|
291 |
-
try:
|
292 |
-
if progress:
|
293 |
-
progress(0.3, "Generating podcast script...")
|
294 |
-
|
295 |
-
# Add timeout to the API call
|
296 |
-
response = await asyncio.wait_for(
|
297 |
-
client.aio.models.generate_content(
|
298 |
-
model="gemini-2.0-flash",
|
299 |
-
contents=messages,
|
300 |
-
config=types.GenerateContentConfig(
|
301 |
-
temperature=1,
|
302 |
-
response_mime_type="application/json",
|
303 |
-
safety_settings=[
|
304 |
-
types.SafetySetting(
|
305 |
-
category=safety_setting["category"],
|
306 |
-
threshold=safety_setting["threshold"]
|
307 |
-
) for safety_setting in safety_settings
|
308 |
-
],
|
309 |
-
system_instruction=system_prompt
|
310 |
-
)
|
311 |
-
),
|
312 |
-
timeout=60 # 60 seconds timeout
|
313 |
-
)
|
314 |
-
except asyncio.TimeoutError:
|
315 |
-
raise Exception("The script generation request timed out. Please try again later.")
|
316 |
-
except Exception as e:
|
317 |
-
if "API key not valid" in str(e):
|
318 |
-
raise Exception("Invalid API key. Please provide a valid Gemini API key.")
|
319 |
-
elif "rate limit" in str(e).lower():
|
320 |
-
raise Exception("Rate limit exceeded for the API key. Please try again later or provide your own Gemini API key.")
|
321 |
-
else:
|
322 |
-
raise Exception(f"Failed to generate podcast script: {e}")
|
323 |
-
|
324 |
-
print(f"Generated podcast script:\n{response.text}")
|
325 |
-
|
326 |
-
if progress:
|
327 |
-
progress(0.4, "Script generated successfully!")
|
328 |
-
|
329 |
-
return json.loads(response.text)
|
330 |
-
|
331 |
-
async def _read_file_bytes(self, file_obj) -> bytes:
|
332 |
-
"""Read file bytes from a file object"""
|
333 |
-
# Check file size before reading
|
334 |
-
if hasattr(file_obj, 'size'):
|
335 |
-
file_size = file_obj.size
|
336 |
-
else:
|
337 |
-
file_size = os.path.getsize(file_obj.name)
|
338 |
-
|
339 |
-
if file_size > MAX_FILE_SIZE_BYTES:
|
340 |
-
raise Exception(f"File size exceeds the {MAX_FILE_SIZE_MB}MB limit. Please upload a smaller file.")
|
341 |
-
|
342 |
-
if hasattr(file_obj, 'read'):
|
343 |
-
return file_obj.read()
|
344 |
-
else:
|
345 |
-
async with aiofiles.open(file_obj.name, 'rb') as f:
|
346 |
-
return await f.read()
|
347 |
-
|
348 |
-
def _get_mime_type(self, filename: str) -> str:
|
349 |
-
"""Determine MIME type based on file extension"""
|
350 |
-
ext = os.path.splitext(filename)[1].lower()
|
351 |
-
if ext == '.pdf':
|
352 |
-
return "application/pdf"
|
353 |
-
elif ext == '.txt':
|
354 |
-
return "text/plain"
|
355 |
-
else:
|
356 |
-
# Fallback to the default mime type detector
|
357 |
-
mime_type, _ = mimetypes.guess_type(filename)
|
358 |
-
return mime_type or "application/octet-stream"
|
359 |
-
|
360 |
-
async def tts_generate(self, text: str, speaker: int, speaker1: str, speaker2: str) -> str:
|
361 |
-
voice = speaker1 if speaker == 1 else speaker2
|
362 |
-
speech = edge_tts.Communicate(text, voice)
|
363 |
-
|
364 |
-
temp_filename = f"temp_{uuid.uuid4()}.wav"
|
365 |
-
try:
|
366 |
-
# Add timeout to TTS generation
|
367 |
-
await asyncio.wait_for(speech.save(temp_filename), timeout=30) # 30 seconds timeout
|
368 |
-
return temp_filename
|
369 |
-
except asyncio.TimeoutError:
|
370 |
-
if os.path.exists(temp_filename):
|
371 |
-
os.remove(temp_filename)
|
372 |
-
raise Exception("Text-to-speech generation timed out. Please try with a shorter text.")
|
373 |
-
except Exception as e:
|
374 |
-
if os.path.exists(temp_filename):
|
375 |
-
os.remove(temp_filename)
|
376 |
-
raise e
|
377 |
-
|
378 |
-
async def combine_audio_files(self, audio_files: List[str], progress=None) -> str:
|
379 |
-
if progress:
|
380 |
-
progress(0.9, "Combining audio files...")
|
381 |
-
|
382 |
-
combined_audio = AudioSegment.empty()
|
383 |
-
for audio_file in audio_files:
|
384 |
-
combined_audio += AudioSegment.from_file(audio_file)
|
385 |
-
os.remove(audio_file) # Clean up temporary files
|
386 |
-
|
387 |
-
output_filename = f"output_{uuid.uuid4()}.wav"
|
388 |
-
combined_audio.export(output_filename, format="wav")
|
389 |
-
|
390 |
-
if progress:
|
391 |
-
progress(1.0, "Podcast generated successfully!")
|
392 |
-
|
393 |
-
return output_filename
|
394 |
-
|
395 |
-
async def generate_podcast(self, input_text: str, language: str, speaker1: str, speaker2: str, api_key: str, file_obj=None, progress=None) -> str:
|
396 |
-
try:
|
397 |
-
if progress:
|
398 |
-
progress(0.1, "Starting podcast generation...")
|
399 |
-
|
400 |
-
# Set overall timeout for the entire process
|
401 |
-
return await asyncio.wait_for(
|
402 |
-
self._generate_podcast_internal(input_text, language, speaker1, speaker2, api_key, file_obj, progress),
|
403 |
-
timeout=600 # 10 minutes total timeout
|
404 |
-
)
|
405 |
-
except asyncio.TimeoutError:
|
406 |
-
raise Exception("The podcast generation process timed out. Please try with shorter text or try again later.")
|
407 |
-
except Exception as e:
|
408 |
-
raise Exception(f"Error generating podcast: {str(e)}")
|
409 |
-
|
410 |
-
async def _generate_podcast_internal(self, input_text: str, language: str, speaker1: str, speaker2: str, api_key: str, file_obj=None, progress=None) -> str:
|
411 |
-
if progress:
|
412 |
-
progress(0.2, "Generating podcast script...")
|
413 |
-
|
414 |
-
podcast_json = await self.generate_script(input_text, language, api_key, file_obj, progress)
|
415 |
-
|
416 |
-
if progress:
|
417 |
-
progress(0.5, "Converting text to speech...")
|
418 |
-
|
419 |
-
# Process TTS in batches for concurrent processing
|
420 |
-
audio_files = []
|
421 |
-
total_lines = len(podcast_json['podcast'])
|
422 |
-
|
423 |
-
# Define batch size to control concurrency
|
424 |
-
batch_size = 10 # Adjust based on system resources
|
425 |
-
|
426 |
-
# Process in batches
|
427 |
-
for batch_start in range(0, total_lines, batch_size):
|
428 |
-
batch_end = min(batch_start + batch_size, total_lines)
|
429 |
-
batch = podcast_json['podcast'][batch_start:batch_end]
|
430 |
-
|
431 |
-
# Create tasks for concurrent processing
|
432 |
-
tts_tasks = []
|
433 |
-
for item in batch:
|
434 |
-
tts_task = self.tts_generate(item['line'], item['speaker'], speaker1, speaker2)
|
435 |
-
tts_tasks.append(tts_task)
|
436 |
-
|
437 |
-
try:
|
438 |
-
# Process batch concurrently
|
439 |
-
batch_results = await asyncio.gather(*tts_tasks, return_exceptions=True)
|
440 |
-
|
441 |
-
# Check for exceptions and handle results
|
442 |
-
for i, result in enumerate(batch_results):
|
443 |
-
if isinstance(result, Exception):
|
444 |
-
# Clean up any files already created
|
445 |
-
for file in audio_files:
|
446 |
-
if os.path.exists(file):
|
447 |
-
os.remove(file)
|
448 |
-
raise Exception(f"Error generating speech: {str(result)}")
|
449 |
-
else:
|
450 |
-
audio_files.append(result)
|
451 |
-
|
452 |
-
# Update progress
|
453 |
-
if progress:
|
454 |
-
current_progress = 0.5 + (0.4 * (batch_end / total_lines))
|
455 |
-
progress(current_progress, f"Processed {batch_end}/{total_lines} speech segments...")
|
456 |
-
|
457 |
-
except Exception as e:
|
458 |
-
# Clean up any files already created
|
459 |
-
for file in audio_files:
|
460 |
-
if os.path.exists(file):
|
461 |
-
os.remove(file)
|
462 |
-
raise Exception(f"Error in batch TTS generation: {str(e)}")
|
463 |
-
|
464 |
-
combined_audio = await self.combine_audio_files(audio_files, progress)
|
465 |
-
return combined_audio
|
466 |
-
|
467 |
-
async def process_input(input_text: str, input_file, language: str, speaker1: str, speaker2: str, api_key: str = "", progress=None) -> str:
|
468 |
-
start_time = time.time()
|
469 |
-
|
470 |
-
voice_names = {
|
471 |
-
"Andrew - English (United States)": "en-US-AndrewMultilingualNeural",
|
472 |
-
"Ava - English (United States)": "en-US-AvaMultilingualNeural",
|
473 |
-
"Brian - English (United States)": "en-US-BrianMultilingualNeural",
|
474 |
-
"Emma - English (United States)": "en-US-EmmaMultilingualNeural",
|
475 |
-
"Florian - German (Germany)": "de-DE-FlorianMultilingualNeural",
|
476 |
-
"Seraphina - German (Germany)": "de-DE-SeraphinaMultilingualNeural",
|
477 |
-
"Remy - French (France)": "fr-FR-RemyMultilingualNeural",
|
478 |
-
"Vivienne - French (France)": "fr-FR-VivienneMultilingualNeural"
|
479 |
-
}
|
480 |
-
|
481 |
-
speaker1 = voice_names[speaker1]
|
482 |
-
speaker2 = voice_names[speaker2]
|
483 |
-
|
484 |
-
try:
|
485 |
-
if progress:
|
486 |
-
progress(0.05, "Processing input...")
|
487 |
-
|
488 |
-
if not api_key:
|
489 |
-
api_key = os.getenv("GENAI_API_KEY")
|
490 |
-
if not api_key:
|
491 |
-
raise Exception("No API key provided. Please provide a Gemini API key.")
|
492 |
-
|
493 |
-
podcast_generator = PodcastGenerator()
|
494 |
-
podcast = await podcast_generator.generate_podcast(input_text, language, speaker1, speaker2, api_key, input_file, progress)
|
495 |
-
|
496 |
-
end_time = time.time()
|
497 |
-
print(f"Total podcast generation time: {end_time - start_time:.2f} seconds")
|
498 |
-
return podcast
|
499 |
-
|
500 |
-
except Exception as e:
|
501 |
-
# Ensure we show a user-friendly error
|
502 |
-
error_msg = str(e)
|
503 |
-
if "rate limit" in error_msg.lower():
|
504 |
-
raise Exception("Rate limit exceeded. Please try again later or use your own API key.")
|
505 |
-
elif "timeout" in error_msg.lower():
|
506 |
-
raise Exception("The request timed out. This could be due to server load or the length of your input. Please try again with shorter text.")
|
507 |
-
else:
|
508 |
-
raise Exception(f"Error: {error_msg}")
|
509 |
-
|
510 |
-
# Gradio UI
|
511 |
-
def generate_podcast_gradio(input_text, input_file, language, speaker1, speaker2, api_key, progress=gr.Progress()):
|
512 |
-
# Handle the file if uploaded
|
513 |
-
file_obj = None
|
514 |
-
if input_file is not None:
|
515 |
-
file_obj = input_file
|
516 |
-
|
517 |
-
# Use the progress function from Gradio
|
518 |
-
def progress_callback(value, text):
|
519 |
-
progress(value, text)
|
520 |
-
|
521 |
-
# Run the async function in the event loop
|
522 |
-
result = asyncio.run(process_input(
|
523 |
-
input_text,
|
524 |
-
file_obj,
|
525 |
-
language,
|
526 |
-
speaker1,
|
527 |
-
speaker2,
|
528 |
-
api_key,
|
529 |
-
progress_callback
|
530 |
-
))
|
531 |
-
|
532 |
-
return result
|
533 |
-
|
534 |
-
def main():
|
535 |
-
# Define language options
|
536 |
-
language_options = [
|
537 |
-
"Auto Detect",
|
538 |
-
"Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Azerbaijani",
|
539 |
-
"Bahasa Indonesian", "Bangla", "Basque", "Bengali", "Bosnian", "Bulgarian",
|
540 |
-
"Burmese", "Catalan", "Chinese Cantonese", "Chinese Mandarin",
|
541 |
-
"Chinese Taiwanese", "Croatian", "Czech", "Danish", "Dutch", "English",
|
542 |
-
"Estonian", "Filipino", "Finnish", "French", "Galician", "Georgian",
|
543 |
-
"German", "Greek", "Hebrew", "Hindi", "Hungarian", "Icelandic", "Irish",
|
544 |
-
"Italian", "Japanese", "Javanese", "Kannada", "Kazakh", "Khmer", "Korean",
|
545 |
-
"Lao", "Latvian", "Lithuanian", "Macedonian", "Malay", "Malayalam",
|
546 |
-
"Maltese", "Mongolian", "Nepali", "Norwegian Bokmål", "Pashto", "Persian",
|
547 |
-
"Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Sinhala",
|
548 |
-
"Slovak", "Slovene", "Somali", "Spanish", "Sundanese", "Swahili",
|
549 |
-
"Swedish", "Tamil", "Telugu", "Thai", "Turkish", "Ukrainian", "Urdu",
|
550 |
-
"Uzbek", "Vietnamese", "Welsh", "Zulu"
|
551 |
-
]
|
552 |
-
|
553 |
-
# Define voice options
|
554 |
-
voice_options = [
|
555 |
-
"Andrew - English (United States)",
|
556 |
-
"Ava - English (United States)",
|
557 |
-
"Brian - English (United States)",
|
558 |
-
"Emma - English (United States)",
|
559 |
-
"Florian - German (Germany)",
|
560 |
-
"Seraphina - German (Germany)",
|
561 |
-
"Remy - French (France)",
|
562 |
-
"Vivienne - French (France)"
|
563 |
-
]
|
564 |
-
|
565 |
-
# Create Gradio interface
|
566 |
-
with gr.Blocks(title="PodcastGen 🎙️") as demo:
|
567 |
-
gr.Markdown("# PodcastGen 🎙️")
|
568 |
-
gr.Markdown("Generate a 2-speaker podcast from text input or documents!")
|
569 |
-
|
570 |
-
with gr.Row():
|
571 |
-
with gr.Column(scale=2):
|
572 |
-
input_text = gr.Textbox(label="Input Text", lines=10, placeholder="Enter text for podcast generation...")
|
573 |
-
|
574 |
-
with gr.Column(scale=1):
|
575 |
-
input_file = gr.File(label="Or Upload a PDF or TXT file", file_types=[".pdf", ".txt"])
|
576 |
-
|
577 |
-
with gr.Row():
|
578 |
-
with gr.Column():
|
579 |
-
api_key = gr.Textbox(label="Your Gemini API Key (Optional)", placeholder="Enter API key here if you're getting rate limited", type="password")
|
580 |
-
language = gr.Dropdown(label="Language", choices=language_options, value="Auto Detect")
|
581 |
-
|
582 |
-
with gr.Column():
|
583 |
-
speaker1 = gr.Dropdown(label="Speaker 1 Voice", choices=voice_options, value="Andrew - English (United States)")
|
584 |
-
speaker2 = gr.Dropdown(label="Speaker 2 Voice", choices=voice_options, value="Ava - English (United States)")
|
585 |
-
|
586 |
-
generate_btn = gr.Button("Generate Podcast", variant="primary")
|
587 |
-
|
588 |
-
with gr.Row():
|
589 |
-
output_audio = gr.Audio(label="Generated Podcast", type="filepath", format="wav")
|
590 |
-
|
591 |
-
generate_btn.click(
|
592 |
-
fn=generate_podcast_gradio,
|
593 |
-
inputs=[input_text, input_file, language, speaker1, speaker2, api_key],
|
594 |
-
outputs=[output_audio]
|
595 |
-
)
|
596 |
-
|
597 |
-
demo.launch()
|
598 |
-
|
599 |
-
if __name__ == "__main__":
|
600 |
-
main()
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import base64
|
3 |
+
import io
|
4 |
+
from PIL import Image
|
5 |
+
import json
|
6 |
+
import os
|
7 |
+
import asyncio
|
8 |
+
from google import genai
|
9 |
+
from google.genai import types
|
10 |
+
|
11 |
+
# Function to convert PIL Image to bytes
|
12 |
+
def pil_to_bytes(img, format="PNG"):
|
13 |
+
img_byte_arr = io.BytesIO()
|
14 |
+
img.save(img_byte_arr, format=format)
|
15 |
+
return img_byte_arr.getvalue()
|
16 |
+
|
17 |
+
# Function to load image as base64
|
18 |
+
async def load_image_base64(img):
|
19 |
+
if isinstance(img, str):
|
20 |
+
# If image is a URL or file path, load it
|
21 |
+
raise ValueError("URL loading not implemented in this version")
|
22 |
+
else:
|
23 |
+
# If image is already a PIL Image
|
24 |
+
return pil_to_bytes(img)
|
25 |
+
|
26 |
+
# Main function to generate edited image using Gemini
|
27 |
+
async def generate_image_gemini(prompt, image, api_key):
|
28 |
+
SAFETY_SETTINGS = {
|
29 |
+
types.HarmCategory.HARM_CATEGORY_HARASSMENT: types.HarmBlockThreshold.BLOCK_NONE,
|
30 |
+
types.HarmCategory.HARM_CATEGORY_HATE_SPEECH: types.HarmBlockThreshold.BLOCK_NONE,
|
31 |
+
types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: types.HarmBlockThreshold.BLOCK_NONE,
|
32 |
+
types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: types.HarmBlockThreshold.BLOCK_NONE,
|
33 |
+
}
|
34 |
+
|
35 |
+
try:
|
36 |
+
# Initialize Gemini client with API key
|
37 |
+
client = genai.Client(api_key=api_key)
|
38 |
+
|
39 |
+
# Convert PIL image to bytes
|
40 |
+
image_bytes = await load_image_base64(image)
|
41 |
+
|
42 |
+
contents = []
|
43 |
+
|
44 |
+
# Add the image to the contents
|
45 |
+
contents.append(
|
46 |
+
types.Content(
|
47 |
+
role="user",
|
48 |
+
parts=[
|
49 |
+
types.Part.from_bytes(
|
50 |
+
data=image_bytes,
|
51 |
+
mime_type="image/png",
|
52 |
+
)
|
53 |
+
],
|
54 |
+
)
|
55 |
+
)
|
56 |
+
|
57 |
+
# Add the prompt to the contents
|
58 |
+
edit_prompt = f"Edit this image: {prompt}"
|
59 |
+
contents.append(
|
60 |
+
types.Content(
|
61 |
+
role="user",
|
62 |
+
parts=[
|
63 |
+
types.Part.from_text(text=edit_prompt),
|
64 |
+
],
|
65 |
+
)
|
66 |
+
)
|
67 |
+
|
68 |
+
response = await client.aio.models.generate_content(
|
69 |
+
model="gemini-2.0-flash-exp",
|
70 |
+
contents=contents,
|
71 |
+
config=types.GenerateContentConfig(
|
72 |
+
safety_settings=[
|
73 |
+
types.SafetySetting(
|
74 |
+
category=category, threshold=threshold
|
75 |
+
) for category, threshold in SAFETY_SETTINGS.items()
|
76 |
+
],
|
77 |
+
response_modalities=['Text', 'Image']
|
78 |
+
)
|
79 |
+
)
|
80 |
+
|
81 |
+
edited_images = []
|
82 |
+
for part in response.candidates[0].content.parts:
|
83 |
+
if part.inline_data is not None:
|
84 |
+
image_bytes = part.inline_data.data
|
85 |
+
edited_images.append(image_bytes)
|
86 |
+
|
87 |
+
# Convert the first returned image bytes to PIL image
|
88 |
+
if edited_images:
|
89 |
+
result_image = Image.open(io.BytesIO(edited_images[0]))
|
90 |
+
return result_image
|
91 |
+
else:
|
92 |
+
return None
|
93 |
+
|
94 |
+
except Exception as e:
|
95 |
+
print(f"Google GenAI client failed with error: {e}")
|
96 |
+
return None
|
97 |
+
|
98 |
+
# Function to process the image edit
|
99 |
+
def process_image_edit(image, prompt, api_key, image_history):
|
100 |
+
if not image or not prompt or not api_key:
|
101 |
+
return None, image_history, "Please provide an image, prompt, and API key"
|
102 |
+
|
103 |
+
# Store current image in history if not empty
|
104 |
+
if image is not None and image_history is None:
|
105 |
+
image_history = []
|
106 |
+
if image is not None:
|
107 |
+
image_history.append(image)
|
108 |
+
|
109 |
+
# Run the async function to edit the image
|
110 |
+
try:
|
111 |
+
edited_image = asyncio.run(generate_image_gemini(prompt, image, api_key))
|
112 |
+
if edited_image:
|
113 |
+
return edited_image, image_history, "Image edited successfully"
|
114 |
+
else:
|
115 |
+
return image, image_history, "Failed to edit image. Please try again."
|
116 |
+
except Exception as e:
|
117 |
+
return image, image_history, f"Error: {str(e)}"
|
118 |
+
|
119 |
+
# Function to undo the last edit
|
120 |
+
def undo_edit(image_history):
|
121 |
+
if image_history and len(image_history) > 1:
|
122 |
+
# Remove current image
|
123 |
+
image_history.pop()
|
124 |
+
# Return the previous image
|
125 |
+
return image_history[-1], image_history, "Reverted to previous image"
|
126 |
+
else:
|
127 |
+
return None, [], "No previous version available"
|
128 |
+
|
129 |
+
# Create Gradio UI
|
130 |
+
def create_ui():
|
131 |
+
with gr.Blocks(title="Gemini Image Editor") as app:
|
132 |
+
gr.Markdown("# Gemini Image Editor")
|
133 |
+
gr.Markdown("Upload an image, enter a description of the edit you want, and let Gemini do the rest!")
|
134 |
+
|
135 |
+
# Store image history in state
|
136 |
+
image_history = gr.State([])
|
137 |
+
|
138 |
+
with gr.Row():
|
139 |
+
with gr.Column():
|
140 |
+
input_image = gr.Image(type="pil", label="Upload Image")
|
141 |
+
prompt = gr.Textbox(label="Edit Description", placeholder="Describe the edit you want...")
|
142 |
+
api_key = gr.Textbox(label="Gemini API Key", placeholder="Enter your Gemini API key", type="password")
|
143 |
+
|
144 |
+
with gr.Row():
|
145 |
+
edit_btn = gr.Button("Edit Image")
|
146 |
+
undo_btn = gr.Button("Undo Last Edit")
|
147 |
+
|
148 |
+
with gr.Column():
|
149 |
+
output_image = gr.Image(type="pil", label="Edited Image")
|
150 |
+
status = gr.Textbox(label="Status", interactive=False)
|
151 |
+
|
152 |
+
# Set up event handlers
|
153 |
+
edit_btn.click(
|
154 |
+
fn=process_image_edit,
|
155 |
+
inputs=[input_image, prompt, api_key, image_history],
|
156 |
+
outputs=[output_image, image_history, status]
|
157 |
+
)
|
158 |
+
|
159 |
+
undo_btn.click(
|
160 |
+
fn=undo_edit,
|
161 |
+
inputs=[image_history],
|
162 |
+
outputs=[output_image, image_history, status]
|
163 |
+
)
|
164 |
+
|
165 |
+
return app
|
166 |
+
|
167 |
+
# Launch the app
|
168 |
+
if __name__ == "__main__":
|
169 |
+
app = create_ui()
|
170 |
+
app.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|