Gopikanth123 commited on
Commit
9f50d19
·
verified ·
1 Parent(s): 67403e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -146
app.py CHANGED
@@ -1,152 +1,159 @@
1
- import streamlit as st
2
- from gradio_client import Client
3
- import speech_recognition as sr
4
- import pyttsx3
5
- import threading
6
-
7
- # Initialize session state
8
- if "messages" not in st.session_state:
9
- st.session_state["messages"] = [] # Store chat history
10
-
11
- # Function to generate a response using Gradio client
12
- def generate_response(query):
13
- try:
14
- client = Client("Gopikanth123/llama2")
15
- result = client.predict(query=query, api_name="/predict")
16
- return result
17
- except Exception as e:
18
- return f"Error communicating with the Gradio backend: {e}"
19
-
20
- # Function to handle user input and bot response
21
- def handle_user_input(user_input):
22
- if user_input:
23
- # Add user message to session state
24
- st.session_state["messages"].append({"user": user_input})
25
-
26
- # Generate bot response
27
- response = generate_response(user_input)
28
- st.session_state["messages"].append({"bot": response})
29
-
30
- # Speak out bot response in a new thread to avoid blocking
31
- threading.Thread(target=speak_text, args=(response,), daemon=True).start()
32
-
33
- # Function for Speech Recognition (Voice Input)
34
- def recognize_speech():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  recognizer = sr.Recognizer()
36
- with sr.Microphone() as source:
37
- st.info("Listening... Speak into the microphone.")
38
- try:
39
- audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
40
- recognized_text = recognizer.recognize_google(audio)
41
- st.session_state["user_input"] = recognized_text # Set recognized text to input field
42
- st.success(f"Recognized Text: {recognized_text}")
43
- handle_user_input(recognized_text)
44
- except sr.WaitTimeoutError:
45
- st.warning("Listening timed out. No speech detected. Please try again.")
46
- except sr.UnknownValueError:
47
- st.error("Sorry, I couldn't understand the audio. Try speaking more clearly.")
48
- except sr.RequestError:
49
- st.error("Could not request results; please check your internet connection.")
50
- except Exception as e:
51
- st.error(f"An unexpected error occurred: {e}")
52
-
53
- # Function to speak text (Voice Output)
54
- def speak_text(text):
55
- engine = pyttsx3.init()
56
- engine.stop() # Ensure no previous loop is running
57
- engine.say(text)
58
- engine.runAndWait()
59
-
60
- # Main Streamlit app
61
- st.set_page_config(page_title="Llama2 Chatbot", page_icon="🤖", layout="wide")
62
- st.markdown(
63
- """
64
- <style>
65
- .stButton>button {
66
- background-color: #6C63FF;
67
- color: white;
68
- font-size: 16px;
69
- border-radius: 10px;
70
- padding: 10px 20px;
71
- }
72
- .stTextInput>div>input {
73
- border: 2px solid #6C63FF;
74
- border-radius: 10px;
75
- padding: 10px;
76
- }
77
- .chat-container {
78
- background-color: #F7F9FC;
79
- padding: 20px;
80
- border-radius: 15px;
81
- max-height: 400px;
82
- overflow-y: auto;
83
- }
84
- .chat-bubble {
85
- padding: 10px 15px;
86
- border-radius: 15px;
87
- margin: 5px 0;
88
- max-width: 80%;
89
- display: inline-block;
90
- }
91
- .user-message {
92
- background-color: #D1C4E9;
93
- text-align: left;
94
- margin-left: auto;
95
- }
96
- .bot-message {
97
- background-color: #BBDEFB;
98
- text-align: left;
99
- margin-right: auto;
100
- }
101
- .input-container {
102
- display: flex;
103
- justify-content: space-between;
104
- gap: 10px;
105
- padding: 10px 0;
106
- }
107
- </style>
108
- """,
109
- unsafe_allow_html=True
110
- )
111
-
112
- st.title("🤖 Chat with Llama2 Bot")
113
- st.markdown(
114
- """
115
  Welcome to the *Llama2 Chatbot*!
116
  - *Type* your message below, or
117
  - *Use the microphone* to speak to the bot.
118
- """
119
- )
120
-
121
- # Display chat history
122
- chat_history_container = st.container()
123
- with chat_history_container:
124
- # st.markdown("### Chat History")
125
- # st.markdown("<div class='chat-container' id='chat-container'>", unsafe_allow_html=True)
126
-
127
- # Update chat history dynamically
128
- def update_chat_history():
129
- chat_history = st.session_state["messages"]
130
- for msg in chat_history:
131
- if "user" in msg:
132
- st.markdown(f"<div class='chat-bubble user-message'><strong>You:</strong> {msg['user']}</div>", unsafe_allow_html=True)
133
- if "bot" in msg:
134
- st.markdown(f"<div class='chat-bubble bot-message'><strong>Bot:</strong> {msg['bot']}</div>", unsafe_allow_html=True)
135
-
136
- # Add input field within a form
137
- with st.form(key='input_form', clear_on_submit=True):
138
- user_input = st.text_input("Type your message here...", placeholder="Hello, how are you?")
139
- submit_button = st.form_submit_button("Send")
140
-
141
- # Handle form submission
142
- if submit_button:
143
- handle_user_input(user_input)
144
- # update_chat_history()
145
-
146
- # Separate button for speech recognition outside of the form
147
- if st.button("Speak"):
148
- recognize_speech()
149
- # update_chat_history()
150
  st.markdown("### Chat History")
151
- # Update chat history on every interaction
152
  update_chat_history()
 
