Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.72 KB | None | 0 0
  1.  
  2. modify in py.play part:
  3. elif action == "save":
  4. if upload_story:
  5. id = story_manager.story.save_to_local()
  6. console_print("Game saved.")
  7. console_print("To load the game, type 'load' and enter the following ID: " + id)
  8. else:
  9. console_print("Saving has been turned off. Cannot save.")
  10.  
  11. elif action =="load":
  12. load_ID = input("What is the ID of the saved game?")
  13. result = story_manager.story.load_from_local(load_ID)
  14. console_print("\nLoading Game...\n")
  15. console_print(result)
  16. =========================================================================================================================
  17.  
  18. modify in the story.maneger part
  19.  
  20. from story.utils import *
  21. import json
  22. import uuid
  23. from subprocess import Popen
  24. import subprocess
  25. import os
  26.  
  27. class Story():
  28.  
  29. def __init__(self, story_start, context ="", seed=None, game_state=None, upload_story=False):
  30. self.story_start = story_start
  31. self.context = context
  32. self.rating = -1
  33. self.upload_story = upload_story
  34.  
  35. # list of actions. First action is the prompt length should always equal that of story blocks
  36. self.actions = []
  37.  
  38. # list of story blocks first story block follows prompt and is intro story
  39. self.results = []
  40.  
  41. # Only needed in constrained/cached version
  42. self.seed = seed
  43. self.choices = []
  44. self.possible_action_results = None
  45. self.uuid = None
  46.  
  47. if game_state is None:
  48. game_state = dict()
  49. self.game_state = game_state
  50. self.memory = 20
  51.  
  52. def __del__(self):
  53. if self.upload_story:
  54. self.save_to_local()
  55. console_print("Game saved.")
  56. console_print("To load the game, type 'load' and enter the following ID: " + self.uuid)
  57.  
  58.  
  59. def init_from_dict(self, story_dict):
  60. self.story_start = story_dict["story_start"]
  61. self.seed = story_dict["seed"]
  62. self.actions = story_dict["actions"]
  63. self.results = story_dict["results"]
  64. self.choices = story_dict["choices"]
  65. self.possible_action_results = story_dict["possible_action_results"]
  66. self.game_state = story_dict["game_state"]
  67. self.context = story_dict["context"]
  68. self.uuid = story_dict["uuid"]
  69.  
  70. if "rating" in story_dict.keys():
  71. self.rating = story_dict["rating"]
  72. else:
  73. self.rating = -1
  74.  
  75.  
  76. def initialize_from_json(self, json_string):
  77. story_dict = json.loads(json_string)
  78. self.init_from_dict(story_dict)
  79.  
  80. def add_to_story(self, action, story_block):
  81. self.actions.append(action)
  82. self.results.append(story_block)
  83.  
  84. def latest_result(self):
  85.  
  86. mem_ind = self.memory
  87. if len(self.results) < 2:
  88. latest_result = self.story_start
  89. else:
  90. latest_result = self.context
  91. while mem_ind > 0:
  92.  
  93. if len(self.results) >= mem_ind:
  94. latest_result += (self.actions[-mem_ind] + self.results[-mem_ind])
  95.  
  96. mem_ind -= 1
  97.  
  98. return latest_result
  99.  
  100. def __str__(self):
  101. story_list = [self.story_start]
  102. for i in range(len(self.results)):
  103. story_list.append("\n" + self.actions[i] + "\n")
  104. story_list.append("\n" + self.results[i])
  105.  
  106. return "".join(story_list)
  107.  
  108. def to_json(self):
  109. story_dict = {}
  110. story_dict["story_start"] = self.story_start
  111. story_dict["seed"] = self.seed
  112. story_dict["actions"] = self.actions
  113. story_dict["results"] = self.results
  114. story_dict["choices"] = self.choices
  115. story_dict["possible_action_results"] = self.possible_action_results
  116. story_dict["game_state"] = self.game_state
  117. story_dict["context"] = self.context
  118. story_dict["uuid"] = self.uuid
  119. story_dict["rating"] = self.rating
  120.  
  121. return json.dumps(story_dict)
  122.  
  123. def save_to_local(self):
  124. self.uuid = str(uuid.uuid1())
  125. story_json = self.to_json()
  126. file_name = "AIDungeonSave_" + str(self.uuid) + ".json"
  127. f = open(file_name, "w")
  128. f.write(story_json)
  129. f.close()
  130. return self.uuid
  131.  
  132. def load_from_local(self, save_name):
  133. file_name = "AIDungeonSave_" + save_name + ".json"
  134. exists = os.path.isfile(file_name)
  135.  
  136. if exists:
  137. with open(file_name, 'r') as fp:
  138. game = json.load(fp)
  139. self.init_from_dict(game)
  140. return str(self)
  141. else:
  142. return "Error save not found."
  143.  
  144.  
  145. def save_to_storage(self):
  146. self.uuid = str(uuid.uuid1())
  147.  
  148.  
  149. story_json = self.to_json()
  150. file_name = "story" + str(self.uuid) + ".json"
  151. f = open(file_name, "w")
  152. f.write(story_json)
  153. f.close()
  154.  
  155. FNULL = open(os.devnull, 'w')
  156. p = Popen(['gsutil.cmd', 'cp', file_name, 'gs://aidungeonstories'], stdout=FNULL, stderr=subprocess.STDOUT)
  157. return self.uuid
  158.  
  159. def load_from_storage(self, story_id):
  160.  
  161. file_name = "story" + story_id + ".json"
  162. cmd = "gsutil.cmd cp gs://aidungeonstories/" + file_name + " ."
  163. os.system(cmd)
  164. exists = os.path.isfile(file_name)
  165.  
  166. if exists:
  167. with open(file_name, 'r') as fp:
  168. game = json.load(fp)
  169. self.init_from_dict(game)
  170. return str(self)
  171. else:
  172. return "Error save not found."
  173.  
  174.  
  175. class StoryManager():
  176.  
  177. def __init__(self, generator):
  178. self.generator = generator
  179. self.story = None
  180.  
  181. def start_new_story(self, story_prompt, context="", game_state=None, upload_story=False):
  182. block = self.generator.generate(context + story_prompt)
  183. block = cut_trailing_sentence(block)
  184. self.story = Story(context + story_prompt + block, context=context, game_state=game_state, upload_story=upload_story)
  185. return self.story
  186.  
  187. def load_story(self, story, from_json=False):
  188. if from_json:
  189. self.story = Story("")
  190. self.story.initialize_from_json(story)
  191. else:
  192. self.story = story
  193. return str(story)
  194.  
  195. def json_story(self):
  196. return self.story.to_json()
  197.  
  198. def story_context(self):
  199. return self.story.latest_result()
  200.  
  201.  
  202. class UnconstrainedStoryManager(StoryManager):
  203.  
  204. def act(self, action_choice):
  205.  
  206. result = self.generate_result(action_choice)
  207. self.story.add_to_story(action_choice, result)
  208. return result
  209.  
  210. def generate_result(self, action):
  211. block = self.generator.generate(self.story_context() + action)
  212. return block
  213.  
  214.  
  215. class ConstrainedStoryManager(StoryManager):
  216.  
  217. def __init__(self, generator, action_verbs_key="classic"):
  218. super().__init__(generator)
  219. self.action_phrases = get_action_verbs(action_verbs_key)
  220. self.cache = False
  221. self.cacher = None
  222. self.seed = None
  223.  
  224. def enable_caching(self, credentials_file=None, seed=0, bucket_name="dungeon-cache"):
  225. self.cache = True
  226. self.cacher = Cacher(credentials_file, bucket_name)
  227. self.seed = seed
  228.  
  229. def start_new_story(self, story_prompt, context="", game_state=None):
  230. if self.cache:
  231. return self.start_new_story_cache(story_prompt, game_state=game_state)
  232. else:
  233. return super().start_new_story(story_prompt, context=context, game_state=game_state)
  234.  
  235. def start_new_story_generate(self, story_prompt, game_state=None):
  236. super().start_new_story(story_prompt, game_state=game_state)
  237. self.story.possible_action_results = self.get_action_results()
  238. return self.story.story_start
  239.  
  240. def start_new_story_cache(self, story_prompt, game_state=None):
  241.  
  242. response = self.cacher.retrieve_from_cache(self.seed, [], "story")
  243. if response is not None:
  244. story_start = story_prompt + response
  245. self.story = Story(story_start, seed=self.seed)
  246. self.story.possible_action_results = self.get_action_results()
  247. else:
  248. story_start = self.start_new_story_generate(story_prompt, game_state=game_state)
  249. self.story.seed = self.seed
  250. self.cacher.cache_file(self.seed, [], story_start, "story")
  251.  
  252. return story_start
  253.  
  254. def load_story(self, story, from_json=False):
  255. story_string = super().load_story(story, from_json=from_json)
  256. return story_string
  257.  
  258. def get_possible_actions(self):
  259. if self.story.possible_action_results is None:
  260. self.story.possible_action_results = self.get_action_results()
  261.  
  262. return [action_result[0] for action_result in self.story.possible_action_results]
  263.  
  264. def act(self, action_choice_str):
  265.  
  266. try:
  267. action_choice = int(action_choice_str)
  268. except:
  269. print("Error invalid choice.")
  270. return None, None
  271.  
  272. if action_choice < 0 or action_choice >= len(self.action_phrases):
  273. print("Error invalid choice.")
  274. return None, None
  275.  
  276. self.story.choices.append(action_choice)
  277. action, result = self.story.possible_action_results[action_choice]
  278. self.story.add_to_story(action, result)
  279. self.story.possible_action_results = self.get_action_results()
  280. return result, self.get_possible_actions()
  281.  
  282. def get_action_results(self):
  283. if self.cache:
  284. return self.get_action_results_cache()
  285. else:
  286. return self.get_action_results_generate()
  287.  
  288. def get_action_results_generate(self):
  289. action_results = [self.generate_action_result(self.story_context(), phrase) for phrase in self.action_phrases]
  290. return action_results
  291.  
  292. def get_action_results_cache(self):
  293. response = self.cacher.retrieve_from_cache(self.story.seed, self.story.choices, "choices")
  294.  
  295. if response is not None:
  296. print("Retrieved from cache")
  297. return json.loads(response)
  298. else:
  299. print("Didn't receive from cache")
  300. action_results = self.get_action_results_generate()
  301. response = json.dumps(action_results)
  302. self.cacher.cache_file(self.story.seed, self.story.choices, response, "choices")
  303. return action_results
  304.  
  305. def generate_action_result(self, prompt, phrase, options=None):
  306.  
  307. action_result = phrase + " " + self.generator.generate(prompt + " " + phrase, options)
  308. action, result = split_first_sentence(action_result)
  309. return action, result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement