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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
import json
|
5 |
+
import gradio as gr
|
6 |
+
from llama_cloud_services import LlamaParse
|
7 |
+
from openai import OpenAI
|
8 |
+
from dotenv import load_dotenv
|
9 |
+
from weasyprint import HTML
|
10 |
+
from pathlib import Path
|
11 |
+
import requests
|
12 |
+
|
13 |
+
MAX_AUDIO_SLIDES = 15
|
14 |
+
|
15 |
+
load_dotenv()
|
16 |
+
|
17 |
+
OUTPUT_DIR = Path("generated_pdf_files")
|
18 |
+
OUTPUT_DIR.mkdir(exist_ok=True)
|
19 |
+
|
20 |
+
OUTPUT_DIR_AUDIO = Path("generated_audio_files")
|
21 |
+
OUTPUT_DIR_AUDIO.mkdir(exist_ok=True)
|
22 |
+
|
23 |
+
MODAL_TTS_URL = os.environ.get("MODAL_TTS_URL")
|
24 |
+
SNC_API_KEY = os.environ.get("SNC_API_KEY")
|
25 |
+
|
26 |
+
|
27 |
+
# LlamaParse Client for document parsing
|
28 |
+
LLAMA_CLOUD_API = os.environ.get("LLAMA_CLOUD_API_KEY")
|
29 |
+
llama_parser_client = None
|
30 |
+
if LLAMA_CLOUD_API:
|
31 |
+
try:
|
32 |
+
llama_parser_client = LlamaParse(api_key=LLAMA_CLOUD_API, result_type="markdown", num_workers=4, language='en', verbose=False)
|
33 |
+
print("β
LlamaParse client initialized successfully.")
|
34 |
+
except Exception as e:
|
35 |
+
print(f"β Error initializing LlamaParse client: {e}")
|
36 |
+
else:
|
37 |
+
print('β οΈ WARNING: LLAMA_CLOUD_API_KEY not found. Document Parsing will be disabled.')
|
38 |
+
|
39 |
+
# Nebius Client for AI generation
|
40 |
+
NEBIUS_API_KEY = os.environ.get("NEBIUS_API_KEY")
|
41 |
+
nebius_client = None
|
42 |
+
if NEBIUS_API_KEY:
|
43 |
+
try:
|
44 |
+
nebius_client = OpenAI(
|
45 |
+
base_url="https://api.studio.nebius.com/v1/",
|
46 |
+
api_key=NEBIUS_API_KEY
|
47 |
+
)
|
48 |
+
print("β
Nebius client initialized successfully.")
|
49 |
+
except Exception as e:
|
50 |
+
print(f"β Error initializing Nebius client: {e}")
|
51 |
+
else:
|
52 |
+
print('β οΈ WARNING: NEBIUS_API_KEY not found. All AI generation tools will be disabled.')
|
53 |
+
|
54 |
+
sambanova_client = None
|
55 |
+
if SNC_API_KEY:
|
56 |
+
sambanova_client = OpenAI(api_key=SNC_API_KEY, base_url='https://api.sambanova.ai/v1')
|
57 |
+
print("β
Sambanova client initialized successfully.")
|
58 |
+
else:
|
59 |
+
print('β οΈ WARNING: SNC_API_KEY not found. All AI generation tools will be disabled.')
|
60 |
+
|
61 |
+
|
62 |
+
|
63 |
+
# Tool 1: Document Parser
|
64 |
+
def parse_documents_tool(files_input_from_gradio: list) -> str:
|
65 |
+
"""Parses uploaded documents using LlamaParse into clean Markdown text."""
|
66 |
+
if not llama_parser_client: raise gr.Error("LlamaParse client not initialized.")
|
67 |
+
if not files_input_from_gradio: raise gr.Error("No files provided for parsing.")
|
68 |
+
|
69 |
+
file_paths = [f.name for f in files_input_from_gradio]
|
70 |
+
try:
|
71 |
+
print(f"Tool 1 (LlamaParse): Parsing {len(file_paths)} documents...")
|
72 |
+
llama_index_documents = llama_parser_client.load_data(file_paths)
|
73 |
+
final_markdown = "\n\n<!-- ========== Next Document ========== -->\n\n".join([doc.text for doc in llama_index_documents if doc.text])
|
74 |
+
print(f"Tool 1 (LlamaParse): Success. Total Markdown length: {len(final_markdown)}")
|
75 |
+
return final_markdown
|
76 |
+
except Exception as e:
|
77 |
+
print(f"β Error in parse_documents_tool: {e}")
|
78 |
+
raise gr.Error(f"LlamaParse failed: {str(e)}")
|
79 |
+
|
80 |
+
# Tool 2: Creative Plan Generator (Augment, Outline, Design)
|
81 |
+
def generate_rich_content_and_theme_tool(parsed_markdown: str, user_topic: str) -> str:
|
82 |
+
"""
|
83 |
+
Analyzes text and a topic to generate a comprehensive JSON 'master plan' for a presentation,
|
84 |
+
including a visual theme, slide structure, augmented content, and visualization ideas.
|
85 |
+
"""
|
86 |
+
if not nebius_client: raise gr.Error("Nebius client not initialized.")
|
87 |
+
|
88 |
+
#
|
89 |
+
prompt = f"""
|
90 |
+
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.
|
91 |
+
|
92 |
+
**Your Plan (JSON Object) Must Contain:**
|
93 |
+
1. `visual_theme`: An object describing the aesthetic with `theme_name`, `primary_color`, `secondary_color`, `accent_color`, `font_headings`, and `font_body`.
|
94 |
+
2. `presentation_title`: A compelling title.
|
95 |
+
3. `slides`: An array of slide objects. For each slide:
|
96 |
+
- `slide_title`: A clear title.
|
97 |
+
- `key_points`: An array of critical bullet points.
|
98 |
+
- `augmented_info`: Additional context and details.
|
99 |
+
- `visualization_suggestion`: A practical idea for a non-image visual element (e.g., "A pure CSS bar chart...").
|
100 |
+
- **`image_generation_prompt`**: An **OPTIONAL** key. Only include this key for the slides you select for an image.
|
101 |
+
- **`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.
|
102 |
+
|
103 |
+
**CRITICAL ART DIRECTION RULES:**
|
104 |
+
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.
|
105 |
+
2. **Title Slide is Mandatory:** The **first (title) slide MUST have an `image_generation_prompt`** to create a strong opening.
|
106 |
+
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.**
|
107 |
+
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.
|
108 |
+
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.
|
109 |
+
- **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."
|
110 |
+
- **Bad Example:** "An image about finance." (Too generic!)
|
111 |
+
- **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.
|
112 |
+
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.
|
113 |
+
|
114 |
+
**Instructions for `image_generation_prompt` for the 'flux-schnell' model:**
|
115 |
+
- Focus on keywords like: "minimalist illustration", "conceptual art", "vector graphic", "isometric design", "abstract shapes", "data visualization art".
|
116 |
+
- Incorporate the `visual_theme` colors into the prompt (e.g., "Dominant colors: [primary_color], [accent_color]").
|
117 |
+
|
118 |
+
**Presentation Topic:** "{user_topic}"
|
119 |
+
**Parsed Document Text:** --- {parsed_markdown} ---
|
120 |
+
Begin JSON Output:
|
121 |
+
"""
|
122 |
+
try:
|
123 |
+
|
124 |
+
# response = nebius_client.chat.completions.create(
|
125 |
+
# model="deepseek-ai/DeepSeek-V3-0324",
|
126 |
+
# messages=[{"role": "user", "content": prompt}],
|
127 |
+
# temperature=0.4,
|
128 |
+
# max_tokens=8192,
|
129 |
+
# response_format={"type": "json_object"},
|
130 |
+
# )
|
131 |
+
print("Tool 2 (Creative Plan): Calling Sambanova (DeepSeek-V3-0324)...")
|
132 |
+
response = sambanova_client.chat.completions.create(
|
133 |
+
model="DeepSeek-V3-0324",
|
134 |
+
messages=[{"role": "user", "content": prompt}],
|
135 |
+
temperature=0.4,
|
136 |
+
max_tokens=8192,
|
137 |
+
response_format={"type": "json_object"},
|
138 |
+
)
|
139 |
+
rich_content_json = response.choices[0].message.content
|
140 |
+
print("\n--- DEBUG: Raw Creative Plan JSON from Model ---\n", rich_content_json, "\n----------------------------------------\n")
|
141 |
+
json.loads(rich_content_json)
|
142 |
+
print("Tool 2 (Creative Plan): Success.")
|
143 |
+
return rich_content_json
|
144 |
+
except Exception as e:
|
145 |
+
print(f"β Error in generate_rich_content_and_theme_tool: {e}")
|
146 |
+
raise gr.Error(f"Creative plan generation failed: {str(e)}")
|
147 |
+
|
148 |
+
def generate_assets_tool(json_plan_str: str) -> str:
|
149 |
+
"""
|
150 |
+
Takes a JSON plan, generates images for each slide using the provided prompts,
|
151 |
+
and returns an updated JSON plan with image URLs.
|
152 |
+
"""
|
153 |
+
if not nebius_client: raise gr.Error("Nebius client not initialized.")
|
154 |
+
|
155 |
+
print("Tool 3 (Asset Gen): Starting image generation for all slides...")
|
156 |
+
plan_data = json.loads(json_plan_str)
|
157 |
+
|
158 |
+
for i, slide in enumerate(plan_data["slides"]):
|
159 |
+
image_prompt = slide.get("image_generation_prompt")
|
160 |
+
if not image_prompt:
|
161 |
+
print(f" - Skipping slide {i+1}, no image prompt found.")
|
162 |
+
plan_data["slides"][i]["image_url"] = None # Explicitly set to null
|
163 |
+
continue
|
164 |
+
|
165 |
+
print(f" - Generating image for slide {i+1}: '{slide['slide_title']}'...")
|
166 |
+
try:
|
167 |
+
response = nebius_client.images.generate(
|
168 |
+
model="black-forest-labs/flux-schnell",
|
169 |
+
prompt=image_prompt,
|
170 |
+
response_format="url",
|
171 |
+
extra_body={
|
172 |
+
"width": 1024,
|
173 |
+
"height": 1024,
|
174 |
+
"num_inference_steps": 4,
|
175 |
+
},
|
176 |
+
)
|
177 |
+
image_url = response.data[0].url
|
178 |
+
plan_data["slides"][i]["image_url"] = image_url
|
179 |
+
print(f" - Success! Image URL: {image_url}")
|
180 |
+
except Exception as e:
|
181 |
+
print(f" - β FAILED to generate image for slide {i+1}: {e}")
|
182 |
+
plan_data["slides"][i]["image_url"] = None
|
183 |
+
|
184 |
+
return json.dumps(plan_data)
|
185 |
+
|
186 |
+
# Tool 4: Audio Asset Generator
|
187 |
+
def generate_audio_assets_tool(json_plan_str: str):
|
188 |
+
"""
|
189 |
+
Takes a JSON plan, generates audio for each slide using the Modal TTS API,
|
190 |
+
and returns an updated JSON plan with audio URLs.
|
191 |
+
"""
|
192 |
+
if not MODAL_TTS_URL:
|
193 |
+
print("β οΈ WARNING: MODAL_TTS_URL not set. Skipping audio generation.")
|
194 |
+
return json_plan_str
|
195 |
+
|
196 |
+
print("Tool 4 (Audio Gen): Starting TTS for all slides via Modal API...")
|
197 |
+
plan_data = json.loads(json_plan_str)
|
198 |
+
|
199 |
+
for i, slide in enumerate(plan_data["slides"]):
|
200 |
+
notes_text = slide.get("speaker_notes_text")
|
201 |
+
if not notes_text:
|
202 |
+
print(f" - Skipping audio for slide {i+1}, no speaker notes text found.")
|
203 |
+
plan_data["slides"][i]["audio_url"] = None
|
204 |
+
continue
|
205 |
+
|
206 |
+
print(f" - Generating audio for slide {i+1}...")
|
207 |
+
try:
|
208 |
+
payload = {"text": notes_text, "voice": "af_heart"}
|
209 |
+
headers = {"Content-Type": "application/json"}
|
210 |
+
|
211 |
+
response = requests.post(MODAL_TTS_URL, json=payload, headers=headers, timeout=180)
|
212 |
+
|
213 |
+
if response.status_code == 200:
|
214 |
+
audio_path = OUTPUT_DIR_AUDIO / f"slide_audio_{i}.wav"
|
215 |
+
with open(audio_path, "wb") as f:
|
216 |
+
f.write(response.content)
|
217 |
+
plan_data["slides"][i]["audio_url"] = str(audio_path)
|
218 |
+
print(f" - Success! Audio saved to {audio_path}")
|
219 |
+
else:
|
220 |
+
print(f" - β FAILED to generate audio for slide {i+1}. Status: {response.status_code}, Response: {response.text}")
|
221 |
+
plan_data["slides"][i]["audio_url"] = None
|
222 |
+
except Exception as e:
|
223 |
+
print(f" - β FAILED to generate audio for slide {i+1} with exception: {e}")
|
224 |
+
plan_data["slides"][i]["audio_url"] = None
|
225 |
+
|
226 |
+
# return json.dumps(plan_data)
|
227 |
+
yield plan_data
|
228 |
+
|
229 |
+
# Tool 3: HTML Presentation Renderer
|
230 |
+
def convert_rich_content_to_html_tool(rich_content_json: str) -> str:
|
231 |
+
"""Takes a rich JSON 'master plan' and renders it as a single, static HTML file."""
|
232 |
+
if not nebius_client: raise gr.Error("Nebius client not initialized.")
|
233 |
+
|
234 |
+
prompt = f"""
|
235 |
+
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.
|
236 |
+
|
237 |
+
**Core Mandate:**
|
238 |
+
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.
|
239 |
+
|
240 |
+
**STRICT TECHNICAL RULES:**
|
241 |
+
1. **NO JAVASCRIPT.** The final output must be pure HTML and CSS.
|
242 |
+
2. **NO INTERACTIVE NAVIGATION.** The page is a static report that users will scroll through.
|
243 |
+
3. **SELF-CONTAINED.** All CSS must be embedded in `<style>` tags in the `<head>`.
|
244 |
+
4. **RAW HTML ONLY.** Your output must be ONLY the raw HTML code, starting with `<!DOCTYPE html>`.
|
245 |
+
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.
|
246 |
+
|
247 |
+
**DESIGN & EXECUTION DIRECTIVES:**
|
248 |
+
- **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).
|
249 |
+
- **Accessibility First:** Ensure all `<img>` tags have descriptive `alt` attributes. Use semantic HTML correctly to ensure the report is accessible.
|
250 |
+
- **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.
|
251 |
+
- **Ambitious Visualizations:** For each `visualization_suggestion`, be ambitious! Use clever CSS to create impressive **static** representations like charts, diagrams, or beautiful card layouts.
|
252 |
+
|
253 |
+
---
|
254 |
+
**CRITICAL LAYOUT & ASSET INSTRUCTION (NEW):**
|
255 |
+
- The JSON for each slide may or may not contain an `image_url`. Your layout must adapt beautifully to both cases.
|
256 |
+
- **If a slide HAS an `image_url`:**
|
257 |
+
1. You **MUST** create a **two-column layout** (e.g., using CSS Grid `grid-template-columns: 1fr 1fr;`).
|
258 |
+
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`.
|
259 |
+
3. Place all the text content (`slide_title`, `key_points`, `augmented_info`, and `visualization_suggestion`) in the other column.
|
260 |
+
- **If a slide does NOT have an `image_url`:**
|
261 |
+
1. You **MUST** use a **single, full-width column layout**.
|
262 |
+
2. This creates a more focused, text-and-data-centric slide, providing visual variety.
|
263 |
+
- This adaptive layout strategy is crucial for a professional and dynamic presentation.
|
264 |
+
|
265 |
+
- This is the most important rule for handling visual elements. Follow it precisely:
|
266 |
+
|
267 |
+
1. **If a slide CONTAINS an `image_url`:**
|
268 |
+
- The `image_url` is the **PRIMARY** visual element for that slide. Your main job is to display it beautifully.
|
269 |
+
- You should **NOT** build a complex, redundant CSS representation for the `visualization_suggestion`.
|
270 |
+
- 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.
|
271 |
+
|
272 |
+
2. **If a slide does NOT contain an `image_url`:**
|
273 |
+
- The `visualization_suggestion` becomes the **PRIMARY** visual element.
|
274 |
+
- 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).
|
275 |
+
|
276 |
+
- **Title Legibility & Contrast (Crucial Rule):** The slide title (`<h2>`) is the most important piece of text on the slide and **MUST** be perfectly legible.
|
277 |
+
- **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.
|
278 |
+
- **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.
|
279 |
+
---
|
280 |
+
**CRITICAL CONTENT INSTRUCTION:**
|
281 |
+
- Your goal is to create a **cohesive narrative** for each slide by intelligently combining `key_points` and `augmented_info`.
|
282 |
+
- Treat the `key_points` as the main headlines and the `augmented_info` as the supporting details. Weave them together naturally.
|
283 |
+
- The final slide should feel like a single, well-structured piece of content.
|
284 |
+
|
285 |
+
---
|
286 |
+
**JSON Design Brief:**
|
287 |
+
{rich_content_json}
|
288 |
+
|
289 |
+
Begin HTML Output:
|
290 |
+
"""
|
291 |
+
try:
|
292 |
+
# print("Tool 3 (HTML Renderer): Calling SambaNova (DeepSeek-R1-Distill-Llama-70B)...")
|
293 |
+
# response = sambanova_client.chat.completions.create(
|
294 |
+
# model="DeepSeek-R1-Distill-Llama-70B",
|
295 |
+
# messages=[{"role": "user", "content": prompt}],
|
296 |
+
# temperature=0.1,
|
297 |
+
# max_tokens=65536,
|
298 |
+
# )
|
299 |
+
print("Tool 3 (HTML Renderer): Calling Nebius (DeepSeek-R1-0528)...")
|
300 |
+
response = nebius_client.chat.completions.create(
|
301 |
+
model="deepseek-ai/DeepSeek-R1-0528",
|
302 |
+
messages=[{"role": "user", "content": prompt}],
|
303 |
+
temperature=0.1,
|
304 |
+
max_tokens=65536,
|
305 |
+
)
|
306 |
+
html_output = response.choices[0].message.content
|
307 |
+
print("\n--- DEBUG: Raw HTML from Model (first 4000 chars) ---\n", html_output[:8000], "\n--------------------------------------------\n")
|
308 |
+
match = re.search(r"```(?:html)?\s*(<!DOCTYPE html>[\s\S]*?</html>)\s*```", html_output, re.I | re.S)
|
309 |
+
if match:
|
310 |
+
html_output = match.group(1)
|
311 |
+
print("Tool 3 (HTML Renderer): Success.")
|
312 |
+
return html_output.strip()
|
313 |
+
except Exception as e:
|
314 |
+
print(f"β Error in convert_rich_content_to_html_tool: {e}")
|
315 |
+
raise gr.Error(f"HTML rendering failed: {str(e)}")
|
316 |
+
|
317 |
+
def create_pdf_from_html(html_content: str, filename: str = "presentation.pdf") -> str | None:
|
318 |
+
"""Converts a string of HTML content into a PDF file on disk."""
|
319 |
+
try:
|
320 |
+
print("Tool 4 (PDF): Generating PDF from HTML and saving to disk...")
|
321 |
+
pdf_path = OUTPUT_DIR / filename
|
322 |
+
HTML(string=html_content).write_pdf(pdf_path)
|
323 |
+
print(f"Tool 4 (PDF): Success. Saved to {pdf_path}")
|
324 |
+
return str(pdf_path)
|
325 |
+
except Exception as e:
|
326 |
+
print(f"β Error in PDF generation: {e}")
|
327 |
+
return None
|
328 |
+
|
329 |
+
MAX_AUDIO_SLIDES = 15
|
330 |
+
|
331 |
+
|
332 |
+
|
333 |
+
def execute_agent_task(uploaded_files_list, user_topic_input):
|
334 |
+
"""
|
335 |
+
Orchestrates the full tool chain and updates the UI with native audio components.
|
336 |
+
"""
|
337 |
+
def log_message(icon, message): return f"<p style='margin-bottom: 5px;'>{icon} {message}</p>"
|
338 |
+
if not uploaded_files_list:
|
339 |
+
raise gr.Error("Please upload at least one document to start.")
|
340 |
+
if not user_topic_input.strip():
|
341 |
+
gr.Warning("Please describe the presentation topic for better results!")
|
342 |
+
user_topic_input = "A professional summary."
|
343 |
+
|
344 |
+
initial_audio_updates = [gr.Audio(visible=False, value=None) for _ in range(MAX_AUDIO_SLIDES)]
|
345 |
+
initial_state = [
|
346 |
+
"<p><i>Starting agent...</i></p>",
|
347 |
+
None, None, None, None,
|
348 |
+
gr.Button(interactive=False), gr.DownloadButton(visible=False),
|
349 |
+
*initial_audio_updates
|
350 |
+
]
|
351 |
+
yield initial_state
|
352 |
+
|
353 |
+
logs = log_message("π", "Agent task started...")
|
354 |
+
try:
|
355 |
+
logs += log_message("π", "<b>Step 1: Parsing Documents...</b>")
|
356 |
+
yield [logs, *initial_state[1:]]
|
357 |
+
parsed_markdown = parse_documents_tool(uploaded_files_list)
|
358 |
+
logs += log_message("β
", "Document parsing successful.")
|
359 |
+
yield [logs, parsed_markdown, *initial_state[2:]]
|
360 |
+
|
361 |
+
logs += log_message("π¨", "<b>Step 2: Generating Creative Plan...</b>")
|
362 |
+
yield [logs, parsed_markdown, *initial_state[2:]]
|
363 |
+
rich_content_json_str = generate_rich_content_and_theme_tool(parsed_markdown, user_topic_input)
|
364 |
+
logs += log_message("β
", "Creative plan generated.")
|
365 |
+
pretty_json_plan = json.dumps(json.loads(rich_content_json_str), indent=2)
|
366 |
+
yield [logs, parsed_markdown, pretty_json_plan, *initial_state[3:]]
|
367 |
+
|
368 |
+
logs += log_message("πΌοΈ", "<b>Step 3: Generating AI Images...</b>")
|
369 |
+
yield [logs, parsed_markdown, pretty_json_plan, *initial_state[3:]]
|
370 |
+
final_plan_with_images_str = generate_assets_tool(rich_content_json_str)
|
371 |
+
logs += log_message("β
", "Image generation complete.")
|
372 |
+
pretty_final_plan_with_images = json.dumps(json.loads(final_plan_with_images_str), indent=2)
|
373 |
+
yield [logs, parsed_markdown, pretty_final_plan_with_images, *initial_state[3:]]
|
374 |
+
|
375 |
+
logs += log_message("π", "<b>Step 4: Generating Speaker Notes Audio...</b>")
|
376 |
+
final_plan_data = None
|
377 |
+
|
378 |
+
# Looping over the audio files that are generated
|
379 |
+
for i, partial_plan_data in enumerate(generate_audio_assets_tool(final_plan_with_images_str)):
|
380 |
+
final_plan_data = partial_plan_data
|
381 |
+
|
382 |
+
audio_updates = [gr.Audio(visible=False, value=None) for _ in range(MAX_AUDIO_SLIDES)]
|
383 |
+
total_slides = len(final_plan_data.get("slides", []))
|
384 |
+
for j, slide in enumerate(final_plan_data["slides"]):
|
385 |
+
if j < MAX_AUDIO_SLIDES:
|
386 |
+
if audio_url := slide.get("audio_url"):
|
387 |
+
slide_title = slide.get("slide_title", f"Slide {j+1}")
|
388 |
+
audio_updates[j] = gr.Audio(visible=True, value=audio_url, label=f"Notes for: {slide_title}", interactive=True)
|
389 |
+
|
390 |
+
temp_logs = logs + log_message("βοΈ", f"<i>Generated audio for slide {i+1}/{total_slides}...</i>")
|
391 |
+
pretty_plan_so_far = json.dumps(final_plan_data, indent=2)
|
392 |
+
|
393 |
+
yield [
|
394 |
+
temp_logs, parsed_markdown, pretty_plan_so_far, None, None,
|
395 |
+
gr.Button(interactive=False), gr.DownloadButton(visible=False),
|
396 |
+
*audio_updates
|
397 |
+
]
|
398 |
+
|
399 |
+
if final_plan_data is None:
|
400 |
+
logs += log_message("β οΈ", "Audio generation was skipped.")
|
401 |
+
final_plan_data = json.loads(final_plan_with_images_str)
|
402 |
+
|
403 |
+
logs += log_message("β
", "Audio generation complete.")
|
404 |
+
final_plan_with_audio_str = json.dumps(final_plan_data)
|
405 |
+
|
406 |
+
final_audio_updates = [gr.Audio(visible=False, value=None) for _ in range(MAX_AUDIO_SLIDES)]
|
407 |
+
for i, slide in enumerate(final_plan_data["slides"]):
|
408 |
+
if i < MAX_AUDIO_SLIDES:
|
409 |
+
if audio_url := slide.get("audio_url"):
|
410 |
+
slide_title = slide.get("slide_title", f"Slide {i+1}")
|
411 |
+
final_audio_updates[i] = gr.Audio(visible=True, value=audio_url, label=f"Notes for: {slide_title}", interactive=True)
|
412 |
+
|
413 |
+
final_pretty_json = json.dumps(final_plan_data, indent=2)
|
414 |
+
|
415 |
+
logs += log_message("π»", "<b>Step 5: Rendering Final HTML...</b>")
|
416 |
+
yield [
|
417 |
+
logs, parsed_markdown, final_pretty_json, None, None,
|
418 |
+
gr.Button(interactive=False), gr.DownloadButton(visible=False),
|
419 |
+
*final_audio_updates
|
420 |
+
]
|
421 |
+
final_html = convert_rich_content_to_html_tool(final_plan_with_audio_str)
|
422 |
+
raw_html_output = final_html
|
423 |
+
|
424 |
+
logs += log_message("πΎ", "<b>Step 6: Generating Downloadable PDF...</b>")
|
425 |
+
pdf_file_path = create_pdf_from_html(final_html)
|
426 |
+
|
427 |
+
if pdf_file_path:
|
428 |
+
logs += log_message("π", "<b>Hooray! All assets generated!</b>")
|
429 |
+
download_button_update = gr.DownloadButton(value=pdf_file_path, visible=True)
|
430 |
+
else:
|
431 |
+
logs += log_message("β οΈ", "<b>PDF creation failed.</b>")
|
432 |
+
download_button_update = gr.DownloadButton(visible=False)
|
433 |
+
|
434 |
+
yield [
|
435 |
+
logs, parsed_markdown, final_pretty_json, final_html, raw_html_output,
|
436 |
+
gr.Button(value="π Run Again", interactive=True),
|
437 |
+
download_button_update,
|
438 |
+
*final_audio_updates
|
439 |
+
]
|
440 |
+
|
441 |
+
except Exception as e:
|
442 |
+
import traceback
|
443 |
+
traceback.print_exc()
|
444 |
+
print(f"π₯π₯π₯ A CRITICAL ERROR OCCURRED: {e}")
|
445 |
+
logs += log_message("π₯", f"<b>A critical error occurred:</b> {str(e)}")
|
446 |
+
yield [logs, *initial_state[1:]]
|
447 |
+
|
448 |
+
|
449 |
+
custom_css = """
|
450 |
+
#logs-box { height: 100%; min-height: 200px; overflow-y: auto; border: 1px solid #e0e0e0; border-radius: 8px; padding: 10px; background-color: #f9f9f9; }
|
451 |
+
#presentation-output { height: 85vh; }
|
452 |
+
"""
|
453 |
+
|
454 |
+
with gr.Blocks(title="Agentic Presentation Generator", theme=gr.themes.Soft(), css=custom_css) as demo:
|
455 |
+
gr.Markdown("# π€ SlideDeck AI : Document-to-Presentation Generator")
|
456 |
+
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.")
|
457 |
+
|
458 |
+
with gr.Row():
|
459 |
+
with gr.Column(scale=1):
|
460 |
+
file_uploads = gr.File(label="1. Upload Your Documents", file_count="multiple")
|
461 |
+
user_topic_input = gr.Textbox(label="2. Describe the Presentation's Topic & Goal", placeholder="e.g., Create an Presentation on this topic.")
|
462 |
+
submit_button = gr.Button("π Run Agent Task", variant="primary")
|
463 |
+
download_pdf_btn = gr.DownloadButton(label="Download as PDF", visible=False)
|
464 |
+
|
465 |
+
gr.Markdown("### π Agent Logs")
|
466 |
+
with gr.Column(elem_id="logs-box"):
|
467 |
+
agent_logs_display = gr.HTML(value="<p><i>Logs will appear here...</i></p>")
|
468 |
+
|
469 |
+
with gr.Column(scale=3):
|
470 |
+
with gr.Tabs(selected="final_presentation_tab"):
|
471 |
+
|
472 |
+
|
473 |
+
with gr.TabItem("π Intermediate Markdown"):
|
474 |
+
intermediate_md_display = gr.Markdown()
|
475 |
+
|
476 |
+
with gr.TabItem("π¨ Creative Plan (JSON)"):
|
477 |
+
intermediate_json_display = gr.Code(language="json")
|
478 |
+
|
479 |
+
with gr.TabItem("π Speaker Notes Audio"):
|
480 |
+
with gr.Column():
|
481 |
+
gr.Markdown("Listen to the AI-generated speaker notes for each slide. Audio will appear here once generated.")
|
482 |
+
audio_players = []
|
483 |
+
for i in range(MAX_AUDIO_SLIDES):
|
484 |
+
player = gr.Audio(label=f"Slide {i+1} Audio", visible=False, interactive=False)
|
485 |
+
audio_players.append(player)
|
486 |
+
|
487 |
+
|
488 |
+
with gr.TabItem("β
Final Presentation", id="final_presentation_tab"):
|
489 |
+
final_html_display = gr.HTML(elem_id="presentation-output")
|
490 |
+
|
491 |
+
with gr.TabItem("π Raw HTML Code"):
|
492 |
+
raw_html_code_display = gr.Code(language="html", label="Generated HTML Source Code")
|
493 |
+
|
494 |
+
|
495 |
+
all_outputs = [
|
496 |
+
agent_logs_display,
|
497 |
+
intermediate_md_display,
|
498 |
+
intermediate_json_display,
|
499 |
+
final_html_display,
|
500 |
+
raw_html_code_display,
|
501 |
+
submit_button,
|
502 |
+
download_pdf_btn,
|
503 |
+
*audio_players
|
504 |
+
]
|
505 |
+
|
506 |
+
all_inputs = [file_uploads, user_topic_input]
|
507 |
+
|
508 |
+
submit_button.click(
|
509 |
+
fn=execute_agent_task,
|
510 |
+
inputs=all_inputs,
|
511 |
+
outputs=all_outputs
|
512 |
+
)
|
513 |
+
|
514 |
+
if __name__ == "__main__":
|
515 |
+
demo.launch(mcp_server=True, debug=True)
|