Spaces:
Runtime error
Runtime error
Commit ·
65ca4cf
1
Parent(s): 066aeeb
🚀 Deploy HackRx app with FastAPI + Docker
Browse files- .env +1 -0
- .gitattributes +1 -0
- Dockerfile +36 -0
- app/__pycache__/backend.cpython-312.pyc +0 -0
- app/__pycache__/main.cpython-312.pyc +0 -0
- app/backend.py +72 -0
- app/main.py +65 -0
- requirements.txt +8 -0
.env
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
GEMINI_API_KEY=AIzaSyBaCZ19qDVQoGglZaPASytcZQerrDeYz6c
|
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
.env
|
Dockerfile
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use lightweight Python base
|
| 2 |
+
FROM python:3.10-slim
|
| 3 |
+
|
| 4 |
+
# Set environment variables
|
| 5 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 6 |
+
ENV PYTHONUNBUFFERED=1
|
| 7 |
+
|
| 8 |
+
# Set working directory
|
| 9 |
+
WORKDIR /code
|
| 10 |
+
|
| 11 |
+
# Install dependencies
|
| 12 |
+
COPY requirements.txt .
|
| 13 |
+
RUN apt-get update && apt-get install -y \
|
| 14 |
+
build-essential \
|
| 15 |
+
libpoppler-cpp-dev \
|
| 16 |
+
pkg-config \
|
| 17 |
+
python3-dev \
|
| 18 |
+
curl \
|
| 19 |
+
git \
|
| 20 |
+
libgl1 \
|
| 21 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 22 |
+
|
| 23 |
+
RUN pip install --upgrade pip
|
| 24 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 25 |
+
|
| 26 |
+
# Copy app files
|
| 27 |
+
COPY app /code/app
|
| 28 |
+
COPY .env /code/.env
|
| 29 |
+
COPY app/main.py /code/app/main.py
|
| 30 |
+
COPY app/backend.py /code/app/backend.py
|
| 31 |
+
|
| 32 |
+
# Expose port for FastAPI
|
| 33 |
+
EXPOSE 7860
|
| 34 |
+
|
| 35 |
+
# Run FastAPI server
|
| 36 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
app/__pycache__/backend.cpython-312.pyc
ADDED
|
Binary file (3.99 kB). View file
|
|
|
app/__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (2.62 kB). View file
|
|
|
app/backend.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import fitz # PyMuPDF
|
| 3 |
+
import faiss
|
| 4 |
+
import numpy as np
|
| 5 |
+
import tempfile
|
| 6 |
+
import requests
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
import google.generativeai as genai
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
|
| 11 |
+
# Load environment variables
|
| 12 |
+
load_dotenv()
|
| 13 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 14 |
+
if api_key:
|
| 15 |
+
genai.configure(api_key=api_key)
|
| 16 |
+
else:
|
| 17 |
+
raise ValueError("GEMINI_API_KEY not found in environment variables")
|
| 18 |
+
|
| 19 |
+
# Load models
|
| 20 |
+
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 21 |
+
generation_model = genai.GenerativeModel("gemini-1.5-flash-002")
|
| 22 |
+
|
| 23 |
+
# ✅ Extract text from PDF URL
|
| 24 |
+
def extract_text_from_pdf_url(pdf_url):
|
| 25 |
+
try:
|
| 26 |
+
response = requests.get(pdf_url)
|
| 27 |
+
response.raise_for_status()
|
| 28 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 29 |
+
tmp.write(response.content)
|
| 30 |
+
tmp_path = tmp.name
|
| 31 |
+
doc = fitz.open(tmp_path)
|
| 32 |
+
return " ".join([page.get_text() for page in doc])
|
| 33 |
+
except Exception as e:
|
| 34 |
+
return f"Error extracting PDF text: {str(e)}"
|
| 35 |
+
|
| 36 |
+
# ✅ Build FAISS index with chunked text
|
| 37 |
+
def build_faiss_index(text, chunk_size=500, overlap=100):
|
| 38 |
+
chunks = []
|
| 39 |
+
for i in range(0, len(text), chunk_size - overlap):
|
| 40 |
+
chunks.append(text[i:i + chunk_size])
|
| 41 |
+
embeddings = embedding_model.encode(chunks)
|
| 42 |
+
index = faiss.IndexFlatL2(embeddings.shape[1])
|
| 43 |
+
index.add(np.array(embeddings))
|
| 44 |
+
return index, chunks
|
| 45 |
+
|
| 46 |
+
# ✅ Generate Gemini answer using top-K matched chunks
|
| 47 |
+
def generate_answer(query, index, chunks, top_k=10):
|
| 48 |
+
query_vec = embedding_model.encode([query])
|
| 49 |
+
_, indices = index.search(np.array(query_vec), top_k)
|
| 50 |
+
context = "\n".join([chunks[i] for i in indices[0] if i < len(chunks)])
|
| 51 |
+
|
| 52 |
+
prompt = f"""
|
| 53 |
+
You are an AI assistant specialized in insurance domain. Your job is to read the context and answer the question based on policy clauses.
|
| 54 |
+
|
| 55 |
+
Instructions:
|
| 56 |
+
- Be precise and fact-based.
|
| 57 |
+
- If multiple conditions apply, list them clearly.
|
| 58 |
+
- If answer is not in context, say \"Sorry, I couldn't find that information.\"
|
| 59 |
+
|
| 60 |
+
<context>
|
| 61 |
+
{context}
|
| 62 |
+
</context>
|
| 63 |
+
|
| 64 |
+
<question>
|
| 65 |
+
{query}
|
| 66 |
+
</question>
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
response = generation_model.generate_content(prompt)
|
| 70 |
+
return response.text.strip()
|
| 71 |
+
except Exception as e:
|
| 72 |
+
return f"Error generating answer: {str(e)}"
|
app/main.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/main.py
|
| 2 |
+
|
| 3 |
+
from fastapi import FastAPI, HTTPException, Header
|
| 4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from typing import List, Optional
|
| 7 |
+
from app.backend import extract_text_from_pdf_url, build_faiss_index, generate_answer
|
| 8 |
+
|
| 9 |
+
# ------------------ Setup App ------------------
|
| 10 |
+
app = FastAPI(
|
| 11 |
+
title="HackRx Intelligent Query–Retrieval System",
|
| 12 |
+
version="1.0.0",
|
| 13 |
+
description="LLM-powered system for insurance/legal/HR document query answering"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Enable CORS (Frontend support)
|
| 17 |
+
app.add_middleware(
|
| 18 |
+
CORSMiddleware,
|
| 19 |
+
allow_origins=["*"],
|
| 20 |
+
allow_methods=["*"],
|
| 21 |
+
allow_headers=["*"]
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
# ------------------ Request and Response Models ------------------
|
| 25 |
+
|
| 26 |
+
class HackRxRequest(BaseModel):
|
| 27 |
+
documents: str # PDF URL
|
| 28 |
+
questions: List[str]
|
| 29 |
+
|
| 30 |
+
class HackRxResponse(BaseModel):
|
| 31 |
+
answers: List[str]
|
| 32 |
+
|
| 33 |
+
# ------------------ Auth Token ------------------
|
| 34 |
+
AUTH_TOKEN = "cf1affb0027b55b966855965bfb46a0a1ff15babd937db87989784ac6fba8e1a"
|
| 35 |
+
|
| 36 |
+
# ------------------ Main Endpoint ------------------
|
| 37 |
+
|
| 38 |
+
@app.get("/")
|
| 39 |
+
def root():
|
| 40 |
+
return {"message": "FastAPI is working!"}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@app.post("/hackrx/run", response_model=HackRxResponse)
|
| 44 |
+
def run_hackrx(
|
| 45 |
+
request: HackRxRequest,
|
| 46 |
+
authorization: Optional[str] = Header(None)
|
| 47 |
+
):
|
| 48 |
+
if authorization != f"Bearer {AUTH_TOKEN}":
|
| 49 |
+
raise HTTPException(status_code=401, detail="Unauthorized: Invalid Bearer Token")
|
| 50 |
+
|
| 51 |
+
# Step 1: Extract text from document
|
| 52 |
+
extracted_text = extract_text_from_pdf_url(request.documents)
|
| 53 |
+
if extracted_text.startswith("Error"):
|
| 54 |
+
raise HTTPException(status_code=400, detail=extracted_text)
|
| 55 |
+
|
| 56 |
+
# Step 2: Build index
|
| 57 |
+
index, chunks = build_faiss_index(extracted_text)
|
| 58 |
+
|
| 59 |
+
# Step 3: Answer questions using FAISS + Gemini
|
| 60 |
+
answers = []
|
| 61 |
+
for question in request.questions:
|
| 62 |
+
answer = generate_answer(question, index, chunks)
|
| 63 |
+
answers.append(answer)
|
| 64 |
+
|
| 65 |
+
return {"answers": answers}
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
python-dotenv
|
| 4 |
+
sentence-transformers
|
| 5 |
+
faiss-cpu
|
| 6 |
+
PyMuPDF
|
| 7 |
+
google-generativeai
|
| 8 |
+
requests
|