ajmel commited on
Commit
f47e679
·
1 Parent(s): 325e622

complete LLM summarization pipeline

Browse files
.gitignore CHANGED
@@ -5,4 +5,5 @@ __pycache__/
5
  instance/
6
  *.log
7
  chroma_db
8
- rag-system/test/loade.py
 
 
5
  instance/
6
  *.log
7
  chroma_db
8
+ rag-system/test/loade.py
9
+ multimodal-engine/data/extracted_frames
README.md CHANGED
@@ -11,7 +11,10 @@ A structured, end-to-end AI engineering roadmap covering three production-focuse
11
  ├── multimodal-engine/ # Phase 2 — AI Reel Generator (Multimodal)
12
  ├── ai-saftey-audit/ # Phase 3 — Safety & Bias Evaluation Toolkit
13
  ├── requirements.txt # Shared top-level dependencies
 
 
14
  └── README.md
 
15
  ```
16
 
17
  ---
@@ -24,14 +27,15 @@ A structured, end-to-end AI engineering roadmap covering three production-focuse
24
 
25
  A production-grade Retrieval-Augmented Generation pipeline. Upload any PDF and have a grounded, citation-backed conversation with its contents. Features a multi-LLM fallback chain (Ollama → HuggingFace → OpenAI → Google Gemini), persistent ChromaDB vector storage, sentence-aware chunking, and a full Streamlit chat UI.
26
 
27
- **Status:** Fully functional with Streamlit UI, CLI runner, and diagnostic test suite.
 
 
28
 
29
  ---
30
 
31
  ### Phase 2 — Multimodal Engine 🔧 In Progress
32
 
33
  **`/multimodal-engine`**
34
-
35
  An AI engine designed to process, analyze, and generate content across multiple data types — text, images, and audio. The core objective is building automated pipelines that link transcription, summarization, and video processing into a single workflow.
36
 
37
  **Planned Deliverable:** AI Reel Generator — takes long-form video/audio, transcribes it, identifies key moments, and outputs a short-form highlight reel.
@@ -209,11 +213,13 @@ python rag-system/test/testdb_load.py
209
 
210
  ## 🖼️ Screenshots
211
 
212
- > _Screenshots will be added as each phase is completed._
213
- >
214
- > **RAG System** Streamlit chat UI with PDF upload, Q&A, and citation panel
215
- > **Multimodal Engine** — Video input → transcript → reel output workflow
216
- > **AI Safety Audit** Red-team test results and bias audit report
 
 
217
 
218
  ---
219
 
@@ -228,10 +234,10 @@ python rag-system/test/testdb_load.py
228
  - [x] Distance-filtered retriever
229
  - [x] Multi-LLM fallback chain (Ollama / HF / OpenAI / Gemini)
230
  - [x] Streamlit chat UI with citations
231
- - [ ] Conversation memory (chat history in prompt)
232
- - [ ] Streaming LLM responses
233
- - [ ] Multi-document support
234
- - [ ] Confidence gate (block hallucination on off-topic queries)
235
  - [ ] Cross-encoder reranking
236
  - [ ] FastAPI backend
237
  - [ ] Docker deployment
 
11
  ├── multimodal-engine/ # Phase 2 — AI Reel Generator (Multimodal)
12
  ├── ai-saftey-audit/ # Phase 3 — Safety & Bias Evaluation Toolkit
13
  ├── requirements.txt # Shared top-level dependencies
14
+ ├── .env
15
+ ├── .gitignore
16
  └── README.md
17
+
18
  ```
19
 
20
  ---
 
27
 
28
  A production-grade Retrieval-Augmented Generation pipeline. Upload any PDF and have a grounded, citation-backed conversation with its contents. Features a multi-LLM fallback chain (Ollama → HuggingFace → OpenAI → Google Gemini), persistent ChromaDB vector storage, sentence-aware chunking, and a full Streamlit chat UI.
29
 
