Spaces:
Runtime error
Runtime error
Download app/backend.py from PavanKumarD/HackRX: direct link, hf CLI and curl.
- Browser
- Download file 3.17 kB
-
https://huggingface.co/spaces/PavanKumarD/HackRX/resolve/83b128fd238bfcd5dfd2e4334c1fa1e859f702ff/app/backend.py
- Command line
-
hf download hf://spaces/PavanKumarD/HackRX@83b128fd238bfcd5dfd2e4334c1fa1e859f702ff/app/backend.py
-
curl -L -o backend.py https://huggingface.co/spaces/PavanKumarD/HackRX/resolve/83b128fd238bfcd5dfd2e4334c1fa1e859f702ff/app/backend.py
3.17 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 = "deepseek/deepseek-r1-0528: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=700, 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." | |
| <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)}" | |