import csv import os import glob import re from datetime import datetime SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(SCRIPT_DIR) TARGET_DIR = os.path.join(BASE_DIR, "TABLEDUMPS") OUTPUT_FILE = os.path.join(BASE_DIR, "uniqueobjects.txt") FIRST_INTRO_OUTPUT_FILE = os.path.join(BASE_DIR, "uuidfirstintroduced.txt") DEBUG_UUID_LOG_FILE = os.path.join(BASE_DIR, "debug.log") DEBUG_UUID_LOG_ENABLED = False DEBUG_UUIDS = { "C080CDE0-DE51455D-BF85BC62-EF65634A", "0BB99D3D-11BD4A6C-9F1300E3-3A8E2592", "CAFEF00D-BEEFF00D-FEEDBEEF-000010A2", } BUILD_MATCHES = { "Env_SCEA-Dusty_2": "DEV", "Env_HDK_CDEVC-PixelButts": "DEV", "Env_HDK-SingstarDev": "DEV", "Env_LBP-imagisphere": "DEV", "Env_SingStar-SingStarDev": "DEV", "Env_SingStar-bowzark": "DEV", "Env_SCEASDFPQA-Spouts": "DEV", "Env_scea989-Spounts": "DEV", "Env_KungFuFactorydba-PixelButts": "DEV", "Env_homecoretest-Soul 1": "DEV", "Env_veemeescee-QuantumDoja2": "DEV", "Env_veemeetovss-Soul 4 DECH2500": "DEV", "cqa-a-Soul 3": "DEV", "cqa-a-Viciousest": "DEV", "cpreprod-QuantumDoja1": "DEV", "cqa-e-QuantumDoja": "DEV", "cqa-e-Soul 3": "DEV", "ObjectCatalogue_5_SCEA_2012-11-12": "BETA", "ObjectCatalogue_5_SCEE_2012-11-12": "BETA", } OUTPUT_FIELDS = [ "UUID_TXXX", "ObjectId", "Version", "Build", ] FIRST_INTRO_BASE_OUTPUT_FIELDS = [ "UUID", "First Date Introduced", "Last Date Removed", ] READDED_FIELD_NAME = "Removed Date->Added Back Date" def get_build_from_file_path(file_path): path_text = file_path.replace("\\", "/").lower() for text, build in BUILD_MATCHES.items(): if text.lower() in path_text: return build return "RETAIL" def version_num(value): try: return int(str(value).strip()) except: return -1 def build_rank(build): if build == "RETAIL": return 0 if build == "BETA": return 1 return 2 def should_replace_existing(old_row, new_row): old_rank = build_rank(old_row["Build"]) new_rank = build_rank(new_row["Build"]) if new_rank < old_rank: return True if new_rank > old_rank: return False return version_num(new_row["Version"]) > version_num(old_row["Version"]) def clean_fieldnames(fieldnames): return [ h.strip().replace("\ufeff", "") for h in fieldnames ] def parse_catalogue_date_from_filename(file_path): filename = os.path.basename(file_path) m = re.match( r"^ObjectCatalogue_5_[^_]+_(\d{4}-\d{2}-\d{2})(?:_|-|\.|$)", filename, re.IGNORECASE ) if m: return datetime.strptime(m.group(1), "%Y-%m-%d").date() m = re.match( r"^OBJECTCATALOGUE_(\d{4}-\d{2}-\d{2})(?:_|-|\.|$)", filename, re.IGNORECASE ) if m: return datetime.strptime(m.group(1), "%Y-%m-%d").date() return None def format_date(date_value): if not date_value: return "" return date_value.strftime("%Y-%m-%d") def find_first_intro_csv_files(): patterns = [ os.path.join(TARGET_DIR, "**", "*_Combined.csv"), os.path.join(TARGET_DIR, "**", "ObjectCatalogue_5_*_Objects.csv"), ] found = [] for pattern in patterns: found.extend(glob.glob(pattern, recursive=True)) seen = set() result = [] for path in found: key = os.path.abspath(path).lower() if key not in seen: seen.add(key) result.append(path) return result def get_object_ids_from_csv(csv_file): object_ids = set() rows_read = 0 rows_skipped_missing_objectid = 0 with open(csv_file, "r", encoding="utf-8-sig", errors="replace", newline="") as f: reader = csv.DictReader(f, delimiter=",") if not reader.fieldnames: return object_ids, rows_read, rows_skipped_missing_objectid, "no header found" fieldnames_clean = clean_fieldnames(reader.fieldnames) reader.fieldnames = fieldnames_clean if "ObjectId" in fieldnames_clean: object_id_field = "ObjectId" elif len(fieldnames_clean) >= 2: object_id_field = fieldnames_clean[1] print(f" WARNING: ObjectId header not found. Using COL B: {repr(object_id_field)}") else: return object_ids, rows_read, rows_skipped_missing_objectid, "ObjectId missing and COL B does not exist" for row in reader: rows_read += 1 uuid = row.get(object_id_field, "").strip() if not uuid: rows_skipped_missing_objectid += 1 continue object_ids.add(uuid.upper()) return object_ids, rows_read, rows_skipped_missing_objectid, None def debug_write(debug_file, message): if not DEBUG_UUID_LOG_ENABLED: return if debug_file is None: return debug_file.write(message + "\n") debug_file.flush() def debug_uuid_event(debug_file, uuid, message): if uuid.upper() not in DEBUG_UUIDS: return debug_write(debug_file, f"{uuid.upper()}\t{message}") def debug_snapshot_status(debug_file, current_date, current_uuids, previous_uuids, removed_now, added_now, currently_removed): if not DEBUG_UUID_LOG_ENABLED: return for debug_uuid in sorted(DEBUG_UUIDS): status = "PRESENT" if debug_uuid in current_uuids else "MISSING" if debug_uuid in added_now: change = "ADDED_SINCE_PREVIOUS" elif debug_uuid in removed_now: change = "REMOVED_SINCE_PREVIOUS" elif debug_uuid in previous_uuids and debug_uuid in current_uuids: change = "STILL_PRESENT" elif debug_uuid not in previous_uuids and debug_uuid not in current_uuids: change = "STILL_MISSING" else: change = "NO_CHANGE" removed_state = "" if debug_uuid in currently_removed: removed_state = f"CURRENTLY_REMOVED_SINCE={format_date(currently_removed[debug_uuid])}" debug_write( debug_file, f"{debug_uuid}\tDATE={format_date(current_date)}\tSTATUS={status}\tCHANGE={change}\t{removed_state}" ) def build_first_intro_log(): if os.path.exists(FIRST_INTRO_OUTPUT_FILE): print("------------------------------------------------------------") print("First-introduced output file already exists. Skipping uuidfirstintroduced.txt only.") print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}") print("------------------------------------------------------------") return debug_file = None if DEBUG_UUID_LOG_ENABLED: debug_file = open(DEBUG_UUID_LOG_FILE, "w", encoding="utf-8", newline="") debug_write(debug_file, "UUID\tDebug") debug_write(debug_file, "------------------------------------------------------------") debug_write(debug_file, "Starting UUID debug trace") debug_write(debug_file, f"Target dir: {TARGET_DIR}") debug_write(debug_file, f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}") debug_write(debug_file, "Debug UUIDs:") for debug_uuid in sorted(DEBUG_UUIDS): debug_write(debug_file, f"{debug_uuid}\tWATCHING") debug_write(debug_file, "------------------------------------------------------------") try: first_intro_files = find_first_intro_csv_files() date_to_uuids = {} date_to_files = {} files_read = 0 files_skipped_dev_beta = 0 files_skipped_no_date = 0 files_skipped_missing_objectid = 0 rows_read = 0 rows_skipped_missing_objectid = 0 print() print("------------------------------------------------------------") print("Building first-introduced / last-removed UUID date log...") print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}") if DEBUG_UUID_LOG_ENABLED: print(f"Debug UUID log file: {DEBUG_UUID_LOG_FILE}") print(f"Found {len(first_intro_files)} candidate file(s).") print("------------------------------------------------------------") print() for csv_file in first_intro_files: build = get_build_from_file_path(csv_file) if build != "RETAIL": files_skipped_dev_beta += 1 debug_write(debug_file, f"SKIP_FILE_DEV_BETA\t{csv_file}\tBuild={build}") continue catalogue_date = parse_catalogue_date_from_filename(csv_file) if catalogue_date is None: files_skipped_no_date += 1 debug_write(debug_file, f"SKIP_FILE_NO_DATE\t{csv_file}") continue print("------------------------------------------------------------") print(f"Reading snapshot file: {csv_file}") print(f"Date: {format_date(catalogue_date)}") print(f"Build: {build}") debug_write( debug_file, f"READ_FILE\tDate={format_date(catalogue_date)}\tBuild={build}\t{csv_file}" ) try: object_ids, file_rows_read, file_rows_skipped, error = get_object_ids_from_csv(csv_file) rows_read += file_rows_read rows_skipped_missing_objectid += file_rows_skipped if error: print(f" SKIP: {error}") files_skipped_missing_objectid += 1 debug_write( debug_file, f"SKIP_FILE_OBJECTID_ERROR\tDate={format_date(catalogue_date)}\tError={error}\t{csv_file}" ) continue if catalogue_date not in date_to_uuids: date_to_uuids[catalogue_date] = set() date_to_files[catalogue_date] = [] date_to_uuids[catalogue_date].update(object_ids) date_to_files[catalogue_date].append(csv_file) files_read += 1 print(f" Rows read: {file_rows_read}") print(f" Skipped missing ObjectId: {file_rows_skipped}") print(f" UUIDs found in file: {len(object_ids)}") for debug_uuid in sorted(DEBUG_UUIDS): if debug_uuid in object_ids: debug_write( debug_file, f"{debug_uuid}\tFOUND_IN_FILE\tDate={format_date(catalogue_date)}\t{csv_file}" ) else: debug_write( debug_file, f"{debug_uuid}\tNOT_FOUND_IN_FILE\tDate={format_date(catalogue_date)}\t{csv_file}" ) except Exception as e: print(f" ERROR reading file: {e}") debug_write( debug_file, f"ERROR_READING_FILE\tDate={format_date(catalogue_date)}\tError={e}\t{csv_file}" ) continue sorted_dates = sorted(date_to_uuids.keys()) first_intro = {} last_removed = {} currently_removed = {} readded_events_by_uuid = {} previous_date = None previous_uuids = set() ever_seen = set() debug_write(debug_file, "------------------------------------------------------------") debug_write(debug_file, "Processing snapshots in date order") for current_date in sorted_dates: current_uuids = date_to_uuids[current_date] print("------------------------------------------------------------") print(f"Processing snapshot date: {format_date(current_date)}") print(f"Files combined for this date: {len(date_to_files[current_date])}") print(f"UUIDs in snapshot: {len(current_uuids)}") debug_write( debug_file, f"SNAPSHOT\tDate={format_date(current_date)}\tFiles={len(date_to_files[current_date])}\tUUIDs={len(current_uuids)}" ) for path in date_to_files[current_date]: debug_write(debug_file, f"SNAPSHOT_FILE\tDate={format_date(current_date)}\t{path}") # First snapshot only establishes the starting set. if previous_date is None: for uuid in current_uuids: first_intro[uuid] = current_date ever_seen.add(uuid) if uuid in DEBUG_UUIDS: debug_uuid_event( debug_file, uuid, f"FIRST_SNAPSHOT_PRESENT\tFirst Date Introduced={format_date(current_date)}" ) for debug_uuid in sorted(DEBUG_UUIDS): if debug_uuid not in current_uuids: debug_uuid_event( debug_file, debug_uuid, f"FIRST_SNAPSHOT_MISSING\tDate={format_date(current_date)}" ) previous_date = current_date previous_uuids = current_uuids continue removed_now = previous_uuids - current_uuids added_now = current_uuids - previous_uuids debug_snapshot_status( debug_file, current_date, current_uuids, previous_uuids, removed_now, added_now, currently_removed ) for uuid in added_now: if uuid not in ever_seen: first_intro[uuid] = current_date ever_seen.add(uuid) debug_uuid_event( debug_file, uuid, f"FIRST_INTRODUCED\tDate={format_date(current_date)}" ) if uuid in currently_removed: removed_date = currently_removed[uuid] event_text = f"{format_date(removed_date)}->{format_date(current_date)}" if uuid not in readded_events_by_uuid: readded_events_by_uuid[uuid] = [] readded_events_by_uuid[uuid].append(event_text) debug_uuid_event( debug_file, uuid, f"REMOVED_THEN_ADDED_BACK\t{event_text}" ) del currently_removed[uuid] for uuid in removed_now: last_removed[uuid] = previous_date currently_removed[uuid] = previous_date debug_uuid_event( debug_file, uuid, f"REMOVED\tLast Date Removed={format_date(previous_date)}\tMissing On={format_date(current_date)}" ) for debug_uuid in sorted(DEBUG_UUIDS): if debug_uuid in current_uuids and debug_uuid not in added_now: debug_uuid_event( debug_file, debug_uuid, f"PRESENT_AFTER_DATE_COMPARE\tDate={format_date(current_date)}" ) if debug_uuid not in current_uuids and debug_uuid not in removed_now: debug_uuid_event( debug_file, debug_uuid, f"MISSING_AFTER_DATE_COMPARE\tDate={format_date(current_date)}" ) print(f" Added since previous snapshot: {len(added_now)}") print(f" Removed since previous snapshot: {len(removed_now)}") previous_date = current_date previous_uuids = current_uuids final_rows = [] for uuid in sorted(first_intro.keys()): final_rows.append({ "UUID": uuid, "First Date Introduced": format_date(first_intro[uuid]), "Last Date Removed": format_date(last_removed.get(uuid)), "Readded Events": readded_events_by_uuid.get(uuid, []), }) max_readded_event_count = 0 for row in final_rows: count = len(row["Readded Events"]) if count > max_readded_event_count: max_readded_event_count = count first_intro_output_fields = ( FIRST_INTRO_BASE_OUTPUT_FIELDS + ([READDED_FIELD_NAME] * max_readded_event_count) ) with open(FIRST_INTRO_OUTPUT_FILE, "w", encoding="utf-8", newline="") as f: writer = csv.writer(f, delimiter="\t") writer.writerow(first_intro_output_fields) for row in final_rows: output_row = [ row["UUID"], row["First Date Introduced"], row["Last Date Removed"], ] readded_events = row["Readded Events"] for event_text in readded_events: output_row.append(event_text) while len(output_row) < len(first_intro_output_fields): output_row.append("") writer.writerow(output_row) debug_write(debug_file, "------------------------------------------------------------") debug_write(debug_file, "Finished UUID debug trace") debug_write(debug_file, f"Snapshot dates processed: {len(sorted_dates)}") total_readded_events = 0 for events in readded_events_by_uuid.values(): total_readded_events += len(events) debug_write(debug_file, f"Removed-then-added events written into uuidfirstintroduced.txt: {total_readded_events}") for debug_uuid in sorted(DEBUG_UUIDS): debug_write(debug_file, "------------------------------------------------------------") debug_write(debug_file, f"{debug_uuid}\tFINAL") debug_write(debug_file, f"{debug_uuid}\tFirst Date Introduced={format_date(first_intro.get(debug_uuid))}") debug_write(debug_file, f"{debug_uuid}\tLast Date Removed={format_date(last_removed.get(debug_uuid))}") events = readded_events_by_uuid.get(debug_uuid, []) if events: for event_text in events: debug_write(debug_file, f"{debug_uuid}\tRemoved Date->Added Back Date={event_text}") else: debug_write(debug_file, f"{debug_uuid}\tRemoved Date->Added Back Date=") print("------------------------------------------------------------") print("First-introduced / last-removed log done.") print(f"Candidate files found: {len(first_intro_files)}") print(f"Files read: {files_read}") print(f"Files skipped DEV/BETA: {files_skipped_dev_beta}") print(f"Files skipped missing date in filename: {files_skipped_no_date}") print(f"Files skipped missing ObjectId/COL B: {files_skipped_missing_objectid}") print(f"Snapshot dates processed: {len(sorted_dates)}") print(f"Rows read total: {rows_read}") print(f"Skipped missing ObjectId: {rows_skipped_missing_objectid}") print(f"Unique UUID rows written: {len(final_rows)}") print(f"Removed-then-added events written into uuidfirstintroduced.txt: {total_readded_events}") print(f"Extra Removed Date->Added Back Date field count: {max_readded_event_count}") print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}") if DEBUG_UUID_LOG_ENABLED: print(f"Debug UUID log file: {DEBUG_UUID_LOG_FILE}") print("------------------------------------------------------------") finally: if debug_file is not None: debug_file.close() def main(): if not os.path.isdir(TARGET_DIR): print("ERROR: Target directory does not exist.") print(f"Target directory: {TARGET_DIR}") input("") return if os.path.exists(OUTPUT_FILE): print("------------------------------------------------------------") print("Main output file already exists. Skipping uniqueobjects.txt only.") print(f"Output file: {OUTPUT_FILE}") print("Second log will still be checked.") print("------------------------------------------------------------") build_first_intro_log() input("") return csv_files = glob.glob( os.path.join(TARGET_DIR, "**", "*_Combined.csv"), recursive=True ) if not csv_files: print("ERROR: No *_Combined.csv files found.") print(f"Searched in: {TARGET_DIR}") print("Second log will still be checked.") build_first_intro_log() input("") return print(f"Script dir: {SCRIPT_DIR}") print(f"Base dir: {BASE_DIR}") print(f"Target dir: {TARGET_DIR}") print(f"Output file: {OUTPUT_FILE}") print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}") if DEBUG_UUID_LOG_ENABLED: print(f"Debug UUID log file: {DEBUG_UUID_LOG_FILE}") print() print(f"Found {len(csv_files)} *_Combined.csv file(s).") print() unique = {} total_rows_read = 0 total_skipped_missing_uuid = 0 total_skipped_missing_fields = 0 for csv_file in csv_files: build = get_build_from_file_path(csv_file) print("------------------------------------------------------------") print(f"Processing: {csv_file}") print(f"Build: {build}") rows_in_file = 0 skipped_in_file = 0 try: with open(csv_file, "r", encoding="utf-8-sig", errors="replace", newline="") as f: reader = csv.DictReader(f, delimiter=",") if not reader.fieldnames: print(" SKIP: no header found") total_skipped_missing_fields += 1 continue fieldnames_clean = clean_fieldnames(reader.fieldnames) reader.fieldnames = fieldnames_clean required = ["UUID_TXXX", "ObjectId", "Version"] missing = [field for field in required if field not in fieldnames_clean] if missing: print(f" SKIP: missing field(s): {', '.join(missing)}") print(" Headers found:") for h in fieldnames_clean: print(f" {repr(h)}") total_skipped_missing_fields += 1 continue for row in reader: total_rows_read += 1 rows_in_file += 1 uuid = row.get("UUID_TXXX", "").strip() if not uuid: total_skipped_missing_uuid += 1 skipped_in_file += 1 continue cleaned = { "UUID_TXXX": uuid, "ObjectId": row.get("ObjectId", "").strip(), "Version": row.get("Version", "").strip(), "Build": build, } if uuid not in unique: unique[uuid] = cleaned else: if should_replace_existing(unique[uuid], cleaned): unique[uuid] = cleaned except Exception as e: print(f" ERROR reading file: {e}") continue print(f" Rows read: {rows_in_file}") print(f" Skipped missing UUID_TXXX: {skipped_in_file}") final_rows = list(unique.values()) final_rows.sort( key=lambda r: ( r["ObjectId"].upper(), -version_num(r["Version"]), ) ) with open(OUTPUT_FILE, "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=OUTPUT_FIELDS, delimiter="\t") writer.writeheader() writer.writerows(final_rows) build_first_intro_log() print("------------------------------------------------------------") print("Done.") print(f"CSV files found: {len(csv_files)}") print(f"Rows read total: {total_rows_read}") print(f"Skipped missing UUID_TXXX: {total_skipped_missing_uuid}") print(f"Skipped files missing fields/header: {total_skipped_missing_fields}") print(f"Unique UUID_TXXX rows written: {len(final_rows)}") print(f"Output file: {OUTPUT_FILE}") print(f"First-introduced output file: {FIRST_INTRO_OUTPUT_FILE}") if DEBUG_UUID_LOG_ENABLED: print(f"Debug UUID log file: {DEBUG_UUID_LOG_FILE}") print("------------------------------------------------------------") input("") if __name__ == "__main__": main()