Spaces:
Sleeping
Sleeping
Update query_service.py
Browse files- query_service.py +342 -373
query_service.py
CHANGED
|
@@ -1,373 +1,342 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import requests
|
| 4 |
-
import base64
|
| 5 |
-
|
| 6 |
-
from
|
| 7 |
-
from langchain_community.
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
)
|
| 62 |
-
print("β
Loaded FAISS vectorstore")
|
| 63 |
-
else:
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def
|
| 82 |
-
"""
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
""
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
)
|
| 210 |
-
|
| 211 |
-
if response.status_code == 200:
|
| 212 |
-
return response.json()
|
| 213 |
-
else:
|
| 214 |
-
return {
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
"
|
| 228 |
-
|
| 229 |
-
"
|
| 230 |
-
"
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 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 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
"type": doc.metadata.get("type"),
|
| 344 |
-
"source": doc.metadata.get("source"),
|
| 345 |
-
"summary": doc.metadata.get("summary", "")[:200],
|
| 346 |
-
}
|
| 347 |
-
|
| 348 |
-
# Don't include full content for images
|
| 349 |
-
if doc.metadata.get("type") == "image":
|
| 350 |
-
doc_info["content"] = "[Base64 Image Data]"
|
| 351 |
-
else:
|
| 352 |
-
doc_info["content"] = doc.page_content[:300]
|
| 353 |
-
|
| 354 |
-
docs_info.append(doc_info)
|
| 355 |
-
|
| 356 |
-
return {
|
| 357 |
-
"question": question,
|
| 358 |
-
"answer": result.get("response", result.get("error", "No response")),
|
| 359 |
-
"retrieved_docs": docs_info,
|
| 360 |
-
"stats": {
|
| 361 |
-
"total_retrieved": len(docs),
|
| 362 |
-
"texts": len(docs_by_type['texts']),
|
| 363 |
-
"tables": len(docs_by_type['tables']),
|
| 364 |
-
"images": len(docs_by_type['images'])
|
| 365 |
-
}
|
| 366 |
-
}
|
| 367 |
-
|
| 368 |
-
except Exception as e:
|
| 369 |
-
import traceback
|
| 370 |
-
return {
|
| 371 |
-
"error": str(e),
|
| 372 |
-
"traceback": traceback.format_exc()
|
| 373 |
-
}
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import requests
|
| 4 |
+
import base64
|
| 5 |
+
import re
|
| 6 |
+
from fastapi import FastAPI
|
| 7 |
+
from langchain_community.vectorstores import FAISS
|
| 8 |
+
from langchain_community.embeddings import SentenceTransformerEmbeddings
|
| 9 |
+
from langchain_core.documents import Document
|
| 10 |
+
|
| 11 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 12 |
+
# Configuration
|
| 13 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 14 |
+
VECTOR_PATH = "./vectorstore/faiss_index"
|
| 15 |
+
DOCSTORE_PATH = "./docstore"
|
| 16 |
+
FINAL_ANSWER_URL = "https://sameer-handsome173-multi-modal.hf.space/final_answer"
|
| 17 |
+
EXTENDED_TIMEOUT = int(os.getenv("FINAL_ANSWER_TIMEOUT", 150))
|
| 18 |
+
|
| 19 |
+
app = FastAPI(title="π Multimodal RAG Query Service")
|
| 20 |
+
|
| 21 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
# JSONFileStore
|
| 23 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
+
class JSONFileStore:
|
| 25 |
+
def __init__(self, store_path: str):
|
| 26 |
+
self.store_path = store_path
|
| 27 |
+
os.makedirs(self.store_path, exist_ok=True)
|
| 28 |
+
|
| 29 |
+
def mget(self, keys: list[str]) -> list[Document]:
|
| 30 |
+
"""Retrieve multiple documents by their keys."""
|
| 31 |
+
documents = []
|
| 32 |
+
for key in keys:
|
| 33 |
+
file_path = os.path.join(self.store_path, f"{key}.json")
|
| 34 |
+
if os.path.exists(file_path):
|
| 35 |
+
try:
|
| 36 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 37 |
+
doc_dict = json.load(f)
|
| 38 |
+
documents.append(
|
| 39 |
+
Document(page_content=doc_dict["page_content"], metadata=doc_dict["metadata"])
|
| 40 |
+
)
|
| 41 |
+
except Exception as e:
|
| 42 |
+
print(f"Error loading {key}: {e}")
|
| 43 |
+
documents.append(None)
|
| 44 |
+
else:
|
| 45 |
+
documents.append(None)
|
| 46 |
+
return documents
|
| 47 |
+
|
| 48 |
+
# βββββββββββββββββββοΏ½οΏ½βββββββββββββββββββββββββββ
|
| 49 |
+
# Initialize embeddings, vectorstore, docstore
|
| 50 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
+
print("π Loading embedding model...")
|
| 52 |
+
try:
|
| 53 |
+
embedding_fn = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 54 |
+
print("β
Embedding model loaded")
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"β Error loading embeddings: {e}")
|
| 57 |
+
raise
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
if os.path.exists(VECTOR_PATH):
|
| 61 |
+
vectorstore = FAISS.load_local(VECTOR_PATH, embedding_fn, allow_dangerous_deserialization=True)
|
| 62 |
+
print("β
Loaded FAISS vectorstore")
|
| 63 |
+
else:
|
| 64 |
+
raise FileNotFoundError("Vectorstore not found")
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print(f"β Error loading vectorstore: {e}")
|
| 67 |
+
raise
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
if not os.path.exists(DOCSTORE_PATH):
|
| 71 |
+
raise FileNotFoundError("Docstore not found")
|
| 72 |
+
store = JSONFileStore(DOCSTORE_PATH)
|
| 73 |
+
print("β
Loaded JSONFileStore")
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f"β Error loading docstore: {e}")
|
| 76 |
+
raise
|
| 77 |
+
|
| 78 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 79 |
+
# Response cleaning helper
|
| 80 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 81 |
+
def clean_response_text(text: str) -> str:
|
| 82 |
+
"""Clean the model's response to remove hashtags, emojis, repetitions and weird tails."""
|
| 83 |
+
if not text:
|
| 84 |
+
return text
|
| 85 |
+
|
| 86 |
+
# Remove hashtags and URLs
|
| 87 |
+
text = re.sub(r"#\S+", "", text)
|
| 88 |
+
text = re.sub(r"http\S+", "", text)
|
| 89 |
+
|
| 90 |
+
# Remove non-ASCII characters (emojis, special symbols)
|
| 91 |
+
text = text.encode("ascii", "ignore").decode()
|
| 92 |
+
|
| 93 |
+
# Remove repeated words sequences (e.g. "word word word")
|
| 94 |
+
text = re.sub(r"\b(\w+)( \1\b)+", r"\1", text, flags=re.IGNORECASE)
|
| 95 |
+
|
| 96 |
+
# Collapse multiple newlines and spaces
|
| 97 |
+
text = re.sub(r"\n{2,}", "\n", text)
|
| 98 |
+
text = re.sub(r" {2,}", " ", text).strip()
|
| 99 |
+
|
| 100 |
+
# Remove trailing model apology lines or noisy tails
|
| 101 |
+
text = re.sub(r"I'm sorry.*", "", text, flags=re.IGNORECASE)
|
| 102 |
+
|
| 103 |
+
return text.strip()
|
| 104 |
+
|
| 105 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 106 |
+
# Helpers for parsing, retrieval and final call
|
| 107 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 108 |
+
def parse_docs(docs: list[Document]) -> dict:
|
| 109 |
+
"""
|
| 110 |
+
Split retrieved documents into images, texts, and tables.
|
| 111 |
+
Returns dict with lists: {"images": [...], "texts": [...], "tables": [...]}
|
| 112 |
+
"""
|
| 113 |
+
images, texts, tables = [], [], []
|
| 114 |
+
|
| 115 |
+
for doc in docs:
|
| 116 |
+
doc_type = doc.metadata.get("type", "text")
|
| 117 |
+
if doc_type == "image" and doc.metadata.get("is_base64", False):
|
| 118 |
+
# store base64 string
|
| 119 |
+
images.append(doc.page_content)
|
| 120 |
+
elif doc_type == "table":
|
| 121 |
+
tables.append(doc.page_content)
|
| 122 |
+
else:
|
| 123 |
+
texts.append(doc.page_content)
|
| 124 |
+
|
| 125 |
+
return {"images": images, "texts": texts, "tables": tables}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def retrieve_documents(query: str, k: int = 5) -> list[Document]:
|
| 129 |
+
"""
|
| 130 |
+
Retrieve documents:
|
| 131 |
+
1. Search vectorstore for similar summaries
|
| 132 |
+
2. Collect unique doc_ids from results (avoid duplicates)
|
| 133 |
+
3. Retrieve originals from docstore
|
| 134 |
+
"""
|
| 135 |
+
try:
|
| 136 |
+
similar_docs = vectorstore.similarity_search(query, k=k)
|
| 137 |
+
if not similar_docs:
|
| 138 |
+
print("β οΈ No similar documents found")
|
| 139 |
+
return []
|
| 140 |
+
|
| 141 |
+
doc_ids = []
|
| 142 |
+
for doc in similar_docs:
|
| 143 |
+
doc_id = doc.metadata.get("doc_id")
|
| 144 |
+
if doc_id and doc_id not in doc_ids:
|
| 145 |
+
doc_ids.append(doc_id)
|
| 146 |
+
|
| 147 |
+
if not doc_ids:
|
| 148 |
+
print("β οΈ No doc_ids found in metadata")
|
| 149 |
+
return []
|
| 150 |
+
|
| 151 |
+
print(f"π Found {len(doc_ids)} unique doc_ids")
|
| 152 |
+
|
| 153 |
+
original_docs = store.mget(doc_ids)
|
| 154 |
+
original_docs = [d for d in original_docs if d is not None]
|
| 155 |
+
print(f"π Retrieved {len(original_docs)} unique documents")
|
| 156 |
+
|
| 157 |
+
return original_docs
|
| 158 |
+
|
| 159 |
+
except Exception as e:
|
| 160 |
+
print(f"β Error in retrieval: {e}")
|
| 161 |
+
return []
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def build_context_and_images(docs_by_type: dict) -> tuple[str, list[str]]:
|
| 165 |
+
"""
|
| 166 |
+
Build context text from texts and tables, and collect image base64 strings.
|
| 167 |
+
Returns: (context_text, list_of_base64_images)
|
| 168 |
+
"""
|
| 169 |
+
context_parts = []
|
| 170 |
+
|
| 171 |
+
# Add text documents
|
| 172 |
+
for i, text_content in enumerate(docs_by_type.get("texts", []), 1):
|
| 173 |
+
context_parts.append(f"--- Text Document {i} ---\n{text_content}")
|
| 174 |
+
|
| 175 |
+
# Add table documents
|
| 176 |
+
for i, table_content in enumerate(docs_by_type.get("tables", []), 1):
|
| 177 |
+
context_parts.append(f"--- Table {i} ---\n{table_content}")
|
| 178 |
+
|
| 179 |
+
context_text = "\n\n".join(context_parts).strip()
|
| 180 |
+
images_b64 = docs_by_type.get("images", [])
|
| 181 |
+
|
| 182 |
+
return context_text, images_b64
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def call_final_answer_endpoint(context: str, question: str, images_b64: list[str]) -> dict:
|
| 186 |
+
"""
|
| 187 |
+
Call the /final_answer endpoint with context, question, and images.
|
| 188 |
+
Uses extended timeout to allow for slow multimodal inference.
|
| 189 |
+
"""
|
| 190 |
+
try:
|
| 191 |
+
# Make prompt instruction clearer for concise output
|
| 192 |
+
data = {
|
| 193 |
+
"context": context,
|
| 194 |
+
"question": f"Answer concisely and without hashtags or emojis.\n\nQuestion: {question}"
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
files = []
|
| 198 |
+
if images_b64:
|
| 199 |
+
for i, img_b64 in enumerate(images_b64):
|
| 200 |
+
try:
|
| 201 |
+
img_bytes = base64.b64decode(img_b64)
|
| 202 |
+
files.append(("images", (f"image_{i}.jpg", img_bytes, "image/jpeg")))
|
| 203 |
+
except Exception as e:
|
| 204 |
+
print(f"β οΈ Error decoding image {i}: {e}")
|
| 205 |
+
|
| 206 |
+
if files:
|
| 207 |
+
response = requests.post(FINAL_ANSWER_URL, data=data, files=files, timeout=EXTENDED_TIMEOUT)
|
| 208 |
+
else:
|
| 209 |
+
response = requests.post(FINAL_ANSWER_URL, data=data, timeout=EXTENDED_TIMEOUT)
|
| 210 |
+
|
| 211 |
+
if response.status_code == 200:
|
| 212 |
+
return response.json()
|
| 213 |
+
else:
|
| 214 |
+
return {"error": f"API returned status {response.status_code}", "details": response.text}
|
| 215 |
+
|
| 216 |
+
except Exception as e:
|
| 217 |
+
return {"error": f"Error calling final_answer endpoint: {str(e)}"}
|
| 218 |
+
|
| 219 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 220 |
+
# FastAPI endpoints
|
| 221 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 222 |
+
@app.get("/")
|
| 223 |
+
def home():
|
| 224 |
+
return {
|
| 225 |
+
"message": "β
Multimodal RAG Query Service is running",
|
| 226 |
+
"timeout_seconds": EXTENDED_TIMEOUT,
|
| 227 |
+
"endpoints": {
|
| 228 |
+
"query": "/query?question=Your+Question",
|
| 229 |
+
"query_with_details": "/query_with_details?question=Your+Question",
|
| 230 |
+
"stats": "/stats",
|
| 231 |
+
},
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@app.get("/stats")
|
| 236 |
+
def get_stats():
|
| 237 |
+
try:
|
| 238 |
+
vector_count = vectorstore.index.ntotal if hasattr(vectorstore, "index") else 0
|
| 239 |
+
docstore_files = len([f for f in os.listdir(DOCSTORE_PATH) if f.endswith(".json")]) if os.path.exists(DOCSTORE_PATH) else 0
|
| 240 |
+
return {"status": "ready", "vectorstore_count": vector_count, "docstore_count": docstore_files}
|
| 241 |
+
except Exception as e:
|
| 242 |
+
return {"status": "error", "error": str(e)}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@app.post("/query")
|
| 246 |
+
async def query_rag(question: str, k: int = 5):
|
| 247 |
+
"""
|
| 248 |
+
Query the Multimodal RAG system:
|
| 249 |
+
1. Search vectorstore for relevant summaries
|
| 250 |
+
2. Retrieve original documents (text + tables + images)
|
| 251 |
+
3. Parse into texts, tables, and images
|
| 252 |
+
4. Call final_answer endpoint with all content
|
| 253 |
+
5. Return cleaned answer
|
| 254 |
+
"""
|
| 255 |
+
try:
|
| 256 |
+
print(f"\nπ Query: {question}")
|
| 257 |
+
|
| 258 |
+
docs = retrieve_documents(question, k=k)
|
| 259 |
+
if not docs:
|
| 260 |
+
return {"question": question, "answer": "No relevant documents found. Please ingest documents first.", "retrieved_docs": 0}
|
| 261 |
+
|
| 262 |
+
docs_by_type = parse_docs(docs)
|
| 263 |
+
print(f"π Parsed: {len(docs_by_type['texts'])} texts, {len(docs_by_type['tables'])} tables, {len(docs_by_type['images'])} images")
|
| 264 |
+
|
| 265 |
+
context_text, images_b64 = build_context_and_images(docs_by_type)
|
| 266 |
+
print("π Calling final_answer endpoint...")
|
| 267 |
+
result = call_final_answer_endpoint(context_text, question, images_b64)
|
| 268 |
+
|
| 269 |
+
if "error" in result:
|
| 270 |
+
return {
|
| 271 |
+
"question": question,
|
| 272 |
+
"error": result["error"],
|
| 273 |
+
"details": result.get("details"),
|
| 274 |
+
"retrieved_docs": len(docs),
|
| 275 |
+
"context_preview": context_text[:300] if context_text else "No context"
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
cleaned_answer = clean_response_text(result.get("response", "No response generated"))
|
| 279 |
+
|
| 280 |
+
return {
|
| 281 |
+
"question": question,
|
| 282 |
+
"answer": cleaned_answer,
|
| 283 |
+
"retrieved_docs": len(docs),
|
| 284 |
+
"docs_info": {
|
| 285 |
+
"texts": len(docs_by_type["texts"]),
|
| 286 |
+
"tables": len(docs_by_type["tables"]),
|
| 287 |
+
"images": len(docs_by_type["images"]),
|
| 288 |
+
},
|
| 289 |
+
"context_preview": context_text[:300] if context_text else "No context",
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
except Exception as e:
|
| 293 |
+
import traceback
|
| 294 |
+
return {"question": question, "error": str(e), "traceback": traceback.format_exc()}
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@app.post("/query_with_details")
|
| 298 |
+
async def query_with_details(question: str, k: int = 5):
|
| 299 |
+
"""Query with detailed document information"""
|
| 300 |
+
try:
|
| 301 |
+
print(f"\nπ Detailed Query: {question}")
|
| 302 |
+
|
| 303 |
+
docs = retrieve_documents(question, k=k)
|
| 304 |
+
if not docs:
|
| 305 |
+
return {"question": question, "answer": "No relevant documents found.", "retrieved_docs": []}
|
| 306 |
+
|
| 307 |
+
docs_by_type = parse_docs(docs)
|
| 308 |
+
context_text, images_b64 = build_context_and_images(docs_by_type)
|
| 309 |
+
|
| 310 |
+
result = call_final_answer_endpoint(context_text, question, images_b64)
|
| 311 |
+
|
| 312 |
+
if "error" in result:
|
| 313 |
+
return {"question": question, "error": result["error"], "details": result.get("details")}
|
| 314 |
+
|
| 315 |
+
docs_info = []
|
| 316 |
+
for doc in docs:
|
| 317 |
+
doc_info = {
|
| 318 |
+
"doc_id": doc.metadata.get("doc_id"),
|
| 319 |
+
"type": doc.metadata.get("type"),
|
| 320 |
+
"source": doc.metadata.get("source"),
|
| 321 |
+
"summary": doc.metadata.get("summary", "")[:200],
|
| 322 |
+
}
|
| 323 |
+
doc_info["content"] = "[Base64 Image Data]" if doc.metadata.get("type") == "image" else doc.page_content[:300]
|
| 324 |
+
docs_info.append(doc_info)
|
| 325 |
+
|
| 326 |
+
cleaned_answer = clean_response_text(result.get("response", "No response generated"))
|
| 327 |
+
|
| 328 |
+
return {
|
| 329 |
+
"question": question,
|
| 330 |
+
"answer": cleaned_answer,
|
| 331 |
+
"retrieved_docs": docs_info,
|
| 332 |
+
"stats": {
|
| 333 |
+
"total_retrieved": len(docs),
|
| 334 |
+
"texts": len(docs_by_type["texts"]),
|
| 335 |
+
"tables": len(docs_by_type["tables"]),
|
| 336 |
+
"images": len(docs_by_type["images"]),
|
| 337 |
+
},
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
except Exception as e:
|
| 341 |
+
import traceback
|
| 342 |
+
return {"error": str(e), "traceback": traceback.format_exc()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|