File size: 27,383 Bytes
1196f2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# app.py
import os
import re
import json
import gradio as gr
from llama_cloud_services import LlamaParse
from openai import OpenAI
from dotenv import load_dotenv
from weasyprint import HTML
from pathlib import Path
import requests

MAX_AUDIO_SLIDES = 15

load_dotenv()

OUTPUT_DIR = Path("generated_pdf_files")
OUTPUT_DIR.mkdir(exist_ok=True)

OUTPUT_DIR_AUDIO = Path("generated_audio_files")
OUTPUT_DIR_AUDIO.mkdir(exist_ok=True)

MODAL_TTS_URL = os.environ.get("MODAL_TTS_URL")
SNC_API_KEY = os.environ.get("SNC_API_KEY")


# LlamaParse Client for document parsing
LLAMA_CLOUD_API = os.environ.get("LLAMA_CLOUD_API_KEY")
llama_parser_client = None
if LLAMA_CLOUD_API:
    try:
        llama_parser_client = LlamaParse(api_key=LLAMA_CLOUD_API, result_type="markdown", num_workers=4, language='en', verbose=False)
        print("βœ… LlamaParse client initialized successfully.")
    except Exception as e:
        print(f"❌ Error initializing LlamaParse client: {e}")
else:
    print('⚠️ WARNING: LLAMA_CLOUD_API_KEY not found. Document Parsing will be disabled.')

# Nebius Client for AI generation
NEBIUS_API_KEY = os.environ.get("NEBIUS_API_KEY")
nebius_client = None
if NEBIUS_API_KEY:
    try:
        nebius_client = OpenAI(
            base_url="https://api.studio.nebius.com/v1/",
            api_key=NEBIUS_API_KEY
        )
        print("βœ… Nebius client initialized successfully.")
    except Exception as e:
        print(f"❌ Error initializing Nebius client: {e}")
else:
    print('⚠️ WARNING: NEBIUS_API_KEY not found. All AI generation tools will be disabled.')

sambanova_client = None
if SNC_API_KEY:
    sambanova_client = OpenAI(api_key=SNC_API_KEY, base_url='https://api.sambanova.ai/v1')
    print("βœ… Sambanova client initialized successfully.")
else:
    print('⚠️ WARNING: SNC_API_KEY not found. All AI generation tools will be disabled.')



#  Tool 1: Document Parser 
def parse_documents_tool(files_input_from_gradio: list) -> str:
    """Parses uploaded documents using LlamaParse into clean Markdown text."""
    if not llama_parser_client: raise gr.Error("LlamaParse client not initialized.")
    if not files_input_from_gradio: raise gr.Error("No files provided for parsing.")
    
    file_paths = [f.name for f in files_input_from_gradio]
    try:
        print(f"Tool 1 (LlamaParse): Parsing {len(file_paths)} documents...")
        llama_index_documents = llama_parser_client.load_data(file_paths)
        final_markdown = "\n\n<!-- ========== Next Document ========== -->\n\n".join([doc.text for doc in llama_index_documents if doc.text])
        print(f"Tool 1 (LlamaParse): Success. Total Markdown length: {len(final_markdown)}")
        return final_markdown
    except Exception as e:
        print(f"❌ Error in parse_documents_tool: {e}")
        raise gr.Error(f"LlamaParse failed: {str(e)}")

#  Tool 2: Creative Plan Generator (Augment, Outline, Design) 
def generate_rich_content_and_theme_tool(parsed_markdown: str, user_topic: str) -> str:
    """
    Analyzes text and a topic to generate a comprehensive JSON 'master plan' for a presentation,
    including a visual theme, slide structure, augmented content, and visualization ideas.
    """
    if not nebius_client: raise gr.Error("Nebius client not initialized.")
    
