script_task.py 8.7 KB

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