SPB Git

Repository Public License Research preview

validate_structure.py 9.8 KB 186 lines python

1#!/usr/bin/env python32"""Validate repository and session structure, metadata, attribution, language and status honesty.34Objective checks only. Fails (exit 1) on: missing required files for the declared status, metadata that5disagrees with course.yaml, missing instructor attribution, placeholder content in non-planned sessions,6slide IDs without speaker notes, learner-facing text that looks English, or a status label that the7evidence does not support.8"""9from __future__ import annotations1011import argparse12import json13import re14import sys1516from atlaslib import (REQUIRED_SESSION_DIRS, REQUIRED_SESSION_FILES, ROOT, STATUSES, Report, expand_inputs,17                      frame_ids, load_course, load_yaml, session_dir)1819ROOT_FILES = ["CLAUDE.md", "README.md", "LICENSE", "CONTRIBUTING.md", "CODE_OF_CONDUCT.md", "SECURITY.md",20              "Makefile", ".gitignore", ".editorconfig", "course.yaml",21              ".github/workflows/latex-build.yml", ".github/workflows/labs-test.yml",22              ".github/workflows/quality-gates.yml",23              "docs/curriculum.md", "docs/pedagogy.md", "docs/visual-design-system.md", "docs/accessibility.md",24              "docs/assessment-policy.md", "docs/source-verification.md", "docs/recording-guide.md",25              "docs/publishing-guide.md", "docs/maintenance.md", "docs/architecture.md",26              "brand/colors.tex", "brand/typography.tex", "brand/identity-guide.md",27              "latex/atlas-beamer.cls", "latex/atlas-theme.sty", "latex/atlas-colors.sty",28              "latex/atlas-figures.sty", "latex/atlas-accessibility.sty",29              "assets/fonts-manifest.md", "assets/asset-register.csv", "datasets/README.md",30              "reports/STATUS.md", "reports/status.json"]31PLACEHOLDERS = re.compile(r"\b(TODO|TBD|FIXME|lorem ipsum|à venir|coming soon|placeholder)\b", re.I)32FR_WORDS = {"le", "la", "les", "des", "une", "un", "et", "est", "pour", "dans", "que", "qui", "du", "au", "pas", "sur"}33EN_WORDS = {"the", "and", "is", "of", "for", "to", "with", "that", "this", "are", "you", "your", "from", "it"}34LEARNER_FACING = ["README.md", "slides/speaker-notes.md", "demos/README.md", "labs/instructions.md",35                  "labs/rubric.md", "quizzes/explanations.md", "video/script.md", "video/storyboard.md",36                  "video/shot-list.md", "accessibility/alt-text.md", "qa/checklist.md"]37WORDS_PER_MINUTE = 150383940def language_ratio(text: str) -> tuple[int, int]:41    text = re.sub(r"```.*?```", " ", text, flags=re.S)42    text = re.sub(r"`[^`]*`", " ", text)43    words = re.findall(r"[a-zàâçéèêëîïôûùüœ']+", text.lower())44    return sum(w in FR_WORDS for w in words), sum(w in EN_WORDS for w in words)454647def script_durations(script: str) -> list[dict]:48    out = []49    for title, body in re.findall(r"^## (Capsule[^\n]*)\n(.*?)(?=^## |\Z)", script, flags=re.S | re.M):50        spoken = re.sub(r"\[[^\]]*\]", " ", body)51        n = len(re.findall(r"\w+", spoken))52        out.append({"segment": title.strip(), "words": n, "estimated_minutes": round(n / WORDS_PER_MINUTE, 1)})53    return out545556def check_session(course: dict, s: dict, rep: Report) -> dict:57    d = session_dir(s)58    sid = s["id"]59    info: dict = {"id": sid}60    if not (d / "metadata.yaml").exists():61        rep.error(f"{sid}: metadata.yaml missing")62        return info63    meta = load_yaml(d / "metadata.yaml")64    status = meta.get("status")65    info["status"] = status66    if status not in STATUSES:67        rep.error(f"{sid}: invalid status {status!r}")68        return info69    for key in ("id", "title", "level", "outcomes", "tags", "dependencies", "language", "author", "affiliation"):70        if not meta.get(key) and key != "dependencies":71            rep.error(f"{sid}: metadata.yaml lacks {key!r}")72    if meta.get("title") != s["title"] or meta.get("outcomes") != s["outcomes"] or meta.get("dependencies") != s["depends_on"]:73        rep.error(f"{sid}: metadata.yaml disagrees with course.yaml (title, outcomes or dependencies)")74    if not 3 <= len(s["outcomes"]) <= 6:75        rep.error(f"{sid}: needs 3–6 learning outcomes")76    if meta.get("author") != course["author"]["name"] or meta.get("language") != course["course"]["language"]:77        rep.error(f"{sid}: author or language differs from course.yaml")78    readme = (d / "README.md").read_text(encoding="utf-8") if (d / "README.md").exists() else ""79    if course["author"]["name"] not in readme or "UQO" not in readme:80        rep.error(f"{sid}: README.md must name the instructor and the affiliation")81    if status == "planned":82        extra = [p.name for p in d.iterdir() if p.name not in ("README.md", "metadata.yaml")]83        if extra:84            rep.warn(f"{sid}: status is planned but the directory already holds {extra}")85        return info8687    for f in REQUIRED_SESSION_FILES:88        p = d / f89        if not p.exists():90            rep.error(f"{sid}: missing {f}")91        elif p.stat().st_size < 40:92            rep.error(f"{sid}: {f} is empty or nearly empty")93    for sub in REQUIRED_SESSION_DIRS:94        if not (d / sub).is_dir() or not any((d / sub).iterdir()):95            rep.error(f"{sid}: directory {sub}/ missing or empty")9697    for p in d.rglob("*"):98        if p.is_file() and p.suffix in {".md", ".tex", ".yaml", ".py", ".vtt"} and "rendered" not in p.parts:99            for i, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1):100                if PLACEHOLDERS.search(line) and "validate" not in line and "espaces réservés" not in line:101                    rep.error(f"{sid}: placeholder text in {p.relative_to(d)}:{i}: {line.strip()[:70]}")102103    ids = frame_ids(d)104    info["slides"] = len(ids)105    expected = [f"{sid}-D{n:02d}" for n in range(2, len(ids) + 2)]106    if ids != expected:107        rep.error(f"{sid}: slide IDs must be unique and sequential from {sid}-D02; found {ids[:4]}…")108    notes = (d / "slides" / "speaker-notes.md").read_text(encoding="utf-8") if (d / "slides" / "speaker-notes.md").exists() else ""109    for fid in [f"{sid}-D01"] + ids:110        if not re.search(rf"^## {fid}\b", notes, flags=re.M):111            rep.error(f"{sid}: speaker-notes.md has no section for {fid}")112113    main = d / "slides" / "main.tex"114    if main.exists():115        tex = expand_inputs(main)116        if "\\AtlasTitleSlide" not in tex or "\\AtlasClosingSlide" not in tex:117            rep.error(f"{sid}: deck must open with \\AtlasTitleSlide and end with \\AtlasClosingSlide (attribution)")118        if not 20 <= len(ids) + 1 <= 40:119            rep.warn(f"{sid}: {len(ids) + 1} content slides (guideline: 20–35)")120        frames_with_note = len(re.findall(r"\\note\{", tex))121        if frames_with_note < len(ids):122            rep.error(f"{sid}: {len(ids) - frames_with_note} slide(s) lack an in-deck \\note")123124    for f in LEARNER_FACING:125        p = d / f126        if p.exists():127            fr, en = language_ratio(p.read_text(encoding="utf-8"))128            if en > fr:129                rep.error(f"{sid}: {f} looks English (fr={fr}, en={en}); learner-facing content must be fr-CA")130    for f in ("README.md", "slides/speaker-notes.md", "labs/instructions.md", "video/script.md", "demos/README.md"):131        p = d / f132        if p.exists() and course["author"]["name"] not in p.read_text(encoding="utf-8"):133            rep.error(f"{sid}: {f} does not identify the instructor")134135    script = d / "video" / "script.md"136    if script.exists():137        text = script.read_text(encoding="utf-8")138        info["video_segments"] = script_durations(text)139        if not 3 <= len(info["video_segments"]) <= 6:140            rep.error(f"{sid}: video script must have 3–6 segments, found {len(info['video_segments'])}")141        if "non enregistré" not in text:142            rep.error(f"{sid}: video/script.md must state that nothing is recorded yet")143        info["video_estimated_minutes"] = round(sum(x["estimated_minutes"] for x in info["video_segments"]), 1)144    for p in d.rglob("*"):145        if p.suffix.lower() in {".mp4", ".mov", ".mkv", ".wav", ".mp3"}:146            rep.error(f"{sid}: media file {p.name} present — recordings are tracked outside the repository")147148    qa_path = d / "qa" / "results.json"149    if qa_path.exists():150        qa = json.loads(qa_path.read_text(encoding="utf-8"))151        if status == "validated":152            vr = qa.get("visual_review", {})153            if vr.get("status") != "passed" or not vr.get("reviewer") or not vr.get("date"):154                rep.error(f"{sid}: status validated requires a recorded, passed visual review")155            if not qa.get("ci", {}).get("passed"):156                rep.error(f"{sid}: status validated requires a recorded CI pass")157    return info158159160def main() -> int:161    argparse.ArgumentParser(description=__doc__).parse_args()162    rep = Report("structure")163    course = load_course()164    for f in ROOT_FILES:165        if not (ROOT / f).exists():166            rep.error(f"repository: missing {f}")167    if len(course["sessions"]) != 24 or [s["id"] for s in course["sessions"]] != [f"S{n:02d}" for n in range(1, 25)]:168        rep.error("course.yaml must define sessions S01…S24 in order")169    ids = {s["id"] for s in course["sessions"]}170    for s in course["sessions"]:171        for dep in s["depends_on"]:172            if dep not in ids or dep >= s["id"]:173                rep.error(f"{s['id']}: invalid prerequisite {dep} (must be an earlier session)")174    readme = (ROOT / "README.md").read_text(encoding="utf-8") if (ROOT / "README.md").exists() else ""175    for needle in (course["author"]["name"], course["author"]["institution"], course["course"]["endorsement_notice"][:40]):176        if needle not in readme:177            rep.error(f"README.md must contain: {needle!r}")178    rep.data["sessions"] = [check_session(course, s, rep) for s in course["sessions"]]179    counts = {k: sum(x.get("status") == k for x in rep.data["sessions"]) for k in STATUSES}180    rep.note("status counts: " + ", ".join(f"{k}={v}" for k, v in counts.items()))181    return rep.finish()182183184if __name__ == "__main__":185    sys.exit(main())186
Files main
Menu

Theme