#    
    prompt = f"""
You are a Chief Creative Officer and an expert AI Art Director. Your task is to take raw text and a presentation topic and create a master plan for a stunning visual report. The output MUST be a single, valid JSON object.

**Your Plan (JSON Object) Must Contain:**
1.  `visual_theme`: An object describing the aesthetic with `theme_name`, `primary_color`, `secondary_color`, `accent_color`, `font_headings`, and `font_body`.
2.  `presentation_title`: A compelling title.
3.  `slides`: An array of slide objects. For each slide:
    -   `slide_title`: A clear title.
    -   `key_points`: An array of critical bullet points.
    -   `augmented_info`: Additional context and details.
    -   `visualization_suggestion`: A practical idea for a non-image visual element (e.g., "A pure CSS bar chart...").
    -   **`image_generation_prompt`**: An **OPTIONAL** key. Only include this key for the slides you select for an image.
    -   **`speaker_notes_text`**: Contains a script for this slide. The text should be engaging, expand on the key points, and guide a presenter on how to deliver the content.

**CRITICAL ART DIRECTION RULES:**
1.  **Selectivity is Key:** Your goal is to select only a **few (2-4) high-impact slides** to feature an image. Do not add an image prompt to every slide. Prompts must be specific and conceptual.
2.  **Title Slide is Mandatory:** The **first (title) slide MUST have an `image_generation_prompt`** to create a strong opening.
3.  **Use Color Names, Not Hex Codes:** In the image prompt, you MUST use the descriptive color `name` you generated (e.g., "Dominant colors: Deep Space Blue, Solar Orange"). **DO NOT use hex codes in the image prompt.**
3.  **Choose Wisely:** For the other 1-3 images, choose slides that have a strong, singular, and visualizable concept. Slides that are very dense with text or data charts are poor candidates for an image.
4.  **Content-Specific Prompts:** The `image_generation_prompt` MUST be highly specific to the content of that slide. It should generate a conceptual, artistic image that represents the slide's core idea. Use descriptive keywords.
    -   **Good Example:** For a slide about financial growth, a good prompt is "Minimalist vector illustration of a green arrow moving upwards through a field of abstract data points, clean background, corporate style."
    -   **Bad Example:** "An image about finance." (Too generic!)
    -   **Text in Images:** When writing an `image_generation_prompt`, AVOID including complex text. If text is necessary, keep it to one or two simple words and specify it clearly, e.g., "with the word 'Growth' elegantly integrated". Image models are bad at rendering lots of text.
5.  **Speaker Notes:** The `speaker_notes_text` should NOT simply repeat the on-slide text. It should provide a narrative, give background, and guide the presenter.

**Instructions for `image_generation_prompt` for the 'flux-schnell' model:**
-   Focus on keywords like: "minimalist illustration", "conceptual art", "vector graphic", "isometric design", "abstract shapes", "data visualization art".
-   Incorporate the `visual_theme` colors into the prompt (e.g., "Dominant colors: [primary_color], [accent_color]").

**Presentation Topic:** "{user_topic}"
**Parsed Document Text:** --- {parsed_markdown} ---
Begin JSON Output:
"""
    try:
        
        # response = nebius_client.chat.completions.create(
        #     model="deepseek-ai/DeepSeek-V3-0324",
        #     messages=[{"role": "user", "content": prompt}],
        #     temperature=0.4,
        #     max_tokens=8192,
        #     response_format={"type": "json_object"},
        # )
        print("Tool 2 (Creative Plan): Calling Sambanova (DeepSeek-V3-0324)...")
        response = sambanova_client.chat.completions.create(
            model="DeepSeek-V3-0324",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.4,
            max_tokens=8192,
            response_format={"type": "json_object"},
        )
        rich_content_json = response.choices[0].message.content
        print("\n--- DEBUG: Raw Creative Plan JSON from Model ---\n", rich_content_json, "\n----------------------------------------\n")
        json.loads(rich_content_json)
        print("Tool 2 (Creative Plan): Success.")
        return rich_content_json
    except Exception as e:
        print(f"❌ Error in generate_rich_content_and_theme_tool: {e}")
        raise gr.Error(f"Creative plan generation failed: {str(e)}")

def generate_assets_tool(json_plan_str: str) -> str:
    """
    Takes a JSON plan, generates images for each slide using the provided prompts,
    and returns an updated JSON plan with image URLs.
    """
    if not nebius_client: raise gr.Error("Nebius client not initialized.")
    
    print("Tool 3 (Asset Gen): Starting image generation for all slides...")
    plan_data = json.loads(json_plan_str)
    
    for i, slide in enumerate(plan_data["slides"]):
        image_prompt = slide.get("image_generation_prompt")
        if not image_prompt:
            print(f"  - Skipping slide {i+1}, no image prompt found.")
            plan_data["slides"][i]["image_url"] = None # Explicitly set to null
            continue

        print(f"  - Generating image for slide {i+1}: '{slide['slide_title']}'...")
        try:
            response = nebius_client.images.generate(
                model="black-forest-labs/flux-schnell",
                prompt=image_prompt,
                response_format="url",
                extra_body={
                    "width": 1024,
                    "height": 1024, 
                    "num_inference_steps": 4, 
                },
            )
            image_url = response.data[0].url
            plan_data["slides"][i]["image_url"] = image_url
            print(f"  - Success! Image URL: {image_url}")
        except Exception as e:
            print(f"  - ❌ FAILED to generate image for slide {i+1}: {e}")
            plan_data["slides"][i]["image_url"] = None

    return json.dumps(plan_data)

