iisadia commited on
Commit
6f37b53
·
verified ·
1 Parent(s): 6116725

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -79
app.py CHANGED
@@ -3,7 +3,7 @@ import time
3
  import requests
4
  from streamlit.components.v1 import html
5
 
6
- # Custom CSS for professional look
7
  def inject_custom_css():
8
  st.markdown("""
9
  <style>
@@ -62,6 +62,7 @@ def inject_custom_css():
62
  </style>
63
  """, unsafe_allow_html=True)
64
 
 
65
  def show_confetti():
66
  html("""
67
  <canvas id="confetti-canvas" class="confetti"></canvas>
@@ -78,6 +79,7 @@ def show_confetti():
78
  </script>
79
  """)
80
 
 
81
  def ask_llama(messages, category, is_final=False):
82
  api_url = "https://api.groq.com/openai/v1/chat/completions"
83
  headers = {
@@ -85,148 +87,144 @@ def ask_llama(messages, category, is_final=False):
85
  "Content-Type": "application/json"
86
  }
87
 
88
- prompt = (f"You're playing 20 questions to guess a {category}. " +
89
- "Ask strategic yes/no questions one at a time." +
90
- (" Based on the answers, what is your final guess? State only the guess." if is_final else ""))
91
-
92
  data = {
93
- "model": "llama-3.3-70b-versatile",
94
  "messages": [{"role": "system", "content": prompt}] + messages,
95
  "temperature": 0.7,
96
  "max_tokens": 100
97
  }
98
-
99
  try:
100
  with st.spinner("Thinking..."):
101
- response = requests.post(api_url, headers=headers, json=data, timeout=10)
102
  response.raise_for_status()
103
  return response.json()["choices"][0]["message"]["content"]
104
  except Exception as e:
105
  st.error(f"API Error: {str(e)}")
106
  return None
107
 
 
108
  def main():
109
  inject_custom_css()
110
  st.markdown('<div class="title">KASOTI</div>', unsafe_allow_html=True)
111
  st.markdown('<div class="subtitle">The Ultimate Guessing Game</div>', unsafe_allow_html=True)
112
 
113
- # Initialize game state
114
  if 'game' not in st.session_state:
115
  st.session_state.game = {
116
  'state': 'start',
117
  'category': None,
118
- 'current_question': None,
119
  'conversation': [],
120
- 'question_count': 0,
121
- 'waiting_for_answer': False
122
  }
123
 
124
- # Start Screen
125
- if st.session_state.game['state'] == 'start':
 
 
126
  st.markdown("""
127
  <div class="question-box">
128
  <h3>Welcome to <span style='color:#6C63FF;'>KASOTI 🎯</span></h3>
129
  <p>Think of something and I'll try to guess it with yes/no questions!</p>
130
  <p>Choose a category:</p>
 
 
 
 
 
131
  </div>
132
  """, unsafe_allow_html=True)
133
 
134
  col1, col2, col3 = st.columns(3)
135
  with col1:
136
  if st.button("Person", use_container_width=True):
137
- st.session_state.game['category'] = 'person'
138
- st.session_state.game['state'] = 'generate_question'
139
  st.rerun()
140
  with col2:
141
  if st.button("Place", use_container_width=True):
142
- st.session_state.game['category'] = 'place'
143
- st.session_state.game['state'] = 'generate_question'
144
  st.rerun()
145
  with col3:
146
  if st.button("Object", use_container_width=True):
147
- st.session_state.game['category'] = 'object'
148
- st.session_state.game['state'] = 'generate_question'
149
  st.rerun()
150
 
151
- # Generate Question State
152
- elif st.session_state.game['state'] == 'generate_question':
153
- # Generate new question
154
- question = ask_llama(
155
- st.session_state.game['conversation'],
156
- st.session_state.game['category']
157
- )
158
-
159
- if question:
160
- st.session_state.game['current_question'] = question
161
- st.session_state.game['conversation'].append({"role": "assistant", "content": question})
162
- st.session_state.game['question_count'] += 1
163
- st.session_state.game['state'] = 'wait_for_answer'
164
- st.session_state.game['waiting_for_answer'] = True
165
- st.rerun()
166
- else:
167
- st.error("Failed to generate question. Please try again.")
168
- st.session_state.game['state'] = 'start'
169
- st.rerun()
170
 
