Spaces:
Sleeping

File size: 5,017 Bytes
f5832cb
 
 
 
 
 
 
 
a502172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5832cb
 
 
 
 
e22a3fa
f5832cb
 
 
e22a3fa
 
f5832cb
 
 
 
 
a502172
f5832cb
 
a502172
f5832cb
 
 
 
a502172
f5832cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e22a3fa
f5832cb
 
 
 
 
 
 
 
 
 
 
 
a502172
f5832cb
 
 
 
 
 
 
a502172
f5832cb
e0f456f
f5832cb
e0f456f
 
 
 
 
 
 
 
 
 
 
 
f5832cb
a502172
f5832cb
 
 
a502172
f5832cb
 
 
 
 
 
 
 
1940c4d
f5832cb
 
1940c4d
f5832cb
 
a502172
f5832cb
 
1940c4d
f5832cb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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()