eranmi commited on
Commit
015f1eb
Β·
1 Parent(s): 3471d91

gradio working prototype

Browse files
ragntex.py CHANGED
@@ -1,128 +1,3 @@
1
- import os
2
- import re
3
- from datetime import datetime
4
- from dotenv import load_dotenv
5
-
6
- from src import (
7
- db,
8
- embed_fn,
9
- process_documents,
10
- save_pdf_images,
11
- save_pdf_figures,
12
- prompt,
13
- CompilePresentation,
14
- client,
15
- demo,
16
- Logger,
17
- )
18
-
19
- LOGGER = Logger.get_logger()
20
 
21
  demo.launch()
22
- load_dotenv()
23
- MAIN_DIR = os.getenv("MAIN_DIR")
24
-
25
- # # Get all the existing papers in the database
26
- # all_entries = db.get(include=["metadatas"])
27
- # existing_pdfs = [meta.get("source_pdf") for meta in all_entries["metadatas"]]
28
-
29
- # # Dataset
30
- # dataset = MAIN_DIR + "dataset/"
31
- # files = os.listdir(dataset)
32
-
33
- # LOGGER.info("Looking for new PDFs to append to our database...")
34
- # # Look for new PDFs to append to our database
35
- # pdf_files = [
36
- # os.path.join(dataset, f)
37
- # for f in files
38
- # if f.lower().endswith(".pdf") and f not in existing_pdfs
39
- # ]
40
-
41
- # documents, metadatas = process_documents(pdf_files)
42
- # LOGGER.info("Adding new PDFs to the database...")
43
- # # Fill in the database
44
- # if documents:
45
- # db.add(
46
- # documents=documents,
47
- # ids=[str(i) for i in range(len(documents))],
48
- # metadatas=metadatas,
49
- # )
50
-
51
- # Prompting
52
- # LOGGER.info("Retrieving relevant documents...")
53
- # embed_fn.document_mode = False
54
- # query = "I need an interesting presentation."
55
- # query_oneline = query.replace(
56
- # "\n", " "
57
- # ) # (Optional) For cleaner input in case of newlines
58
- # result = db.query(query_texts=[query], n_results=2)
59
- # [documents] = result["documents"]
60
- # [metadatas] = result["metadatas"]
61
-
62
-
63
- # for passage, metas in zip(documents, metadatas):
64
- # passage_oneline = passage.replace("\n", " ")
65
- # images_passage = metas["images_passage"]
66
-
67
- # prompt += f"PASSAGE: {passage_oneline}\n"
68
- # prompt += f"IMAGES: {images_passage}\n"
69
-
70
- # Create a new subfolder
71
- # LOGGER.info("πŸ’Ύ Creating new subfolder...")
72
- # base_path = MAIN_DIR + "output/"
73
- # timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
74
- # work_dir = os.path.join(base_path, timestamp)
75
- # os.makedirs(work_dir, exist_ok=False)
76
- # LOGGER.info("πŸ“ Created folder: %s", work_dir)
77
-
78
- # # Generate the presentation code
79
- # model_name = "gemini-2.0-flash"
80
- # # model_name = "gemini-2.5-flash-preview-04-17"
81
- # LOGGER.info("⭐️ Generating response...")
82
- # answer = client.models.generate_content(model=model_name, contents=prompt)
83
- # LOGGER.info("🎲 Generated the response using: %s", model_name)
84
-
85
- # # Create a subfolder for graphics
86
- # graphics_dir = os.path.join(work_dir, "gfx")
87
- # os.makedirs(graphics_dir, exist_ok=True)
88
- # LOGGER.info("πŸŒ„ Images will be saved to: %s", graphics_dir)
89
-
90
- # # Find images, which are used in the presentation
91
- # pattern_img = re.compile(
92
- # r"doc(?P<doc>[a-zA-Z0-9_]+)_page(?P<page>\d+)_img(?P<img>\d+)_hash(?P<hash>[a-fA-F0-9]{8})\.png"
93
- # )
94
- # matches_img = pattern_img.finditer(answer.text)
95
-
96
- # req_imgs = []
97
- # for match in matches_img:
98
- # req_img = {
99
- # "doc": match.group("doc"),
100
- # "page": int(match.group("page")),
101
- # "img": int(match.group("img")),
102
- # "hash": match.group("hash"),
103
- # }
104
- # req_imgs.append(req_img)
105
-
106
- # # Find figures, which are used in the presentation
107
- # pattern_fig = re.compile(
108
- # r"doc(?P<doc>[a-zA-Z0-9_]+)_page(?P<page>\d+)_fig(?P<fig>\d+)_hash(?P<hash>[a-fA-F0-9]{8})\.png"
109
- # )
110
- # matches_fig = pattern_fig.finditer(answer.text)
111
-
112
- # req_figs = []
113
- # for match in matches_fig:
114
- # req_fig = {
115
- # "doc": match.group("doc"),
116
- # "page": int(match.group("page")),
117
- # "fig": int(match.group("fig")),
118
- # "hash": match.group("hash"),
119
- # }
120
- # req_figs.append(req_fig)
121
-
122
- # # Save the required graphics
123
- # for metadata in metadatas:
124
- # save_pdf_images(metadata["pdf_path"], req_imgs, graphics_dir)
125
- # save_pdf_figures(metadata["pdf_path"], req_figs, graphics_dir)
126
-
127
- # LOGGER.info("Compiling presentation...")
128
- # CompilePresentation(answer.text, work_dir)
 
