Spaces:
Runtime error
Runtime error
Update app/backend.py
Browse files- app/backend.py +41 -21
app/backend.py
CHANGED
|
@@ -5,22 +5,22 @@ import numpy as np
|
|
| 5 |
import tempfile
|
| 6 |
import requests
|
| 7 |
from sentence_transformers import SentenceTransformer
|
| 8 |
-
import
|
| 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 |
-
#
|
| 20 |
embedding_model = SentenceTransformer("models/all-MiniLM-L6-v2")
|
| 21 |
-
generation_model = genai.GenerativeModel("gemini-1.5-flash-002")
|
| 22 |
|
| 23 |
-
# β
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
def extract_text_from_pdf_url(pdf_url):
|
| 25 |
try:
|
| 26 |
response = requests.get(pdf_url)
|
|
@@ -33,8 +33,8 @@ def extract_text_from_pdf_url(pdf_url):
|
|
| 33 |
except Exception as e:
|
| 34 |
return f"Error extracting PDF text: {str(e)}"
|
| 35 |
|
| 36 |
-
# β
|
| 37 |
-
def build_faiss_index(text, chunk_size=
|
| 38 |
chunks = []
|
| 39 |
for i in range(0, len(text), chunk_size - overlap):
|
| 40 |
chunks.append(text[i:i + chunk_size])
|
|
@@ -43,19 +43,21 @@ def build_faiss_index(text, chunk_size=500, overlap=100):
|
|
| 43 |
index.add(np.array(embeddings))
|
| 44 |
return index, chunks
|
| 45 |
|
| 46 |
-
# β
Generate
|
| 47 |
-
def generate_answer(query, index, chunks, top_k=
|
| 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
|
| 54 |
|
| 55 |
Instructions:
|
| 56 |
-
-
|
| 57 |
-
-
|
| 58 |
-
-
|
|
|
|
|
|
|
| 59 |
|
| 60 |
<context>
|
| 61 |
{context}
|
|
@@ -64,9 +66,27 @@ Instructions:
|
|
| 64 |
<question>
|
| 65 |
{query}
|
| 66 |
</question>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
"""
|
|
|
|
|
|
|
| 68 |
try:
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
except Exception as e:
|
| 72 |
-
return f"Error generating answer: {str(e)}"
|
|
|
|
| 5 |
import tempfile
|
| 6 |
import requests
|
| 7 |
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from openai import OpenAI # β
Ensure you installed openai>=1.0.0 for OpenRouter
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
|
| 11 |
+
# β
Load environment variables (optional but recommended)
|
| 12 |
load_dotenv()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# β
Set up embedding model
|
| 15 |
embedding_model = SentenceTransformer("models/all-MiniLM-L6-v2")
|
|
|
|
| 16 |
|
| 17 |
+
# β
Model name for OpenRouter (DeepSeek)
|
| 18 |
+
MODEL_NAME = "deepseek/deepseek-r1-0528:free"
|
| 19 |
+
|
| 20 |
+
# β
API key (you can load from environment for safety)
|
| 21 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "sk-or-...") # fallback
|
| 22 |
+
|
| 23 |
+
# β
Extract text from a PDF URL
|
| 24 |
def extract_text_from_pdf_url(pdf_url):
|
| 25 |
try:
|
| 26 |
response = requests.get(pdf_url)
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
return f"Error extracting PDF text: {str(e)}"
|
| 35 |
|
| 36 |
+
# β
Chunk the text and build FAISS index
|
| 37 |
+
def build_faiss_index(text, chunk_size=700, overlap=150):
|
| 38 |
chunks = []
|
| 39 |
for i in range(0, len(text), chunk_size - overlap):
|
| 40 |
chunks.append(text[i:i + chunk_size])
|
|
|
|
| 43 |
index.add(np.array(embeddings))
|
| 44 |
return index, chunks
|
| 45 |
|
| 46 |
+
# β
Generate answer using OpenRouter's DeepSeek
|
| 47 |
+
def generate_answer(query, index, chunks, top_k=20):
|
| 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 expert insurance assistant. Your job is to answer user questions based strictly on the provided policy document.
|
| 54 |
|
| 55 |
Instructions:
|
| 56 |
+
- Use only the information in <context> to answer the <question>.
|
| 57 |
+
- Always restate the relevant clause clearly and completely.
|
| 58 |
+
- Provide full context (e.g., duration, limits, eligibility, exclusions).
|
| 59 |
+
- Use domain-specific language and proper structure (as in insurance policy).
|
| 60 |
+
- If the information is not found, respond with: "Sorry, I couldn't find that information."
|
| 61 |
|
| 62 |
<context>
|
| 63 |
{context}
|
|
|
|
| 66 |
<question>
|
| 67 |
{query}
|
| 68 |
</question>
|
| 69 |
+
|
| 70 |
+
Your answer must be:
|
| 71 |
+
- Factual and detailed (avoid vague or generic answers).
|
| 72 |
+
- Clearly structured in proper English.
|
| 73 |
+
- Written in 2β4 sentences like a policy explainer.
|
| 74 |
"""
|
| 75 |
+
|
| 76 |
+
|
| 77 |
try:
|
| 78 |
+
client = OpenAI(
|
| 79 |
+
base_url="https://openrouter.ai/api/v1",
|
| 80 |
+
api_key=OPENROUTER_API_KEY
|
| 81 |
+
)
|
| 82 |
+
completion = client.chat.completions.create(
|
| 83 |
+
model=MODEL_NAME,
|
| 84 |
+
messages=[{"role": "user", "content": prompt}],
|
| 85 |
+
extra_headers={
|
| 86 |
+
"HTTP-Referer": "https://hackrx.yourproject.com",
|
| 87 |
+
"X-Title": "HackRx-PolicyQA"
|
| 88 |
+
}
|
| 89 |
+
)
|
| 90 |
+
return completion.choices[0].message.content.strip()
|
| 91 |
except Exception as e:
|
| 92 |
+
return f"β Error generating answer: {str(e)}"
|