iisadia commited on
Commit
74a6ec1
·
verified ·
1 Parent(s): 1acbcfb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -177
app.py CHANGED
@@ -1,199 +1,180 @@
1
  import streamlit as st
2
- from transformers import pipeline
3
- import streamlit as st
4
- from transformers import pipeline
5
- import os
6
-
7
- # Disable parallelism to avoid warnings
8
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
9
-
10
- # Initialize the game
11
- def init_game():
12
- if 'questions_asked' not in st.session_state:
13
- st.session_state.questions_asked = 0
14
- st.session_state.answers = []
15
- st.session_state.game_over = False
16
- st.session_state.current_question = "Is it a living thing?"
17
-
18
- # Load a smaller model with caching
19
- @st.cache_resource(show_spinner="Loading game engine...")
20
- def load_model():
21
- try:
22
- return pipeline(
23
- "text-generation",
24
- model="distilgpt2", # Smaller than GPT-2
25
- device=-1, # Force CPU
26
- framework="pt", # Explicitly use PyTorch
27
- torch_dtype="auto"
28
- )
29
- except Exception as e:
30
- st.error(f"Failed to load model: {str(e)}")
31
- return None
32
 
33
- def generate_question(model, previous_answers):
34
- if not previous_answers:
35
- return "Is it a living thing?"
36
-
37
- prompt = """We're playing a guessing game. Here are the previous Q&A:
38
- """
39
- for i, (q, a) in enumerate(previous_answers, 1):
40
- prompt += f"{i}. Q: {q} A: {'Yes' if a else 'No'}\n"
41
- prompt += "\nWhat should be the next yes/no question to narrow down the possible options?\nQ:"
42
-
43
- try:
44
- response = model(
45
- prompt,
46
- max_new_tokens=30, # Shorter response
47
- do_sample=True,
48
- temperature=0.7,
49
- top_p=0.9
50
- )
51
- question = response[0]['generated_text'].split("Q:")[-1].strip()
52
- question = question.split("\n")[0].split("?")[0] + "?" if "?" not in question else question.split("?")[0] + "?"
53
- return question
54
- except Exception as e:
55
- st.error(f"Error generating question: {str(e)}")
56
- return "Is it something you can hold in your hand?"
57
-
58
- def main():
59
- st.title("KASOTI - The Guessing Game")
60
-
61
- # Initialize with loading state
62
- with st.spinner("Setting up the game..."):
63
- model = load_model()
64
-
65
- if model is None:
66
- st.error("Failed to initialize the game. Please refresh the page.")
67
- return
68
-
69
- init_game()
70
-
71
- st.header("Think of a famous person, place, or object")
72
- st.write(f"Questions asked: {st.session_state.questions_asked}/20")
73
-
74
- if not st.session_state.game_over:
75
- st.subheader(st.session_state.current_question)
76
 
77
- col1, col2, col3 = st.columns(3)
78
- with col1:
79
- if st.button("Yes"):
80
- st.session_state.answers.append((st.session_state.current_question, True))
81
- st.session_state.questions_asked += 1
82
- st.session_state.current_question = generate_question(model, st.session_state.answers)
83
- st.rerun()
84
- with col2:
85
- if st.button("No"):
86
- st.session_state.answers.append((st.session_state.current_question, False))
87
- st.session_state.questions_asked += 1
88
- st.session_state.current_question = generate_question(model, st.session_state.answers)
89
- st.rerun()
90
- with col3:
91
- if st.button("I don't know"):
92
- st.session_state.answers.append((st.session_state.current_question, None))
93
- st.session_state.questions_asked += 1
94
- st.session_state.current_question = generate_question(model, st.session_state.answers)
95
- st.rerun()
96
 
97
- if st.session_state.questions_asked >= 20:
98
- st.session_state.game_over = True
99
-
100
- if st.session_state.game_over:
101
- st.subheader("Game Over!")
102
- st.write("I've run out of questions. What were you thinking of?")
103
- user_input = st.text_input("Enter what you were thinking of:")
104
- if user_input:
105
- st.write(f"Ah! I was thinking of {user_input}. Let's play again!")
106
- st.session_state.clear()
107
- st.rerun()
108
 