1
+ from src import demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/__init__.py CHANGED
@@ -1,21 +1,22 @@
1
- from .database import db, embed_fn
2
- from .processing import process_documents, save_pdf_images, save_pdf_figures, prompt
3
- from .compilation import CompilePresentation
4
- from .services import client
5
- from .utils import upload_files, Logger
6
 
7
  from .interface import demo
8
 
9
  __all__ = [
10
- "db",
11
- "embed_fn",
12
- "process_documents",
13
- "save_pdf_images",
14
- "save_pdf_figures",
15
- "prompt",
16
- "CompilePresentation",
17
- "client",
18
- "upload_files",
19
- "Logger",
20
  "demo",
 
21
  ]
 
1
+ # from .database import db, embed_fn
2
+ # from .processing import process_documents, save_pdf_images, save_pdf_figures, get_prompt
3
+ # from .compilation import CompilePresentation
4
+ # from .services import client, generate_presentation
5
+ # from .utils import upload_files, Logger
6
 
7
  from .interface import demo
8
 
9
  __all__ = [
10
+ # "db",
11
+ # "embed_fn",
12
+ # "process_documents",
13
+ # "save_pdf_images",
14
+ # "save_pdf_figures",
15
+ # "get_prompt",
16
+ # "CompilePresentation",
17
+ # "client",
18
+ # "upload_files",
19
+ # "Logger",
20
  "demo",
21
+ # "generate_presentation",
22
  ]
src/compilation/latex_compilation.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import subprocess
3
  from ..utils import Logger
@@ -18,7 +19,7 @@ def CompilePresentation(latex_code, work_dir):
18
  f.write(latex_code)
19
 
20
  LOGGER.info("=" * 100)
21
- LOGGER.info("πŸ“„ Files in the directory:")
22
 
23
  # List files in the directory using Python (instead of `!ls`)
24
  for file in os.listdir(work_dir):
 
1
+ # compilation/latex_compilation.py
2
  import os
3
  import subprocess
4
  from ..utils import Logger
 
19
  f.write(latex_code)
20
 
21
  LOGGER.info("=" * 100)
22
+ LOGGER.info("πŸ“„ Files in the directory: %s", work_dir)
23
 
24
  # List files in the directory using Python (instead of `!ls`)
25
  for file in os.listdir(work_dir):
src/database/__init__.py CHANGED
@@ -1,3 +1,4 @@
1
  from .database import db, embed_fn
 
2
 
3
- __all__ = ["db", "embed_fn"]
 
1
  from .database import db, embed_fn
2
+ from .ingest import ingest_files_to_db
3
 
4
+ __all__ = ["db", "embed_fn", "ingest_files_to_db"]
src/database/database.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from google.api_core import retry
2
  from google.genai import types
3
  from google import genai
 
1
+ # database/database.py
2
  from google.api_core import retry
3
  from google.genai import types
4
  from google import genai
