def test_fix_settings(self): broken = settings.defaults() del broken['wait_time'] broken['fake'] = True settings.access_registry(save=broken) settings.fix_settings(self.log) self.assertEqual(settings.access_registry(), settings.defaults())
def manual_tune(args, res_keys, npdtypes): keys = [] values = [] for k, v in args.items(): keys.append(k) values.append(v) keys += res_keys record_list = [] try: for c in itertools.product(*values): print('Try this setting : ', dict(zip(keys, c))) settings.fix_settings(dict(zip(keys, c))) train.main(settings.params) test.main(settings.params) res = quantitive_evaluate.main(settings.params, 'relpred') record_list.append(tuple([*c, *[res[k] for k in res_keys]])) results = pd.DataFrame( np.array(record_list, dtype=[(keys[i], npdtypes[i]) for i in range(len(keys))])) finally: results.to_csv(os.path.join('expr_log.csv'))
def menu_restore_defaults(self, *args): self.log.info("GUI: Restoring default settings") # TODO: consider sharing code between this and settings GUI restore defaults button settings.fix_settings(self.log) default_settings: dict = settings.defaults() current_settings: dict = settings.access_registry() self.pause() if current_settings == default_settings: self.log.debug("Current settings are default") messagebox.showinfo( self.loc.text("Restore defaults"), self.loc.text("Current settings are already default.")) else: changed_settings: dict = { s: current_settings[s] for s in current_settings if current_settings[s] != default_settings[s] } self.log.debug(f"Changed settings: {changed_settings}") allowed_reset: str = "yes" if len(changed_settings) == 1: allowed_reset = messagebox.askquestion( self.loc.text("Restore defaults"), self.loc.text("Restore 1 setting to default?")) elif len(changed_settings) > 1: allowed_reset = messagebox.askquestion( self.loc.text("Restore defaults"), self.loc.text("Restore {0} settings to defaults?").format( len(changed_settings))) if allowed_reset == "yes": settings.access_registry(save=default_settings) self.log.debug("Restored default settings") else: self.log.debug("Didn't restore default settings") self.unpause()
target = [tuple(x) for j, x in enumerate(targets[i])] assert len(list(set(prediction))) == len(prediction) assert len(list(set(target))) == len(target) target_set = set.intersection(few_shot_index_set, target) print(i) # print('prediction', prediction) # print('target', target) total += len(target_set) res['recall@50'] += len(set.intersection(set(prediction[:50]), target_set))) res['recall@100'] += len(set.intersection(set(prediction[:100]), target_set))) res['recall@50'] /= total res['recall@100'] /= total return res def main(params, which_expr): # load predictions predictions = np.load(os.path.join('results', params['dataset'], 'predictions.npy'), allow_pickle=True) targets = np.load(os.path.join('results', params['dataset'], 'targets.npy'), allow_pickle=True) if which_expr == 'relpred' or which_expr == 'all': res = evaluate_relationship_prediction(predictions, targets) if which_expr == 'fewshot': res = evalutate_relationship_prediction(predictions, sys.argv[2]) return res if __name__ == '__main__': from settings import params, fix_settings fix_settings() main(params, sys.argv[1])
def __init__(self, master: tk.Toplevel, log: logger.Log, position: Optional[tuple] = None, reload_settings: Optional[tuple] = None): self.log: logger.Log = log self.log.info( f"Opening settings menu for TF2 Rich Presence {launcher.VERSION}") self.gui_language: Optional[str] = localization.langs[ localization.langs.index( reload_settings[8].get())] if reload_settings else None self.loc: localization.Localizer = localization.Localizer( self.log, self.gui_language if self.gui_language else settings.get('language')) self.log_levels: Tuple[str, ...] = ('Debug', 'Info', 'Error', 'Critical', 'Off') self.sentry_levels: Tuple[str, ...] = ('All errors', 'Crashes', 'Never') self.rpc_lines: Tuple[str, ...] = ('Server name', 'Player count', 'Time on map', 'Kills', 'Class') self.log_levels_display: List[str] = [ self.loc.text(item) for item in self.log_levels ] self.sentry_levels_display: List[str] = [ self.loc.text(item) for item in self.sentry_levels ] self.rpc_lines_display: List[str] = [ self.loc.text(item) for item in self.rpc_lines ] if reload_settings: # the GUI was reloaded with a new language, so persist the currently selected (but not saved) settings self.sentry_level, self.wait_time, self.wait_time_slow, self.check_updates, self.request_timeout, self.hide_queued_gamemode, self.log_level, self.console_scan_kb, \ self.language, self.top_line, self.bottom_line, self.trim_console_log, self.server_rate_limit, self.gui_scale, self.drawing_gamemodes, self.preserve_window_pos = reload_settings else: # create every setting variable without values self.sentry_level: tk.StringVar = tk.StringVar() self.wait_time: tk.IntVar = tk.IntVar() self.wait_time_slow: tk.IntVar = tk.IntVar() self.check_updates: tk.BooleanVar = tk.BooleanVar() self.request_timeout: tk.IntVar = tk.IntVar() self.hide_queued_gamemode: tk.BooleanVar = tk.BooleanVar() self.log_level: tk.StringVar = tk.StringVar() self.console_scan_kb: tk.IntVar = tk.IntVar() self.language: tk.StringVar = tk.StringVar() self.top_line: tk.StringVar = tk.StringVar() self.bottom_line: tk.StringVar = tk.StringVar() self.trim_console_log: tk.BooleanVar = tk.BooleanVar() self.server_rate_limit: tk.IntVar = tk.IntVar() self.gui_scale: tk.IntVar = tk.IntVar() self.drawing_gamemodes: tk.BooleanVar = tk.BooleanVar() self.preserve_window_pos: tk.BooleanVar = tk.BooleanVar() try: # load settings from registry settings.fix_settings(self.log) self.settings_loaded: dict = settings.access_registry() self.log.debug(f"Current settings: {self.settings_loaded}") self.log.debug( f"Are default: {self.settings_loaded == settings.defaults()}" ) self.sentry_level.set(self.settings_loaded['sentry_level']) self.wait_time.set(self.settings_loaded['wait_time']) self.wait_time_slow.set(self.settings_loaded['wait_time_slow']) self.check_updates.set(self.settings_loaded['check_updates']) self.request_timeout.set( self.settings_loaded['request_timeout']) self.hide_queued_gamemode.set( self.settings_loaded['hide_queued_gamemode']) self.log_level.set(self.settings_loaded['log_level']) self.console_scan_kb.set( self.settings_loaded['console_scan_kb']) self.language.set(self.gui_language if self.gui_language else self.settings_loaded['language']) self.top_line.set(self.settings_loaded['top_line']) self.bottom_line.set(self.settings_loaded['bottom_line']) self.trim_console_log.set( self.settings_loaded['trim_console_log']) self.server_rate_limit.set( self.settings_loaded['server_rate_limit']) self.gui_scale.set(self.settings_loaded['gui_scale']) self.drawing_gamemodes.set( self.settings_loaded['drawing_gamemodes']) self.preserve_window_pos.set( self.settings_loaded['preserve_window_pos']) except Exception: # probably a json decode error formatted_exception: str = traceback.format_exc() self.log.error( f"Error in loading settings, defaulting: \n{formatted_exception}" ) messagebox.showerror( self.loc.text("Error"), self.loc.text( "Couldn't load settings, reverting to defaults.{0}"). format(f'\n\n{formatted_exception}')) self.restore_defaults() self.settings_loaded: dict = settings.defaults() # account for localization self.localization_compensate() actual_language: str = self.language.get() actual_top_line: str = self.top_line.get() actual_bottom_line: str = self.bottom_line.get() # actually create the settings window fairly late to reduce time with a tiny window visible self.master: Union[tk.Toplevel, tk.Tk] = master tk.Frame.__init__(self, self.master) if position: gui.pos_window_by_center(self.master, *position) check_int_command: str = self.register(check_int) self.master.protocol('WM_DELETE_WINDOW', self.close_window) self.master.title( self.loc.text("TF2 Rich Presence ({0}) settings").format( launcher.VERSION)) self.master.resizable(False, False) # disables resizing gui.set_window_icon(self.log, self.master, True) if not reload_settings: self.window_x: Optional[int] = None self.window_y: Optional[int] = None # create label frames self.lf_main: ttk.Labelframe = ttk.Labelframe( self.master, text=self.loc.text("Main")) self.lf_advanced: ttk.Labelframe = ttk.Labelframe( self.master, text=self.loc.text("Advanced")) # create settings widgets setting1_frame = ttk.Frame(self.lf_advanced) setting1_text = ttk.Label( setting1_frame, text="{}".format(self.loc.text("Log reporting frequency: "))) setting1_radiobuttons = [] for sentry_level_text in self.sentry_levels_display: setting1_radiobuttons.append( ttk.Radiobutton(setting1_frame, variable=self.sentry_level, text=sentry_level_text, value=sentry_level_text, command=self.setting_changed)) setting3_frame = ttk.Frame(self.lf_main) setting3_text = ttk.Label( setting3_frame, text="{}".format( self.loc.text("Delay between refreshes, in seconds: "))) setting3_option = ttk.Spinbox(setting3_frame, textvariable=self.wait_time, width=6, from_=0, to=float('inf'), validate='all', validatecommand=(check_int_command, '%P'), command=self.setting_changed) setting5 = ttk.Checkbutton( self.lf_main, variable=self.check_updates, command=self.setting_changed, text="{}".format( self.loc.text("Check for program updates when launching"))) setting6_frame = ttk.Frame(self.lf_advanced) setting6_text = ttk.Label( setting6_frame, text="{}".format( self.loc.text( "Internet connection timeout (for updater and server querying): " ))) setting6_option = ttk.Spinbox(setting6_frame, textvariable=self.request_timeout, width=6, from_=0, to=float('inf'), validate='all', validatecommand=(check_int_command, '%P'), command=self.setting_changed) setting8 = ttk.Checkbutton( self.lf_main, variable=self.hide_queued_gamemode, command=self.setting_changed, text="{}".format( self.loc.text( "Hide game type (Casual, Comp, MvM) queued for"))) setting9_frame = ttk.Frame(self.lf_advanced) setting9_text = ttk.Label(setting9_frame, text="{}".format( self.loc.text("Max log level: "))) setting9_radiobuttons = [] for log_level_text in self.log_levels_display: setting9_radiobuttons.append( ttk.Radiobutton(setting9_frame, variable=self.log_level, text=log_level_text, value=log_level_text, command=self.setting_changed)) setting10_frame = ttk.Frame(self.lf_advanced) setting10_text = ttk.Label( setting10_frame, text="{}".format( self.loc.text("Max kilobytes of console.log to scan: "))) setting10_option = ttk.Spinbox(setting10_frame, textvariable=self.console_scan_kb, width=8, from_=0, to=float('inf'), validate='all', validatecommand=(check_int_command, '%P'), command=self.setting_changed) setting13_frame = ttk.Frame(self.lf_main) setting13_text = ttk.Label(setting13_frame, text="{}".format( self.loc.text("Language: "))) setting13_options = ttk.OptionMenu(setting13_frame, self.language, localization.langs[0], *localization.langs_localized, command=self.update_language) setting14_frame = ttk.Frame(self.lf_main) setting14_text = ttk.Label(setting14_frame, text="{}".format( self.loc.text("Bottom line: "))) setting14_radiobuttons = [] for rpc_line_text in self.rpc_lines_display: setting14_radiobuttons.append( ttk.Radiobutton(setting14_frame, variable=self.bottom_line, text=rpc_line_text, value=rpc_line_text, command=self.setting_changed)) setting15 = ttk.Checkbutton( self.lf_advanced, variable=self.trim_console_log, command=self.setting_changed, text="{}".format( self.loc.text( "Occasionally limit console.log's size and remove empty lines and common errors" ))) setting16_frame = ttk.Frame(self.lf_main) setting16_text = ttk.Label( setting16_frame, text="{}".format( self.loc.text( "Delay between refreshes when TF2 and Discord aren't running: " ))) # and Steam but whatever setting16_option = ttk.Spinbox(setting16_frame, textvariable=self.wait_time_slow, width=6, from_=0, to=float('inf'), validate='all', validatecommand=(check_int_command, '%P'), command=self.setting_changed) setting17_frame = ttk.Frame(self.lf_advanced) setting17_text = ttk.Label( setting17_frame, text="{}".format(self.loc.text("Server querying rate limit: "))) setting17_option = ttk.Spinbox(setting17_frame, textvariable=self.server_rate_limit, width=6, from_=0, to=float('inf'), validate='all', validatecommand=(check_int_command, '%P'), command=self.setting_changed) setting18_frame = ttk.Frame(self.lf_main) setting18_text = ttk.Label(setting18_frame, text="{}".format( self.loc.text("GUI scale: "))) setting18_option = tk.Scale(setting18_frame, variable=self.gui_scale, from_=50, to=200, resolution=5, length=150, orient=tk.HORIZONTAL, command=self.setting_changed) setting19_frame = ttk.Frame(self.lf_main) setting19_text = ttk.Label(setting19_frame, text="{}".format( self.loc.text("Top line: "))) setting19_radiobuttons = [] for rpc_line_text in self.rpc_lines_display: setting19_radiobuttons.append( ttk.Radiobutton(setting19_frame, variable=self.top_line, text=rpc_line_text, value=rpc_line_text, command=self.setting_changed)) setting20 = ttk.Checkbutton( self.lf_main, variable=self.drawing_gamemodes, command=self.setting_changed, text="{}".format( self.loc.text("Use classic gamemode images in the GUI"))) setting21 = ttk.Checkbutton( self.lf_main, variable=self.preserve_window_pos, command=self.setting_changed, text="{}".format( self.loc.text("Remember previous window position"))) # more localization compensation self.language.set(actual_language) self.top_line.set(actual_top_line) self.bottom_line.set(actual_bottom_line) # prepare widgets to be added setting1_text.pack(side='left', fill='none', expand=False) for setting1_radiobutton in setting1_radiobuttons: setting1_radiobutton.pack(side='left', fill='none', expand=False, padx=(0, 5)) setting3_text.pack(side='left', fill='none', expand=False) setting3_option.pack(side='left', fill='none', expand=False) setting6_text.pack(side='left', fill='none', expand=False) setting6_option.pack(side='left', fill='none', expand=False) setting9_text.pack(side='left', fill='none', expand=False) for setting9_radiobutton in setting9_radiobuttons: setting9_radiobutton.pack(side='left', fill='none', expand=False, padx=(0, 5)) setting10_text.pack(side='left', fill='none', expand=False) setting10_option.pack(side='left', fill='none', expand=False) setting13_text.pack(side='left', fill='none', expand=False) setting13_options.pack(side='left', fill='none', expand=False) setting14_text.pack(side='left', fill='none', expand=False) for setting14_radiobutton in setting14_radiobuttons: setting14_radiobutton.pack(side='left', fill='none', expand=False, padx=(0, 5)) setting16_text.pack(side='left', fill='none', expand=False) setting16_option.pack(side='left', fill='none', expand=False) setting17_text.pack(side='left', fill='none', expand=False) setting17_option.pack(side='left', fill='none', expand=False) setting18_text.pack(side='left', fill='none', expand=False) setting18_option.pack(side='left', padx=5) setting19_text.pack(side='left', fill='none', expand=False) for setting19_radiobutton in setting19_radiobuttons: setting19_radiobutton.pack(side='left', fill='none', expand=False, padx=(0, 5)) # add widgets to the labelframes and main window setting13_frame.grid(row=0, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(9, 0)) setting3_frame.grid(row=1, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(3, 0)) setting16_frame.grid(row=2, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(3, 0)) setting19_frame.grid(row=3, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(3, 0)) setting14_frame.grid(row=4, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(3, 0)) setting18_frame.grid(row=5, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(0, 0)) setting10_frame.grid(row=6, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(11, 0)) setting20.grid(row=7, sticky=tk.W, columnspan=2, padx=(20, 40), pady=(4, 0)) setting8.grid(row=8, sticky=tk.W, columnspan=2, padx=(20, 40), pady=(4, 0)) setting21.grid(row=9, sticky=tk.W, columnspan=2, padx=(20, 40), pady=(4, 0)) setting15.grid(row=10, sticky=tk.W, columnspan=2, padx=(20, 40), pady=(4, 0)) setting5.grid(row=11, sticky=tk.W, columnspan=2, padx=(20, 40), pady=(4, 10)) setting6_frame.grid(row=12, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(4, 0)) setting17_frame.grid(row=13, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(3, 0)) setting1_frame.grid(row=14, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(4, 0)) setting9_frame.grid(row=15, columnspan=2, sticky=tk.W, padx=(20, 40), pady=(4, 10)) self.lf_main.grid(row=0, padx=30, pady=15, sticky=tk.W + tk.E) self.lf_advanced.grid(row=1, padx=30, pady=0, sticky=tk.W + tk.E) self.buttons_frame = ttk.Frame(self.master) self.restore_button = ttk.Button( self.buttons_frame, text=self.loc.text("Restore defaults"), command=self.restore_defaults) self.restore_button.grid(row=0, column=1, padx=(10, 0), pady=(20, 20)) cancel_button = ttk.Button(self.buttons_frame, text=self.loc.text("Close without saving"), command=self.close_without_saving) cancel_button.grid(row=0, column=2, padx=10, pady=(20, 20)) self.ok_button = ttk.Button(self.buttons_frame, text=self.loc.text("Save and close"), command=self.save_and_close, default=tk.ACTIVE) self.ok_button.grid(row=0, column=3, sticky=tk.W, padx=0, pady=(20, 20)) self.buttons_frame.grid(row=100, columnspan=3) self.defaults_button_enabled: bool = True self.setting_changed() self.master.update() self.window_dimensions = self.master.winfo_width( ), self.master.winfo_height() self.log.debug(f"Window size: {self.window_dimensions}") self.master.focus_force() self.master.grab_set() if position: gui.pos_window_by_center(self.master, *position)
def __init__(self, log: Optional[logger.Log] = None, set_process_priority: bool = True): if log: self.log: logger.Log = log else: self.log = logger.Log() self.log.error( f"Initialized main.TF2RichPresense without a log, defaulting to one at {self.log.filename}" ) settings.fix_settings(self.log) default_settings: dict = settings.defaults() current_settings: dict = settings.access_registry() if current_settings == default_settings: self.log.debug("Current settings are default") else: self.log.debug( f"Non-default settings: {settings.compare_settings(default_settings, current_settings)}" ) self.gui: gui.GUI = gui.GUI(self.log, main_controlled=True) self.process_scanner: processes.ProcessScanner = processes.ProcessScanner( self.log) self.loc: localization.Localizer = localization.Localizer(self.log) self.game_state: game_state.GameState = game_state.GameState( self.log, self.loc) self.rpc_client: Optional[ipc.DiscordIPC] = None self.client_connected: bool = False self.rpc_connected: bool = False self.test_state: str = 'init' self.activity: dict = {} self.should_mention_discord: bool = True self.should_mention_tf2: bool = True self.should_mention_steam: bool = True self.has_checked_class_configs: bool = False self.has_seen_kataiser: bool = False self.console_log_mtime: Optional[int] = None self.old_console_log_mtime: Optional[int] = None self.loop_iteration: int = 0 self.custom_functions = None self.usernames: Set[str] = set() self.last_name_scan_time: float = time.time() # close enough self.steam_config_mtimes: Dict[str, int] = {} self.cleanup_primed: bool = True self.slow_sleep_time: bool = False self.has_set_process_priority: bool = not set_process_priority self.kataiser_scan_loop: int = 0 self.did_init_operations: bool = False self.no_condebug: bool = False self.fast_next_loop: bool = False self.reset_launched_with_button: bool = False self.last_console_log_size: Optional[int] = None try: self.log.cleanup(20 if launcher.DEBUG else 10) except (FileNotFoundError, PermissionError): self.log.error( f"Couldn't clean up logs folder:\n{traceback.format_exc()}") self.log.debug( f"CPU: {psutil.cpu_count(logical=False)} cores, {psutil.cpu_count()} threads, {round(psutil.cpu_freq().max / 1000, 1)} GHz" ) platform_info: Dict[str, Any] = { 'architecture': platform.architecture, 'machine': platform.machine, 'system': platform.system, 'platform': platform.platform, 'processor': platform.processor, 'python_version_tuple': platform.python_version_tuple } for platform_part in platform_info: try: if platform_part == 'platform': platform_info[platform_part] = platform_info[ platform_part](aliased=True) else: platform_info[platform_part] = platform_info[ platform_part]() except Exception: self.log.error( f"Exception during platform.{platform_part}(), skipping\n{traceback.format_exc()}" ) self.log.debug(f"Platform: {platform_info}") if not os.path.supports_unicode_filenames: self.log.error( "Looks like the OS doesn't support unicode filenames. This might cause problems" ) self.import_custom()