#  Tool 4: Audio Asset Generator 
def generate_audio_assets_tool(json_plan_str: str):
    """
    Takes a JSON plan, generates audio for each slide using the Modal TTS API,
    and returns an updated JSON plan with audio URLs.
    """
    if not MODAL_TTS_URL:
        print("⚠️ WARNING: MODAL_TTS_URL not set. Skipping audio generation.")
        return json_plan_str

    print("Tool 4 (Audio Gen): Starting TTS for all slides via Modal API...")
    plan_data = json.loads(json_plan_str)

    for i, slide in enumerate(plan_data["slides"]):
        notes_text = slide.get("speaker_notes_text")
        if not notes_text:
            print(f"  - Skipping audio for slide {i+1}, no speaker notes text found.")
            plan_data["slides"][i]["audio_url"] = None
            continue

        print(f"  - Generating audio for slide {i+1}...")
        try:
            payload = {"text": notes_text, "voice": "af_heart"} 
            headers = {"Content-Type": "application/json"}
            
            response = requests.post(MODAL_TTS_URL, json=payload, headers=headers, timeout=180)
            
            if response.status_code == 200:
                audio_path = OUTPUT_DIR_AUDIO / f"slide_audio_{i}.wav"
                with open(audio_path, "wb") as f:
                    f.write(response.content)
                plan_data["slides"][i]["audio_url"] = str(audio_path)
                print(f"  - Success! Audio saved to {audio_path}")
            else:
                print(f"  - ❌ FAILED to generate audio for slide {i+1}. Status: {response.status_code}, Response: {response.text}")
                plan_data["slides"][i]["audio_url"] = None
        except Exception as e:
            print(f"  - ❌ FAILED to generate audio for slide {i+1} with exception: {e}")
            plan_data["slides"][i]["audio_url"] = None

    # return json.dumps(plan_data)
    yield plan_data

