Spaces:
Running
Running
File size: 8,803 Bytes
aa1b4ab |
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 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
# app.py
import streamlit as st
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():
# Set Streamlit page config
st.set_page_config(
page_title="MyPod - AI based Podcast Generator",
layout="centered"
)
st.title("๐ MyPod - AI-based Podcast Generator")
st.markdown(
"""
<style>
.main {
background-color: #f9f9f9;
}
.block-container {
padding: 2rem;
border-radius: 10px;
background-color: #ffffff;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
</style>
""",
unsafe_allow_html=True
)
st.markdown(
"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 'Generate Podcast'** to produce 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.** 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! ๐ฅ"
)
st.write("---")
# Create 2 columns for inputs
col1, col2 = st.columns(2)
with col1:
file = st.file_uploader("Upload PDF (Only .pdf)", type=["pdf"])
url = st.text_input("Or Enter URL")
video_url = st.text_input("Or Enter YouTube Link (Requires User Auth - Work in Progress)")
with col2:
research_topic_input = st.text_input("Or Research a Topic")
tone = st.radio(
"Tone",
["Humorous", "Formal", "Casual", "Youthful"],
index=2
)
length = st.radio(
"Length",
["1-3 Mins", "3-5 Mins", "5-10 Mins", "10-20 Mins"],
index=0
)
st.write("")
generate_button = st.button("Generate Podcast")
if generate_button:
# Run the generate_podcast function
with st.spinner("Generating your podcast, please wait..."):
podcast_file, transcript = generate_podcast(
file, url, video_url, research_topic_input, tone, length
)
if podcast_file is None:
st.error(transcript)
else:
st.success("Podcast generated successfully!")
audio_file = open(podcast_file, 'rb')
audio_bytes = audio_file.read()
audio_file.close()
st.audio(audio_bytes, format='audio/mp3')
st.markdown(transcript)
# Clean up the temp file
os.remove(podcast_file)
if __name__ == "__main__":
main()
|