Spaces:
Build error
Build error
Update app.py
Browse files55 unmodified lines5657585960616216 unmodified lines798081828384858687881 unmodified line9091929394959697989918 unmodified lines1181191201211221231245 unmodified lines1301311321331341351362 unmodified lines1391401411421431441451461471481 unmodified line15015115215315415515640 unmodified lines19719819920020120220331 unmodified lines2352362372382392402414 unmodified lines24624724824925025125225325425529 unmodified lines28528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939055 unmodified linesreturn header + audio_datadef parse_audio_mime_type(mime_type: str) -> dict[str, int | None]:"""Parses bits per sample and rate from an audio MIME type string."""bits_per_sample = 16rate = 2400016 unmodified linesreturn {"bits_per_sample": bits_per_sample, "rate": rate}def fetch_web_content(url, progress=gr.Progress()):"""Fetch and analyze web content using Gemini with tools."""try:progress(0.1, desc="Initializing Gemini client...")logger.info("Initializing Gemini client...")if not GEMINI_API_KEY:1 unmodified lineclient = genai.Client(api_key=GEMINI_API_KEY)progress(0.2, desc="Fetching web content...")logger.info(f"Fetching content from URL: {url}")model = "gemini-2.5-flash-preview-04-17"contents = [types.Content(role="user",18 unmodified linesresponse_mime_type="text/plain",)progress(0.4, desc="Analyzing content with AI...")logger.info("Generating content with Gemini...")content_text = ""5 unmodified linesif chunk.text:content_text += chunk.textprogress(0.6, desc="Content analysis complete!")logger.info(f"Content generation complete. Length: {len(content_text)} characters")return content_text2 unmodified linesraise edef generate_podcast_from_content(content_text, speaker1_name="Anna Chope", speaker2_name="Adam Chan", progress=gr.Progress()):"""Generate audio podcast from text content."""try:progress(0.7, desc="Generating podcast audio...")logger.info("Starting audio generation...")if not GEMINI_API_KEY:1 unmodified lineclient = genai.Client(api_key=GEMINI_API_KEY)model = "gemini-2.5-flash-preview-tts"podcast_prompt = f"""Please read aloud the following content in a natural podcast interview style with two distinct speakers.Make it sound conversational and engaging:40 unmodified lines),)progress(0.8, desc="Converting to audio...")logger.info("Generating audio stream...")# Create temporary file31 unmodified lines# For simplicity, just use the first chunk (you might want to concatenate them)final_audio = audio_chunks[0]save_binary_file(temp_file.name, final_audio)progress(1.0, desc="Podcast generated successfully!")logger.info(f"Audio file saved: {temp_file.name}")return temp_file.nameelse:4 unmodified linesraise edef generate_web_podcast(url, speaker1_name, speaker2_name, progress=gr.Progress()):"""Main function to fetch web content and generate podcast."""try:progress(0.0, desc="Starting podcast generation...")logger.info(f"Starting podcast generation for URL: {url}")# Validate inputs29 unmodified lines# Create Gradio interfacedef create_interface():try:with gr.Blocks(title="๐๏ธ Web-to-Podcast Generator",theme=gr.themes.Soft(),analytics_enabled=False) as demo:gr.Markdown("""# ๐๏ธ Web-to-Podcast GeneratorTransform any website into an engaging podcast conversation between two AI hosts!Simply paste a URL and let AI create a natural dialogue discussing the content.""")with gr.Row():with gr.Column(scale=2):url_input = gr.Textbox(label="Website URL",placeholder="https://example.com",info="Enter the URL of the website you want to convert to a podcast",lines=1)with gr.Row():speaker1_input = gr.Textbox(label="Host 1 Name",value="Anna Chope",info="Name of the first podcast host",lines=1)speaker2_input = gr.Textbox(label="Host 2 Name",value="Adam Chan",info="Name of the second podcast host",lines=1)generate_btn = gr.Button("๐๏ธ Generate Podcast", variant="primary", size="lg")with gr.Column(scale=1):gr.Markdown("""### Instructions:1. Enter a website URL2. Customize host names (optional)3. Click "Generate Podcast"4. Wait for the AI to analyze content and create audio5. Download your podcast!### Examples:- News articles- Blog posts- Product pages- Documentation- Research papers""")with gr.Row():status_output = gr.Textbox(label="Status", interactive=False, lines=2)with gr.Row():audio_output = gr.Audio(label="Generated Podcast", type="filepath")with gr.Accordion("๐ Generated Script Preview", open=False):script_output = gr.Textbox(label="Podcast Script",lines=10,interactive=False,info="Preview of the conversation script generated from the website content")# Event handlersgenerate_btn.click(fn=generate_web_podcast,inputs=[url_input, speaker1_input, speaker2_input],outputs=[audio_output, status_output, script_output],show_progress=True)# Examplesgr.Examples(examples=[["https://github.com/weaviate/weaviate", "Anna", "Adam"],["https://huggingface.co/blog", "Sarah", "Mike"],["https://openai.com/blog", "Emma", "John"],],inputs=[url_input, speaker1_input, speaker2_input],)gr.Markdown("""---**Note:** API key is now directly embedded in the code for convenience.The generated podcast will feature two AI voices having a natural conversation about the website content.""")return demoexcept Exception as e:logger.error(f"Error creating interface: {e}")raise eif __name__ == "__main__":55 unmodified lines5657585960616216 unmodified lines79808182838485868788891 unmodified line91929394959697989910010118 unmodified lines1201211221231241251261275 unmodified lines1331341351361371381391402 unmodified lines1431441451461471481491501511521531 unmodified line15515615715815916016140 unmodified lines20220320420520620720820931 unmodified lines2412422432442452462472484 unmodified lines25325425525625725825926026126226329 unmodified lines29329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339455 unmodified linesreturn header + audio_datadef parse_audio_mime_type(mime_type: str) -> dict:"""Parses bits per sample and rate from an audio MIME type string."""bits_per_sample = 16rate = 2400016 unmodified linesreturn {"bits_per_sample": bits_per_sample, "rate": rate}def fetch_web_content(url, progress=None):"""Fetch and analyze web content using Gemini with tools."""try:if progress:progress(0.1, desc="Initializing Gemini client...")logger.info("Initializing Gemini client...")if not GEMINI_API_KEY:1 unmodified lineclient = genai.Client(api_key=GEMINI_API_KEY)if progress:progress(0.2, desc="Fetching web content...")logger.info(f"Fetching content from URL: {url}")model = "gemini-2.0-flash-exp" # Updated model namecontents = [types.Content(role="user",18 unmodified linesresponse_mime_type="text/plain",)if progress:progress(0.4, desc="Analyzing content with AI...")logger.info("Generating content with Gemini...")content_text = ""5 unmodified linesif chunk.text:content_text += chunk.textif progress:progress(0.6, desc="Content analysis complete!")logger.info(f"Content generation complete. Length: {len(content_text)} characters")return content_text2 unmodified linesraise edef generate_podcast_from_content(content_text, speaker1_name="Anna Chope", speaker2_name="Adam Chan", progress=None):"""Generate audio podcast from text content."""try:if progress:progress(0.7, desc="Generating podcast audio...")logger.info("Starting audio generation...")if not GEMINI_API_KEY:1 unmodified lineclient = genai.Client(api_key=GEMINI_API_KEY)model = "gemini-2.0-flash-exp" # Updated model namepodcast_prompt = f"""Please read aloud the following content in a natural podcast interview style with two distinct speakers.Make it sound conversational and engaging:40 unmodified lines),)if progress:progress(0.8, desc="Converting to audio...")logger.info("Generating audio stream...")# Create temporary file31 unmodified lines# For simplicity, just use the first chunk (you might want to concatenate them)final_audio = audio_chunks[0]save_binary_file(temp_file.name, final_audio)if progress:progress(1.0, desc="Podcast generated successfully!")logger.info(f"Audio file saved: {temp_file.name}")return temp_file.nameelse:4 unmodified linesraise edef generate_web_podcast(url, speaker1_name, speaker2_name, progress=None):"""Main function to fetch web content and generate podcast."""try:if progress:progress(0.0, desc="Starting podcast generation...")logger.info(f"Starting podcast generation for URL: {url}")# Validate inputs29 unmodified lines# Create Gradio interfacedef create_interface():"""Create and return the Gradio interface."""with gr.Blocks(title="๐๏ธ Web-to-Podcast Generator",theme=gr.themes.Soft(),analytics_enabled=False) as demo:gr.Markdown("""# ๐๏ธ Web-to-Podcast GeneratorTransform any website into an engaging podcast conversation between two AI hosts!Simply paste a URL and let AI create a natural dialogue discussing the content.""")with gr.Row():with gr.Column(scale=2):url_input = gr.Textbox(label="Website URL",placeholder="https://example.com",info="Enter the URL of the website you want to convert to a podcast",lines=1)with gr.Row():speaker1_input = gr.Textbox(label="Host 1 Name",value="Anna Chope",info="Name of the first podcast host",lines=1)speaker2_input = gr.Textbox(label="Host 2 Name",value="Adam Chan",info="Name of the second podcast host",lines=1)generate_btn = gr.Button("๐๏ธ Generate Podcast", variant="primary", size="lg")with gr.Column(scale=1):gr.Markdown("""### Instructions:1. Enter a website URL2. Customize host names (optional)3. Click "Generate Podcast"4. Wait for the AI to analyze content and create audio5. Download your podcast!### Examples:- News articles- Blog posts- Product pages- Documentation- Research papers""")with gr.Row():status_output = gr.Textbox(label="Status", interactive=False, lines=2)with gr.Row():audio_output = gr.Audio(label="Generated Podcast", type="filepath")with gr.Accordion("๐ Generated Script Preview", open=False):script_output = gr.Textbox(label="Podcast Script",lines=10,interactive=False,info="Preview of the conversation script generated from the website content")# Event handlersgenerate_btn.click(fn=generate_web_podcast,inputs=[url_input, speaker1_input, speaker2_input],outputs=[audio_output, status_output, script_output],show_progress=True)# Examplesgr.Examples(examples=[["https://github.com/weaviate/weaviate", "Anna", "Adam"],["https://huggingface.co/blog", "Sarah", "Mike"],["https://openai.com/blog", "Emma", "John"],],inputs=[url_input, speaker1_input, speaker2_input],)gr.Markdown("""---**Note:** API key is now directly embedded in the code for convenience.The generated podcast will feature two AI voices having a natural conversation about the website content.""")return demoif __name__ == "__main__":
app.py+113-109