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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -120
app.py CHANGED
@@ -1,18 +1,19 @@
1
  import streamlit as st
2
  import time
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>
10
  @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap');
11
-
12
  * {
13
  font-family: 'Poppins', sans-serif;
14
  }
15
-
16
  .title {
17
  font-size: 3rem !important;
18
  font-weight: 700 !important;
@@ -20,14 +21,14 @@ def inject_custom_css():
20
  text-align: center;
21
  margin-bottom: 0.5rem;
22
  }
23
-
24
  .subtitle {
25
  font-size: 1.2rem !important;
26
  text-align: center;
27
  color: #666 !important;
28
  margin-bottom: 2rem;
29
  }
30
-
31
  .question-box {
32
  background: #F8F9FA;
33
  border-radius: 15px;
@@ -36,7 +37,24 @@ def inject_custom_css():
36
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
37
  color: black;
38
  }
39
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  .final-reveal {
41
  animation: fadeIn 2s;
42
  font-size: 2.5rem;
@@ -44,12 +62,12 @@ def inject_custom_css():
44
  text-align: center;
45
  margin: 2rem 0;
46
  }
47
-
48
  @keyframes fadeIn {
49
  from { opacity: 0; }
50
  to { opacity: 1; }
51
  }
52
-
53
  .confetti {
54
  position: fixed;
55
  top: 0;
@@ -62,7 +80,7 @@ def inject_custom_css():
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>
@@ -70,159 +88,156 @@ def show_confetti():
70
  <script>
71
  const canvas = document.getElementById('confetti-canvas');
72
  const confetti = confetti.create(canvas, { resize: true });
 
73
  confetti({
74
  particleCount: 150,
75
  spread: 70,
76
  origin: { y: 0.6 }
77
  });
78
- setTimeout(() => canvas.remove(), 5000);
 
 
 
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 = {
86
- "Authorization": "Bearer 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",
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
 
 
1
  import streamlit as st
2
  import time
3
  import requests
4
+ import json
5
  from streamlit.components.v1 import html
6
 
7
+ # Custom CSS for professional look
8
  def inject_custom_css():
9
  st.markdown("""
10
  <style>
11
  @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap');
12
+
13
  * {
14
  font-family: 'Poppins', sans-serif;
15
  }
16
+
17
  .title {
18
  font-size: 3rem !important;
19
  font-weight: 700 !important;
 
21
  text-align: center;
22
  margin-bottom: 0.5rem;
23
  }
24
+
25
  .subtitle {
26
  font-size: 1.2rem !important;
27
  text-align: center;
28
  color: #666 !important;
29
  margin-bottom: 2rem;
30
  }
31
+
32
  .question-box {
33
  background: #F8F9FA;
34
  border-radius: 15px;
 
37
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
38
  color: black;
39
  }
40
+
41
+ .answer-btn {
42
+ border-radius: 12px !important;
43
+ padding: 0.5rem 1.5rem !important;
44
+ font-weight: 600 !important;
45
+ margin: 0.5rem !important;
46
+ }
47
+
48
+ .yes-btn {
49
+ background: #6C63FF !important;
50
+ color: white !important;
51
+ }
52
+
53
+ .no-btn {
54
+ background: #FF6B6B !important;
55
+ color: white !important;
56
+ }
57
+
58
  .final-reveal {
59
  animation: fadeIn 2s;
60
  font-size: 2.5rem;
 
62
  text-align: center;
63
  margin: 2rem 0;
64
  }
65
+
66
  @keyframes fadeIn {
67
  from { opacity: 0; }
68
  to { opacity: 1; }
69
  }
70
+
71
  .confetti {
72
  position: fixed;
73
  top: 0;
 
80
  </style>
81
  """, unsafe_allow_html=True)
82
 
83
+ # Confetti animation (for final reveal)
84
  def show_confetti():
85
  html("""
86
  <canvas id="confetti-canvas" class="confetti"></canvas>
 
88
  <script>
89
  const canvas = document.getElementById('confetti-canvas');
90
  const confetti = confetti.create(canvas, { resize: true });
91
+
92
  confetti({
93
  particleCount: 150,
94
  spread: 70,
95
  origin: { y: 0.6 }
96
  });
97
+
98
+ setTimeout(() => {
99
+ canvas.remove();
100
+ }, 5000);
101
  </script>
102
  """)
103
 
104
+ # Groq Llama AI API call
105
+ def ask_llama(conversation_history, category):
106
+ api_url = "https://api.groq.com/openai/v1/chat/completions" # Updated API URL
107
  headers = {
108
+ "Authorization": "Bearer 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", # Your new API key
109
  "Content-Type": "application/json"
110
  }
111
+
112
+ messages = [
113
+ {
114
+ "role": "system",
115
+ "content": f"You're playing 20 questions to guess a {category}. Ask strategic yes/no questions."
116
+ }
117
+ ] + conversation_history
118
 
119
  data = {
120
+ "model": "llama-3.3-70b-versatile", # The model you are using
121
+ "messages": messages,
122
  "temperature": 0.7,
123
  "max_tokens": 100
124
  }
125
 
126
  try:
127
+ response = requests.post(api_url, headers=headers, json=data)
128
+ response.raise_for_status()
129
+ return response.json()["choices"][0]["message"]["content"]
 
130
  except Exception as e:
131
+ st.error(f"Error calling Llama API: {str(e)}")
132
+ return "Could not generate question"
133
 
134
+ # Game logic
135
  def main():
136
  inject_custom_css()
137
+
138
  st.markdown('<div class="title">KASOTI</div>', unsafe_allow_html=True)
139
  st.markdown('<div class="subtitle">The Ultimate Guessing Game</div>', unsafe_allow_html=True)
140
 
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
 
149
  # Start screen
150
+ if st.session_state.game_state == "start":
151
  st.markdown("""
152
  <div class="question-box">
153
  <h3>Welcome to <span style='color:#6C63FF;'>KASOTI 🎯</span></h3>
154
+ <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>
155
+ <p>You can choose from three categories:</p>
156
  <ul>
157
+ <li><strong>person</strong> – like a celebrity, fictional character, etc.</li>
158
+ <li><strong>place</strong> – like a city, country, or location</li>
159
+ <li><strong>object</strong> – like something you can touch or use</li>
160
  </ul>
161
+ <p><strong>Type one of these categories below</strong> to begin: <code>person</code>, <code>place</code>, or <code>object</code>.</p>
162
  </div>
163
  """, unsafe_allow_html=True)
164
 
165
+ with st.form("start_form"):
166
+ category_input = st.text_input("Enter category (person / place / object):").strip().lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
+ if st.form_submit_button("Start Game"):
169
+ if not category_input:
170
+ st.error("Please enter a category!")
171
+ elif category_input not in ["person", "place", "object"]:
172
+ st.error("Please enter either 'person', 'place', or 'object'!")
173
+ else:
174
+ st.session_state.category = category_input
175
+ # Generate first question
176
+ first_question = ask_llama([{
177
+ "role": "user",
178
+ "content": "Ask your first yes/no question."
179
+ }], category_input)
180
+ st.session_state.questions = [first_question]
181
+ st.session_state.conversation_history = [
182
+ {"role": "assistant", "content": first_question}
183
+ ]
184
+ st.session_state.game_state = "gameplay"
185
+ st.rerun()
186
 
187
+ # Gameplay screen
188
+ elif st.session_state.game_state == "gameplay":
189
+ current_question = st.session_state.questions[st.session_state.current_q]
190
+ st.markdown(f'<div class="question-box">Question {st.session_state.current_q + 1}/20:<br><br>'
191
+ f'<strong>{current_question}</strong></div>',
192
+ unsafe_allow_html=True)
193
 
194
+ with st.form("answer_form"):
195
+ answer_input = st.text_input("Your answer (yes/no):", key=f"answer_{st.session_state.current_q}").strip().lower()
196
+
197
+ if st.form_submit_button("Submit"):
198
+ if answer_input not in ["yes", "no"]:
199
+ st.error("Please answer with 'yes' or 'no'!")
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  else:
201
+ # Record answer
202
+ st.session_state.answers.append(answer_input)
203
+ st.session_state.conversation_history.append(
204
+ {"role": "user", "content": answer_input}
205
+ )
206
 
207
+ # Check if we've reached max questions
208
+ if st.session_state.current_q >= 19: # 0-based index
209
+ st.session_state.game_state = "result"
210
+ else:
211
+ # Generate next question
212
+ next_question = ask_llama(
213
+ st.session_state.conversation_history,
214
+ st.session_state.category
215
+ )
216
+ st.session_state.questions.append(next_question)
217
+ st.session_state.conversation_history.append(
218
+ {"role": "assistant", "content": next_question}
219
+ )
220
+ st.session_state.current_q += 1
221
 
222
+ st.rerun()
 
 
 
 
 
 
223
 
224
+ # Result screen
225
+ elif st.session_state.game_state == "result":
226
+ # Generate final guess
227
+ final_guess = ask_llama(
228
+ st.session_state.conversation_history + [
229
+ {"role": "user", "content": "Based on all my answers, what is your final guess? Just state the guess directly."}
230
+ ],
231
+ st.session_state.category
232
+ )
233
+
234
+ show_confetti()
235
+ st.markdown('<div class="final-reveal">🎉 I think it\'s...</div>', unsafe_allow_html=True)
236
+ time.sleep(1)
237
+ st.markdown(f'<div class="final-reveal" style="font-size:3.5rem;color:#6C63FF;">{final_guess}</div>',
238
+ unsafe_allow_html=True)
239
+
240
+ if st.button("Play Again", key="play_again"):
241
  st.session_state.clear()
242
  st.rerun()
243