File size: 13,565 Bytes
1292ed1
74a6ec1
8622a36
74a6ec1
695c0fc
97ed4c6
43ff131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b922996
767b287
8627d53
 
 
cceffd8
8627d53
 
43ff131
 
 
 
 
1292ed1
 
cceffd8
1dd8568
e46e0c0
cceffd8
4db3cf5
3ff9487
1dd8568
 
 
 
 
 
 
43ff131
6f37b53
43ff131
3ff9487
cceffd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46e0c0
 
43ff131
 
 
41aab98
e46e0c0
 
 
 
 
 
 
 
 
 
 
 
 
f34b1bf
 
767b287
43ff131
e46e0c0
cceffd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46e0c0
 
 
 
 
f34b1bf
e46e0c0
43ff131
 
 
 
41aab98
1dbf749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46e0c0
43ff131
dc7c09f
43ff131
 
 
dc7c09f
 
 
 
 
 
061722d
 
dc7c09f
 
 
43ff131
41aab98
cceffd8
 
 
 
 
 
 
 
 
 
 
 
 
 
41aab98
 
43ff131
 
 
 
41aab98
 
 
 
 
 
 
43ff131
41aab98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43ff131
41aab98
 
 
 
 
 
cceffd8
41aab98
 
 
 
 
 
 
 
 
 
 
 
cceffd8
41aab98
 
 
 
 
 
1292ed1
cceffd8
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import streamlit as st
import time
import requests
from streamlit.components.v1 import html
import os
from dotenv import load_dotenv
import numpy as np
import torchaudio
from audio_recorder_streamlit import audio_recorder
import torch
from io import BytesIO
import hashlib

# Load Whisper model (cached)
@st.cache_resource
def load_model():
    return pipeline("automatic-speech-recognition", model="openai/whisper-base")

# Audio processing function
def process_audio(audio_bytes):
    waveform, sample_rate = torchaudio.load(BytesIO(audio_bytes))
    if waveform.shape[0] > 1:  # Convert stereo to mono
        waveform = torch.mean(waveform, dim=0, keepdim=True)
    if sample_rate != 16000:  # Resample to 16kHz if needed
        resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)
        waveform = resampler(waveform)
    return {"raw": waveform.numpy().squeeze(), "sampling_rate": 16000}

# Voice input component
def voice_input(key, prompt_text, default_text=""):
    col1, col2 = st.columns([4, 1])
    with col1:
        text_input = st.text_input(prompt_text, value=default_text, key=f"text_{key}")
    with col2:
        audio_bytes = audio_recorder(
            pause_threshold=0.8,
            text="๐ŸŽค Speak",
            recording_color="#e8b622",
            neutral_color="#6aa36f",
            key=f"recorder_{key}"
        )
    
    # Process audio if new recording is available
    if audio_bytes:
        current_hash = hashlib.md5(audio_bytes).hexdigest()
        if f"last_audio_hash_{key}" not in st.session_state or current_hash != st.session_state[f"last_audio_hash_{key}"]:
            st.session_state[f"last_audio_hash_{key}"] = current_hash
            try:
                audio_input = process_audio(audio_bytes)
                whisper = load_model()
                transcribed_text = whisper(audio_input)["text"]
                
                # Update the corresponding text input
                st.session_state[f"text_{key}"] = transcribed_text
                st.rerun()
                
            except Exception as e:
                st.error(f"Error in voice input: {str(e)}")
    
    return text_input

# Import transformers and cache the help agent for performance
@st.cache_resource
def get_help_agent():
    from transformers import pipeline
    # Using BlenderBot 400M Distill as the public conversational model (used elsewhere)
    return pipeline("conversational", model="facebook/blenderbot-400M-distill")

# [Rest of your existing functions remain exactly the same...]
# inject_custom_css()
# show_confetti()
# ask_llama()
# ask_help_agent()

