script_task.py 9.2 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.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. 'recall_activity': hya_config.hya_recall_activity,
  96. 'auto_bean': hya_config.hya_auto_bean
  97. }
  98. return Agent(strategy=strategy)
  99. @cached_property
  100. def debugger(self) -> Debugger:
  101. debug_config = self._config.debug_config
  102. hya_interval = debug_config.hya_interval
  103. hya_save_result = debug_config.hya_save_result
  104. if hya_interval <= 100 or hya_interval >= 1000:
  105. raise RequestHumanTakeover('screenshot_interval must be between 1000 and 10000')
  106. self.set_fast_screenshot_interval(hya_interval)
  107. return Debugger(info_enable=debug_config.hya_info,
  108. continuous_learning=debug_config.continuous_learning,
  109. hya_save_result=hya_save_result)
  110. def run(self):
  111. hya_count: int = 0
  112. self.limit_count: int = self._config.hyakkiyakou_config.hya_limit_count
  113. limit_time = self._config.hyakkiyakou_config.hya_limit_time
  114. self.limit_time: timedelta = timedelta(hours=limit_time.hour, minutes=limit_time.minute,
  115. seconds=limit_time.second)
  116. self.ui_get_current_page()
  117. self.ui_goto(page_hyakkiyakou)
  118. while 1:
  119. if hya_count >= self.limit_count:
  120. logger.info('Hyakkiyakou count limit out')
  121. break
  122. if datetime.now() - self.start_time >= self.limit_time:
  123. logger.info('Hyakkiyakou time limit out')
  124. break
  125. self.one()
  126. hya_count += 1
  127. while 1:
  128. self.screenshot()
  129. if not self.appear(self.I_HACCESS):
  130. continue
  131. if self.appear(self.I_HCLOSE_RED):
  132. break
  133. self.ui_click_until_disappear(self.I_HCLOSE_RED)
  134. self.set_next_run(task='Hyakkiyakou', success=True, finish=False)
  135. raise TaskEnd
  136. def one(self):
  137. self.reset_state()
  138. if not self.appear(self.I_HACCESS):
  139. logger.warning('Page Error')
  140. if self._config.hyakkiyakou_config.hya_invite_friend:
  141. self.invite_friend(True)
  142. # start
  143. self.ui_click(self.I_HACCESS, self.I_HSTART, interval=2)
  144. self.wait_until_appear(self.I_HTITLE)
  145. # 随机选一个
  146. click_button = choice([self.C_HSELECT_1, self.C_HSELECT_2, self.C_HSELECT_3])
  147. while 1:
  148. self.screenshot()
  149. if not self.appear(self.I_HTITLE):
  150. break
  151. if self.appear_then_click(self.I_HSTART, interval=2):
  152. continue
  153. if not self.appear(self.I_HSELECTED):
  154. self.click(click_button, interval=2)
  155. self.device.stuck_record_add('BATTLE_STATUS_S')
  156. # 正式开始
  157. logger.hr('Start Hyakkiyakou')
  158. init_bean_flag: bool = False
  159. last_action = [0, 0, False, 10]
  160. self.hya_fs_check_timer.reset()
  161. if self._config.debug_config.hya_show:
  162. self.debugger.show_start()
  163. while 1:
  164. self.fast_screenshot(screenshot=self._config.debug_config.hya_screenshot_method)
  165. if self.appear(self.I_HEND):
  166. break
  167. if not self.appear(self.I_CHECK_RUN):
  168. continue
  169. if not init_bean_flag:
  170. init_bean_flag = True
  171. self.bean_05to10()
  172. time.sleep(0.5)
  173. if not self.appear(self.I_HFREEZE):
  174. # --------------------------------------------------------
  175. self.slave_state = self.update_state()
  176. tracks = self.tracker(image=self.device.image, response=last_action)
  177. last_action = self.agent.decision(tracks=tracks, state=self.slave_state)
  178. self.do_action(last_action, state=self.slave_state)
  179. else:
  180. # TODO freeze state
  181. tracks = []
  182. # debug
  183. if self._config.debug_config.hya_show:
  184. draw_image = draw_tracks(self.device.image, tracks=tracks)
  185. self.debugger.show_sync(image=draw_image)
  186. if self._config.debug_config.continuous_learning:
  187. self.debugger.deal_learning(image=self.device.image, tracks=tracks)
  188. if self._config.debug_config.hya_info:
  189. self.debugger.show_info(tracker=self.tracker, f=self.agent.focus)
  190. logger.info('Hyakkiyakou End')
  191. if self._config.debug_config.hya_show:
  192. self.debugger.show_stop()
  193. if self._config.debug_config.hya_save_result:
  194. # 走个动画
  195. time.sleep(1.5)
  196. self.debugger.save_result(self.device.image)
  197. self.ui_click(self.I_HEND, self.I_HACCESS)
  198. self.debugger.save_images()
  199. del self.debugger
  200. # you maybe update oashya
  201. self.tracker.clear_tracks()
  202. def do_action(self, action: list, state):
  203. x, y, throw, bean = action
  204. if not throw:
  205. return
  206. if state[0] <= 0:
  207. return
  208. self.fast_click(x=x, y=y, control_method=self._config.debug_config.hya_control_method)
  209. if __name__ == '__main__':
  210. from module.config.config import Config
  211. from module.device.device import Device
  212. c = Config('oas1')
  213. d = Device(c)
  214. t = ScriptTask(c, d)
  215. t.run()
  216. # from tasks.Hyakkiyakou.agent.tagent import test_observe, test_state
  217. # test_state()
  218. # from debugger import test_track
  219. # test_track(show=False)
  220. pass