#  Tool 3: HTML Presentation Renderer  
def convert_rich_content_to_html_tool(rich_content_json: str) -> str:
    """Takes a rich JSON 'master plan' and renders it as a single, static HTML file."""
    if not nebius_client: raise gr.Error("Nebius client not initialized.")

    prompt = f"""
You are a '10x' Staff Front-End Engineer and a world-class Information Designer. You are an expert in creating beautiful, accessible, and high-performance static web reports from data. You have a deep understanding of web standards and know how to interpret technical requirements pragmatically.

**Core Mandate:**
Your task is to take the provided JSON design brief and transform it into a single, static, scrollable HTML file that is both breathtakingly beautiful and easy to understand.

**STRICT TECHNICAL RULES:**
1.  **NO JAVASCRIPT.** The final output must be pure HTML and CSS.
2.  **NO INTERACTIVE NAVIGATION.** The page is a static report that users will scroll through.
3.  **SELF-CONTAINED.** All CSS must be embedded in `<style>` tags in the `<head>`.
4.  **RAW HTML ONLY.** Your output must be ONLY the raw HTML code, starting with `<!DOCTYPE html>`.
5.  **Regarding "Self-Contained":** This rule applies to your authored CSS. You ARE PERMITTED and EXPECTED to use `<link>` tags in the `<head>` to import third-party resources like the required Google Fonts and the Font Awesome CSS library from their CDNs. This is standard industry practice and is not a violation of the rules.

**DESIGN & EXECUTION DIRECTIVES:**
-   **Modern Stack & Philosophy:** Use modern **HTML5** semantic tags and advanced **CSS3** features. Your design must be inspired by the principles of utility-first frameworks like **Tailwind CSS** (consistent spacing, colors, typography).
-   **Accessibility First:** Ensure all `<img>` tags have descriptive `alt` attributes. Use semantic HTML correctly to ensure the report is accessible.
-   **Theme Implementation:** Flawlessly execute the `visual_theme` from the JSON. Create CSS variables for all colors and use the specified Google Fonts and Font Awesome icons.
-   **Ambitious Visualizations:** For each `visualization_suggestion`, be ambitious! Use clever CSS to create impressive **static** representations like charts, diagrams, or beautiful card layouts.

---
**CRITICAL LAYOUT & ASSET INSTRUCTION (NEW):**
-   The JSON for each slide may or may not contain an `image_url`. Your layout must adapt beautifully to both cases.
-   **If a slide HAS an `image_url`:**
    1.  You **MUST** create a **two-column layout** (e.g., using CSS Grid `grid-template-columns: 1fr 1fr;`).
    2.  Place the image in one column, rendered as a standard `<img>` tag. Style it to be a **square** with a subtle `box-shadow` and `border-radius`.
    3.  Place all the text content (`slide_title`, `key_points`, `augmented_info`, and `visualization_suggestion`) in the other column.
-   **If a slide does NOT have an `image_url`:**
    1.  You **MUST** use a **single, full-width column layout**.
    2.  This creates a more focused, text-and-data-centric slide, providing visual variety.
-   This adaptive layout strategy is crucial for a professional and dynamic presentation.

-   This is the most important rule for handling visual elements. Follow it precisely:

    1.  **If a slide CONTAINS an `image_url`:**
        -   The `image_url` is the **PRIMARY** visual element for that slide. Your main job is to display it beautifully.
        -   You should **NOT** build a complex, redundant CSS representation for the `visualization_suggestion`.
        -   Instead, simply render the text of the `visualization_suggestion` as a small, styled **caption** or note below the main text (e.g., inside a `<footer>` tag with italics). This provides context without clutter.

    2.  **If a slide does NOT contain an `image_url`:**
        -   The `visualization_suggestion` becomes the **PRIMARY** visual element.
        -   In this case, and ONLY in this case, you **MUST** be ambitious and use your expert CSS skills to build the impressive static representation described in the suggestion (e.g., charts, diagrams, timelines).
    
-   **Title Legibility & Contrast (Crucial Rule):** The slide title (`<h2>`) is the most important piece of text on the slide and **MUST** be perfectly legible.
-   **Background:** The element containing the title MUST have a solid, opaque background color (e.g., using `background-color: var(--primary);`). **DO NOT** place title text directly on top of a gradient or background image where contrast may vary.
-   **Text Color:** The title's text color MUST have a very high contrast against its solid background. A simple, effective rule is: use a pure white (`#FFFFFF`) or very light theme color for dark backgrounds, and a pure black (`#000000`) or very dark theme color for light backgrounds. Legibility is more important than using a specific theme color for the text if it creates poor contrast.
---
**CRITICAL CONTENT INSTRUCTION:**
-   Your goal is to create a **cohesive narrative** for each slide by intelligently combining `key_points` and `augmented_info`.
-   Treat the `key_points` as the main headlines and the `augmented_info` as the supporting details. Weave them together naturally.
-   The final slide should feel like a single, well-structured piece of content.

---
**JSON Design Brief:**
{rich_content_json}

Begin HTML Output:
"""
    try:
        # print("Tool 3 (HTML Renderer): Calling SambaNova (DeepSeek-R1-Distill-Llama-70B)...")
        # response = sambanova_client.chat.completions.create(
        #     model="DeepSeek-R1-Distill-Llama-70B",
        #     messages=[{"role": "user", "content": prompt}],
        #     temperature=0.1,
        #     max_tokens=65536,
        # )
        print("Tool 3 (HTML Renderer): Calling Nebius (DeepSeek-R1-0528)...")
        response = nebius_client.chat.completions.create(
            model="deepseek-ai/DeepSeek-R1-0528",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.1,
            max_tokens=65536,
        )
        html_output = response.choices[0].message.content
        print("\n--- DEBUG: Raw HTML from Model (first 4000 chars) ---\n", html_output[:8000], "\n--------------------------------------------\n")
        match = re.search(r"```(?:html)?\s*(<!DOCTYPE html>[\s\S]*?</html>)\s*```", html_output, re.I | re.S)
        if match:
            html_output = match.group(1)
        print("Tool 3 (HTML Renderer): Success.")
        return html_output.strip()
    except Exception as e:
        print(f"❌ Error in convert_rich_content_to_html_tool: {e}")
        raise gr.Error(f"HTML rendering failed: {str(e)}")

def create_pdf_from_html(html_content: str, filename: str = "presentation.pdf") -> str | None:
    """Converts a string of HTML content into a PDF file on disk."""
    try:
        print("Tool 4 (PDF): Generating PDF from HTML and saving to disk...")
        pdf_path = OUTPUT_DIR / filename
        HTML(string=html_content).write_pdf(pdf_path)
        print(f"Tool 4 (PDF): Success. Saved to {pdf_path}")
        return str(pdf_path)
    except Exception as e:
        print(f"❌ Error in PDF generation: {e}")
        return None

