Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import gradio as grimport osimport torchfrom transformers import AutoTokenizer, AutoModelForCausalLMfrom sentence_transformers import SentenceTransformerimport faissimport numpy as npimport whisperfrom gtts import gTTS
# -------------------------# Load RAG model# -------------------------model_id = "microsoft/phi-3-mini-4k-instruct"tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.float16, device_map="auto")
# -------------------------# Load embedding model and index docs# -------------------------embedder = SentenceTransformer("all-MiniLM-L6-v2")
def load_docs(doc_folder="docs"): docs = [] for filename in os.listdir(doc_folder): if filename.endswith(".txt"): with open(os.path.join(doc_folder, filename), "r", encoding="utf-8") as f: text = f.read() # Split into chunks words = text.split() chunk_size = 500 overlap = 100 for i in range(0, len(words), chunk_size - overlap): chunk = " ".join(words[i:i+chunk_size]) docs.append(chunk) return docs
docs = load_docs()embeddings = embedder.encode(docs)dim = embeddings.shape[1]index = faiss.IndexFlatL2(dim)index.add(np.array(embeddings))
# -------------------------# Load Whisper model# -------------------------whisper_model = whisper.load_model("base") # use "tiny" for CPU
# -------------------------# RAG functions# -------------------------def retrieve(query, top_k=3): q_emb = embedder.encode([query]) D, I = index.search(np.array(q_emb), top_k) return [docs[i] for i in I[0]]
def ask_phi(query, top_k=3): context = "\n".join(retrieve(query, top_k)) prompt = f"""You are an assistant that answers user questions using ONLY the provided context documents.If the answer is not in the documents, respond with:"I don’t have information about that in the provided documents."
Guidelines:- Start your response with a friendly greeting, e.g., "Great! Let me explain this..."- Answer in a natural, human-like style; do not use bullet points.- End your response with a friendly closure, e.g., "Hope this helps! If you need more assistance, feel free to ask."- Only use the information from the provided context.
Context:{context}
Question: {query}
Answer:""" inputs = tokenizer(prompt, return_tensors="pt").to("cuda") outputs = model.generate( **inputs, max_new_tokens=200, temperature=0.3, top_p=0.9, do_sample=True ) generated_text = tokenizer.decode(outputs[0][inputs['input_ids'].shape[-1]:], skip_special_tokens=True) clean_answer = generated_text.split("Question:")[0].strip() return clean_answer
# -------------------------# TTS# -------------------------def text_to_speech(text): tts = gTTS(text=text, lang="en") tts.save("answer.mp3") return "answer.mp3"
# -------------------------# Gradio pipeline# -------------------------def voice_bot(audio): # audio is numpy array from mic from scipy.io.wavfile import write write("user_input.wav", 44100, audio)
# Step 1: Transcribe query = whisper_model.transcribe("user_input.wav", language="en")['text'].strip() print("User Asked:", query)
# Step 2: Get RAG answer answer = ask_phi(query) print("Answer:", answer)
# Step 3: TTS audio_file = text_to_speech(answer)
return answer, audio_file
# -------------------------# Launch Gradio# -------------------------iface = gr.Interface( fn=voice_bot, inputs=gr.Audio(source="microphone", type="numpy"), outputs=[gr.Textbox(label="Answer"), gr.Audio(label="Audio Answer")], title="Voice-based RAG Assistant", description="Ask questions about leave or tickets. Answer in English, plays audio using gTTS.")
iface.launch()app.py+133