From 4a2ece9274fbec8856c0a2161fce3243e2467ae8 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Tue, 13 Jan 2026 16:42:31 +0000 Subject: [PATCH] Refactor: Replace print statements with uniform logging - Replaced `print()` calls with `mw.logger.log()` or injected `logger.log()` across `src/Ankimon/`. - Updated `Settings` and `DataHandler` classes to accept `logger` via dependency injection. - Updated `singletons.py` to inject `logger` into `Settings` and `DataHandler`. - Updated `PokemonCollectionDialog` to handle logging correctly in `trade_pokemon` helper functions using `mw.logger`. - Refactored `src/Ankimon/utils.py`, `src/Ankimon/functions/`, and `src/Ankimon/poke_engine/` files to use logging. - Configured standard python logging for standalone script `update_moves.py`. - Removed commented-out debug print statements in `pokedex_obj.py`. - Replaced `showInfo` calls in `TrainerCard` with `logger.log_and_showinfo` for consistency. --- .../functions/LegendaryCatchingFunction.py | 7 ------- src/Ankimon/functions/battle_functions.py | 7 ++++--- src/Ankimon/functions/pokedex_functions.py | 4 ++-- src/Ankimon/functions/sprite_functions.py | 3 ++- src/Ankimon/functions/trainer_functions.py | 3 ++- .../poke_engine/ankimon_hooks_to_poke_engine.py | 5 +++-- .../poke_engine/data/scripts/update_moves.py | 5 ++++- src/Ankimon/pokedex/pokedex_obj.py | 17 +++++------------ src/Ankimon/pyobj/collection_dialog.py | 6 +++--- src/Ankimon/pyobj/data_handler.py | 9 +++++---- src/Ankimon/pyobj/settings.py | 11 ++++++----- src/Ankimon/pyobj/trainer_card.py | 10 +++++----- src/Ankimon/singletons.py | 4 ++-- src/Ankimon/utils.py | 4 ++-- 14 files changed, 45 insertions(+), 50 deletions(-) diff --git a/src/Ankimon/functions/LegendaryCatchingFunction.py b/src/Ankimon/functions/LegendaryCatchingFunction.py index d7dd396ba..d5e870895 100644 --- a/src/Ankimon/functions/LegendaryCatchingFunction.py +++ b/src/Ankimon/functions/LegendaryCatchingFunction.py @@ -49,10 +49,3 @@ def get_catchable_pokemon(self, caught_pokemon): if self.can_catch(caught_pokemon, pokemon): catchable.add(pokemon) return catchable - - -# Example usage -caught = {151, 243, 244, 245} # Already caught Mew, Raikou, Entei, Suicune -catching = LegendaryCatching() - -print("Catchable Pokémon:", catching.get_catchable_pokemon(caught)) diff --git a/src/Ankimon/functions/battle_functions.py b/src/Ankimon/functions/battle_functions.py index ea5f3dd16..8c3a3297e 100644 --- a/src/Ankimon/functions/battle_functions.py +++ b/src/Ankimon/functions/battle_functions.py @@ -3,6 +3,7 @@ from ..poke_engine import constants from ..resources import move_names_file_path from ..pyobj.error_handler import show_warning_with_traceback +from aqt import mw with open(move_names_file_path, "r", encoding="utf-8") as f: MOVE_NAME_LOOKUP = json.load(f) @@ -117,7 +118,7 @@ def update_pokemon_battle_status(battle_info: dict, enemy_pokemon, main_pokemon) from ..pyobj.error_handler import show_warning_with_traceback show_warning_with_traceback(e, "Failed to update pokemon battle status") except ImportError: - print(f"ERROR in update_pokemon_battle_status: {e}") + mw.logger.log("error", f"ERROR in update_pokemon_battle_status: {e}") return False, False @@ -154,7 +155,7 @@ def safe_translate(key: str, **kwargs) -> str: if result and result.strip(): return result except (KeyError, AttributeError, Exception) as e: - print(f"Translation error for key '{key}': {e}") + mw.logger.log("error", f"Translation error for key '{key}': {e}") if 'pokemon_name' in kwargs and 'status_name' in kwargs: if 'apply' in key or 'still' in key: @@ -486,7 +487,7 @@ def check_persistent_effects(): effect_messages.append(message) except Exception as e: - print(f"Error processing state change {change}: {e}") + mw.logger.log("error", f"Error processing state change {change}: {e}") effect_messages.append(f"Battle effect occurred (processing error)") continue diff --git a/src/Ankimon/functions/pokedex_functions.py b/src/Ankimon/functions/pokedex_functions.py index b15e39101..622881127 100644 --- a/src/Ankimon/functions/pokedex_functions.py +++ b/src/Ankimon/functions/pokedex_functions.py @@ -563,9 +563,9 @@ def check_key_in_table(column_name, value, file_path): break # Exit the loop once the matching row is found except FileNotFoundError: - print(f"Error: The file {file_path} does not exist.") + mw.logger.log("error", f"Error: The file {file_path} does not exist.") except Exception as e: - print(f"Error: {e}") + mw.logger.log("error", f"Error: {e}") # Return the matching row or None if no match is found return matching_row diff --git a/src/Ankimon/functions/sprite_functions.py b/src/Ankimon/functions/sprite_functions.py index 1bed2b308..dfbb04646 100644 --- a/src/Ankimon/functions/sprite_functions.py +++ b/src/Ankimon/functions/sprite_functions.py @@ -1,5 +1,6 @@ from ..resources import pkmnimgfolder import os +from aqt import mw def get_sprite_path(side: str, sprite_type: str, id: int=132, shiny: bool=False, gender: str="M"): """Return the path to the sprite of the Pokémon with robust fallbacks.""" @@ -30,5 +31,5 @@ def get_sprite_path(side: str, sprite_type: str, id: int=132, shiny: bool=False, return path # 5. Fallback to the generic substitute image - print(f"Unable to find sprite for ID {id} (Shiny: {shiny}, Gender: {gender}). Returning substitute.") + mw.logger.log("warning", f"Unable to find sprite for ID {id} (Shiny: {shiny}, Gender: {gender}). Returning substitute.") return default_path diff --git a/src/Ankimon/functions/trainer_functions.py b/src/Ankimon/functions/trainer_functions.py index 343244324..a59e0b8f9 100644 --- a/src/Ankimon/functions/trainer_functions.py +++ b/src/Ankimon/functions/trainer_functions.py @@ -6,6 +6,7 @@ from .pokemon_functions import find_experience_for_level from .pokedex_functions import check_evolution_for_pokemon, return_name_for_id from aqt.utils import showInfo, showWarning +from aqt import mw def find_trainer_rank(highest_level, trainer_level): """ @@ -59,7 +60,7 @@ def find_trainer_rank(highest_level, trainer_level): return rank except FileNotFoundError: - print("Error: One of the files (Pokedex or MyPokemon) could not be found.") + mw.logger.log("error", "Error: One of the files (Pokedex or MyPokemon) could not be found.") return "Unknown Rank" def xp_share_gain_exp(logger, settings_obj, evo_window, main_pokemon_id, exp, xp_share_individual_id): diff --git a/src/Ankimon/poke_engine/ankimon_hooks_to_poke_engine.py b/src/Ankimon/poke_engine/ankimon_hooks_to_poke_engine.py index a1244b217..66932bde5 100644 --- a/src/Ankimon/poke_engine/ankimon_hooks_to_poke_engine.py +++ b/src/Ankimon/poke_engine/ankimon_hooks_to_poke_engine.py @@ -9,6 +9,7 @@ from .helpers import normalize_name from .find_state_instructions import get_all_state_instructions from ..pyobj.error_handler import show_warning_with_traceback +from aqt import mw def reset_stat_boosts(pokemon: Pokemon) -> Pokemon: """ @@ -302,7 +303,7 @@ def simulate_battle_with_poke_engine( 'state': new_state } - print(f"{unlucky_life * 100}% chance: {battle_effects}") + mw.logger.log("info", f"{unlucky_life * 100}% chance: {battle_effects}") return battle_info, new_state, dmg_from_enemy_move, dmg_from_user_move, mutator_full_reset, battle_info_changes except Exception as e: @@ -443,5 +444,5 @@ def print_state_changes(changes): key = change['key'] before = change['before'] after = change['after'] - print(f"{key}: {before} -> {after}") + mw.logger.log("info", f"{key}: {before} -> {after}") diff --git a/src/Ankimon/poke_engine/data/scripts/update_moves.py b/src/Ankimon/poke_engine/data/scripts/update_moves.py index c52698d2b..71b18ed92 100644 --- a/src/Ankimon/poke_engine/data/scripts/update_moves.py +++ b/src/Ankimon/poke_engine/data/scripts/update_moves.py @@ -3,6 +3,9 @@ import json import copy import subprocess +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') """ @@ -39,7 +42,7 @@ # exit if stderr is not empty if stderr: - print("Something went wrong? stderr: {}".format(stderr)) + logging.error("Something went wrong? stderr: {}".format(stderr)) # add a console log to the .js file. This will error if the file doesn't exist with open("/tmp/moves.js", "a") as f: diff --git a/src/Ankimon/pokedex/pokedex_obj.py b/src/Ankimon/pokedex/pokedex_obj.py index 85664340a..f9dffda01 100644 --- a/src/Ankimon/pokedex/pokedex_obj.py +++ b/src/Ankimon/pokedex/pokedex_obj.py @@ -47,11 +47,9 @@ def __init__(self, addon_dir, ankimon_tracker): def load_html(self): self.ankimon_tracker.get_ids_in_collection() self.owned_pokemon_ids = self.ankimon_tracker.owned_pokemon_ids - #print("POKEDEX_DEBUG: Caught Pokémon IDs:", self.owned_pokemon_ids) # Convert caught IDs to string str_owned_pokemon_ids = ",".join(map(str, self.owned_pokemon_ids)) if self.owned_pokemon_ids else "" - #print("POKEDEX_DEBUG: Caught IDs string:", str_owned_pokemon_ids) # Calculate defeated Pokémon count defeated_count = 0 @@ -63,12 +61,12 @@ def load_html(self): try: with open(mypokemon_path, "r", encoding="utf-8") as file: pokemon_list = json.load(file) - print("POKEDEX_DEBUG: Loaded pokemon_list!") + mw.logger.log("info", "POKEDEX_DEBUG: Loaded pokemon_list!") except json.JSONDecodeError: - print("POKEDEX_DEBUG: Invalid JSON in mypokemon.json at", mypokemon_path) + mw.logger.log("error", f"POKEDEX_DEBUG: Invalid JSON in mypokemon.json at {mypokemon_path}") except Exception as e: - print("POKEDEX_DEBUG: Error reading mypokemon.json at", mypokemon_path, ":", str(e)) + mw.logger.log("error", f"POKEDEX_DEBUG: Error reading mypokemon.json at {mypokemon_path}: {str(e)}") if pokemon_list: for pokemon in pokemon_list: @@ -76,23 +74,18 @@ def load_html(self): try: defeated_num = int(float(str(defeated))) # Handle int, float, string defeated_count += defeated_num - #print(f"POKEDEX_DEBUG: Pokemon ID {pokemon.get('id', 'unknown')}: pokemon_defeated = {defeated_num}") except (TypeError, ValueError): - print(f"POKEDEX_DEBUG: Invalid pokemon_defeated for ID {pokemon.get('id', 'unknown')}: {defeated}") + mw.logger.log("warning", f"POKEDEX_DEBUG: Invalid pokemon_defeated for ID {pokemon.get('id', 'unknown')}: {defeated}") else: - print("POKEDEX_DEBUG: No valid mypokemon.json found") - - #print("POKEDEX_DEBUG: Total defeated_count =", defeated_count) + mw.logger.log("warning", "POKEDEX_DEBUG: No valid mypokemon.json found") file_path = os.path.join(self.addon_dir, "pokedex", "pokedex.html").replace("\\", "/") - #print("POKEDEX_DEBUG: Loading HTML from:", file_path) url = QUrl.fromLocalFile(file_path) query = QUrlQuery() query.addQueryItem("numbers", str_owned_pokemon_ids) query.addQueryItem("defeated", str(defeated_count)) url.setQuery(query) - #print("POKEDEX_DEBUG: Final URL:", url.toString()) self.webview.setUrl(url) diff --git a/src/Ankimon/pyobj/collection_dialog.py b/src/Ankimon/pyobj/collection_dialog.py index 6e6734bc4..dad4810e0 100644 --- a/src/Ankimon/pyobj/collection_dialog.py +++ b/src/Ankimon/pyobj/collection_dialog.py @@ -591,7 +591,7 @@ def PokemonTradeIn(number_code, old_pokemon_name, position): "growth_rate": growth_rate, } trade_pokemon(f"{old_pokemon_name}", pokemon_trade, position) - logger.log_and_showinfo("info",f"You have sucessfully traded your {old_pokemon_name} for {name} ") + mw.logger.log_and_showinfo("info",f"You have sucessfully traded your {old_pokemon_name} for {name} ") else: showWarning("Please enter a valid Code !") @@ -602,10 +602,10 @@ def trade_pokemon(old_pokemon_name, pokemon_trade, position): with open(mypokemon_path, "r", encoding="utf-8") as file: pokemon_list = json.load(file) except FileNotFoundError: - print("The Pokemon file was not found. Please check the file path.") + mw.logger.log_and_showinfo("error", "The Pokemon file was not found. Please check the file path.") return except json.JSONDecodeError as e: - print(f"Error decoding JSON: {e}") + mw.logger.log_and_showinfo("error", f"Error decoding JSON: {e}") return # Find and replace the specific Pokemon's information diff --git a/src/Ankimon/pyobj/data_handler.py b/src/Ankimon/pyobj/data_handler.py index 2a9a39f47..ab3616543 100644 --- a/src/Ankimon/pyobj/data_handler.py +++ b/src/Ankimon/pyobj/data_handler.py @@ -26,7 +26,8 @@ } class DataHandler: - def __init__(self): + def __init__(self, logger): + self.logger = logger self.new_values = new_values self.path = user_path # Store the provided path self.data = {} # Store any potential errors or file read issues @@ -59,7 +60,7 @@ def read_files(self): if isinstance(entry, dict): valid_content.append(entry) else: - print(f"Skipping invalid entry in {file}: {entry}") + self.logger.log("warning", f"Skipping invalid entry in {file}: {entry}") setattr(self, attr_name, valid_content) else: setattr(self, attr_name, content) @@ -78,7 +79,7 @@ def assign_unique_ids(self, pokemon_list): unique_ids = set() for idx, entry in enumerate(pokemon_list): if not isinstance(entry, dict): - print(f"Skipping invalid entry at index {idx} - not a dictionary") + self.logger.log("warning", f"Skipping invalid entry at index {idx} - not a dictionary") continue try: unique_ids = set(pokemon.get("individual_id") for pokemon in pokemon_list if "individual_id" in pokemon) @@ -97,7 +98,7 @@ def assign_unique_ids(self, pokemon_list): unique_ids.add(new_id) break except: - print("Unique ID assignment failed") + self.logger.log("error", "Unique ID assignment failed") def assign_new_variables(self, pokemon_list): """ diff --git a/src/Ankimon/pyobj/settings.py b/src/Ankimon/pyobj/settings.py index 088646cd9..4fc8306ff 100644 --- a/src/Ankimon/pyobj/settings.py +++ b/src/Ankimon/pyobj/settings.py @@ -67,7 +67,8 @@ } class Settings: - def __init__(self): + def __init__(self, logger): + self.logger = logger self.config = self.load_config() self.compute_gui_config() @@ -94,7 +95,7 @@ def load_config(self): with open(items_path, 'w', encoding='utf-8') as f: json.dump(config["items"], f, indent=4) except Exception as e: - print(f"Ankimon: Error migrating 'items' data during load_config: {e}") + self.logger.log("error", f"Ankimon: Error migrating 'items' data during load_config: {e}") del config["items"] if "trainer.team" in config: @@ -113,10 +114,10 @@ def load_config(self): try: config[key] = int(config[key]) except ValueError: - print(f"Ankimon: Warning: Could not convert '{config[key]}' for key '{key}' to int. Keeping as string.") + self.logger.log("warning", f"Ankimon: Warning: Could not convert '{config[key]}' for key '{key}' to int. Keeping as string.") except Exception as e: - print(f"Ankimon: Error loading config from config.obf: {e}. Falling back to default config.") + self.logger.log("error", f"Ankimon: Error loading config from config.obf: {e}. Falling back to default config.") config = {} # Fallback to default if error occurs modified = False @@ -143,7 +144,7 @@ def save_config(self, config): with open(obfuscated_config_path, 'w', encoding='utf-8') as f: f.write(file_content) except Exception as e: - print(f"Ankimon: Could not save obfuscated config: {e}") + self.logger.log("error", f"Ankimon: Could not save obfuscated config: {e}") def get(self, key): return self.config.get(key) diff --git a/src/Ankimon/pyobj/trainer_card.py b/src/Ankimon/pyobj/trainer_card.py index d06d21016..5127f37d2 100644 --- a/src/Ankimon/pyobj/trainer_card.py +++ b/src/Ankimon/pyobj/trainer_card.py @@ -76,10 +76,10 @@ def get_highest_level_pokemon(self): highest_pokemon = max(pokemon_data, key=lambda p: p.get("level", 0)) return f"{highest_pokemon.get('name', 'None')} (Level {highest_pokemon.get('level', 0)})" except FileNotFoundError: - showInfo(f"File not found: {mypokemon_path}") + self.logger.log_and_showinfo("error", f"File not found: {mypokemon_path}") return "None" except json.JSONDecodeError: - showInfo(f"Error decoding JSON from file: {mypokemon_path}") + self.logger.log_and_showinfo("error", f"Error decoding JSON from file: {mypokemon_path}") return "None" def highest_pokemon_level(self): @@ -96,10 +96,10 @@ def highest_pokemon_level(self): highest_pokemon = max(pokemon_data, key=lambda p: p.get("level", 0)) return int(highest_pokemon.get('level', 0)) except FileNotFoundError: - showInfo(f"File not found: {mypokemon_path}") + self.logger.log_and_showinfo("error", f"File not found: {mypokemon_path}") return int(0) except json.JSONDecodeError: - showInfo(f"Error decoding JSON from file: {mypokemon_path}") + self.logger.log_and_showinfo("error", f"Error decoding JSON from file: {mypokemon_path}") return int(0) def add_achievement(self, achievement): @@ -140,7 +140,7 @@ def gain_xp(self, tier, allow_to_choose_move=False): if allow_to_choose_move is True: xp_gained = xp_gained * 0.5 self.xp += xp_gained - print(f"Gained {xp_gained} XP from defeating a {tier} Pokémon!") + self.logger.log("info", f"Gained {xp_gained} XP from defeating a {tier} Pokémon!") self.check_level_up() def check_level_up(self): diff --git a/src/Ankimon/singletons.py b/src/Ankimon/singletons.py index c9f2958a3..41ec29c5b 100644 --- a/src/Ankimon/singletons.py +++ b/src/Ankimon/singletons.py @@ -53,7 +53,7 @@ logger = ShowInfoLogger() # Create the Settings object -settings_obj = Settings() +settings_obj = Settings(logger) # Pass the correct attributes to SettingsWindow settings_window = SettingsWindow( @@ -151,7 +151,7 @@ achievement_bag = AchievementWindow() -data_handler_obj = DataHandler() +data_handler_obj = DataHandler(logger) data_handler_window = DataHandlerWindow(data_handler = data_handler_obj) # Initialize the Pokémon Shop Manager diff --git a/src/Ankimon/utils.py b/src/Ankimon/utils.py index 025593cf2..a21ec15fe 100644 --- a/src/Ankimon/utils.py +++ b/src/Ankimon/utils.py @@ -511,7 +511,7 @@ def count_items_and_rewrite(file_path): with open(file_path, "w", encoding="utf-8") as f: json.dump(updated_items, f, indent=4, ensure_ascii=False) - print("items.json has been updated with aggregated quantities!") + mw.logger.log("info", "items.json has been updated with aggregated quantities!") except Exception as e: show_warning_with_traceback(exception=e, message=f"An unexpected error occurred: {e}") @@ -586,7 +586,7 @@ def get_all_sprites(directory): ] return sprite_names except FileNotFoundError: - print(f"Error: The directory '{directory}' does not exist.") + mw.logger.log("error", f"Error: The directory '{directory}' does not exist.") return [] def play_effect_sound(settings_obj, sound_type):