siddhartharyaai's picture
Rename app (39).py to app.py
80a3d62 verified
# app.py
import gradio as gr
from utils import (
generate_script,
generate_audio_mp3, # Updated import
truncate_text,
extract_text_from_url,
transcribe_youtube_video,
research_topic
)
from prompts import SYSTEM_PROMPT # Ensure this module exists
import pypdf
from pydub import AudioSegment
import tempfile
import os
def generate_podcast(file, url, video_url, research_topic_input, tone, length):
print("[LOG] generate_podcast called")
# Check that only one input source is used
sources = [bool(file), bool(url), bool(video_url), bool(research_topic_input)]
if sum(sources) > 1:
print("[ERROR] Multiple input sources provided.")
return None, "Please provide either a PDF file, a URL, a YouTube link, or a Research topic - not multiple."
if not any(sources):
print("[ERROR] No input source provided.")
return None, "Please provide at least one source."
text = ""
if file:
try:
print("[LOG] Reading PDF file:", file.name)
if not file.name.lower().endswith('.pdf'):
print("[ERROR] Uploaded file is not a PDF.")
return None, "Please upload a PDF file."
reader = pypdf.PdfReader(file.name)
text = " ".join(page.extract_text() for page in reader.pages if page.extract_text())
print("[LOG] PDF text extraction successful.")
except Exception as e:
print("[ERROR] Error reading PDF file:", e)
return None, f"Error reading PDF file: {str(e)}"
elif url:
try:
print("[LOG] Using URL input")
text = extract_text_from_url(url)
if not text:
print("[ERROR] Failed to extract text from URL.")
return None, "Failed to extract text from the provided URL."
except Exception as e:
print("[ERROR] Error extracting text from URL:", e)
return None, f"Error extracting text from URL: {str(e)}"
elif video_url:
try:
print("[LOG] Using YouTube video input")
text = transcribe_youtube_video(video_url)
if not text:
print("[ERROR] Failed to transcribe YouTube video.")
return None, "Failed to transcribe the provided YouTube video."
except Exception as e:
print("[ERROR] Error transcribing YouTube video:", e)
return None, f"Error transcribing YouTube video: {str(e)}"
elif research_topic_input:
try:
print("[LOG] Researching topic:", research_topic_input)
text = research_topic(research_topic_input)
if not text:
print("[ERROR] No information found for the topic.")
return None, f"Sorry, I couldn't find recent information on '{research_topic_input}'."
except Exception as e:
print("[ERROR] Error researching topic:", e)
return None, f"Error researching topic: {str(e)}"
else:
print("[ERROR] No valid input source detected.")
return None, "Please provide a PDF file, URL, YouTube link, or Research topic."
try:
text = truncate_text(text)
script = generate_script(SYSTEM_PROMPT, text, tone, length)
except Exception as e:
print("[ERROR] Error generating script:", e)
return None, f"Error generating script: {str(e)}"
audio_segments = []
transcript = ""
try:
print("[LOG] Generating audio segments...")
# Define crossfade duration in milliseconds
crossfade_duration = 50 # 50ms crossfade for smooth transitions
for i, item in enumerate(script.dialogue):
try:
audio_file = generate_audio_mp3(item.text, item.speaker) # Updated function call
line_audio = AudioSegment.from_file(audio_file, format="mp3") # Changed format to mp3
audio_segments.append(line_audio)
transcript += f"**{item.speaker}**: {item.text}\n\n"
os.remove(audio_file)
except Exception as e:
print(f"[ERROR] Error generating audio for dialogue item {i+1}: {e}")
continue
if not audio_segments:
print("[ERROR] No audio segments were generated.")
return None, "No audio segments were generated."
print("[LOG] Combining audio segments with crossfades...")
# Initialize combined audio with the first segment
combined = audio_segments[0]
# Append remaining segments with crossfade
for seg in audio_segments[1:]:
combined = combined.append(seg, crossfade=crossfade_duration)
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_audio: # Changed suffix to mp3
combined.export(temp_audio.name, format="mp3") # Changed format to mp3
print("[LOG] Podcast generated:", temp_audio.name)
return temp_audio.name, transcript
except Exception as e:
print("[ERROR] Error generating audio:", e)
return None, f"Error generating audio: {str(e)}"
def main():
iface = gr.Interface(
fn=generate_podcast,
inputs=[
gr.File(label="Upload PDF", file_types=[".pdf"]),
gr.Textbox(label="OR Enter URL", placeholder="Enter the URL of a webpage to convert into a podcast."),
gr.Textbox(label="OR Enter YouTube Link (Requires User Auth - Work in Progress)", placeholder="Enter a YouTube video URL to transcribe and convert into a podcast."),
gr.Textbox(label="OR Research a Topic", placeholder="Enter a detailed topic to research and convert into a podcast."),
gr.Radio(
choices=["Humorous", "Formal", "Casual", "Youthful"],
label="Tone",
value="Casual"
),
gr.Radio(
choices=["1-3 Mins", "3-5 Mins", "5-10 Mins", "10-20 Mins"],
label="Length",
value="1-3 Mins"
)
],
outputs=[
gr.Audio(label="Podcast"),
gr.Markdown(label="Transcript")
],
title="🎙 MyPod - AI based Podcast Generator",
description=(
"Welcome to **MyPod**, your go-to AI-powered podcast generator! 🎉\n\n"
"MyPod transforms your documents, webpages, YouTube videos, or research topics into a more human-sounding, conversational podcast.\n"
"Select a tone and a duration range. The script will be on-topic, concise, and respect your chosen length.\n\n"
"**How to use:**\n"
"1. **Provide one source:** PDF, URL, YouTube link (Requires User Auth - Work in Progress), or a Topic to Research.\n"
"2. **Choose the tone and the target duration.**\n"
"3. **Click 'Submit'** to generate your podcast.\n\n"
"**Research a Topic:** Please be as detailed as possible in your topic statement. If it's too niche or specific, you might not get the desired outcome. We'll fetch information from Wikipedia and RSS feeds (BBC, CNN, Associated Press, NDTV, Times of India, The Hindu, Economic Times, Google News) or the LLM knowledge base to get recent info about the topic.\n\n"
"**Token Limit:** Up to ~2,048 tokens are supported. Long inputs may be truncated.\n"
"**Note:** YouTube transcription uses Whisper on CPU and may take longer for very long videos.\n\n"
"**⏳Please be patient while your podcast is being generated.**\n"
"This process involves content analysis, script creation, and high-quality audio synthesis, which may take a few minutes.\n\n"
"🔥 **Ready to create your personalized podcast? Give it a try now and let the magic happen!** 🔥"
),
theme=None # Removed custom CSS to revert to default theme
)
iface.launch()
if __name__ == "__main__":
main()