aspect ratio and model name user-defined, saveguard around generate content
Browse files- .github/workflows/docker.yml +0 -35
- src/compilation/json_to_tex.py +10 -5
- src/compilation/latex_compilation.py +2 -2
- src/database/__init__.py +2 -1
- src/database/database.py +2 -1
- src/database/db_manipulation.py +15 -5
- src/generator.py +40 -13
- src/interface/__init__.py +11 -3
- src/interface/gradio_interface.py +75 -17
- src/interface/session_manager.py +15 -4
- src/services/__init__.py +2 -2
- src/services/google_client.py +41 -1
- src/services/output_schema.py +2 -1
- src/services/prompt.py +2 -1
.github/workflows/docker.yml
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 1 |
-
name: Docker CI
|
| 2 |
-
|
| 3 |
-
on:
|
| 4 |
-
push:
|
| 5 |
-
branches: [main]
|
| 6 |
-
tags:
|
| 7 |
-
- 'v*' # e.g. v1.0.0
|
| 8 |
-
pull_request:
|
| 9 |
-
branches: [main]
|
| 10 |
-
|
| 11 |
-
jobs:
|
| 12 |
-
docker-build:
|
| 13 |
-
runs-on: ubuntu-latest
|
| 14 |
-
|
| 15 |
-
steps:
|
| 16 |
-
- name: Checkout code
|
| 17 |
-
uses: actions/checkout@v4
|
| 18 |
-
|
| 19 |
-
- name: Set up Docker Buildx
|
| 20 |
-
uses: docker/setup-buildx-action@v3
|
| 21 |
-
|
| 22 |
-
- name: Log in to DockerHub
|
| 23 |
-
uses: docker/login-action@v3
|
| 24 |
-
if: github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')
|
| 25 |
-
with:
|
| 26 |
-
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
| 27 |
-
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
| 28 |
-
|
| 29 |
-
- name: Build Docker image
|
| 30 |
-
uses: docker/build-push-action@v5
|
| 31 |
-
with:
|
| 32 |
-
context: .
|
| 33 |
-
file: Dockerfile
|
| 34 |
-
push: ${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
|
| 35 |
-
tags: yourusername/ragntex:latest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/compilation/json_to_tex.py
CHANGED
|
@@ -20,17 +20,22 @@ def render_content(content: list[str], content_format: str) -> str:
|
|
| 20 |
)
|
| 21 |
|
| 22 |
|
| 23 |
-
def json_to_tex(
|
|
|
|
|
|
|
| 24 |
"""Convert a JSON representation of a presentation to LaTeX Beamer format.
|
| 25 |
Args:
|
| 26 |
presentation (Dict[str, Any]): JSON LLM output of the presentation.
|
| 27 |
theme (str): Beamer theme to use.
|
| 28 |
color_theme (str): Beamer color theme to use.
|
|
|
|
| 29 |
Returns:
|
| 30 |
str: LaTeX Beamer code as a string.
|
| 31 |
"""
|
| 32 |
presentation = json.loads(presentation_json)
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
\\usetheme{{{theme}}}
|
| 35 |
\\usecolortheme{{{color_theme}}}
|
| 36 |
\\title{{{presentation["title"]}}}
|
|
@@ -51,10 +56,10 @@ def json_to_tex(presentation_json: str, theme: str, color_theme: str) -> str:
|
|
| 51 |
content_format = slide.get("content_format", "itemize")
|
| 52 |
body = render_content(content, content_format)
|
| 53 |
|
| 54 |
-
if slide_type == "title":
|
| 55 |
-
|
| 56 |
|
| 57 |
-
|
| 58 |
title = "Introduction" if slide_type == "introduction" else "Summary"
|
| 59 |
slides.append(
|
| 60 |
f"""\\begin{{frame}}
|
|
|
|
| 20 |
)
|
| 21 |
|
| 22 |
|
| 23 |
+
def json_to_tex(
|
| 24 |
+
presentation_json: str, theme: str, color_theme: str, aspect_ratio: str
|
| 25 |
+
) -> str:
|
| 26 |
"""Convert a JSON representation of a presentation to LaTeX Beamer format.
|
| 27 |
Args:
|
| 28 |
presentation (Dict[str, Any]): JSON LLM output of the presentation.
|
| 29 |
theme (str): Beamer theme to use.
|
| 30 |
color_theme (str): Beamer color theme to use.
|
| 31 |
+
aspect_ratio (str): Aspect ratio for the presentation, e.g., "16:9", "4:3".
|
| 32 |
Returns:
|
| 33 |
str: LaTeX Beamer code as a string.
|
| 34 |
"""
|
| 35 |
presentation = json.loads(presentation_json)
|
| 36 |
+
aspect_ratio_num = 169 if aspect_ratio == "16:9" else 43
|
| 37 |
+
header = f"""\\documentclass[aspectratio={aspect_ratio_num}]{{beamer}}
|
| 38 |
+
\\usepackage[utf8]{{inputenc}}
|
| 39 |
\\usetheme{{{theme}}}
|
| 40 |
\\usecolortheme{{{color_theme}}}
|
| 41 |
\\title{{{presentation["title"]}}}
|
|
|
|
| 56 |
content_format = slide.get("content_format", "itemize")
|
| 57 |
body = render_content(content, content_format)
|
| 58 |
|
| 59 |
+
# if slide_type == "title":
|
| 60 |
+
# continue
|
| 61 |
|
| 62 |
+
if slide_type in {"introduction", "summary"}:
|
| 63 |
title = "Introduction" if slide_type == "introduction" else "Summary"
|
| 64 |
slides.append(
|
| 65 |
f"""\\begin{{frame}}
|
src/compilation/latex_compilation.py
CHANGED
|
@@ -61,7 +61,7 @@ def compile_presentation(latex_code, work_dir) -> str:
|
|
| 61 |
)
|
| 62 |
# Check for PDF output
|
| 63 |
pdf_file = Path(work_dir) / "presentation.pdf"
|
| 64 |
-
if not pdf_file.exists:
|
| 65 |
LOGGER.error(
|
| 66 |
"❌ PDF generation failed and no PDF file found. Here's the log: %s",
|
| 67 |
e.stderr.decode(),
|
|
@@ -77,7 +77,7 @@ def compile_presentation(latex_code, work_dir) -> str:
|
|
| 77 |
|
| 78 |
# Success, but still check for PDF output
|
| 79 |
pdf_file = Path(work_dir) / "presentation.pdf"
|
| 80 |
-
if not pdf_file.exists:
|
| 81 |
langfuse_context.update_current_observation(
|
| 82 |
output={
|
| 83 |
"pdf.success": False,
|
|
|
|
| 61 |
)
|
| 62 |
# Check for PDF output
|
| 63 |
pdf_file = Path(work_dir) / "presentation.pdf"
|
| 64 |
+
if not pdf_file.exists():
|
| 65 |
LOGGER.error(
|
| 66 |
"❌ PDF generation failed and no PDF file found. Here's the log: %s",
|
| 67 |
e.stderr.decode(),
|
|
|
|
| 77 |
|
| 78 |
# Success, but still check for PDF output
|
| 79 |
pdf_file = Path(work_dir) / "presentation.pdf"
|
| 80 |
+
if not pdf_file.exists():
|
| 81 |
langfuse_context.update_current_observation(
|
| 82 |
output={
|
| 83 |
"pdf.success": False,
|
src/database/__init__.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""This module initializes the database package."""
|
| 2 |
|
| 3 |
from .database import chroma_client, embed_fn
|
| 4 |
-
from .db_manipulation import
|
|
|
|
| 5 |
|
| 6 |
__all__ = ["chroma_client", "embed_fn", "ingest_files_to_db", "retrive_files_from_db", "clean_db"]
|
|
|
|
| 1 |
"""This module initializes the database package."""
|
| 2 |
|
| 3 |
from .database import chroma_client, embed_fn
|
| 4 |
+
from .db_manipulation import (clean_db, ingest_files_to_db,
|
| 5 |
+
retrive_files_from_db)
|
| 6 |
|
| 7 |
__all__ = ["chroma_client", "embed_fn", "ingest_files_to_db", "retrive_files_from_db", "clean_db"]
|
src/database/database.py
CHANGED
|
@@ -34,7 +34,8 @@ class GeminiEmbeddingFunction(EmbeddingFunction):
|
|
| 34 |
)
|
| 35 |
return [e.values for e in response.embeddings]
|
| 36 |
|
|
|
|
| 37 |
embed_fn = GeminiEmbeddingFunction()
|
| 38 |
embed_fn.document_mode = True
|
| 39 |
|
| 40 |
-
chroma_client = chromadb.Client()
|
|
|
|
| 34 |
)
|
| 35 |
return [e.values for e in response.embeddings]
|
| 36 |
|
| 37 |
+
|
| 38 |
embed_fn = GeminiEmbeddingFunction()
|
| 39 |
embed_fn.document_mode = True
|
| 40 |
|
| 41 |
+
chroma_client = chromadb.Client()
|
src/database/db_manipulation.py
CHANGED
|
@@ -19,7 +19,9 @@ def ingest_files_to_db(pdf_files, session_id) -> list[str]:
|
|
| 19 |
session_id (str): Unique identifier for the current session.
|
| 20 |
"""
|
| 21 |
# Get or create the database collection
|
| 22 |
-
db = chroma_client.get_or_create_collection(
|
|
|
|
|
|
|
| 23 |
|
| 24 |
# Get all the existing entries and extract the known filenames
|
| 25 |
all_entries = db.get(include=["metadatas"]) or []
|
|
@@ -61,7 +63,9 @@ MetadataBatch = List[List[Metadata]]
|
|
| 61 |
|
| 62 |
|
| 63 |
@observe(name="🔍 retrieve_files_from_db")
|
| 64 |
-
def retrive_files_from_db(
|
|
|
|
|
|
|
| 65 |
"""Retrieve relevant documents from the database based on the provided topic.
|
| 66 |
Args:
|
| 67 |
topic (str): The topic for which to retrieve documents.
|
|
@@ -72,7 +76,9 @@ def retrive_files_from_db(topic: str, session_id: str) -> tuple[DocumentsBatch,
|
|
| 72 |
- list[dict]: List of metadata associated with the documents.
|
| 73 |
"""
|
| 74 |
# Get or create the database collection
|
| 75 |
-
db = chroma_client.get_or_create_collection(
|
|
|
|
|
|
|
| 76 |
if not db:
|
| 77 |
LOGGER.error("❌ Database collection not found or could not be created.")
|
| 78 |
return [], []
|
|
@@ -101,9 +107,13 @@ def clean_db(session_id: str) -> None:
|
|
| 101 |
Args:
|
| 102 |
session_id (str): Unique identifier for the current session.
|
| 103 |
"""
|
| 104 |
-
db = chroma_client.get_or_create_collection(
|
|
|
|
|
|
|
| 105 |
if db:
|
| 106 |
chroma_client.delete_collection(name=session_id)
|
| 107 |
LOGGER.info("🗑️ Cleaning database for session ID: %s", session_id)
|
| 108 |
else:
|
| 109 |
-
LOGGER.warning(
|
|
|
|
|
|
|
|
|
| 19 |
session_id (str): Unique identifier for the current session.
|
| 20 |
"""
|
| 21 |
# Get or create the database collection
|
| 22 |
+
db = chroma_client.get_or_create_collection(
|
| 23 |
+
name=session_id, embedding_function=embed_fn
|
| 24 |
+
)
|
| 25 |
|
| 26 |
# Get all the existing entries and extract the known filenames
|
| 27 |
all_entries = db.get(include=["metadatas"]) or []
|
|
|
|
| 63 |
|
| 64 |
|
| 65 |
@observe(name="🔍 retrieve_files_from_db")
|
| 66 |
+
def retrive_files_from_db(
|
| 67 |
+
topic: str, session_id: str
|
| 68 |
+
) -> tuple[DocumentsBatch, MetadataBatch]:
|
| 69 |
"""Retrieve relevant documents from the database based on the provided topic.
|
| 70 |
Args:
|
| 71 |
topic (str): The topic for which to retrieve documents.
|
|
|
|
| 76 |
- list[dict]: List of metadata associated with the documents.
|
| 77 |
"""
|
| 78 |
# Get or create the database collection
|
| 79 |
+
db = chroma_client.get_or_create_collection(
|
| 80 |
+
name=session_id, embedding_function=embed_fn
|
| 81 |
+
)
|
| 82 |
if not db:
|
| 83 |
LOGGER.error("❌ Database collection not found or could not be created.")
|
| 84 |
return [], []
|
|
|
|
| 107 |
Args:
|
| 108 |
session_id (str): Unique identifier for the current session.
|
| 109 |
"""
|
| 110 |
+
db = chroma_client.get_or_create_collection(
|
| 111 |
+
name=session_id, embedding_function=embed_fn
|
| 112 |
+
)
|
| 113 |
if db:
|
| 114 |
chroma_client.delete_collection(name=session_id)
|
| 115 |
LOGGER.info("🗑️ Cleaning database for session ID: %s", session_id)
|
| 116 |
else:
|
| 117 |
+
LOGGER.warning(
|
| 118 |
+
"❌ Database collection not found for session ID: %s", session_id
|
| 119 |
+
)
|
src/generator.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
"""Module to put it all together and manage the generation of a presentation."""
|
| 2 |
|
|
|
|
|
|
|
| 3 |
from langfuse.decorators import langfuse_context, observe
|
| 4 |
|
| 5 |
from src.compilation import compile_presentation, json_to_tex
|
|
@@ -7,14 +9,25 @@ from src.compilation import compile_presentation, json_to_tex
|
|
| 7 |
# from datetime import datetime
|
| 8 |
from src.database import retrive_files_from_db
|
| 9 |
from src.processing import create_output_folder, find_used_gfx
|
| 10 |
-
from src.services import Presentation, build_prompt, client
|
| 11 |
from src.telemetry import Logger
|
| 12 |
|
| 13 |
LOGGER = Logger.get_logger()
|
| 14 |
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
@observe(name="🧑🎨 generate_presentation")
|
| 17 |
-
def generate_presentation(
|
| 18 |
"""Main function to generate a presentation based on the provided theme, color, and topic.
|
| 19 |
Args:
|
| 20 |
theme (str): The theme of the presentation, chosen by user via UI, defaults to "default".
|
|
@@ -28,25 +41,37 @@ def generate_presentation(theme, color, topic, session_id) -> tuple[str, str, st
|
|
| 28 |
- str: Trace ID for telemetry purposes.
|
| 29 |
- str: Path to the presentation folder.
|
| 30 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
trace_id = langfuse_context.get_current_trace_id()
|
| 33 |
|
| 34 |
-
[documents], [metadatas] = retrive_files_from_db(topic, session_id)
|
| 35 |
|
| 36 |
prompt = build_prompt(documents, metadatas)
|
| 37 |
|
| 38 |
work_dir = create_output_folder(session_id)
|
| 39 |
# Generate the presentation code
|
| 40 |
-
model_name =
|
| 41 |
LOGGER.info("⭐️ Generating response...")
|
| 42 |
-
answer = client.models.generate_content(
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
langfuse_context.update_current_observation(
|
| 51 |
output={
|
| 52 |
"model_name": model_name,
|
|
@@ -57,7 +82,9 @@ def generate_presentation(theme, color, topic, session_id) -> tuple[str, str, st
|
|
| 57 |
LOGGER.info("🎲 Generated the response using: %s", model_name)
|
| 58 |
|
| 59 |
find_used_gfx(answer, work_dir, metadatas)
|
| 60 |
-
latex_code = json_to_tex(
|
|
|
|
|
|
|
| 61 |
compilation_status = compile_presentation(latex_code, work_dir)
|
| 62 |
|
| 63 |
# delete_uploaded_files(uploaded_files)
|
|
|
|
| 1 |
"""Module to put it all together and manage the generation of a presentation."""
|
| 2 |
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
|
| 5 |
from langfuse.decorators import langfuse_context, observe
|
| 6 |
|
| 7 |
from src.compilation import compile_presentation, json_to_tex
|
|
|
|
| 9 |
# from datetime import datetime
|
| 10 |
from src.database import retrive_files_from_db
|
| 11 |
from src.processing import create_output_folder, find_used_gfx
|
| 12 |
+
from src.services import Presentation, build_prompt, client, generate_with_retry
|
| 13 |
from src.telemetry import Logger
|
| 14 |
|
| 15 |
LOGGER = Logger.get_logger()
|
| 16 |
|
| 17 |
|
| 18 |
+
@dataclass
|
| 19 |
+
class PresentationConfig:
|
| 20 |
+
"""Configuration for the presentation generation."""
|
| 21 |
+
|
| 22 |
+
model_name: str = "gemini-2.0-flash"
|
| 23 |
+
aspect_ratio: str = "16:9"
|
| 24 |
+
theme: str = "default"
|
| 25 |
+
color_theme: str = "default"
|
| 26 |
+
topic: str = ""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
@observe(name="🧑🎨 generate_presentation")
|
| 30 |
+
def generate_presentation(config_dict, session_id) -> tuple[str, str, str]:
|
| 31 |
"""Main function to generate a presentation based on the provided theme, color, and topic.
|
| 32 |
Args:
|
| 33 |
theme (str): The theme of the presentation, chosen by user via UI, defaults to "default".
|
|
|
|
| 41 |
- str: Trace ID for telemetry purposes.
|
| 42 |
- str: Path to the presentation folder.
|
| 43 |
"""
|
| 44 |
+
# Cast dict to dataclass
|
| 45 |
+
try:
|
| 46 |
+
config = PresentationConfig(**config_dict)
|
| 47 |
+
except TypeError as e:
|
| 48 |
+
# Handle missing or extra keys gracefully
|
| 49 |
+
return f"Config error: {str(e)}", None, None
|
| 50 |
|
| 51 |
trace_id = langfuse_context.get_current_trace_id()
|
| 52 |
|
| 53 |
+
[documents], [metadatas] = retrive_files_from_db(config.topic, session_id)
|
| 54 |
|
| 55 |
prompt = build_prompt(documents, metadatas)
|
| 56 |
|
| 57 |
work_dir = create_output_folder(session_id)
|
| 58 |
# Generate the presentation code
|
| 59 |
+
model_name = config.model_name
|
| 60 |
LOGGER.info("⭐️ Generating response...")
|
| 61 |
+
# answer = client.models.generate_content(
|
| 62 |
+
# model=model_name,
|
| 63 |
+
# contents=prompt,
|
| 64 |
+
# config={
|
| 65 |
+
# "response_mime_type": "application/json",
|
| 66 |
+
# "response_schema": Presentation,
|
| 67 |
+
# },
|
| 68 |
+
# )
|
| 69 |
+
try:
|
| 70 |
+
answer = generate_with_retry(client, model_name, prompt)
|
| 71 |
+
except Exception as e:
|
| 72 |
+
LOGGER.error("❌ Gemini is not reponding: %s", str(e))
|
| 73 |
+
return f"Gemini error: {str(e)}", trace_id, work_dir
|
| 74 |
+
|
| 75 |
langfuse_context.update_current_observation(
|
| 76 |
output={
|
| 77 |
"model_name": model_name,
|
|
|
|
| 82 |
LOGGER.info("🎲 Generated the response using: %s", model_name)
|
| 83 |
|
| 84 |
find_used_gfx(answer, work_dir, metadatas)
|
| 85 |
+
latex_code = json_to_tex(
|
| 86 |
+
answer.text, config.theme, config.color_theme, config.aspect_ratio
|
| 87 |
+
)
|
| 88 |
compilation_status = compile_presentation(latex_code, work_dir)
|
| 89 |
|
| 90 |
# delete_uploaded_files(uploaded_files)
|
src/interface/__init__.py
CHANGED
|
@@ -1,7 +1,15 @@
|
|
| 1 |
"""This module initializes the UI package."""
|
| 2 |
|
| 3 |
from .gradio_interface import demo
|
| 4 |
-
from .manage_files import
|
| 5 |
-
from .session_manager import
|
| 6 |
|
| 7 |
-
__all__ = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""This module initializes the UI package."""
|
| 2 |
|
| 3 |
from .gradio_interface import demo
|
| 4 |
+
from .manage_files import delete_files, download_files, upload_files
|
| 5 |
+
from .session_manager import check_session_status, create_session, with_update_session
|
| 6 |
|
| 7 |
+
__all__ = [
|
| 8 |
+
"demo",
|
| 9 |
+
"upload_files",
|
| 10 |
+
"download_files",
|
| 11 |
+
"delete_files",
|
| 12 |
+
"create_session",
|
| 13 |
+
"with_update_session",
|
| 14 |
+
"check_session_status",
|
| 15 |
+
]
|
src/interface/gradio_interface.py
CHANGED
|
@@ -7,13 +7,32 @@ import gradio as gr
|
|
| 7 |
|
| 8 |
from ..generator import generate_presentation
|
| 9 |
from ..telemetry import submit_feedback
|
| 10 |
-
from .manage_files import
|
| 11 |
-
from .session_manager import
|
|
|
|
| 12 |
|
| 13 |
SESSION_TIMEOUT = 900
|
| 14 |
|
| 15 |
|
| 16 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""Helper function to handle uploaded documents and update the list of uploaded files.
|
| 18 |
Args:
|
| 19 |
files (list): List of file-like objects to be uploaded.
|
|
@@ -64,6 +83,7 @@ def encode_image(image_path) -> str:
|
|
| 64 |
data = f.read()
|
| 65 |
return f"data:image/png;base64,{base64.b64encode(data).decode()}"
|
| 66 |
|
|
|
|
| 67 |
banner_base64 = encode_image("gfx/long_logo.png")
|
| 68 |
logo_base64 = encode_image("gfx/icon_logo.png")
|
| 69 |
github_base64 = encode_image("gfx/github-mark-white.png")
|
|
@@ -248,7 +268,33 @@ with gr.Blocks(theme=theme, js=JS_FUNC) as demo:
|
|
| 248 |
)
|
| 249 |
upload_button = gr.Button("Upload Files", variant="primary")
|
| 250 |
|
| 251 |
-
gr.Markdown("## 🎨 Step 2: Choose the
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
presentation_theme_state = gr.State("default")
|
| 253 |
theme_dropdown = gr.Dropdown(
|
| 254 |
choices=[
|
|
@@ -285,10 +331,16 @@ with gr.Blocks(theme=theme, js=JS_FUNC) as demo:
|
|
| 285 |
)
|
| 286 |
# output = gr.Textbox()
|
| 287 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
theme_dropdown.change(
|
| 289 |
-
fn=lambda
|
| 290 |
-
inputs=theme_dropdown,
|
| 291 |
-
outputs=
|
| 292 |
)
|
| 293 |
color_theme_state = gr.State("default")
|
| 294 |
color_dropdown = gr.Dropdown(
|
|
@@ -313,10 +365,16 @@ with gr.Blocks(theme=theme, js=JS_FUNC) as demo:
|
|
| 313 |
label="Choose a color theme",
|
| 314 |
)
|
| 315 |
# output = gr.Textbox()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
color_dropdown.change(
|
| 317 |
-
fn=lambda
|
| 318 |
-
inputs=color_dropdown,
|
| 319 |
-
outputs=
|
| 320 |
)
|
| 321 |
|
| 322 |
gr.Markdown("## 🧠 Step 3: Enter Presentation Topic")
|
|
@@ -325,6 +383,11 @@ with gr.Blocks(theme=theme, js=JS_FUNC) as demo:
|
|
| 325 |
placeholder="e.g., Introduction to Quantum Computing",
|
| 326 |
lines=1,
|
| 327 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
submit_topic_button = gr.Button("Generate Presentation", variant="primary")
|
| 329 |
|
| 330 |
with gr.Column(scale=1):
|
|
@@ -415,10 +478,7 @@ with gr.Blocks(theme=theme, js=JS_FUNC) as demo:
|
|
| 415 |
|
| 416 |
upload_button.click(
|
| 417 |
fn=with_update_session(upload_and_update_list),
|
| 418 |
-
inputs=[
|
| 419 |
-
file_input,
|
| 420 |
-
uploaded_files_state,
|
| 421 |
-
session_id],
|
| 422 |
outputs=[upload_output, uploaded_files_state],
|
| 423 |
)
|
| 424 |
|
|
@@ -426,9 +486,7 @@ with gr.Blocks(theme=theme, js=JS_FUNC) as demo:
|
|
| 426 |
submit_topic_button.click(
|
| 427 |
fn=with_update_session(generate_presentation),
|
| 428 |
inputs=[
|
| 429 |
-
|
| 430 |
-
color_theme_state,
|
| 431 |
-
topic_input,
|
| 432 |
session_id,
|
| 433 |
],
|
| 434 |
outputs=[compilation_status, trace_id_state, presentation_folder_state],
|
|
|
|
| 7 |
|
| 8 |
from ..generator import generate_presentation
|
| 9 |
from ..telemetry import submit_feedback
|
| 10 |
+
from .manage_files import download_files, upload_files
|
| 11 |
+
from .session_manager import (check_session_status, create_session,
|
| 12 |
+
with_update_session)
|
| 13 |
|
| 14 |
SESSION_TIMEOUT = 900
|
| 15 |
|
| 16 |
|
| 17 |
+
def update_config(key, value, config) -> dict:
|
| 18 |
+
"""Helper function to update configuration settings.
|
| 19 |
+
These settings will be later used for generate_presentation function.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
key (str): Configuration key to update.
|
| 23 |
+
value (str): New value for the configuration key.
|
| 24 |
+
config (dict): Current configuration dictionary.
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
dict: Updated configuration dictionary with the new key-value pair.
|
| 28 |
+
"""
|
| 29 |
+
config[key] = value
|
| 30 |
+
return config
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def upload_and_update_list(
|
| 34 |
+
files: list, uploaded_list, session_id
|
| 35 |
+
) -> tuple[str, list[str]]:
|
| 36 |
"""Helper function to handle uploaded documents and update the list of uploaded files.
|
| 37 |
Args:
|
| 38 |
files (list): List of file-like objects to be uploaded.
|
|
|
|
| 83 |
data = f.read()
|
| 84 |
return f"data:image/png;base64,{base64.b64encode(data).decode()}"
|
| 85 |
|
| 86 |
+
|
| 87 |
banner_base64 = encode_image("gfx/long_logo.png")
|
| 88 |
logo_base64 = encode_image("gfx/icon_logo.png")
|
| 89 |
github_base64 = encode_image("gfx/github-mark-white.png")
|
|
|
|
| 268 |
)
|
| 269 |
upload_button = gr.Button("Upload Files", variant="primary")
|
| 270 |
|
| 271 |
+
gr.Markdown("## 🎨 Step 2: Choose the parameters")
|
| 272 |
+
config_state = gr.State({})
|
| 273 |
+
model_state = gr.State("default")
|
| 274 |
+
model_radio = gr.Radio(
|
| 275 |
+
["gemini-2.0-flash", "gemini-2.5-flash-preview-05-20"],
|
| 276 |
+
label="LLM",
|
| 277 |
+
info="Choose Gemini version",
|
| 278 |
+
value="gemini-2.0-flash",
|
| 279 |
+
)
|
| 280 |
+
model_radio.change(
|
| 281 |
+
fn=lambda value, config: update_config("model_name", value, config),
|
| 282 |
+
inputs=[model_radio, config_state], # only real components here
|
| 283 |
+
outputs=config_state,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
aspect_ratio_radio = gr.Radio(
|
| 287 |
+
["16:9", "4:3"],
|
| 288 |
+
label="Aspect Ratio",
|
| 289 |
+
info="Choose presentation aspect ratio",
|
| 290 |
+
value="16:9",
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
aspect_ratio_radio.change(
|
| 294 |
+
fn=lambda value, config: update_config("aspect_ratio", value, config),
|
| 295 |
+
inputs=[aspect_ratio_radio, config_state], # only real components here
|
| 296 |
+
outputs=config_state,
|
| 297 |
+
)
|
| 298 |
presentation_theme_state = gr.State("default")
|
| 299 |
theme_dropdown = gr.Dropdown(
|
| 300 |
choices=[
|
|
|
|
| 331 |
)
|
| 332 |
# output = gr.Textbox()
|
| 333 |
|
| 334 |
+
# theme_dropdown.change(
|
| 335 |
+
# fn=lambda val: val,
|
| 336 |
+
# inputs=theme_dropdown,
|
| 337 |
+
# outputs=presentation_theme_state,
|
| 338 |
+
# )
|
| 339 |
+
|
| 340 |
theme_dropdown.change(
|
| 341 |
+
fn=lambda value, config: update_config("theme", value, config),
|
| 342 |
+
inputs=[theme_dropdown, config_state], # only real components here
|
| 343 |
+
outputs=config_state,
|
| 344 |
)
|
| 345 |
color_theme_state = gr.State("default")
|
| 346 |
color_dropdown = gr.Dropdown(
|
|
|
|
| 365 |
label="Choose a color theme",
|
| 366 |
)
|
| 367 |
# output = gr.Textbox()
|
| 368 |
+
# color_dropdown.change(
|
| 369 |
+
# fn=lambda val: val,
|
| 370 |
+
# inputs=color_dropdown,
|
| 371 |
+
# outputs=color_theme_state,
|
| 372 |
+
# )
|
| 373 |
+
|
| 374 |
color_dropdown.change(
|
| 375 |
+
fn=lambda value, config: update_config("color_theme", value, config),
|
| 376 |
+
inputs=[color_dropdown, config_state], # only real components here
|
| 377 |
+
outputs=config_state,
|
| 378 |
)
|
| 379 |
|
| 380 |
gr.Markdown("## 🧠 Step 3: Enter Presentation Topic")
|
|
|
|
| 383 |
placeholder="e.g., Introduction to Quantum Computing",
|
| 384 |
lines=1,
|
| 385 |
)
|
| 386 |
+
topic_input.change(
|
| 387 |
+
fn=lambda value, config: update_config("topic", value, config),
|
| 388 |
+
inputs=[topic_input, config_state], # only real components here
|
| 389 |
+
outputs=config_state,
|
| 390 |
+
)
|
| 391 |
submit_topic_button = gr.Button("Generate Presentation", variant="primary")
|
| 392 |
|
| 393 |
with gr.Column(scale=1):
|
|
|
|
| 478 |
|
| 479 |
upload_button.click(
|
| 480 |
fn=with_update_session(upload_and_update_list),
|
| 481 |
+
inputs=[file_input, uploaded_files_state, session_id],
|
|
|
|
|
|
|
|
|
|
| 482 |
outputs=[upload_output, uploaded_files_state],
|
| 483 |
)
|
| 484 |
|
|
|
|
| 486 |
submit_topic_button.click(
|
| 487 |
fn=with_update_session(generate_presentation),
|
| 488 |
inputs=[
|
| 489 |
+
config_state,
|
|
|
|
|
|
|
| 490 |
session_id,
|
| 491 |
],
|
| 492 |
outputs=[compilation_status, trace_id_state, presentation_folder_state],
|
src/interface/session_manager.py
CHANGED
|
@@ -1,13 +1,14 @@
|
|
| 1 |
"""Session Manager Module"""
|
| 2 |
|
| 3 |
-
import uuid
|
| 4 |
-
import time
|
| 5 |
import threading
|
| 6 |
-
|
|
|
|
| 7 |
from functools import wraps
|
|
|
|
|
|
|
|
|
|
| 8 |
from ..telemetry.logging_utils import Logger
|
| 9 |
from .manage_files import delete_files
|
| 10 |
-
from ..database import clean_db
|
| 11 |
|
| 12 |
LOGGER = Logger.get_logger()
|
| 13 |
|
|
@@ -109,4 +110,14 @@ def with_update_session(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
| 109 |
|
| 110 |
|
| 111 |
def check_session_status(session_id: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
return "active" if session_id in session_data else "expired"
|
|
|
|
| 1 |
"""Session Manager Module"""
|
| 2 |
|
|
|
|
|
|
|
| 3 |
import threading
|
| 4 |
+
import time
|
| 5 |
+
import uuid
|
| 6 |
from functools import wraps
|
| 7 |
+
from typing import Any, Callable
|
| 8 |
+
|
| 9 |
+
from ..database import clean_db
|
| 10 |
from ..telemetry.logging_utils import Logger
|
| 11 |
from .manage_files import delete_files
|
|
|
|
| 12 |
|
| 13 |
LOGGER = Logger.get_logger()
|
| 14 |
|
|
|
|
| 110 |
|
| 111 |
|
| 112 |
def check_session_status(session_id: str) -> str:
|
| 113 |
+
"""Check if a session is active or expired.
|
| 114 |
+
This function checks if the provided session ID exists in the session data.
|
| 115 |
+
If it exists, the session is considered active; otherwise, it is expired.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
session_id (str): The ID of the session to check.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
str: "active" if the session is active, "expired" if it is not.
|
| 122 |
+
"""
|
| 123 |
return "active" if session_id in session_data else "expired"
|
src/services/__init__.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""This module initializes the services package."""
|
| 2 |
|
| 3 |
-
from .google_client import client
|
| 4 |
from .output_schema import Presentation
|
| 5 |
from .prompt import build_prompt
|
| 6 |
|
| 7 |
-
__all__ = ["client", "build_prompt", "Presentation"]
|
|
|
|
| 1 |
"""This module initializes the services package."""
|
| 2 |
|
| 3 |
+
from .google_client import client, generate_with_retry
|
| 4 |
from .output_schema import Presentation
|
| 5 |
from .prompt import build_prompt
|
| 6 |
|
| 7 |
+
__all__ = ["client", "build_prompt", "Presentation", "generate_with_retry"]
|
src/services/google_client.py
CHANGED
|
@@ -1,10 +1,50 @@
|
|
| 1 |
"""Initialize and export a GenAI client using the provided Google API key."""
|
| 2 |
|
| 3 |
import os
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
from google import genai
|
| 7 |
|
|
|
|
|
|
|
| 8 |
load_dotenv()
|
| 9 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 10 |
client = genai.Client(api_key=GOOGLE_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""Initialize and export a GenAI client using the provided Google API key."""
|
| 2 |
|
| 3 |
import os
|
| 4 |
+
import time
|
| 5 |
+
import httpx
|
| 6 |
+
from google.api_core.exceptions import GoogleAPIError
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
from google import genai
|
| 9 |
|
| 10 |
+
from .output_schema import Presentation
|
| 11 |
+
|
| 12 |
load_dotenv()
|
| 13 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 14 |
client = genai.Client(api_key=GOOGLE_API_KEY)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def generate_with_retry(client, model_name, prompt, max_retries=3, retry_delay=2):
|
| 18 |
+
|
| 19 |
+
answer = None
|
| 20 |
+
|
| 21 |
+
for attempt in range(1, max_retries + 1):
|
| 22 |
+
try:
|
| 23 |
+
answer = client.models.generate_content(
|
| 24 |
+
model=model_name,
|
| 25 |
+
contents=prompt,
|
| 26 |
+
config={
|
| 27 |
+
"response_mime_type": "application/json",
|
| 28 |
+
"response_schema": Presentation,
|
| 29 |
+
},
|
| 30 |
+
)
|
| 31 |
+
return answer
|
| 32 |
+
|
| 33 |
+
except httpx.RemoteProtocolError as e:
|
| 34 |
+
print(f"[Attempt {attempt}] Server disconnected: {e}")
|
| 35 |
+
if attempt < max_retries:
|
| 36 |
+
time.sleep(retry_delay)
|
| 37 |
+
else:
|
| 38 |
+
raise # re-raise if out of retries
|
| 39 |
+
|
| 40 |
+
except httpx.HTTPError as e:
|
| 41 |
+
print(f"[Attempt {attempt}] HTTP error: {e}")
|
| 42 |
+
raise # you might not want to retry on all HTTP errors
|
| 43 |
+
|
| 44 |
+
except GoogleAPIError as e:
|
| 45 |
+
print(f"Google API error: {e}")
|
| 46 |
+
raise
|
| 47 |
+
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"Unexpected error: {e}")
|
| 50 |
+
raise
|
src/services/output_schema.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""This module defines the output schema for the LLM output."""
|
| 2 |
|
| 3 |
-
from typing import
|
|
|
|
| 4 |
from pydantic import BaseModel, Field
|
| 5 |
|
| 6 |
|
|
|
|
| 1 |
"""This module defines the output schema for the LLM output."""
|
| 2 |
|
| 3 |
+
from typing import List, Literal, Optional
|
| 4 |
+
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
|
| 7 |
|
src/services/prompt.py
CHANGED
|
@@ -163,7 +163,7 @@ You must output only a **valid JSON object** with the following fields:
|
|
| 163 |
- "single_image"
|
| 164 |
- "image": Optional object, **required only if layout is "two_column" or "single_image"**, with:
|
| 165 |
- "path": Exact image path from a predefined list.
|
| 166 |
-
- "caption": Image caption text. If "None", do not use the image.
|
| 167 |
- "orientation": One of "horizontal", "vertical", or "square". Take it from the image metadata.
|
| 168 |
|
| 169 |
**Rules:**
|
|
@@ -172,6 +172,7 @@ You must output only a **valid JSON object** with the following fields:
|
|
| 172 |
- Include 2–4 "core_idea" slides.
|
| 173 |
- Use **at least one image**.
|
| 174 |
- Include images in **at least half of the core idea slides**.
|
|
|
|
| 175 |
- Use:
|
| 176 |
- "two_column" layout for **vertical** or **square** images.
|
| 177 |
- "single_image" layout for **horizontal** images.
|
|
|
|
| 163 |
- "single_image"
|
| 164 |
- "image": Optional object, **required only if layout is "two_column" or "single_image"**, with:
|
| 165 |
- "path": Exact image path from a predefined list.
|
| 166 |
+
- "caption": Image caption text. Summarize it in one consize sentence. If "None", do not use the image.
|
| 167 |
- "orientation": One of "horizontal", "vertical", or "square". Take it from the image metadata.
|
| 168 |
|
| 169 |
**Rules:**
|
|
|
|
| 172 |
- Include 2–4 "core_idea" slides.
|
| 173 |
- Use **at least one image**.
|
| 174 |
- Include images in **at least half of the core idea slides**.
|
| 175 |
+
- Each and every bullet point or phrase must be valid, clear, and easy to understand.
|
| 176 |
- Use:
|
| 177 |
- "two_column" layout for **vertical** or **square** images.
|
| 178 |
- "single_image" layout for **horizontal** images.
|