Spaces:
Sleeping

Chatbot / app.py
TestFZAI's picture
Update app.py
e22a3fa verified
Raw History Blame Contribute Delete
5.02 kB
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
import whisper
from gtts import gTTS
from scipy.io.wavfile import write
# -------------------------
# Embedded documents
# -------------------------
docs = {
"leave": """
To check your leave balances, navigate to the Leave Module in the HR system.
Select the 'My Leave' section. Here you can view your personal leave requests,
including Leave Type, Total Count, Approved Leave, and Carry Forward.
You can filter by Year or Status (Pending, Approved, Rejected, etc.).
To apply for leave, select Leave Type, Session, Start Date, End Date, enter Reason, and submit.
Contingency or compensatory leave uses the same process.
""",
"ticket": """
For ticket management, you can log in to the Ticketing System.
To create a new ticket, select the 'New Ticket' option and fill in details such as
Ticket Type, Description, and Priority. You can track ticket status in the 'My Tickets' section.
Resolved tickets can be closed, and you can filter tickets by Open, Pending, or Closed.
"""
}
# -------------------------
# Split docs into chunks
# -------------------------
chunk_size = 500
overlap = 100
all_chunks = []
for doc_name, text in docs.items():
words = text.split()
for i in range(0, len(words), chunk_size - overlap):
chunk = " ".join(words[i:i+chunk_size])
all_chunks.append(chunk)
# -------------------------
# Build embeddings index
# -------------------------
embedder = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = embedder.encode(all_chunks)
dim = embeddings.shape[1]
index = faiss.IndexFlatL2(dim)
index.add(np.array(embeddings))
# -------------------------
# Load RAG model
# -------------------------
model_id = "microsoft/phi-3-mini-4k-instruct"
device = "cuda" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None
)
# -------------------------
# Load Whisper model
# -------------------------
whisper_model = whisper.load_model("base") # "tiny" for CPU
# -------------------------
# RAG helper functions
# -------------------------
def retrieve(query, top_k=3):
q_emb = embedder.encode([query])
D, I = index.search(np.array(q_emb), top_k)
return [all_chunks[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(device)
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 function
# -------------------------
def text_to_speech(text):
tts = gTTS(text=text, lang="en")
tts.save("answer.mp3")
return "answer.mp3"
# -------------------------
# Gradio interface
# -------------------------
def voice_bot(audio):
if audio is None:
return "No audio detected. Please record your question.", None
# Gradio may return (sample_rate, numpy_array)
if isinstance(audio, tuple):
sample_rate, audio_data = audio
else:
sample_rate = 44100 # default fallback
audio_data = audio
# Save audio as WAV
write("user_input.wav", sample_rate, audio_data)
# Step 1: Whisper transcription
query = whisper_model.transcribe("user_input.wav", language="en")['text'].strip()
print("User Asked:", query)
# Step 2: RAG answer
answer = ask_phi(query)
print("Answer:", answer)
# Step 3: TTS
audio_file = text_to_speech(answer)
return answer, audio_file
iface = gr.Interface(
fn=voice_bot,
inputs=gr.Audio(label="Record your question", type="numpy"), # no 'source' argument
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 with TTS playback."
)
iface.launch()