Spaces:
Runtime error

File size: 3,186 Bytes
96b4219
 
 
 
 
 
 
2bd46f3
96b4219
 
2bd46f3
96b4219
 
2bd46f3
ccbe236
96b4219
2bd46f3
031a2a9
2bd46f3
 
 
 
 
96b4219
 
 
 
 
 
 
 
 
 
 
 
2bd46f3
7142ce1
96b4219
 
 
 
 
 
 
 
2bd46f3
 
96b4219
 
 
 
 
2bd46f3
96b4219
 
2bd46f3
 
 
 
 
031a2a9
96b4219
 
 
 
 
 
 
 
2bd46f3
 
 
 
 
96b4219
2bd46f3
 
96b4219
2bd46f3
 
 
 
 
 
 
 
 
 
 
 
 
96b4219
2bd46f3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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)}"