script_task.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import time
  5. import cv2
  6. import numpy as np
  7. from datetime import datetime, timedelta
  8. from numpy import uint8, fromfile
  9. from random import choice
  10. from cached_property import cached_property
  11. # Use cmd to install: ./toolkit/python.exe -m pip install -i https://pypi.org/simple/ oashya --trusted-host pypi.org
  12. # update oashya: ./toolkit/python.exe -m pip install --upgrade oashya
  13. from oashya.tracker import Tracker
  14. from oashya.labels import label2id
  15. from oashya.utils import draw_tracks
  16. from module.exception import TaskEnd
  17. from module.logger import logger
  18. from module.exception import RequestHumanTakeover
  19. from tasks.Component.SwitchOnmyoji.switch_onmyoji import SwitchOnmyoji
  20. from tasks.GameUi.game_ui import GameUi
  21. from tasks.GameUi.page import page_hyakkiyakou, page_main, page_onmyodo
  22. from tasks.Hyakkiyakou.config import InferenceEngine, ModelPrecision
  23. from tasks.Hyakkiyakou.agent.agent import Agent
  24. from tasks.Hyakkiyakou.slave.hya_slave import HyaSlave
  25. from tasks.Hyakkiyakou.debugger import Debugger
  26. def plot_save(image, boxes):
  27. color_palette = np.random.uniform(0, 255, size=(226, 3))
  28. for box in boxes:
  29. _cls = box[0]
  30. _scores = box[1]
  31. _x, _y, _w, _h = box[2]
  32. x1 = int(_x - _w / 2)
  33. y1 = int(_y - _h / 2)
  34. x2 = int(_x + _w / 2)
  35. y2 = int(_y + _h / 2)
  36. cv2.rectangle(image, (x1, y1), (x2, y2), color_palette[_cls], 2)
  37. #
  38. cv2.putText(image, f'{_cls} {_scores:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color_palette[_cls],
  39. 2)
  40. save_file = './tasks/Hyakkiyakou/temp/image.png'
  41. cv2.imwrite(save_file, image)
  42. class ScriptTask(GameUi, HyaSlave, SwitchOnmyoji):
  43. @property
  44. def _config(self):
  45. return self.config.hyakkiyakou
  46. @cached_property
  47. def tracker(self) -> Tracker:
  48. hyakkiyakou_models = self._config.hyakkiyakou_models
  49. conf = hyakkiyakou_models.conf_threshold
  50. nms = hyakkiyakou_models.iou_threshold
  51. if conf < 0.2 or conf > 1:
  52. raise RequestHumanTakeover('conf_threshold should be in [0.2, 1]')
  53. if nms < 0.2 or nms > 1:
  54. raise RequestHumanTakeover('iou_threshold should be in [0.2, 1]')
  55. inf_en = 'onnxruntime' if hyakkiyakou_models.inference_engine == InferenceEngine.ONNXRUNTIME else 'tensorrt'
  56. precision = 'fp32' if hyakkiyakou_models.model_precision == ModelPrecision.FP32 else 'int8'
  57. # 这个坑后面在补
  58. if inf_en == 'tensorrt' or precision == 'int8':
  59. raise RequestHumanTakeover('Only support onnxruntime')
  60. debug_info: bool = self._config.debug_config.hya_info
  61. args = {
  62. 'conf_threshold': conf,
  63. 'iou_threshold': nms,
  64. 'precision': precision,
  65. 'inference_engine': inf_en,
  66. 'debug': debug_info,
  67. }
  68. return Tracker(args=args)
  69. @cached_property
  70. def agent(self) -> Agent:
  71. hya_config = self._config.hyakkiyakou_config
  72. sp = hya_config.hya_sp
  73. ssr = hya_config.hya_ssr
  74. sr = hya_config.hya_sr
  75. r = hya_config.hya_r
  76. n = hya_config.hya_n
  77. g = hya_config.hya_g
  78. weights: list = [sp, ssr, sr, r, n, g]
  79. str_priorities: str = hya_config.hya_priorities
  80. if str_priorities == '':
  81. priorities = []
  82. else:
  83. str_priorities = str_priorities.replace(' ', '').replace(',', ',')
  84. try:
  85. priorities = [label2id(s) for s in str_priorities.split(',')]
  86. except Exception as e:
  87. logger.error(f'Priority error: {str_priorities}')
  88. logger.error(e)
  89. raise RequestHumanTakeover
  90. strategy: dict = {
  91. 'weights': weights,
  92. 'priorities': priorities,
  93. 'invite_friend': hya_config.hya_invite_friend,
  94. 'auto_bean': hya_config.hya_auto_bean
  95. }
  96. return Agent(strategy=strategy)
  97. @cached_property
  98. def debugger(self) -> Debugger:
  99. debug_config = self._config.debug_config
  100. hya_interval = debug_config.hya_interval
  101. hya_save_result = debug_config.hya_save_result
  102. if hya_interval <= 100 or hya_interval >= 1000:
  103. raise RequestHumanTakeover('screenshot_interval must be between 1000 and 10000')
  104. self.set_fast_screenshot_interval(hya_interval)
  105. return Debugger(info_enable=debug_config.hya_info,
  106. continuous_learning=debug_config.continuous_learning,
  107. hya_save_result=hya_save_result)
  108. def run(self):
  109. hya_count: int = 0
  110. self.limit_count: int = self._config.hyakkiyakou_config.hya_limit_count
  111. limit_time = self._config.hyakkiyakou_config.hya_limit_time
  112. self.limit_time: timedelta = timedelta(hours=limit_time.hour, minutes=limit_time.minute,
  113. seconds=limit_time.second)
  114. self.ui_goto_page(page_onmyodo)
  115. self.switch_onmyoji(self._config.hyakkiyakou_config.hya_onmyoji)
  116. self.ui_goto_page(page_hyakkiyakou)
  117. while 1:
  118. if hya_count >= self.limit_count:
  119. logger.info('Hyakkiyakou count limit out')
  120. break
  121. if datetime.now() - self.start_time >= self.limit_time:
  122. logger.info('Hyakkiyakou time limit out')
  123. break
  124. self.one()
  125. hya_count += 1
  126. logger.info(f'count: {hya_count}/{self.limit_count}')
  127. logger.info(f'time: {(datetime.now() - self.start_time).total_seconds():.1f}s/{self.limit_time.total_seconds()}s')
  128. while 1:
  129. self.screenshot()
  130. if not self.appear(self.I_HACCESS):
  131. continue
  132. if self.appear(self.I_HCLOSE_RED):
  133. break
  134. self.ui_click_until_disappear(self.I_HCLOSE_RED)
  135. self.set_next_run(task='Hyakkiyakou', success=True, finish=False)
  136. raise TaskEnd
  137. def one(self):
  138. self.reset_state()
  139. if not self.appear(self.I_HACCESS):
  140. logger.warning('Page Error')
  141. if self._config.hyakkiyakou_config.hya_invite_friend:
  142. self.invite_friend()
  143. # start
  144. self.ui_click(self.I_HACCESS, self.I_HSTART, interval=2)
  145. self.wait_until_appear(self.I_HTITLE)
  146. # 随机选一个
  147. click_button = choice([self.C_HSELECT_1, self.C_HSELECT_2, self.C_HSELECT_3])
  148. while 1:
  149. self.screenshot()
  150. if not self.appear(self.I_HTITLE):
  151. break
  152. if self.appear_then_click(self.I_HSTART, interval=2):
  153. continue
  154. if not self.appear(self.I_HSELECTED):
  155. self.click(click_button, interval=2)
  156. self.device.stuck_record_add('BATTLE_STATUS_S')
  157. # 正式开始
  158. logger.hr('Start Hyakkiyakou')
  159. init_bean_flag: bool = False
  160. last_action = [0, 0, False, 10]
  161. self.hya_fs_check_timer.reset()
  162. if self._config.debug_config.hya_show:
  163. self.debugger.show_start()
  164. while 1:
  165. self.fast_screenshot(screenshot=self._config.debug_config.hya_screenshot_method)
  166. if self.appear(self.I_HEND):
  167. break
  168. if not self.appear(self.I_CHECK_RUN):
  169. continue
  170. if not init_bean_flag:
  171. init_bean_flag = True
  172. self.bean_05to10()
  173. time.sleep(0.5)
  174. if not self.appear(self.I_HFREEZE):
  175. # --------------------------------------------------------
  176. self.slave_state = self.update_state()
  177. tracks = self.tracker(image=self.device.image, response=last_action)
  178. last_action = self.agent.decision(tracks=tracks, state=self.slave_state)
  179. self.do_action(last_action, state=self.slave_state)
  180. else:
  181. # TODO freeze state
  182. tracks = []
  183. # debug
  184. if self._config.debug_config.hya_show:
  185. draw_image = draw_tracks(self.device.image, tracks=tracks)
  186. self.debugger.show_sync(image=draw_image)
  187. if self._config.debug_config.continuous_learning:
  188. self.debugger.deal_learning(image=self.device.image, tracks=tracks)
  189. if self._config.debug_config.hya_info:
  190. self.debugger.show_info(tracker=self.tracker, f=self.agent.focus)
  191. logger.info('Hyakkiyakou End')
  192. if self._config.debug_config.hya_show:
  193. self.debugger.show_stop()
  194. if self._config.debug_config.hya_save_result:
  195. # 走个动画
  196. time.sleep(1.5)
  197. self.debugger.save_result(self.device.image)
  198. self.ui_click(self.I_HEND, self.I_HACCESS)
  199. self.debugger.save_images()
  200. del self.debugger
  201. # you maybe update oashya
  202. self.tracker.clear_tracks()
  203. def do_action(self, action: list, state):
  204. x, y, throw, bean = action
  205. if not throw:
  206. return
  207. if state[0] <= 0:
  208. return
  209. self.fast_click(x=x, y=y, control_method=self._config.debug_config.hya_control_method)
  210. if __name__ == '__main__':
  211. from module.config.config import Config
  212. from module.device.device import Device
  213. c = Config('oas1')
  214. d = Device(c)
  215. t = ScriptTask(c, d)
  216. t.run()
  217. # from tasks.Hyakkiyakou.agent.tagent import test_observe, test_state
  218. # test_state()
  219. # from debugger import test_track
  220. # test_track(show=False)
  221. pass