File size: 2,394 Bytes
227483d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edfd23f
227483d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()