171
- # Wait for Answer State
172
- elif st.session_state.game['state'] == 'wait_for_answer':
173
  st.markdown(f"""
174
  <div class="question-box">
175
- Question {st.session_state.game['question_count']}:<br><br>
176
- <strong>{st.session_state.game['current_question']}</strong>
177
  </div>
178
  """, unsafe_allow_html=True)
179
 
180
  with st.form("answer_form"):
181
- answer = st.radio("Your answer:", ["Yes", "No"], index=None, horizontal=True)
182
  submitted = st.form_submit_button("Submit")
183
-
184
- if submitted and answer:
185
- # Record answer
186
- answer_lower = answer.lower()
187
- st.session_state.game['conversation'].append({"role": "user", "content": answer_lower})
188
- st.session_state.game['waiting_for_answer'] = False
189
-
190
- # Check if we should guess or ask another question
191
- if st.session_state.game['question_count'] >= 5: # Minimum 5 questions before checking
192
- ready = ask_llama(
193
- st.session_state.game['conversation'] + [
194
- {"role": "user", "content": "Can you guess now? Answer only 'yes' or 'no'."}
195
- ],
196
- st.session_state.game['category']
197
  )
198
- if ready and ready.strip().lower() == 'yes':
199
- st.session_state.game['state'] = 'result'
200
  st.rerun()
201
-
202
- # Continue with next question if under 20
203
- if st.session_state.game['question_count'] < 20:
204
- st.session_state.game['state'] = 'generate_question'
205
- st.rerun()
 
 
 
 
 
206
  else:
207
- st.session_state.game['state'] = 'result'
208
  st.rerun()
209
 
210
  # Result Screen
211
- elif st.session_state.game['state'] == 'result':
212
- guess = ask_llama(
213
- st.session_state.game['conversation'],
214
- st.session_state.game['category'],
215
- is_final=True
216
- )
217
-
218
- if guess:
219
  show_confetti()
220
  st.markdown('<div class="final-reveal">🎉 I think it\'s...</div>', unsafe_allow_html=True)
221
  time.sleep(1)
222
- st.markdown(f'<div class="final-reveal" style="font-size:3.5rem;color:#6C63FF;">{guess}</div>',
223
- unsafe_allow_html=True)
224
  else:
225
- st.error("Sorry, I couldn't make a guess. Let's try again!")
226
-
227
  if st.button("Play Again", type="primary"):
228
  st.session_state.clear()
229
  st.rerun()
230
 
231
  if __name__ == "__main__":
232
- main()
 
3
  import requests
4
  from streamlit.components.v1 import html
5
 
6
+ # Inject custom CSS
7
  def inject_custom_css():
8
  st.markdown("""
9
  <style>
 
62
  </style>
63
  """, unsafe_allow_html=True)
64
 
65
+ # Show confetti effect
66
  def show_confetti():
67
  html("""
68
  <canvas id="confetti-canvas" class="confetti"></canvas>
 
79
  </script>
80
  """)
81
 
82
+ # Call Groq API (LLama model)
83
  def ask_llama(messages, category, is_final=False):
84
  api_url = "https://api.groq.com/openai/v1/chat/completions"
85
  headers = {
 
87
  "Content-Type": "application/json"
88
  }
89
 
90
+ prompt = ("You're playing 20 questions to guess a " + category +
91
+ ". Ask strategic yes/no questions one at a time." +
92
+ (" Based on the answers, what is your final guess? State only the guess." if is_final else ""))
93
+
94
  data = {
95
+ "model": "llama-3-70b-8192",
96
  "messages": [{"role": "system", "content": prompt}] + messages,
97
  "temperature": 0.7,
98
  "max_tokens": 100
99
  }
100
+
101
  try:
102
  with st.spinner("Thinking..."):
103
+ response = requests.post(api_url, headers=headers, json=data, timeout=15)
104
  response.raise_for_status()
105
  return response.json()["choices"][0]["message"]["content"]
106
  except Exception as e:
107
  st.error(f"API Error: {str(e)}")
108
  return None
109
 
110
+ # Main Game Logic
111
  def main():
112
  inject_custom_css()
113
  st.markdown('<div class="title">KASOTI</div>', unsafe_allow_html=True)
114
  st.markdown('<div class="subtitle">The Ultimate Guessing Game</div>', unsafe_allow_html=True)
115
 
116
+ # Session State
117
  if 'game' not in st.session_state:
