Spaces:
Sleeping
Sleeping
Download backend.py from PavanKumarD/FinBot: direct link, hf CLI and curl.
- Browser
- Download file 2.11 kB
-
https://huggingface.co/spaces/PavanKumarD/FinBot/resolve/main/backend.py
- Command line
-
hf download hf://spaces/PavanKumarD/FinBot/backend.py
-
curl -L -o backend.py https://huggingface.co/spaces/PavanKumarD/FinBot/resolve/main/backend.py
2.11 kB
| import os | |
| import fitz # PyMuPDF | |
| import faiss | |
| import numpy as np | |
| from sentence_transformers import SentenceTransformer | |
| import google.generativeai as genai | |
| # Configure Gemini API | |
| genai.configure(api_key=os.getenv("AIzaSyBaCZ19qDVQoGglZaPASytcZQerrDeYz6c")) # use Hugging Face Secrets | |
| embedding_model = SentenceTransformer("all-MiniLM-L6-v2") | |
| generation_model = genai.GenerativeModel("gemini-1.5-flash-002") | |
| # Initialize globals | |
| index = None | |
| document_chunks = [] | |
| user_data = "" | |
| logged_in = True # toggle for simulation | |
| def extract_text_from_pdf(file): | |
| doc = fitz.open(stream=file.read(), filetype="pdf") | |
| text = "" | |
| for page in doc: | |
| text += page.get_text() | |
| return text | |
| def split_into_chunks(text, chunk_size=500): | |
| import textwrap | |
| return textwrap.wrap(text, width=chunk_size) | |
| def build_faiss_index(chunks): | |
| global index, document_chunks | |
| document_chunks = chunks | |
| embeddings = embedding_model.encode(chunks, convert_to_numpy=True) | |
| index = faiss.IndexFlatL2(embeddings.shape[1]) | |
| index.add(embeddings) | |
| def retrieve_context(query, top_k=5): | |
| if index is None: | |
| return ["No documents indexed."] | |
| query_embedding = embedding_model.encode([query], convert_to_numpy=True) | |
| _, indices = index.search(query_embedding, top_k) | |
| return [document_chunks[i] for i in indices[0]] | |
| def generate_answer(query): | |
| retrieved_docs = retrieve_context(query) | |
| context = "\n".join(retrieved_docs) | |
| if logged_in and user_data: | |
| context += "\nUser Data:\n" + user_data | |
| prompt = f""" | |
| You are FinBot, a knowledgeable assistant trained on financial banking queries. | |
| Your job is to read the context carefully and explain the answer to the user's question using only the provided information. | |
| Do not make estimations or include any knowledge that is not in the context. Be clear and concise. | |
| <context> | |
| {context} | |
| </context> | |
| <question> | |
| {query} | |
| </question> | |
| """ | |
| response = generation_model.generate_content(prompt) | |
| return response.text.strip() | |
| def set_user_data(file): | |
| global user_data | |
| user_data = extract_text_from_pdf(file) | |