Standardisation des scripts
This commit is contained in:
+138
-75
@@ -1,102 +1,165 @@
|
||||
import json
|
||||
import os
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
from copienator import (
|
||||
EvaluationWorkspace,
|
||||
ExitCode,
|
||||
evaluation_parser,
|
||||
execute,
|
||||
read_json,
|
||||
workspace_from_args,
|
||||
)
|
||||
from platform_utils import replace_with_link_or_copy, safe_filename
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3:
|
||||
print("Usage: python giving_names.py <directory_path> <Bnot/BGnot>")
|
||||
sys.exit(1)
|
||||
ANNOTATION_CHOICES = ("BGnot", "Bnot", "Anot")
|
||||
|
||||
work_dir = os.path.abspath(sys.argv[1])
|
||||
copies_dir = Path(work_dir) / "Copies"
|
||||
bnot_dir = sys.argv[2]
|
||||
target_subdir = os.path.join(work_dir, "A Rendre")
|
||||
os.makedirs(target_subdir, exist_ok=True)
|
||||
|
||||
# --- 1. Load the expected names list ---
|
||||
expected_names = set()
|
||||
names_path = os.path.join(work_dir, "names")
|
||||
if not os.path.exists(names_path):
|
||||
names_path = "names" # Fallback to current dir
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = evaluation_parser("Assign student names and prepare the return directory.")
|
||||
parser.add_argument(
|
||||
"annotation_dir",
|
||||
choices=ANNOTATION_CHOICES,
|
||||
help="Annotation directory to use",
|
||||
)
|
||||
return parser
|
||||
|
||||
if os.path.exists(names_path):
|
||||
with open(names_path, 'r', encoding='utf-8') as f:
|
||||
expected_names = {line.strip() for line in f if line.strip()}
|
||||
else:
|
||||
print(f"Warning: 'names' file not found in {work_dir} or current directory.")
|
||||
|
||||
# --- 2. Existing Collection Logic ---
|
||||
def _read_expected_names(workspace: EvaluationWorkspace) -> set[str]:
|
||||
names_path = workspace.names_file()
|
||||
if not names_path.exists():
|
||||
print(
|
||||
f"Warning: names file not found in {workspace.root} or the current directory.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return set()
|
||||
return {
|
||||
line.strip()
|
||||
for line in names_path.read_text(encoding="utf-8").splitlines()
|
||||
if line.strip()
|
||||
}
|
||||
|
||||
|
||||
def prepare_named_returns(
|
||||
workspace: EvaluationWorkspace,
|
||||
annotation_dir_name: str,
|
||||
) -> ExitCode:
|
||||
workspace.require_directories("Copies", annotation_dir_name)
|
||||
workspace.return_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
expected_names = _read_expected_names(workspace)
|
||||
copies_map: defaultdict[str, list[str]] = defaultdict(list)
|
||||
pattern = re.compile(r"^Copie(\d+)\.json$")
|
||||
copies_map = defaultdict(list)
|
||||
assigned_names = set() # To track which names were successfully linked
|
||||
had_errors = False
|
||||
|
||||
for filename in os.listdir(copies_dir):
|
||||
match = pattern.match(filename)
|
||||
if match:
|
||||
copie_id = match.group(1)
|
||||
json_path = os.path.join(copies_dir, filename)
|
||||
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)
|
||||
except Exception as e:
|
||||
print(f"Error processing {filename}: {e}")
|
||||
for json_path in workspace.copies_dir.iterdir():
|
||||
match = pattern.match(json_path.name)
|
||||
if not match:
|
||||
continue
|
||||
try:
|
||||
data = read_json(json_path)
|
||||
if not isinstance(data, dict):
|
||||
raise TypeError("expected a JSON object")
|
||||
name = str(data.get("name", "Unknown")).strip()
|
||||
copies_map[name].append(match.group(1))
|
||||
except (OSError, TypeError, ValueError) as exc:
|
||||
print(f"Error processing {json_path}: {exc}", file=sys.stderr)
|
||||
had_errors = True
|
||||
|
||||
# --- 3. Process and Link ---
|
||||
for name, ids in copies_map.items():
|
||||
assigned_names: set[str] = set()
|
||||
selected_annotations = workspace.root / annotation_dir_name
|
||||
fallback_annotations = workspace.annotation_dir("simple")
|
||||
|
||||
for name, copy_ids in copies_map.items():
|
||||
if name == "Unknown":
|
||||
print(f"ALERT: 'Unknown' name found for IDs: {', '.join(ids)}")
|
||||
elif len(ids) > 1:
|
||||
print(f"ALERT: Name '{name}' assigned to multiple IDs: {', '.join(ids)}")
|
||||
print(
|
||||
f"Warning: unknown name for copies: {', '.join(copy_ids)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
elif len(copy_ids) > 1:
|
||||
print(
|
||||
f"Warning: name {name!r} is assigned to multiple copies: "
|
||||
f"{', '.join(copy_ids)}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
safe_name = safe_filename(name)
|
||||
|
||||
for copie_id in ids:
|
||||
path_b = os.path.join(work_dir, f"{bnot_dir}/Copie{copie_id}")
|
||||
path_a = os.path.join(work_dir, f"Anot/Copie{copie_id}")
|
||||
|
||||
for copy_id in copy_ids:
|
||||
selected = selected_annotations / f"Copie{copy_id}"
|
||||
fallback = fallback_annotations / f"Copie{copy_id}"
|
||||
source_folder = None
|
||||
if os.path.exists(os.path.join(path_b, "Concat.jpg")) and os.path.exists(os.path.join(path_b, "score.json")):
|
||||
source_folder = path_b
|
||||
elif os.path.exists(os.path.join(path_a, "Concat.jpg")) and os.path.exists(os.path.join(path_a, "score.json")):
|
||||
source_folder = path_a
|
||||
|
||||
if not source_folder:
|
||||
for candidate in (selected, fallback):
|
||||
if (candidate / "Concat.jpg").exists() and (
|
||||
candidate / "score.json"
|
||||
).exists():
|
||||
source_folder = candidate
|
||||
break
|
||||
if source_folder is None:
|
||||
continue
|
||||
|
||||
# If we reached here, the link is possible
|
||||
assigned_names.add(name)
|
||||
|
||||
dest_folder_name = f"{safe_name} ({copie_id})"
|
||||
dest_path = os.path.join(target_subdir, dest_folder_name)
|
||||
os.makedirs(dest_path, exist_ok=True)
|
||||
|
||||
links = [("Concat.jpg", f"{safe_name}.jpg"),("Concat_F.pdf", f"{safe_name}.pdf"), ("score.json", "score.json")]
|
||||
for src_name, dst_name in links:
|
||||
src_file = os.path.join(source_folder, src_name)
|
||||
dst_link = os.path.join(dest_path, dst_name)
|
||||
destination = workspace.return_dir / f"{safe_name} ({copy_id})"
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
links = (
|
||||
("Concat.jpg", f"{safe_name}.jpg"),
|
||||
("Concat_F.pdf", f"{safe_name}.pdf"),
|
||||
("score.json", "score.json"),
|
||||
)
|
||||
for source_name, destination_name in links:
|
||||
source = source_folder / source_name
|
||||
if not source.exists():
|
||||
continue
|
||||
try:
|
||||
if os.path.exists(src_file):
|
||||
method = replace_with_link_or_copy(src_file, dst_link, prefer="symlink")
|
||||
if method == "copy":
|
||||
print(f"Copied {src_name} for {dest_folder_name} (links unavailable)")
|
||||
except OSError as e:
|
||||
print(f"Error linking {src_name} for {dest_folder_name}: {e}")
|
||||
method = replace_with_link_or_copy(
|
||||
source,
|
||||
destination / destination_name,
|
||||
prefer="symlink",
|
||||
)
|
||||
if method == "copy":
|
||||
print(
|
||||
f"Copied {source_name} for {destination.name} "
|
||||
"(links unavailable)"
|
||||
)
|
||||
except OSError as exc:
|
||||
print(
|
||||
f"Error linking {source} for {destination.name}: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
had_errors = True
|
||||
|
||||
# --- 4. Print Unassigned Names ---
|
||||
unassigned = expected_names - assigned_names
|
||||
if unassigned:
|
||||
print("\n" + "!" * 40)
|
||||
print("NAMES FROM LIST NOT ASSIGNED:")
|
||||
for n in sorted(unassigned):
|
||||
print(f" - {n}")
|
||||
print("!" * 40)
|
||||
print("Names from the list that were not assigned:", file=sys.stderr)
|
||||
for name in sorted(unassigned):
|
||||
print(f" - {name}", file=sys.stderr)
|
||||
|
||||
return ExitCode.PARTIAL if had_errors else ExitCode.SUCCESS
|
||||
|
||||
|
||||
def run(
|
||||
workspace: EvaluationWorkspace,
|
||||
*,
|
||||
annotation_dir: str,
|
||||
) -> ExitCode:
|
||||
return prepare_named_returns(workspace, annotation_dir)
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = build_parser()
|
||||
return execute(
|
||||
parser,
|
||||
argv,
|
||||
lambda args: run(
|
||||
workspace_from_args(args, repository=Path.cwd()),
|
||||
annotation_dir=args.annotation_dir,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
raise SystemExit(main())
|
||||
|
||||
Reference in New Issue
Block a user