Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -51,6 +51,18 @@ load_dotenv()
|
|
| 51 |
vector_cache = {}
|
| 52 |
ml_models = {}
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
@asynccontextmanager
|
| 55 |
async def lifespan(app: FastAPI):
|
| 56 |
# This code runs ONCE when the application starts up
|
|
@@ -67,7 +79,8 @@ async def lifespan(app: FastAPI):
|
|
| 67 |
|
| 68 |
# if not nvidia_api_key:
|
| 69 |
# raise RuntimeError("CRITICAL: Missing nvidia api key in environment secrets!")
|
| 70 |
-
|
|
|
|
| 71 |
# Load models into the shared dictionary
|
| 72 |
ml_models["embedder"] = HuggingFaceEmbeddings(
|
| 73 |
# model_name="BAAI/bge-large-en-v1.5", #better but lil slower
|
|
@@ -109,11 +122,26 @@ Answer the query , do not add extra information irrelevently.
|
|
| 109 |
response: Yes, the policy covers maternity expenses, including childbirth and lawful medical termination of pregnancy. To be eligible, the female insured person must have been continuously covered for at least 24 months. The benefit is limited to two deliveries or terminations during the policy period.
|
| 110 |
"""
|
| 111 |
)
|
|
|
|
|
|
|
| 112 |
print("✅ Models and prompt loaded successfully!")
|
| 113 |
except Exception as e:
|
| 114 |
print("❌ Lifespan error:", str(e))
|
| 115 |
raise e
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
yield
|
| 118 |
print("🧹 Cleaning up.")
|
| 119 |
ml_models.clear()
|
|
@@ -204,16 +232,16 @@ async def run_hackrx(req: RunRequest):
|
|
| 204 |
keyword_retriever = BM25Retriever.from_documents(chunks)
|
| 205 |
keyword_retriever.k = 8
|
| 206 |
# dense_retriever = Chroma.from_documents(documents=chunks, embedding=ml_models["embedder"]).as_retriever()
|
| 207 |
-
ensemble_retriever = EnsembleRetriever(retrievers=[keyword_retriever, dense_retriever], weights=[0.4, 0.6],search_kwargs={"k":
|
| 208 |
### to make it faster we are now using our built reranker thats why commenting the code below
|
| 209 |
-
compression_retriever = ContextualCompressionRetriever(
|
| 210 |
-
|
| 211 |
-
)
|
| 212 |
|
| 213 |
|
| 214 |
# Define the RAG chain using pre-loaded components
|
| 215 |
hybrid_rag_chain = (
|
| 216 |
-
{"context": itemgetter("full_query") |
|
| 217 |
| ml_models["prompt_template"]
|
| 218 |
| ml_models["llm"]
|
| 219 |
)
|
|
|
|
| 51 |
vector_cache = {}
|
| 52 |
ml_models = {}
|
| 53 |
|
| 54 |
+
PRELOAD_URLS = [
|
| 55 |
+
"https://hackrx.blob.core.windows.net/assets/Arogya%20Sanjeevani%20Policy%20-%20CIN%20-%20U10200WB1906GOI001713%201.pdf?sv=2023-01-03&st=2025-07-21T08%3A29%3A02Z&se=2025-09-22T08%3A29%3A00Z&sr=b&sp=r&sig=nzrz1K9Iurt%2BBXom%2FB%2BMPTFMFP3PRnIvEsipAX10Ig4%3D",
|
| 56 |
+
"https://hackrx.blob.core.windows.net/assets/Super_Splendor_(Feb_2023).pdf?sv=2023-01-03&st=2025-07-21T08%3A10%3A00Z&se=2025-09-22T08%3A10%3A00Z&sr=b&sp=r&sig=vhHrl63YtrEOCsAy%2BpVKr20b3ZUo5HMz1lF9%2BJh6LQ0%3D",
|
| 57 |
+
"https://hackrx.blob.core.windows.net/assets/Family%20Medicare%20Policy%20(UIN-%20UIIHLIP22070V042122)%201.pdf?sv=2023-01-03&st=2025-07-22T10%3A17%3A39Z&se=2025-08-23T10%3A17%3A00Z&sr=b&sp=r&sig=dA7BEMIZg3WcePcckBOb4QjfxK%2B4rIfxBs2%2F%2BNwoPjQ%3D",
|
| 58 |
+
"https://hackrx.blob.core.windows.net/assets/indian_constitution.pdf?sv=2023-01-03&st=2025-07-28T06%3A42%3A00Z&se=2026-11-29T06%3A42%3A00Z&sr=b&sp=r&sig=5Gs%2FOXqP3zY00lgciu4BZjDV5QjTDIx7fgnfdz6Pu24%3D",
|
| 59 |
+
"https://hackrx.blob.core.windows.net/assets/UNI%20GROUP%20HEALTH%20INSURANCE%20POLICY%20-%20UIIHLGP26043V022526%201.pdf?sv=2023-01-03&spr=https&st=2025-07-31T17%3A06%3A03Z&se=2026-08-01T17%3A06%3A00Z&sr=b&sp=r&sig=wLlooaThgRx91i2z4WaeggT0qnuUUEzIUKj42GsvMfg%3D",
|
| 60 |
+
"https://hackrx.blob.core.windows.net/assets/Happy%20Family%20Floater%20-%202024%20OICHLIP25046V062425%201.pdf?sv=2023-01-03&spr=https&st=2025-07-31T17%3A24%3A30Z&se=2026-08-01T17%3A24%3A00Z&sr=b&sp=r&sig=VNMTTQUjdXGYb2F4Di4P0zNvmM2rTBoEHr%2BnkUXIqpQ%3D",
|
| 61 |
+
"https://dn790007.ca.archive.org/0/items/newtonspmathema00newtrich/newtonspmathema00newtrich.pdf"
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
|
| 66 |
@asynccontextmanager
|
| 67 |
async def lifespan(app: FastAPI):
|
| 68 |
# This code runs ONCE when the application starts up
|
|
|
|
| 79 |
|
| 80 |
# if not nvidia_api_key:
|
| 81 |
# raise RuntimeError("CRITICAL: Missing nvidia api key in environment secrets!")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
# Load models into the shared dictionary
|
| 85 |
ml_models["embedder"] = HuggingFaceEmbeddings(
|
| 86 |
# model_name="BAAI/bge-large-en-v1.5", #better but lil slower
|
|
|
|
| 122 |
response: Yes, the policy covers maternity expenses, including childbirth and lawful medical termination of pregnancy. To be eligible, the female insured person must have been continuously covered for at least 24 months. The benefit is limited to two deliveries or terminations during the policy period.
|
| 123 |
"""
|
| 124 |
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
print("✅ Models and prompt loaded successfully!")
|
| 128 |
except Exception as e:
|
| 129 |
print("❌ Lifespan error:", str(e))
|
| 130 |
raise e
|
| 131 |
|
| 132 |
+
# Preload vectorstores for all URLs
|
| 133 |
+
for url in PRELOAD_URLS:
|
| 134 |
+
doc_url = str(url)
|
| 135 |
+
|
| 136 |
+
if doc_url not in vector_cache:
|
| 137 |
+
print(f"📄 Processing new document: {doc_url}")
|
| 138 |
+
chunks = load_and_chunk(doc_url)
|
| 139 |
+
|
| 140 |
+
# Build vectorstore & save to cache
|
| 141 |
+
vectorstore = await FAISS.afrom_documents(documents=chunks, embedding=ml_models["embedder"])
|
| 142 |
+
vector_cache[doc_url] = vectorstore # store in memory cache
|
| 143 |
+
print(f"✅ Vectorstore cached for: {doc_url}")
|
| 144 |
+
|
| 145 |
yield
|
| 146 |
print("🧹 Cleaning up.")
|
| 147 |
ml_models.clear()
|
|
|
|
| 232 |
keyword_retriever = BM25Retriever.from_documents(chunks)
|
| 233 |
keyword_retriever.k = 8
|
| 234 |
# dense_retriever = Chroma.from_documents(documents=chunks, embedding=ml_models["embedder"]).as_retriever()
|
| 235 |
+
ensemble_retriever = EnsembleRetriever(retrievers=[keyword_retriever, dense_retriever], weights=[0.4, 0.6],search_kwargs={"k": 12})
|
| 236 |
### to make it faster we are now using our built reranker thats why commenting the code below
|
| 237 |
+
# compression_retriever = ContextualCompressionRetriever(
|
| 238 |
+
# base_retriever=ensemble_retriever, base_compressor=ml_models["reranker_compressor"]
|
| 239 |
+
# )
|
| 240 |
|
| 241 |
|
| 242 |
# Define the RAG chain using pre-loaded components
|
| 243 |
hybrid_rag_chain = (
|
| 244 |
+
{"context": itemgetter("full_query") | ensemble_retriever, "full_query": itemgetter("full_query")}
|
| 245 |
| ml_models["prompt_template"]
|
| 246 |
| ml_models["llm"]
|
| 247 |
)
|