script_task.py 9.2 KB

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