File size: 11,980 Bytes
9a08797
7cbea0a
 
 
 
 
 
 
 
 
 
4ba56a4
 
 
7cbea0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ba56a4
 
7cbea0a
4ba56a4
7cbea0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a08797
7cbea0a
 
 
 
 
 
 
 
 
 
4ba56a4
 
7cbea0a
4ba56a4
7cbea0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a08797
7cbea0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ba56a4
7cbea0a
 
 
 
 
9a08797
 
 
7cbea0a
4ba56a4
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import gradio as gr
import base64
import mimetypes
import os
import re
import struct
import tempfile
import asyncio
from google import genai
from google.genai import types

# Direct API key - WARNING: This is not recommended for production use
GEMINI_API_KEY = "AIzaSyDy5hjn9NFamWhBjqsVsD2WSoFNr2MrHSw"


def save_binary_file(file_name, data):
    """Save binary data to a file."""
    with open(file_name, "wb") as f:
        f.write(data)
    return file_name


def convert_to_wav(audio_data: bytes, mime_type: str) -> bytes:
    """Generates a WAV file header for the given audio data and parameters."""
    parameters = parse_audio_mime_type(mime_type)
    bits_per_sample = parameters["bits_per_sample"]
    sample_rate = parameters["rate"]
    num_channels = 1
    data_size = len(audio_data)
    bytes_per_sample = bits_per_sample // 8
    block_align = num_channels * bytes_per_sample
    byte_rate = sample_rate * block_align
    chunk_size = 36 + data_size

    header = struct.pack(
        "<4sI4s4sIHHIIHH4sI",
        b"RIFF",          # ChunkID
        chunk_size,       # ChunkSize (total file size - 8 bytes)
        b"WAVE",          # Format
        b"fmt ",          # Subchunk1ID
        16,               # Subchunk1Size (16 for PCM)
        1,                # AudioFormat (1 for PCM)
        num_channels,     # NumChannels
        sample_rate,      # SampleRate
        byte_rate,        # ByteRate
        block_align,      # BlockAlign
        bits_per_sample,  # BitsPerSample
        b"data",          # Subchunk2ID
        data_size         # Subchunk2Size (size of audio data)
    )
    return header + audio_data