30
+ 🔗 **Live Demo:** [ragsystem-chatpadf.streamlit.app](https://ragsystem-chatpadf.streamlit.app/)
31
+
32
+ **Status:** Fully functional — live deployed on Streamlit Cloud with UI, CLI runner, and diagnostic test suite.
33
 
34
  ---
35
 
36
  ### Phase 2 — Multimodal Engine 🔧 In Progress
37
 
38
  **`/multimodal-engine`**
 
39
  An AI engine designed to process, analyze, and generate content across multiple data types — text, images, and audio. The core objective is building automated pipelines that link transcription, summarization, and video processing into a single workflow.
40
 
41
  **Planned Deliverable:** AI Reel Generator — takes long-form video/audio, transcribes it, identifies key moments, and outputs a short-form highlight reel.
 
213
 
214
  ## 🖼️ Screenshots
215
 
216
+ **RAG System** Live at [ragsystem-chatpadf.streamlit.app](https://ragsystem-chatpadf.streamlit.app/)
217
+
218
+ | Dashboard | Document Ingestion | Chat + Citations |
219
+ |---|---|---|
220
+ | ![Dashboard](rag-system/assets/image.png) | ![Ingestion](rag-system/assets/image_pdfup.png) | ![Chat](rag-system/assets/image_chat.png) |
221
+
222
+ > **Multimodal Engine** and **AI Safety Audit** screenshots will be added as each phase ships.
223
 
224
  ---
225
 
 
234
  - [x] Distance-filtered retriever
235
  - [x] Multi-LLM fallback chain (Ollama / HF / OpenAI / Gemini)
236
  - [x] Streamlit chat UI with citations
237
+ - [x] Conversation memory (chat history in prompt)
238
+ - [x] Streaming LLM responses
239
+ - [x] Multi-document support
240
+ - [x] Confidence gate (block hallucination on off-topic queries)
241
  - [ ] Cross-encoder reranking
242
  - [ ] FastAPI backend
243
  - [ ] Docker deployment
multimodal-engine/app/__init__.py ADDED
File without changes
multimodal-engine/app/video_processor.py CHANGED
@@ -1,6 +1,7 @@
1
- import subprocess, os, glob
2
  from google import genai
3
  from dotenv import load_dotenv
 
4
 
5
  load_dotenv()
6
 
@@ -36,6 +37,46 @@ def extract_keyframe(video_path, keyframe_output_dir, interval_seconds=5):
36
  print(f"ffmpeg keyfrmae extrction fsiled")
37
  raise e
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  def analyze_scene_with_gemini(frame_dir):
41
  print(f"[2] Initializing visaula analyzing")
@@ -76,9 +117,9 @@ def analyze_scene_with_gemini(frame_dir):
76
  client.files.delete(name=cloud_file.name)
77
 
78
  return response.text
79
- except Exception as e:
80
- print(f"Vission Infrenec as {e}")
81
- return None
82
 
83
 
84
  if __name__ == "__main__":
 
1
+ import subprocess, os, glob, base64
2
  from google import genai
3
  from dotenv import load_dotenv
4
+ from openai import OpenAI
5
 
6
  load_dotenv()
7
 
 
37
  print(f"ffmpeg keyfrmae extrction fsiled")
38
  raise e
39
 
40
+ def encode_image_to_base64(image_path):
41
+
42
+ with open(image_path, "rb") as image_file:
43
+ return base64.b64encode(image_file.read()).decode('utf-8')
44
+
45
+ def run_openai(frame_path, prompt):
46
+ print("[Fallback] Routing Visual analysis to Openai")
47
+
48
+ try:
49
+ openai_clinet = OpenAI()
50
+
51
+ content_payload = [{"type": "text", "text": prompt}]
52
+
53
+ for path in frame_path:
54
+ base64_image = encode_image_to_base64(path)
55
+
56
+ content_payload.append(
57
+ {
58
+ "type": "image_url",
59
+ "image_url": {
60
+ "url": f"data:image/jpeg;base64,{base64_image}"
61
+ }
62
+ }
63
+ )
64
+
65
+ print("Processing Openai Vission Inference")
66
+
67
+ response = openai_clinet.chat.completions.create(
68
+ model="gpt-4o-mini",
69
+ messages=[{"role": "user", "content": content_payload}],
70
+ max_tokens=1000
71
+ )
72
+
73
+ print("Openai Vission Inference Completed")
74
+
75
+ return response.choices[0].message.content
76
+ except Exception as e:
77
+ print(f"🚨 Fallback Exception: OpenAI engine also failed. Reason: {e}")
78
+ return None
79
+
80
 
81
  def analyze_scene_with_gemini(frame_dir):
82
  print(f"[2] Initializing visaula analyzing")
 
117
  client.files.delete(name=cloud_file.name)
118
 
119
  return response.text
120
+ except Exception as gemin_error:
121
+ print(f"🚨 Fallback Exception: Gemini engine also failed. Reason: {gemin_error}")
122
+ return run_openai(frame_path, prompt)
123
 
124
 
125
  if __name__ == "__main__":
multimodal-engine/app/workflow_engine.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys
2
+ from dotenv import load_dotenv
3
+ from google import genai
4
+ from openai import OpenAI
5
+
6
+ from audio_processor import extract_audio_from_video, transcribe_audio, save_transcript_todisk
7
+ from video_processor import extract_keyframe, analyze_scene_with_gemini
8
+
9
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
10
+ load_dotenv()
11
+
12
+
13
+ def generate_production_blog(audio_transcript, visual_breakdown):
14
+
15
+ print(f"[3]: Orchastrating final content Synthesis via gemin")
16
+
17
+ client = genai.Client()
18
+
19
+ prompt = f"""
20
+ You are an expert technical content writer and software documentation engineer.
21
+
22
+ I am providing you with two distinct data inputs extracted from a video tutorial:
23
+ 1. RAW AUDIO TRANSCRIPT:
24
+ ---
25
+ {audio_transcript}
26
+ ---
27
+
28
+ 2. CHRONOLOGICAL VISUAL BREAKDOWN:
29
+ ---
30
+ {visual_breakdown}
31
+ ---
32
+
33
+ TASK:
34
+ Synthesize these two inputs into a comprehensive, high-quality, step-by-step Technical Blog Post
35
+ written in Markdown.
36
+
37
+ STRUCTURE RULES:
38
+ - Add a catchy title at the top (#).
39
+ - Write a short introduction explaining what software is being demonstrated.
40
+ - Break the content down into logical step-by-step sections using clear headings (##).
41
+ - Blend the visual timeline actions smoothly with the spoken words so it reads like a cohesive tutorial.
42
+ - Highlight specific keyboard shortcuts, timestamps, or interface menus mentioned on screen using code blocks or bold text.
43
+ - End with a summary conclusion.
44
+
45
+ Do not add conversational commentary—return ONLY the markdown content.
46
+ """
47
+
48
+ try:
49
+ response = client.models.generate_content(
50
+ model="gemini-2.5-flash",
51
+ contents=[prompt]
52
+ )
53
+
54
+ return response.text
55
+ except Exception as e:
56
+ print(f"Error during content synthesis: {str(e)}")
57
+ return None
58
+
59
+ def run_integrated_pipeline(video_path):
60
+
61
+ print(f"🚀 -----Starting Integrated Multimodal Content Generation Pipeline-----------")
62
+
63
+ audio_output_path = "../data/extracted_audio.mp3"
64
+ frames_dir = "../data/extracted_frames"
65
+ blogs_output_path = "../output/how_multimodals_work_blog.md"
66
+
67
+ if not os.path.exists("../output"):
68
+ os.makedirs("../output")
69
+
70
+ # phase 1 extracted the audio
71
+ extract_audio_from_video(video_path, audio_output_path)
72
+ audio_transcript = transcribe_audio(audio_output_path)
73
+
74
+ if not audio_transcript:
75
+ print("Pipeline stopped: audio transcribe layer Faileed")
76
+ return None
77
+
78
+ #phase 2: Visual stream trace
79
+
80
+ extract_keyframe(video_path, frames_dir, interval_seconds=5)
81
+ visual_breakdown = analyze_scene_with_gemini(frames_dir)
82
+
83
+ if not visual_breakdown:
84
+ print("Pipeline stopped: visual analysis layer Faileed")
85
+ return None
86
+
87
+ #phase 3 final Blog synthesis
88
+
89
+ final_blog_content = generate_production_blog(audio_transcript, visual_breakdown)
90
+
91
+ if final_blog_content:
92
+ with open(blogs_output_path, "w", encoding="utf-8") as f:
93
+ f.write(final_blog_content)
94
+ print(f"\n System Success Complete multimodal blog post generated at {blogs_output_path}")
95
+ else:
96
+ print("Pipeline stopped: final content synthesis layer Faileed")
97
+
98
+ if __name__ == "__main__":
99
+ TARGET_VIDEO = "../data/sample.mp4"
100
+
101
+ if not os.path.exists(TARGET_VIDEO):
102
+ print(f"⚠️ Verification Guard: Please confirm your testing file is ready at: {TARGET_VIDEO}")
103
+ else:
104
+ run_integrated_pipeline(TARGET_VIDEO)
105
+
106
+
multimodal-engine/data/extracted_audio.mp3 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7564824e6396f97dbfa377439e5c83386c0bf75e3375668d4deb330e72e59c5a
3
- size 919779
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86c6d4d4a32f4a4c439fcc0f1b76528be7f4d5964274f1194be842eb303156d4
3
+ size 1845861
multimodal-engine/data/sample.mp4 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5ba6afa7d5249164d3726b5a05d30d8140f8c37b5a9dc8cd4bee4ee808aa8d14
3
- size 3086518
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2fb6398207b9a54a33b4ec03c172fc699dd194d25d2e089b9efbfa8b2174478e
3
+ size 15769615
multimodal-engine/data/transcript.txt DELETED
@@ -1,13 +0,0 @@
1
- Inkscribe works on Mac or Windows. And while this demo is on the Mac version, the software is pretty much identical on both platforms.
2
-
3
- Using Inkscribe couldn't be simpler. Launch the application, drag an audio or video file onto Inkscribe's media window, click play, and start typing.
4
-
5
- Hello. I'm Mr. Ray. It's that easy.
6
-
7
- You can type anything you want in Inkscribe's text area. You can also insert time codes anywhere you want to mark when things happen.
8
-
9
- And later, you can click on the time codes to jump to that exact point in your video.
10
-
11
- Inkscribe does not do the typing for you, but its wide selection of custom keyboard shortcuts makes it super easy to type notes and transcripts without your hands ever leaving the keyboard.
12
-
13
- You can learn more about Inkscribe and find additional tutorials on Inkscribe's many features at inkscribe.com. Thanks for watching.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
multimodal-engine/output/how_multimodals_work_blog.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Understanding Generative AI: A Comprehensive Guide
2
+
3
+ Generative Artificial Intelligence is rapidly transforming how we create and interact with digital content. This guide, drawing insights from a recent tutorial, provides a step-by-step breakdown of what generative AI is, how it works, its capabilities, potential pitfalls, and how to effectively utilize it.
4
+
5
+ ## 1. Defining Generative AI and the Power of Prompts
6
+
7
+ The journey into generative AI begins with its core definition.
8
+ At **0:00**, the video opens on a laptop screen featuring a chat window, prominently displaying the question `What is generative AI?` alongside a blinking cursor. This immediate visual sets the stage for understanding that generative AI creates new content using artificial intelligence. This content can range from texts and images to videos, music, and voices. The key to directing this creation lies in what's known as a **prompt**—a descriptive input provided in a chat dialogue box, guiding the AI on what you want it to generate.
9
+
10
+ ## 2. Unveiling Generative AI's Creative Capabilities
11
+
12
+ As the video progresses to **0:05**, a friendly robot appears, and by **0:10**, it's seen with arms spread wide as a deluge of colorful items—representing diverse information and data like brain scans, molecules, books, and digital screens—erupts from a box. This vivid imagery illustrates the expansive capabilities of generative AI tools. They can swiftly provide answers to complex questions, summarize intricate information, and generate a wide array of ideas. Depending on their application, these tools can produce short stories, detailed paintings, functional pieces of code, or even intricate musical compositions.
13
+
14
+ ## 3. The Data Foundation and AI's Learning Process
15
+
16
+ Moving to **0:25**, visuals of stacked books and a floating document, followed by a person interacting with a large tablet displaying various digital interfaces at **0:15** and **0:20**, metaphorically introduce the interaction process. Then, at **0:35**, a person observes a line of diverse digital displays, including documents, portraits, and abstract shapes. This leads into **0:40**, where a pink funnel is shown, into which web pages with cat images, spreadsheets, charts, and books are tumbling downwards.
17
+
18
+ This sequence highlights that the foundation for all AI creation is built upon vast quantities of data. The AI system processes and accesses this data, as visually represented by the funnel, to identify intricate patterns and similarities. At **0:45**, these digital assets emerge from the funnel as a complex, interconnected network of colored nodes, resembling a neural network. This visual signifies the AI's internal processing, culminating in the creation of new content.
19
+
20
+ ## 4. The Impressive Quality of AI-Generated Content
21
+
22
+ At **0:50**, the background shifts to green, revealing a tablet screen displaying a surreal, Salvador Dalí-esque landscape. This visual, immediately followed by an elegantly dressed man comparing an ornate framed painting of the same landscape to its digital counterpart on a tablet at **0:55**, underscores a crucial characteristic of AI-generated output: it is new, often remarkably impressive, and frequently challenging to distinguish from content created by humans.
23
+
24
+ ## 5. Exploring Diverse Outputs, Including Deepfakes
25
+
26
+ The generative power of AI extends to various media. At **1:00**, a video player shows a paused scene of simple pyramids, which by **1:05**, has been augmented with two knights on horseback in the foreground. This demonstrates AI's ability to generate or modify video content. Further, at **1:10**, a web browser displays a "NEWS" page filled with eclectic and unusual articles and images, from flying saucers to a yellow lion emerging from a garage, showcasing the breadth of diverse content generation.
27
+
28
+ However, this capability also introduces potential misuses. Generative AI can be utilized to produce images or videos that appear real but are fabricated, a phenomenon commonly known as **deepfakes**.
29
+
30
+ ## 6. Understanding AI's Limitations: Hallucinations and Quality Factors
31
+
32
+ The tutorial then shifts focus to the challenges and limitations of generative AI. At **1:15**, a person interacts with a stylized robot, and by **1:20**, their speech bubbles show differing perspectives (a globe for the human, a flat Earth for the robot), illustrating potential discrepancies. The video explains that AI-generated texts can be difficult to recognize as machine-made. Even more critically, AI can produce answers that sound plausible and correct but are factually incorrect—a phenomenon termed **hallucinating**.
33
+
34
+ At **1:25**, a man with a thoughtful expression has a complex thought bubble above his head, suggesting the intricate processes involved in AI's responses. The quality of generative AI's output is directly tied to two critical factors: the quality of the data it was trained on and, significantly, the quality of the prompts provided by the user. This is visually reinforced at **1:30**, as the man types on a laptop, with a glowing input field above it.
35
+
36
+ ## 7. Guiding AI for Effective Utilization and Human Responsibility
37
+
38
+ The tutorial emphasizes the importance of user interaction. At **1:35**, an initial projection of a robotic head with somewhat unsettling red eyes appears above the laptop, which then transforms into a friendly, smiling robot with simple, round eyes by **1:40**. This visual transformation symbolizes the impact of effective interaction. To harness generative AI's full potential, users must learn to guide these tools with **meaningful prompts** and employ them thoughtfully.
39
+
40
+ Generative AI offers immense potential, acting as a powerful writing or learning partner. The video concludes with compelling visuals of collaboration: at **1:45**, a diverse group of people and robots stand together with speech bubbles, and at **1:50**, they are seated around a table, actively working side-by-side. The core message is clear: while AI is adept at handling the "hard work" of content generation, humans bear the ultimate responsibility for verifying the facts and ensuring accuracy. The final "AI Campus" logo at **1:55** reinforces this educational focus.
41
+
42
+ ## Conclusion
43
+
44
+ Generative AI is a powerful and versatile technology capable of creating diverse, high-quality content. Understanding its mechanisms, from data processing to prompt-based interaction, is crucial for effective utilization. While it offers immense potential as a creative and analytical partner, users must also be aware of its limitations, such as the potential for deepfakes and hallucinations. By learning to craft meaningful prompts and taking responsibility for factual verification, we can thoughtfully leverage generative AI to augment human capabilities across various fields.
rag-system/README.md CHANGED
@@ -1,7 +1,14 @@
1
  # ⚙️ Enterprise RAG System — Chat with PDF
2
 
 
 
 
 
 
3
  A production-grade **Retrieval-Augmented Generation (RAG)** pipeline that allows users to upload multiple PDFs and hold grounded, conversational, citation-backed interactions with their contents. Built with a highly modular architecture, a real-time stream validation engine, a multi-LLM resilient fallback chain, and an interactive Streamlit UI dashboard.
4
 
 
 
5
  ![Main App Dashboard](assets/image.png)
6
 
7
  ---
@@ -85,6 +92,16 @@ Upload multiple PDFs ➔ ask questions ➔ get real-time streaming answers compl
85
  - **Dynamic Retrieval Confidence Scoring** — Translates database Euclidean distance calculations into a user-friendly percentage rating on the dashboard interface
86
 
87
 
 
 
 
 
 
 
 
 
 
 
88
  ---
89
 
90
  ## 🖼️ User Interface Captures
 
1
  # ⚙️ Enterprise RAG System — Chat with PDF
2
 
3
+ [![Live Demo](https://img.shields.io/badge/🚀%20Live%20Demo-Streamlit%20Cloud-FF4B4B?style=for-the-badge&logo=streamlit)](https://ragsystem-chatpadf.streamlit.app/)
4
+ [![Python](https://img.shields.io/badge/Python-3.10+-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://python.org)
5
+ [![LangChain](https://img.shields.io/badge/LangChain-Framework-1C3C3C?style=for-the-badge)](https://langchain.com)
6
+ [![ChromaDB](https://img.shields.io/badge/ChromaDB-Vector%20Store-orange?style=for-the-badge)](https://trychroma.com)
7
+
8
  A production-grade **Retrieval-Augmented Generation (RAG)** pipeline that allows users to upload multiple PDFs and hold grounded, conversational, citation-backed interactions with their contents. Built with a highly modular architecture, a real-time stream validation engine, a multi-LLM resilient fallback chain, and an interactive Streamlit UI dashboard.
9
 
10
+ > 🔗 **Try it live:** [ragsystem-chatpadf.streamlit.app](https://ragsystem-chatpadf.streamlit.app/)
11
+
12
  ![Main App Dashboard](assets/image.png)
13
 
14
  ---
 
92
  - **Dynamic Retrieval Confidence Scoring** — Translates database Euclidean distance calculations into a user-friendly percentage rating on the dashboard interface
93
 
94
 
95
+ ---
96
+
97
+ ## 🎬 Demo
98
+
99
+ 📺 **Video Walkthrough** — Full pipeline demonstration: PDF upload → chunking → retrieval → streaming answer with citations.
100
+
101
+ > ▶️ Watch the demo video to see the multi-LLM fallback chain, real-time streaming, and citation panel in action.
102
+
103
+ 🔗 **Live App:** [ragsystem-chatpadf.streamlit.app](https://ragsystem-chatpadf.streamlit.app/)
104
+
105
  ---
106
 
107
  ## 🖼️ User Interface Captures