mahazainab commited on
Commit
b0e009e
1 Parent(s): f9a3a93

Update code

Browse files
Files changed (1) hide show
  1. app.py +105 -60
app.py CHANGED
@@ -1,64 +1,109 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
62
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
  import gradio as gr
5
+ import whisper
6
+ from gtts import gTTS
7
+ from groq import Groq
8
+ import pandas as pd
9
+ import numpy as np
10
+ from sentence_transformers import SentenceTransformer
11
+ import faiss
12
+
13
+ index_file_path="faiss_index.index"
14
+ embeddings_file_path="embeddings.npy"
15
+ # Load Whisper model for transcription
16
+ model = whisper.load_model("base")
17
+
18
+ # Set up Groq API client (make sure your API key is correct)
19
+ client = Groq(api_key="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")
20
+
21
+ # Load the dataset
22
+ df = pd.read_json("hf://datasets/Amod/mental_health_counseling_conversations/combined_dataset.json", lines=True)
23
+
24
+
25
+ corpus = df['Context'].dropna().tolist()
26
+
27
+ # Initialize SentenceTransformer to generate embeddings
28
+ embedder = SentenceTransformer('paraphrase-MiniLM-L6-v2')
29
+
30
+ # Function to load or build the FAISS index
31
+ def load_or_build_index():
32
+ if os.path.exists(index_file_path) and os.path.exists(embeddings_file_path):
33
+ print("Loading existing index and embeddings...")
34
+ index = faiss.read_index(index_file_path)
35
+ embeddings = np.load(embeddings_file_path)
36
+ else:
37
+ print("Building new index...")
38
+ embeddings = embedder.encode(corpus, convert_to_numpy=True)
39
+ dimension = embeddings.shape[1]
40
+ index = faiss.IndexFlatL2(dimension) # FAISS index for L2 (Euclidean) distance
41
+ index.add(embeddings)
42
+ faiss.write_index(index, index_file_path) # Save the index to disk
43
+ np.save(embeddings_file_path, embeddings) # Save embeddings to disk
44
+ return index, embeddings
45
+
46
+ # Load or build the FAISS index
47
+ index, corpus_embeddings = load_or_build_index()
48
+
49
+ # Function to retrieve the most relevant context from the corpus using FAISS
50
+ def retrieve_relevant_context(user_input):
51
+ user_input_embedding = embedder.encode([user_input]) # Convert the user's query into an embedding
52
+ k = 1 # Retrieve the top 1 most relevant document
53
+ D, I = index.search(user_input_embedding, k) # Perform the search in the FAISS index
54
+ return corpus[I[0][0]] # Return the most relevant document
55
+
56
+ # Function to process the audio input, retrieve context, and generate a response
57
+ def chatbot(audio):
58
+ # Transcribe the audio input using Whisper
59
+ transcription = model.transcribe(audio)
60
+ user_input = transcription["text"]
61
+
62
+ # Retrieve the most relevant context from the dataset using the vector database (FAISS)
63
+ relevant_context = retrieve_relevant_context(user_input)
64
+
65
+ # Generate a response using the Groq API with Llama 8B, including relevant context
66
+ chat_completion = client.chat.completions.create(
67
+ messages=[
68
+ {"role": "user", "content": user_input},
69
+ {"role": "system", "content": f"Context: {relevant_context}"}
70
+ ],
71
+ model="llama3-8b-8192"
72
+ )
73
+
74
+ # Extract the generated response text
75
+ response_text = chat_completion.choices[0].message.content
76
+
77
+ # Convert the response text to speech using gTTS
78
+ tts = gTTS(text=response_text, lang='en')
79
+ tts.save("response.mp3")
80
+
81
+ return response_text, "response.mp3"
82
+
83
+ # Create a custom Gradio interface
84
+ def build_interface():
85
+ with gr.Blocks() as demo:
86
+ gr.Markdown(
87
+ """
88
+ <h1 style="text-align: center; color: #4CAF50;">Chill Parents</h1>
89
+ <h3 style="text-align: center;">Chatbot to help parents and other family members to reduce stress between them</h3>
90
+ <p style="text-align: center;">Talk to the AI-powered chatbot and get responses in real-time. Start by recording your voice.</p>
91
+ """
92
+ )
93
+ with gr.Row():
94
+ with gr.Column(scale=1):
95
+ audio_input = gr.Audio(type="filepath", label="Record Your Voice")
96
+ with gr.Column(scale=2):
97
+ chatbot_output_text = gr.Textbox(label="Chatbot Response")
98
+ chatbot_output_audio = gr.Audio(label="Audio Response")
99
+
100
+ submit_button = gr.Button("Submit")
101
+
102
+ submit_button.click(chatbot, inputs=audio_input, outputs=[chatbot_output_text, chatbot_output_audio])
103
 
104
+ return demo
105
 
106
+ # Launch the interface
107
  if __name__ == "__main__":
108
+ interface = build_interface()
109
+ interface.launch()