iisadia commited on
Commit
25f0c4f
·
verified ·
1 Parent(s): 4db3cf5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -140
app.py CHANGED
@@ -37,23 +37,6 @@ def inject_custom_css():
37
  color: black;
38
  }
39
 
40
- .answer-btn {
41
- border-radius: 12px !important;
42
- padding: 0.5rem 1.5rem !important;
43
- font-weight: 600 !important;
44
- margin: 0.5rem !important;
45
- }
46
-
47
- .yes-btn {
48
- background: #6C63FF !important;
49
- color: white !important;
50
- }
51
-
52
- .no-btn {
53
- background: #FF6B6B !important;
54
- color: white !important;
55
- }
56
-
57
  .final-reveal {
58
  animation: fadeIn 2s;
59
  font-size: 2.5rem;
@@ -76,10 +59,23 @@ def inject_custom_css():
76
  pointer-events: none;
77
  z-index: 1000;
78
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  </style>
80
  """, unsafe_allow_html=True)
81
 
82
- # Confetti animation (for final reveal)
83
  def show_confetti():
84
  html("""
85
  <canvas id="confetti-canvas" class="confetti"></canvas>
@@ -87,177 +83,170 @@ def show_confetti():
87
  <script>
88
  const canvas = document.getElementById('confetti-canvas');
89
  const confetti = confetti.create(canvas, { resize: true });
90
-
91
  confetti({
92
  particleCount: 150,
93
  spread: 70,
94
  origin: { y: 0.6 }
95
  });
96
-
97
- setTimeout(() => {
98
- canvas.remove();
99
- }, 5000);
100
  </script>
101
  """)
102
 
103
- # Groq Llama AI API call
104
- def ask_llama(conversation_history, category):
105
  api_url = "https://api.groq.com/openai/v1/chat/completions"
106
  headers = {
107
  "Authorization": "Bearer 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",
108
  "Content-Type": "application/json"
109
  }
110
 
111
- messages = [
112
- {
113
- "role": "system",
114
- "content": f"You're playing 20 questions to guess a {category}. Ask strategic yes/no questions one at a time based on previous answers."
115
- }
116
- ] + conversation_history
117
 
118
  data = {
119
  "model": "llama-3.3-70b-versatile",
120
- "messages": messages,
121
  "temperature": 0.7,
122
  "max_tokens": 100
123
  }
124
 
125
  try:
126
- response = requests.post(api_url, headers=headers, json=data)
127
- response.raise_for_status()
128
- return response.json()["choices"][0]["message"]["content"]
 
129
  except Exception as e:
130
- st.error(f"Error calling Llama API: {str(e)}")
131
- return "Could not generate question"
132
 
133
- # Game logic
134
  def main():
135
  inject_custom_css()
136
-
137
  st.markdown('<div class="title">KASOTI</div>', unsafe_allow_html=True)
138
  st.markdown('<div class="subtitle">The Ultimate Guessing Game</div>', unsafe_allow_html=True)
139
-
140
- # Initialize session state
141
- if 'game_state' not in st.session_state:
142
- st.session_state.game_state = "start"
143
- st.session_state.questions = []
144
- st.session_state.current_q = 0
145
- st.session_state.answers = []
146
- st.session_state.conversation_history = []
147
- st.session_state.category = None
148
- st.session_state.waiting_for_answer = True
149
- st.session_state.question_generated = False
150
 
151
- # Start screen
152
- if st.session_state.game_state == "start":
 
 
 
 
 
 
 
 
 
 
153
  st.markdown("""
154
  <div class="question-box">
155
  <h3>Welcome to <span style='color:#6C63FF;'>KASOTI 🎯</span></h3>
156
- <p>This is a fun guessing game! You'll think of something, and I'll ask maximum 20 Yes/No questions to guess what it is.</p>
157
- <p>You can choose from three categories:</p>
158
  <ul>
159
- <li><strong>person</strong> – like a celebrity, fictional character, etc.</li>
160
- <li><strong>place</strong> – like a city, country, or location</li>
161
- <li><strong>object</strong> – like something you can touch or use</li>
162
  </ul>
163
- <p><strong>Type one of these categories below</strong> to begin: <code>person</code>, <code>place</code>, or <code>object</code>.</p>
164
  </div>
165
  """, unsafe_allow_html=True)
166
 
167
- with st.form("start_form"):
168
- category_input = st.text_input("Enter category (person / place / object):").strip().lower()
169
-
170
- if st.form_submit_button("Start Game"):
171
- if not category_input:
172
- st.error("Please enter a category!")
173
- elif category_input not in ["person", "place", "object"]:
174
- st.error("Please enter either 'person', 'place', or 'object'!")
175
- else:
176
- st.session_state.category = category_input
177
- st.session_state.game_state = "gameplay"
178
- st.rerun()
 
 
 
 
179
 
180
- # Gameplay screen - generate first question if needed
181
- elif st.session_state.game_state == "gameplay":
182
- if not st.session_state.questions:
183
- # Generate first question
184
- first_question = ask_llama([{
185
- "role": "user",
186
- "content": "Ask your first yes/no question."
187
- }], st.session_state.category)
188
- st.session_state.questions = [first_question]
189
- st.session_state.conversation_history = [
190
- {"role": "assistant", "content": first_question}
191
- ]
192
- st.session_state.waiting_for_answer = True
193
- st.rerun()
 
 
194
 
195
  # Show current question
196
- current_question = st.session_state.questions[st.session_state.current_q]
197
- st.markdown(f'<div class="question-box">Question {st.session_state.current_q + 1}/20:<br><br>'
198
- f'<strong>{current_question}</strong></div>',
199
- unsafe_allow_html=True)
200
-
 
 
 
201
  # Answer form
202
  with st.form("answer_form"):
203
- answer_input = st.text_input("Your answer (yes/no):").strip().lower()
204
-
205
  if st.form_submit_button("Submit"):
206
- if answer_input not in ["yes", "no"]:
207
- st.error("Please answer with 'yes' or 'no'!")
208
- else:
209
- # Record answer
210
- st.session_state.answers.append(answer_input)
211
- st.session_state.conversation_history.append(
212
- {"role": "user", "content": answer_input}
213
- )
214
- st.session_state.waiting_for_answer = False
215
-
216
- # Check if we've reached max questions
217
- if st.session_state.current_q >= 19:
218
- st.session_state.game_state = "result"
219
- st.rerun()
220
 
221
- # Generate next question if answer was submitted
222
- if not st.session_state.waiting_for_answer and st.session_state.current_q < 19:
223
- # Generate next question based on all previous Q&A
224
- next_question = ask_llama(
225
- st.session_state.conversation_history,
226
- st.session_state.category
227
- )
228
- st.session_state.questions.append(next_question)
229
- st.session_state.conversation_history.append(
230
- {"role": "assistant", "content": next_question}
231
- )
232
- st.session_state.current_q += 1
233
- st.session_state.waiting_for_answer = True
234
- st.rerun()
235
 
236
- # Early guess button
237
- if st.button("I think I can guess now!"):
238
- st.session_state.game_state = "result"
239
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
240
 
241
- # Result screen
242
- elif st.session_state.game_state == "result":
243
- # Generate final guess
244
- final_guess = ask_llama(
245
- st.session_state.conversation_history + [
246
- {"role": "user", "content": "Based on all my answers, what is your final guess? Just state the guess directly."}
247
- ],
248
- st.session_state.category
249
  )
250
 
251
- show_confetti()
252
- st.markdown('<div class="final-reveal">🎉 I think it\'s...</div>', unsafe_allow_html=True)
253
- time.sleep(1)
254
- st.markdown(f'<div class="final-reveal" style="font-size:3.5rem;color:#6C63FF;">{final_guess}</div>',
255
- unsafe_allow_html=True)
256
-
257
- st.markdown("<br><br>", unsafe_allow_html=True)
 
258
 
259
- # Play again button
260
- if st.button("Play Again", key="play_again"):
261
  st.session_state.clear()
262
  st.rerun()
263
 
 
37
  color: black;
38
  }
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  .final-reveal {
41
  animation: fadeIn 2s;
42
  font-size: 2.5rem;
 
59
  pointer-events: none;
60
  z-index: 1000;
61
  }
62
+
63
+ .loading {
64
+ display: inline-block;
65
+ width: 20px;
66
+ height: 20px;
67
+ border: 3px solid rgba(108,99,255,.3);
68
+ border-radius: 50%;
69
+ border-top-color: #6C63FF;
70
+ animation: spin 1s ease-in-out infinite;
71
+ }
72
+
73
+ @keyframes spin {
74
+ to { transform: rotate(360deg); }
75
+ }
76
  </style>
77
  """, unsafe_allow_html=True)
