smruthi49 commited on
Commit
0f421f4
·
verified ·
1 Parent(s): 89a74d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -60
app.py CHANGED
@@ -1,64 +1,130 @@
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
  import gradio as gr
2
+ import asyncio
3
+ from deepgram import DeepgramClientOptions, DeepgramClient
4
+ from pydub import AudioSegment
5
+ from pydub.playback import play
6
+ import io
7
+ import os
8
+ import time
9
+ import re
10
+ from langchain_core.prompts import ChatPromptTemplate
11
+ from langchain_groq import ChatGroq
12
+ from langchain.memory import ConversationBufferMemory
13
+ from langchain.chains import LLMChain
14
+ import httpx
15
+ from dotenv import load_dotenv
16
+
17
+ # Load environment variables
18
+ load_dotenv()
19
+
20
+ class LanguageModelProcessor:
21
+ def __init__(self):
22
+ self.llm = ChatGroq(temperature=0, model_name="llama3-8b-8192", groq_api_key=os.getenv("GROQ_API_KEY"))
23
+ self.memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
24
+ with open('system_prompt.txt', 'r') as file:
25
+ system_prompt = file.read().strip()
26
+ self.prompt = ChatPromptTemplate.from_messages([
27
+ SystemMessagePromptTemplate.from_template(system_prompt),
28
+ ChatPromptTemplate.MessagesPlaceholder(variable_name="chat_history"),
29
+ ChatPromptTemplate.HumanMessagePromptTemplate.from_template("{text}")
30
+ ])
31
+ self.conversation = LLMChain(
32
+ llm=self.llm,
33
+ prompt=self.prompt,
34
+ memory=self.memory
35
+ )
36
+
37
+ def process(self, text):
38
+ self.memory.chat_memory.add_user_message(text)
39
+ start_time = time.time()
40
+ response = self.conversation.invoke({"text": text})
41
+ end_time = time.time()
42
+ self.memory.chat_memory.add_ai_message(response['text'])
43
+ elapsed_time = int((end_time - start_time) * 1000)
44
+ return response['text']
45
+
46
+
47
+ class TextToSpeech:
48
+ DG_API_KEY = os.getenv("DEEPGRAM_API_KEY")
49
+ MODEL_NAME = "aura-asteria-en"
50
+
51
+ def speak(self, text):
52
+ DEEPGRAM_URL = f"https://api.deepgram.com/v1/speak?model={self.MODEL_NAME}"
53
+ headers = {
54
+ "Authorization": f"Token {self.DG_API_KEY}",
55
+ "Content-Type": "application/json"
56
+ }
57
+ payload = {"text": text}
58
+ response = requests.post(DEEPGRAM_URL, headers=headers, json=payload)
59
+ if response.status_code == 200:
60
+ audio = AudioSegment.from_mp3(io.BytesIO(response.content))
61
+ play(audio)
62
+ else:
63
+ print(f"Error: {response.status_code}, {response.text}")
64
+
65
+
66
+ class ConversationManager:
67
+ def __init__(self):
68
+ self.llm = LanguageModelProcessor()
69
+ self.tts = TextToSpeech()
70
+ self.commodity = None
71
+ self.state = None
72
+ self.district = None
73
+
74
+ def run_conversation(self, transcription_response):
75
+ if not self.commodity or not self.state or not self.district:
76
+ llm_response = self.llm.process(transcription_response)
77
+ details = self.extract_details_from_llm_response(llm_response)
78
+ if details == 'No details.':
79
+ self.tts.speak(llm_response)
80
+ return llm_response
81
+ else:
82
+ return self.fetch_commodity_prices()
83
+
84
+ def extract_details_from_llm_response(self, response):
85
+ pattern = r'\[commodity, state, district\] = \[([^,]+), ([^,]+), ([^\]]+)\]'
86
+ match = re.search(pattern, response)
87
+ if match:
88
+ self.commodity = match.group(1)
89
+ self.state = match.group(2)
90
+ self.district = match.group(3)
91
+ return f"Commodity: {self.commodity}, State: {self.state}, District: {self.district}"
92
+ else:
93
+ return "No details."
94
+
95
+ async def fetch_commodity_prices(self):
96
+ return "Fetching commodity prices..."
97
+
98
+
99
+ def gradio_interface(input_text):
100
+ # Instantiate the Conversation Manager
101
+ manager = ConversationManager()
102
+ # Process the input and return response
103
+ response = manager.run_conversation(input_text)
104
+ return response
105
+
106
+
107
+ # Gradio UI Definition
108
+ def gradio_app():
109
+ # Define Gradio Interface
110
+ with gr.Blocks() as demo:
111
+ gr.Markdown("# Commodity Price Chatbot with LLM and Speech")
112
+
113
+ with gr.Row():
114
+ input_box = gr.Textbox(label="Speak/Type your message", placeholder="Enter your message here...")
115
+ output_box = gr.Textbox(label="Response", interactive=False)
116
+
117
+ with gr.Row():
118
+ mic_button = gr.Audio(source="microphone", type="microphone", label="Use microphone")
119
+ submit_button = gr.Button("Submit")
120
+
121
+ submit_button.click(fn=gradio_interface, inputs=input_box, outputs=output_box)
122
+ mic_button.change(fn=gradio_interface, inputs=mic_button, outputs=output_box)
123
+
124
+ return demo
125
 
126
 
127
  if __name__ == "__main__":
128
+ app = gradio_app()
129
+ app.launch()
130
+