jsakshi commited on
Commit
c8c920f
·
verified ·
1 Parent(s): bb50953

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -105
app.py CHANGED
@@ -1,117 +1,203 @@
1
  import gradio as gr
2
- from transformers import pipeline
3
 
4
- # Load TinyLlama model for text generation
5
- generator = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0")
 
 
 
 
 
6
 
7
- # Store the current story and last options in global variables
8
- current_story = ""
9
- last_options = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- def start_story(prompt):
12
- global current_story, last_options
13
- # Generate the initial story segment
14
- formatted_prompt = f"Human: Write a creative story starting with: '{prompt}' in about 100-150 words."
15
- story_result = generator(
16
- formatted_prompt,
17
- max_new_tokens=150, # ~10 lines (100-150 words)
18
- temperature=0.7,
19
- top_k=50,
20
- do_sample=True,
21
- truncation=True
22
- )[0]["generated_text"]
23
- current_story = story_result.replace(formatted_prompt, "").strip()
24
-
25
- # Generate story-specific options
26
- options_prompt = f"Human: Based on this story: '{current_story}', suggest three distinct options for what happens next. Each option should be 10-20 words and continue the narrative logically."
27
- options_result = generator(
28
- options_prompt,
29
- max_new_tokens=100, # Enough for 3 options
30
- temperature=0.8, # Slightly higher for variety
31
- top_k=50,
32
- do_sample=True,
33
- truncation=True
34
- )[0]["generated_text"]
35
- options_text = options_result.replace(options_prompt, "").strip()
36
-
37
- # Parse options, with fallback if generation is messy
38
- options_lines = [line.strip() for line in options_text.split("\n") if line.strip()]
39
- last_options = options_lines[:3] if len(options_lines) >= 3 else [
40
- "The story took an unexpected twist.",
41
- "A new challenge emerged from the shadows.",
42
- "The journey led to an unlikely ally."
43
  ]
 
 
 
 
 
44
 
45
- options_display = "\n\n**Choose an option:**\n" + "\n".join([f"{i+1}. {opt}" for i, opt in enumerate(last_options)])
46
- return current_story + options_display
 
 
 
 
 
 
 
 
 
 
47
 
48
- def continue_story(option_num):
49
- global current_story, last_options
50
- if not current_story:
51
- return "Please start a story first!"
52
- if not last_options or not (1 <= int(option_num) <= 3):
53
- return "Invalid option! Choose 1, 2, or 3."
54
-
55
- # Continue the story with the chosen option
56
- chosen_option = last_options[int(option_num) - 1]
57
- formatted_prompt = f"Human: Continue this story: '{current_story}' with this direction: '{chosen_option}' in about 100-150 words."
58
- story_result = generator(
59
- formatted_prompt,
60
- max_new_tokens=150, # ~10 lines
61
- temperature=0.7,
62
- top_k=50,
63
- do_sample=True,
64
- truncation=True
65
- )[0]["generated_text"]
66
- current_story = story_result.replace(formatted_prompt, "").strip()
67
-
68
- # Generate new story-specific options
69
- options_prompt = f"Human: Based on this story: '{current_story}', suggest three distinct options for what happens next. Each option should be 10-20 words and continue the narrative logically."
70
- options_result = generator(
71
- options_prompt,
72
- max_new_tokens=100,
73
- temperature=0.8,
74
- top_k=50,
75
- do_sample=True,
76
- truncation=True
77
- )[0]["generated_text"]
78
- options_text = options_result.replace(options_prompt, "").strip()
79
-
80
- options_lines = [line.strip() for line in options_text.split("\n") if line.strip()]
81
- last_options = options_lines[:3] if len(options_lines) >= 3 else [
82
- "The story took an unexpected twist.",
83
- "A new challenge emerged from the shadows.",
84
- "The journey led to an unlikely ally."
85
- ]
86
 
87
- options_display = "\n\n**Choose an option:**\n" + "\n".join([f"{i+1}. {opt}" for i, opt in enumerate(last_options)])
88
- return current_story + options_display
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- def reset_story():
91
- global current_story, last_options
92
- current_story = ""
93
- last_options = []
94
- return "Story reset. Enter a new prompt to begin!"
 
 
 
 
 
 
 
