66 lines
2.2 KiB
Python
66 lines
2.2 KiB
Python
import os
|
|
import sys
|
|
import json
|
|
import shutil
|
|
import re
|
|
from collections import defaultdict
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python rename_copies.py <directory_path>")
|
|
sys.exit(1)
|
|
|
|
work_dir = sys.argv[1]
|
|
target_subdir = os.path.join(work_dir, "Copies annotées")
|
|
|
|
os.makedirs(target_subdir, exist_ok=True)
|
|
|
|
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:
|
|
copie_id = match.group(1)
|
|
json_path = os.path.join(work_dir, filename)
|
|
source_folder = os.path.join(work_dir, f"Anot_Copie{copie_id}")
|
|
|
|
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()
|
|
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()
|