118
  st.session_state.game = {
119
  'state': 'start',
120
  'category': None,
121
+ 'questions': [],
122
  'conversation': [],
123
+ 'input_buffer': ""
 
124
  }
125
 
126
+ game = st.session_state.game
127
+
128
+ # Start screen
129
+ if game['state'] == 'start':
130
  st.markdown("""
131
  <div class="question-box">
132
  <h3>Welcome to <span style='color:#6C63FF;'>KASOTI 🎯</span></h3>
133
  <p>Think of something and I'll try to guess it with yes/no questions!</p>
134
  <p>Choose a category:</p>
135
+ <ul>
136
+ <li><strong>person</strong> (celebrity, fictional character)</li>
137
+ <li><strong>place</strong> (city, country, location)</li>
138
+ <li><strong>object</strong> (something you can touch)</li>
139
+ </ul>
140
  </div>
141
  """, unsafe_allow_html=True)
142
 
143
  col1, col2, col3 = st.columns(3)
144
  with col1:
145
  if st.button("Person", use_container_width=True):
146
+ game['category'] = 'person'
147
+ game['state'] = 'playing'
148
  st.rerun()
149
  with col2:
150
  if st.button("Place", use_container_width=True):
151
+ game['category'] = 'place'
152
+ game['state'] = 'playing'
153
  st.rerun()
154
  with col3:
155
  if st.button("Object", use_container_width=True):
156
+ game['category'] = 'object'
157
+ game['state'] = 'playing'
158
  st.rerun()
159
 
160
+ # Game play screen
161
+ elif game['state'] == 'playing':
162
+ if not game['questions']:
163
+ first_q = ask_llama([{"role": "user", "content": "Ask your first yes/no question."}], game['category'])
164
+ if first_q:
165
+ game['questions'].append(first_q)
166
+ game['conversation'].append({"role": "assistant", "content": first_q})
167
+ st.rerun()
168
+ else:
169
+ st.error("Failed to generate question.")
170
+ game['state'] = 'start'
171
+ st.rerun()
172
+
173
+ current_q_index = len(game['questions']) - 1
174
+ current_q = game['questions'][current_q_index]
 
 
 
 
175
 
 
 
176
  st.markdown(f"""
177
  <div class="question-box">
178
+ Question {current_q_index + 1}:<br><br>
179
+ <strong>{current_q}</strong>
180
  </div>
181
  """, unsafe_allow_html=True)
182
 
183
  with st.form("answer_form"):
184
+ user_input = st.text_input("Your answer (Yes, No, or more detailed response):")
185
  submitted = st.form_submit_button("Submit")
186
+
187
+ if submitted and user_input.strip() != "":
188
+ game['conversation'].append({"role": "user", "content": user_input.strip()})
189
+
190
+ # Ask if ready to guess after 5 questions
191
+ if current_q_index >= 4:
192
+ can_guess = ask_llama(
193
+ game['conversation'] + [{"role": "user", "content": "Can you guess now? Answer only yes or no."}],
194
+ game['category']
 
 
 
 
 
195
  )
196
+ if can_guess and can_guess.strip().lower() == 'yes':
197
+ game['state'] = 'result'
198
  st.rerun()
199
+
200
+ # Generate next question
201
+ if current_q_index < 19:
202
+ next_q = ask_llama(game['conversation'], game['category'])
203
+ if next_q:
204
+ game['questions'].append(next_q)
205
+ game['conversation'].append({"role": "assistant", "content": next_q})
206
+ st.rerun()
207
+ else:
208
+ st.error("Couldn't get next question.")
209
  else:
210
+ game['state'] = 'result'
211
  st.rerun()
212
 
213
  # Result Screen
214
+ elif game['state'] == 'result':
215
+ final_guess = ask_llama(game['conversation'], game['category'], is_final=True)
216
+
217
+ if final_guess:
 
 
 
 
218
  show_confetti()
219
  st.markdown('<div class="final-reveal">🎉 I think it\'s...</div>', unsafe_allow_html=True)
220
  time.sleep(1)
221
+ st.markdown(f'<div class="final-reveal" style="font-size:3.5rem;color:#6C63FF;">{final_guess}</div>', unsafe_allow_html=True)
 
222
  else:
223
+ st.error("Sorry, I couldn't make a guess.")
224
+
225
  if st.button("Play Again", type="primary"):
226
  st.session_state.clear()
227
  st.rerun()
228
 
229
  if __name__ == "__main__":
230
+ main()