stringforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,60 @@
1
+ r"""
2
+ stringforge.vacuavault — tooling for the HuggingFace ``vacua_vault``
3
+ dataset repository.
4
+
5
+ This subpackage provides three CLI-driven operations for maintaining the
6
+ remote vault repo:
7
+
8
+ - **validate** (on PR branch): parse the git diff, re-validate added
9
+ parquet files, post a catalog preview as a PR comment. Implemented
10
+ in :mod:`.ci`.
11
+ - **rebuild_catalog** (post-merge on main): scan the repo for all
12
+ parquet files, regenerate ``catalog.parquet`` from their metadata.
13
+ Implemented in :mod:`.catalog`.
14
+ - **curate** (maintainer operation): promote a community submission
15
+ out of ``community/`` up to the model-level directory, stripping the
16
+ ``{hf_username}_`` prefix and preserving attribution. Implemented in
17
+ :mod:`.curate`.
18
+
19
+ All three are dispatched by :mod:`.__main__` via argparse subcommands.
20
+
21
+ Module layout::
22
+
23
+ stringforge/vacuavault/
24
+ ├── __init__.py — this file (re-exports public entry points)
25
+ ├── __main__.py — CLI dispatcher
26
+ ├── ci.py — validate_pr_diff()
27
+ ├── catalog.py — rebuild_catalog()
28
+ ├── curate.py — curate_submission()
29
+ └── schema.py — SCHEMA constants + _validate_parquet()
30
+ """
31
+ from .ci import validate_pr_diff
32
+ from .catalog import rebuild_catalog
33
+ from .curate import curate_submission
34
+ from .schema import (
35
+ SCHEMA_VERSION,
36
+ RESERVED_NAMES,
37
+ LABEL_SLUG_RE,
38
+ validate_parquet_file,
39
+ split_by_validation,
40
+ _extract_identity_from_row,
41
+ _identity_from_row,
42
+ _check_identity_consistency,
43
+ )
44
+
45
+ __all__ = [
46
+ "validate_pr_diff",
47
+ "rebuild_catalog",
48
+ "curate_submission",
49
+ "SCHEMA_VERSION",
50
+ "RESERVED_NAMES",
51
+ "LABEL_SLUG_RE",
52
+ "validate_parquet_file",
53
+ "split_by_validation",
54
+ # Identity helpers (introduced with the auto-load path). Underscored
55
+ # because they're stable-but-low-level: the public API is
56
+ # validate_parquet_file's behaviour, not the helpers themselves.
57
+ "_extract_identity_from_row",
58
+ "_identity_from_row",
59
+ "_check_identity_consistency",
60
+ ]
@@ -0,0 +1,104 @@
1
+ r"""
2
+ CLI dispatcher for the ``stringforge.vacuavault`` tooling.
3
+
4
+ Usage:
5
+
6
+ python -m stringforge.vacuavault validate [--base-branch main] [--repo-path .]
7
+ python -m stringforge.vacuavault rebuild_catalog [--repo-path .] [--output catalog.parquet]
8
+ python -m stringforge.vacuavault curate <community_file> [--repo-root .] [--new-label LABEL] [--dry-run]
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from .ci import validate_pr_diff
17
+ from .catalog import rebuild_catalog
18
+ from .curate import curate_submission
19
+
20
+
21
+ def _cmd_validate(args: argparse.Namespace) -> int:
22
+ # Pure schema-only validation — this CLI imports nothing from
23
+ # jaxvacua. Physics-aware variants live in a separate
24
+ # downstream CLI (e.g. ``jaxvacua-vault validate
25
+ # --check-physics``), which can pass a populated
26
+ # ``model_loader`` to :func:`validate_pr_diff` directly.
27
+ return validate_pr_diff(
28
+ repo_path=args.repo_path,
29
+ base_branch=args.base_branch,
30
+ report_path=args.report_path,
31
+ catalog_preview_path=args.preview_path,
32
+ model_loader=None,
33
+ verbose=True,
34
+ )
35
+
36
+
37
+ def _cmd_rebuild(args: argparse.Namespace) -> int:
38
+ rebuild_catalog(
39
+ repo_path=args.repo_path,
40
+ output=args.output,
41
+ verbose=True,
42
+ )
43
+ return 0
44
+
45
+
46
+ def _cmd_curate(args: argparse.Namespace) -> int:
47
+ target = curate_submission(
48
+ community_path=args.file,
49
+ repo_root=args.repo_root,
50
+ new_label=args.new_label,
51
+ dry_run=args.dry_run,
52
+ verbose=True,
53
+ )
54
+ print(f"curated → {target}")
55
+ return 0
56
+
57
+
58
+ def main(argv: list[str] | None = None) -> int:
59
+ parser = argparse.ArgumentParser(
60
+ prog="python -m stringforge.vacuavault",
61
+ description="Tooling for the HuggingFace vacua_vault dataset repo.",
62
+ )
63
+ sub = parser.add_subparsers(dest="cmd", required=True)
64
+
65
+ # validate
66
+ pv = sub.add_parser(
67
+ "validate",
68
+ help="Validate parquet files in a PR diff (CI entry point).",
69
+ )
70
+ pv.add_argument("--repo-path", default=".", help="Vault repo root (default: cwd).")
71
+ pv.add_argument("--base-branch", default="main",
72
+ help="PR base branch (default: main).")
73
+ pv.add_argument("--report-path", default="validation_report.json")
74
+ pv.add_argument("--preview-path", default="catalog_preview.md")
75
+ pv.set_defaults(func=_cmd_validate)
76
+
77
+ # rebuild_catalog
78
+ pr = sub.add_parser(
79
+ "rebuild_catalog",
80
+ help="Regenerate catalog.parquet from the repo contents.",
81
+ )
82
+ pr.add_argument("--repo-path", default=".")
83
+ pr.add_argument("--output", default=None,
84
+ help="Output path (default: <repo>/catalog.parquet).")
85
+ pr.set_defaults(func=_cmd_rebuild)
86
+
87
+ # curate
88
+ pc = sub.add_parser(
89
+ "curate",
90
+ help="Promote a community/ submission up to the model directory.",
91
+ )
92
+ pc.add_argument("file", help="Path to the file under community/.")
93
+ pc.add_argument("--repo-root", default=".")
94
+ pc.add_argument("--new-label", default=None,
95
+ help="Override the target filename stem.")
96
+ pc.add_argument("--dry-run", action="store_true")
97
+ pc.set_defaults(func=_cmd_curate)
98
+
99
+ args = parser.parse_args(argv)
100
+ return int(args.func(args))
101
+
102
+
103
+ if __name__ == "__main__":
104
+ sys.exit(main())
@@ -0,0 +1,222 @@
1
+ r"""
2
+ Catalog regeneration for the HuggingFace ``vacua_vault`` repo.
3
+
4
+ Scans the repo for ``**/*.parquet`` (excluding ``catalog.parquet``,
5
+ ``retractions.parquet``, and ``_rejected/**``) and writes a fresh
6
+ ``catalog.parquet`` at the repo root with one row per file.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ from typing import Any, Dict, List, Optional
17
+
18
+ from .schema import SCHEMA_VERSION, RESERVED_NAMES
19
+
20
+
21
+ #: Columns in the regenerated catalog.
22
+ CATALOG_COLUMNS = (
23
+ "file_path", "basename", "status",
24
+ "h12", "ks_id", "triang_id", "cicy_id", "model_ID",
25
+ "susy", "method", "nmax", "qualifiers",
26
+ "classification_source",
27
+ "label", "version", "committed_by",
28
+ "n_rows", "schema_version",
29
+ "checksum", "superseded_by",
30
+ "retracted", "retraction_reason", "retracted_at",
31
+ "uploaded_at",
32
+ )
33
+
34
+
35
+ def _sha256(path: Path) -> str:
36
+ h = hashlib.sha256()
37
+ with open(path, "rb") as f:
38
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
39
+ h.update(chunk)
40
+ return h.hexdigest()
41
+
42
+
43
+ def _parse_path(repo_root: Path, p: Path) -> Dict[str, Any]:
44
+ """Extract identity + status from a parquet file's path."""
45
+ rel = p.relative_to(repo_root)
46
+ parts = rel.parts
47
+ info: Dict[str, Any] = {
48
+ "file_path": str(rel),
49
+ "basename": p.name,
50
+ "h12": None,
51
+ "ks_id": None,
52
+ "triang_id": None,
53
+ "cicy_id": None,
54
+ "model_ID": None,
55
+ "status": "curated",
56
+ "label": None,
57
+ "version": 1,
58
+ }
59
+ # tdf/h12_N/ks_X_tri_Y/[community/_rejected/]<name>.parquet
60
+ if len(parts) >= 4 and parts[0] == "tdf":
61
+ m = re.match(r"h12_(\d+)", parts[1])
62
+ if m:
63
+ info["h12"] = int(m.group(1))
64
+ m = re.match(r"ks_(\d+)_tri_(\d+)", parts[2])
65
+ if m:
66
+ info["ks_id"] = int(m.group(1))
67
+ info["triang_id"] = int(m.group(2))
68
+ rest = parts[3:]
69
+ if rest and rest[0] == "community":
70
+ info["status"] = "pending"
71
+ rest = rest[1:]
72
+ if rest and rest[0] == "_rejected":
73
+ info["status"] = "rejected"
74
+ rest = rest[1:]
75
+ # cicy/cicy_X/...
76
+ elif len(parts) >= 3 and parts[0] == "cicy":
77
+ m = re.match(r"cicy_(\d+)", parts[1])
78
+ if m:
79
+ info["cicy_id"] = int(m.group(1))
80
+ rest = parts[2:]
81
+ if rest and rest[0] == "community":
82
+ info["status"] = "pending"
83
+ rest = rest[1:]
84
+ # local/h12_N/model_M/[community/_rejected/]<name>.parquet
85
+ # (local JAXVacua models loaded via h12 + model_ID; the on-disk vault
86
+ # uses a flat KS/h12_N_model_M dir, the remote vault this nested layout.)
87
+ elif len(parts) >= 4 and parts[0] == "local":
88
+ m = re.match(r"h12_(\d+)", parts[1])
89
+ if m:
90
+ info["h12"] = int(m.group(1))
91
+ m = re.match(r"model_(\d+)", parts[2])
92
+ if m:
93
+ info["model_ID"] = int(m.group(1))
94
+ rest = parts[3:]
95
+ if rest and rest[0] == "community":
96
+ info["status"] = "pending"
97
+ rest = rest[1:]
98
+ if rest and rest[0] == "_rejected":
99
+ info["status"] = "rejected"
100
+ rest = rest[1:]
101
+ # Parse label + optional _v{n}
102
+ stem = os.path.splitext(p.name)[0]
103
+ # Community files are {hf_username}_{label}[_v{n}]
104
+ if info["status"] == "pending" and "_" in stem:
105
+ # Best-effort: split once, assume first segment is username
106
+ _hfu, lbl_stem = stem.split("_", 1)
107
+ else:
108
+ lbl_stem = stem
109
+ vm = re.match(r"^(?P<label>.+?)(?:_v(?P<ver>\d+))?$", lbl_stem)
110
+ if vm:
111
+ info["label"] = vm.group("label")
112
+ if vm.group("ver"):
113
+ info["version"] = int(vm.group("ver"))
114
+ return info
115
+
116
+
117
+ def _read_metadata(p: Path) -> Dict[str, str]:
118
+ """Read parquet key-value metadata; return empty dict on error."""
119
+ try:
120
+ import pyarrow.parquet as pq
121
+ tbl = pq.read_table(p)
122
+ raw = tbl.schema.metadata or {}
123
+ return {
124
+ k.decode(): v.decode() for k, v in raw.items()
125
+ if isinstance(k, (bytes, bytearray))
126
+ }
127
+ except Exception:
128
+ return {}
129
+
130
+
131
+ def _guess_susy_from_filename(stem: str) -> str:
132
+ s = stem.lower()
133
+ if "nonsusy" in s or "non_susy" in s or "non-susy" in s:
134
+ return "nonSUSY"
135
+ if "susy" in s:
136
+ return "SUSY"
137
+ return "unknown"
138
+
139
+
140
+ def _count_rows(p: Path) -> int:
141
+ try:
142
+ import pyarrow.parquet as pq
143
+ return pq.ParquetFile(p).metadata.num_rows
144
+ except Exception:
145
+ return -1
146
+
147
+
148
+ def rebuild_catalog(
149
+ repo_path: str | Path,
150
+ output: Optional[str] = None,
151
+ verbose: bool = True,
152
+ ) -> Path:
153
+ r"""
154
+ **Description:**
155
+ Scan *repo_path* for vault parquet files and regenerate
156
+ ``catalog.parquet``.
157
+
158
+ Args:
159
+ repo_path: Path to the local vault repo checkout.
160
+ output: Optional output path. Defaults to
161
+ ``<repo_path>/catalog.parquet``.
162
+ verbose: Print progress.
163
+
164
+ Returns:
165
+ pathlib.Path: Path to the written catalog.
166
+ """
167
+ import pandas as pd
168
+
169
+ root = Path(repo_path).resolve()
170
+ if not root.is_dir():
171
+ raise ValueError(f"repo_path {root} is not a directory")
172
+
173
+ rows: List[Dict[str, Any]] = []
174
+ for p in sorted(root.rglob("*.parquet")):
175
+ rel = p.relative_to(root)
176
+ # Skip top-level metadata parquets and rejected split-offs
177
+ if p.name in RESERVED_NAMES:
178
+ continue
179
+ if any(part == "_rejected" for part in rel.parts):
180
+ # Still include in the catalogue, but flag status.
181
+ pass # fall through; _parse_path will set status="rejected"
182
+
183
+ info = _parse_path(root, p)
184
+ md = _read_metadata(p)
185
+
186
+ # Determine classification source
187
+ has_md_classification = any(k in md for k in ("susy", "method", "nmax", "qualifiers"))
188
+ if has_md_classification:
189
+ info["classification_source"] = "parquet_metadata"
190
+ else:
191
+ info["classification_source"] = "filename_guess"
192
+
193
+ info["susy"] = md.get("susy") or _guess_susy_from_filename(p.stem)
194
+ info["method"] = md.get("method", "unknown")
195
+ info["nmax"] = (int(md["nmax"]) if md.get("nmax") and md["nmax"].isdigit() else None)
196
+ info["qualifiers"] = md.get("qualifiers", "{}")
197
+ info["committed_by"] = md.get("committed_by", "")
198
+ info["uploaded_at"] = md.get("uploaded_at", "")
199
+
200
+ info["n_rows"] = _count_rows(p)
201
+ info["schema_version"] = int(md.get("schema_version", SCHEMA_VERSION))
202
+ info["checksum"] = _sha256(p)
203
+ info["superseded_by"] = md.get("superseded_by", "")
204
+ info["retracted"] = (md.get("retracted", "false").lower() == "true")
205
+ info["retraction_reason"] = md.get("retraction_reason", "")
206
+ info["retracted_at"] = md.get("retracted_at", "")
207
+
208
+ # Fill any missing catalog columns with defaults
209
+ for c in CATALOG_COLUMNS:
210
+ info.setdefault(c, None)
211
+
212
+ rows.append(info)
213
+ if verbose:
214
+ print(f"[catalog] {rel} rows={info['n_rows']} "
215
+ f"susy={info['susy']} status={info['status']}")
216
+
217
+ df = pd.DataFrame(rows, columns=list(CATALOG_COLUMNS))
218
+ out = Path(output) if output else (root / "catalog.parquet")
219
+ df.to_parquet(out, index=False)
220
+ if verbose:
221
+ print(f"[catalog] wrote {len(df)} rows to {out}")
222
+ return out
@@ -0,0 +1,188 @@
1
+ r"""
2
+ Server-side PR validation for the ``vacua_vault`` repo.
3
+
4
+ Called by CI on every PR. Parses the git diff for added/modified
5
+ parquet files, re-validates them (no trust in client-side validation),
6
+ and writes:
7
+
8
+ - ``validation_report.json`` — machine-readable per-file results.
9
+ - ``catalog_preview.md`` — human-readable summary for a PR comment.
10
+
11
+ Exit code is 0 on pass, 1 on fail (blocks merge).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import subprocess
18
+ from pathlib import Path
19
+ from typing import Any, Dict, List, Optional
20
+
21
+ from .schema import validate_parquet_file, SCHEMA_VERSION
22
+
23
+
24
+ def _git(args: list[str], cwd: str | Path) -> str:
25
+ res = subprocess.run(
26
+ ["git", *args], cwd=str(cwd),
27
+ capture_output=True, text=True, check=False,
28
+ )
29
+ return res.stdout.strip()
30
+
31
+
32
+ def _changed_parquet_paths(
33
+ repo_path: str | Path, base_branch: str,
34
+ ) -> List[Path]:
35
+ r"""Return Paths of added/modified parquet files in the diff."""
36
+ out = _git(
37
+ ["diff", "--name-only", f"origin/{base_branch}...HEAD", "--",
38
+ "*.parquet"],
39
+ cwd=repo_path,
40
+ )
41
+ files: List[Path] = []
42
+ for line in out.splitlines():
43
+ p = Path(repo_path) / line.strip()
44
+ if p.exists() and p.suffix == ".parquet":
45
+ files.append(p)
46
+ return files
47
+
48
+
49
+ def validate_pr_diff(
50
+ repo_path: str | Path,
51
+ base_branch: str = "main",
52
+ report_path: str = "validation_report.json",
53
+ catalog_preview_path: str = "catalog_preview.md",
54
+ model_loader: Optional[Any] = None,
55
+ verbose: bool = True,
56
+ ) -> int:
57
+ r"""
58
+ **Description:**
59
+ Validate every added/changed parquet in the PR diff.
60
+
61
+ Args:
62
+ repo_path: Path to the checked-out vault repo.
63
+ base_branch: Base branch of the PR (usually ``main``).
64
+ report_path: Where to write ``validation_report.json``.
65
+ catalog_preview_path: Where to write the Markdown preview
66
+ posted as a PR comment.
67
+ model_loader: Optional callable accepting ``(ks_id, triang_id)``,
68
+ ``(cicy_id)``, or ``(h12, model_ID)`` (for ``local/`` models)
69
+ → model, used for F-term physics checks. When omitted, only
70
+ schema/structural checks are performed.
71
+ verbose: Print progress.
72
+
73
+ Returns:
74
+ int: Exit code (0 = all green, 1 = at least one failure).
75
+ """
76
+ repo = Path(repo_path).resolve()
77
+ changed = _changed_parquet_paths(repo, base_branch)
78
+
79
+ if verbose:
80
+ print(f"[ci] {len(changed)} changed parquet file(s) in PR")
81
+
82
+ per_file: List[Dict[str, Any]] = []
83
+ any_failed = False
84
+
85
+ for p in changed:
86
+ rel = p.relative_to(repo)
87
+ model = None
88
+ if model_loader is not None:
89
+ # Infer identity from the path
90
+ parts = rel.parts
91
+ try:
92
+ if parts[0] == "tdf":
93
+ ks_tri = parts[2] # ks_X_tri_Y
94
+ import re
95
+ m = re.match(r"ks_(\d+)_tri_(\d+)", ks_tri)
96
+ if m:
97
+ model = model_loader(
98
+ ks_id=int(m.group(1)),
99
+ triang_id=int(m.group(2)),
100
+ )
101
+ elif parts[0] == "cicy":
102
+ import re
103
+ m = re.match(r"cicy_(\d+)", parts[1])
104
+ if m:
105
+ model = model_loader(cicy_id=int(m.group(1)))
106
+ elif parts[0] == "local":
107
+ # local/h12_N/model_M/... → load by (h12, model_ID)
108
+ import re
109
+ mh = re.match(r"h12_(\d+)", parts[1])
110
+ mm = re.match(r"model_(\d+)", parts[2])
111
+ if mh and mm:
112
+ model = model_loader(
113
+ h12=int(mh.group(1)),
114
+ model_ID=int(mm.group(1)),
115
+ )
116
+ except Exception as e:
117
+ if verbose:
118
+ print(f"[ci] model_loader failed for {rel}: {e}")
119
+
120
+ result = validate_parquet_file(
121
+ p, model=model, expected_schema_version=SCHEMA_VERSION,
122
+ )
123
+ entry = {
124
+ "file_path": str(rel),
125
+ "passed": result["passed"],
126
+ "n_rows": result["n_rows"],
127
+ "n_failed": result["n_failed"],
128
+ "errors": result["errors"],
129
+ "warnings": result["warnings"],
130
+ "metadata": result["metadata"],
131
+ }
132
+ if not result["passed"]:
133
+ any_failed = True
134
+ entry["per_row_errors"] = [
135
+ {"index": r["index"], "errors": r["errors"]}
136
+ for r in result["per_row_report"] if not r["passed"]
137
+ ]
138
+ per_file.append(entry)
139
+ if verbose:
140
+ flag = "✓" if result["passed"] else "✗"
141
+ print(f"[ci] {flag} {rel} rows={result['n_rows']} "
142
+ f"failed={result['n_failed']}")
143
+
144
+ # Write JSON report
145
+ report = {
146
+ "pr_base": base_branch,
147
+ "schema_version": SCHEMA_VERSION,
148
+ "n_files": len(changed),
149
+ "n_failed_files": sum(1 for e in per_file if not e["passed"]),
150
+ "per_file": per_file,
151
+ }
152
+ rp = Path(report_path)
153
+ rp.parent.mkdir(parents=True, exist_ok=True)
154
+ rp.write_text(json.dumps(report, indent=2))
155
+
156
+ # Write Markdown preview
157
+ lines: List[str] = ["## vacua_vault CI preview", ""]
158
+ if not changed:
159
+ lines.append("No parquet file changes in this PR.")
160
+ else:
161
+ total_rows = sum(e["n_rows"] for e in per_file)
162
+ n_fail = sum(1 for e in per_file if not e["passed"])
163
+ lines.append(
164
+ f"- **{len(changed)}** file(s) changed, "
165
+ f"**{total_rows:,}** total rows."
166
+ )
167
+ lines.append(
168
+ f"- **{n_fail}** file(s) failed validation."
169
+ if n_fail else "- All files passed validation."
170
+ )
171
+ lines.append("")
172
+ lines.append("| File | Rows | Status |")
173
+ lines.append("| --- | --- | --- |")
174
+ for e in per_file:
175
+ status = "✅ pass" if e["passed"] else "❌ fail"
176
+ lines.append(f"| `{e['file_path']}` | {e['n_rows']} | {status} |")
177
+ # Detailed errors
178
+ for e in per_file:
179
+ if not e["passed"]:
180
+ lines.append("")
181
+ lines.append(f"### Errors in `{e['file_path']}`")
182
+ for err in e["errors"]:
183
+ lines.append(f"- {err}")
184
+ cp = Path(catalog_preview_path)
185
+ cp.parent.mkdir(parents=True, exist_ok=True)
186
+ cp.write_text("\n".join(lines) + "\n")
187
+
188
+ return 1 if any_failed else 0
@@ -0,0 +1,119 @@
1
+ r"""
2
+ Promote a community submission from ``community/`` up to the model-level
3
+ directory.
4
+
5
+ Called by the maintainer after a PR has been merged and the submission
6
+ has passed review. Strips the ``{hf_username}_`` filename prefix and
7
+ records the original contributor in the file's parquet metadata as
8
+ ``original_contributor`` so attribution survives the rename.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ import shutil
15
+ from pathlib import Path
16
+ from typing import Optional
17
+
18
+
19
+ def _strip_username_prefix(stem: str) -> tuple[Optional[str], str]:
20
+ """Return (hf_username, remaining_label). If the stem has no
21
+ underscore, treat it as a label with no username prefix."""
22
+ if "_" not in stem:
23
+ return None, stem
24
+ hfu, rest = stem.split("_", 1)
25
+ return hfu, rest
26
+
27
+
28
+ def curate_submission(
29
+ community_path: str | Path,
30
+ repo_root: str | Path,
31
+ new_label: Optional[str] = None,
32
+ dry_run: bool = False,
33
+ verbose: bool = True,
34
+ ) -> Path:
35
+ r"""
36
+ **Description:**
37
+ Promote a parquet file from a model's ``community/`` directory up
38
+ to the model-level directory.
39
+
40
+ Operations:
41
+
42
+ 1. Verify the file lives under ``.../{model_dir}/community/``.
43
+ 2. Compute the target path as
44
+ ``.../{model_dir}/{new_label or stripped_stem}.parquet``.
45
+ 3. Move the file, updating its parquet key-value metadata with
46
+ ``original_contributor`` (the stripped HF-username prefix) and
47
+ ``status="curated"``.
48
+ 4. If the target name already exists, append a ``_v{n}`` suffix.
49
+
50
+ Args:
51
+ community_path: Absolute path to the file under ``community/``.
52
+ repo_root: Absolute path to the vault repo root. Used for
53
+ sanity checks only.
54
+ new_label: Optional override for the target filename stem
55
+ (without extension, without the ``_v{n}`` suffix).
56
+ dry_run: If True, print what would happen and return the
57
+ projected target path without moving anything.
58
+ verbose: Print progress.
59
+
60
+ Returns:
61
+ pathlib.Path: Path of the moved file (or the projected path
62
+ when ``dry_run=True``).
63
+
64
+ Raises:
65
+ ValueError: If the path is not under a ``community/`` folder
66
+ of the vault repo.
67
+ """
68
+ import pyarrow.parquet as pq
69
+ import pyarrow as pa
70
+
71
+ src = Path(community_path).resolve()
72
+ root = Path(repo_root).resolve()
73
+ try:
74
+ rel = src.relative_to(root)
75
+ except ValueError:
76
+ raise ValueError(
77
+ f"{src} is not under repo_root={root}"
78
+ ) from None
79
+
80
+ parts = rel.parts
81
+ if "community" not in parts:
82
+ raise ValueError(
83
+ f"{rel} is not under a community/ directory"
84
+ )
85
+ ci = parts.index("community")
86
+ model_dir = root.joinpath(*parts[:ci])
87
+
88
+ stem = os.path.splitext(src.name)[0]
89
+ ext = os.path.splitext(src.name)[1]
90
+ hfu, label_stem = _strip_username_prefix(stem)
91
+ target_stem = new_label if new_label else label_stem
92
+ target = model_dir / f"{target_stem}{ext}"
93
+
94
+ # Collision → auto-version
95
+ n = 2
96
+ base_stem = re.sub(r"_v\d+$", "", target_stem)
97
+ while target.exists():
98
+ target = model_dir / f"{base_stem}_v{n}{ext}"
99
+ n += 1
100
+
101
+ if verbose:
102
+ print(f"[curate] {rel} → {target.relative_to(root)}")
103
+ if hfu:
104
+ print(f"[curate] original_contributor = {hfu!r}")
105
+
106
+ if dry_run:
107
+ return target
108
+
109
+ # Read, update metadata, write to new location
110
+ table = pq.read_table(src)
111
+ existing = dict(table.schema.metadata or {})
112
+ existing[b"status"] = b"curated"
113
+ if hfu:
114
+ existing[b"original_contributor"] = hfu.encode()
115
+ table = table.replace_schema_metadata(existing)
116
+ pq.write_table(table, target)
117
+ src.unlink()
118
+
119
+ return target