78
 
 
79
  def show_confetti():
80
  html("""
81
  <canvas id="confetti-canvas" class="confetti"></canvas>
 
83
  <script>
84
  const canvas = document.getElementById('confetti-canvas');
85
  const confetti = confetti.create(canvas, { resize: true });
 
86
  confetti({
87
  particleCount: 150,
88
  spread: 70,
89
  origin: { y: 0.6 }
90
  });
91
+ setTimeout(() => canvas.remove(), 5000);
 
 
 
92
  </script>
93
  """)
94
 
95
+ def ask_llama(messages, category, is_final=False):
 
96
  api_url = "https://api.groq.com/openai/v1/chat/completions"
97
  headers = {
98
  "Authorization": "Bearer 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",
99
  "Content-Type": "application/json"
100
  }
101
 
102
+ prompt = ("You're playing 20 questions to guess a " + category +
103
+ ". Ask strategic yes/no questions one at a time." +
104
+ (" Based on the answers, what is your final guess? State only the guess." if is_final else ""))
 
 
 
105
 
106
  data = {
107
  "model": "llama-3.3-70b-versatile",
108
+ "messages": [{"role": "system", "content": prompt}] + messages,
109
  "temperature": 0.7,
110
  "max_tokens": 100
111
  }
112
 
113
  try:
