def test_getMyEntryFromContext(self): context = {'game': {}} self.assertIsNone(IkaUtils.getMyEntryFromContext(context)) context['game']['players'] = [ { 'me': False, 'team': 1, 'rank_in_team': 1 }, { 'me': False, 'team': 1, 'rank_in_team': 2 }, { 'me': False, 'team': 2, 'rank_in_team': 1 }, { 'me': False, 'team': 2, 'rank_in_team': 2 }, ] self.assertIsNone(IkaUtils.getMyEntryFromContext(context)) context['game']['players'][2]['me'] = True me = IkaUtils.getMyEntryFromContext(context) self.assertEqual(2, me['team']) self.assertEqual(1, me['rank_in_team'])
def test_get_game_offset_msec(self): mock_context = {'game': {}, 'engine': {}} self.assertIsNone(IkaUtils.get_game_offset_msec(mock_context)) mock_context['engine']['msec'] = 1234567 self.assertIsNone(IkaUtils.get_game_offset_msec(mock_context)) mock_context['game']['start_offset_msec'] = 1000000 self.assertEqual(234567, IkaUtils.get_game_offset_msec(mock_context))
def _http_request_func(self, path, payload): url_api = '%s%s' % (self.base_uri, path) http_headers = { 'Content-Type': 'application/x-msgpack', } mp_payload = ''.join(map(chr, umsgpack.packb(payload))) try: pool = urllib3.PoolManager(timeout=3.0) req = pool.urlopen( 'POST', url_api, headers=http_headers, body=mp_payload, ) return json.loads(req.data.decode('utf-8')) except urllib3.exceptions.MaxRetryError: fallback = self._fallback # or .... or ... if fallback: IkaUtils.dprint( '%s: Remote API Error. Falling back to local mode' % self) return self._local_request_func(path, payload) raise Exception( 'API Error: Failed to connect to API endpoint. (No fallback)')
def _http_request_func(self, path, payload): url_api = '%s%s' % (self.base_uri, path) http_headers = { 'Content-Type': 'application/x-msgpack', } mp_payload = ''.join(map(chr, umsgpack.packb(payload))) try: pool = urllib3.PoolManager(timeout=10.0) req = pool.urlopen( 'POST', url_api, headers=http_headers, body=mp_payload, ) return json.loads(req.data.decode('utf-8')) except urllib3.exceptions.MaxRetryError: fallback = self._fallback # or .... or ... if fallback: IkaUtils.dprint( '%s: Remote API Error. Falling back to local mode' % self) return self._local_request_func(path, payload) raise Exception( 'API Error: Failed to connect to API endpoint. (No fallback)')
def init_for_cvfile(args, capture): if not capture.is_active(): IkaUtils.dprint('Failed to initialize with: %s' % capture._source_file) sys.exit(1) pos_msec = args.get('time_msec') or time_to_msec(args.get('time') or '0:0') if pos_msec: capture.set_pos_msec(pos_msec)
def print_language_settings(): from ikalog.utils import IkaUtils IkaUtils.dprint( 'IkaLog Primary CLI Language: %s (set LANG to override)' % Localization.get_languages()[0]) IkaUtils.dprint( 'IkaLog Game Language: %s (set IKALOG_LANG to override)' % Localization.get_game_languages()[0])
def __init__(self, bbox=None): ''' bbox -- bbox Crop bounding box as (x, y, w, h) ''' self._check_import() self._bbox = bbox self._launch = self._time() IkaUtils.dprint('%s: initalizing screen capture' % (self))
def evaluate(self, img_bgr=None, img_gray=None): # if not hasattr(self, '_warned_evaluate_is_deprecated'): if not self._warned_evaluate_is_deprecated: IkaUtils.dprint('%s: evaluate() is depricated.' % self) self._warned_evaluate_is_deprecated = True return self(img_bgr=img_bgr, img_gray=img_gray)
def write_answer_file(self, video_file, record): answer_fullpath = self.answer_filename(video_file, self.answer_type, None) f = open(answer_fullpath, "w") f.write(json.dumps(record)) f.close() IkaUtils.dprint("wrote answer file %s" % answer_fullpath) return True
def IkaUI_main(): IkaUtils.dprint(_('Hello!')) application = wx.App() input_plugin = VideoCapture() engine = IkaEngine(keep_alive=True) engine.close_session_at_eof = True engine.set_capture(input_plugin) # 設定画面を持つ各種 Output Plugin # -> 設定画面の生成とプラグインリストへの登録 outputs_with_gui = [ outputs.CSV(), # outputs.Fluentd(), outputs.JSON(), # outputs.Hue(), outputs.OBS(), outputs.Twitter(), outputs.Screenshot(), outputs.Boyomi(), outputs.Slack(), outputs.StatInk(), outputs.DebugVideoWriter(), outputs.WebSocketServer(), ] gui = IkaLogGUI(engine, outputs_with_gui) plugins = [] # とりあえずデバッグ用にコンソールプラグイン plugins.append(outputs.Console()) # 各パネルをプラグインしてイベントを受信する plugins.append(gui.preview) plugins.append(gui.last_result) # 設定画面を持つ input plugin もイベントを受信する plugins.append(input_plugin) # UI 自体もイベントを受信 plugins.append(gui) plugins.extend(outputs_with_gui) # 本当に困ったときのデバッグログ増加モード if 'IKALOG_DEBUG' in os.environ: plugins.append(outputs.DebugLog()) # プラグインリストを登録 engine.set_plugins(plugins) gui.run() application.MainLoop() IkaUtils.dprint(_('Bye!'))
def write_answer_file(self, video_file, record): answer_fullpath = self.answer_filename( video_file, self.answer_type, None) f = open(answer_fullpath, 'w') f.write(json.dumps(record)) f.close() IkaUtils.dprint('wrote answer file %s' % answer_fullpath) return True
def test_getFileName(self): self.assertIsNone(IkaUtils.getFileName(None, 0)) self.assertEqual('/tmp/statink.msgpack', IkaUtils.getFileName('/tmp/statink.msgpack', 0)) self.assertEqual('/tmp/statink-1.msgpack', IkaUtils.getFileName('/tmp/statink.msgpack', 1)) self.assertEqual('/tmp/statink-10.msgpack', IkaUtils.getFileName('/tmp/statink.msgpack', 10)) self.assertEqual('/tmp/video.mp4-1.statink', IkaUtils.getFileName('/tmp/video.mp4.statink', 1))
def read_raw(self): from PIL import ImageGrab try: img = ImageGrab.grab(None) except TypeError: # なぜ発生することがあるのか、よくわからない IkaUtils.dprint('%s: Failed to grab desktop image' % self) return None img = np.asarray(img) return img
def read_frame(self): try: self.lock.acquire() if not self.is_active(): return None next_tick = None img = self._read_frame_func() # Skip some frames for performance. try: if self.cap_recorded_video: self._skip_frame_recorded() else: next_tick = self._skip_frame_realtime() except EOFError: pass # EOFError should be captured by the next cycle. finally: self.lock.release() if img is None: return None if self.cap_optimal_input_resolution: res720p = (img.shape[0] == 720) and (img.shape[1] == 1280) res1080p = (img.shape[0] == 1080) and (img.shape[1] == 1920) if not (res720p or res1080p): IkaUtils.dprint( 'Invalid input resolution (%dx%d). Acceptable res: 1280x720 or 1920x1080' % (img.shape[1], img.shape[0]) ) return None if next_tick is not None: self.last_tick = next_tick # need stratch? stratch = ( img.shape[0] != self.output_geometry[0] or img.shape[1] != self.output_geometry[1]) if stratch: img = cv2.resize( img, (self.output_geometry[1], self.output_geometry[0]), # fixme ) img = self._offset_filter.execute(img) return img
def test_lobby2text(self): lobby = 'tag' # English self.assertEqual('Squad Battle', IkaUtils.lobby2text(lobby, languages='en')) # Japanese self.assertEqual('タッグマッチ', IkaUtils.lobby2text(lobby, languages='ja')) # Fallback to English self.assertEqual('Squad Battle', IkaUtils.lobby2text(lobby, languages='??')) # Multiple languages self.assertEqual('タッグマッチ', IkaUtils.lobby2text(lobby, languages=['ja', 'en'])) ### Invalid lobby type lobby = 'nawabari' # Turf War self.assertEqual('?', IkaUtils.lobby2text(lobby, languages='en')) self.assertEqual('?', IkaUtils.lobby2text(lobby, languages='ja')) ### Unkonwn unknown_lobby = 'unknown' self.assertEqual('?', IkaUtils.lobby2text(unknown_lobby)) self.assertEqual('<:=', IkaUtils.lobby2text(unknown_lobby, unknown='<:='))
def test_add_event(self): mock_context = { 'game': { 'start_offset_msec': 100 }, 'engine': { 'msec': 101 } } IkaUtils.add_event(mock_context, 'key', 7) self.assertEqual({'key': [[1, 7]]}, mock_context['game']['events']) IkaUtils.add_event(mock_context, 'key', 11) self.assertEqual({'key': [[1, 11]]}, mock_context['game']['events']) IkaUtils.add_event(mock_context, 'key2', 13) self.assertEqual({ 'key': [[1, 11]], 'key2': [[1, 13]] }, mock_context['game']['events']) mock_context['engine']['msec'] = 102 IkaUtils.add_event(mock_context, 'key', 7) self.assertEqual({ 'key': [[1, 11], [2, 7]], 'key2': [[1, 13]] }, mock_context['game']['events'])
def test_weapon2text(self): ### Weapons weapon = 'bamboo14mk3' # English self.assertEqual('Bamboozler 14 Mk III', IkaUtils.weapon2text(weapon, languages='en')) # Japanese self.assertEqual('14式竹筒銃・丙', IkaUtils.weapon2text(weapon, languages='ja')) # Fallback to English self.assertEqual('Bamboozler 14 Mk III', IkaUtils.weapon2text(weapon, languages='??')) # Multiple languages self.assertEqual('14式竹筒銃・丙', IkaUtils.weapon2text(weapon, languages=['ja', 'en'])) ### Invalid weapons weapon = 'kyubanbomb' # Suction Bomb self.assertEqual('?', IkaUtils.weapon2text(weapon, languages='en')) self.assertEqual('?', IkaUtils.weapon2text(weapon, languages='ja')) ### Unkonwn unknown_weapon = 'unknown' self.assertEqual('?', IkaUtils.weapon2text(unknown_weapon)) self.assertEqual('<:=', IkaUtils.weapon2text(unknown_weapon, unknown='<:='))
def read_frame(self): try: self.lock.acquire() if not self.is_active(): return None next_tick = None img = self._read_frame_func() # Skip some frames for performance. try: if self.cap_recorded_video: self._skip_frame_recorded() else: next_tick = self._skip_frame_realtime() except EOFError: pass # EOFError should be captured by the next cycle. finally: self.lock.release() if img is None: return None if self.cap_optimal_input_resolution: res720p = (img.shape[0] == 720) and (img.shape[1] == 1280) res1080p = (img.shape[0] == 1080) and (img.shape[1] == 1920) if not (res720p or res1080p): IkaUtils.dprint( 'Invalid input resolution (%dx%d). Acceptable res: 1280x720 or 1920x1080' % (img.shape[1], img.shape[0])) return None if next_tick is not None: self.last_tick = next_tick # need stratch? stratch = (img.shape[0] != self.output_geometry[0] or img.shape[1] != self.output_geometry[1]) if stratch: img = cv2.resize( img, (self.output_geometry[1], self.output_geometry[0]), # fixme ) img = self._offset_filter.execute(img) return img
def test_get_file_name(self): mock_context = {'game': {'index': 0}, 'engine': {'source_file': None}} self.assertIsNone(IkaUtils.get_file_name(None, mock_context)) self.assertEqual('/tmp/statink.msgpack', IkaUtils.get_file_name('/tmp/statink.msgpack', mock_context)) mock_context['game']['index'] = 1 self.assertEqual('/tmp/statink-1.msgpack', IkaUtils.get_file_name('/tmp/statink.msgpack', mock_context)) mock_context['game']['index'] = 10 self.assertEqual('/tmp/statink-10.msgpack', IkaUtils.get_file_name('/tmp/statink.msgpack', mock_context)) mock_context['game']['index'] = 1 self.assertEqual('/tmp/video.mp4-1.statink', IkaUtils.get_file_name('/tmp/video.mp4.statink', mock_context)) self.assertEqual('/tmp/video.mp4-1.statink', IkaUtils.get_file_name('/tmp/video.mp4.statink', mock_context)) mock_context['engine']['source_file'] = None mock_context['game']['index'] = 0 self.assertEqual('__INPUT_FILE__.statink', IkaUtils.get_file_name('__INPUT_FILE__.statink', mock_context)) mock_context['engine']['source_file'] = None mock_context['game']['index'] = 2 self.assertEqual('__INPUT_FILE__-2.statink', IkaUtils.get_file_name('__INPUT_FILE__.statink', mock_context)) mock_context['engine']['source_file'] = '/tmp/video.mp4' mock_context['game']['index'] = 0 self.assertEqual('/tmp/video.mp4.statink', IkaUtils.get_file_name('__INPUT_FILE__.statink', mock_context)) mock_context['engine']['source_file'] = '/tmp/video.mp4' mock_context['game']['index'] = 3 self.assertEqual('/tmp/video.mp4-3.statink', IkaUtils.get_file_name('__INPUT_FILE__.statink', mock_context))
def test_copy_context(self): mock_context = { 'engine': { 'engine': self, 'source_file': 'video.mp4', 'service': { 'call_plugins_later': self.test_copy_context }, }, 'game': { 'map': 'kinmedai', 'rule': 'area', } } copied_context = IkaUtils.copy_context(mock_context) copied_context['engine']['source_file'] = 'movie.ts' copied_context['game']['map'] = 'hokke' copied_context['game']['rule'] = 'nawabari' self.assertEqual('video.mp4', mock_context['engine']['source_file']) self.assertEqual('movie.ts', copied_context['engine']['source_file']) self.assertIsNotNone(mock_context['engine']['engine']) self.assertIsNotNone( mock_context['engine']['service'].get('call_plugins_later')) self.assertEqual('kinmedai', mock_context['game']['map']) self.assertEqual('area', mock_context['game']['rule']) self.assertIsNone(copied_context['engine']['engine']) self.assertIsNone( copied_context['engine']['service'].get('call_plugins_later')) self.assertEqual('hokke', copied_context['game']['map']) self.assertEqual('nawabari', copied_context['game']['rule'])
def composite_payload(self, context): payload = { # 'id': game_id, #'recognition_source': filename, 'recognition_at': int(time.time()), 'agent': 'IkaLog re-recognition', 'agent_version': IKALOG_VERSION, 'players': [], } me = IkaUtils.getMyEntryFromContext(context) for e in context['game']['players']: player = {} player['team'] = 'my' if (e['team'] == me['team']) else 'his' player['is_me'] = 'yes' if e['me'] else 'no' player['weapon'] = e['weapon'] payload['players'].append(player) _set_values( [ # 'type', 'stat.ink Field', 'IkaLog Field' ['int', 'rank_in_team', 'rank_in_team'], ['int', 'kill', 'kills'], ['int', 'death', 'deaths'], ['int', 'level', 'rank'], ['int', 'point', 'score'], ['str_lower', 'rank', 'udemae_pre'], ], player, e) return payload
def test_getMyEntryFromContext(self): context = {'game': {}} self.assertIsNone(IkaUtils.getMyEntryFromContext(context)) context['game']['players'] = [ {'me': False, 'team': 1, 'rank_in_team': 1}, {'me': False, 'team': 1, 'rank_in_team': 2}, {'me': False, 'team': 2, 'rank_in_team': 1}, {'me': False, 'team': 2, 'rank_in_team': 2}, ] self.assertIsNone(IkaUtils.getMyEntryFromContext(context)) context['game']['players'][2]['me'] = True me = IkaUtils.getMyEntryFromContext(context) self.assertEqual(2, me['team']) self.assertEqual(1, me['rank_in_team'])
def test_copy_context(self): mock_context = { 'engine': { 'engine': self, 'source_file': 'video.mp4', 'service': {'call_plugins_later': self.test_copy_context}, }, 'game': { 'map': 'kinmedai', 'rule': 'area', }} copied_context = IkaUtils.copy_context(mock_context) copied_context['engine']['source_file'] = 'movie.ts' copied_context['game']['map'] = 'hokke' copied_context['game']['rule'] = 'nawabari' self.assertEqual('video.mp4', mock_context['engine']['source_file']) self.assertEqual('movie.ts', copied_context['engine']['source_file']) self.assertIsNotNone(mock_context['engine']['engine']) self.assertIsNotNone( mock_context['engine']['service'].get('call_plugins_later')) self.assertEqual('kinmedai', mock_context['game']['map']) self.assertEqual('area', mock_context['game']['rule']) self.assertIsNone(copied_context['engine']['engine']) self.assertIsNone( copied_context['engine']['service'].get('call_plugins_later')) self.assertEqual('hokke', copied_context['game']['map']) self.assertEqual('nawabari', copied_context['game']['rule'])
def test_get_file_name(self): mock_context = {'game': {'index': 0}, 'engine': {'source_file': None}} self.assertIsNone(IkaUtils.get_file_name(None, mock_context)) self.assertEqual( '/tmp/statink.msgpack', IkaUtils.get_file_name('/tmp/statink.msgpack', mock_context)) mock_context['game']['index'] = 1 self.assertEqual( '/tmp/statink-1.msgpack', IkaUtils.get_file_name('/tmp/statink.msgpack', mock_context)) mock_context['game']['index'] = 10 self.assertEqual( '/tmp/statink-10.msgpack', IkaUtils.get_file_name('/tmp/statink.msgpack', mock_context)) mock_context['game']['index'] = 1 self.assertEqual( '/tmp/video.mp4-1.statink', IkaUtils.get_file_name('/tmp/video.mp4.statink', mock_context)) self.assertEqual( '/tmp/video.mp4-1.statink', IkaUtils.get_file_name('/tmp/video.mp4.statink', mock_context)) mock_context['engine']['source_file'] = None mock_context['game']['index'] = 0 self.assertEqual( '__INPUT_FILE__.statink', IkaUtils.get_file_name('__INPUT_FILE__.statink', mock_context)) mock_context['engine']['source_file'] = None mock_context['game']['index'] = 2 self.assertEqual( '__INPUT_FILE__-2.statink', IkaUtils.get_file_name('__INPUT_FILE__.statink', mock_context)) mock_context['engine']['source_file'] = '/tmp/video.mp4' mock_context['game']['index'] = 0 self.assertEqual( '/tmp/video.mp4.statink', IkaUtils.get_file_name('__INPUT_FILE__.statink', mock_context)) mock_context['engine']['source_file'] = '/tmp/video.mp4' mock_context['game']['index'] = 3 self.assertEqual( '/tmp/video.mp4-3.statink', IkaUtils.get_file_name('__INPUT_FILE__.statink', mock_context))
def test_extend_languages(self): # Default languages self.assertIsNotNone(IkaUtils.extend_languages(None)) # The specified language(s) should be in the beginning. # 'en' and 'ja' as fallback languages should also exist. languages = IkaUtils.extend_languages('??') self.assertEqual('??', languages[0]) self.assertTrue('en' in languages) self.assertTrue('ja' in languages) # Input can be a list. languages = IkaUtils.extend_languages(['ja', 'fr']) self.assertEqual('ja', languages[0]) self.assertEqual('fr', languages[1]) self.assertTrue('en' in languages) self.assertTrue('ja' in languages)
def __init__(self, bbox=None): ''' bbox -- bbox Crop bounding box as (x, y, w, h) ''' self._check_import() self._launch = self._time() self._offset_filter = WarpFilter(self) self._calibration_requested = False if bbox is not None: self._offset_filter.set_bbox( bbox[0], bbox[1], bbox[2], bbox[3], ) self._offset_filter.enable() IkaUtils.dprint('%s: initalizing screen capture' % (self))
def predict(self, img_weapon): t1 = time.time() feat_weapon = self.image_to_feature(img_weapon) # print(feat_weapon.shape) y = forward_mlp(feat_weapon, self._layers) y_id = np.argmax(y, axis=1) # print(y) # print(y_id) # print(self._weapons_keys[y_id[0]]) # print(self._weapons_keys.index('sshooter')) t2 = time.time() IkaUtils.dprint('%s: predict %s took %s seconds' % (self, self._weapons_keys[y_id[0]], t2-t1)) return self._weapons_keys[y_id[0]], 0
def _set_values(fields, dest, src): for field in fields: f_type = field[0] f_statink = field[1] f_ikalog = field[2] if (f_ikalog in src) and (src[f_ikalog] is not None): if f_type == 'int': try: dest[f_statink] = int(src[f_ikalog]) except: # ValueError IkaUtils.dprint('%s: field %s failed: src[%s] == %s' % ( self, f_statink, f_ikalog, src[f_ikalog])) pass elif f_type == 'str': dest[f_statink] = str(src[f_ikalog]) elif f_type == 'str_lower': dest[f_statink] = str(src[f_ikalog]).lower()
def predict(self, img_weapon): t1 = time.time() feat_weapon = self.image_to_feature(img_weapon) # print(feat_weapon.shape) y = forward_mlp(feat_weapon, self._layers) y_id = np.argmax(y, axis=1) # print(y) # print(y_id) # print(self._weapons_keys[y_id[0]]) # print(self._weapons_keys.index('sshooter')) t2 = time.time() IkaUtils.dprint('%s: predict %s took %s seconds' % (self, self._weapons_keys[y_id[0]], t2 - t1)) return self._weapons_keys[y_id[0]], 0
def _set_values(fields, dest, src): for field in fields: f_type = field[0] f_statink = field[1] f_ikalog = field[2] if (f_ikalog in src) and (src[f_ikalog] is not None): if f_type == 'int': try: dest[f_statink] = int(src[f_ikalog]) except: # ValueError IkaUtils.dprint('%s: field %s failed: src[%s] == %s' % (self, f_statink, f_ikalog, src[f_ikalog])) pass elif f_type == 'str': dest[f_statink] = str(src[f_ikalog]) elif f_type == 'str_lower': dest[f_statink] = str(src[f_ikalog]).lower()
def auto_calibrate(self, img): r = self._warp_filter.calibrateWarp( img, validation_func=self.on_validate_warp) if r: self._warp_filter.enable() IkaUtils.dprint(_('Calibration succeeded!')) return True else: msg = '\n'.join([ _('Calibration failed! Cannot detect WiiU display.'), _('IkaLog expects 1280 x 720, or 1920 x 1080 as input resolution.' ), ]) try: r = wx.MessageDialog(None, msg, _('Warning'), wx.OK | wx.ICON_ERROR).ShowModal() except: IkaUtils.dprint(msg) return False
def auto_calibrate(self, img): r = self._warp_filter.calibrateWarp( img, validation_func=self.on_validate_warp ) if r: self._warp_filter.enable() IkaUtils.dprint(_('Calibration succeeded!')) return True else: msg = '\n'.join([ _('Calibration failed! Cannot detect WiiU display.'), _('IkaLog expects 1280 x 720, or 1920 x 1080 as input resolution.'), ]) try: r = wx.MessageDialog(None, msg, _('Warning'), wx.OK | wx.ICON_ERROR).ShowModal() except: IkaUtils.dprint(msg) return False
def auto_calibrate(self, img): r = self._warp_filter.calibrateWarp( img, validation_func=self.on_validate_warp ) if r: self._warp_filter.enable() IkaUtils.dprint('キャリブレーション成功') return True else: msg = '\n'.join([ 'WiiU の画面が検知できませんでした', '入力サイズは 1280 x 720 もしくは 1920 x 1080 です。', 'キャリブレーションを中断します。' ]) try: r = wx.MessageDialog(None, msg, 'Warining', wx.OK | wx.ICON_ERROR).ShowModal() except: IkaUtils.dprint(msg) return False
def __init__(self, bbox=None): ''' bbox -- bbox Crop bounding box as (x, y, w, h) ''' self._check_import() self.last_input_geom = None self._launch = self._time() self._warp_filter = WarpFilter(self) self._calibration_requested = False if bbox is not None: self._warp_filter.set_bbox( bbox[0], bbox[1], bbox[2], bbox[3], ) self._warp_filter.enable() IkaUtils.dprint('%s: initalizing screen capture' % (self))
def test_gear_ability2text(self): gear = 'ninja_squid' # English self.assertEqual('Ninja Squid', IkaUtils.gear_ability2text(gear, languages='en')) # Japanese self.assertEqual('イカニンジャ', IkaUtils.gear_ability2text(gear, languages='ja')) # Fallback to English self.assertEqual('Ninja Squid', IkaUtils.gear_ability2text(gear, languages='??')) # Multiple languages self.assertEqual('イカニンジャ', IkaUtils.gear_ability2text(gear, languages=['ja', 'en'])) # Unkonwn unknown_gear = 'unknown' self.assertEqual('?', IkaUtils.gear_ability2text(unknown_gear)) self.assertEqual('<:=', IkaUtils.gear_ability2text(unknown_gear, unknown='<:='))
def test_add_event(self): mock_context = {'game': {'start_offset_msec': 100}, 'engine': {'msec': 101}} IkaUtils.add_event(mock_context, 'key', 7) self.assertEqual({'key': [[1, 7]]}, mock_context['game']['events']) IkaUtils.add_event(mock_context, 'key', 11) self.assertEqual({'key': [[1, 11]]}, mock_context['game']['events']) IkaUtils.add_event(mock_context, 'key2', 13) self.assertEqual({'key': [[1, 11]], 'key2': [[1, 13]]}, mock_context['game']['events']) mock_context['engine']['msec'] = 102 IkaUtils.add_event(mock_context, 'key', 7) self.assertEqual({'key': [[1, 11], [2, 7]], 'key2': [[1, 13]]}, mock_context['game']['events'])
def on_validate_warp(self, points): w = int(points[1][0] - points[0][0]) h = int(points[2][1] - points[1][1]) print('on_validate_warp: ', w, h) acceptable_geoms = [[720, 1280], [1080, 1920]] acceptable = False exact = False for geom in acceptable_geoms: if (geom[0] - 3 < h) and (h < geom[0] + 3): if (geom[1] - 3 < w) and (w < geom[1] + 3): acceptable = True if geom[0] == h and geom[1] == w: exact = True if exact: pass elif acceptable: msg = '\n'.join([ 'キャリブレーションできましたが、期待する画面サイズと異なります (%d x %d)' % (w, h), 'IkaLog への入力サイズは 1280 x 720 もしくは 1920 x 1080 です。', '各種認識が正常に動作しない可能性があります。', '', '再度キャリブレーションすると改善する場合があります。', '', ]) try: r = wx.MessageDialog(None, msg, 'Warining', wx.OK | wx.ICON_ERROR).ShowModal() except: IkaUtils.dprint(msg) else: return False self.last_capture_geom = (h, w) return True
def on_validate_warp(self, points): w = int(points[1][0] - points[0][0]) h = int(points[2][1] - points[1][1]) print('on_validate_warp: ', w, h) acceptable_geoms = [[720, 1280], [1080, 1920]] acceptable = False exact = False for geom in acceptable_geoms: if (geom[0] - 3 < h) and (h < geom[0] + 3): if (geom[1] - 3 < w) and (w < geom[1] + 3): acceptable = True if geom[0] == h and geom[1] == w: exact = True if exact: pass elif acceptable: msg = '\n'.join([ _('Calibration succeeded!'), _('Due to the input resultion (%d x %d) some recognition may fail unexpectedly.' ) % (w, h), _('IkaLog expects 1280 x 720, or 1920 x 1080 as input resolution.' ), ]) try: r = wx.MessageDialog(None, msg, _('Warning'), wx.OK | wx.ICON_ERROR).ShowModal() except: IkaUtils.dprint(msg) else: return False self.last_capture_geom = (h, w) return True
def test_get_time(self): mock_context = {'engine': {'epoch_time': None, 'msec': 5000}} # epoch_time is None time_before = time.time() time_actual = IkaUtils.getTime(mock_context) time_after = time.time() self.assertTrue(time_before <= time_actual <= time_after) # epoch_time is 0 mock_context['engine']['epoch_time'] = 0 expected_time = (mock_context['engine']['epoch_time'] + mock_context['engine']['msec'] / 1000.0) self.assertEqual(expected_time, IkaUtils.getTime(mock_context)) # epoch_time is 2015-05-28 10:00:00, msec is 1 hour mock_context['engine']['epoch_time'] = ( time.mktime(time.strptime("20150528_100000", "%Y%m%d_%H%M%S"))) mock_context['engine']['msec'] = 60 * 60 * 1000 time_actual = IkaUtils.getTime(mock_context) self.assertEqual("20150528_110000", time.strftime("%Y%m%d_%H%M%S", time.localtime(time_actual)))
def test_get_time(self): mock_context = {'engine': {'epoch_time': None, 'msec': 5000}} # epoch_time is None time_before = time.time() time_actual = IkaUtils.getTime(mock_context) time_after = time.time() self.assertTrue(time_before <= time_actual <= time_after) # epoch_time is 0 mock_context['engine']['epoch_time'] = 0 expected_time = (mock_context['engine']['epoch_time'] + mock_context['engine']['msec'] / 1000.0) self.assertEqual(expected_time, IkaUtils.getTime(mock_context)) # epoch_time is 2015-05-28 10:00:00, msec is 1 hour mock_context['engine']['epoch_time'] = (time.mktime( time.strptime("20150528_100000", "%Y%m%d_%H%M%S"))) mock_context['engine']['msec'] = 60 * 60 * 1000 time_actual = IkaUtils.getTime(mock_context) self.assertEqual( "20150528_110000", time.strftime("%Y%m%d_%H%M%S", time.localtime(time_actual)))
def on_validate_warp(self, points): w = int(points[1][0] - points[0][0]) h = int(points[2][1] - points[1][1]) print('on_validate_warp: ', w, h) acceptable_geoms = [[720, 1280], [1080, 1920]] acceptable = False exact = False for geom in acceptable_geoms: if (geom[0] - 3 < h) and (h < geom[0] + 3): if (geom[1] - 3 < w) and (w < geom[1] + 3): acceptable = True if geom[0] == h and geom[1] == w: exact = True if exact: pass elif acceptable: msg = '\n'.join([ _('Calibration succeeded!'), _('Due to the input resultion (%d x %d) some recognition may fail unexpectedly.') % (w, h), _('IkaLog expects 1280 x 720, or 1920 x 1080 as input resolution.'), ]) try: r = wx.MessageDialog(None, msg, _('Warning'), wx.OK | wx.ICON_ERROR).ShowModal() except: IkaUtils.dprint(msg) else: return False self.last_capture_geom = (h, w) return True
def test_get_path(self): self.assertTrue(os.path.isfile(IkaUtils.get_path('IkaLog.py'))) self.assertTrue(os.path.isdir(IkaUtils.get_path('test'))) self.assertTrue(os.path.isdir(IkaUtils.get_path())) self.assertEqual(os.path.abspath(__file__), IkaUtils.get_path('test', 'utils', 'test_ikautils.py')) if IkaUtils.isWindows(): pass # TODO: add test cases else: abspath = '/tmp/test/dir' self.assertEqual(abspath, IkaUtils.get_path(abspath))
def test_get_path(self): self.assertTrue(os.path.isfile(IkaUtils.get_path('IkaLog.py'))) self.assertTrue(os.path.isdir(IkaUtils.get_path('test'))) self.assertTrue(os.path.isdir(IkaUtils.get_path())) self.assertEqual( os.path.abspath(__file__), IkaUtils.get_path('test', 'utils', 'test_ikautils.py')) if IkaUtils.isWindows(): pass # TODO: add test cases else: abspath = '/tmp/test/dir' self.assertEqual(abspath, IkaUtils.get_path(abspath))
def test_rule2text(self): rule_id = 'area' # English self.assertEqual('Splat Zones', IkaUtils.rule2text(rule_id, languages='en')) # Japanese self.assertEqual('ガチエリア', IkaUtils.rule2text(rule_id, languages='ja')) # Fallback to English self.assertEqual('Splat Zones', IkaUtils.rule2text(rule_id, languages='??')) # Multiple languages self.assertEqual('ガチエリア', IkaUtils.rule2text(rule_id, languages=['ja', 'en'])) # Unkonwn unknown_rule_id = 'unknown' self.assertEqual('?', IkaUtils.rule2text(unknown_rule_id)) self.assertEqual('<:=', IkaUtils.rule2text(unknown_rule_id, unknown='<:='))
def test_map2text(self): map_id = 'shottsuru' # English self.assertEqual('Piranha Pit', IkaUtils.map2text(map_id, languages='en')) # Japanese self.assertEqual('ショッツル鉱山', IkaUtils.map2text(map_id, languages='ja')) # Fallback to English self.assertEqual('Piranha Pit', IkaUtils.map2text(map_id, languages='??')) # Multiple languages self.assertEqual('ショッツル鉱山', IkaUtils.map2text(map_id, languages=['ja', 'en'])) # Unkonwn unknown_map_id = 'unknown' self.assertEqual('?', IkaUtils.map2text(unknown_map_id)) self.assertEqual('<:=', IkaUtils.map2text(unknown_map_id, unknown='<:='))
def test_map2text(self): map_mock = IkaMatcherMock('kinmedai') # English self.assertEqual('Museum d\'Alfonsino', IkaUtils.map2text(map_mock, languages='en')) # Japanese self.assertEqual('キンメダイ美術館', IkaUtils.map2text(map_mock, languages='ja')) # Fallback to English self.assertEqual('Museum d\'Alfonsino', IkaUtils.map2text(map_mock, languages='??')) # Multiple languages self.assertEqual('キンメダイ美術館', IkaUtils.map2text(map_mock, languages=['ja', 'en'])) # Unkonwn unknown_map_mock = IkaMatcherMock('unknown') self.assertEqual('?', IkaUtils.map2text(unknown_map_mock)) self.assertEqual('<:=', IkaUtils.map2text(unknown_map_mock, unknown='<:='))
def test_gear_ability2text(self): gear = 'ninja_squid' # English self.assertEqual('Ninja Squid', IkaUtils.gear_ability2text(gear, languages='en')) # Japanese self.assertEqual('イカニンジャ', IkaUtils.gear_ability2text(gear, languages='ja')) # Fallback to English self.assertEqual('Ninja Squid', IkaUtils.gear_ability2text(gear, languages='??')) # Multiple languages self.assertEqual( 'イカニンジャ', IkaUtils.gear_ability2text(gear, languages=['ja', 'en'])) # Unkonwn unknown_gear = 'unknown' self.assertEqual('?', IkaUtils.gear_ability2text(unknown_gear)) self.assertEqual( '<:=', IkaUtils.gear_ability2text(unknown_gear, unknown='<:='))
def test_rule_id2text(self): rule_id = 'nawabari' # English self.assertEqual('Turf War', IkaUtils.rule_id2text(rule_id, languages='en')) # Japanese self.assertEqual('ナワバリバトル', IkaUtils.rule_id2text(rule_id, languages='ja')) # Fallback to English self.assertEqual('Turf War', IkaUtils.rule_id2text(rule_id, languages='??')) # Multiple languages self.assertEqual( 'ナワバリバトル', IkaUtils.rule_id2text(rule_id, languages=['ja', 'en'])) # Unkonwn unknown_rule_id = 'unknown' self.assertEqual('?', IkaUtils.rule_id2text(unknown_rule_id)) self.assertEqual('<:=', IkaUtils.rule_id2text(unknown_rule_id, unknown='<:='))