MAX_AUDIO_SLIDES = 15 



def execute_agent_task(uploaded_files_list, user_topic_input):
    """
    Orchestrates the full tool chain and updates the UI with native audio components.
    """
    def log_message(icon, message): return f"<p style='margin-bottom: 5px;'>{icon} {message}</p>"
    if not uploaded_files_list:
        raise gr.Error("Please upload at least one document to start.")
    if not user_topic_input.strip():
        gr.Warning("Please describe the presentation topic for better results!")
        user_topic_input = "A professional summary."

    initial_audio_updates = [gr.Audio(visible=False, value=None) for _ in range(MAX_AUDIO_SLIDES)]
    initial_state = [
        "<p><i>Starting agent...</i></p>",
        None, None, None, None,
        gr.Button(interactive=False), gr.DownloadButton(visible=False),
        *initial_audio_updates
    ]
    yield initial_state

    logs = log_message("πŸš€", "Agent task started...")
    try:
        logs += log_message("πŸ“„", "<b>Step 1: Parsing Documents...</b>")
        yield [logs, *initial_state[1:]]
        parsed_markdown = parse_documents_tool(uploaded_files_list)
        logs += log_message("βœ…", "Document parsing successful.")
        yield [logs, parsed_markdown, *initial_state[2:]]

        logs += log_message("🎨", "<b>Step 2: Generating Creative Plan...</b>")
        yield [logs, parsed_markdown, *initial_state[2:]]
        rich_content_json_str = generate_rich_content_and_theme_tool(parsed_markdown, user_topic_input)
        logs += log_message("βœ…", "Creative plan generated.")
        pretty_json_plan = json.dumps(json.loads(rich_content_json_str), indent=2)
        yield [logs, parsed_markdown, pretty_json_plan, *initial_state[3:]]

        logs += log_message("πŸ–ΌοΈ", "<b>Step 3: Generating AI Images...</b>")
        yield [logs, parsed_markdown, pretty_json_plan, *initial_state[3:]]
        final_plan_with_images_str = generate_assets_tool(rich_content_json_str)
        logs += log_message("βœ…", "Image generation complete.")
        pretty_final_plan_with_images = json.dumps(json.loads(final_plan_with_images_str), indent=2)
        yield [logs, parsed_markdown, pretty_final_plan_with_images, *initial_state[3:]]

        logs += log_message("πŸ”Š", "<b>Step 4: Generating Speaker Notes Audio...</b>")
        final_plan_data = None
        
        # Looping over the audio files that are generated
        for i, partial_plan_data in enumerate(generate_audio_assets_tool(final_plan_with_images_str)):
            final_plan_data = partial_plan_data  
            
            audio_updates = [gr.Audio(visible=False, value=None) for _ in range(MAX_AUDIO_SLIDES)]
            total_slides = len(final_plan_data.get("slides", []))
            for j, slide in enumerate(final_plan_data["slides"]):
                if j < MAX_AUDIO_SLIDES:
                    if audio_url := slide.get("audio_url"):
                        slide_title = slide.get("slide_title", f"Slide {j+1}")
                        audio_updates[j] = gr.Audio(visible=True, value=audio_url, label=f"Notes for: {slide_title}", interactive=True)
            
            temp_logs = logs + log_message("βš™οΈ", f"<i>Generated audio for slide {i+1}/{total_slides}...</i>")
            pretty_plan_so_far = json.dumps(final_plan_data, indent=2)
            
            yield [
                temp_logs, parsed_markdown, pretty_plan_so_far, None, None,
                gr.Button(interactive=False), gr.DownloadButton(visible=False),
                *audio_updates
            ]
        
        if final_plan_data is None:
            logs += log_message("⚠️", "Audio generation was skipped.")
            final_plan_data = json.loads(final_plan_with_images_str)

        logs += log_message("βœ…", "Audio generation complete.")
        final_plan_with_audio_str = json.dumps(final_plan_data)
        
        final_audio_updates = [gr.Audio(visible=False, value=None) for _ in range(MAX_AUDIO_SLIDES)]
        for i, slide in enumerate(final_plan_data["slides"]):
             if i < MAX_AUDIO_SLIDES:
                if audio_url := slide.get("audio_url"):
                    slide_title = slide.get("slide_title", f"Slide {i+1}")
                    final_audio_updates[i] = gr.Audio(visible=True, value=audio_url, label=f"Notes for: {slide_title}", interactive=True)
        
        final_pretty_json = json.dumps(final_plan_data, indent=2)

        logs += log_message("πŸ’»", "<b>Step 5: Rendering Final HTML...</b>")
        yield [
            logs, parsed_markdown, final_pretty_json, None, None,
            gr.Button(interactive=False), gr.DownloadButton(visible=False),
            *final_audio_updates
        ]
        final_html = convert_rich_content_to_html_tool(final_plan_with_audio_str)
        raw_html_output = final_html

        logs += log_message("πŸ’Ύ", "<b>Step 6: Generating Downloadable PDF...</b>")
        pdf_file_path = create_pdf_from_html(final_html)

        if pdf_file_path:
            logs += log_message("πŸŽ‰", "<b>Hooray! All assets generated!</b>")
            download_button_update = gr.DownloadButton(value=pdf_file_path, visible=True)
        else:
            logs += log_message("⚠️", "<b>PDF creation failed.</b>")
            download_button_update = gr.DownloadButton(visible=False)

        yield [
            logs, parsed_markdown, final_pretty_json, final_html, raw_html_output,
            gr.Button(value="πŸš€ Run Again", interactive=True),
            download_button_update,
            *final_audio_updates
        ]

    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"πŸ”₯πŸ”₯πŸ”₯ A CRITICAL ERROR OCCURRED: {e}")
        logs += log_message("πŸ”₯", f"<b>A critical error occurred:</b> {str(e)}")
        yield [logs, *initial_state[1:]]


