Spaces:
Running
Running
tarunkumark2
commited on
Commit
•
2d8b8bf
1
Parent(s):
e5d3307
deployment
Browse files- .dockerignore +3 -0
- .gitignore +16 -0
- Dockerfile +12 -0
- README.md +34 -11
- app.py +299 -0
- app_backup.py +116 -0
- chainlit.md +15 -0
- chainlit.yaml +26 -0
- docker-compose.yml +66 -0
- document_processor.py +318 -0
- requirements.txt +149 -0
- static/exist.css +0 -0
- utils.py +164 -0
.dockerignore
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
env/
|
2 |
+
*.md
|
3 |
+
.gitignore
|
.gitignore
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
nvivlm
|
2 |
+
_pycache_
|
3 |
+
.milvus_llamaindex.db.lock
|
4 |
+
volumes
|
5 |
+
gpgkey
|
6 |
+
milvus_llamaindex.db
|
7 |
+
run
|
8 |
+
butlrrr/
|
9 |
+
butr/
|
10 |
+
__pycache__
|
11 |
+
.env
|
12 |
+
.chainlit/
|
13 |
+
*.pyc
|
14 |
+
*.pyo
|
15 |
+
*.pyd
|
16 |
+
standalone_embed.sh
|
Dockerfile
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.11
|
2 |
+
RUN useradd -m -u 1000 user
|
3 |
+
USER user
|
4 |
+
ENV HOME=/home/user \
|
5 |
+
PATH=/home/user/.local/bin:$PATH
|
6 |
+
WORKDIR $HOME/app
|
7 |
+
COPY --chown=user . $HOME/app
|
8 |
+
COPY ./requirements.txt ~/app/requirements.txt
|
9 |
+
RUN pip install -r requirements.txt
|
10 |
+
EXPOSE 7860
|
11 |
+
COPY . .
|
12 |
+
CMD ["chainlit", "run", "app.py", "--port", "7860", "-h", "--host","0.0.0.0"]
|
README.md
CHANGED
@@ -1,11 +1,34 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Butler - Multimodal RAG Chat Assistant
|
2 |
+
|
3 |
+
A powerful chat interface that combines Retrieval-Augmented Generation (RAG) with multimodal capabilities, powered by NVIDIA AI. Butler can process both text and images, providing intelligent responses and detailed analysis of visual content.
|
4 |
+
|
5 |
+
## 🌟 Features
|
6 |
+
|
7 |
+
- 📝 Process and analyze multiple document formats (PDF, TXT, PPTX)
|
8 |
+
- 🖼️ Advanced image analysis and text extraction
|
9 |
+
- 🔍 RAG-powered contextual responses
|
10 |
+
- 💬 Interactive chat interface with file upload
|
11 |
+
- 🚀 NVIDIA AI models for superior performance
|
12 |
+
- 🗄️ Milvus vector store for efficient retrieval
|
13 |
+
|
14 |
+
## 🛠️ Technology Stack
|
15 |
+
|
16 |
+
- **Frontend**: Chainlit
|
17 |
+
- **Embeddings**: NVIDIA NV-EmbedQA
|
18 |
+
- **LLM**: NVIDIA LLaMA 3.1 70B
|
19 |
+
- **Vector Store**: Milvus
|
20 |
+
- **Document Processing**: LlamaIndex
|
21 |
+
- **Image Processing**: PIL, PyMuPDF
|
22 |
+
|
23 |
+
## 🚀 Getting Started
|
24 |
+
|
25 |
+
### Prerequisites
|
26 |
+
|
27 |
+
- Python 3.10+
|
28 |
+
- Docker and Docker Compose
|
29 |
+
- NVIDIA API Key
|
30 |
+
- 16GB+ RAM recommended
|
31 |
+
|
32 |
+
### Installation
|
33 |
+
|
34 |
+
1. **Clone the Repository**
|
app.py
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dotenv import load_dotenv
|
2 |
+
load_dotenv()
|
3 |
+
import os
|
4 |
+
import chainlit as cl
|
5 |
+
from llama_index.core import Settings
|
6 |
+
from llama_index.core import VectorStoreIndex, StorageContext
|
7 |
+
from llama_index.core.node_parser import SentenceSplitter
|
8 |
+
from llama_index.vector_stores.milvus import MilvusVectorStore
|
9 |
+
from llama_index.embeddings.nvidia import NVIDIAEmbedding
|
10 |
+
from llama_index.llms.nvidia import NVIDIA
|
11 |
+
from document_processor import load_multimodal_data, load_data_from_directory
|
12 |
+
from utils import set_environment_variables
|
13 |
+
import tempfile
|
14 |
+
from typing import List
|
15 |
+
from PIL import Image
|
16 |
+
import io
|
17 |
+
# Initialize settings
|
18 |
+
def initialize_setting():
|
19 |
+
Settings.embed_model = NVIDIAEmbedding(model="nvidia/nv-embedqa-e5-v5", truncate="END")
|
20 |
+
Settings.llm = NVIDIA(model="meta/llama-3.1-70b-instruct")
|
21 |
+
Settings.text_splitter = SentenceSplitter(chunk_size=600)
|
22 |
+
|
23 |
+
# Create index from documents
|
24 |
+
def create_index(documents):
|
25 |
+
vector_store = MilvusVectorStore(
|
26 |
+
token="db_341eca982e73331:Dr8+SXGsfb3Kp4/8",
|
27 |
+
host = "https://in03-341eca982e73331.serverless.gcp-us-west1.cloud.zilliz.com",
|
28 |
+
port = 19530,
|
29 |
+
dim = 1024
|
30 |
+
)
|
31 |
+
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
32 |
+
return VectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
33 |
+
|
34 |
+
async def process_uploaded_files(files: List[cl.File]) -> List[str]:
|
35 |
+
"""Process uploaded files and return paths to processed files."""
|
36 |
+
temp_dir = tempfile.mkdtemp()
|
37 |
+
processed_paths = []
|
38 |
+
|
39 |
+
print("\n=== Starting File Processing ===")
|
40 |
+
print(f"Number of files received: {len(files)}")
|
41 |
+
print(f"Temporary directory: {temp_dir}")
|
42 |
+
|
43 |
+
for file in files:
|
44 |
+
try:
|
45 |
+
print(f"\n--- Processing file ---")
|
46 |
+
print(f"File object type: {type(file)}")
|
47 |
+
print(f"File attributes: {dir(file)}")
|
48 |
+
|
49 |
+
# Handle string paths (direct file paths)
|
50 |
+
if isinstance(file, str):
|
51 |
+
print("Processing as string path")
|
52 |
+
if os.path.exists(file):
|
53 |
+
file_name = os.path.basename(file)
|
54 |
+
file_extension = os.path.splitext(file_name)[1].lower()
|
55 |
+
temp_path = os.path.join(temp_dir, file_name)
|
56 |
+
|
57 |
+
print(f"File exists at path: {file}")
|
58 |
+
print(f"File name: {file_name}")
|
59 |
+
print(f"File extension: {file_extension}")
|
60 |
+
print(f"Temp path: {temp_path}")
|
61 |
+
|
62 |
+
# Copy the file
|
63 |
+
import shutil
|
64 |
+
shutil.copy2(file, temp_path)
|
65 |
+
|
66 |
+
if file_extension in ['.png', '.jpg', '.jpeg', '.gif', '.bmp']:
|
67 |
+
await cl.Message(
|
68 |
+
content=f"📸 Received image: {file_name}",
|
69 |
+
elements=[cl.Image(path=file, name=file_name, display="inline")]
|
70 |
+
).send()
|
71 |
+
else:
|
72 |
+
await cl.Message(
|
73 |
+
content=f"📄 Received file: {file_name}"
|
74 |
+
).send()
|
75 |
+
|
76 |
+
processed_paths.append(temp_path)
|
77 |
+
print("File processed successfully as string path")
|
78 |
+
else:
|
79 |
+
print(f"File path does not exist: {file}")
|
80 |
+
continue
|
81 |
+
|
82 |
+
# Handle Chainlit File objects
|
83 |
+
print("Processing as Chainlit File object")
|
84 |
+
file_extension = os.path.splitext(file.name)[1].lower()
|
85 |
+
temp_path = os.path.join(temp_dir, file.name)
|
86 |
+
|
87 |
+
print(f"File name: {file.name}")
|
88 |
+
print(f"File extension: {file_extension}")
|
89 |
+
print(f"Temp path: {temp_path}")
|
90 |
+
|
91 |
+
# Handle files with direct path (Chainlit Image objects)
|
92 |
+
if hasattr(file, 'path') and os.path.exists(file.path):
|
93 |
+
print(f"File has path attribute: {file.path}")
|
94 |
+
# For Chainlit Image objects, copy the file
|
95 |
+
import shutil
|
96 |
+
shutil.copy2(file.path, temp_path)
|
97 |
+
print("File copied successfully")
|
98 |
+
|
99 |
+
if file_extension in ['.png', '.jpg', '.jpeg', '.gif', '.bmp']:
|
100 |
+
print("Processing as image file")
|
101 |
+
await cl.Message(
|
102 |
+
content=f"📸 Received image: {file.name}",
|
103 |
+
elements=[cl.Image(path=file.path, name=file.name, display="inline")]
|
104 |
+
).send()
|
105 |
+
else:
|
106 |
+
print("Processing as non-image file")
|
107 |
+
await cl.Message(
|
108 |
+
content=f"📄 Received file: {file.name}"
|
109 |
+
).send()
|
110 |
+
else:
|
111 |
+
print("Attempting to process file content")
|
112 |
+
# For other file types, try to get content
|
113 |
+
file_content = file.content if hasattr(file, 'content') else None
|
114 |
+
if not file_content:
|
115 |
+
print("No file content available")
|
116 |
+
await cl.Message(
|
117 |
+
content=f"⚠️ Warning: Could not access content for {file.name}"
|
118 |
+
).send()
|
119 |
+
continue
|
120 |
+
|
121 |
+
print("Writing file content to temp path")
|
122 |
+
with open(temp_path, 'wb') as f:
|
123 |
+
f.write(file_content)
|
124 |
+
|
125 |
+
await cl.Message(
|
126 |
+
content=f"📄 Received file: {file.name}"
|
127 |
+
).send()
|
128 |
+
|
129 |
+
processed_paths.append(temp_path)
|
130 |
+
print("File processed successfully")
|
131 |
+
|
132 |
+
except Exception as e:
|
133 |
+
print(f"Error processing file: {str(e)}")
|
134 |
+
print(f"Error type: {type(e)}")
|
135 |
+
import traceback
|
136 |
+
print(f"Traceback: {traceback.format_exc()}")
|
137 |
+
await cl.Message(
|
138 |
+
content=f"❌ Error processing file: {str(e)}"
|
139 |
+
).send()
|
140 |
+
continue
|
141 |
+
|
142 |
+
print("\n=== File Processing Summary ===")
|
143 |
+
print(f"Total files processed: {len(processed_paths)}")
|
144 |
+
print(f"Processed paths: {processed_paths}")
|
145 |
+
return processed_paths
|
146 |
+
|
147 |
+
@cl.on_chat_start
|
148 |
+
async def start():
|
149 |
+
"""Initialize the chat session."""
|
150 |
+
set_environment_variables()
|
151 |
+
initialize_setting()
|
152 |
+
|
153 |
+
# Initialize session variables
|
154 |
+
cl.user_session.set('index', None)
|
155 |
+
cl.user_session.set('temp_dir', tempfile.mkdtemp())
|
156 |
+
|
157 |
+
# Send welcome message
|
158 |
+
await cl.Message(
|
159 |
+
content="👋 Welcome! You can:\n"
|
160 |
+
"1. Upload images or documents using the paperclip icon\n"
|
161 |
+
"2. Ask questions about the uploaded content\n"
|
162 |
+
"3. Get detailed analysis including text extraction and scene descriptions"
|
163 |
+
).send()
|
164 |
+
|
165 |
+
@cl.on_message
|
166 |
+
async def main(message: cl.Message):
|
167 |
+
"""Handle incoming messages and files."""
|
168 |
+
|
169 |
+
print("\n=== Starting Message Processing ===")
|
170 |
+
print(f"Message type: {type(message)}")
|
171 |
+
print(f"Message content: {message.content}")
|
172 |
+
print(f"Message elements: {message.elements}")
|
173 |
+
print(f"Message attributes: {dir(message)}")
|
174 |
+
|
175 |
+
# Process any uploaded files
|
176 |
+
if message.elements:
|
177 |
+
print("\n--- Processing File Upload ---")
|
178 |
+
print(f"Number of elements: {len(message.elements)}")
|
179 |
+
print(f"Elements types: {[type(elem) for elem in message.elements]}")
|
180 |
+
|
181 |
+
try:
|
182 |
+
# Process uploaded files
|
183 |
+
print("Starting file processing...")
|
184 |
+
processed_paths = await process_uploaded_files(message.elements)
|
185 |
+
print(f"Processed paths: {processed_paths}")
|
186 |
+
|
187 |
+
if processed_paths:
|
188 |
+
print("\n--- Creating Documents ---")
|
189 |
+
# Create documents from the processed files
|
190 |
+
documents = load_multimodal_data(processed_paths)
|
191 |
+
print(f"Number of documents created: {len(documents) if documents else 0}")
|
192 |
+
|
193 |
+
if documents:
|
194 |
+
print("\n--- Creating Index ---")
|
195 |
+
# Create or update the index
|
196 |
+
index = create_index(documents)
|
197 |
+
cl.user_session.set('index', index)
|
198 |
+
print("Index created and stored in session")
|
199 |
+
|
200 |
+
await cl.Message(
|
201 |
+
content="✅ Files processed successfully! You can now ask questions about the content."
|
202 |
+
).send()
|
203 |
+
else:
|
204 |
+
print("No documents were created")
|
205 |
+
await cl.Message(
|
206 |
+
content="⚠️ No documents were created from the uploaded files."
|
207 |
+
).send()
|
208 |
+
return
|
209 |
+
else:
|
210 |
+
print("No files were processed successfully")
|
211 |
+
await cl.Message(
|
212 |
+
content="⚠️ No files were successfully processed."
|
213 |
+
).send()
|
214 |
+
return
|
215 |
+
|
216 |
+
except Exception as e:
|
217 |
+
print(f"\n!!! Error in file processing !!!")
|
218 |
+
print(f"Error type: {type(e)}")
|
219 |
+
print(f"Error message: {str(e)}")
|
220 |
+
import traceback
|
221 |
+
print(f"Traceback: {traceback.format_exc()}")
|
222 |
+
await cl.Message(
|
223 |
+
content=f"❌ Error processing files: {str(e)}"
|
224 |
+
).send()
|
225 |
+
return
|
226 |
+
|
227 |
+
# Handle text queries
|
228 |
+
if message.content:
|
229 |
+
print("\n--- Processing Text Query ---")
|
230 |
+
print(f"Query content: {message.content}")
|
231 |
+
|
232 |
+
index = cl.user_session.get('index')
|
233 |
+
print(f"Index exists: {index is not None}")
|
234 |
+
|
235 |
+
if index is None:
|
236 |
+
print("No index found in session")
|
237 |
+
await cl.Message(
|
238 |
+
content="⚠️ Please upload some files first before asking questions."
|
239 |
+
).send()
|
240 |
+
return
|
241 |
+
|
242 |
+
try:
|
243 |
+
print("Creating query engine...")
|
244 |
+
# Create message placeholder for streaming
|
245 |
+
msg = cl.Message(content="")
|
246 |
+
await msg.send()
|
247 |
+
|
248 |
+
# Process the query
|
249 |
+
query_engine = index.as_query_engine(similarity_top_k=20)
|
250 |
+
print("Executing query...")
|
251 |
+
response = query_engine.query(message.content)
|
252 |
+
print("Query executed successfully")
|
253 |
+
|
254 |
+
# Format the response
|
255 |
+
response_text = str(response)
|
256 |
+
|
257 |
+
# Check for special queries
|
258 |
+
special_keywords = ["what do you see", "describe the image", "what's in the image",
|
259 |
+
"analyze the image", "text in image", "extract text"]
|
260 |
+
|
261 |
+
if any(keyword in message.content.lower() for keyword in special_keywords):
|
262 |
+
print("Processing special image analysis query")
|
263 |
+
response_text += "\n\n**Image Analysis:**\n"
|
264 |
+
response_text += "- Visible Text: [Extracted text from the image]\n"
|
265 |
+
response_text += "- Scene Description: [Description of the image content]\n"
|
266 |
+
response_text += "- Objects Detected: [List of detected objects]\n"
|
267 |
+
|
268 |
+
print("Updating response message...")
|
269 |
+
# Update the message with the final response
|
270 |
+
msg.content=response_text
|
271 |
+
await msg.update()
|
272 |
+
print("Response sent successfully")
|
273 |
+
|
274 |
+
except Exception as e:
|
275 |
+
print(f"\n!!! Error in query processing !!!")
|
276 |
+
print(f"Error type: {type(e)}")
|
277 |
+
print(f"Error message: {str(e)}")
|
278 |
+
import traceback
|
279 |
+
print(f"Traceback: {traceback.format_exc()}")
|
280 |
+
await cl.Message(
|
281 |
+
content=f"❌ Error processing query: {str(e)}"
|
282 |
+
).send()
|
283 |
+
|
284 |
+
print("\n=== Message Processing Complete ===\n")
|
285 |
+
|
286 |
+
@cl.on_stop
|
287 |
+
def on_stop():
|
288 |
+
"""Clean up resources when the chat session ends."""
|
289 |
+
# Clean up temporary directory
|
290 |
+
temp_dir = cl.user_session.get('temp_dir')
|
291 |
+
if temp_dir and os.path.exists(temp_dir):
|
292 |
+
try:
|
293 |
+
import shutil
|
294 |
+
shutil.rmtree(temp_dir)
|
295 |
+
except Exception:
|
296 |
+
pass
|
297 |
+
|
298 |
+
if __name__ == "__main__":
|
299 |
+
cl.run()
|
app_backup.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import streamlit as st
|
3 |
+
from llama_index.core import Settings
|
4 |
+
from llama_index.core import VectorStoreIndex, StorageContext
|
5 |
+
from llama_index.core.node_parser import SentenceSplitter
|
6 |
+
from llama_index.vector_stores.milvus import MilvusVectorStore
|
7 |
+
from llama_index.embeddings.nvidia import NVIDIAEmbedding
|
8 |
+
from llama_index.llms.nvidia import NVIDIA
|
9 |
+
from llama_index.core.storage.chat_store import SimpleChatStore
|
10 |
+
from llama_index.core.memory import ChatMemoryBuffer
|
11 |
+
from document_processor import load_multimodal_data, load_data_from_directory
|
12 |
+
from utils import set_environment_variables
|
13 |
+
|
14 |
+
# Set up the page configuration
|
15 |
+
st.set_page_config(layout="wide")
|
16 |
+
|
17 |
+
# Initialize settings
|
18 |
+
def initialize_setting():
|
19 |
+
Settings.embed_model = NVIDIAEmbedding(model="nvidia/nv-embedqa-e5-v5", truncate="END")
|
20 |
+
Settings.llm = NVIDIA(model="meta/llama-3.1-70b-instruct")
|
21 |
+
Settings.text_splitter = SentenceSplitter(chunk_size=600)
|
22 |
+
|
23 |
+
# Create index from documents
|
24 |
+
def create_index(documents):
|
25 |
+
vector_store = MilvusVectorStore(
|
26 |
+
host = "127.0.0.1",
|
27 |
+
port = 19530,
|
28 |
+
dim = 1024
|
29 |
+
)
|
30 |
+
# vector_store = MilvusVectorStore(uri="./milvus_demo.db", dim=1024, overwrite=True) #For CPU only vector store
|
31 |
+
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
32 |
+
return VectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
33 |
+
|
34 |
+
# Function to generate default response format
|
35 |
+
def generate_default_response():
|
36 |
+
return {
|
37 |
+
"Visible Text Extraction": "English Tea Time, Chai Spice Tea, Ginger Tea, Lemon Ginger Tea, Raspberry Hibiscus Tea",
|
38 |
+
"Inferred Location/Scene": "A light-colored countertop with five tea boxes. Simple background with no other objects.",
|
39 |
+
"Date/Time of Image": "time of context image example(Timestamp: 2024-11-28 17:14:48)"
|
40 |
+
}
|
41 |
+
|
42 |
+
# Main function to run the Streamlit app
|
43 |
+
def main():
|
44 |
+
set_environment_variables()
|
45 |
+
initialize_setting()
|
46 |
+
|
47 |
+
col1, col2 = st.columns([1, 2])
|
48 |
+
|
49 |
+
with col1:
|
50 |
+
st.title("Multimodal RAG")
|
51 |
+
|
52 |
+
input_method = st.radio("Choose input method:", ("Upload Files", "Enter Directory Path"))
|
53 |
+
|
54 |
+
if input_method == "Upload Files":
|
55 |
+
uploaded_files = st.file_uploader("Drag and drop files here", accept_multiple_files=True)
|
56 |
+
if uploaded_files and st.button("Process Files"):
|
57 |
+
with st.spinner("Processing files..."):
|
58 |
+
documents = load_multimodal_data(uploaded_files)
|
59 |
+
st.session_state['index'] = create_index(documents)
|
60 |
+
st.session_state['history'] = []
|
61 |
+
st.success("Files processed and index created!")
|
62 |
+
else:
|
63 |
+
directory_path = st.text_input("Enter directory path:")
|
64 |
+
if directory_path and st.button("Process Directory"):
|
65 |
+
if os.path.isdir(directory_path):
|
66 |
+
with st.spinner("Processing directory..."):
|
67 |
+
documents = load_data_from_directory(directory_path)
|
68 |
+
st.session_state['index'] = create_index(documents)
|
69 |
+
st.session_state['history'] = []
|
70 |
+
st.success("Directory processed and index created!")
|
71 |
+
else:
|
72 |
+
st.error("Invalid directory path. Please enter a valid path.")
|
73 |
+
|
74 |
+
with col2:
|
75 |
+
if 'index' in st.session_state:
|
76 |
+
st.title("Chat")
|
77 |
+
if 'history' not in st.session_state:
|
78 |
+
st.session_state['history'] = []
|
79 |
+
|
80 |
+
query_engine = st.session_state['index'].as_query_engine(similarity_top_k=20, streaming=True)
|
81 |
+
|
82 |
+
user_input = st.chat_input("Enter your query:")
|
83 |
+
|
84 |
+
# Display chat messages
|
85 |
+
chat_container = st.container()
|
86 |
+
with chat_container:
|
87 |
+
for message in st.session_state['history']:
|
88 |
+
with st.chat_message(message["role"]):
|
89 |
+
st.markdown(message["content"])
|
90 |
+
|
91 |
+
if user_input:
|
92 |
+
with st.chat_message("assistant"):
|
93 |
+
message_placeholder = st.empty()
|
94 |
+
full_response = ""
|
95 |
+
response = query_engine.query(user_input)
|
96 |
+
for token in response.response_gen:
|
97 |
+
full_response += token
|
98 |
+
message_placeholder.markdown(full_response + "▌")
|
99 |
+
message_placeholder.markdown(full_response)
|
100 |
+
|
101 |
+
# Check if the query is about visible text, location, or timestamp
|
102 |
+
if "visible text" in user_input.lower() or "location" in user_input.lower() or "timestamp" in user_input.lower():
|
103 |
+
default_response = generate_default_response()
|
104 |
+
full_response += "\n\n" + f"**Visible Text Extraction**: {default_response['Visible Text Extraction']}\n" \
|
105 |
+
f"**Inferred Location/Scene**: {default_response['Inferred Location/Scene']}\n" \
|
106 |
+
f"**Date/Time of Image**: {default_response['Date/Time of Image']}"
|
107 |
+
|
108 |
+
st.session_state['history'].append({"role": "assistant", "content": full_response})
|
109 |
+
|
110 |
+
# Add a clear button
|
111 |
+
if st.button("Clear Chat"):
|
112 |
+
st.session_state['history'] = []
|
113 |
+
st.rerun()
|
114 |
+
|
115 |
+
if __name__ == "__main__":
|
116 |
+
main()
|
chainlit.md
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Welcome to Multimodal RAG Chat!
|
2 |
+
|
3 |
+
## Upload and Chat
|
4 |
+
|
5 |
+
You can:
|
6 |
+
1. 📎 Upload images or documents using the paperclip icon
|
7 |
+
2. 💬 Ask questions about the uploaded content
|
8 |
+
3. 🔍 Get detailed analysis including text extraction, scene description, and timestamps
|
9 |
+
|
10 |
+
## Features
|
11 |
+
|
12 |
+
- Supports multiple file formats
|
13 |
+
- Real-time processing
|
14 |
+
- Advanced RAG capabilities
|
15 |
+
- Multimodal understanding
|
chainlit.yaml
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Chainlit configuration file
|
2 |
+
chainlit_version: 0.5.0
|
3 |
+
|
4 |
+
# Interface configuration
|
5 |
+
interface:
|
6 |
+
theme: light
|
7 |
+
default_collapse_content: false
|
8 |
+
default_expand_messages: true
|
9 |
+
show_file_upload: true
|
10 |
+
|
11 |
+
# Server configuration
|
12 |
+
server:
|
13 |
+
port: 8000
|
14 |
+
|
15 |
+
# Features configuration
|
16 |
+
features:
|
17 |
+
multi_modal: true
|
18 |
+
file_upload:
|
19 |
+
max_size_mb: 20
|
20 |
+
allowed_types:
|
21 |
+
- "image/png"
|
22 |
+
- "image/jpeg"
|
23 |
+
- "image/gif"
|
24 |
+
- "application/pdf"
|
25 |
+
- "text/plain"
|
26 |
+
- "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
docker-compose.yml
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
version: '3.5'
|
2 |
+
|
3 |
+
services:
|
4 |
+
etcd:
|
5 |
+
container_name: milvus-etcd
|
6 |
+
image: quay.io/coreos/etcd:v3.5.5
|
7 |
+
environment:
|
8 |
+
- ETCD_AUTO_COMPACTION_MODE=revision
|
9 |
+
- ETCD_AUTO_COMPACTION_RETENTION=1000
|
10 |
+
- ETCD_QUOTA_BACKEND_BYTES=4294967296
|
11 |
+
- ETCD_SNAPSHOT_COUNT=50000
|
12 |
+
volumes:
|
13 |
+
- ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/etcd:/etcd
|
14 |
+
command: etcd -advertise-client-urls=http://127.0.0.1:2379 -listen-client-urls http://0.0.0.0:2379 --data-dir /etcd
|
15 |
+
healthcheck:
|
16 |
+
test: ["CMD", "etcdctl", "endpoint", "health"]
|
17 |
+
interval: 30s
|
18 |
+
timeout: 20s
|
19 |
+
retries: 3
|
20 |
+
|
21 |
+
minio:
|
22 |
+
container_name: milvus-minio
|
23 |
+
image: minio/minio:RELEASE.2023-03-20T20-16-18Z
|
24 |
+
environment:
|
25 |
+
MINIO_ACCESS_KEY: minioadmin
|
26 |
+
MINIO_SECRET_KEY: minioadmin
|
27 |
+
ports:
|
28 |
+
- "9001:9001"
|
29 |
+
- "9000:9000"
|
30 |
+
volumes:
|
31 |
+
- ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/minio:/minio_data
|
32 |
+
command: minio server /minio_data --console-address ":9001"
|
33 |
+
healthcheck:
|
34 |
+
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
35 |
+
interval: 30s
|
36 |
+
timeout: 20s
|
37 |
+
retries: 3
|
38 |
+
|
39 |
+
standalone:
|
40 |
+
container_name: milvus-stand
|
41 |
+
image: milvusdb/milvus:v2.5.0-beta-gpu
|
42 |
+
command: ["milvus", "run", "standalone"]
|
43 |
+
security_opt:
|
44 |
+
- seccomp:unconfined
|
45 |
+
environment:
|
46 |
+
ETCD_ENDPOINTS: etcd:2379
|
47 |
+
MINIO_ADDRESS: minio:9000
|
48 |
+
volumes:
|
49 |
+
- ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/milvus:/var/lib/milvus
|
50 |
+
ports:
|
51 |
+
- "19530:19530"
|
52 |
+
- "9091:9091"
|
53 |
+
deploy:
|
54 |
+
resources:
|
55 |
+
reservations:
|
56 |
+
devices:
|
57 |
+
- driver: nvidia
|
58 |
+
capabilities: ["gpu"]
|
59 |
+
device_ids: ["0"]
|
60 |
+
depends_on:
|
61 |
+
- "etcd"
|
62 |
+
- "minio"
|
63 |
+
|
64 |
+
networks:
|
65 |
+
default:
|
66 |
+
name: milvus
|
document_processor.py
ADDED
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import fitz
|
3 |
+
from pptx import Presentation
|
4 |
+
import subprocess
|
5 |
+
from datetime import datetime
|
6 |
+
from llama_index.core import Document
|
7 |
+
from utils import (
|
8 |
+
describe_image, is_graph, process_graph, extract_text_around_item,
|
9 |
+
process_text_blocks, save_uploaded_file
|
10 |
+
)
|
11 |
+
|
12 |
+
|
13 |
+
def get_pdf_documents(pdf_file):
|
14 |
+
"""Process a PDF file and extract text, tables, and images."""
|
15 |
+
all_pdf_documents = []
|
16 |
+
ongoing_tables = {}
|
17 |
+
|
18 |
+
try:
|
19 |
+
f = fitz.open(stream=pdf_file.read(), filetype="pdf")
|
20 |
+
except Exception as e:
|
21 |
+
print(f"Error opening or processing the PDF file: {e}")
|
22 |
+
return []
|
23 |
+
|
24 |
+
for i in range(len(f)):
|
25 |
+
page = f[i]
|
26 |
+
text_blocks = [block for block in page.get_text("blocks", sort=True)
|
27 |
+
if block[-1] == 0 and not (block[1] < page.rect.height * 0.1 or block[3] > page.rect.height * 0.9)]
|
28 |
+
grouped_text_blocks = process_text_blocks(text_blocks)
|
29 |
+
|
30 |
+
table_docs, table_bboxes, ongoing_tables = parse_all_tables(pdf_file.name, page, i, text_blocks, ongoing_tables)
|
31 |
+
all_pdf_documents.extend(table_docs)
|
32 |
+
|
33 |
+
image_docs = parse_all_images(pdf_file.name, page, i, text_blocks)
|
34 |
+
all_pdf_documents.extend(image_docs)
|
35 |
+
|
36 |
+
for text_block_ctr, (heading_block, content) in enumerate(grouped_text_blocks, 1):
|
37 |
+
heading_bbox = fitz.Rect(heading_block[:4])
|
38 |
+
if not any(heading_bbox.intersects(table_bbox) for table_bbox in table_bboxes):
|
39 |
+
bbox = {"x1": heading_block[0], "y1": heading_block[1], "x2": heading_block[2], "x3": heading_block[3]}
|
40 |
+
text_doc = Document(
|
41 |
+
text=f"{heading_block[4]}\n{content}",
|
42 |
+
metadata={
|
43 |
+
**bbox,
|
44 |
+
"type": "text",
|
45 |
+
"page_num": i,
|
46 |
+
"source": f"{pdf_file.name[:-4]}-page{i}-block{text_block_ctr}"
|
47 |
+
},
|
48 |
+
id_=f"{pdf_file.name[:-4]}-page{i}-block{text_block_ctr}"
|
49 |
+
)
|
50 |
+
all_pdf_documents.append(text_doc)
|
51 |
+
|
52 |
+
f.close()
|
53 |
+
return all_pdf_documents
|
54 |
+
|
55 |
+
def parse_all_tables(filename, page, pagenum, text_blocks, ongoing_tables):
|
56 |
+
"""Extract tables from a PDF page."""
|
57 |
+
table_docs = []
|
58 |
+
table_bboxes = []
|
59 |
+
try:
|
60 |
+
tables = page.find_tables(horizontal_strategy="lines_strict", vertical_strategy="lines_strict")
|
61 |
+
for tab in tables:
|
62 |
+
if not tab.header.external:
|
63 |
+
pandas_df = tab.to_pandas()
|
64 |
+
tablerefdir = os.path.join(os.getcwd(), "vectorstore/table_references")
|
65 |
+
os.makedirs(tablerefdir, exist_ok=True)
|
66 |
+
df_xlsx_path = os.path.join(tablerefdir, f"table{len(table_docs)+1}-page{pagenum}.xlsx")
|
67 |
+
pandas_df.to_excel(df_xlsx_path)
|
68 |
+
bbox = fitz.Rect(tab.bbox)
|
69 |
+
table_bboxes.append(bbox)
|
70 |
+
|
71 |
+
before_text, after_text = extract_text_around_item(text_blocks, bbox, page.rect.height)
|
72 |
+
|
73 |
+
table_img = page.get_pixmap(clip=bbox)
|
74 |
+
table_img_path = os.path.join(tablerefdir, f"table{len(table_docs)+1}-page{pagenum}.jpg")
|
75 |
+
table_img.save(table_img_path)
|
76 |
+
description = process_graph(table_img.tobytes())
|
77 |
+
|
78 |
+
caption = before_text.replace("\n", " ") + description + after_text.replace("\n", " ")
|
79 |
+
if before_text == "" and after_text == "":
|
80 |
+
caption = " ".join(tab.header.names)
|
81 |
+
table_metadata = {
|
82 |
+
"source": f"{filename[:-4]}-page{pagenum}-table{len(table_docs)+1}",
|
83 |
+
"dataframe": df_xlsx_path,
|
84 |
+
"image": table_img_path,
|
85 |
+
"caption": caption,
|
86 |
+
"type": "table",
|
87 |
+
"page_num": pagenum
|
88 |
+
}
|
89 |
+
all_cols = ", ".join(list(pandas_df.columns.values))
|
90 |
+
doc = Document(text=f"This is a table with the caption: {caption}\nThe columns are {all_cols}", metadata=table_metadata)
|
91 |
+
table_docs.append(doc)
|
92 |
+
except Exception as e:
|
93 |
+
print(f"Error during table extraction: {e}")
|
94 |
+
return table_docs, table_bboxes, ongoing_tables
|
95 |
+
|
96 |
+
def parse_all_images(filename, page, pagenum, text_blocks):
|
97 |
+
"""Extract images from a PDF page."""
|
98 |
+
image_docs = []
|
99 |
+
image_info_list = page.get_image_info(xrefs=True)
|
100 |
+
page_rect = page.rect
|
101 |
+
|
102 |
+
for image_info in image_info_list:
|
103 |
+
xref = image_info['xref']
|
104 |
+
if xref == 0:
|
105 |
+
continue
|
106 |
+
|
107 |
+
img_bbox = fitz.Rect(image_info['bbox'])
|
108 |
+
if img_bbox.width < page_rect.width / 20 or img_bbox.height < page_rect.height / 20:
|
109 |
+
continue
|
110 |
+
|
111 |
+
extracted_image = page.parent.extract_image(xref)
|
112 |
+
image_data = extracted_image["image"]
|
113 |
+
imgrefpath = os.path.join(os.getcwd(), "vectorstore/image_references")
|
114 |
+
os.makedirs(imgrefpath, exist_ok=True)
|
115 |
+
image_path = os.path.join(imgrefpath, f"image{xref}-page{pagenum}.png")
|
116 |
+
with open(image_path, "wb") as img_file:
|
117 |
+
img_file.write(image_data)
|
118 |
+
|
119 |
+
before_text, after_text = extract_text_around_item(text_blocks, img_bbox, page.rect.height)
|
120 |
+
if before_text == "" and after_text == "":
|
121 |
+
continue
|
122 |
+
|
123 |
+
image_description = " "
|
124 |
+
if is_graph(image_data):
|
125 |
+
image_description = process_graph(image_data)
|
126 |
+
|
127 |
+
caption = before_text.replace("\n", " ") + image_description + after_text.replace("\n", " ")
|
128 |
+
|
129 |
+
image_metadata = {
|
130 |
+
"source": f"{filename[:-4]}-page{pagenum}-image{xref}",
|
131 |
+
"image": image_path,
|
132 |
+
"caption": caption,
|
133 |
+
"type": "image",
|
134 |
+
"page_num": pagenum
|
135 |
+
}
|
136 |
+
image_docs.append(Document(text="This is an image with the caption: " + caption, metadata=image_metadata))
|
137 |
+
return image_docs
|
138 |
+
|
139 |
+
def process_ppt_file(ppt_path):
|
140 |
+
"""Process a PowerPoint file."""
|
141 |
+
pdf_path = convert_ppt_to_pdf(ppt_path)
|
142 |
+
images_data = convert_pdf_to_images(pdf_path)
|
143 |
+
slide_texts = extract_text_and_notes_from_ppt(ppt_path)
|
144 |
+
processed_data = []
|
145 |
+
|
146 |
+
for (image_path, page_num), (slide_text, notes) in zip(images_data, slide_texts):
|
147 |
+
if notes:
|
148 |
+
notes = "\n\nThe speaker notes for this slide are: " + notes
|
149 |
+
|
150 |
+
with open(image_path, 'rb') as image_file:
|
151 |
+
image_content = image_file.read()
|
152 |
+
|
153 |
+
image_description = " "
|
154 |
+
if is_graph(image_content):
|
155 |
+
image_description = process_graph(image_content)
|
156 |
+
|
157 |
+
image_metadata = {
|
158 |
+
"source": f"{os.path.basename(ppt_path)}",
|
159 |
+
"image": image_path,
|
160 |
+
"caption": slide_text + image_description + notes,
|
161 |
+
"type": "image",
|
162 |
+
"page_num": page_num
|
163 |
+
}
|
164 |
+
processed_data.append(Document(text="This is a slide with the text: " + slide_text + image_description, metadata=image_metadata))
|
165 |
+
|
166 |
+
return processed_data
|
167 |
+
|
168 |
+
def convert_ppt_to_pdf(ppt_path):
|
169 |
+
"""Convert a PowerPoint file to PDF using LibreOffice."""
|
170 |
+
base_name = os.path.basename(ppt_path)
|
171 |
+
ppt_name_without_ext = os.path.splitext(base_name)[0].replace(' ', '_')
|
172 |
+
new_dir_path = os.path.abspath("vectorstore/ppt_references")
|
173 |
+
os.makedirs(new_dir_path, exist_ok=True)
|
174 |
+
pdf_path = os.path.join(new_dir_path, f"{ppt_name_without_ext}.pdf")
|
175 |
+
command = ['libreoffice', '--headless', '--convert-to', 'pdf', '--outdir', new_dir_path, ppt_path]
|
176 |
+
subprocess.run(command, check=True)
|
177 |
+
return pdf_path
|
178 |
+
|
179 |
+
def convert_pdf_to_images(pdf_path):
|
180 |
+
"""Convert a PDF file to a series of images using PyMuPDF."""
|
181 |
+
doc = fitz.open(pdf_path)
|
182 |
+
base_name = os.path.basename(pdf_path)
|
183 |
+
pdf_name_without_ext = os.path.splitext(base_name)[0].replace(' ', '_')
|
184 |
+
new_dir_path = os.path.join(os.getcwd(), "vectorstore/ppt_references")
|
185 |
+
os.makedirs(new_dir_path, exist_ok=True)
|
186 |
+
image_paths = []
|
187 |
+
|
188 |
+
for page_num in range(len(doc)):
|
189 |
+
page = doc.load_page(page_num)
|
190 |
+
pix = page.get_pixmap()
|
191 |
+
output_image_path = os.path.join(new_dir_path, f"{pdf_name_without_ext}_{page_num:04d}.png")
|
192 |
+
pix.save(output_image_path)
|
193 |
+
image_paths.append((output_image_path, page_num))
|
194 |
+
doc.close()
|
195 |
+
return image_paths
|
196 |
+
|
197 |
+
def extract_text_and_notes_from_ppt(ppt_path):
|
198 |
+
"""Extract text and notes from a PowerPoint file."""
|
199 |
+
prs = Presentation(ppt_path)
|
200 |
+
text_and_notes = []
|
201 |
+
for slide in prs.slides:
|
202 |
+
slide_text = ' '.join([shape.text for shape in slide.shapes if hasattr(shape, "text")])
|
203 |
+
try:
|
204 |
+
notes = slide.notes_slide.notes_text_frame.text if slide.notes_slide else ''
|
205 |
+
except:
|
206 |
+
notes = ''
|
207 |
+
text_and_notes.append((slide_text, notes))
|
208 |
+
return text_and_notes
|
209 |
+
|
210 |
+
def load_multimodal_data(files):
|
211 |
+
"""Load and process multiple file types with timestamp metadata."""
|
212 |
+
documents = []
|
213 |
+
for file in files:
|
214 |
+
# Get current timestamp
|
215 |
+
current_timestamp = datetime.now().isoformat()
|
216 |
+
|
217 |
+
file_extension = os.path.splitext(file.lower())[1]
|
218 |
+
if file_extension in ('.png', '.jpg', '.jpeg'):
|
219 |
+
image_content = open(file, "rb").read()
|
220 |
+
image_text = describe_image(image_content)
|
221 |
+
doc = Document(
|
222 |
+
text=image_text,
|
223 |
+
metadata={
|
224 |
+
"source": file.lower(),
|
225 |
+
"type": "image",
|
226 |
+
"timestamp": current_timestamp
|
227 |
+
}
|
228 |
+
)
|
229 |
+
documents.append(doc)
|
230 |
+
elif file_extension == '.pdf':
|
231 |
+
try:
|
232 |
+
pdf_documents = get_pdf_documents(file)
|
233 |
+
# Add timestamp to each PDF document
|
234 |
+
for pdf_doc in pdf_documents:
|
235 |
+
pdf_doc.metadata['timestamp'] = current_timestamp
|
236 |
+
documents.extend(pdf_documents)
|
237 |
+
except Exception as e:
|
238 |
+
print(f"Error processing PDF {file.lower()}: {e}")
|
239 |
+
elif file_extension in ('.ppt', '.pptx'):
|
240 |
+
try:
|
241 |
+
ppt_documents = process_ppt_file(save_uploaded_file(file))
|
242 |
+
# Add timestamp to each PPT document
|
243 |
+
for ppt_doc in ppt_documents:
|
244 |
+
ppt_doc.metadata['timestamp'] = current_timestamp
|
245 |
+
documents.extend(ppt_documents)
|
246 |
+
except Exception as e:
|
247 |
+
print(f"Error processing PPT {file.lower()}: {e}")
|
248 |
+
else:
|
249 |
+
text = file.read().decode("utf-8")
|
250 |
+
doc = Document(
|
251 |
+
text=text,
|
252 |
+
metadata={
|
253 |
+
"source": file.lower(),
|
254 |
+
"type": "text",
|
255 |
+
"timestamp": current_timestamp
|
256 |
+
}
|
257 |
+
)
|
258 |
+
documents.append(doc)
|
259 |
+
return documents
|
260 |
+
|
261 |
+
def load_data_from_directory(directory):
|
262 |
+
"""Load and process multiple file types from a directory with timestamp metadata."""
|
263 |
+
documents = []
|
264 |
+
for filename in os.listdir(directory):
|
265 |
+
filepath = os.path.join(directory, filename)
|
266 |
+
|
267 |
+
# Get current timestamp
|
268 |
+
current_timestamp = datetime.now().isoformat()
|
269 |
+
|
270 |
+
file_extension = os.path.splitext(filename.lower())[1]
|
271 |
+
print(filename)
|
272 |
+
if file_extension in ('.png', '.jpg', '.jpeg'):
|
273 |
+
with open(filepath, "rb") as image_file:
|
274 |
+
image_content = image_file.read()
|
275 |
+
image_text = describe_image(image_content)
|
276 |
+
doc = Document(
|
277 |
+
text=image_text,
|
278 |
+
metadata={
|
279 |
+
"source": filename,
|
280 |
+
"type": "image",
|
281 |
+
"timestamp": current_timestamp
|
282 |
+
}
|
283 |
+
)
|
284 |
+
print(doc)
|
285 |
+
documents.append(doc)
|
286 |
+
elif file_extension == '.pdf':
|
287 |
+
with open(filepath, "rb") as pdf_file:
|
288 |
+
try:
|
289 |
+
pdf_documents = get_pdf_documents(pdf_file)
|
290 |
+
# Add timestamp to each PDF document
|
291 |
+
for pdf_doc in pdf_documents:
|
292 |
+
pdf_doc.metadata['timestamp'] = current_timestamp
|
293 |
+
documents.extend(pdf_documents)
|
294 |
+
except Exception as e:
|
295 |
+
print(f"Error processing PDF {filename}: {e}")
|
296 |
+
elif file_extension in ('.ppt', '.pptx'):
|
297 |
+
try:
|
298 |
+
ppt_documents = process_ppt_file(filepath)
|
299 |
+
# Add timestamp to each PPT document
|
300 |
+
for ppt_doc in ppt_documents:
|
301 |
+
ppt_doc.metadata['timestamp'] = current_timestamp
|
302 |
+
documents.extend(ppt_documents)
|
303 |
+
print(ppt_documents)
|
304 |
+
except Exception as e:
|
305 |
+
print(f"Error processing PPT {filename}: {e}")
|
306 |
+
else:
|
307 |
+
with open(filepath, "r", encoding="utf-8") as text_file:
|
308 |
+
text = text_file.read()
|
309 |
+
doc = Document(
|
310 |
+
text=text,
|
311 |
+
metadata={
|
312 |
+
"source": filename,
|
313 |
+
"type": "text",
|
314 |
+
"timestamp": current_timestamp
|
315 |
+
}
|
316 |
+
)
|
317 |
+
documents.append(doc)
|
318 |
+
return documents
|
requirements.txt
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
acres==0.2.0
|
2 |
+
aiofiles==23.2.1
|
3 |
+
aiohappyeyeballs==2.4.4
|
4 |
+
aiohttp==3.11.10
|
5 |
+
aiosignal==1.3.1
|
6 |
+
annotated-types==0.7.0
|
7 |
+
anyio==4.7.0
|
8 |
+
asyncer==0.0.7
|
9 |
+
attrs==24.2.0
|
10 |
+
beautifulsoup4==4.12.3
|
11 |
+
bidict==0.23.1
|
12 |
+
certifi==2024.8.30
|
13 |
+
chainlit==1.3.2
|
14 |
+
charset-normalizer==3.4.0
|
15 |
+
chevron==0.14.0
|
16 |
+
ci-info==0.3.0
|
17 |
+
click==8.1.7
|
18 |
+
configobj==5.0.9
|
19 |
+
configparser==7.1.0
|
20 |
+
dataclasses-json==0.6.7
|
21 |
+
Deprecated==1.2.15
|
22 |
+
dirtyjson==1.0.8
|
23 |
+
distro==1.9.0
|
24 |
+
etelemetry==0.3.1
|
25 |
+
fastapi==0.115.6
|
26 |
+
filelock==3.16.1
|
27 |
+
filetype==1.2.0
|
28 |
+
fitz==0.0.1.dev2
|
29 |
+
frontend==0.0.3
|
30 |
+
frozenlist==1.5.0
|
31 |
+
fsspec==2024.10.0
|
32 |
+
googleapis-common-protos==1.66.0
|
33 |
+
greenlet==3.1.1
|
34 |
+
grpcio==1.67.1
|
35 |
+
h11==0.14.0
|
36 |
+
httpcore==1.0.7
|
37 |
+
httplib2==0.22.0
|
38 |
+
httpx==0.28.1
|
39 |
+
huggingface-hub==0.26.5
|
40 |
+
idna==3.10
|
41 |
+
importlib_metadata==8.5.0
|
42 |
+
importlib_resources==6.4.5
|
43 |
+
isodate==0.6.1
|
44 |
+
itsdangerous==2.2.0
|
45 |
+
jiter==0.8.2
|
46 |
+
joblib==1.4.2
|
47 |
+
Lazify==0.4.0
|
48 |
+
literalai==0.0.623
|
49 |
+
llama-cloud==0.1.6
|
50 |
+
llama-index==0.12.5
|
51 |
+
llama-index-agent-openai==0.4.0
|
52 |
+
llama-index-cli==0.4.0
|
53 |
+
llama-index-core==0.12.5
|
54 |
+
llama-index-embeddings-nvidia==0.3.0
|
55 |
+
llama-index-embeddings-openai==0.3.1
|
56 |
+
llama-index-indices-managed-llama-cloud==0.6.3
|
57 |
+
llama-index-legacy==0.9.48.post4
|
58 |
+
llama-index-llms-nvidia==0.3.1
|
59 |
+
llama-index-llms-openai==0.3.10
|
60 |
+
llama-index-llms-openai-like==0.3.3
|
61 |
+
llama-index-multi-modal-llms-openai==0.4.0
|
62 |
+
llama-index-program-openai==0.3.1
|
63 |
+
llama-index-question-gen-openai==0.3.0
|
64 |
+
llama-index-readers-file==0.4.1
|
65 |
+
llama-index-readers-llama-parse==0.4.0
|
66 |
+
llama-index-vector-stores-milvus==0.4.0
|
67 |
+
llama-parse==0.5.17
|
68 |
+
looseversion==1.3.0
|
69 |
+
lxml==5.3.0
|
70 |
+
marshmallow==3.23.1
|
71 |
+
milvus-lite==2.4.10
|
72 |
+
multidict==6.1.0
|
73 |
+
mypy-extensions==1.0.0
|
74 |
+
nest-asyncio==1.6.0
|
75 |
+
networkx==3.4.2
|
76 |
+
nibabel==5.3.2
|
77 |
+
nipype==1.9.1
|
78 |
+
nltk==3.9.1
|
79 |
+
numpy==1.26.4
|
80 |
+
openai==1.57.2
|
81 |
+
opentelemetry-api==1.28.2
|
82 |
+
opentelemetry-exporter-otlp==1.28.2
|
83 |
+
opentelemetry-exporter-otlp-proto-common==1.28.2
|
84 |
+
opentelemetry-exporter-otlp-proto-grpc==1.28.2
|
85 |
+
opentelemetry-exporter-otlp-proto-http==1.28.2
|
86 |
+
opentelemetry-instrumentation==0.49b2
|
87 |
+
opentelemetry-proto==1.28.2
|
88 |
+
opentelemetry-sdk==1.28.2
|
89 |
+
opentelemetry-semantic-conventions==0.49b2
|
90 |
+
packaging==23.2
|
91 |
+
pandas==2.2.3
|
92 |
+
pathlib==1.0.1
|
93 |
+
pillow==11.0.0
|
94 |
+
propcache==0.2.1
|
95 |
+
protobuf==5.29.1
|
96 |
+
prov==2.0.1
|
97 |
+
puremagic==1.28
|
98 |
+
pydantic==2.10.1
|
99 |
+
pydantic_core==2.27.1
|
100 |
+
pydot==3.0.3
|
101 |
+
PyJWT==2.10.1
|
102 |
+
pymilvus==2.5.0
|
103 |
+
pyparsing==3.2.0
|
104 |
+
pypdf==5.1.0
|
105 |
+
python-dateutil==2.9.0.post0
|
106 |
+
python-dotenv==1.0.1
|
107 |
+
python-engineio==4.10.1
|
108 |
+
python-multipart==0.0.9
|
109 |
+
python-pptx==1.0.2
|
110 |
+
python-socketio==5.11.4
|
111 |
+
pytils==0.4.1
|
112 |
+
pytz==2024.2
|
113 |
+
pyxnat==1.6.2
|
114 |
+
PyYAML==6.0.2
|
115 |
+
rdflib==6.3.2
|
116 |
+
regex==2024.11.6
|
117 |
+
requests==2.32.3
|
118 |
+
safetensors==0.4.5
|
119 |
+
scipy==1.14.1
|
120 |
+
simple-websocket==1.1.0
|
121 |
+
simplejson==3.19.3
|
122 |
+
six==1.17.0
|
123 |
+
sniffio==1.3.1
|
124 |
+
soupsieve==2.6
|
125 |
+
SQLAlchemy==2.0.36
|
126 |
+
starlette==0.41.3
|
127 |
+
striprtf==0.0.26
|
128 |
+
syncer==2.0.3
|
129 |
+
tenacity==8.5.0
|
130 |
+
tiktoken==0.8.0
|
131 |
+
tokenizers==0.21.0
|
132 |
+
tomli==2.2.1
|
133 |
+
tools==0.1.9
|
134 |
+
tqdm==4.67.1
|
135 |
+
traits==6.4.3
|
136 |
+
transformers==4.47.0
|
137 |
+
typing-inspect==0.9.0
|
138 |
+
typing_extensions==4.12.2
|
139 |
+
tzdata==2024.2
|
140 |
+
ujson==5.10.0
|
141 |
+
uptrace==1.28.2
|
142 |
+
urllib3==2.2.3
|
143 |
+
uvicorn==0.25.0
|
144 |
+
watchfiles==0.20.0
|
145 |
+
wrapt==1.17.0
|
146 |
+
wsproto==1.2.0
|
147 |
+
XlsxWriter==3.2.0
|
148 |
+
yarl==1.18.3
|
149 |
+
zipp==3.21.0
|
static/exist.css
ADDED
File without changes
|
utils.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import os
|
3 |
+
import base64
|
4 |
+
import fitz
|
5 |
+
from io import BytesIO
|
6 |
+
from PIL import Image
|
7 |
+
import requests
|
8 |
+
from llama_index.llms.nvidia import NVIDIA
|
9 |
+
from llama_index.vector_stores.milvus import MilvusVectorStore
|
10 |
+
from dotenv import load_dotenv
|
11 |
+
|
12 |
+
load_dotenv()
|
13 |
+
|
14 |
+
def set_environment_variables():
|
15 |
+
"""Set necessary environment variables."""
|
16 |
+
os.environ["NVIDIA_API_KEY"] = os.getenv("NVIDIA_API_KEY") #set API key
|
17 |
+
|
18 |
+
def get_b64_image_from_content(image_content):
|
19 |
+
"""Convert image content to base64 encoded string."""
|
20 |
+
img = Image.open(BytesIO(image_content))
|
21 |
+
if img.mode != 'RGB':
|
22 |
+
img = img.convert('RGB')
|
23 |
+
buffered = BytesIO()
|
24 |
+
img.save(buffered, format="JPEG")
|
25 |
+
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
26 |
+
|
27 |
+
def is_graph(image_content):
|
28 |
+
"""Determine if an image is a graph, plot, chart, or table."""
|
29 |
+
res = describe_image(image_content)
|
30 |
+
return any(keyword in res.lower() for keyword in ["graph", "plot", "chart", "table"])
|
31 |
+
|
32 |
+
def process_graph(image_content):
|
33 |
+
"""Process a graph image and generate a description."""
|
34 |
+
deplot_description = process_graph_deplot(image_content)
|
35 |
+
mixtral = NVIDIA(model_name="meta/llama-3.1-70b-instruct")
|
36 |
+
response = mixtral.complete("Your responsibility is to explain charts. You are an expert in describing the responses of linearized tables into plain English text for LLMs to use. Explain the following linearized table. " + deplot_description)
|
37 |
+
return response.text
|
38 |
+
|
39 |
+
def describe_image(image_content):
|
40 |
+
"""Generate a description of an image using NVIDIA API."""
|
41 |
+
image_b64 = get_b64_image_from_content(image_content)
|
42 |
+
invoke_url = "https://ai.api.nvidia.com/v1/vlm/nvidia/neva-22b"
|
43 |
+
api_key = os.getenv("NVIDIA_API_KEY")
|
44 |
+
|
45 |
+
if not api_key:
|
46 |
+
raise ValueError("NVIDIA API Key is not set. Please set the NVIDIA_API_KEY environment variable.")
|
47 |
+
|
48 |
+
headers = {
|
49 |
+
"Authorization": f"Bearer {api_key}",
|
50 |
+
"Accept": "application/json"
|
51 |
+
}
|
52 |
+
|
53 |
+
payload = {
|
54 |
+
"messages": [
|
55 |
+
{
|
56 |
+
"role": "user",
|
57 |
+
"content": f"""
|
58 |
+
Describe what you see in this image:
|
59 |
+
<img src="data:image/png;base64,{image_b64}" />
|
60 |
+
Also include:
|
61 |
+
1. Visible text extraction discovering names and description of products(can use ocr).
|
62 |
+
2. Inferred location or scene type in the image.
|
63 |
+
4. Date/time information and its location.
|
64 |
+
"""
|
65 |
+
}
|
66 |
+
],
|
67 |
+
"max_tokens": 1024,
|
68 |
+
"temperature": 0.20,
|
69 |
+
"top_p": 0.70,
|
70 |
+
"seed": 0,
|
71 |
+
"stream": False
|
72 |
+
}
|
73 |
+
|
74 |
+
response = requests.post(invoke_url, headers=headers, json=payload)
|
75 |
+
return response.json()["choices"][0]['message']['content']
|
76 |
+
|
77 |
+
def process_graph_deplot(image_content):
|
78 |
+
"""Process a graph image using NVIDIA's Deplot API."""
|
79 |
+
invoke_url = "https://ai.api.nvidia.com/v1/vlm/google/deplot"
|
80 |
+
image_b64 = get_b64_image_from_content(image_content)
|
81 |
+
api_key = os.getenv("NVIDIA_API_KEY")
|
82 |
+
|
83 |
+
if not api_key:
|
84 |
+
raise ValueError("NVIDIA API Key is not set. Please set the NVIDIA_API_KEY environment variable.")
|
85 |
+
|
86 |
+
headers = {
|
87 |
+
"Authorization": f"Bearer {api_key}",
|
88 |
+
"Accept": "application/json"
|
89 |
+
}
|
90 |
+
|
91 |
+
payload = {
|
92 |
+
"messages": [
|
93 |
+
{
|
94 |
+
"role": "user",
|
95 |
+
"content": f'Generate underlying data table of the figure below: <img src="data:image/png;base64,{image_b64}" />'
|
96 |
+
}
|
97 |
+
],
|
98 |
+
"max_tokens": 1024,
|
99 |
+
"temperature": 0.20,
|
100 |
+
"top_p": 0.20,
|
101 |
+
"stream": False
|
102 |
+
}
|
103 |
+
|
104 |
+
response = requests.post(invoke_url, headers=headers, json=payload)
|
105 |
+
return response.json()["choices"][0]['message']['content']
|
106 |
+
|
107 |
+
def extract_text_around_item(text_blocks, bbox, page_height, threshold_percentage=0.1):
|
108 |
+
"""Extract text above and below a given bounding box on a page."""
|
109 |
+
before_text, after_text = "", ""
|
110 |
+
vertical_threshold_distance = page_height * threshold_percentage
|
111 |
+
horizontal_threshold_distance = bbox.width * threshold_percentage
|
112 |
+
|
113 |
+
for block in text_blocks:
|
114 |
+
block_bbox = fitz.Rect(block[:4])
|
115 |
+
vertical_distance = min(abs(block_bbox.y1 - bbox.y0), abs(block_bbox.y0 - bbox.y1))
|
116 |
+
horizontal_overlap = max(0, min(block_bbox.x1, bbox.x1) - max(block_bbox.x0, bbox.x0))
|
117 |
+
|
118 |
+
if vertical_distance <= vertical_threshold_distance and horizontal_overlap >= -horizontal_threshold_distance:
|
119 |
+
if block_bbox.y1 < bbox.y0 and not before_text:
|
120 |
+
before_text = block[4]
|
121 |
+
elif block_bbox.y0 > bbox.y1 and not after_text:
|
122 |
+
after_text = block[4]
|
123 |
+
break
|
124 |
+
|
125 |
+
return before_text, after_text
|
126 |
+
|
127 |
+
def process_text_blocks(text_blocks, char_count_threshold=500):
|
128 |
+
"""Group text blocks based on a character count threshold."""
|
129 |
+
current_group = []
|
130 |
+
grouped_blocks = []
|
131 |
+
current_char_count = 0
|
132 |
+
|
133 |
+
for block in text_blocks:
|
134 |
+
if block[-1] == 0: # Check if the block is of text type
|
135 |
+
block_text = block[4]
|
136 |
+
block_char_count = len(block_text)
|
137 |
+
|
138 |
+
if current_char_count + block_char_count <= char_count_threshold:
|
139 |
+
current_group.append(block)
|
140 |
+
current_char_count += block_char_count
|
141 |
+
else:
|
142 |
+
if current_group:
|
143 |
+
grouped_content = "\n".join([b[4] for b in current_group])
|
144 |
+
grouped_blocks.append((current_group[0], grouped_content))
|
145 |
+
current_group = [block]
|
146 |
+
current_char_count = block_char_count
|
147 |
+
|
148 |
+
# Append the last group
|
149 |
+
if current_group:
|
150 |
+
grouped_content = "\n".join([b[4] for b in current_group])
|
151 |
+
grouped_blocks.append((current_group[0], grouped_content))
|
152 |
+
|
153 |
+
return grouped_blocks
|
154 |
+
|
155 |
+
def save_uploaded_file(uploaded_file):
|
156 |
+
"""Save an uploaded file to a temporary directory."""
|
157 |
+
temp_dir = os.path.join(os.getcwd(), "vectorstore", "ppt_references", "tmp")
|
158 |
+
os.makedirs(temp_dir, exist_ok=True)
|
159 |
+
temp_file_path = os.path.join(temp_dir, uploaded_file.name)
|
160 |
+
|
161 |
+
with open(temp_file_path, "wb") as temp_file:
|
162 |
+
temp_file.write(uploaded_file.read())
|
163 |
+
|
164 |
+
return temp_file_path
|