renamed to app.py
Browse files
app.py
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import speech_recognition as sr
|
3 |
+
from openai import OpenAI
|
4 |
+
|
5 |
+
# Initialize session state for chat visibility
|
6 |
+
if "chat_started" not in st.session_state:
|
7 |
+
st.session_state.chat_started = False
|
8 |
+
|
9 |
+
if "chat_history" not in st.session_state:
|
10 |
+
st.session_state.chat_history = []
|
11 |
+
if "feedback" not in st.session_state:
|
12 |
+
st.session_state.feedback = {}
|
13 |
+
|
14 |
+
st.set_page_config(page_title="π½οΈ Food Chatbot", page_icon="π½οΈ", layout="wide")
|
15 |
+
|
16 |
+
# π― Welcome Screen (Only Show if Chat Not Started)
|
17 |
+
if not st.session_state.chat_started:
|
18 |
+
st.title("π€ Welcome to the Foodie Chatbot!")
|
19 |
+
st.write("Your go-to chatbot for all things food: recipes, restaurant recommendations, and more!")
|
20 |
+
|
21 |
+
st.subheader("β¨ Features")
|
22 |
+
st.markdown("""
|
23 |
+
- π² **Get Recipes**: Find delicious recipes based on ingredients or dish names.
|
24 |
+
- π **Where to Buy**: Discover where you can buy specific food items.
|
25 |
+
- π½οΈ **Restaurant Recommendations**: Find the best restaurants serving your favorite dishes.
|
26 |
+
- ποΈ **Voice Input**: Speak your query instead of typing.
|
27 |
+
- π **Chat History**: Track your past questions and answers.
|
28 |
+
""")
|
29 |
+
|
30 |
+
if st.button("π Start Chat"):
|
31 |
+
st.session_state.chat_started = True
|
32 |
+
st.rerun()
|
33 |
+
st.stop()
|
34 |
+
|
35 |
+
st.title("π½οΈ Foodie Chatbot")
|
36 |
+
|
37 |
+
# π€ Function to capture voice input
|
38 |
+
def get_voice_input():
|
39 |
+
recognizer = sr.Recognizer()
|
40 |
+
with sr.Microphone() as source:
|
41 |
+
st.info("π€ Listening... Speak now!")
|
42 |
+
try:
|
43 |
+
audio = recognizer.listen(source, timeout=5)
|
44 |
+
text = recognizer.recognize_google(audio)
|
45 |
+
return text
|
46 |
+
except sr.UnknownValueError:
|
47 |
+
st.error("π Could not understand the audio.")
|
48 |
+
except sr.RequestError:
|
49 |
+
st.error("π Speech Recognition service unavailable.")
|
50 |
+
return ""
|
51 |
+
|
52 |
+
# π€ Voice Input Button
|
53 |
+
if st.button("π€ Speak Query"):
|
54 |
+
voice_text = get_voice_input()
|
55 |
+
if voice_text:
|
56 |
+
st.session_state["user_prompt"] = voice_text
|
57 |
+
else:
|
58 |
+
st.warning("No voice input detected.")
|
59 |
+
|
60 |
+
# π User Input Text Area
|
61 |
+
user_prompt = st.text_area("Enter Any Food:", st.session_state.get("user_prompt", ""))
|
62 |
+
|
63 |
+
# βοΈ Sidebar Settings
|
64 |
+
st.sidebar.header("βοΈ Settings")
|
65 |
+
output_format = st.sidebar.selectbox("Select Query Type", ["Recipe", "Where to Buy", "Best Restaurant"])
|
66 |
+
max_tokens = st.sidebar.slider("Response Length (Max Tokens)", 100, 1024, 500)
|
67 |
+
creative_mode = st.sidebar.checkbox("Enable Creative Mode", value=True)
|
68 |
+
|
69 |
+
# π Chat History in Sidebar
|
70 |
+
st.sidebar.header("π Chat History")
|
71 |
+
if st.sidebar.button("ποΈ Clear Chat History"):
|
72 |
+
st.session_state.chat_history = []
|
73 |
+
st.session_state.feedback = {}
|
74 |
+
|
75 |
+
with st.sidebar.expander("π View Chat History", expanded=False):
|
76 |
+
for i, chat in enumerate(reversed(st.session_state.chat_history)):
|
77 |
+
st.markdown(f"**User:** {chat['user']}")
|
78 |
+
bot_preview = chat['bot'][:200] + ("..." if len(chat['bot']) > 200 else "")
|
79 |
+
st.markdown(f"**Bot:** {bot_preview}")
|
80 |
+
|
81 |
+
if len(chat['bot']) > 200:
|
82 |
+
if st.toggle(f"π Show Full Response ({i+1})", key=f"toggle_{i}"):
|
83 |
+
st.markdown(chat['bot'])
|
84 |
+
|
85 |
+
feedback_value = st.session_state.feedback.get(chat['user'], "No Feedback Given")
|
86 |
+
st.markdown(f"**Feedback:** {feedback_value}")
|
87 |
+
st.markdown("---")
|
88 |
+
|
89 |
+
response_container = st.empty()
|
90 |
+
feedback_container = st.empty()
|
91 |
+
|
92 |
+
# π Generate Response
|
93 |
+
if st.button("Generate Response"):
|
94 |
+
if user_prompt.strip():
|
95 |
+
client = OpenAI(
|
96 |
+
base_url="https://integrate.api.nvidia.com/v1",
|
97 |
+
api_key="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"
|
98 |
+
)
|
99 |
+
|
100 |
+
messages = [{"role": "user", "content": f"Provide information about {user_prompt} as a {output_format.lower()}"}]
|
101 |
+
|
102 |
+
try:
|
103 |
+
completion = client.chat.completions.create(
|
104 |
+
model="tiiuae/falcon3-7b-instruct",
|
105 |
+
messages=messages,
|
106 |
+
top_p=0.9 if creative_mode else 0.7,
|
107 |
+
max_tokens=max_tokens,
|
108 |
+
stream=True
|
109 |
+
)
|
110 |
+
|
111 |
+
response_text = ""
|
112 |
+
progress_text = st.empty()
|
113 |
+
|
114 |
+
for chunk in completion:
|
115 |
+
if chunk.choices[0].delta.content is not None:
|
116 |
+
response_text += chunk.choices[0].delta.content
|
117 |
+
progress_text.markdown(f"### Generating... β³\n{response_text}")
|
118 |
+
|
119 |
+
progress_text.empty()
|
120 |
+
response_container.markdown(f"### Generated Response\n{response_text}")
|
121 |
+
|
122 |
+
chat_entry = {"user": user_prompt, "bot": response_text}
|
123 |
+
st.session_state.chat_history.append(chat_entry)
|
124 |
+
|
125 |
+
feedback = feedback_container.radio(
|
126 |
+
"Was this response helpful?",
|
127 |
+
["π Yes", "π No"],
|
128 |
+
index=None,
|
129 |
+
key=f"feedback_{len(st.session_state.chat_history)}",
|
130 |
+
horizontal=True
|
131 |
+
)
|
132 |
+
|
133 |
+
st.session_state.feedback[user_prompt] = feedback
|
134 |
+
|
135 |
+
except Exception as e:
|
136 |
+
st.error(f"β Error: {e}")
|