Spaces:
Sleeping
Sleeping
Nikhil push
Browse files- app.py +74 -78
- ingest.py +55 -0
- llm.py +95 -0
- rag_pipeline.py +86 -5
- requirements.txt +12 -3
- stt.py +36 -0
- tts.py +63 -0
app.py
CHANGED
|
@@ -1,18 +1,17 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
STT : openai/whisper-large-v3 (hf-inference, ASR)
|
| 6 |
-
LLM : mistralai/Mistral-7B-Instruct-v0.3 (featherless provider, free tier)
|
| 7 |
-
TTS : facebook/mms-tts-hin (hf-inference, Hindi TTS, small model)
|
| 8 |
-
"""
|
| 9 |
|
| 10 |
import os
|
| 11 |
import io
|
| 12 |
import numpy as np
|
| 13 |
import soundfile as sf
|
| 14 |
import gradio as gr
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
from rag_pipeline import (
|
| 18 |
normalize_jargon,
|
|
@@ -20,82 +19,79 @@ from rag_pipeline import (
|
|
| 20 |
build_rag_prompt,
|
| 21 |
format_response_for_tts,
|
| 22 |
get_retriever,
|
|
|
|
| 23 |
)
|
| 24 |
|
| 25 |
# ─────────────────────────────────────────────
|
| 26 |
-
#
|
|
|
|
| 27 |
# ─────────────────────────────────────────────
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
# ─────────────────────────────────────────────
|
| 39 |
-
#
|
| 40 |
# ─────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def stt_whisper(audio_array: np.ndarray, sample_rate: int) -> str:
|
| 47 |
-
"""Convert Hindi audio to text using Whisper via hf-inference."""
|
| 48 |
-
buf = io.BytesIO()
|
| 49 |
-
sf.write(buf, audio_array, sample_rate, format="WAV", subtype="PCM_16")
|
| 50 |
-
buf.seek(0)
|
| 51 |
-
|
| 52 |
-
client = get_client("hf-inference")
|
| 53 |
-
result = client.automatic_speech_recognition(
|
| 54 |
-
audio=buf.read(),
|
| 55 |
-
model=STT_MODEL,
|
| 56 |
-
)
|
| 57 |
-
# result is an ASROutput object with .text
|
| 58 |
-
return result.text.strip() if hasattr(result, "text") else str(result).strip()
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def llm_generate(prompt: str) -> str:
|
| 62 |
-
"""Generate Hindi answer using Mistral via featherless (free tier)."""
|
| 63 |
-
client = get_client("featherless")
|
| 64 |
-
|
| 65 |
-
# Build messages in chat format
|
| 66 |
-
messages = [
|
| 67 |
-
{
|
| 68 |
-
"role": "system",
|
| 69 |
-
"content": (
|
| 70 |
-
"आप एक सहायक बैंकिंग सहायक हैं। केवल दी गई जानकारी के आधार पर "
|
| 71 |
-
"सरल हिंद��� में 3-4 वाक्यों में उत्तर दें। "
|
| 72 |
-
"यदि जानकारी नहीं है तो कहें: 'यह जानकारी मेरे पास नहीं है। "
|
| 73 |
-
"कृपया अपने बैंक से संपर्क करें।' हमेशा हिंदी में उत्तर दें।"
|
| 74 |
-
),
|
| 75 |
-
},
|
| 76 |
-
{"role": "user", "content": prompt},
|
| 77 |
-
]
|
| 78 |
-
|
| 79 |
-
response = client.chat.completions.create(
|
| 80 |
-
model=LLM_MODEL,
|
| 81 |
-
messages=messages,
|
| 82 |
-
max_tokens=350,
|
| 83 |
-
temperature=0.7,
|
| 84 |
-
)
|
| 85 |
-
return response.choices[0].message.content.strip()
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def tts_hindi(text: str):
|
| 89 |
-
"""Convert Hindi text to speech using MMS-TTS-HIN via hf-inference."""
|
| 90 |
-
client = get_client("hf-inference")
|
| 91 |
-
try:
|
| 92 |
-
audio_bytes = client.text_to_speech(text=text, model=TTS_MODEL)
|
| 93 |
-
buf = io.BytesIO(audio_bytes)
|
| 94 |
-
audio_array, sample_rate = sf.read(buf)
|
| 95 |
-
return int(sample_rate), audio_array.astype(np.float32)
|
| 96 |
-
except Exception as e:
|
| 97 |
-
print(f"TTS error: {e}")
|
| 98 |
-
return None
|
| 99 |
|
| 100 |
|
| 101 |
# ─────────────────────────────────────────────
|
|
@@ -130,7 +126,7 @@ def run_voice_pipeline(audio_input):
|
|
| 130 |
|
| 131 |
normalized = normalize_jargon(hindi_text)
|
| 132 |
eng_query = translate_to_retrieval_query(normalized)
|
| 133 |
-
docs =
|
| 134 |
citations = "\n".join(f"• {d['title']}" for d in docs) if docs else "कोई स्रोत नहीं मिला।"
|
| 135 |
|
| 136 |
yield hindi_text, "⏳ उत्तर तैयार किया जा रहा है...", citations, None
|
|
@@ -176,7 +172,7 @@ def run_text_pipeline(text_input: str):
|
|
| 176 |
|
| 177 |
normalized = normalize_jargon(text_input)
|
| 178 |
eng_query = translate_to_retrieval_query(normalized)
|
| 179 |
-
docs =
|
| 180 |
citations = "\n".join(f"• {d['title']}" for d in docs) if docs else "कोई स्रोत नहीं मिला।"
|
| 181 |
|
| 182 |
yield text_input, "⏳ उत्तर तैयार किया जा रहा है...", citations, None
|
|
@@ -331,7 +327,7 @@ def build_ui():
|
|
| 331 |
with gr.Row():
|
| 332 |
with gr.Column(scale=1, elem_classes="panel"):
|
| 333 |
gr.HTML('<p style="color:#B8C4D8;font-size:13px;margin:0 0 12px;">माइक बटन दबाएं → हिंदी में बोलें → Submit</p>')
|
| 334 |
-
v_audio_in = gr.Audio(
|
| 335 |
v_btn = gr.Button("🔍 उत्तर खोजें", variant="primary")
|
| 336 |
v_transcript= gr.Textbox(label="📝 Transcript", interactive=False, lines=2, placeholder="आपकी बात यहाँ दिखेगी...")
|
| 337 |
with gr.Column(scale=1, elem_classes="panel"):
|
|
|
|
| 1 |
+
# STARTUP:
|
| 2 |
+
# 1. pip install -r requirements.txt
|
| 3 |
+
# 2. python ingest.py ← run once to build ChromaDB
|
| 4 |
+
# 3. python app.py ← start the app
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
import os
|
| 7 |
import io
|
| 8 |
import numpy as np
|
| 9 |
import soundfile as sf
|
| 10 |
import gradio as gr
|
| 11 |
+
|
| 12 |
+
from stt import stt_whisper
|
| 13 |
+
from llm import llm_generate
|
| 14 |
+
from tts import tts_hindi
|
| 15 |
|
| 16 |
from rag_pipeline import (
|
| 17 |
normalize_jargon,
|
|
|
|
| 19 |
build_rag_prompt,
|
| 20 |
format_response_for_tts,
|
| 21 |
get_retriever,
|
| 22 |
+
retrieve_with_embeddings,
|
| 23 |
)
|
| 24 |
|
| 25 |
# ─────────────────────────────────────────────
|
| 26 |
+
# AUTO INGEST — builds ChromaDB on first startup
|
| 27 |
+
# Runs automatically if chroma_db folder not found
|
| 28 |
# ─────────────────────────────────────────────
|
| 29 |
+
import os
|
| 30 |
+
if not os.path.exists("./chroma_db"):
|
| 31 |
+
print("ChromaDB not found — building knowledge base index...")
|
| 32 |
+
try:
|
| 33 |
+
from knowledge_base import KNOWLEDGE_BASE
|
| 34 |
+
from sentence_transformers import SentenceTransformer
|
| 35 |
+
import chromadb
|
| 36 |
|
| 37 |
+
print("Loading embedding model for ingest...")
|
| 38 |
+
_embedder = SentenceTransformer(
|
| 39 |
+
'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2'
|
| 40 |
+
)
|
| 41 |
+
_chroma = chromadb.PersistentClient(path="./chroma_db")
|
| 42 |
+
_collection = _chroma.get_or_create_collection("banking_hindi")
|
| 43 |
+
|
| 44 |
+
_documents = []
|
| 45 |
+
_metadatas = []
|
| 46 |
+
_ids = []
|
| 47 |
+
|
| 48 |
+
for doc in KNOWLEDGE_BASE:
|
| 49 |
+
full_text = f"{doc['title']}\n{doc['content']}"
|
| 50 |
+
_documents.append(full_text)
|
| 51 |
+
_metadatas.append({
|
| 52 |
+
"id": doc["id"],
|
| 53 |
+
"title": doc["title"],
|
| 54 |
+
"category": doc["category"]
|
| 55 |
+
})
|
| 56 |
+
_ids.append(doc["id"])
|
| 57 |
+
|
| 58 |
+
print(f"Embedding {len(_documents)} documents... (takes 2-3 min on first run)")
|
| 59 |
+
_embeddings = _embedder.encode(
|
| 60 |
+
_documents,
|
| 61 |
+
show_progress_bar=True,
|
| 62 |
+
batch_size=8
|
| 63 |
+
).tolist()
|
| 64 |
+
|
| 65 |
+
_collection.add(
|
| 66 |
+
documents=_documents,
|
| 67 |
+
embeddings=_embeddings,
|
| 68 |
+
metadatas=_metadatas,
|
| 69 |
+
ids=_ids
|
| 70 |
+
)
|
| 71 |
+
print(f"✅ ChromaDB ready — {len(_documents)} documents indexed")
|
| 72 |
+
|
| 73 |
+
# Cleanup temp variables
|
| 74 |
+
del _embedder, _chroma, _collection
|
| 75 |
+
del _documents, _metadatas, _ids, _embeddings
|
| 76 |
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f"⚠️ Auto-ingest failed: {e}. Will use keyword retrieval fallback.")
|
| 79 |
+
else:
|
| 80 |
+
print("✅ ChromaDB found — skipping ingest")
|
| 81 |
|
| 82 |
# ─────────────────────────────────────────────
|
| 83 |
+
# CONFIG
|
| 84 |
# ─────────────────────────────────────────────
|
| 85 |
+
HF_TOKEN = (
|
| 86 |
+
os.environ.get("HF_TOKEN") or
|
| 87 |
+
os.environ.get("HF_API_TOKEN") or
|
| 88 |
+
os.environ.get("HUGGINGFACE_TOKEN") or
|
| 89 |
+
""
|
| 90 |
+
)
|
| 91 |
+
print(f"DEBUG app.py: HF_TOKEN loaded = {bool(HF_TOKEN)}, length = {len(HF_TOKEN)}")
|
| 92 |
|
| 93 |
+
|
| 94 |
+
# (STT, LLM, and TTS functions moved to separate modules)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
|
| 97 |
# ─────────────────────────────────────────────
|
|
|
|
| 126 |
|
| 127 |
normalized = normalize_jargon(hindi_text)
|
| 128 |
eng_query = translate_to_retrieval_query(normalized)
|
| 129 |
+
docs = retrieve_with_embeddings(eng_query, top_k=3)
|
| 130 |
citations = "\n".join(f"• {d['title']}" for d in docs) if docs else "कोई स्रोत नहीं मिला।"
|
| 131 |
|
| 132 |
yield hindi_text, "⏳ उत्तर तैयार किया जा रहा है...", citations, None
|
|
|
|
| 172 |
|
| 173 |
normalized = normalize_jargon(text_input)
|
| 174 |
eng_query = translate_to_retrieval_query(normalized)
|
| 175 |
+
docs = retrieve_with_embeddings(eng_query, top_k=3)
|
| 176 |
citations = "\n".join(f"• {d['title']}" for d in docs) if docs else "कोई स्रोत नहीं मिला।"
|
| 177 |
|
| 178 |
yield text_input, "⏳ उत्तर तैयार किया जा रहा है...", citations, None
|
|
|
|
| 327 |
with gr.Row():
|
| 328 |
with gr.Column(scale=1, elem_classes="panel"):
|
| 329 |
gr.HTML('<p style="color:#B8C4D8;font-size:13px;margin:0 0 12px;">माइक बटन दबाएं → हिंदी में बोलें → Submit</p>')
|
| 330 |
+
v_audio_in = gr.Audio(source="microphone", type="numpy", label="🎤 अपना प्रश्न बोलें")
|
| 331 |
v_btn = gr.Button("🔍 उत्तर खोजें", variant="primary")
|
| 332 |
v_transcript= gr.Textbox(label="📝 Transcript", interactive=False, lines=2, placeholder="आपकी बात यहाँ दिखेगी...")
|
| 333 |
with gr.Column(scale=1, elem_classes="panel"):
|
ingest.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
One-time script to build ChromaDB vector store from knowledge base.
|
| 3 |
+
Run once before starting the app: python ingest.py
|
| 4 |
+
Embeds all 37 knowledge base documents using multilingual MiniLM.
|
| 5 |
+
"""
|
| 6 |
+
from knowledge_base import KNOWLEDGE_BASE
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
import chromadb
|
| 9 |
+
|
| 10 |
+
print("Loading embedding model...")
|
| 11 |
+
embedder = SentenceTransformer(
|
| 12 |
+
'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2'
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
print("Setting up ChromaDB...")
|
| 16 |
+
chroma_client = chromadb.PersistentClient(path="./chroma_db")
|
| 17 |
+
|
| 18 |
+
# Delete existing collection to rebuild fresh
|
| 19 |
+
try:
|
| 20 |
+
chroma_client.delete_collection("banking_hindi")
|
| 21 |
+
print("Deleted existing collection.")
|
| 22 |
+
except:
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
collection = chroma_client.get_or_create_collection("banking_hindi")
|
| 26 |
+
|
| 27 |
+
documents = []
|
| 28 |
+
metadatas = []
|
| 29 |
+
ids = []
|
| 30 |
+
|
| 31 |
+
for doc in KNOWLEDGE_BASE:
|
| 32 |
+
full_text = f"{doc['title']}\n{doc['content']}"
|
| 33 |
+
documents.append(full_text)
|
| 34 |
+
metadatas.append({
|
| 35 |
+
"id": doc["id"],
|
| 36 |
+
"title": doc["title"],
|
| 37 |
+
"category": doc["category"]
|
| 38 |
+
})
|
| 39 |
+
ids.append(doc["id"])
|
| 40 |
+
|
| 41 |
+
print(f"Embedding {len(documents)} documents...")
|
| 42 |
+
embeddings = embedder.encode(
|
| 43 |
+
documents,
|
| 44 |
+
show_progress_bar=True,
|
| 45 |
+
batch_size=8
|
| 46 |
+
).tolist()
|
| 47 |
+
|
| 48 |
+
collection.add(
|
| 49 |
+
documents=documents,
|
| 50 |
+
embeddings=embeddings,
|
| 51 |
+
metadatas=metadatas,
|
| 52 |
+
ids=ids
|
| 53 |
+
)
|
| 54 |
+
print(f"✅ Successfully ingested {len(documents)} documents into ChromaDB")
|
| 55 |
+
print(f"Collection count: {collection.count()}")
|
llm.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LLM Module - Llama 3.1 70B via HuggingFace Router
|
| 3 |
+
Uses router.huggingface.co OpenAI-compatible endpoint.
|
| 4 |
+
Same pattern as verified working production code.
|
| 5 |
+
Includes retry logic for model cold starts.
|
| 6 |
+
"""
|
| 7 |
+
import requests
|
| 8 |
+
import time
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
HF_TOKEN = (
|
| 12 |
+
os.environ.get("HF_TOKEN") or
|
| 13 |
+
os.environ.get("HF_API_TOKEN") or
|
| 14 |
+
os.environ.get("HUGGINGFACE_TOKEN") or
|
| 15 |
+
""
|
| 16 |
+
)
|
| 17 |
+
print(f"DEBUG LLM: HF_TOKEN loaded = {bool(HF_TOKEN)}")
|
| 18 |
+
|
| 19 |
+
LLM_ROUTER_URL = "https://router.huggingface.co/v1/chat/completions"
|
| 20 |
+
LLM_MODEL = "meta-llama/Llama-3.1-70B-Instruct"
|
| 21 |
+
|
| 22 |
+
SYSTEM_PROMPT = """आप एक भारतीय बैंकिंग सहायक हैं।
|
| 23 |
+
आपका काम है ग्रामीण और शहरी भारतीय उपयोगकर्ताओं को
|
| 24 |
+
बैंकिंग और वित्तीय जानकारी सरल हिंदी में देना।
|
| 25 |
+
|
| 26 |
+
सख्त नियम:
|
| 27 |
+
1. केवल हिंदी में उत्तर दें — अंग्रेजी बिल्कुल नहीं
|
| 28 |
+
2. केवल दिए गए संदर्भ से उत्तर दें
|
| 29 |
+
3. यदि संदर्भ में जानकारी नहीं है तो कहें:
|
| 30 |
+
यह जानकारी मेरे पास नहीं है। कृपया अपने बैंक से संपर्क करें।
|
| 31 |
+
4. ब्याज दर, EMI, या कोई भी राशि केवल संदर्भ से बताएं
|
| 32 |
+
5. उत्तर 3-4 वाक्यों में दें — TTS के लिए छोटा रखें
|
| 33 |
+
6. सरल भाषा — जैसे किसी गांव के व्यक्ति को समझाना हो"""
|
| 34 |
+
|
| 35 |
+
def llm_generate(prompt: str) -> str:
|
| 36 |
+
"""
|
| 37 |
+
Generate Hindi answer using Llama 3.1 70B.
|
| 38 |
+
Keeps same function signature as existing llm_generate() in app.py.
|
| 39 |
+
"""
|
| 40 |
+
if not HF_TOKEN:
|
| 41 |
+
return ("HF_TOKEN नहीं मिला। "
|
| 42 |
+
"Space Settings → Secrets में HF_TOKEN जोड़ें।")
|
| 43 |
+
|
| 44 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 45 |
+
payload = {
|
| 46 |
+
"model": LLM_MODEL,
|
| 47 |
+
"messages": [
|
| 48 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 49 |
+
{"role": "user", "content": prompt}
|
| 50 |
+
],
|
| 51 |
+
"max_tokens": 350,
|
| 52 |
+
"temperature": 0.3
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
for i in range(3):
|
| 56 |
+
try:
|
| 57 |
+
res = requests.post(
|
| 58 |
+
LLM_ROUTER_URL,
|
| 59 |
+
headers=headers,
|
| 60 |
+
json=payload,
|
| 61 |
+
timeout=45
|
| 62 |
+
)
|
| 63 |
+
print(f"DEBUG LLM status: {res.status_code}")
|
| 64 |
+
|
| 65 |
+
if res.status_code != 200:
|
| 66 |
+
print(f"DEBUG LLM error body: {res.text[:300]}")
|
| 67 |
+
|
| 68 |
+
if not res.text.strip():
|
| 69 |
+
print(f"Empty response, retry {i+1}...")
|
| 70 |
+
time.sleep(5)
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
result = res.json()
|
| 74 |
+
|
| 75 |
+
if isinstance(result, dict) and "choices" in result:
|
| 76 |
+
answer = result["choices"][0]["message"]["content"].strip()
|
| 77 |
+
print(f"DEBUG LLM answer preview: {answer[:100]}")
|
| 78 |
+
return answer
|
| 79 |
+
|
| 80 |
+
if isinstance(result, dict) and "error" in result:
|
| 81 |
+
err = result.get("error", "")
|
| 82 |
+
if isinstance(err, dict):
|
| 83 |
+
err = err.get("message", str(err))
|
| 84 |
+
if "loading" in str(err).lower():
|
| 85 |
+
print(f"Model loading, retry {i+1} in 10s...")
|
| 86 |
+
time.sleep(10)
|
| 87 |
+
continue
|
| 88 |
+
print(f"LLM API error: {err}")
|
| 89 |
+
break
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"LLM exception retry {i+1}: {e}")
|
| 93 |
+
time.sleep(2)
|
| 94 |
+
|
| 95 |
+
return "माफ करें, अभी उत्तर देने में समस्या हो रही है। कृपया दोबारा प्रयास करें।"
|
rag_pipeline.py
CHANGED
|
@@ -240,8 +240,89 @@ def format_response_for_tts(text: str) -> str:
|
|
| 240 |
|
| 241 |
def get_tts_description(text: str) -> str:
|
| 242 |
"""Speaker description for Indic-Parler-TTS."""
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
def get_tts_description(text: str) -> str:
|
| 242 |
"""Speaker description for Indic-Parler-TTS."""
|
| 243 |
+
|
| 244 |
+
# ─────────────────────────────────────────────
|
| 245 |
+
# EMBEDDING RETRIEVER — multilingual, Hindi-aware
|
| 246 |
+
# Uses paraphrase-multilingual-MiniLM-L12-v2
|
| 247 |
+
# Falls back to SimpleRetriever if ChromaDB not ready
|
| 248 |
+
# ─────────────────────────────────────────────
|
| 249 |
+
|
| 250 |
+
try:
|
| 251 |
+
from sentence_transformers import SentenceTransformer
|
| 252 |
+
from FlagEmbedding import FlagReranker
|
| 253 |
+
import chromadb
|
| 254 |
+
|
| 255 |
+
print("Loading embedding model (multilingual MiniLM)...")
|
| 256 |
+
embedder = SentenceTransformer(
|
| 257 |
+
'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2'
|
| 258 |
+
)
|
| 259 |
+
print("Loading reranker (bge-reranker-v2-m3)...")
|
| 260 |
+
reranker = FlagReranker('BAAI/bge-reranker-v2-m3', use_fp16=False)
|
| 261 |
+
|
| 262 |
+
chroma_client = chromadb.PersistentClient(path="./chroma_db")
|
| 263 |
+
EMBEDDING_READY = True
|
| 264 |
+
print("Embedding retriever ready.")
|
| 265 |
+
|
| 266 |
+
except Exception as e:
|
| 267 |
+
print(f"Embedding retriever not available: {e}. Using keyword retriever.")
|
| 268 |
+
EMBEDDING_READY = False
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def retrieve_with_embeddings(query: str, top_k: int = 3) -> list:
|
| 272 |
+
"""
|
| 273 |
+
Two-stage retrieval:
|
| 274 |
+
Stage 1 - ChromaDB embedding search (top 10)
|
| 275 |
+
Stage 2 - bge-reranker picks best 3
|
| 276 |
+
Falls back to SimpleRetriever if embeddings not ready.
|
| 277 |
+
Critical for Hinglish queries like
|
| 278 |
+
'home loan ka interest kitna hai for salaried?'
|
| 279 |
+
"""
|
| 280 |
+
if not EMBEDDING_READY:
|
| 281 |
+
print("DEBUG RAG: falling back to keyword retriever")
|
| 282 |
+
retriever = get_retriever()
|
| 283 |
+
return retriever.retrieve(query, top_k=top_k)
|
| 284 |
+
|
| 285 |
+
try:
|
| 286 |
+
collection = chroma_client.get_collection("banking_hindi")
|
| 287 |
+
except Exception:
|
| 288 |
+
print("DEBUG RAG: ChromaDB collection not found, run ingest.py first")
|
| 289 |
+
print("DEBUG RAG: falling back to keyword retriever")
|
| 290 |
+
retriever = get_retriever()
|
| 291 |
+
return retriever.retrieve(query, top_k=top_k)
|
| 292 |
+
|
| 293 |
+
try:
|
| 294 |
+
# Stage 1: embedding similarity search
|
| 295 |
+
query_embedding = embedder.encode([query]).tolist()
|
| 296 |
+
results = collection.query(
|
| 297 |
+
query_embeddings=query_embedding,
|
| 298 |
+
n_results=min(10, collection.count())
|
| 299 |
+
)
|
| 300 |
+
candidates = results['documents'][0]
|
| 301 |
+
metadatas = results['metadatas'][0]
|
| 302 |
+
|
| 303 |
+
print(f"DEBUG RAG: {len(candidates)} candidates from ChromaDB")
|
| 304 |
+
|
| 305 |
+
# Stage 2: rerank
|
| 306 |
+
pairs = [[query, doc] for doc in candidates]
|
| 307 |
+
scores = reranker.compute_score(pairs)
|
| 308 |
+
ranked = sorted(
|
| 309 |
+
zip(scores, candidates, metadatas),
|
| 310 |
+
reverse=True
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
top_results = [
|
| 314 |
+
{
|
| 315 |
+
"id": meta.get("id", ""),
|
| 316 |
+
"title": meta.get("title", ""),
|
| 317 |
+
"content": doc,
|
| 318 |
+
"category": meta.get("category", "")
|
| 319 |
+
}
|
| 320 |
+
for _, doc, meta in ranked[:top_k]
|
| 321 |
+
]
|
| 322 |
+
print(f"DEBUG RAG: top result = {top_results[0]['title'] if top_results else 'none'}")
|
| 323 |
+
return top_results
|
| 324 |
+
|
| 325 |
+
except Exception as e:
|
| 326 |
+
print(f"DEBUG RAG: embedding retrieval error: {e}")
|
| 327 |
+
retriever = get_retriever()
|
| 328 |
+
return retriever.retrieve(query, top_k=top_k)
|
requirements.txt
CHANGED
|
@@ -1,4 +1,13 @@
|
|
| 1 |
-
gradio
|
| 2 |
-
huggingface_hub>=0.
|
| 3 |
soundfile>=0.12.1
|
| 4 |
-
numpy>=1.24.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.44.1
|
| 2 |
+
huggingface_hub>=0.24.0
|
| 3 |
soundfile>=0.12.1
|
| 4 |
+
numpy>=1.24.0
|
| 5 |
+
faster-whisper
|
| 6 |
+
chromadb
|
| 7 |
+
sentence-transformers
|
| 8 |
+
FlagEmbedding
|
| 9 |
+
requests
|
| 10 |
+
torch
|
| 11 |
+
transformers
|
| 12 |
+
accelerate
|
| 13 |
+
edge-tts
|
stt.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
STT Module - faster-whisper medium int8 on CPU
|
| 3 |
+
Transcribes Hindi audio to text.
|
| 4 |
+
Faster than openai/whisper via API, runs locally, no API cost.
|
| 5 |
+
"""
|
| 6 |
+
from faster_whisper import WhisperModel
|
| 7 |
+
import numpy as np
|
| 8 |
+
import soundfile as sf
|
| 9 |
+
import io
|
| 10 |
+
|
| 11 |
+
print("Loading Whisper model (medium int8)... first run downloads ~500MB")
|
| 12 |
+
whisper_model = WhisperModel("medium", device="cpu", compute_type="int8")
|
| 13 |
+
print("Whisper model loaded.")
|
| 14 |
+
|
| 15 |
+
def stt_whisper(audio_array: np.ndarray, sample_rate: int) -> str:
|
| 16 |
+
"""
|
| 17 |
+
Convert Hindi audio array to text.
|
| 18 |
+
Keeps same function signature as existing stt_whisper() in app.py.
|
| 19 |
+
"""
|
| 20 |
+
try:
|
| 21 |
+
buf = io.BytesIO()
|
| 22 |
+
sf.write(buf, audio_array, sample_rate, format="WAV", subtype="PCM_16")
|
| 23 |
+
buf.seek(0)
|
| 24 |
+
|
| 25 |
+
segments, info = whisper_model.transcribe(
|
| 26 |
+
buf,
|
| 27 |
+
language="hi",
|
| 28 |
+
beam_size=5
|
| 29 |
+
)
|
| 30 |
+
transcript = " ".join([s.text for s in segments]).strip()
|
| 31 |
+
print(f"DEBUG STT transcript: {transcript}")
|
| 32 |
+
print(f"DEBUG STT detected language: {info.language} confidence: {info.language_probability:.2f}")
|
| 33 |
+
return transcript
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print(f"STT error: {e}")
|
| 36 |
+
return ""
|
tts.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
TTS Module - Microsoft Edge TTS
|
| 3 |
+
Uses hi-IN-SwaraNeural — natural Hindi female voice.
|
| 4 |
+
No compilation needed, works on Python 3.14 + Windows.
|
| 5 |
+
No API key required.
|
| 6 |
+
Returns (sample_rate, audio_array) tuple — same as existing tts_hindi().
|
| 7 |
+
"""
|
| 8 |
+
import edge_tts
|
| 9 |
+
import asyncio
|
| 10 |
+
import numpy as np
|
| 11 |
+
import soundfile as sf
|
| 12 |
+
import io
|
| 13 |
+
import tempfile
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
HINDI_VOICE = "hi-IN-SwaraNeural"
|
| 17 |
+
|
| 18 |
+
def tts_hindi(text: str):
|
| 19 |
+
"""
|
| 20 |
+
Convert Hindi text to audio using Edge TTS.
|
| 21 |
+
Keeps same function signature as existing tts_hindi() in app.py.
|
| 22 |
+
Returns (sample_rate, audio_array) tuple or None on failure.
|
| 23 |
+
"""
|
| 24 |
+
try:
|
| 25 |
+
if not text or not text.strip():
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
# Limit text length
|
| 29 |
+
if len(text) > 500:
|
| 30 |
+
text = text[:500]
|
| 31 |
+
print("DEBUG TTS: text truncated to 500 chars")
|
| 32 |
+
|
| 33 |
+
# Edge TTS is async — run it synchronously
|
| 34 |
+
async def _generate():
|
| 35 |
+
communicate = edge_tts.Communicate(text, HINDI_VOICE)
|
| 36 |
+
# Use tempfile to get a proper temp path
|
| 37 |
+
fd, tmp_path = tempfile.mkstemp(suffix=".mp3")
|
| 38 |
+
os.close(fd) # Close file descriptor immediately
|
| 39 |
+
try:
|
| 40 |
+
await communicate.save(tmp_path)
|
| 41 |
+
return tmp_path
|
| 42 |
+
except Exception as e:
|
| 43 |
+
if os.path.exists(tmp_path):
|
| 44 |
+
os.remove(tmp_path)
|
| 45 |
+
raise e
|
| 46 |
+
|
| 47 |
+
# Run async function
|
| 48 |
+
tmp_path = asyncio.run(_generate())
|
| 49 |
+
|
| 50 |
+
# Read audio file
|
| 51 |
+
audio_array, sample_rate = sf.read(tmp_path)
|
| 52 |
+
audio_array = audio_array.astype(np.float32)
|
| 53 |
+
|
| 54 |
+
# Cleanup temp file
|
| 55 |
+
if os.path.exists(tmp_path):
|
| 56 |
+
os.remove(tmp_path)
|
| 57 |
+
|
| 58 |
+
print(f"DEBUG TTS: generated audio at {sample_rate}Hz")
|
| 59 |
+
return (int(sample_rate), audio_array)
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
print(f"TTS error: {e}")
|
| 63 |
+
return None
|