View difference between Paste ID: AMYbspLN and CA8WZZuR
SHOW: | | - or go back to the newest paste.
1
from story.story_manager import *
2
from generator.gpt2.gpt2_generator import *
3
from story.utils import *
4
import time, sys, os
5
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
6
7
def flush_input():
8
    import msvcrt
9
    while msvcrt.kbhit():
10
        msvcrt.getch()
11
12
def select_game():
13
    with open(YAML_FILE, 'r') as stream:
14
        data = yaml.safe_load(stream)
15
16
    print("Pick a setting.")
17
    settings = data["settings"].keys()
18
    for i, setting in enumerate(settings):
19
        print_str = str(i) + ") " + setting
20
        if setting == "fantasy":
21
            print_str += " (recommended)"
22
23
        console_print(print_str)
24
    console_print(str(len(settings)) + ") custom")
25
    choice = get_num_options(len(settings)+1)
26
27
    if choice == len(settings):
28
29
        context = ""
30
        console_print("\nEnter a prompt that describes who you are and the first couple sentences of where you start "
31
                      "out ex:\n 'You are a knight in the kingdom of Larion. You are hunting the evil dragon who has been " +
32
                      "terrorizing the kingdom. You enter the forest searching for the dragon and see' ")
33
        prompt = input("Starting Prompt: ")
34
        return context, prompt
35
36
    setting_key = list(settings)[choice]
37
38
    print("\nPick a character")
39
    characters = data["settings"][setting_key]["characters"]
40
    for i, character in enumerate(characters):
41
        console_print(str(i) + ") " + character)
42
    character_key = list(characters)[get_num_options(len(characters))]
43
44
    name = input("\nWhat is your name? ")
45
    setting_description = data["settings"][setting_key]["description"]
46
    character = data["settings"][setting_key]["characters"][character_key]
47
48
    context = "You are " + name + ", a " + character_key + " " + setting_description + \
49
              "You have a " + character["item1"] + " and a " + character["item2"] + ". "
50
    prompt_num = np.random.randint(0, len(character["prompts"]))
51
    prompt = character["prompts"][prompt_num]
52
53
    return context, prompt
54
    
55
56
def instructions():
57
    text = "\nAI Dungeon 2 Instructions:"
58
    text += '\n Enter actions starting with a verb ex. "go to the tavern" or "attack the orc."'
59
    text += '\n To speak enter \'say "(thing you want to say)"\' or just "(thing you want to say)" '
60
    text += '\n\nThe following commands can be entered for any action: '
61
    text += '\n  "revert"   Reverts the last action allowing you to pick a different action.'
62
    text += '\n  "quit"     Quits the game and saves'
63
    text += '\n  "restart"  Starts a new game and saves your current one'
64
    text += '\n  "save"     Makes a new save of your game and gives you the save ID'
65
    text += '\n  "load"     Asks for a save ID and loads the game if the ID is valid'
66
    text += '\n  "print"    Prints a transcript of your adventure (without extra newline formatting)'
67
    text += '\n  "settemp" Changes the AI temperature, default is now 0.15, previously 0.4. Going lower will make AI less random.'
68
    text += '\n  "help"     Prints these instructions again'
69
    return text
70
71
def play_aidungeon_2():
72
73
    console_print("AI Dungeon 2 will save and use your actions and game to continually improve AI Dungeon."
74
                  + " If you would like to disable this enter 'nosaving' for any action. This will also turn off the "
75
                  + "ability to save games.")
76
77
    upload_story = True
78
79
    print("\nInitializing AI Dungeon! (This might take a few minutes)\n")
80
    generator = GPT2Generator()
81
    story_manager = UnconstrainedStoryManager(generator)
82
    print("\n")
83
84
    #with open('opening.txt', 'r') as file:
85
    #    starter = file.read()
86
    #print(starter)
87
88
    while True:
89
        if story_manager.story != None:
90
            del story_manager.story
91
92
        print("\n\n")
93
        context, prompt = select_game()
94
        console_print(instructions())
95
        print("\nGenerating story...")
96
97
        story_manager.start_new_story(prompt, context=context, upload_story=upload_story)
98
99
        print("\n")
100
        console_print(str(story_manager.story))
101
        while True:
102
            flush_input()
103
            action = input("> ")
104
            if action == "restart":
105
                rating = input("Please rate the story quality from 1-10: ")
