from __future__ import annotations import math import os import pathlib import re import sys from contextlib import nullcontext from functools import partial from typing import TYPE_CHECKING, Any import psutil from alive_progress import alive_bar import modules.constants as const if TYPE_CHECKING: from modules.config.config import Config from modules.dat.parse_dat import TitleData from modules.input import UserInput from modules.clone_lists.clone_list import CloneList from modules.dat.parse_dat import get_clrmamepro_titles, get_dat_header, get_logiqx_titles from modules.interruptible_pool import InterruptiblePool from modules.titletools import Regex, TitleTools from modules.utils import ExitRetool, Font, eprint, format_value, pattern2string, regex_test class Dat: def __init__( self, is_clrmamepro: bool = False, clrmamepro_category: str = '', header: list[str] | None = None, name: str = 'Unknown', description: str = 'Unknown', version: str = 'Unknown', author: str = 'Unknown', homepage: str = 'Unknown', url: str = 'Unknown', comment: str = 'Unknown', numbered: bool = False, end: bool = False, output_filename: str = '', ) -> None: """ Creates an object that contains an input DAT's details. Interactively browsable if you `print()` the object. Args: is_clrmamepro (bool): Whether the DAT file is in CLRMAMEPro format. clrmamepro_category (str): The category to apply to CLRMAMEPro title entries. header (list[str], optional): The original DAT header. Defaults to `None`. name (str, optional): The name in the DAT header. Defaults to `Unknown`. description (str, optional): The description in the DAT header. Defaults to `Unknown`. version (str, optional): The version in the DAT header. Defaults to `Unknown`. author (str, optional): The author in the DAT header. Defaults to `Unknown`. homepage (str, optional): The homepage in the DAT header. Defaults to `Unknown`. url (str, optional): The URL in the DAT header. Defaults to `Unknown`. comment (str, optional): The comment in the DAT header. Defaults to `Unknown`. numbered (bool, optional): Whether the DAT's titles are prefixed with a number. Defaults to `False`. end (bool, optional): If something goes wrong during batch processing, Retool sets this to `True`, which allows it to move onto the next file in the batch. Defaults to `False`. output_filename (str, optional): Stores the name of the output file generated by Retool. Defaults to `''`. """ self.name: str = name self.original_header: list[str] = header if header is not None else [] self.output_filename: str = output_filename self.description: str = description self.version: str = version self.author: str = author self.homepage: str = homepage self.url: str = url self.comment: str = comment self.dat_manager_directives: list[str] = [] self.datafile_tag = '' self.numbered: bool = numbered self.is_clrmamepro: bool = is_clrmamepro self.clrmamepro_category: str = clrmamepro_category self.search_name: str = '' self.retool: str = '' self.end: bool = end def __str__(self) -> str: return_attributes: list[list[str]] = [] for attribute in dir(self): if not attribute.startswith('__'): if len(str(getattr(self, attribute))) > 80: return_attributes.append( [ f' ├ .{attribute}:', f'(...) {format_value(str(type(getattr(self, attribute)).__name__))}', ] ) else: return_attributes.append( [f' ├ .{attribute}:', format_value(getattr(self, attribute))] ) final_item: list[str] = return_attributes[-1].copy() for i, s in enumerate(final_item): return_attributes[-1][i] = s.replace('├', '└') # Column alignment def class_output() -> None: eprint('\n ○ Dat object') col_width: int = max(len(word) for row in return_attributes for word in row) - 20 for row in return_attributes: eprint(''.join(str(word).ljust(col_width) for word in row), wrap=False) key: str = 'blank' class_output() while key != 'q': eprint( '\nEnter a dictionary key to expand (e.g. tags_disc_rename), q to continue, or hit enter to list: ', indent=0, ) key = input() if hasattr(self, key): if isinstance(getattr(self, key), CloneList | Regex): eprint(f'\n{vars(getattr(self, key))}', wrap=False) else: eprint(f'\n{format_value(getattr(self, key))}', wrap=False) elif key == '': class_output() else: if key != 'q': eprint(f'\nUnknown key "{key}".', wrap=False) else: break return '' class DatNode: def __init__( self, config: Config, input_dat: Dat, metadata: dict[str, dict[str, str]], node: TitleData ) -> None: """ Creates an object that contains all of a title's properties. If you `print()` a DatNode object, it shows you a tree-like view of all its contents. Args: config (Config): The Retool config object. input_dat (Dat): The Retool input_dat object. metadata (dict[str, dict[str, str]], optional): Metadata related to the DAT, that contains languages for each of the titles scraped from No-Intro and Redump's sites. Defaults to `None`. node (TitleData): A dict created from a title's element in the DAT file, containing information like name, category, description and ROMs if present. """ # Set the XML tag name self.tag_name: str = node.tag_name # Set full/numbered title names self.full_name: str = '' self.full_name_original: str = '' self.numbered_name: str = '' self.local_name: str = '' if not input_dat.numbered: self.full_name = node.name else: self.full_name = node.name[7:] self.numbered_name = node.name self.full_name = TitleTools.replace_invalid_characters( self.full_name, config, is_header_detail=False ) self.full_name_original = self.full_name # Get the tags from the title name self.tags: set[str] = set([f'({x}' for x in self.full_name.split(' (')][1:None]) # Set unrecognized attributes and children from the element self.tag_attribs: dict[str, str] = node.tag_attribs self.unrecognized_children: list[str] = node.unrecognized_children # Set languages and regions self.languages_implied: tuple[str, ...] = () self.languages_online: tuple[str, ...] = () self.languages_title: tuple[str, ...] = () self.languages: tuple[str, ...] = () self.languages_original: tuple[str, ...] = () self.regions: tuple[str, ...] = () self.primary_region: str = '' self.primary_region_original: str = '' self.secondary_region: str = '' if self.full_name in metadata: if not metadata[self.full_name]['languages']: self.languages_online = () else: self.languages_online = tuple(sorted(metadata[self.full_name]['languages'])) self.languages_title_str: str = TitleTools.languages( self.full_name, self.tags, config, 'get' ) self.languages_title_orig_str: str = self.languages_title_str if '+' in self.languages_title_str: self.languages_title_str = self.languages_title_str.replace('+', ',') if self.languages_title_str: self.languages_title = tuple(sorted(set(self.languages_title_str.split(',')))) self.regions_str: str = TitleTools.regions(self.full_name, config, 'get') regions: list[str] = list(config.region_order_default) self.regions = tuple([region for region in regions if region in self.regions_str]) if not self.regions: self.regions = ('Unknown',) self.primary_region = self.regions[0] self.primary_region_original = self.primary_region # Get the primary region based on the region order region_order: list[str] = config.region_order_user if config.system_region_order_user: if {'override': 'true'} in config.system_region_order_user: region_order = [ str(x) for x in config.system_region_order_user if 'override' not in x ] if len(self.regions) > 1: for region in region_order: if region in self.regions: self.primary_region = region break if not self.primary_region: self.primary_region = self.regions[0] if len(self.regions) > 1: self.secondary_region = [x for x in self.regions if x not in [self.primary_region]][0] if self.primary_region in config.languages_implied: self.languages_implied = config.languages_implied[self.primary_region] # Set the canonical supported languages for the title if self.languages_online: if self.languages_online != ('nolang',): self.languages = self.languages_online else: self.languages_online = () if not self.languages_online and not self.languages_title: self.languages = self.languages_implied if not self.languages_online and self.languages_title: self.languages = self.languages_title self.languages_original = self.languages # If the language code for the title is just Zh, try to infer whether simplified # or traditional Chinese is being used if 'Zh' in self.languages: if 'China' in self.regions or 'Singapore' in self.regions: self.languages = tuple([x.replace('Zh', 'Zh-Hans') for x in self.languages]) elif 'Hong Kong' in self.regions or 'Taiwan' in self.regions: self.languages = tuple([x.replace('Zh', 'Zh-Hant') for x in self.languages]) # Set various names used for title matching -- for speed, we don't use all of the # built-in name conversion functions, as they generate the names from scratch # which requires extra work regions_replace: str = f' ({self.regions_str})' languages_replace: str = f' ({self.languages_title_orig_str})' self.short_name: str = TitleTools.get_short_name(self.full_name, self.tags, config) self.region_free_name: str = self.full_name.replace(languages_replace, '').replace( regions_replace, '' ) self.short_name_original: str = self.short_name self.group_name: str = TitleTools.get_group_name(self.full_name, config) self.group_name_conditional: str = '' # Set an indicator if the title has been moved using a clone list condition self.group_moved_by_condition: bool = False # Pull local names from metadata metadata_local_language: str = '' if self.full_name in metadata: if 'localName' in metadata[self.full_name]: # Check if a system config is in play local_name_user_order_language_codes: list[str] = [] if config.system_localization_order_user: if {'override': 'true'} in config.system_localization_order_user: local_name_user_order_language_codes = [ str(x) for x in config.system_localization_order_user if 'override' not in x ] elif config.localization_order_user: local_name_user_order_language_codes = list(config.localization_order_user) # Get the inferred language from the primary region if self.primary_region in config.languages_filter: if config.languages_filter[self.primary_region]: metadata_local_language = config.languages_filter[self.primary_region][0] # Make sure the alternate name is only applied if the title only has one or # two languages, and don't change the title if the only language is English if len(self.languages) <= 2 and self.languages != ('En',): if metadata_local_language in local_name_user_order_language_codes: self.local_name = metadata[self.full_name]['localName'] # Re-add the tags to the local name where appropriate if self.local_name: tags = pattern2string(re.compile(' \\(.*'), self.full_name) self.local_name = f'{self.local_name}{tags}' # Populate the description and rom fields if node.description: self.description: str = node.description else: self.description = '' if node.files: self.roms: list[dict[str, str]] = node.files rom_attributes: list[str] = [ 'name', 'crc', 'header', 'mia', 'md5', 'sha1', 'sha256', 'size', ] for attribute in rom_attributes: self.roms = process_roms(self.roms, attribute, self.full_name) self.cloneof: str = '' self.clonelist_priority: int = 1 self.is_mia: bool = False self.is_retroachievement: bool = False self.is_oldest: bool = False self.is_superset: bool = False self.contains_titles: dict[str, dict[str, int]] = {} # Determine if a title is fully MIA if '[MIA]' in self.full_name or len([x for x in self.roms if x['mia'] == 'yes']) == len( self.roms ): self.is_mia = True # Work with categories self.categories: list[str] = [] if node.categories: for category in node.categories: if category == 'Console': self.categories.append('BIOS') else: self.categories.append(category) self.categories = category_assign( self.full_name, self.categories, config.regex.addons, 'Add-Ons' ) self.categories = category_assign( self.full_name, self.categories, (config.regex.programs,), 'Applications' ) self.categories = category_assign( self.full_name, self.categories, (config.regex.audio,), 'Audio' ) self.categories = category_assign( self.full_name, self.categories, (config.regex.bios,), 'BIOS' ) self.categories = category_assign( self.full_name, self.categories, config.regex.demos, 'Demos' ) self.categories = category_assign( self.full_name, self.categories, (config.regex.multimedia,), 'Multimedia' ) self.categories = category_assign( self.full_name, self.categories, config.regex.preproduction, 'Preproduction' ) self.categories = category_assign( self.full_name, self.categories, config.regex.video, 'Video' ) if '[bios]' in self.full_name.lower(): if 'BIOS' not in self.categories: self.categories.append('BIOS') elif self.categories == []: self.categories.append('Games') # Check if the title should be tagged as a demo self.is_demo: bool = False for demo_regex in config.regex.demos: if re.search(demo_regex, self.full_name) or 'Demos' in self.categories: self.is_demo = True self.short_name = self.short_name.lower() # Add a reason why a title was excluded/included, and if its related titles should # also be excluded/included by Retool self.exclude_reason: str = '' self.include_reason: str = '' self.exclude_include_related: bool = False # Assign user language and region priority region_priority: set[int] = set() language_priority: set[int] = set() # Check if a system config is in play language_order: list[str] = [] if config.languages_filter: language_order = config.language_order_user if config.system_language_order_user: if {'override': 'true'} in config.system_language_order_user: language_order = [ str(x) for x in config.system_language_order_user if 'override' not in x ] else: language_order = config.region_order_languages_user for i, region in enumerate(region_order): if region in self.regions: region_priority.add(i) for j, language_code in enumerate(language_order): for language in self.languages: if re.search(language_code, language): language_priority.add(j) if not region_priority: region_priority.add(100) if not language_priority: language_priority.add(100) self.region_priority: int = sorted(region_priority)[0] self.language_priority: int = sorted(language_priority)[0] self.normalized_version: dict[str, str | bool] = TitleTools.get_normalized_version( self.full_name, config ) def __str__(self) -> str: return_list: list[str] = [] return_list.append(f' ○ full_name:\t\t\t{self.full_name}\n') return_list.append(format_attribute(self.numbered_name, 'numbered_name', '\t\t')) return_list.append(format_attribute(self.local_name, 'local_name', '\t\t\t')) return_list.append(format_attribute(self.description, 'description', '\t\t')) return_list.append(f' ├ region_free_name:\t\t{self.region_free_name}\n') return_list.append(f' ├ short_name:\t\t\t{self.short_name}\n') return_list.append(f' ├ group_name:\t\t\t{self.group_name}\n') return_list.append(f' ├ group_moved_by_condition:\t{self.group_moved_by_condition}\n') return_list.append(format_attribute(self.tags, 'tags', '\t\t\t')) return_list.append(f' ├ regions:\t\t\t{self.regions}\n') return_list.append(f' ├ primary_region:\t\t{self.primary_region}\n') return_list.append(format_attribute(self.secondary_region, 'secondary_region', '\t\t')) return_list.append( format_attribute(self.languages_title_orig_str, 'languages_title_orig_str', '\t') ) return_list.append(format_attribute(self.languages_title, 'languages_title', '\t\t')) return_list.append(format_attribute(self.languages_implied, 'languages_implied', '\t\t')) return_list.append(format_attribute(self.languages_online, 'languages_online', '\t\t')) return_list.append(format_attribute(self.languages, 'languages', '\t\t\t')) return_list.append(format_attribute(self.normalized_version, 'normalized_version', '\t')) return_list.append(format_attribute(self.cloneof, 'cloneof', '\t\t\t')) return_list.append(format_attribute(self.is_demo, 'is_demo', '\t\t\t')) return_list.append(format_attribute(self.is_mia, 'is_mia', '\t\t\t')) return_list.append(format_attribute(self.is_oldest, 'is_oldest', '\t\t\t')) return_list.append(format_attribute(self.is_retroachievement, 'is_retroachievement', '\t')) return_list.append(format_attribute(self.is_superset, 'is_superset', '\t\t')) return_list.append(format_attribute(self.contains_titles, 'contains_titles', '\t\t')) return_list.append(format_attribute(self.clonelist_priority, 'clonelist_priority', '\t\t')) return_list.append(format_attribute(self.region_priority, 'region_priority', '\t\t')) return_list.append(format_attribute(self.language_priority, 'language_priority', '\t\t')) return_list.append(format_attribute(self.exclude_reason, 'exclude_reason', '\t\t')) return_list.append(format_attribute(self.include_reason, 'include_reason', '\t\t')) return_list.append( format_attribute(self.exclude_include_related, 'exclude_include_related', '\t') ) return_list.append(f' ├ categories:\t\t\t{self.categories}\n') return_list.append(' └ roms ┐ \n') for i, rom in enumerate(self.roms): if i == len(self.roms) - 1: return_list.append( f' └ name: {rom["name"]} | {format_attribute(rom["header"], "header", "", is_rom=True)} | {format_attribute(rom["mia"], "mia", "", is_rom=True)} | crc: {rom["crc"]} | md5: {rom["md5"]} | sha1: {rom["sha1"]} | {format_attribute(rom["sha256"], "sha256", "", is_rom=True)} | size: {rom["size"]}\n\n' ) else: return_list.append( f' ├ name: {rom["name"]} | {format_attribute(rom["header"], "header", "", is_rom=True)} | {format_attribute(rom["mia"], "mia", "", is_rom=True)} | crc: {rom["crc"]} | md5: {rom["md5"]} | sha1: {rom["sha1"]} | {format_attribute(rom["sha256"], "sha256", "", is_rom=True)} | size: {rom["size"]}\n' ) return_str: str = ''.join(return_list) return return_str def category_assign( full_name: str, categories: list[str], regexes: tuple[Any, ...], category: str ) -> list[str]: """ Assigns a category to a title based on a regex match in its name. Args: full_name (str): The full name of a title. regexes (tuple[Any, ...]): A collection of regexes to iterate through. categories (list[str]): The categories list from a title. regexes (tuple[Any, ...]): The regexes to match against a title name to derive a category. category (str): The category to assign to the title if a regex matches. """ for item in regexes: if re.search(item, full_name): if category not in categories: categories.append(category) return categories def format_attribute(attribute: Any, string: str, tabs: str, is_rom: bool = False) -> str: """ Formats an output string based on whether an attribute in the title object has a value, or if its value contains ROMs. Args: attribute (Any): The DatNode attribute. string (str): The name of the attribute to use in the output string. tabs (str): Tab indentation for the output string. is_rom (bool, optional): Whether the output string should be formatted for ROM data. Defaults to `False`. Returns: str: A formatted output string based on whether an attribute has a value or not, or if its value contains ROMs. """ none_str: str = f'{Font.disabled}None{Font.end}' attribute_result: str = '' if not attribute: if not isinstance(attribute, int | bool): attribute = none_str if is_rom: attribute_result = f'{string}: {attribute}' else: attribute_result = f' ├ {string}:{tabs}{attribute}\n' return attribute_result def process_dat( dat_file: str, input_type: str, gui_input: UserInput | None, config: Config ) -> tuple[Dat, CloneList, dict[str, set[DatNode]]]: """ Reads in an input DAT file and prepares the data for use in Retool. Also imports system configs, including the related clone list and metadata file. Args: dat_file (str): The DAT file being processed. input_type (str): Whether Retool is operating on a file or folder. gui_input (UserInput): Used to determine if the function is being called from the GUI. config (Config): The Retool config object. Raises: ExitRetool: Silently exit if run from the GUI, so UI elements can re-enable. Returns: Dat: A Dat object created from the input DAT file, so Retool can work on the data efficiently. """ # Set a string for skipping to the next file if something goes wrong in a batch # operation if input_type != 'file': next_status: str = ' Skipping file...' else: next_status = '' # Import the DAT file eprint(f'• Reading DAT file: "{Font.b}{pathlib.Path(dat_file).resolve()}{Font.be}"') input_dat: Dat = Dat() # Check the DAT format by parsing the header eprint('• Checking DAT file format... ') try: input_dat = get_dat_header(pathlib.Path(dat_file), input_dat, config, gui_input) except OSError as e: eprint(f'• {Font.b}Error{Font.be}: {e!s}.{next_status}', level='error') if input_type == 'file': raise else: input_dat.end = True return (input_dat, CloneList(), {}) # Exit if no header is found, as it's likely an invalid input file if input_dat.end: eprint( f'• {Font.b}"{dat_file}"{Font.be} isn\'t a compatible DAT file.{next_status}', level='error', ) if input_type == 'file': if gui_input: raise ExitRetool else: sys.exit(1) else: return (input_dat, CloneList(), {}) # Import system settings from modules.input import import_clone_list_mia_ra, import_metadata, import_system_settings import_system_settings( config, input_dat.search_name, const.SYSTEM_LANGUAGE_ORDER_KEY, const.SYSTEM_REGION_ORDER_KEY, const.SYSTEM_LOCALIZATION_ORDER_KEY, const.SYSTEM_VIDEO_ORDER_KEY, const.SYSTEM_LIST_PREFIX_KEY, const.SYSTEM_LIST_SUFFIX_KEY, const.SYSTEM_OVERRIDE_EXCLUDE_KEY, const.SYSTEM_OVERRIDE_INCLUDE_KEY, const.SYSTEM_FILTER_KEY, const.SYSTEM_EXCLUSIONS_OPTIONS_KEY, ) # If the DAT file has been processed before, exit if input_dat.retool and not config.user_input.reprocess_dat: eprint( '• Skipping file as it\'s already been processed by Retool. You can allow ' f'this with the {Font.b}--reprocess{Font.be} flag, or in the Retool GUI ' f'go to {Font.b}Options > Output options{Font.be} and enable ' f'{Font.b}Allow processing of already processed files{Font.be}.' ) if input_type == 'file': if gui_input: raise ExitRetool else: sys.exit(0) else: input_dat.end = True return (input_dat, CloneList(), {}) # Provide DAT file details to reassure the user that the correct file is being # processed eprint() eprint(f'{Font.b}DAT DETAILS{Font.be}', section=True) eprint(f'Description: {input_dat.description}', indent=2, section=True, wrap=False) eprint(f'Author/s: {input_dat.author}', indent=14, section=True) eprint(f'URL: {input_dat.url}', indent=2, section=True) eprint(f'Version: {input_dat.version}\n', indent=2, section=True) # Process the titles eprint('• Reading DAT file...') if input_dat.is_clrmamepro: titles = get_clrmamepro_titles(pathlib.Path(dat_file), input_dat) else: titles = get_logiqx_titles(pathlib.Path(dat_file), ('game', 'machine')) # Under Windows, adjust the number of processes to use based on the number # of titles in the DAT file. This is because the cost of starting up a # process under Windows in Python is significantly higher than Linux if sys.platform.startswith('win'): magic_number: float = 0.001 processes: int = int(math.sqrt(len(titles) * magic_number)) if processes == 0: processes = 1 elif processes != 1: # This seems to be a good approximate for ideal performance compared to # manual benchmarking processes = processes + 6 # Cap to the maximum number of processes to the number of CPU cores if processes > config.cpu_count: processes = config.cpu_count config.cpu_count = processes if config.cpu_count == 1: config.user_input.single_cpu = True eprint('• Reading DAT file... done.', overwrite=True) # Check if the DAT is numbered if 'no-intro' in input_dat.url.lower(): input_dat.numbered = True for dat_title in titles: if not re.search('^([0-9]|x|z)([0-9]|B)[0-9]{2,2} - ', dat_title.name): input_dat.numbered = False numbered_dat: str = ['No', 'Yes'][input_dat.numbered] eprint(f'• Numbered dat detected: {numbered_dat}', indent=3) # If no titles are found, exit if not titles: eprint( f'• {Font.b}Error{Font.be}: {Font.b}"{dat_file}"{Font.be}. No valid ' f'titles in input DAT file. Titles must have at least a size or ' f'one digest.{next_status}', level='error', ) if input_type == 'file': if gui_input: raise ExitRetool else: sys.exit(1) else: input_dat.end = True return (input_dat, CloneList(), {}) # Check all the overrides and post filters for invalid regex and strip it out if not config.user_input.no_overrides: config.global_exclude = regex_test( list(config.global_exclude), 'global exclude', 'user filter' ) config.global_include = regex_test( list(config.global_include), 'global include', 'user filter' ) config.system_exclude = regex_test( list(config.system_exclude), 'system exclude', 'user filter' ) config.system_include = regex_test( list(config.system_include), 'system include', 'user filter' ) if config.global_filter: config.global_filter = regex_test( list(config.global_filter), 'global post filter', 'user filter' ) if config.system_filter: override_status: list[str | dict[str, str]] = [ x for x in config.system_filter if x == {'override': 'true'} or x == {'override': 'false'} ] regex_test_system_filter: list[str] = regex_test( [ str(x) for x in config.system_filter if x != {'override': 'true'} and x != {'override': 'false'} ], 'system post filter', 'user filter', ) config.system_filter = override_status for regex in regex_test_system_filter: config.system_filter.append(regex) # Import the clone list clone_list: CloneList = import_clone_list_mia_ra(input_dat, gui_input, config) # Import the metadata file metadata = import_metadata(input_dat, config) # Process the DAT file if config.user_input.single_cpu: alive_bar_context = nullcontext() eprint('• Processing DAT file...') else: progress_bar: str = 'smooth' spinner: str = 'waves' parent_processes: list[str] = [ str(x).lower() for x in psutil.Process(os.getpid()).parents() ] if any( s for s in parent_processes if 'cmd.exe' in s or 'powershell.exe' in s or 'explorer.exe' in s ): if not any( s for s in parent_processes if 'code.exe' in s or 'windowsterminal.exe' in s ): progress_bar = 'classic2' spinner = 'classic' alive_bar_context = alive_bar( total=len(titles), title='• Processing DAT file', length=20, enrich_print=False, stats=False, monitor='{percent:.2%}', receipt_text=True, bar=progress_bar, spinner=spinner, file=sys.stderr, ) # Define DatNode as the function to run on multiple processors, and use a partial to # prepush arg values into it as a sort of prepackaged function so we can use it in a # map later func = partial(DatNode, config, input_dat, metadata) # Multiprocessing to speed up DatNode creation process_list: list[DatNode] = [] if config.user_input.single_cpu: process_list = list(map(func, titles)) else: chunk_size: int = int(len(titles) / config.cpu_count) chunk_size = chunk_size if chunk_size >= 1 else 1 with alive_bar_context as bar, InterruptiblePool(config.cpu_count) as p: for result in p.imap_unordered(func, titles, chunksize=chunk_size): process_list.append(result) if bar: bar() # Check there isn't a duplicate title or name in the group, as No-Intro doesn't check # for these things original_titles: dict[str, set[DatNode]] = {} duplicate_titles: set[DatNode] = set() duplicate_names: set[str] = set() for title in process_list: if title.group_name not in original_titles: original_titles[title.group_name] = set() for original_title in original_titles[title.group_name]: if original_title.full_name == title.full_name: # Check first if the entire title is duplicated, use the # node a proxy if original_title.roms == title.roms: duplicate_titles.add(title) continue # Rename files with the same filename. First, get the current dupe # number. dupe_number: int = 0 if re.search(' \\(Dupe \\d+\\)', title.full_name): dupe_string: str = pattern2string( re.compile(' \\(Dupe \\d+\\)'), title.full_name ) dupe_number = int(pattern2string(re.compile('\\d+'), dupe_string)) + 1 title.full_name = re.sub(' \\(Dupe \\d+\\)', '', title.full_name) title.description = re.sub(' \\(Dupe \\d+\\)', '', title.description) title.short_name = re.sub(' \\(Dupe \\d+\\)', '', title.short_name) title.region_free_name = re.sub(' \\(Dupe \\d+\\)', '', title.region_free_name) else: dupe_number += 1 before_rename: str = title.full_name title.full_name = f'{title.full_name} (Dupe {dupe_number})' title.description = f'{title.description} (Dupe {dupe_number})' title.short_name = f'{title.short_name} (Dupe {dupe_number})' title.region_free_name = f'{title.region_free_name} (Dupe {dupe_number})' if f'{before_rename} > {title.full_name}' not in duplicate_names: duplicate_names.add( f'{Font.warning_bold}{before_rename}{Font.warning} -> {Font.warning_bold}{title.full_name}{Font.warning}' ) original_titles[title.group_name].add(title) # Remove duplicate titles for title in duplicate_titles: if title in process_list: config.stats.duplicate_titles_count += 1 process_list.remove(title) if title in original_titles[title.group_name]: original_titles[title.group_name].remove(title) if duplicate_names: eprint( '• The following titles with identical names were found in ' 'the input DAT file, and will be renamed. They won\'t be processed as ' 'clones:\n', level='warning', ) for duplicate_title in sorted(duplicate_names): eprint(f' • {duplicate_title}', level='warning', wrap=False) eprint(f'{Font.end}') eprint('• Processing DAT file... done.', overwrite=True) return (input_dat, clone_list, original_titles) def process_roms( roms: list[dict[str, str]], attribute: str, full_name: str ) -> list[dict[str, str]]: """ Checks that the various ROM attributes are available for a given title, and formats them accordingly. Additionally marks ROMs as MIA where necessary. Args: attribute (str): The attribute to format, either `crc`, `md5`, `sha1`, `sha256`, or `header`. full_name (str): The full name of the ROM. roms (list[dict[str, str]]): The ROMs from the title. """ for rom in roms: if attribute not in rom: rom[attribute] = '' # Format digests with lower case if ( attribute == 'crc' or attribute == 'md5' or attribute == 'sha1' or attribute == 'sha256' or attribute == 'header' ): rom[attribute] = rom[attribute].lower() # Mark ROMs as MIA if the title is marked as MIA if '[MIA]' in full_name: rom['mia'] = 'yes' return roms