src/database/ingest.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # database/ingest.py
2
+ from pathlib import Path
3
+ from .database import db
4
+ from ..utils import Logger
5
+ from ..processing import process_documents
6
+
7
+ LOGGER = Logger.get_logger()
8
+
9
+
10
+ def ingest_files_to_db(pdf_files) -> None:
11
+ """Add new files to the database if they are not yet there.
12
+ Args:
13
+ pdf_files (list): List of PDF files to be ingested.
14
+ """
15
+ print("pdf_files", pdf_files)
16
+ # Get all the existing entries and extract the known filenames
17
+ all_entries = db.get(include=["metadatas"])
18
+ existing_pdfs = set(
19
+ meta.get("source_pdf")
20
+ for meta in all_entries["metadatas"]
21
+ if meta.get("source_pdf")
22
+ )
23
+
24
+ # Filter out already ingested PDFs
25
+ new_pdfs = [file for file in pdf_files if Path(file).name not in existing_pdfs]
26
+
27
+ if not new_pdfs:
28
+ LOGGER.info("No new PDFs to ingest. Skipping ingestion.")
29
+ return
30
+
31
+ # Process new files only
32
+ documents, metadatas = process_documents(new_pdfs)
33
+
34
+ LOGGER.info(f"Adding {len(new_pdfs)} new PDFs to the database...")
35
+ if documents:
36
+ db.add(
37
+ documents=documents,
38
+ ids=[str(i) for i in range(len(documents))],
39
+ metadatas=metadatas,
40
+ )
41
+ LOGGER.info("Documents ingested successfully.")
src/interface/gradio_interface.py CHANGED
@@ -1,17 +1,23 @@
 
 
1
  import gradio as gr
2
- from ..utils import (
3
- upload_files,
4
- process_presentation_topic,
5
- process_presentation_style,
6
- process_color_style,
7
- )
8
 
9
 
10
  def upload_and_update_list(files, uploaded_list):
11
- status = upload_files(files)
12
- new_files = [file.name for file in files if file.name not in uploaded_list]
13
- updated_list = uploaded_list + new_files
14
- return status, updated_list, "\n".join(updated_list)
 
 
 
 
 
 
 
 
15
 
16
 
17
  with gr.Blocks() as demo:
@@ -28,7 +34,8 @@ with gr.Blocks() as demo:
28
  upload_button = gr.Button("Upload Files")
29
 
30
  gr.Markdown("## 🎨 Step 2: Choose the presentation and color themes")