114
+ with st.spinner("Thinking..."):
115
+ response = requests.post(api_url, headers=headers, json=data, timeout=10)
116
+ response.raise_for_status()
117
+ return response.json()["choices"][0]["message"]["content"]
118
  except Exception as e:
119
+ st.error(f"API Error: {str(e)}")
120
+ return None
121
 
 
122
  def main():
123
  inject_custom_css()
 
124
  st.markdown('<div class="title">KASOTI</div>', unsafe_allow_html=True)
125
  st.markdown('<div class="subtitle">The Ultimate Guessing Game</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
126
 
127
+ # Initialize game state
128
+ if 'game' not in st.session_state:
129
+ st.session_state.game = {
130
+ 'state': 'start',
131
+ 'category': None,
132
+ 'questions': [],
133
+ 'answers': [],
134
+ 'conversation': []
135
+ }
136
+
137
+ # Start Screen
138
+ if st.session_state.game['state'] == 'start':
139
  st.markdown("""
140
  <div class="question-box">
141
  <h3>Welcome to <span style='color:#6C63FF;'>KASOTI 🎯</span></h3>
142
+ <p>Think of something and I'll try to guess it with yes/no questions!</p>
143
+ <p>Choose a category:</p>
144
  <ul>
145
+ <li><strong>person</strong> (celebrity, fictional character)</li>
146
+ <li><strong>place</strong> (city, country, location)</li>
147
+ <li><strong>object</strong> (something you can touch)</li>
148
  </ul>
 
149
  </div>
150
  """, unsafe_allow_html=True)
151
 
152
+ col1, col2, col3 = st.columns(3)
153
+ with col1:
154
+ if st.button("Person", use_container_width=True):
155
+ st.session_state.game['category'] = 'person'
156
+ st.session_state.game['state'] = 'playing'
157
+ st.rerun()
158
+ with col2:
159
+ if st.button("Place", use_container_width=True):
160
+ st.session_state.game['category'] = 'place'
161
+ st.session_state.game['state'] = 'playing'
162
+ st.rerun()
163
+ with col3:
164
+ if st.button("Object", use_container_width=True):
165
+ st.session_state.game['category'] = 'object'
166
+ st.session_state.game['state'] = 'playing'
167
+ st.rerun()
168
 
169
+ # Game Play Screen
170
+ elif st.session_state.game['state'] == 'playing':
171
+ # Generate first question if none exists
172
+ if not st.session_state.game['questions']:
173
+ question = ask_llama(
174
+ [{"role": "user", "content": "Ask your first yes/no question."}],
175
+ st.session_state.game['category']
176
+ )
177
+ if question:
178
+ st.session_state.game['questions'].append(question)
179
+ st.session_state.game['conversation'].append({"role": "assistant", "content": question})
180
+ st.rerun()
181
+ else:
182
+ st.error("Failed to generate question. Please try again.")
183
+ st.session_state.game['state'] = 'start'
184
+ st.rerun()
185
 
186
  # Show current question
187
+ current_q = len(st.session_state.game['questions']) - 1
188
+ st.markdown(f"""
189
+ <div class="question-box">
190
+ Question {current_q + 1}:<br><br>
191
+ <strong>{st.session_state.game['questions'][current_q]}</strong>
192
+ </div>
193
+ """, unsafe_allow_html=True)
194
+
195
  # Answer form
196
  with st.form("answer_form"):
197
+ answer = st.radio("Your answer:", ["Yes", "No"], horizontal=True)
 
198
  if st.form_submit_button("Submit"):
199
+ # Record answer
200
+ answer_lower = answer.lower()
201
+ st.session_state.game['answers'].append(answer_lower)
202
+ st.session_state.game['conversation'].append({"role": "user", "content": answer_lower})
 
 
 
 
 
 
 
 
 
 
203
 
204
+ # Check if AI can guess now
205
+ if current_q >= 4: # Minimum 5 questions before checking
206
+ ready = ask_llama(
207
+ st.session_state.game['conversation'] + [
208
+ {"role": "user", "content": "Can you guess now? Answer only 'yes' or 'no'."}
209
+ ],
210
+ st.session_state.game['category']
211
+ )
212
+ if ready and ready.strip().lower() == 'yes':
213
+ st.session_state.game['state'] = 'result'
214
+ st.rerun()
 
 
 
215
 
216
+ # Generate next question if under 20
217
+ if current_q < 19:
218
+ next_q = ask_llama(
219
+ st.session_state.game['conversation'],
220
+ st.session_state.game['category']
221
+ )
222
+ if next_q:
223
+ st.session_state.game['questions'].append(next_q)
224
+ st.session_state.game['conversation'].append({"role": "assistant", "content": next_q})
225
+ st.rerun()
226
+ else:
227
+ st.error("Failed to generate next question")
228
+ else:
229
+ st.session_state.game['state'] = 'result'
230
+ st.rerun()
231
 
232
+ # Result Screen
233
+ elif st.session_state.game['state'] == 'result':
234
+ guess = ask_llama(
235
+ st.session_state.game['conversation'],
236
+ st.session_state.game['category'],
237
+ is_final=True
 
 
238
  )
239
 
240
+ if guess:
241
+ show_confetti()
242
+ st.markdown('<div class="final-reveal">🎉 I think it\'s...</div>', unsafe_allow_html=True)
243
+ time.sleep(1)
244
+ st.markdown(f'<div class="final-reveal" style="font-size:3.5rem;color:#6C63FF;">{guess}</div>',
245
+ unsafe_allow_html=True)
246
+ else:
247
+ st.error("Sorry, I couldn't make a guess. Let's try again!")
248
 
249
+ if st.button("Play Again", type="primary"):
 
250
  st.session_state.clear()
251
  st.rerun()
252