Spaces:
Sleeping
Sleeping
Download app/backend.py from PavanKumarD/voice_assistance: direct link, hf CLI and curl.
- Browser
- Download file 7.19 kB
-
https://huggingface.co/spaces/PavanKumarD/voice_assistance/resolve/main/app/backend.py
- Command line
-
hf download hf://spaces/PavanKumarD/voice_assistance/app/backend.py
-
curl -L -o backend.py https://huggingface.co/spaces/PavanKumarD/voice_assistance/resolve/main/app/backend.py
7.19 kB
| import os | |
| import fitz # PyMuPDF | |
| import faiss | |
| import numpy as np | |
| import traceback | |
| from dotenv import load_dotenv | |
| from openai import OpenAI | |
| from sentence_transformers import SentenceTransformer | |
| # Load environment variables | |
| load_dotenv() | |
| current_api_index = 0 | |
| # ✅ Load multiple OpenRouter API keys from env | |
| openrouter_keys = os.getenv("OPENROUTER_API_KEYS", "").split(",") | |
| # ✅ Preferred model | |
| MODEL_NAME = "z-ai/glm-4.5-air:free" | |
| # ✅ Embedding model | |
| embedding_model = SentenceTransformer("models/all-MiniLM-L6-v2") | |
| # -------- PDF Utils -------- | |
| def extract_text_from_pdf(pdf_path): | |
| doc = fitz.open(pdf_path) | |
| return " ".join([page.get_text() for page in doc]) | |
| def build_faiss_index(text, chunk_size=1000, overlap=150): | |
| chunks, i = [], 0 | |
| while i < len(text): | |
| chunk = text[i:i + chunk_size] | |
| chunks.append(chunk) | |
| i += chunk_size - overlap | |
| embeddings = embedding_model.encode(chunks) | |
| index = faiss.IndexFlatL2(embeddings.shape[1]) | |
| index.add(np.array(embeddings)) | |
| return index, chunks | |
| # -------- Chat History Summarizer -------- | |
| def summarize_chat_history(chat_history, model=MODEL_NAME): | |
| if not chat_history: | |
| return "" | |
| history_text = "\n".join([f"{'User' if h['role'] == 'user' else 'FinBot'}: {h['message']}" for h in chat_history]) | |
| prompt = f""" | |
| Summarize the following conversation between a user and FinBot in 2-3 lines. | |
| <conversation> | |
| {history_text} | |
| </conversation> | |
| Summary: | |
| """ | |
| try: | |
| client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=openrouter_keys[-1]) | |
| completion = client.chat.completions.create( | |
| model=model, | |
| messages=[{"role": "user", "content": prompt}], | |
| extra_headers={"HTTP-Referer": "http://localhost:8000", "X-Title": "FinBot"} | |
| ) | |
| return completion.choices[0].message.content.strip() | |
| except Exception as e: | |
| print("⚠️ Failed to summarize:", e) | |
| return "" | |
| # -------- Prompt Builders -------- | |
| def build_prompt_bank(query, context, user_data_text="", summary_block=""): | |
| system_prompt = """You are a helpful assistant. Automatically detect the language of the user's question and respond in the same language.""" | |
| user_data_block = f"\n<user_data>\n{user_data_text.strip()}\n</user_data>" if user_data_text else "" | |
| return f""" | |
| ou are FinBot, a helpful and knowledgeable AI assistant designed to assist users with financial banking queries. | |
| You're also capable of answering general questions like greetings, date, time, or friendly comments in a conversational tone and properly explain to the user your response. | |
| You should act proficional as well as a close friend whom the user has known for a long time. | |
| Your responsibilities: | |
| - Use <context> and <user_data> to answer financial questions precisely. | |
| - Answer general questions like a friend explaining everyting. | |
| - Do not hallucinate information. | |
| - Use some 3-7 respectful sentences per response that makes good sense. | |
| - more context info for general questions. | |
| - do not mention the thinking process just answer the question. | |
| Format responses with: | |
| - add proper heading and side heading formating and tables and equations properly | |
| - Use headings (##, ###) for sections. | |
| - Use bullet points (-) for lists, no nested lists inside table cells. | |
| - Use **bold** to highlight important terms. | |
| - Do not include raw <br> or HTML—just Markdown syntax. | |
| - give proper equations using LaTeX syntax ($...$ or $$...$$) | |
| Respond in Markdown format. | |
| <system_prompt> | |
| {system_prompt} | |
| </system_prompt> | |
| <chat_history> | |
| {summary_block} | |
| </chat_history> | |
| <context> | |
| {context} | |
| </context> | |
| {user_data_block} | |
| <question> | |
| {query} | |
| </question> | |
| """ | |
| def build_prompt_nse(query, context, summary_block=""): | |
| system_prompt = """You are a helpful assistant. Automatically detect the language of the user's question and respond in the same language.""" | |
| return f""" | |
| You are FinBot NSE, a professional and knowledgeable AI assistant designed to interpret and answer questions from NSE circulars, SEBI regulations, and financial compliance documents. | |
| You must always maintain a formal, factual, and report-like tone. | |
| Your responsibilities: | |
| - Use <context> to answer queries precisely. | |
| - Do not hallucinate or assume information outside <context>. | |
| - Summarize circulars, clauses, rules, and highlight **dates, figures, percentages** where available. | |
| - Answer in **3–7 formal, well-structured sentences** like a compliance officer would. | |
| - If context is insufficient, politely state that information is not available. | |
| - Keep tone **professional and factual**, not casual. | |
| Format responses with: | |
| - Use **Markdown headings (##, ###)** for sections. | |
| - Use bullet points (-) for key highlights. | |
| - Use **bold** for important terms. | |
| - Use tables where needed (dates, figures, clauses). | |
| - Give equations or percentages in proper LaTeX ($...$ or $$...$$). | |
| - Never include raw <br> or HTML—only Markdown. | |
| Respond in Markdown format. | |
| <system_prompt> | |
| {system_prompt} | |
| </system_prompt> | |
| <chat_history> | |
| {summary_block} | |
| </chat_history> | |
| <context> | |
| {context} | |
| </context> | |
| {user_data_block} | |
| <question> | |
| {query} | |
| </question> | |
| """ | |
| # -------- Answer Generator -------- | |
| def generate_answer(query, index, chunks, chat_history=None, user_data_text="", top_k=10, kb_type="bank"): | |
| global current_api_index | |
| query_vec = embedding_model.encode([query]) | |
| _, indices = index.search(np.array(query_vec), top_k) | |
| retrieved = [chunks[i] for i in indices[0] if i < len(chunks)] | |
| relevant_chunks = list(dict.fromkeys(retrieved)) | |
| if not relevant_chunks: | |
| return "⚠️ No relevant context found. Please try again with a different query." | |
| context = "\n".join(relevant_chunks) | |
| # Smart history | |
| conversation_summary = "" | |
| MAX_HISTORY_TURNS = 6 | |
| if chat_history and len(chat_history) > MAX_HISTORY_TURNS: | |
| conversation_summary = summarize_chat_history(chat_history) | |
| chat_history.clear() | |
| summary_block = f"<chat_summary>\n{conversation_summary}\n</chat_summary>" if conversation_summary else "" | |
| # Select prompt | |
| if kb_type.lower() == "nse": | |
| prompt = build_prompt_nse(query, context, user_data_text, summary_block) | |
| else: | |
| prompt = build_prompt_bank(query, context, user_data_text, summary_block) | |
| # Retry keys | |
| indices_to_try = [current_api_index] + [i for i in range(len(openrouter_keys)) if i != current_api_index] | |
| for idx in indices_to_try: | |
| api_key = openrouter_keys[idx].strip() | |
| try: | |
| print(f"🔑 Trying API Key #{idx + 1}") | |
| client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key) | |
| completion = client.chat.completions.create( | |
| model=MODEL_NAME, | |
| messages=[{"role": "user", "content": prompt}], | |
| extra_headers={"HTTP-Referer": "http://localhost:8000", "X-Title": "FinBot"} | |
| ) | |
| current_api_index = idx | |
| return completion.choices[0].message.content.strip() | |
| except Exception as e: | |
| print(f"❌ Failed with Key #{idx+1}: {e}") | |
| traceback.print_exc() | |
| return "❗ All API keys failed. Please try later." |