Gopikanth123 commited on
Commit
65ea836
·
verified ·
1 Parent(s): 8585ad9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -0
app.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()