109
- if st.button("Play Again"):
110
- st.session_state.clear()
111
- st.rerun()
112
-
113
- if __name__ == "__main__":
114
- main()
115
- # Initialize the game
116
- def init_game():
117
- if 'questions_asked' not in st.session_state:
118
- st.session_state.questions_asked = 0
119
- st.session_state.answers = []
120
- st.session_state.game_over = False
121
- st.session_state.current_question = "Is it a living thing?"
122
-
123
- # Load the LLM model
124
- @st.cache_resource
125
- def load_model():
126
- return pipeline("text-generation", model="gpt2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
- def generate_question(model, previous_answers):
129
- if not previous_answers:
130
- return "Is it a living thing?"
131
-
132
- # Create a prompt for the LLM based on previous answers
133
- prompt = "We're playing a guessing game. Here are the previous Q&A:\n"
134
- for i, (q, a) in enumerate(previous_answers, 1):
135
- prompt += f"{i}. Q: {q} A: {'Yes' if a else 'No'}\n"
136
- prompt += "What should be the next yes/no question to narrow down the possible options?\nQ:"
137
 
138
- # Generate the next question
139
- response = model(prompt, max_length=100, num_return_sequences=1)
140
- question = response[0]['generated_text'].split("Q:")[-1].strip()
 
 
141
 
142
- # Clean up the question (remove anything after newlines or multiple questions)
143
- question = question.split("\n")[0].split("?")[0] + "?" if "?" not in question else question.split("?")[0] + "?"
144
- return question
 
 
145
 
 
146
  def main():
147
- st.title("KASOTI - The Guessing Game")
148
 
149
- # Initialize the model and game state
150
- model = load_model()
151
- init_game()
152
 
153
- # Display game header
154
- st.header("Think of a famous person, place, or object")
155
- st.write(f"Questions asked: {st.session_state.questions_asked}/20")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
- # Display the current question
158
- if not st.session_state.game_over:
159
- st.subheader(st.session_state.current_question)
160
 
161
- # Answer buttons
162
- col1, col2, col3 = st.columns(3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  with col1:
164
- if st.button("Yes"):
165
- st.session_state.answers.append((st.session_state.current_question, True))
166
- st.session_state.questions_asked += 1
167
- st.session_state.current_question = generate_question(model, st.session_state.answers)
168
- st.rerun()
169
  with col2:
170
- if st.button("No"):
171
- st.session_state.answers.append((st.session_state.current_question, False))
172
- st.session_state.questions_asked += 1
173
- st.session_state.current_question = generate_question(model, st.session_state.answers)
174
- st.rerun()
175
- with col3:
176
- if st.button("I don't know"):
177
- st.session_state.answers.append((st.session_state.current_question, None))
178
- st.session_state.questions_asked += 1
179
- st.session_state.current_question = generate_question(model, st.session_state.answers)
180
- st.rerun()
181
 
182
- # Check if game is over
183
- if st.session_state.questions_asked >= 20:
184
- st.session_state.game_over = True
185
-
186
- # Game over state
187
- if st.session_state.game_over:
188
- st.subheader("Game Over!")
189
- st.write("I've run out of questions. What were you thinking of?")
190
- user_input = st.text_input("Enter what you were thinking of:")
191
- if user_input:
192
- st.write(f"Ah! I was thinking of {user_input}. Let's play again!")
193
- st.session_state.clear()
194
  st.rerun()
 
 
 
 
 
 
 
 
 
 
195
 
196
- if st.button("Play Again"):
197
  st.session_state.clear()
198
  st.rerun()
199
 
 
1
  import streamlit as st
2
+ import time
3
+ import random
4
+ from streamlit.components.v1 import html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ # Custom CSS for professional look
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;
19
+ color: #6C63FF !important;
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;
34
+ padding: 2rem;
35
+ margin: 1.5rem 0;
36
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
37
+ }
38
+
39
+ .answer-btn {
40
+ border-radius: 12px !important;
41
+ padding: 0.5rem 1.5rem !important;
42
+ font-weight: 600 !important;
43
+ margin: 0.5rem !important;
44
+ }
45
+
46
+ .yes-btn {
47
+ background: #6C63FF !important;
48
+ color: white !important;
49
+ }
50
+
51
+ .no-btn {
52
+ background: #FF6B6B !important;
53
+ color: white !important;
54
+ }
55
+
56
+ .final-reveal {
57
+ animation: fadeIn 2s;
58
+ font-size: 2.5rem;
59
+ color: #6C63FF;
60
+ text-align: center;
61
+ margin: 2rem 0;
62
+ }
63
+
64
+ @keyframes fadeIn {
65
+ from { opacity: 0; }
66
+ to { opacity: 1; }
67
+ }
68
+
69
+ .confetti {
70
+ position: fixed;
71
+ top: 0;
72
+ left: 0;
73
+ width: 100%;
74
+ height: 100%;
75
+ pointer-events: none;
76
+ z-index: 1000;
77
+ }
78
+ </style>
79
+ """, unsafe_allow_html=True)
80
 
81
+ # Confetti animation (for final reveal)
82
+ def show_confetti():
83
+ html("""
84
+ <canvas id="confetti-canvas" class="confetti"></canvas>
85
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/confetti.browser.min.js"></script>
86
+ <script>
87
+ const canvas = document.getElementById('confetti-canvas');
88
+ const confetti = confetti.create(canvas, { resize: true });
 
89
 
90
+ confetti({
91
+ particleCount: 150,
92
+ spread: 70,
93
+ origin: { y: 0.6 }
94
+ });
95
 
96
+ setTimeout(() => {
97
+ canvas.remove();
98
+ }, 5000);
99
+ </script>
100
+ """)
101
 
102
+ # Game logic with fake data
103
  def main():
104
+ inject_custom_css()
105
 
106
+ st.markdown('<div class="title">KASOTI</div>', unsafe_allow_html=True)
107
+ st.markdown('<div class="subtitle">The Ultimate Guessing Game</div>', unsafe_allow_html=True)
 
108
 
109
+ if 'game_state' not in st.session_state:
110
+ st.session_state.game_state = "start"
111
+ st.session_state.questions = [
112
+ "Is it something you can hold in your hand?",
113
+ "Is it commonly found in households?",
114
+ "Can it be used as a tool?",
115
+ "Is it primarily made of metal?",
116
+ "Does it have moving parts?",
117
+ "Is it electronic?",
118
+ "Is it something you would gift to someone?",
119
+ "Can it be found in an office?",
120
+ "Does it require electricity to function?",
121
+ "Is it typically under $100?"
122
+ ]
123
+ st.session_state.current_q = 0
124
+ st.session_state.answers = []
125
+ st.session_state.target = "smartphone" # Fake target for testing
126
 
127
+ # Start screen
128
+ if st.session_state.game_state == "start":
129
+ st.image("https://via.placeholder.com/600x300?text=Think+of+Something", use_column_width=True)
130
 
131
+ with st.form("start_form"):
132
+ category = st.radio("What are you thinking of?",
133
+ ["A famous person", "An object", "A place"],
134
+ index=1)
135
+ user_input = st.text_input("Type it here (we won't peek!):").strip().lower()
136
+
137
+ if st.form_submit_button("Start Game"):
138
+ if not user_input:
139
+ st.error("Please type something!")
140
+ elif len(user_input) < 3:
141
+ st.error("Too short! Type properly.")
142
+ else:
143
+ st.session_state.game_state = "gameplay"
144
+ st.session_state.user_input = user_input
145
+ st.rerun()
146
+
147
+ # Gameplay screen
148
+ elif st.session_state.game_state == "gameplay":
149
+ col1, col2 = st.columns([1, 3])
150
  with col1:
151
+ st.image("https://via.placeholder.com/200?text=Question", width=150)
 
 
 
 
152
  with col2:
153
+ st.markdown(f'<div class="question-box">Question {st.session_state.current_q + 1}/10:<br><br>'
154
+ f'<strong>{st.session_state.questions[st.session_state.current_q]}</strong></div>',
155
+ unsafe_allow_html=True)
 
 
 
 
 
 
 
 
156
 
157
+ answer = st.radio("Your answer:", ["Yes", "No"], horizontal=True, label_visibility="collapsed")
158
+
159
+ if st.button("Submit Answer", type="primary"):
160
+ st.session_state.answers.append(answer == "Yes")
161
+ st.session_state.current_q += 1
162
+
163
+ if st.session_state.current_q >= len(st.session_state.questions):
164
+ st.session_state.game_state = "result"
 
 
 
 
165
  st.rerun()
166
+
167
+ # Result screen
168
+ elif st.session_state.game_state == "result":
169
+ show_confetti()
170
+ st.markdown('<div class="final-reveal">🎉 I think it\'s a...</div>', unsafe_allow_html=True)
171
+ time.sleep(1)
172
+ st.markdown(f'<div class="final-reveal" style="font-size:3.5rem;color:#6C63FF;">{st.session_state.target.upper()}</div>',
173
+ unsafe_allow_html=True)
174
+
175
+ st.image("https://via.placeholder.com/400x200?text=Congratulations", use_column_width=True)
176
 
177
+ if st.button("Play Again", key="play_again"):
178
  st.session_state.clear()
179
  st.rerun()
180