custom_css = """
#logs-box { height: 100%; min-height: 200px; overflow-y: auto; border: 1px solid #e0e0e0; border-radius: 8px; padding: 10px; background-color: #f9f9f9; }
#presentation-output { height: 85vh; }
"""

with gr.Blocks(title="Agentic Presentation Generator", theme=gr.themes.Soft(), css=custom_css) as demo:
    gr.Markdown("# πŸ€– SlideDeck AI : Document-to-Presentation Generator")
    gr.Markdown("Upload documents and describe your presentation's goal. The agent will analyze, generate a creative plan, and render a beautiful, static web presentation with AI-narrated speaker notes.")

    with gr.Row():
        with gr.Column(scale=1):
            file_uploads = gr.File(label="1. Upload Your Documents", file_count="multiple")
            user_topic_input = gr.Textbox(label="2. Describe the Presentation's Topic & Goal", placeholder="e.g., Create an Presentation on this topic.")
            submit_button = gr.Button("πŸš€ Run Agent Task", variant="primary")
            download_pdf_btn = gr.DownloadButton(label="Download as PDF", visible=False)
            
            gr.Markdown("### πŸ“œ Agent Logs")
            with gr.Column(elem_id="logs-box"):
                agent_logs_display = gr.HTML(value="<p><i>Logs will appear here...</i></p>")

        with gr.Column(scale=3):
            with gr.Tabs(selected="final_presentation_tab"):
                
                
                with gr.TabItem("πŸ“ Intermediate Markdown"):
                    intermediate_md_display = gr.Markdown()

                with gr.TabItem("🎨 Creative Plan (JSON)"):
                    intermediate_json_display = gr.Code(language="json")
                
                with gr.TabItem("πŸ”Š Speaker Notes Audio"):
                    with gr.Column():
                        gr.Markdown("Listen to the AI-generated speaker notes for each slide. Audio will appear here once generated.")
                        audio_players = []
                        for i in range(MAX_AUDIO_SLIDES):
                            player = gr.Audio(label=f"Slide {i+1} Audio", visible=False, interactive=False)
                            audio_players.append(player)
                
                
                with gr.TabItem("βœ… Final Presentation", id="final_presentation_tab"):
                    final_html_display = gr.HTML(elem_id="presentation-output")
                
                with gr.TabItem("πŸ“„ Raw HTML Code"):
                    raw_html_code_display = gr.Code(language="html", label="Generated HTML Source Code")

    
    all_outputs = [
        agent_logs_display,
        intermediate_md_display,
        intermediate_json_display,
        final_html_display,
        raw_html_code_display,
        submit_button,
        download_pdf_btn,
        *audio_players 
    ]

    all_inputs = [file_uploads, user_topic_input]

    submit_button.click(
        fn=execute_agent_task,
        inputs=all_inputs,
        outputs=all_outputs
    )

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