script_task.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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
  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. args = {
  62. 'conf_threshold': conf,
  63. 'iou_threshold': nms,
  64. 'precision': precision,
  65. 'inference_engine': inf_en,
  66. }
  67. return Tracker(args=args)
  68. @cached_property
  69. def agent(self) -> Agent:
  70. hya_config = self._config.hyakkiyakou_config
  71. sp = hya_config.hya_sp
  72. ssr = hya_config.hya_ssr
  73. sr = hya_config.hya_sr
  74. r = hya_config.hya_r
  75. n = hya_config.hya_n
  76. g = hya_config.hya_g
  77. weights: list = [sp, ssr, sr, r, n, g]
  78. str_priorities: str = hya_config.hya_priorities
  79. if str_priorities == '':
  80. priorities = []
  81. else:
  82. str_priorities = str_priorities.replace(' ', '').replace(',', ',')
  83. try:
  84. priorities = [label2id(s) for s in str_priorities.split(',')]
  85. except Exception as e:
  86. logger.error(f'Priority error: {str_priorities}')
  87. logger.error(e)
  88. raise RequestHumanTakeover
  89. strategy: dict = {
  90. 'weights': weights,
  91. 'priorities': priorities,
  92. 'invite_friend': hya_config.hya_invite_friend,
  93. 'auto_bean': hya_config.hya_auto_bean
  94. }
  95. return Agent(strategy=strategy)
  96. @cached_property
  97. def debugger(self) -> Debugger:
  98. debug_config = self._config.debug_config
  99. hya_interval = debug_config.hya_interval
  100. hya_save_result = debug_config.hya_save_result
  101. if hya_interval <= 100 or hya_interval >= 1000:
  102. raise RequestHumanTakeover('screenshot_interval must be between 1000 and 10000')
  103. self.set_fast_screenshot_interval(hya_interval)
  104. return Debugger(info_enable=debug_config.hya_info,
  105. continuous_learning=debug_config.continuous_learning,
  106. hya_save_result=hya_save_result)
  107. def run(self):
  108. hya_count: int = 0
  109. self.limit_count: int = self._config.hyakkiyakou_config.hya_limit_count
  110. limit_time = self._config.hyakkiyakou_config.hya_limit_time
  111. self.limit_time: timedelta = timedelta(hours=limit_time.hour, minutes=limit_time.minute,
  112. seconds=limit_time.second)
  113. self.ui_get_current_page()
  114. self.ui_goto(page_hyakkiyakou)
  115. while 1:
  116. if hya_count >= self.limit_count:
  117. logger.info('Hyakkiyakou count limit out')
  118. break
  119. if datetime.now() - self.start_time >= self.limit_time:
  120. logger.info('Hyakkiyakou time limit out')
  121. break
  122. self.one()
  123. hya_count += 1
  124. while 1:
  125. self.screenshot()
  126. if not self.appear(self.I_HACCESS):
  127. continue
  128. if self.appear(self.I_HCLOSE_RED):
  129. break
  130. self.ui_click_until_disappear(self.I_HCLOSE_RED)
  131. self.set_next_run(task='Hyakkiyakou', success=True, finish=False)
  132. raise TaskEnd
  133. def one(self):
  134. self.reset_state()
  135. if not self.appear(self.I_HACCESS):
  136. logger.warning('Page Error')
  137. if self._config.hyakkiyakou_config.hya_invite_friend:
  138. self.invite_friend(True)
  139. # start
  140. self.ui_click(self.I_HACCESS, self.I_HSTART, interval=2)
  141. self.wait_until_appear(self.I_HTITLE)
  142. # 随机选一个
  143. click_button = choice([self.C_HSELECT_1, self.C_HSELECT_2, self.C_HSELECT_3])
  144. while 1:
  145. self.screenshot()
  146. if not self.appear(self.I_HTITLE):
  147. break
  148. if self.appear_then_click(self.I_HSTART, interval=2):
  149. continue
  150. if not self.appear(self.I_HSELECTED):
  151. self.click(click_button, interval=2)
  152. self.device.stuck_record_add('BATTLE_STATUS_S')
  153. # 正式开始
  154. logger.hr('Start Hyakkiyakou')
  155. init_bean_flag: bool = False
  156. last_action = [0, 0, False, 10]
  157. if self._config.debug_config.hya_show:
  158. self.debugger.show_start()
  159. while 1:
  160. self.fast_screenshot()
  161. if self.appear(self.I_HEND):
  162. break
  163. if not self.appear(self.I_CHECK_RUN):
  164. continue
  165. if not init_bean_flag:
  166. init_bean_flag = True
  167. self.bean_05to10()
  168. time.sleep(0.5)
  169. if not self.appear(self.I_HFREEZE):
  170. # --------------------------------------------------------
  171. self.slave_state = self.update_state()
  172. tracks = self.tracker(image=self.device.image, response=last_action)
  173. last_action = self.agent.decision(tracks=tracks, state=self.slave_state)
  174. self.do_action(last_action, state=self.slave_state)
  175. else:
  176. # TODO freeze state
  177. tracks = []
  178. # debug
  179. if self._config.debug_config.hya_show:
  180. draw_image = draw_tracks(self.device.image, tracks=tracks)
  181. self.debugger.show_sync(image=draw_image)
  182. if self._config.debug_config.continuous_learning:
  183. self.debugger.deal_learning(image=self.device.image, tracks=tracks)
  184. logger.info('Hyakkiyakou End')
  185. if self._config.debug_config.hya_show:
  186. self.debugger.show_stop()
  187. if self._config.debug_config.hya_save_result:
  188. # 走个动画
  189. time.sleep(0.9)
  190. self.debugger.save_result(self.device.image)
  191. self.ui_click(self.I_HEND, self.I_HACCESS)
  192. self.debugger.save_images()
  193. del self.debugger
  194. def do_action(self, action: list, state):
  195. x, y, throw, bean = action
  196. if not throw:
  197. return
  198. if state[0] <= 0:
  199. return
  200. self.fast_click(x=x, y=y)
  201. # def test_opencv():
  202. # import timeit
  203. # from module.config.config import Config
  204. # from module.device.device import Device
  205. #
  206. # c = Config('oas1')
  207. # d = Device(c)
  208. #
  209. # t = ScriptTask(c, d)
  210. # t.fast_screenshot()
  211. # def sh():
  212. # t.device.image = cv2.cvtColor(t.device.image, cv2.COLOR_BGR2RGB)
  213. # execution_time = timeit.timeit(sh, number=100)
  214. # print(f"执行总的时间: {execution_time * 1000} ms")
  215. # cv2.imshow('test', t.device.image)
  216. # cv2.waitKey(0)
  217. if __name__ == '__main__':
  218. from module.config.config import Config
  219. from module.device.device import Device
  220. c = Config('oas1')
  221. d = Device(c)
  222. t = ScriptTask(c, d)
  223. t.run()
  224. # from tasks.Hyakkiyakou.agent.tagent import test_observe, test_state
  225. # test_state()
  226. # from debugger import test_track
  227. # test_track(show=False)
  228. pass