def main():
    inject_custom_css()

    st.markdown('<div class="title">KASOTI</div>', unsafe_allow_html=True)
    st.markdown('<div class="subtitle">AI-Powered Guessing Game Challenge</div>', unsafe_allow_html=True)

    if 'game_state' not in st.session_state:
        st.session_state.game_state = "start"
        st.session_state.questions = []
        st.session_state.current_q = 0
        st.session_state.answers = []
        st.session_state.conversation_history = []
        st.session_state.category = None
        st.session_state.final_guess = None
        st.session_state.help_conversation = []

    # Start screen with voice input
    if st.session_state.game_state == "start":
        with st.container():
            st.markdown("""
            <div class="question-box">
                <h3 style="color: #6C63FF; margin-bottom: 1.5rem;">๐ŸŽฎ Welcome to KASOTI</h3>
                <p style="line-height: 1.6; color: #64748B;">
                    Think of something and I'll try to guess it in 20 questions or less!<br>
                    Choose from these categories:
                </p>
                <div style="display: grid; gap: 1rem; margin: 2rem 0;">
                    <div style="padding: 1.5rem; background: #f8f9fa; border-radius: 12px;">
                        <h4 style="margin: 0; color: #6C63FF;">๐Ÿง‘ Person</h4>
                        <p style="margin: 0.5rem 0 0; color: #64748B;">Celebrity, fictional character, historical figure</p>
                    </div>
                    <div style="padding: 1.5rem; background: #f8f9fa; border-radius: 12px;">
                        <h4 style="margin: 0; color: #6C63FF;">๐ŸŒ Place</h4>
                        <p style="margin: 0.5rem 0 0; color: #64748B;">City, country, landmark, geographical location</p>
                    </div>
                    <div style="padding: 1.5rem; background: #f8f9fa; border-radius: 12px;">
                        <h4 style="margin: 0; color: #6C63FF;">๐ŸŽฏ Object</h4>
                        <p style="margin: 0.5rem 0 0; color: #64748B;">Everyday item, tool, vehicle, or concept</p>
                    </div>
                </div>
            </div>
            """, unsafe_allow_html=True)

        with st.form("start_form"):
            # Replace text input with voice input component
            category_input = voice_input("category", "Enter category (person/place/object):").strip().lower()
            
            if st.form_submit_button("Start Game"):
                if not category_input:
                    st.error("Please enter a category!")
                elif category_input not in ["person", "place", "object"]:
                    st.error("Please enter either 'person', 'place', or 'object'!")
                else:
                    st.session_state.category = category_input
                    first_question = ask_llama([
                        {"role": "user", "content": "Ask your first strategic yes/no question."}
                    ], category_input)
                    st.session_state.questions = [first_question]
                    st.session_state.conversation_history = [
                        {"role": "assistant", "content": first_question}
                    ]
                    st.session_state.game_state = "gameplay"
                    st.experimental_rerun()

    # Gameplay screen with voice answer input
    elif st.session_state.game_state == "gameplay":
        with st.container():
            progress = (st.session_state.current_q + 1) / 20
            st.markdown(f"""
            <div class="question-count">QUESTION {st.session_state.current_q + 1} OF 20</div>
            <div class="progress-bar">
                <div class="progress-fill" style="width: {progress * 100}%"></div>
            </div>
            """, unsafe_allow_html=True)

            current_question = st.session_state.questions[st.session_state.current_q]
            
            st.markdown(f'''
            <div class="question-box">
                <div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1.5rem;">
                    <div style="background: #6C63FF; width: 40px; height: 40px; border-radius: 50%; 
                            display: flex; align-items: center; justify-content: center; color: white;">
                        <i class="fas fa-robot"></i>
                    </div>
                    <h3 style="margin: 0; color: #1E293B;">AI Question</h3>
                </div>
                <p style="font-size: 1.1rem; line-height: 1.6; color: #1E293B;">{current_question}</p>
            </div>
            ''', unsafe_allow_html=True)

        if "Final Guess:" in current_question:
            st.session_state.final_guess = current_question.split("Final Guess:")[1].strip()
            st.session_state.game_state = "confirm_guess"
            st.experimental_rerun()

        with st.form("answer_form"):
            # Replace text input with voice input component for answers
            answer_input = voice_input(f"answer_{st.session_state.current_q}", 
                                     "Your answer (yes/no/both):").strip().lower()
            
            if st.form_submit_button("Submit"):
                if answer_input not in ["yes", "no", "both"]:
                    st.error("Please answer with 'yes', 'no', or 'both'!")
                else:
                    st.session_state.answers.append(answer_input)
                    st.session_state.conversation_history.append(
                        {"role": "user", "content": answer_input}
                    )

                    next_response = ask_llama(
                        st.session_state.conversation_history,
                        st.session_state.category
                    )

                    if "Final Guess:" in next_response:
                        st.session_state.final_guess = next_response.split("Final Guess:")[1].strip()
                        st.session_state.game_state = "confirm_guess"
                    else:
                        st.session_state.questions.append(next_response)
                        st.session_state.conversation_history.append(
                            {"role": "assistant", "content": next_response}
                        )
                        st.session_state.current_q += 1

                        if st.session_state.current_q >= 20:
                            st.session_state.game_state = "result"

                    st.experimental_rerun()

        # Help assistant with voice input
        with st.expander("Need Help? Chat with AI Assistant"):
            # Replace help query input with voice input
            help_query = voice_input("help_query", "Enter your help query:")
            
            if st.button("Send", key="send_help"):
                if help_query:
                    help_response = ask_help_agent(help_query)
                    st.session_state.help_conversation.append({"query": help_query, "response": help_response})
                else:
                    st.error("Please enter a query!")
            if st.session_state.help_conversation:
                for msg in st.session_state.help_conversation:
                    st.markdown(f"**You:** {msg['query']}")
                    st.markdown(f"**Help Assistant:** {msg['response']}")

    # Guess confirmation with voice input
    elif st.session_state.game_state == "confirm_guess":
        st.markdown(f'''
        <div class="question-box">
            <div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1.5rem;">
                <div style="background: #6C63FF; width: 40px; height: 40px; border-radius: 50%; 
                        display: flex; align-items: center; justify-content: center; color: white;">
                    <i class="fas fa-lightbulb"></i>
                </div>
                <h3 style="margin: 0; color: #1E293B;">AI's Final Guess</h3>
            </div>
            <p style="font-size: 1.2rem; line-height: 1.6; color: #1E293B;">
                Is it <strong style="color: #6C63FF;">{st.session_state.final_guess}</strong>?
            </p>
        </div>
        ''', unsafe_allow_html=True)

        with st.form("confirm_form"):
            # Replace confirmation input with voice input
            confirm_input = voice_input("confirm_input", 
                                       "Type your answer (yes/no/both):").strip().lower()
            
            if st.form_submit_button("Submit"):
                if confirm_input not in ["yes", "no", "both"]:
                    st.error("Please answer with 'yes', 'no', or 'both'!")
                else:
                    if confirm_input == "yes":
                        st.session_state.game_state = "result"
                        st.experimental_rerun()
                        st.stop()
                    else:
                        st.session_state.conversation_history.append(
                            {"role": "user", "content": "no"}
                        )
                        st.session_state.game_state = "gameplay"
                        next_response = ask_llama(
                            st.session_state.conversation_history,
                            st.session_state.category
                        )
                        st.session_state.questions.append(next_response)
                        st.session_state.conversation_history.append(
                            {"role": "assistant", "content": next_response}
                        )
                        st.session_state.current_q += 1
                        st.experimental_rerun()

    # Result screen (unchanged)
    elif st.session_state.game_state == "result":
        if not st.session_state.final_guess:
            qa_history = "\n".join(
                [f"Q{i+1}: {q}\nA: {a}"
                 for i, (q, a) in enumerate(zip(st.session_state.questions, st.session_state.answers))]
            )

            final_guess = ask_llama(
                [{"role": "user", "content": qa_history}],
                st.session_state.category,
                is_final_guess=True
            )
            st.session_state.final_guess = final_guess.split("Final Guess:")[-1].strip()

        show_confetti()
        st.markdown(f'<div class="final-reveal">๐ŸŽ‰ It\'s...</div>', unsafe_allow_html=True)
        time.sleep(1)
        st.markdown(f'<div class="final-reveal" style="font-size:3.5rem;color:#6C63FF;">{st.session_state.final_guess}</div>',
                    unsafe_allow_html=True)
        st.markdown(f"<p style='text-align:center; color:#64748B;'>Guessed in {len(st.session_state.questions)} questions</p>",
                    unsafe_allow_html=True)

        if st.button("Play Again", key="play_again"):
            st.session_state.clear()
            st.experimental_rerun()

if __name__ == "__main__":
    main()