diff --git a/giving_names.py b/giving_names.py index 550e5d1..a10e05e 100644 --- a/giving_names.py +++ b/giving_names.py @@ -3,6 +3,7 @@ import sys import json import shutil import re +from collections import defaultdict def main(): if len(sys.argv) < 2: @@ -12,12 +13,14 @@ def main(): work_dir = sys.argv[1] target_subdir = os.path.join(work_dir, "Copies annotées") - # Create destination folder if it doesn't exist os.makedirs(target_subdir, exist_ok=True) - # Regex to match "CopieXX.json" and capture XX pattern = re.compile(r"^Copie(\d+)\.json$") + # Store data: name -> list of (copie_id, source_folder) + copies_map = defaultdict(list) + + # 1. Collect all data for filename in os.listdir(work_dir): match = pattern.match(filename) if match: @@ -25,24 +28,38 @@ def main(): json_path = os.path.join(work_dir, filename) source_folder = os.path.join(work_dir, f"Anot_Copie{copie_id}") - # Check if corresponding folder exists if os.path.isdir(source_folder): try: with open(json_path, 'r', encoding='utf-8') as f: data = json.load(f) name = data.get("name", "Unknown").strip() - - # Sanitize filename (remove characters invalid in paths) - safe_name = re.sub(r'[<>:"/\\|?*]', '', name) - - new_folder_name = f"{safe_name} ({copie_id})" - dest_path = os.path.join(target_subdir, new_folder_name) - - print(f"Moving '{source_folder}' -> '{dest_path}'") - shutil.move(source_folder, dest_path) - + copies_map[name].append((copie_id, source_folder)) except Exception as e: print(f"Error processing {filename}: {e}") + # 2. Check constraints and move files + for name, entries in copies_map.items(): + # Alert if name is Unknown + if name == "Unknown": + ids = [e[0] for e in entries] + print(f"ALERT: 'Unknown' name found for IDs: {', '.join(ids)}") + + # Alert if duplicates (same name, multiple IDs) + elif len(entries) > 1: + ids = [e[0] for e in entries] + print(f"ALERT: Name '{name}' assigned to multiple IDs: {', '.join(ids)}") + + # Perform move + safe_name = re.sub(r'[<>:"/\\|?*]', '', name) + for copie_id, source_folder in entries: + new_folder_name = f"{safe_name} ({copie_id})" + dest_path = os.path.join(target_subdir, new_folder_name) + + try: + print(f"Moving '{source_folder}' -> '{dest_path}'") + shutil.move(source_folder, dest_path) + except Exception as e: + print(f"Error moving {source_folder}: {e}") + if __name__ == "__main__": main()