Spaces:
Sleeping
Sleeping
Update src/rag_system.py
Browse files- src/rag_system.py +264 -320
src/rag_system.py
CHANGED
|
@@ -1,16 +1,24 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
|
| 4 |
"""
|
| 5 |
from typing import List, Dict
|
| 6 |
from langchain_openai import ChatOpenAI
|
| 7 |
-
from langchain_core.messages import HumanMessage, SystemMessage
|
| 8 |
-
import
|
| 9 |
-
from config import
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
class MultimodalRAG:
|
| 13 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
def __init__(self, api_key: str = None, debug: bool = True):
|
| 16 |
api_key = api_key or OPENAI_API_KEY
|
|
@@ -25,10 +33,10 @@ class MultimodalRAG:
|
|
| 25 |
|
| 26 |
self.conversation_history = []
|
| 27 |
self.language = LANGUAGE
|
| 28 |
-
self.
|
| 29 |
|
| 30 |
if self.debug:
|
| 31 |
-
print("β
|
| 32 |
|
| 33 |
def _debug_print(self, label: str, data: any):
|
| 34 |
"""Print debug information"""
|
|
@@ -36,354 +44,290 @@ class MultimodalRAG:
|
|
| 36 |
print(f"\nπ DEBUG [{label}]:")
|
| 37 |
if isinstance(data, (list, dict)):
|
| 38 |
print(f" Type: {type(data).__name__}")
|
| 39 |
-
print(f" Content: {str(data)[:
|
| 40 |
else:
|
| 41 |
print(f" {data}")
|
| 42 |
|
| 43 |
-
def
|
| 44 |
-
"""
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
content_type = result.get('type', 'unknown')
|
| 56 |
-
content = result.get('content', '')
|
| 57 |
-
distance = result.get('distance', 0)
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
elif content_type == 'table':
|
| 63 |
-
table_count += 1
|
| 64 |
-
else:
|
| 65 |
-
text_count += 1
|
| 66 |
|
| 67 |
-
self.
|
| 68 |
-
f"
|
| 69 |
-
content[:100]
|
| 70 |
-
)
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
self._debug_print("
|
| 80 |
-
f"Text: {text_count}, Images: {image_count}, Tables: {table_count}")
|
| 81 |
-
self._debug_print("Total Context Length", len(context))
|
| 82 |
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
# Build context from search results
|
| 91 |
-
context = self._build_context_prompt(search_results)
|
| 92 |
-
|
| 93 |
-
# Create system message
|
| 94 |
-
system_message = SystemMessage(
|
| 95 |
-
content=f"""You are a helpful assistant that answers questions about documents.
|
| 96 |
-
You work with documents that contain text, tables, and images.
|
| 97 |
-
Language: {self.language}
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
response = self.llm.invoke([system_message] + self.conversation_history)
|
| 117 |
-
|
| 118 |
-
# Add response to history
|
| 119 |
-
self.conversation_history.append(response)
|
| 120 |
-
|
| 121 |
-
self._debug_print("Response Length", len(response.content))
|
| 122 |
-
|
| 123 |
-
# Keep conversation history manageable (last 10 messages)
|
| 124 |
-
if len(self.conversation_history) > 10:
|
| 125 |
-
self.conversation_history = self.conversation_history[-10:]
|
| 126 |
-
|
| 127 |
-
return response.content
|
| 128 |
|
| 129 |
-
|
| 130 |
-
self._debug_print("ERROR in answer_question", str(e))
|
| 131 |
-
print(f"Error generating answer: {e}")
|
| 132 |
-
return f"Error: Could not generate answer. {str(e)}"
|
| 133 |
|
| 134 |
-
def
|
| 135 |
-
"""
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
f"Text length: {len(document_content)}, Images: {len(images)}, Tables: {len(tables)}")
|
| 144 |
-
|
| 145 |
-
# Log entry
|
| 146 |
-
log_entry = {
|
| 147 |
-
'document_text_length': len(document_content),
|
| 148 |
-
'total_images': len(images),
|
| 149 |
-
'total_tables': len(tables),
|
| 150 |
-
'images_with_ocr': 0,
|
| 151 |
-
'images_empty_ocr': 0,
|
| 152 |
-
'ocr_texts': [],
|
| 153 |
-
'table_texts': [],
|
| 154 |
-
'summary_prompt_length': 0,
|
| 155 |
-
'summary_result': '',
|
| 156 |
-
'summary_result_length': 0
|
| 157 |
-
}
|
| 158 |
-
|
| 159 |
-
# Extract OCR text from images
|
| 160 |
-
image_ocr_texts = []
|
| 161 |
-
for idx, img in enumerate(images):
|
| 162 |
-
ocr_text = img.get('ocr_text', '')
|
| 163 |
-
if ocr_text:
|
| 164 |
-
image_ocr_texts.append(f"Image {idx}: {ocr_text}")
|
| 165 |
-
log_entry['images_with_ocr'] += 1
|
| 166 |
-
log_entry['ocr_texts'].append({
|
| 167 |
-
'image_index': idx,
|
| 168 |
-
'ocr_length': len(ocr_text),
|
| 169 |
-
'ocr_content': ocr_text[:200] # First 200 chars
|
| 170 |
-
})
|
| 171 |
-
self._debug_print(f"Image {idx} OCR", ocr_text[:100])
|
| 172 |
-
else:
|
| 173 |
-
log_entry['images_empty_ocr'] += 1
|
| 174 |
-
log_entry['ocr_texts'].append({
|
| 175 |
-
'image_index': idx,
|
| 176 |
-
'ocr_length': 0,
|
| 177 |
-
'ocr_content': 'EMPTY'
|
| 178 |
-
})
|
| 179 |
-
self._debug_print(f"Image {idx} OCR", "β οΈ EMPTY - No OCR text extracted!")
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
for idx, tbl in enumerate(tables):
|
| 184 |
-
table_content = tbl.get('content', '')
|
| 185 |
-
if table_content:
|
| 186 |
-
table_texts.append(f"Table {idx}:\n{table_content}")
|
| 187 |
-
log_entry['table_texts'].append({
|
| 188 |
-
'table_index': idx,
|
| 189 |
-
'table_length': len(table_content),
|
| 190 |
-
'table_content': table_content[:200]
|
| 191 |
-
})
|
| 192 |
-
self._debug_print(f"Table {idx} Content", table_content[:100])
|
| 193 |
-
else:
|
| 194 |
-
self._debug_print(f"Table {idx} Content", "β οΈ EMPTY - No table content!")
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
| 198 |
|
| 199 |
-
|
| 200 |
-
{
|
| 201 |
|
| 202 |
-
"""
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
4. Key information from images (if present)
|
| 222 |
-
5. Key information from tables (if present)
|
| 223 |
-
6. Overall document purpose"""
|
| 224 |
-
|
| 225 |
-
log_entry['summary_prompt_length'] = len(summary_prompt)
|
| 226 |
-
|
| 227 |
-
self._debug_print("Summary Prompt Length", len(summary_prompt))
|
| 228 |
-
self._debug_print("Summary Prompt Content", summary_prompt[:200])
|
| 229 |
-
|
| 230 |
-
message = HumanMessage(content=summary_prompt)
|
| 231 |
-
self._debug_print("Calling LLM for summarization", f"Model: {OPENAI_MODEL}")
|
| 232 |
-
|
| 233 |
-
response = self.llm.invoke([message])
|
| 234 |
-
summary = response.content
|
| 235 |
-
|
| 236 |
-
log_entry['summary_result'] = summary
|
| 237 |
-
log_entry['summary_result_length'] = len(summary)
|
| 238 |
-
|
| 239 |
-
self._debug_print("Summary Response Length", len(summary))
|
| 240 |
-
|
| 241 |
-
# PRINT DETAILED SUMMARIZATION LOG
|
| 242 |
-
self._print_summarization_log(log_entry)
|
| 243 |
-
|
| 244 |
-
# Store in log
|
| 245 |
-
self.summarization_log.append(log_entry)
|
| 246 |
-
|
| 247 |
-
return summary
|
| 248 |
|
| 249 |
-
|
| 250 |
-
self._debug_print("ERROR in summarize_document", str(e))
|
| 251 |
-
print(f"Error summarizing document: {e}")
|
| 252 |
-
return f"Error: Could not summarize document. {str(e)}"
|
| 253 |
|
| 254 |
-
def
|
| 255 |
-
"""
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
print(f" Table {idx}: {length} characters")
|
| 291 |
-
print(f" Content: {content}...")
|
| 292 |
|
| 293 |
-
#
|
| 294 |
-
print("\n
|
| 295 |
-
print(f"
|
| 296 |
-
print(f" Includes images: {'β
Yes' if log_entry['ocr_texts'] else 'β No'}")
|
| 297 |
-
print(f" Includes tables: {'β
Yes' if log_entry['table_texts'] else 'β No'}")
|
| 298 |
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
print(f" Length: {log_entry['summary_result_length']:,} characters")
|
| 302 |
-
print(f" Content:")
|
| 303 |
-
print(" " + "-"*66)
|
| 304 |
|
| 305 |
-
#
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
| 309 |
|
| 310 |
-
|
| 311 |
-
print(f"
|
| 312 |
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
"""Get all summarization logs"""
|
| 319 |
-
return self.summarization_log
|
| 320 |
-
|
| 321 |
-
def print_summarization_history(self):
|
| 322 |
-
"""Print all summarization logs"""
|
| 323 |
-
print("\nπ SUMMARIZATION HISTORY:")
|
| 324 |
-
print(f"Total summarizations: {len(self.summarization_log)}")
|
| 325 |
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
'total_results': len(search_results),
|
| 336 |
-
'by_type': {'text': 0, 'image': 0, 'table': 0},
|
| 337 |
-
'average_distance': 0,
|
| 338 |
-
'images_with_content': 0,
|
| 339 |
-
'images_empty': 0,
|
| 340 |
-
'details': []
|
| 341 |
}
|
| 342 |
|
| 343 |
-
|
|
|
|
| 344 |
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
else:
|
| 360 |
-
analysis['images_empty'] += 1
|
| 361 |
-
|
| 362 |
-
analysis['details'].append({
|
| 363 |
-
'index': idx,
|
| 364 |
-
'type': content_type,
|
| 365 |
-
'distance': distance,
|
| 366 |
-
'content_length': len(content),
|
| 367 |
-
'has_content': bool(content.strip())
|
| 368 |
-
})
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
|
| 373 |
-
|
| 374 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
|
| 376 |
def clear_history(self):
|
| 377 |
"""Clear conversation history"""
|
| 378 |
self.conversation_history = []
|
| 379 |
if self.debug:
|
| 380 |
-
print("β
Conversation history cleared")
|
| 381 |
-
|
| 382 |
-
def get_history(self) -> List:
|
| 383 |
-
"""Get conversation history"""
|
| 384 |
-
return self.conversation_history
|
| 385 |
-
|
| 386 |
-
def toggle_debug(self, enabled: bool):
|
| 387 |
-
"""Toggle debug mode on/off"""
|
| 388 |
-
self.debug = enabled
|
| 389 |
-
print(f"π Debug mode: {'ON' if enabled else 'OFF'}")
|
|
|
|
| 1 |
"""
|
| 2 |
+
Enhanced RAG System - Individual Summarization + Vector Store Persistence
|
| 3 |
+
Summarizes each image, text chunk, and table separately, then stores results
|
| 4 |
"""
|
| 5 |
from typing import List, Dict
|
| 6 |
from langchain_openai import ChatOpenAI
|
| 7 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 8 |
+
import hashlib
|
| 9 |
+
from config import (
|
| 10 |
+
OPENAI_API_KEY, OPENAI_MODEL, TEMPERATURE, MAX_TOKENS,
|
| 11 |
+
LANGUAGE, CACHE_RESPONSES, BATCH_SEARCH_RESULTS
|
| 12 |
+
)
|
| 13 |
|
| 14 |
|
| 15 |
class MultimodalRAG:
|
| 16 |
+
"""
|
| 17 |
+
RAG system that:
|
| 18 |
+
1. Summarizes each component individually
|
| 19 |
+
2. Stores summaries in vector store
|
| 20 |
+
3. Enables fine-grained semantic search
|
| 21 |
+
"""
|
| 22 |
|
| 23 |
def __init__(self, api_key: str = None, debug: bool = True):
|
| 24 |
api_key = api_key or OPENAI_API_KEY
|
|
|
|
| 33 |
|
| 34 |
self.conversation_history = []
|
| 35 |
self.language = LANGUAGE
|
| 36 |
+
self.summaries_log = []
|
| 37 |
|
| 38 |
if self.debug:
|
| 39 |
+
print("β
EnhancedMultimodalRAG initialized")
|
| 40 |
|
| 41 |
def _debug_print(self, label: str, data: any):
|
| 42 |
"""Print debug information"""
|
|
|
|
| 44 |
print(f"\nπ DEBUG [{label}]:")
|
| 45 |
if isinstance(data, (list, dict)):
|
| 46 |
print(f" Type: {type(data).__name__}")
|
| 47 |
+
print(f" Content: {str(data)[:300]}...")
|
| 48 |
else:
|
| 49 |
print(f" {data}")
|
| 50 |
|
| 51 |
+
def summarize_image(self, image_ocr_text: str, image_idx: int) -> str:
|
| 52 |
+
"""
|
| 53 |
+
Summarize a single image's OCR text
|
| 54 |
+
Returns concise summary focused on image content
|
| 55 |
+
"""
|
| 56 |
+
if not image_ocr_text or len(image_ocr_text.strip()) < 5:
|
| 57 |
+
return f"[Image {image_idx}: No readable text or empty content]"
|
| 58 |
|
| 59 |
+
try:
|
| 60 |
+
prompt = f"""Summarize this text extracted from an image in {self.language}.
|
| 61 |
+
Keep it concise but informative. Focus on key information, data, and visual elements.
|
| 62 |
+
|
| 63 |
+
Image OCR Text:
|
| 64 |
+
{image_ocr_text}
|
| 65 |
+
|
| 66 |
+
Summary (2-3 sentences maximum):"""
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
message = HumanMessage(content=prompt)
|
| 69 |
+
response = self.llm.invoke([message])
|
| 70 |
+
summary = response.content.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
if self.debug:
|
| 73 |
+
self._debug_print(f"Image {image_idx} Summary", summary)
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
return summary
|
| 76 |
+
except Exception as e:
|
| 77 |
+
error_msg = f"[Image {image_idx}: Summarization failed - {str(e)}]"
|
| 78 |
+
print(f"Error summarizing image {image_idx}: {e}")
|
| 79 |
+
return error_msg
|
| 80 |
+
|
| 81 |
+
def summarize_text_chunks(self, text: str, chunk_size: int = 1500) -> List[Dict]:
|
| 82 |
+
"""
|
| 83 |
+
Chunk text and summarize each chunk individually
|
| 84 |
+
Returns list of {chunk_text, summary, type, index}
|
| 85 |
+
"""
|
| 86 |
+
chunks = []
|
| 87 |
+
|
| 88 |
+
# Split text into chunks
|
| 89 |
+
text_chunks = self._chunk_text(text, chunk_size=chunk_size, overlap=300)
|
| 90 |
|
| 91 |
+
self._debug_print("Text Chunking", f"Created {len(text_chunks)} chunks")
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
for idx, chunk in enumerate(text_chunks):
|
| 94 |
+
if len(chunk.strip()) < 50: # Skip very small chunks
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
# Summarize chunk
|
| 99 |
+
prompt = f"""Summarize this text chunk in {self.language}.
|
| 100 |
+
Keep it concise. Extract key points, facts, and main ideas.
|
| 101 |
|
| 102 |
+
Text Chunk:
|
| 103 |
+
{chunk}
|
| 104 |
+
|
| 105 |
+
Summary (2-3 sentences maximum):"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
message = HumanMessage(content=prompt)
|
| 108 |
+
response = self.llm.invoke([message])
|
| 109 |
+
summary = response.content.strip()
|
| 110 |
+
|
| 111 |
+
chunks.append({
|
| 112 |
+
'type': 'text_chunk',
|
| 113 |
+
'chunk_index': len(chunks),
|
| 114 |
+
'original_text': chunk[:500], # Store first 500 chars
|
| 115 |
+
'summary': summary,
|
| 116 |
+
'chunk_length': len(chunk)
|
| 117 |
+
})
|
| 118 |
+
|
| 119 |
+
if self.debug:
|
| 120 |
+
self._debug_print(f"Text Chunk {len(chunks)-1} Summary", summary)
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
print(f"Error summarizing text chunk: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
return chunks
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
def summarize_tables(self, tables: List[Dict]) -> List[Dict]:
|
| 128 |
+
"""
|
| 129 |
+
Summarize each table individually
|
| 130 |
+
Returns list of {table_content, summary, type, index}
|
| 131 |
+
"""
|
| 132 |
+
summaries = []
|
| 133 |
+
|
| 134 |
+
for idx, table in enumerate(tables):
|
| 135 |
+
table_content = table.get('content', '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
if not table_content or len(table_content.strip()) < 10:
|
| 138 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
+
try:
|
| 141 |
+
# Summarize table
|
| 142 |
+
prompt = f"""Analyze and summarize this table/structured data in {self.language}.
|
| 143 |
+
Extract key insights, row/column meanings, and important figures.
|
| 144 |
|
| 145 |
+
Table Content:
|
| 146 |
+
{table_content}
|
| 147 |
|
| 148 |
+
Summary (2-3 sentences maximum):"""
|
| 149 |
+
|
| 150 |
+
message = HumanMessage(content=prompt)
|
| 151 |
+
response = self.llm.invoke([message])
|
| 152 |
+
summary = response.content.strip()
|
| 153 |
+
|
| 154 |
+
summaries.append({
|
| 155 |
+
'type': 'table',
|
| 156 |
+
'table_index': idx,
|
| 157 |
+
'original_content': table_content[:500],
|
| 158 |
+
'summary': summary,
|
| 159 |
+
'table_length': len(table_content)
|
| 160 |
+
})
|
| 161 |
+
|
| 162 |
+
if self.debug:
|
| 163 |
+
self._debug_print(f"Table {idx} Summary", summary)
|
| 164 |
+
|
| 165 |
+
except Exception as e:
|
| 166 |
+
print(f"Error summarizing table {idx}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
return summaries
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
def summarize_images(self, images: List[Dict]) -> List[Dict]:
|
| 171 |
+
"""
|
| 172 |
+
Summarize each image individually
|
| 173 |
+
Returns list of {image_index, ocr_text, summary, type}
|
| 174 |
+
"""
|
| 175 |
+
summaries = []
|
| 176 |
|
| 177 |
+
for idx, image in enumerate(images):
|
| 178 |
+
ocr_text = image.get('ocr_text', '')
|
| 179 |
+
summary = self.summarize_image(ocr_text, idx)
|
| 180 |
+
|
| 181 |
+
summaries.append({
|
| 182 |
+
'type': 'image',
|
| 183 |
+
'image_index': idx,
|
| 184 |
+
'original_ocr': ocr_text[:500],
|
| 185 |
+
'summary': summary,
|
| 186 |
+
'ocr_length': len(ocr_text)
|
| 187 |
+
})
|
| 188 |
|
| 189 |
+
return summaries
|
| 190 |
+
|
| 191 |
+
def process_and_store_document(
|
| 192 |
+
self,
|
| 193 |
+
text: str,
|
| 194 |
+
images: List[Dict],
|
| 195 |
+
tables: List[Dict],
|
| 196 |
+
vector_store,
|
| 197 |
+
doc_id: str
|
| 198 |
+
) -> Dict:
|
| 199 |
+
"""
|
| 200 |
+
Main function: Summarize all components and store in vector store
|
| 201 |
+
Returns summary statistics
|
| 202 |
+
"""
|
| 203 |
+
print(f"\n{'='*70}")
|
| 204 |
+
print(f"PROCESSING AND STORING: {doc_id}")
|
| 205 |
+
print(f"{'='*70}")
|
| 206 |
|
| 207 |
+
results = {
|
| 208 |
+
'doc_id': doc_id,
|
| 209 |
+
'image_summaries': [],
|
| 210 |
+
'text_summaries': [],
|
| 211 |
+
'table_summaries': [],
|
| 212 |
+
'total_stored': 0
|
| 213 |
+
}
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
+
# 1. Summarize and store images
|
| 216 |
+
print(f"\nπΌοΈ PROCESSING IMAGES ({len(images)} total)")
|
| 217 |
+
print(f"{'β'*70}")
|
|
|
|
|
|
|
| 218 |
|
| 219 |
+
image_summaries = self.summarize_images(images)
|
| 220 |
+
results['image_summaries'] = image_summaries
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
+
# Store each image summary in vector store
|
| 223 |
+
image_docs = {
|
| 224 |
+
'text': ' | '.join([f"Image {s['image_index']}: {s['summary']}"
|
| 225 |
+
for s in image_summaries]),
|
| 226 |
+
'images': [],
|
| 227 |
+
'tables': []
|
| 228 |
+
}
|
| 229 |
|
| 230 |
+
for summary in image_summaries:
|
| 231 |
+
print(f" β
Image {summary['image_index']}: {summary['summary'][:50]}...")
|
| 232 |
|
| 233 |
+
if image_summaries:
|
| 234 |
+
try:
|
| 235 |
+
vector_store.add_documents(
|
| 236 |
+
image_docs,
|
| 237 |
+
f"{doc_id}_images"
|
| 238 |
+
)
|
| 239 |
+
results['total_stored'] += len(image_summaries)
|
| 240 |
+
print(f"β
Stored {len(image_summaries)} image summaries")
|
| 241 |
+
except Exception as e:
|
| 242 |
+
print(f"β Error storing image summaries: {e}")
|
| 243 |
|
| 244 |
+
# 2. Summarize and store text chunks
|
| 245 |
+
print(f"\nπ PROCESSING TEXT CHUNKS")
|
| 246 |
+
print(f"{'β'*70}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
+
text_summaries = self.summarize_text_chunks(text)
|
| 249 |
+
results['text_summaries'] = text_summaries
|
| 250 |
+
|
| 251 |
+
# Store each text chunk summary in vector store
|
| 252 |
+
text_docs = {
|
| 253 |
+
'text': ' | '.join([f"Chunk {s['chunk_index']}: {s['summary']}"
|
| 254 |
+
for s in text_summaries]),
|
| 255 |
+
'images': [],
|
| 256 |
+
'tables': []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
}
|
| 258 |
|
| 259 |
+
for summary in text_summaries:
|
| 260 |
+
print(f" β
Chunk {summary['chunk_index']}: {summary['summary'][:50]}...")
|
| 261 |
|
| 262 |
+
if text_summaries:
|
| 263 |
+
try:
|
| 264 |
+
vector_store.add_documents(
|
| 265 |
+
text_docs,
|
| 266 |
+
f"{doc_id}_text_chunks"
|
| 267 |
+
)
|
| 268 |
+
results['total_stored'] += len(text_summaries)
|
| 269 |
+
print(f"β
Stored {len(text_summaries)} text chunk summaries")
|
| 270 |
+
except Exception as e:
|
| 271 |
+
print(f"β Error storing text summaries: {e}")
|
| 272 |
+
|
| 273 |
+
# 3. Summarize and store tables
|
| 274 |
+
print(f"\nπ PROCESSING TABLES ({len(tables)} total)")
|
| 275 |
+
print(f"{'β'*70}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
+
table_summaries = self.summarize_tables(tables)
|
| 278 |
+
results['table_summaries'] = table_summaries
|
| 279 |
|
| 280 |
+
# Store each table summary in vector store
|
| 281 |
+
table_docs = {
|
| 282 |
+
'text': ' | '.join([f"Table {s['table_index']}: {s['summary']}"
|
| 283 |
+
for s in table_summaries]),
|
| 284 |
+
'images': [],
|
| 285 |
+
'tables': []
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
for summary in table_summaries:
|
| 289 |
+
print(f" β
Table {summary['table_index']}: {summary['summary'][:50]}...")
|
| 290 |
+
|
| 291 |
+
if table_summaries:
|
| 292 |
+
try:
|
| 293 |
+
vector_store.add_documents(
|
| 294 |
+
table_docs,
|
| 295 |
+
f"{doc_id}_tables"
|
| 296 |
+
)
|
| 297 |
+
results['total_stored'] += len(table_summaries)
|
| 298 |
+
print(f"β
Stored {len(table_summaries)} table summaries")
|
| 299 |
+
except Exception as e:
|
| 300 |
+
print(f"β Error storing table summaries: {e}")
|
| 301 |
+
|
| 302 |
+
# 4. Summary statistics
|
| 303 |
+
print(f"\n{'='*70}")
|
| 304 |
+
print(f"π STORAGE SUMMARY")
|
| 305 |
+
print(f"{'='*70}")
|
| 306 |
+
print(f" Images summarized & stored: {len(image_summaries)}")
|
| 307 |
+
print(f" Text chunks summarized & stored: {len(text_summaries)}")
|
| 308 |
+
print(f" Tables summarized & stored: {len(table_summaries)}")
|
| 309 |
+
print(f" Total items stored: {results['total_stored']}")
|
| 310 |
+
print(f"{'='*70}")
|
| 311 |
+
|
| 312 |
+
self.summaries_log.append(results)
|
| 313 |
+
return results
|
| 314 |
+
|
| 315 |
+
def _chunk_text(self, text: str, chunk_size: int = 1500, overlap: int = 300) -> List[str]:
|
| 316 |
+
"""Split text into overlapping chunks"""
|
| 317 |
+
chunks = []
|
| 318 |
+
start = 0
|
| 319 |
+
while start < len(text):
|
| 320 |
+
end = start + chunk_size
|
| 321 |
+
chunks.append(text[start:end])
|
| 322 |
+
start = end - overlap
|
| 323 |
+
return chunks
|
| 324 |
+
|
| 325 |
+
def get_summaries_log(self) -> List[Dict]:
|
| 326 |
+
"""Get all processing logs"""
|
| 327 |
+
return self.summaries_log
|
| 328 |
|
| 329 |
def clear_history(self):
|
| 330 |
"""Clear conversation history"""
|
| 331 |
self.conversation_history = []
|
| 332 |
if self.debug:
|
| 333 |
+
print("β
Conversation history cleared")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|