Spaces:
Runtime error
Runtime error
Update app/backend.py
Browse files- app/backend.py +71 -71
app/backend.py
CHANGED
|
@@ -1,72 +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("
|
| 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)}"
|
|
|
|
| 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("models/ll-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)}"
|