Spaces:
Runtime error

HackRX / app /backend.py
PavanKumarD's picture
Update app/backend.py
7142ce1 verified
Raw History Blame Contribute Delete
3.19 kB
import os
import fitz # PyMuPDF
import faiss
import numpy as np
import tempfile
import requests
from sentence_transformers import SentenceTransformer
from openai import OpenAI # βœ… Ensure you installed openai>=1.0.0 for OpenRouter
from dotenv import load_dotenv
# βœ… Load environment variables (optional but recommended)
load_dotenv()
# βœ… Set up embedding model
embedding_model = SentenceTransformer("models/all-MiniLM-L6-v2")
# βœ… Model name for OpenRouter (DeepSeek)
MODEL_NAME = "z-ai/glm-4.5-air:free"
# βœ… API key (you can load from environment for safety)
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "sk-or-...") # fallback
# βœ… Extract text from a PDF URL
def extract_text_from_pdf_url(pdf_url):
try:
response = requests.get(pdf_url)
response.raise_for_status()
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
tmp.write(response.content)
tmp_path = tmp.name
doc = fitz.open(tmp_path)
return " ".join([page.get_text() for page in doc])
except Exception as e:
return f"Error extracting PDF text: {str(e)}"
# βœ… Chunk the text and build FAISS index
def build_faiss_index(text, chunk_size=1700, overlap=150):
chunks = []
for i in range(0, len(text), chunk_size - overlap):
chunks.append(text[i:i + chunk_size])
embeddings = embedding_model.encode(chunks)
index = faiss.IndexFlatL2(embeddings.shape[1])
index.add(np.array(embeddings))
return index, chunks
# βœ… Generate answer using OpenRouter's DeepSeek
def generate_answer(query, index, chunks, top_k=20):
query_vec = embedding_model.encode([query])
_, indices = index.search(np.array(query_vec), top_k)
context = "\n".join([chunks[i] for i in indices[0] if i < len(chunks)])
prompt = f"""
You are an expert insurance assistant. Your job is to answer user questions based strictly on the provided policy document.
Instructions:
- Use only the information in <context> to answer the <question>.
- Always restate the relevant clause clearly and completely.
- Provide full context (e.g., duration, limits, eligibility, exclusions).
- Use domain-specific language and proper structure (as in insurance policy).
- If the information is not found, respond with: "Sorry, I couldn't find that information."
- give in one sentence.
<context>
{context}
</context>
<question>
{query}
</question>
Your answer must be:
- Factual and detailed (avoid vague or generic answers).
- Clearly structured in proper English.
- Written in 2–4 sentences like a policy explainer.
"""
try:
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=OPENROUTER_API_KEY
)
completion = client.chat.completions.create(
model=MODEL_NAME,
messages=[{"role": "user", "content": prompt}],
extra_headers={
"HTTP-Referer": "https://hackrx.yourproject.com",
"X-Title": "HackRx-PolicyQA"
}
)
return completion.choices[0].message.content.strip()
except Exception as e:
return f"❌ Error generating answer: {str(e)}"