31
- dropdown = gr.Dropdown(
 
32
  choices=[
33
  "default",
34
  "Darmstadt",
@@ -61,11 +68,15 @@ with gr.Blocks() as demo:
61
  value="default", # default option
62
  label="Choose a presentation theme",
63
  )
64
- output = gr.Textbox()
65
- dropdown.change(
66
- fn=process_presentation_style, inputs=dropdown, outputs=output
 
 
 
67
  )
68
- dropdown = gr.Dropdown(
 
69
  choices=[
70
  "default",
71
  "albatross",
@@ -86,8 +97,12 @@ with gr.Blocks() as demo:
86
  value="default", # default option
87
  label="Choose a color theme",
88
  )
89
- output = gr.Textbox()
90
- dropdown.change(fn=process_color_style, inputs=dropdown, outputs=output)
 
 
 
 
91
 
92
  gr.Markdown("## 🧠 Step 3: Enter Presentation Topic")
93
  topic_input = gr.Textbox(
@@ -106,12 +121,29 @@ with gr.Blocks() as demo:
106
  gr.Markdown("## πŸ“ Outline or Confirmation")
107
  topic_output = gr.Textbox(label="Topic Output", lines=6, interactive=False)
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  upload_button.click(
110
  fn=upload_and_update_list,
111
  inputs=[file_input, uploaded_files_state],
112
  outputs=[upload_output, uploaded_files_state],
113
  )
114
 
115
- submit_topic_button.click(
116
- fn=process_presentation_topic, inputs=[topic_input], outputs=[topic_output]
 
 
117
  )
 
1
+ # interface/gradio_interface.py
2
+
3
  import gradio as gr
4
+ from ..utils import upload_files
5
+ from ..services import generate_presentation
 
 
 
 
6
 
7
 
8
  def upload_and_update_list(files, uploaded_list):
9
+ status, new_paths = upload_files(files)
10
+ updated_list = uploaded_list + [p for p in new_paths if p not in uploaded_list]
11
+ # file_list_display = "\n".join(file.name for file in updated_list)
12
+ return status, updated_list # , file_list_display
13
+
14
+
15
+ def generate_iframe(file_path):
16
+ if not file_path:
17
+ return ""
18
+ return (
19
+ f'<embed src="{file_path}" type="application/pdf" width="100%" height="600px">'
20
+ )
21
 
22
 
23
  with gr.Blocks() as demo:
 
34
  upload_button = gr.Button("Upload Files")
35
 
36
  gr.Markdown("## 🎨 Step 2: Choose the presentation and color themes")
37
+ presentation_theme_state = gr.State("default")
38
+ theme_dropdown = gr.Dropdown(
39
  choices=[
40
  "default",
41
  "Darmstadt",
 
68
  value="default", # default option
69
  label="Choose a presentation theme",
70
  )
71
+ # output = gr.Textbox()
72
+
73
+ theme_dropdown.change(
74
+ fn=lambda val: val,
75
+ inputs=theme_dropdown,
76
+ outputs=presentation_theme_state,
77
  )
78
+ color_theme_state = gr.State("default")
79
+ color_dropdown = gr.Dropdown(
80
  choices=[
81
  "default",
82
  "albatross",
 
97
  value="default", # default option
98
  label="Choose a color theme",
99
  )
100
+ # output = gr.Textbox()
101
+ color_dropdown.change(
102
+ fn=lambda val: val,
103
+ inputs=color_dropdown,
104
+ outputs=color_theme_state,
105
+ )
106
 
107
  gr.Markdown("## 🧠 Step 3: Enter Presentation Topic")
108
  topic_input = gr.Textbox(
 
121
  gr.Markdown("## πŸ“ Outline or Confirmation")
122
  topic_output = gr.Textbox(label="Topic Output", lines=6, interactive=False)
123
 
124
+ gr.Markdown("## πŸŽ‰ Final Presentation")
125
+ pdf_output = gr.File(label="Download/View Presentation")
126
+ pdf_output_viewer = gr.HTML(label="Presentation Preview")
127
+
128
+ submit_topic_button.click(
129
+ fn=generate_presentation,
130
+ inputs=[
131
+ presentation_theme_state,
132
+ color_theme_state,
133
+ topic_input,
134
+ uploaded_files_state,
135
+ ],
136
+ outputs=[topic_output, pdf_output, pdf_output_viewer],
137
+ )
138
+
139
  upload_button.click(
140
  fn=upload_and_update_list,
141
  inputs=[file_input, uploaded_files_state],
142
  outputs=[upload_output, uploaded_files_state],
143
  )
144
 
145
+ pdf_output.change(
146
+ fn=generate_iframe,
147
+ inputs=pdf_output,
148
+ outputs=pdf_output_viewer,
149
  )
src/processing/__init__.py CHANGED
@@ -1,5 +1,5 @@
1
  from .document_processing import process_documents
2
  from .images_processing import save_pdf_images, save_pdf_figures
3
- from .prompt import prompt
4
 
5
- __all__ = ["process_documents", "save_pdf_images", "save_pdf_figures", "prompt"]
 
1
  from .document_processing import process_documents
2
  from .images_processing import save_pdf_images, save_pdf_figures
3
+ from .prompt import get_prompt
4
 
5
+ __all__ = ["process_documents", "save_pdf_images", "save_pdf_figures", "get_prompt"]
src/processing/document_processing.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import re
2
  import fitz
3
  import os
 
1
+ # processing/document_processing.py
2
  import re
3
  import fitz
4
  import os
src/processing/images_processing.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import fitz
2
  import re
3
  import os
 
1
+ # processing/images_processing.py
2
  import fitz
3
  import re
4
  import os
src/processing/prompt.py CHANGED
@@ -1,100 +1,110 @@
1
- prompt = r"""You are a presentation assistant that creates clear, concise, and engaging slide decks from the reference material provided. You extract the most relevant and important information, organize it logically, and generate LaTeX code for a presentation using the Beamer class.
2
-
3
- Structure your slides as follows:
4
- 1. **Introduction**: Present the topic and explain why it's important or interesting.
5
- 2. **Main Content**: Break down the topic into 2–4 core ideas, one idea per slide. Explain each with clear language, bullet points, or short sentences.
6
- 3. **Summary**: Recap the key takeaways, what was learned, and what it means for the audience.
7
-
8
- Use friendly and accessible language that anyone can understand. Avoid technical jargon unless it's essentialβ€”and when you use it, explain it simply.
9
-
10
- Output only valid LaTeX Beamer code. Each slide must be defined using \begin{frame} ... \end{frame}.
11
-
12
- Here is some reference content retrieved from a document. Please generate a LaTeX Beamer presentation based on the content, following this structure:
13
-
14
- 1. Introduction (what is the topic and why it matters)
15
- 2. Main Part (a few slides on the core ideas)
16
- 3. Summary (what was learned, 2–3 key takeaways)
17
-
18
- Please output valid LaTeX code only, like this format:
19
-
20
- \documentclass{beamer}
21
- \usetheme{Madrid}
22
-
23
- \title{[Presentation Title]}
24
- \author{AI-generated}
25
- \date{\today}
26
-
27
- \begin{document}
28
-
29
- \frame{\titlepage}
30
-
31
- \begin{frame}
32
- \frametitle{Introduction}
33
- \begin{itemize}
34
- \item What's the topic?
35
- \item Why is it important?
36
- \end{itemize}
37
- \end{frame}
38
-
39
- \begin{frame}
40
- \frametitle{Core Idea 1}
41
- \begin{itemize}
42
- \item Key point 1
43
- \item Key point 2
44
- \end{itemize}
45
- \end{frame}
46
-
47
- \begin{frame}
48
- \frametitle{Core Idea 2}
49
- \begin{columns}
50
- \begin{column}{0.5\linewidth}
51
- \begin{itemize}
52
- \item Key point 1
53
- \item Key point 2
54
- \end{itemize}
55
- \end{column}
56
- \begin{column}{0.5\linewidth}
57
- \center{\includegraphics[height=1.0\textheight, width=1.0\textwidth, keepaspectratio]{gfx/image} \\ image caption}
58
- \end{column}
59
- \end{columns}
60
- \end{frame}
61
-
62
- \begin{frame}
63
- \frametitle{Core Idea 3}
64
- \center{\includegraphics[height=0.5\textheight, width=0.8\textwidth, keepaspectratio]{gfx/image} \\ image caption\\}
65
- \begin{itemize}
66
- \item Key point 1
67
- \item Key point 2
68
- \end{itemize}
69
- \end{frame}
70
-
71
- ...
72
-
73
- \begin{frame}
74
- \frametitle{Summary}
75
- \begin{itemize}
76
- \item Key takeaway 1
77
- \item Key takeaway 2
78
- \end{itemize}
79
- \end{frame}
80
-
81
- \end{document}
82
-
83
- """
84
-
85
- prompt += r"""You must use **at least one image** when creating a presentation. In your output, include `\\includegraphics` commands in **at least half of the slides** where appropriate.
86
-
87
- Prioritize the slide structure of **Core Idea 2** (two-column layout) over **Core Idea 3** (single image on top).
88
- Only use Core Idea 3 when appropriate based on the image orientation.
89
-
90
- You must select images **only from the list provided below**. Each item includes:
91
- - `"path"`: the exact image path to use β€” **you must copy it exactly as-is**.
92
- - `"caption"`: the image's description β€” if `"None"`, **do not use the image**.
93
- - `"orientation"`: either `"horizontal"`, `"vertical"`, or `"square"`.
94
-
95
- Strict rules:
96
- - Never invent, change, or guess the image path. Use the `"path"` value exactly as written.
97
- - Never change or edit anything inside the square brackets `[...]` in any `\\includegraphics` command. All image formatting options (height, width, keepaspectratio) must be left untouched.
98
- - Skip any image with caption `"None"`.
99
- - Use **Core Idea 2** layout for **vertical** and **square** images.
100
- - Use **Core Idea 3** layout for **horizontal** images (when a two-column layout is not suitable).\n\n"""
 
 
 
 
 
 
 
 
 
 
 
1
+ # processing/prompt.py
2
+ def get_prompt(
3
+ presentation_theme: str = "default", color_theme: str = "default"
4
+ ) -> str:
5
+ """
6
+ Returns the prompt used for generating LaTeX Beamer presentations.
7
+ Args:
8
+ presentation_theme (str): The theme for the presentation, default is "default".
9
+ color_theme (str): The color theme for the presentation, default is "default".
10
+ """
11
+ prompt = f"""You are a presentation assistant that creates clear, concise, and engaging slide decks from the reference material provided. You extract the most relevant and important information, organize it logically, and generate LaTeX code for a presentation using the Beamer class.
12
+
13
+ Structure your slides as follows:
14
+ 1. **Introduction**: Present the topic and explain why it's important or interesting.
15
+ 2. **Main Content**: Break down the topic into 2–4 core ideas, one idea per slide. Explain each with clear language, bullet points, or short sentences.
16
+ 3. **Summary**: Recap the key takeaways, what was learned, and what it means for the audience.
17
+
18
+ Use friendly and accessible language that anyone can understand. Avoid technical jargon unless it's essentialβ€”and when you use it, explain it simply.
19
+
20
+ Output only valid LaTeX Beamer code. Each slide must be defined using \\begin{{frame}} ... \\end{{frame}}.
21
+
22
+ Here is some reference content retrieved from a document. Please generate a LaTeX Beamer presentation based on the content, following this structure:
23
+
24
+ 1. Introduction (what is the topic and why it matters)
25
+ 2. Main Part (a few slides on the core ideas)
26
+ 3. Summary (what was learned, 2–3 key takeaways)
27
+
28
+ Please output valid LaTeX code only, like this format:
29
+
30
+ \\documentclass{{beamer}}
31
+ \\usetheme{{{presentation_theme}}}
32
+ \\usecolortheme{{{color_theme}}}
33
+ \\title{{[Presentation Title]}}
34
+ \\author{{AI-generated}}
35
+ \\date{{\\today}}
36
+
37
+ \\begin{{document}}
38
+
39
+ \\frame{{\\titlepage}}
40
+
41
+ \\begin{{frame}}
42
+ \\frametitle{{Introduction}}
43
+ \\begin{{itemize}}
44
+ \\item What's the topic?
45
+ \\item Why is it important?
46
+ \\end{{itemize}}
47
+ \\end{{frame}}
48
+
49
+ \\begin{{frame}}
50
+ \\frametitle{{Core Idea 1}}
51
+ \\begin{{itemize}}
52
+ \\item Key point 1
53
+ \\item Key point 2
54
+ \\end{{itemize}}
55
+ \\end{{frame}}
56
+
57
+ \\begin{{frame}}
58
+ \\frametitle{{Core Idea 2}}
59
+ \\begin{{columns}}
60
+ \\begin{{column}}{{0.5\\linewidth}}
61
+ \\begin{{itemize}}
62
+ \\item Key point 1
63
+ \\item Key point 2
64
+ \\end{{itemize}}
65
+ \\end{{column}}
66
+ \\begin{{column}}{{0.5\\linewidth}}
67
+ \\center{{\\includegraphics[height=1.0\\textheight, width=1.0\\textwidth, keepaspectratio]{{gfx/image}} \\\\ image caption}}
68
+ \\end{{column}}
69
+ \\end{{columns}}
70
+ \\end{{frame}}
71
+
72
+ \\begin{{frame}}
73
+ \\frametitle{{Core Idea 3}}
74
+ \\center{{\\includegraphics[height=0.5\\textheight, width=0.8\\textwidth, keepaspectratio]{{gfx/image}} \\\\ image caption\\\\}}
75
+ \\begin{{itemize}}
76
+ \\item Key point 1
77
+ \\item Key point 2
78
+ \\end{{itemize}}
79
+ \\end{{frame}}
80
+
81
+ ...
82
+
83
+ \\begin{{frame}}
84
+ \\frametitle{{Summary}}
85
+ \\begin{{itemize}}
86
+ \\item Key takeaway 1
87
+ \\item Key takeaway 2
88
+ \\end{{itemize}}
89
+ \\end{{frame}}
90
+
91
+ \\end{{document}}
92
+
93
+ You must use **at least one image** when creating a presentation. In your output, include `\\includegraphics` commands in **at least half of the slides** where appropriate.
94
+
95
+ Prioritize the slide structure of **Core Idea 2** (two-column layout) over **Core Idea 3** (single image on top).
96
+ Only use Core Idea 3 when appropriate based on the image orientation.
97
+
98
+ You must select images **only from the list provided below**. Each item includes:
99
+ - `"path"`: the exact image path to use β€” **you must copy it exactly as-is**.
100
+ - `"caption"`: the image's description β€” if `"None"`, **do not use the image**.
101
+ - `"orientation"`: either `"horizontal"`, `"vertical"`, or `"square"`.
102
+
103
+ Strict rules:
104
+ - Never invent, change, or guess the image path. Use the `"path"` value exactly as written.
105
+ - Never change or edit anything inside the square brackets `[...]` in any `\\includegraphics` command. All image formatting options (height, width, keepaspectratio) must be left untouched.
106
+ - Skip any image with caption `"None"`.
107
+ - Use **Core Idea 2** layout for **vertical** and **square** images.
108
+ - Use **Core Idea 3** layout for **horizontal** images (when a two-column layout is not suitable).\n\n"""
109
+
110
+ return prompt
src/services/__init__.py CHANGED
@@ -1,3 +1,4 @@
1
  from .google_client import client
 
2
 
3
- __all__ = ["client"]
 
1
  from .google_client import client
2
+ from .generator import generate_presentation
3
 
4
+ __all__ = ["client", "generate_presentation"]
src/services/generator.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # services/generator.py
2
+ import os
3
+ import re
4
+ from pathlib import Path
5
+ from datetime import datetime
6
+ from ..database import db, embed_fn, ingest_files_to_db
7
+ from ..utils import Logger
8
+ from ..processing import get_prompt
9
+ from . import client
10
+ from ..compilation import CompilePresentation
11
+ from ..processing import save_pdf_images, save_pdf_figures
12
+
13
+ LOGGER = Logger.get_logger()
14
+
15
+
16
+ def generate_presentation(theme, color, topic, uploaded_files):
17
+ print(f"Theme: {theme}, Color: {color}, Topic: {topic}")
18
+ ingest_files_to_db(uploaded_files)
19
+
20
+ LOGGER.info("Retrieving relevant documents...")
21
+ embed_fn.document_mode = False
22
+
23
+ query_oneline = topic.replace(
24
+ "\n", " "
25
+ ) # (Optional) For cleaner input in case of newlines
26
+ result = db.query(query_texts=[query_oneline], n_results=2)
27
+ [documents] = result["documents"]
28
+ [metadatas] = result["metadatas"]
29
+
30
+ prompt = get_prompt(theme, color)
31
+
32
+ for passage, metas in zip(documents, metadatas):
33
+ passage_oneline = passage.replace("\n", " ")
34
+ images_passage = metas["images_passage"]
35
+
36
+ prompt += f"PASSAGE: {passage_oneline}\n"
37
+ prompt += f"IMAGES: {images_passage}\n"
38
+
39
+ # Create a new subfolder
40
+ LOGGER.info("πŸ’Ύ Creating new subfolder...")
41
+ cwd = Path.cwd()
42
+ one_level_up = cwd.parent
43
+ base_path = one_level_up / "output"
44
+ timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
45
+ work_dir = os.path.join(base_path, timestamp)
46
+ print("work_dir", work_dir)
47
+ os.makedirs(work_dir, exist_ok=False)
48
+ LOGGER.info("πŸ“ Created folder: %s", work_dir)
49
+
50
+ # Generate the presentation code
51
+ model_name = "gemini-2.0-flash"
52
+ LOGGER.info("⭐️ Generating response...")
53
+ answer = client.models.generate_content(model=model_name, contents=prompt)
54
+ LOGGER.info("🎲 Generated the response using: %s", model_name)
55
+ # Create a subfolder for graphics
56
+
57
+ graphics_dir = os.path.join(work_dir, "gfx")
58
+ os.makedirs(graphics_dir, exist_ok=True)
59
+ LOGGER.info("πŸŒ„ Images will be saved to: %s", graphics_dir)
60
+
61
+ # Find images, which are used in the presentation
62
+ pattern_img = re.compile(
63
+ r"doc(?P<doc>[a-zA-Z0-9_]+)_page(?P<page>\d+)_img(?P<img>\d+)_hash(?P<hash>[a-fA-F0-9]{8})\.png"
64
+ )
65
+ matches_img = pattern_img.finditer(answer.text)
66
+
67
+ req_imgs = []
68
+ for match in matches_img:
69
+ req_img = {
70
+ "doc": match.group("doc"),
71
+ "page": int(match.group("page")),
72
+ "img": int(match.group("img")),
73
+ "hash": match.group("hash"),
74
+ }
75
+ req_imgs.append(req_img)
76
+
77
+ # Find figures, which are used in the presentation
78
+ pattern_fig = re.compile(
79
+ r"doc(?P<doc>[a-zA-Z0-9_]+)_page(?P<page>\d+)_fig(?P<fig>\d+)_hash(?P<hash>[a-fA-F0-9]{8})\.png"
80
+ )
81
+ matches_fig = pattern_fig.finditer(answer.text)
82
+
83
+ req_figs = []
84
+ for match in matches_fig:
85
+ req_fig = {
86
+ "doc": match.group("doc"),
87
+ "page": int(match.group("page")),
88
+ "fig": int(match.group("fig")),
89
+ "hash": match.group("hash"),
90
+ }
91
+ req_figs.append(req_fig)
92
+
93
+ # Save the required graphics
94
+ for metadata in metadatas:
95
+ save_pdf_images(metadata["pdf_path"], req_imgs, graphics_dir)
96
+ save_pdf_figures(metadata["pdf_path"], req_figs, graphics_dir)
97
+
98
+ LOGGER.info("Compiling presentation...")
99
+ CompilePresentation(answer.text, work_dir)
100
+ LOGGER.info("Presentation is ready!")
101
+ # Clean up uploaded files
102
+ print("uploaded_files", uploaded_files)
103
+ for file in uploaded_files:
104
+ try:
105
+ path = Path(file)
106
+ if path.exists():
107
+ path.unlink() # Delete the file
108
+ LOGGER.info(f"Deleted file: {file}")
109
+ else:
110
+ LOGGER.warning(f"File not found for deletion: {file}")
111
+ except Exception as e:
112
+ LOGGER.warning(f"Failed to delete {file}", exc_info=e)
113
+
114
+ LOGGER.info("🧹 Cleaned up uploaded files.")
115
+ output_path = Path(work_dir + "/presentation.pdf")
116
+ return "Presentation generated successfully!", str(output_path), ""
src/services/google_client.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  from google import genai
3
  from dotenv import load_dotenv
 
1
+ # services/google_client.py
2
  import os
3
  from google import genai
4
  from dotenv import load_dotenv
src/utils/__init__.py CHANGED
@@ -1,15 +1,9 @@
1
  from .gradio_user_settings import (
2
  upload_files,
3
- process_presentation_topic,
4
- process_presentation_style,
5
- process_color_style,
6
  )
7
  from .logging_utils import Logger
8
 
9
  __all__ = [
10
  "upload_files",
11
- "process_presentation_topic",
12
- "process_presentation_style",
13
- "process_color_style",
14
  "Logger",
15
  ]
 
1
  from .gradio_user_settings import (
2
  upload_files,
 
 
 
3
  )
4
  from .logging_utils import Logger
5
 
6
  __all__ = [
7
  "upload_files",
 
 
 
8
  "Logger",
9
  ]
src/utils/gradio_user_settings.py CHANGED
@@ -1,4 +1,4 @@
1
- #
2
 
3
  from pathlib import Path
4
  import shutil
@@ -17,6 +17,8 @@ def upload_files(files):
17
  UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
18
 
19
  messages = []
 
 
20
  for file in files:
21
  try:
22
  temp_path = Path(file.name)
@@ -34,23 +36,10 @@ def upload_files(files):
34
  messages.append(f"βœ… Uploaded: {file_name}")
35
  LOGGER.info("Uploaded file %s to %s", file_name, UPLOAD_DIR)
36
 
 
 
37
  except Exception as e:
38
  LOGGER.error(f"Error uploading {file_name}: {e}")
39
  messages.append(f"❌ Error uploading {file_name}: {e}")
40
 
41
- return "\n".join(messages)
42
-
43
-
44
- def process_presentation_topic(topic):
45
- # Placeholder logic – you can later generate a LaTeX outline here
46
- return f"πŸ“Œ Topic received: '{topic}'\n\nReady to generate your slides!"
47
-
48
-
49
- def process_presentation_style(style):
50
- # Placeholder logic – you can later generate a LaTeX outline here
51
- return f"🎨 Style selected: '{style}'\n\nReady to generate your slides!"
52
-
53
-
54
- def process_color_style(style):
55
- # Placeholder logic – you can later generate a LaTeX outline here
56
- return f"🎨 Color selected: '{style}'\n\nReady to generate your slides!"
 
1
+ # utils/gradio_user_settings.py
2
 
3
  from pathlib import Path
4
  import shutil
 
17
  UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
18
 
19
  messages = []
20
+ saved_paths = []
21
+
22
  for file in files:
23
  try:
24
  temp_path = Path(file.name)
 
36
  messages.append(f"βœ… Uploaded: {file_name}")
37
  LOGGER.info("Uploaded file %s to %s", file_name, UPLOAD_DIR)
38
 
39
+ saved_paths.append(str(target_path))
40
+
41
  except Exception as e:
42
  LOGGER.error(f"Error uploading {file_name}: {e}")
43
  messages.append(f"❌ Error uploading {file_name}: {e}")
44
 
45
+ return "\n".join(messages), saved_paths
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/utils/logging_utils.py CHANGED
@@ -1,8 +1,4 @@
1
- """
2
- logging_utils.py
3
-
4
- This module provides logging configuration.
5
- """
6
 
7
  import logging
8
 
 
1
+ # utils/logging_utils.py
 
 
 
 
2
 
3
  import logging
4