File size: 5,125 Bytes
cdb0af7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import streamlit as st
import speech_recognition as sr
from openai import OpenAI

# Initialize session state for chat visibility
if "chat_started" not in st.session_state:
    st.session_state.chat_started = False

if "chat_history" not in st.session_state:
    st.session_state.chat_history = []
if "feedback" not in st.session_state:
    st.session_state.feedback = {}

st.set_page_config(page_title="🍽️ Food Chatbot", page_icon="🍽️", layout="wide")

# 🎯 Welcome Screen (Only Show if Chat Not Started)
if not st.session_state.chat_started:
    st.title("πŸ€– Welcome to the Foodie Chatbot!")
    st.write("Your go-to chatbot for all things food: recipes, restaurant recommendations, and more!")

    st.subheader("✨ Features")
    st.markdown("""
    - 🍲 **Get Recipes**: Find delicious recipes based on ingredients or dish names.
    - πŸ›’ **Where to Buy**: Discover where you can buy specific food items.
    - 🍽️ **Restaurant Recommendations**: Find the best restaurants serving your favorite dishes.
    - πŸŽ™οΈ **Voice Input**: Speak your query instead of typing.
    - πŸ“œ **Chat History**: Track your past questions and answers.
    """)

    if st.button("πŸš€ Start Chat"):
        st.session_state.chat_started = True
        st.rerun()
    st.stop()

st.title("🍽️ Foodie Chatbot")

# 🎀 Function to capture voice input
def get_voice_input():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        st.info("🎀 Listening... Speak now!")
        try:
            audio = recognizer.listen(source, timeout=5)
            text = recognizer.recognize_google(audio)
            return text
        except sr.UnknownValueError:
            st.error("πŸ˜• Could not understand the audio.")
        except sr.RequestError:
            st.error("πŸ”Œ Speech Recognition service unavailable.")
    return ""

# 🎀 Voice Input Button
if st.button("🎀 Speak Query"):
    voice_text = get_voice_input()
    if voice_text:
        st.session_state["user_prompt"] = voice_text
    else:
        st.warning("No voice input detected.")

# πŸ“ User Input Text Area
user_prompt = st.text_area("Enter Any Food:", st.session_state.get("user_prompt", ""))

# βš™οΈ Sidebar Settings
st.sidebar.header("βš™οΈ Settings")
output_format = st.sidebar.selectbox("Select Query Type", ["Recipe", "Where to Buy", "Best Restaurant"])
max_tokens = st.sidebar.slider("Response Length (Max Tokens)", 100, 1024, 500)
creative_mode = st.sidebar.checkbox("Enable Creative Mode", value=True)

# πŸ“œ Chat History in Sidebar
st.sidebar.header("πŸ“œ Chat History")
if st.sidebar.button("πŸ—‘οΈ Clear Chat History"):
    st.session_state.chat_history = []
    st.session_state.feedback = {}

with st.sidebar.expander("πŸ” View Chat History", expanded=False):
    for i, chat in enumerate(reversed(st.session_state.chat_history)):
        st.markdown(f"**User:** {chat['user']}")
        bot_preview = chat['bot'][:200] + ("..." if len(chat['bot']) > 200 else "")
        st.markdown(f"**Bot:** {bot_preview}")

        if len(chat['bot']) > 200:
            if st.toggle(f"πŸ“– Show Full Response ({i+1})", key=f"toggle_{i}"):
                st.markdown(chat['bot'])

        feedback_value = st.session_state.feedback.get(chat['user'], "No Feedback Given")
        st.markdown(f"**Feedback:** {feedback_value}")
        st.markdown("---")

response_container = st.empty()
feedback_container = st.empty()

# πŸš€ Generate Response
if st.button("Generate Response"):
    if user_prompt.strip():
        client = OpenAI(
            base_url="https://integrate.api.nvidia.com/v1",
            api_key="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"
        )

        messages = [{"role": "user", "content": f"Provide information about {user_prompt} as a {output_format.lower()}"}]

        try:
            completion = client.chat.completions.create(
                model="tiiuae/falcon3-7b-instruct",
                messages=messages,
                top_p=0.9 if creative_mode else 0.7,
                max_tokens=max_tokens,
                stream=True
            )

            response_text = ""
            progress_text = st.empty()

            for chunk in completion:
                if chunk.choices[0].delta.content is not None:
                    response_text += chunk.choices[0].delta.content
                    progress_text.markdown(f"### Generating... ⏳\n{response_text}")

            progress_text.empty()
            response_container.markdown(f"### Generated Response\n{response_text}")

            chat_entry = {"user": user_prompt, "bot": response_text}
            st.session_state.chat_history.append(chat_entry)

            feedback = feedback_container.radio(
                "Was this response helpful?",
                ["πŸ‘ Yes", "πŸ‘Ž No"],
                index=None,
                key=f"feedback_{len(st.session_state.chat_history)}",
                horizontal=True
            )

            st.session_state.feedback[user_prompt] = feedback

        except Exception as e:
            st.error(f"❌ Error: {e}")