guessing-game / app.py
ysharma's picture
ysharma HF staff
added username to the layout
edfd23f
import gradio as gr
import random
from transformers import pipeline
import pathlib
model = pipeline(model="declare-lab/flan-alpaca-large")
class Game:
def __init__(self):
self.words = pathlib.Path('solutions.txt').read_text().splitlines()
self.word_list = random.sample(self.words, 5)
self.secret_word = random.choice(self.word_list)
def reset(self):
self.word_list = random.sample(self.words, 5)
self.secret_word = random.choice(self.word_list)
@property
def prompt(self):
return f"Try to guess the word! Either enter the word or ask a hint. The word will be one of {self.word_list}"
def __str__(self):
return f"word_list: {self.word_list}, secret_word: {self.secret_word}"
with gr.Blocks(theme='gstaff/xkcd') as demo:
game_state = gr.State(Game())
game_state.value.reset()
title = gr.Markdown("# Guessing Game")
description = gr.HTML("""This Gradio Demo was build by <a href="https://huggingface.co/gstaff" target="_blank">Grant Stafford @gstaff</a>.""")
chatbot = gr.Chatbot(value=[(None, game_state.value.prompt)])
msg = gr.Textbox()
restart = gr.Button("Restart")
def user(user_message, history, game):
return "", history + [[user_message, None]], game
def bot(history, game):
user_input = history[-1][0]
if game.secret_word in user_input.strip().lower().split():
history[-1][1] = f"You win, the word was {game.secret_word}!"
print(history)
return history, game
if user_input.strip().lower() in game.word_list:
history[-1][1] = "Wrong guess, try again."
return history, game
instructions = f"The word is {game.secret_word}. Answer this: {user_input}"
bot_message = model(instructions, max_length=256, do_sample=True)[0]['generated_text']
response = bot_message.replace(game.secret_word, "?????").replace(game.secret_word.title(), "?????")
history[-1][1] = response
return history, game
def restart_game(game):
game.reset()
return [(None, game.prompt)], game
msg.submit(user, [msg, chatbot, game_state], [msg, chatbot, game_state], queue=False).then(
bot, [chatbot, game_state], [chatbot, game_state]
)
restart.click(restart_game, game_state, [chatbot, game_state], queue=False)
demo.launch()