def 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 = 16
    rate = 24000

    parts = mime_type.split(";")
    for param in parts:
        param = param.strip()
        if param.lower().startswith("rate="):
            try:
                rate_str = param.split("=", 1)[1]
                rate = int(rate_str)
            except (ValueError, IndexError):
                pass
        elif param.startswith("audio/L"):
            try:
                bits_per_sample = int(param.split("L", 1)[1])
            except (ValueError, IndexError):
                pass

    return {"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."""
    progress(0.1, desc="Initializing Gemini client...")
    
    if not GEMINI_API_KEY:
        raise ValueError("GEMINI_API_KEY is not set")
    
    client = genai.Client(api_key=GEMINI_API_KEY)
    
    progress(0.2, desc="Fetching web content...")

    model = "gemini-2.5-flash-preview-04-17"
    contents = [
        types.Content(
            role="user",
            parts=[
                types.Part.from_text(text=f"""Please analyze the content from this URL: {url}
                
                Create a comprehensive summary that would be suitable for a podcast discussion between two hosts. 
                Focus on the key points, interesting aspects, and discussion-worthy topics.
                
                Format your response as a natural conversation between two podcast hosts discussing the content."""),
            ],
        ),
    ]
    
    tools = [
        types.Tool(url_context=types.UrlContext()),
        types.Tool(google_search=types.GoogleSearch()),
    ]
    
    generate_content_config = types.GenerateContentConfig(
        tools=tools,
        response_mime_type="text/plain",
    )

    progress(0.4, desc="Analyzing content with AI...")
    
    content_text = ""
    for chunk in client.models.generate_content_stream(
        model=model,
        contents=contents,
        config=generate_content_config,
    ):
        content_text += chunk.text
    
    progress(0.6, desc="Content analysis complete!")
    return content_text


def generate_podcast_from_content(content_text, speaker1_name="Anna Chope", speaker2_name="Adam Chan", progress=gr.Progress()):
    """Generate audio podcast from text content."""
    progress(0.7, desc="Generating podcast audio...")
    
    if not GEMINI_API_KEY:
        raise ValueError("GEMINI_API_KEY is not set")
    
    client = 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:

    {content_text}
    
    If the content is not already in dialogue format, please convert it into a natural conversation between two podcast hosts Speaker 1 {speaker1_name} and Speaker 2 {speaker2_name} discussing the topic. They should introduce themselves at the beginning."""

    contents = [
        types.Content(
            role="user",
            parts=[
                types.Part.from_text(text=podcast_prompt),
            ],
        ),
    ]
    
    generate_content_config = types.GenerateContentConfig(
        temperature=1,
        response_modalities=[
            "audio",
        ],
        speech_config=types.SpeechConfig(
            multi_speaker_voice_config=types.MultiSpeakerVoiceConfig(
                speaker_voice_configs=[
                    types.SpeakerVoiceConfig(
                        speaker="Speaker 1",
                        voice_config=types.VoiceConfig(
                            prebuilt_voice_config=types.PrebuiltVoiceConfig(
                                voice_name="Zephyr"
                            )
                        ),
                    ),
                    types.SpeakerVoiceConfig(
                        speaker="Speaker 2",
                        voice_config=types.VoiceConfig(
                            prebuilt_voice_config=types.PrebuiltVoiceConfig(
                                voice_name="Puck"
                            )
                        ),
                    ),
                ]
            ),
        ),
    )

    progress(0.8, desc="Converting to audio...")
    
    # Create temporary file
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
    temp_file.close()
    
    audio_chunks = []
    
    for chunk in client.models.generate_content_stream(
        model=model,
        contents=contents,
        config=generate_content_config,
    ):
        if (
            chunk.candidates is None
            or chunk.candidates[0].content is None
            or chunk.candidates[0].content.parts is None
        ):
            continue
            
        if (chunk.candidates[0].content.parts[0].inline_data and 
            chunk.candidates[0].content.parts[0].inline_data.data):
            
            inline_data = chunk.candidates[0].content.parts[0].inline_data
            data_buffer = inline_data.data
            
            # Convert to WAV if needed
            if inline_data.mime_type != "audio/wav":
                data_buffer = convert_to_wav(inline_data.data, inline_data.mime_type)
            
            audio_chunks.append(data_buffer)
    
    # Combine all audio chunks
    if audio_chunks:
        # 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!")
        return temp_file.name
    else:
        raise ValueError("No audio data generated")


def 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...")
        
        # Validate URL
        if not url or not url.startswith(('http://', 'https://')):
            raise ValueError("Please enter a valid URL starting with http:// or https://")
        
        # Step 1: Fetch and analyze web content
        content_text = fetch_web_content(url, progress)
        
        # Step 2: Generate podcast from the content
        audio_file = generate_podcast_from_content(content_text, speaker1_name, speaker2_name, progress)
        
        return audio_file, "βœ… Podcast generated successfully!", content_text
        
    except Exception as e:
        error_msg = f"❌ Error generating podcast: {str(e)}"
        return None, error_msg, ""


# Create Gradio interface
def create_interface():
    with gr.Blocks(title="πŸŽ™οΈ Web-to-Podcast Generator", theme=gr.themes.Soft()) as demo:
        gr.Markdown("""
        # πŸŽ™οΈ Web-to-Podcast Generator
        
        Transform 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"
                )
                
                with gr.Row():
                    speaker1_input = gr.Textbox(
                        label="Host 1 Name",
                        value="Anna Chope",
                        info="Name of the first podcast host"
                    )
                    speaker2_input = gr.Textbox(
                        label="Host 2 Name", 
                        value="Adam Chan",
                        info="Name of the second podcast host"
                    )
                
                generate_btn = gr.Button("πŸŽ™οΈ Generate Podcast", variant="primary", size="lg")
                
            with gr.Column(scale=1):
                gr.Markdown("""
                ### Instructions:
                1. Enter a website URL
                2. Customize host names (optional)
                3. Click "Generate Podcast"
                4. Wait for the AI to analyze content and create audio
                5. Download your podcast!
                
                ### Examples:
                - News articles
                - Blog posts
                - Product pages
                - Documentation
                - Research papers
                """)
        
        with gr.Row():
            status_output = gr.Textbox(label="Status", interactive=False)
        
        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 handlers
        generate_btn.click(
            fn=generate_web_podcast,
            inputs=[url_input, speaker1_input, speaker2_input],
            outputs=[audio_output, status_output, script_output],
            show_progress=True
        )
        
        # Examples
        gr.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 demo


if __name__ == "__main__":
    demo = create_interface()
    demo.launch(debug=True)