File size: 16,321 Bytes
1292ed1 74a6ec1 8622a36 74a6ec1 695c0fc b922996 767b287 8627d53 41aab98 8627d53 41aab98 74a6ec1 41aab98 e46e0c0 41aab98 f34b1bf 41aab98 767b287 41aab98 f34b1bf 41aab98 e46e0c0 41aab98 767b287 41aab98 767b287 41aab98 e46e0c0 41aab98 767b287 41aab98 767b287 41aab98 f34b1bf 41aab98 e46e0c0 41aab98 e46e0c0 41aab98 767b287 41aab98 767b287 41aab98 f34b1bf 41aab98 767b287 41aab98 e46e0c0 41aab98 e46e0c0 41aab98 e46e0c0 41aab98 767b287 41aab98 e46e0c0 41aab98 e46e0c0 41aab98 e46e0c0 41aab98 f34b1bf 41aab98 767b287 41aab98 74a6ec1 1292ed1 41aab98 8627d53 74a6ec1 8627d53 41aab98 8627d53 74a6ec1 8627d53 1292ed1 41aab98 f34b1bf 41aab98 1292ed1 41aab98 1dd8568 e46e0c0 41aab98 4db3cf5 3ff9487 1dd8568 41aab98 6f37b53 41aab98 3ff9487 e46e0c0 41aab98 e46e0c0 41aab98 e46e0c0 f34b1bf 767b287 41aab98 e46e0c0 41aab98 e46e0c0 f34b1bf 41aab98 e46e0c0 41aab98 1dbf749 41aab98 1dbf749 41aab98 1dbf749 e46e0c0 41aab98 1dbf749 41aab98 1292ed1 41aab98 |
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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
import streamlit as st
import time
import requests
from streamlit.components.v1 import html
import os
# 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
return pipeline("conversational", model="facebook/blenderbot-400M-distill")
# Custom CSS for enhanced professional look with UI improvements
def inject_custom_css():
st.markdown("""
<style>
/* UPDATED: Importing and configuring a modern font with improved responsiveness */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap');
html, body {
background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
color: #333;
margin: 0;
padding: 0;
height: 100%;
}
* {
font-family: 'Poppins', sans-serif;
}
.title {
font-size: 3rem !important;
font-weight: 700 !important;
color: #6C63FF !important;
text-align: center;
margin: 2rem 0 0.5rem 0;
}
.subtitle {
font-size: 1.2rem !important;
text-align: center;
color: #666 !important;
margin-bottom: 2rem;
}
/* UPDATED: Improved question box with subtle border-radius & shadow */
.question-box {
background: #ffffff;
border-radius: 15px;
padding: 2rem;
margin: 1.5rem auto;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
max-width: 650px;
color: #333 !important;
}
/* UPDATED: Button styling improvements */
.answer-btn {
border-radius: 12px !important;
padding: 0.5rem 1.5rem !important;
font-weight: 600 !important;
margin: 0.5rem !important;
border: none;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.2s ease;
}
.answer-btn:hover {
transform: scale(1.05);
}
.yes-btn {
background: #6C63FF !important;
color: white !important;
}
.no-btn {
background: #FF6B6B !important;
color: white !important;
}
/* UPDATED: Enhanced final reveal with glow effect */
.final-reveal {
animation: fadeIn 2s;
font-size: 2.5rem;
color: #6C63FF;
text-align: center;
margin: 2rem 0;
text-shadow: 0 0 10px rgba(108, 99, 255, 0.4);
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
/* UPDATED: Full screen confetti canvas styling remains the same */
.confetti {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 1000;
}
/* UPDATED: Confidence meter visual improvement */
.confidence-meter {
height: 10px;
background: linear-gradient(90deg, #FF6B6B 0%, #6C63FF 100%);
border-radius: 5px;
margin: 10px 0;
}
/* UPDATED: Styling for the forms to center them in the layout */
form {
max-width: 650px;
margin: 0 auto;
}
</style>
""", unsafe_allow_html=True)
# Confetti animation
def show_confetti():
html("""
<canvas id="confetti-canvas" class="confetti"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/confetti.browser.min.js"></script>
<script>
const canvas = document.getElementById('confetti-canvas');
const confetti = confetti.create(canvas, { resize: true });
confetti({
particleCount: 150,
spread: 70,
origin: { y: 0.6 }
});
setTimeout(() => { canvas.remove(); }, 5000);
</script>
""")
# Enhanced AI question generation for guessing game using Llama model
def ask_llama(conversation_history, category, is_final_guess=False):
api_url = "https://api.groq.com/openai/v1/chat/completions"
headers = {
"Authorization": "Bearer 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",
"Content-Type": "application/json"
}
system_prompt = f"""You're playing 20 questions to guess a {category}. Follow these rules:
1. Ask strategic, non-repeating yes/no questions that narrow down possibilities
2. Consider all previous answers carefully before asking next question
3. If you're very confident (80%+ sure), respond with "Final Guess: [your guess]"
4. For places: ask about continent, climate, famous landmarks, country, city or population
5. For people: ask about fictional or real, profession, gender, alive/dead, nationality, or fame
6. For objects: ask about size, color, usage, material, or where it's found
7. Never repeat questions and always make progress toward guessing"""
if is_final_guess:
prompt = f"""Based on these answers about a {category}, provide ONLY your final guess with no extra text:
{conversation_history}"""
else:
prompt = "Ask your next strategic yes/no question that will best narrow down the possibilities."
messages = [
{"role": "system", "content": system_prompt},
*conversation_history,
{"role": "user", "content": prompt}
]
data = {
"model": "llama-3.3-70b-versatile",
"messages": messages,
"temperature": 0.7 if is_final_guess else 0.8,
"max_tokens": 100
}
try:
response = requests.post(api_url, headers=headers, json=data)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
except Exception as e:
st.error(f"Error calling Llama API: {str(e)}")
return "Could not generate question"
# New function for the help AI assistant using the Hugging Face InferenceClient
def ask_help_agent(query):
try:
from huggingface_hub import InferenceClient
# Initialize the client with the provided model
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=os.environ.get("HF_HUB_TOKEN"))
system_message = "You are a friendly Chatbot."
# Build history from session state (if any)
history = []
if "help_conversation" in st.session_state:
for msg in st.session_state.help_conversation:
history.append((msg.get("query", ""), msg.get("response", "")))
messages = [{"role": "system", "content": system_message}]
for user_msg, bot_msg in history:
if user_msg:
messages.append({"role": "user", "content": user_msg})
if bot_msg:
messages.append({"role": "assistant", "content": bot_msg})
messages.append({"role": "user", "content": query})
response_text = ""
# Using streaming to collect the entire response from the model
for message in client.chat_completion(
messages,
max_tokens=150,
stream=True,
temperature=0.7,
top_p=0.95,
):
token = message.choices[0].delta.content
response_text += token
return response_text
except Exception as e:
return f"Error in help agent: {str(e)}"
# Main game logic
def main():
inject_custom_css() # UPDATED: Now uses enhanced CSS
st.markdown('<div class="title">KASOTI</div>', unsafe_allow_html=True)
st.markdown('<div class="subtitle">The Smart Guessing Game</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 = [] # separate history for help agent
# Start screen
if st.session_state.game_state == "start":
st.markdown("""
<div class="question-box">
<h3>Welcome to <span style='color:#6C63FF;'>KASOTI 🎯</span></h3>
<p>Think of something and I'll try to guess it in 20 questions or less!</p>
<p>Choose a category:</p>
<ul>
<li><strong>Person</strong> - celebrity, fictional character, historical figure</li>
<li><strong>Place</strong> - city, country, landmark, geographical location</li>
<li><strong>Object</strong> - everyday item, tool, vehicle, etc.</li>
</ul>
<p>Type your category below to begin:</p>
</div>
""", unsafe_allow_html=True)
with st.form("start_form"):
category_input = st.text_input("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
elif st.session_state.game_state == "gameplay":
current_question = st.session_state.questions[st.session_state.current_q]
# Check if AI made a guess
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()
st.markdown(f'<div class="question-box">Question {st.session_state.current_q + 1}/20:<br><br>'
f'<strong>{current_question}</strong></div>',
unsafe_allow_html=True)
with st.form("answer_form"):
answer_input = st.text_input("Your answer (yes/no/both):",
key=f"answer_{st.session_state.current_q}").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}
)
# Generate next response
next_response = ask_llama(
st.session_state.conversation_history,
st.session_state.category
)
# Check if AI made a guess
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
# Stop after 20 questions max
if st.session_state.current_q >= 20:
st.session_state.game_state = "result"
st.experimental_rerun()
# Side Help Option: independent chat with an AI help assistant using Hugging Face model
with st.expander("Need Help? Chat with AI Assistant"):
help_query = st.text_input("Enter your help query:", key="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 screen using text input response
elif st.session_state.game_state == "confirm_guess":
st.markdown(f'<div class="question-box">🤖 My Final Guess:<br><br>'
f'<strong>Is it {st.session_state.final_guess}?</strong></div>',
unsafe_allow_html=True)
with st.form("confirm_form"):
confirm_input = st.text_input("Type your answer (yes/no/both):", key="confirm_input").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() # Immediately halt further execution
else:
# Add negative response to history and continue gameplay
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
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'>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()
|