95
 
96
- # Create the Gradio interface
97
- with gr.Blocks(title="AI Story Game") as demo:
98
- gr.Markdown("# AI Story Game")
99
- gr.Markdown("Start your adventure with a prompt, then guide the story with options or reset it!")
100
-
101
- # Input for the initial prompt
102
- prompt_input = gr.Textbox(label="Start your story with a prompt", placeholder="E.g., 'A thief crept through the shadows...'")
103
- output = gr.Textbox(label="Your Story", lines=15)
104
-
105
- # Option input and buttons
106
- option_input = gr.Textbox(label="Enter option number (1-3)", placeholder="E.g., 1", lines=1)
107
- start_button = gr.Button("Start Story")
108
- continue_button = gr.Button("Continue Story")
109
- reset_button = gr.Button("Reset Story")
110
-
111
- # Connect buttons to functions
112
- start_button.click(fn=start_story, inputs=prompt_input, outputs=output)
113
- continue_button.click(fn=continue_story, inputs=option_input, outputs=output)
114
- reset_button.click(fn=reset_story, inputs=None, outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
- # Launch the app
117
  demo.launch()
 
1
  import gradio as gr
2
+ import random
3
 
4
+ # Word lists for different categories
5
+ WORD_LISTS = {
6
+ "animals": ["elephant", "penguin", "giraffe", "dolphin", "tiger", "lion", "zebra"],
7
+ "food": ["pizza", "burger", "pasta", "sushi", "taco", "cookie", "salad"],
8
+ "colors": ["purple", "orange", "yellow", "green", "brown", "black", "white"],
9
+ "countries": ["france", "japan", "india", "brazil", "egypt", "spain", "italy"]
10
+ }
11
 
12
+ CLUES = {
13
+ "elephant": [
14
+ "I am the largest land mammal",
15
+ "I have a long trunk",
16
+ "I have big ears and tusks",
17
+ "I never forget",
18
+ "I live in Africa or Asia"
19
+ ],
20
+ "penguin": [
21
+ "I am a flightless bird",
22
+ "I love the cold",
23
+ "I waddle when I walk",
24
+ "I wear a natural tuxedo",
25
+ "I swim very well"
26
+ ],
27
+ # Add more pre-generated clues for each word...
28
+ }
29
 
30
+ class GameState:
31
+ def __init__(self):
32
+ self.score = 0
33
+ self.current_word = ""
34
+ self.clues_shown = 0
35
+ self.guesses_left = 5
36
+ self.category = ""
37
+
38
+ def reset(self):
39
+ self.__init__()
40
+
41
+ game = GameState()
42
+
43
+ def get_random_clues(word):
44
+ """Get pre-written clues or generate simple ones."""
45
+ if word in CLUES:
46
+ return CLUES[word]
47
+
48
+ # Fallback clues if word not in CLUES dictionary
49
+ return [
50
+ f"This word has {len(word)} letters",
51
+ f"It starts with '{word[0]}'",
52
+ f"It ends with '{word[-1]}'",
53
+ f"It belongs to category: {game.category}",
54
+ "This is your last clue!"
 
 
 
 
 
 
 
55
  ]
56
+
57
+ def start_game(category):
58
+ """Start a new game with selected category."""
59
+ if not category:
60
+ return "Please select a category first!", "", get_status(), False
61
 
62
+ game.reset()
63
+ game.category = category
64
+ game.current_word = random.choice(WORD_LISTS[category])
65
+ game.clues_shown = 0
66
+ clue = get_random_clues(game.current_word)[0]
67
+
68
+ return (
69
+ f"Category: {category}\nFirst clue: {clue}",
70
+ "",
71
+ get_status(),
72
+ True
73
+ )
74
 
75
+ def make_guess(guess, interface_state):
76
+ """Process the player's guess."""
77
+ if not interface_state:
78
+ return "Please start a new game first!", "", get_status(), False
79
+
80
+ if not guess:
81
+ return "Please enter a guess!", "", get_status(), interface_state
82
+
83
+ guess = guess.lower().strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ if guess == game.current_word:
86
+ score_increase = (game.guesses_left * 20) - (game.clues_shown * 5)
87
+ game.score += score_increase
88
+ return (
89
+ f"🎉 Correct! +{score_increase} points! The word was: {game.current_word}",
90
+ "",
91
+ get_status(),
92
+ False
93
+ )
94
+
95
+ game.guesses_left -= 1
96
+
97
+ if game.guesses_left <= 0:
98
+ return (
99
+ f"Game Over! The word was: {game.current_word}",
100
+ "",
101
+ get_status(),
102
+ False
103
+ )
104
+
105
+ feedback = generate_feedback(guess)
106
+ return feedback, "", get_status(), interface_state
107
 
108
+ def get_hint(interface_state):
109
+ """Provide next clue for the current word."""
110
+ if not interface_state:
111
+ return "Please start a new game first!", "", get_status(), False
112
+
113
+ clues = get_random_clues(game.current_word)
114
+ game.clues_shown += 1
115
+
116
+ if game.clues_shown >= len(clues):
117
+ return "No more clues available!", "", get_status(), interface_state
118
+
119
+ return f"Clue #{game.clues_shown + 1}: {clues[game.clues_shown]}", "", get_status(), interface_state
120
 
121
+ def generate_feedback(guess):
122
+ """Generate helpful feedback for incorrect guesses."""
123
+ word = game.current_word
124
+
125
+ if len(guess) != len(word):
126
+ return f"The word has {len(word)} letters (your guess had {len(guess)})"
127
+
128
+ correct_pos = sum(1 for a, b in zip(guess, word) if a == b)
129
+ correct_letters = len(set(guess) & set(word))
130
+
131
+ return f"'{guess}' is not correct. {correct_pos} letters in correct position, {correct_letters} correct letters. {game.guesses_left} guesses left!"
132
+
133
+ def get_status():
134
+ """Get current game status."""
135
+ return f"""
136
+ 🎮 Game Status:
137
+ Score: {game.score}
138
+ Guesses Left: {game.guesses_left}
139
+ Hints Used: {game.clues_shown}
140
+ """
141
+
142
+ # Gradio interface
143
+ with gr.Blocks(title="Word Guessing Game") as demo:
144
+ gr.Markdown("# 🎮 Word Guessing Game")
145
+ gr.Markdown("Guess the word from the clues! Get bonus points for using fewer hints and guesses.")
146
+
147
+ # Game state (hidden)
148
+ interface_state = gr.State(False)
149
+
150
+ # Game status
151
+ status_display = gr.Textbox(
152
+ label="Game Status",
153
+ value=get_status(),
154
+ interactive=False
155
+ )
156
+
157
+ # Category selection
158
+ category_select = gr.Dropdown(
159
+ choices=list(WORD_LISTS.keys()),
160
+ label="Choose Category"
161
+ )
162
+
163
+ # Game display
164
+ game_display = gr.Textbox(
165
+ label="Game Progress",
166
+ interactive=False,
167
+ lines=3
168
+ )
169
+
170
+ # Player input
171
+ with gr.Row():
172
+ guess_input = gr.Textbox(
173
+ label="Your Guess",
174
+ placeholder="Type your guess here..."
175
+ )
176
+ guess_button = gr.Button("🎯 Make Guess")
177
+
178
+ # Hint button
179
+ hint_button = gr.Button("💡 Get Hint")
180
+
181
+ # Start new game button
182
+ start_button = gr.Button("🎲 Start New Game")
183
+
184
+ # Event handlers
185
+ start_button.click(
186
+ fn=start_game,
187
+ inputs=[category_select],
188
+ outputs=[game_display, guess_input, status_display, interface_state]
189
+ )
190
+
191
+ guess_button.click(
192
+ fn=make_guess,
193
+ inputs=[guess_input, interface_state],
194
+ outputs=[game_display, guess_input, status_display, interface_state]
195
+ )
196
+
197
+ hint_button.click(
198
+ fn=get_hint,
199
+ inputs=[interface_state],
200
+ outputs=[game_display, guess_input, status_display, interface_state]
201
+ )
202
 
 
203
  demo.launch()