1
+ import streamlit as st
2
+ import sounddevice as sd
3
+ import numpy as np
4
+ import speech_recognition as sr
5
+ import pyttsx3
6
+ import threading
7
+ import io
8
+ from gradio_client import Client
9
+
10
+ # Initialize session state
11
+ if "messages" not in st.session_state:
12
+ st.session_state["messages"] = [] # Store chat history
13
+
14
+ # Function to generate a response using Gradio client
15
+ def generate_response(query):
16
+ try:
17
+ client = Client("Gopikanth123/llama2")
18
+ result = client.predict(query=query, api_name="/predict")
19
+ return result
20
+ except Exception as e:
21
+ return f"Error communicating with the Gradio backend: {e}"
22
+
23
+ # Function to handle user input and bot response
24
+ def handle_user_input(user_input):
25
+ if user_input:
26
+ # Add user message to session state
27
+ st.session_state["messages"].append({"user": user_input})
28
+
29
+ # Generate bot response
30
+ response = generate_response(user_input)
31
+ st.session_state["messages"].append({"bot": response})
32
+
33
+ # Speak out bot response in a new thread to avoid blocking
34
+ threading.Thread(target=speak_text, args=(response,), daemon=True).start()
35
+
36
+ # Update chat history after each interaction
37
+ # update_chat_history()
38
+
39
+ # Function to speak text (Voice Output)
40
+ def speak_text(text):
41
+ engine = pyttsx3.init()
42
+ engine.stop() # Ensure no previous loop is running
43
+ engine.say(text)
44
+ engine.runAndWait()
45
+
46
+ # Function to update chat history dynamically
47
+ def update_chat_history():
48
+ chat_history = st.session_state["messages"]
49
+ for msg in chat_history:
50
+ if "user" in msg:
51
+ st.markdown(f"<div class='chat-bubble user-message'><strong>You:</strong> {msg['user']}</div>", unsafe_allow_html=True)
52
+ if "bot" in msg:
53
+ st.markdown(f"<div class='chat-bubble bot-message'><strong>Bot:</strong> {msg['bot']}</div>", unsafe_allow_html=True)
54
+
55
+ # Function to recognize speech using sounddevice
56
+ def recognize_speech_sounddevice():
57
+ st.info("Listening... Speak into the microphone.")
58
+ fs = 16000 # Sample rate in Hz
59
+ duration = 5 # Duration in seconds
60
+
61
+ # Record the audio using sounddevice
62
+ audio_data = sd.rec(int(duration * fs), samplerate=fs, channels=1, dtype='int16')
63
+ sd.wait()
64
+
65
+ # Convert the audio data to the format expected by speech_recognition
66
  recognizer = sr.Recognizer()
67
+ audio = sr.AudioData(audio_data.tobytes(), fs, 2)
68
+
69
+ try:
70
+ recognized_text = recognizer.recognize_google(audio)
71
+ st.session_state["user_input"] = recognized_text
72
+ st.success(f"Recognized Text: {recognized_text}")
73
+ handle_user_input(recognized_text)
74
+ except sr.UnknownValueError:
75
+ st.error("Sorry, I couldn't understand the audio.")
76
+ except sr.RequestError:
77
+ st.error("Could not request results; please check your internet connection.")
78
+
79
+
80
+ # Main Streamlit app
81
+ st.set_page_config(page_title="Llama2 Chatbot", page_icon="🤖", layout="wide")
82
+ st.markdown(
83
+ """
84
+ <style>
85
+ .stButton>button {
86
+ background-color: #6C63FF;
87
+ color: white;
88
+ font-size: 16px;
89
+ border-radius: 10px;
90
+ padding: 10px 20px;
91
+ }
92
+ .stTextInput>div>input {
93
+ border: 2px solid #6C63FF;
94
+ border-radius: 10px;
95
+ padding: 10px;
96
+ }
97
+ .chat-container {
98
+ background-color: #F7F9FC;
99
+ padding: 20px;
100
+ border-radius: 15px;
101
+ max-height: 400px;
102
+ overflow-y: auto;
103
+ }
104
+ .chat-bubble {
105
+ padding: 10px 15px;
106
+ border-radius: 15px;
107
+ margin: 5px 0;
108
+ max-width: 80%;
109
+ display: inline-block;
110
+ }
111
+ .user-message {
112
+ background-color: #D1C4E9;
113
+ text-align: left;
114
+ margin-left: auto;
115
+ }
116
+ .bot-message {
117
+ background-color: #BBDEFB;
118
+ text-align: left;
119
+ margin-right: auto;
120
+ }
121
+ .input-container {
122
+ display: flex;
123
+ justify-content: space-between;
124
+ gap: 10px;
125
+ padding: 10px 0;
126
+ }
127
+ </style>
128
+ """,
129
+ unsafe_allow_html=True
130
+ )
131
+
132
+ st.title("🤖 Chat with Llama2 Bot")
133
+ st.markdown(
134
+ """
 
 
 
 
 
 
 
 
 
 
 
135
  Welcome to the *Llama2 Chatbot*!
136
  - *Type* your message below, or
137
  - *Use the microphone* to speak to the bot.
138
+ """
139
+ )
140
+
141
+ # Display chat history
142
+ chat_history_container = st.container()
143
+ with chat_history_container:
144
+ # Add input field within a form
145
+ with st.form(key='input_form', clear_on_submit=True):
146
+ user_input = st.text_input("Type your message here...", placeholder="Hello, how are you?")
147
+ submit_button = st.form_submit_button("Send")
148
+
149
+ # Handle form submission
150
+ if submit_button:
151
+ handle_user_input(user_input)
152
+
153
+ # Separate button for speech recognition outside of the form
154
+ if st.button("Speak"):
155
+ recognize_speech_sounddevice()
156
+
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  st.markdown("### Chat History")
158
+ # Update chat history on every interaction
159
  update_chat_history()