106
                rating_float = float(rating)
107
                story_manager.story.rating = rating_float
108
                break
109
110
            elif action == "quit":
111
                rating = input("Please rate the story quality from 1-10: ")
112
                rating_float = float(rating)
113
                story_manager.story.rating = rating_float
114
                exit()
115
116
            elif action == "nosaving":
117
                upload_story = False
118
                story_manager.story.upload_story = False
119
                console_print("Saving turned off.")
120
121
            elif action == "help":
122
                console_print(instructions())
123
124
            elif action == "save":
125
                if upload_story:
126
                    id = story_manager.story.save_to_storage()
127
                    console_print("Game saved.")
128
                    console_print("To load the game, type 'load' and enter the following ID: " + id)
129
                else:
130
                    console_print("Saving has been turned off. Cannot save.")
131
132
            elif action =="load":
133
                load_ID = input("What is the ID of the saved game?")
134
                result = story_manager.story.load_from_storage(load_ID)
135
                console_print("\nLoading Game...\n")
136
                console_print(result)
137
138
            elif len(action.split(" ")) == 2 and action.split(" ")[0] == "load":
139
                load_ID = action.split(" ")[1]
140
                result = story_manager.story.load_from_storage(load_ID)
141
                console_print("\nLoading Game...\n")
142
                console_print(result)
143
144
            elif action == "print":
145
                print("\nPRINTING\n")
146
                if line_break == "n":
147
                    print(str(story_manager.story))
148
                elif line_break == "y":
149
                    console_print(str(story_manager.story))
150
                elif line_break.isdigit():
151
                    console_print(str(story_manager.story), int(line_break))
152
153
            elif action == "settemp":
154
                temp = float(input("Set a new temperature>"))
155
                if type(temp)==int or float:
156
                    story_manager.generator = GPT2Generator(temperature=temp)
157
                else:
158
                    print("\nEnter a number, please")
159
                    print(str(story_manager.story))
160
161
            elif action == "revert":
162
163
                if len(story_manager.story.actions) is 0:
164
                    console_print("You can't go back any farther. ")
165
                    continue
166
167
                story_manager.story.actions = story_manager.story.actions[:-1]
168
                story_manager.story.results = story_manager.story.results[:-1]
169
                console_print("Last action reverted. ")
170
                if len(story_manager.story.results) > 0:
171
                    console_print(story_manager.story.results[-1])
172
                else:
173
                    console_print(story_manager.story.story_start)
174
                continue
175
176
            else:
177
                if action == "":
178
                    action = ""
179
                    result = story_manager.act(action)
180
                    console_print(result)
181
182
                elif action[0] == '"':
183
                    action = "You say " + action
184
185
                else:
186
                    action = action.strip()
187
                    action = action[0].lower() + action[1:]
188
189
                    if "You" not in action[:6] and "I" not in action[:6]:
190
                        action = "You " + action
191
192
                    if action[-1] not in [".", "?", "!"]:
193
                        action = action + "."
194
195
                    action = first_to_second_person(action)
196
197
                    action = "\n> " + action + "\n"
198
199
                result = "\n" + story_manager.act(action)
200
                if len(story_manager.story.results) >= 2:
201
                    similarity = get_similarity(story_manager.story.results[-1], story_manager.story.results[-2])
202
                    if similarity > 0.9:
203
                        story_manager.story.actions = story_manager.story.actions[:-1]
204
                        story_manager.story.results = story_manager.story.results[:-1]
205
                        console_print("Woops that action caused the model to start looping. Try a different action to prevent that.")
206
                        continue
207
208
                if player_won(result):
209
                    console_print(result + "\n CONGRATS YOU WIN")
210
                    break
211
                elif player_died(result):
212
                    console_print(result)
213
                    console_print("YOU DIED. GAME OVER")
214
                    console_print("\nOptions:")
215
                    console_print('0) Start a new game')
216
                    console_print('1) "I\'m not dead yet!" (If you didn\'t actually die) ')
217
                    console_print('Which do you choose? ')
218
                    choice = get_num_options(2)
219
                    if choice == 0:
220
                        break
221
                    else:
222
                        console_print("Sorry about that...where were we?")
223
                        console_print(result)
224
225
                else:
226
                    console_print(result)
227
228
229
if __name__ == '__main__':
230
    play_aidungeon_2()