|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Build JSON data file for the interactive SDRF builder UI. |
| 3 | +
|
| 4 | +Compiles YAML template definitions into a single JSON file containing |
| 5 | +resolved templates, combination rules, and term definitions. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + python3 build_sdrf_builder_data.py <sdrf-templates-dir> <output-json-path> |
| 9 | +""" |
| 10 | + |
| 11 | +import csv |
| 12 | +import json |
| 13 | +import sys |
| 14 | +from pathlib import Path |
| 15 | +from typing import Any |
| 16 | + |
| 17 | +sys.path.insert(0, str(Path(__file__).parent)) |
| 18 | +from resolve_templates import resolve_all |
| 19 | + |
| 20 | +# Fallback example values for well-known column names |
| 21 | +FALLBACK_EXAMPLES: dict[str, str] = { |
| 22 | + "source name": "sample_1", |
| 23 | + "assay name": "run_1", |
| 24 | + "comment[data file]": "sample1.raw", |
| 25 | + "comment[fraction identifier]": "1", |
| 26 | + "comment[technical replicate]": "1", |
| 27 | + "comment[label]": "label free sample", |
| 28 | +} |
| 29 | + |
| 30 | + |
| 31 | +def _compact_validators(validators: list[dict] | None) -> list[dict]: |
| 32 | + """Return a compact representation of validators.""" |
| 33 | + if not validators: |
| 34 | + return [] |
| 35 | + result = [] |
| 36 | + for v in validators: |
| 37 | + compact: dict[str, Any] = {"type": v.get("validator_name", "")} |
| 38 | + params = v.get("params", {}) |
| 39 | + if params: |
| 40 | + compact["params"] = params |
| 41 | + result.append(compact) |
| 42 | + return result |
| 43 | + |
| 44 | + |
| 45 | +def _example_value(column: dict) -> str: |
| 46 | + """Derive an example value for a column from validators or fallbacks.""" |
| 47 | + validators = column.get("validators") or [] |
| 48 | + for v in validators: |
| 49 | + params = v.get("params", {}) |
| 50 | + if params.get("examples"): |
| 51 | + return str(params["examples"][0]) |
| 52 | + if params.get("values"): |
| 53 | + return str(params["values"][0]) |
| 54 | + return FALLBACK_EXAMPLES.get(column.get("name", ""), "") |
| 55 | + |
| 56 | + |
| 57 | +def _serialize_column(col: dict) -> dict: |
| 58 | + """Serialize a single column dict for JSON output.""" |
| 59 | + return { |
| 60 | + "name": col.get("name", ""), |
| 61 | + "requirement": col.get("requirement", "optional"), |
| 62 | + "description": col.get("description", ""), |
| 63 | + "ontology_accession": col.get("ontology_accession", ""), |
| 64 | + "cardinality": col.get("cardinality", "single"), |
| 65 | + "allow_not_applicable": col.get("allow_not_applicable", False), |
| 66 | + "allow_not_available": col.get("allow_not_available", False), |
| 67 | + "source_template": col.get("source_template", ""), |
| 68 | + "validators": _compact_validators(col.get("validators")), |
| 69 | + "example_value": _example_value(col), |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | +def _extract_combination_rules( |
| 74 | + all_templates: dict[str, dict], |
| 75 | +) -> dict[str, Any]: |
| 76 | + """Extract combination rules from all resolved templates.""" |
| 77 | + # Deduplicate mutually_exclusive groups (stored as frozensets) |
| 78 | + exclusive_groups: set[frozenset[str]] = set() |
| 79 | + requires: dict[str, list[str]] = {} |
| 80 | + excludes: dict[str, list[str]] = {} |
| 81 | + |
| 82 | + for name, tpl in all_templates.items(): |
| 83 | + me = tpl.get("mutually_exclusive_with") or [] |
| 84 | + if me: |
| 85 | + group = frozenset([name] + list(me)) |
| 86 | + exclusive_groups.add(group) |
| 87 | + |
| 88 | + req = tpl.get("requires") |
| 89 | + if req: |
| 90 | + requires[name] = list(req) if isinstance(req, list) else [req] |
| 91 | + |
| 92 | + exc = tpl.get("excludes") |
| 93 | + if exc: |
| 94 | + excludes[name] = list(exc) if isinstance(exc, list) else [exc] |
| 95 | + |
| 96 | + return { |
| 97 | + "mutually_exclusive": [sorted(g) for g in exclusive_groups], |
| 98 | + "requires": requires, |
| 99 | + "excludes": excludes, |
| 100 | + } |
| 101 | + |
| 102 | + |
| 103 | +def _load_terms(repo_root: Path) -> list[dict]: |
| 104 | + """Load sdrf-terms.tsv from known locations.""" |
| 105 | + candidates = [ |
| 106 | + repo_root / "sdrf-proteomics" / "metadata-guidelines" / "sdrf-terms.tsv", |
| 107 | + repo_root / "local-info" / "demo_web" / "sdrf-terms.tsv", |
| 108 | + ] |
| 109 | + terms_path = None |
| 110 | + for p in candidates: |
| 111 | + if p.exists(): |
| 112 | + terms_path = p |
| 113 | + break |
| 114 | + |
| 115 | + if terms_path is None: |
| 116 | + print("Warning: sdrf-terms.tsv not found, terms list will be empty.") |
| 117 | + return [] |
| 118 | + |
| 119 | + terms: list[dict] = [] |
| 120 | + with open(terms_path, newline="") as f: |
| 121 | + reader = csv.DictReader(f, delimiter="\t") |
| 122 | + for row in reader: |
| 123 | + terms.append( |
| 124 | + { |
| 125 | + "term": row.get("term", ""), |
| 126 | + "type": row.get("type", ""), |
| 127 | + "description": row.get("description", ""), |
| 128 | + "values": row.get("values", ""), |
| 129 | + "ontology_accession": row.get("ontology_term_accession", ""), |
| 130 | + "allow_not_available": row.get("allow_not_available", "false") |
| 131 | + == "true", |
| 132 | + "allow_not_applicable": row.get("allow_not_applicable", "false") |
| 133 | + == "true", |
| 134 | + } |
| 135 | + ) |
| 136 | + print(f"Loaded {len(terms)} terms from {terms_path}") |
| 137 | + return terms |
| 138 | + |
| 139 | + |
| 140 | +def main() -> None: |
| 141 | + if len(sys.argv) < 3: |
| 142 | + print( |
| 143 | + "Usage: python3 build_sdrf_builder_data.py " |
| 144 | + "<sdrf-templates-dir> <output-json-path>" |
| 145 | + ) |
| 146 | + sys.exit(1) |
| 147 | + |
| 148 | + templates_dir = Path(sys.argv[1]) |
| 149 | + output_path = Path(sys.argv[2]) |
| 150 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 151 | + |
| 152 | + repo_root = Path(__file__).resolve().parent.parent |
| 153 | + |
| 154 | + # Resolve all templates |
| 155 | + all_templates = resolve_all(templates_dir) |
| 156 | + print(f"Resolved {len(all_templates)} templates") |
| 157 | + |
| 158 | + # Serialize templates |
| 159 | + templates_json: dict[str, dict] = {} |
| 160 | + for name, tpl in all_templates.items(): |
| 161 | + templates_json[name] = { |
| 162 | + "description": tpl.get("description", ""), |
| 163 | + "layer": tpl.get("layer"), |
| 164 | + "usable_alone": tpl.get("usable_alone", False), |
| 165 | + "extends": tpl.get("extends"), |
| 166 | + "inheritance_chain": tpl.get("inheritance_chain", []), |
| 167 | + "columns": [_serialize_column(c) for c in tpl["all_columns"]], |
| 168 | + "own_columns": [_serialize_column(c) for c in tpl["own_columns"]], |
| 169 | + } |
| 170 | + |
| 171 | + # Extract combination rules |
| 172 | + combination_rules = _extract_combination_rules(all_templates) |
| 173 | + |
| 174 | + # Load terms |
| 175 | + terms = _load_terms(repo_root) |
| 176 | + |
| 177 | + # Write output |
| 178 | + output = { |
| 179 | + "templates": templates_json, |
| 180 | + "combination_rules": combination_rules, |
| 181 | + "terms": terms, |
| 182 | + } |
| 183 | + with open(output_path, "w") as f: |
| 184 | + json.dump(output, f, indent=2) |
| 185 | + |
| 186 | + print(f"Wrote builder data to {output_path}") |
| 187 | + |
| 188 | + |
| 189 | +if __name__ == "__main__": |
| 190 | + main() |
0 commit comments