"""Read locally obtained OpenPsychometrics item text without copying it into configs. The domain builders retain item order, response wording and sampling policy in config.yaml. Text comes from the matching official codebook, entirely offline. """ from __future__ import annotations import copy import html import re from pathlib import Path from typing import Any _SCALES = { "AS+SC+AD+DO", "BIG5", "CFCS", "DASS", "ECR", "FTI", "HBDS", "HEXACO", "HSNS+DD", "HSQ", "IPIP-FFM", "MACH", "NPAS", "NPI", "NR-6", "OSRI44", "PWE", "RIASEC", "RSE", "SD3", } _NO_FINAL_PERIOD = {"FTI", "HBDS", "HEXACO", "HSNS+DD", "HSQ", "IPIP-FFM"} _ANSWER_SUFFIX = {"DASS", "FTI", "MACH", "NR-6", "PWE"} def _read_codebook(path: Path, scale: str) -> dict[str, str]: if not path.is_file(): raise FileNotFoundError(f"Missing {scale} codebook: {path}. Obtain the matching official archive listed in the domain SOURCE.md.") # These official ZIP codebooks use Windows-1252; the other supported # archives provide UTF-8 text. Decode the originals without replacement. encoding = "cp1252" if scale in {"HSQ", "SD3", "HSNS+DD"} else "utf-8" source = path.read_text(encoding=encoding) entries: dict[str, str] = {} def add(code: str, text: str) -> None: text = text.strip() if code in entries and entries[code] != text: raise ValueError(f"Conflicting item {code!r} in codebook: {path}") entries[code] = text if scale == "ECR": for row in re.findall(r"]*>(.*?)", source, re.I | re.S): cells = re.findall(r"]*>(.*?)", row, re.I | re.S) if len(cells) < 3: continue cells = [html.unescape(re.sub(r"<[^>]+>", "", x)).strip() for x in cells] match = re.match(r'"(.*?)" rated', cells[2], re.S) if match: add(cells[0], match.group(1)) else: for line in source.splitlines(): match = re.match(r"\s*([A-Za-z]+\d+[A-Za-z]?|nerdy)[.\s:]+(.+)", line) if match: add(match.group(1), match.group(2)) match = re.match(r"\s*['\"]([A-Za-z]+\d+)['\"]\s*:\s*(['\"])(.*?)\2\s*,?\s*$", line) if match: add(match.group(1), match.group(3)) return entries def _item_text(scale: str, code: str, entries: dict[str, str]) -> str: source_code = code[:-1] if scale in _ANSWER_SUFFIX and re.fullmatch(r"Q\d+A", code) else code if source_code not in entries: raise ValueError(f"{scale}: codebook is missing item {source_code!r} required by {code!r}") text = html.unescape(entries[source_code]) if not text.strip(): raise ValueError(f"{scale}: empty codebook item {source_code!r}") if scale == "AS+SC+AD+DO": text = ("I am " if code == "AD3" else "I ") + text[:1].lower() + text[1:] elif code.startswith("TIPI") or (scale == "NPAS" and code == "nerdy"): text = "I see myself as " + text[:1].lower() + text[1:] if code == "nerdy": text += "." if scale == "HSQ": text = text.replace("\u2019", "'") if code in {"Q5", "Q30"}: text = re.sub(r"\s*[—–]\s*", "—", text) elif scale == "SD3": text = text.replace("\u2019", "'") elif scale == "PWE" and code == "Q6A": text = text.replace("\u2019", "'") return text.rstrip(".") if scale in _NO_FINAL_PERIOD else text def _item_pair(scale: str, code: str, entries: dict[str, str]) -> dict[int, str]: if code not in entries: raise ValueError(f"{scale}: codebook is missing forced-choice item {code!r}") match = re.fullmatch(r"1\s*=\s*(.*?)\s+2\s*=\s*(.*)", entries[code]) if match is None: raise ValueError(f"{scale}: invalid two-option codebook item {code!r}") values = [html.unescape(text.strip()) for text in match.groups()] if scale == "FTI": values = [text.rstrip(".") for text in values] if not all(values): raise ValueError(f"{scale}: empty option in codebook item {code!r}") return dict(enumerate(values, 1)) def _item_ids(value: Any, scale: str) -> list[str]: if not isinstance(value, list) or not value or any(not isinstance(x, str) or not x for x in value): raise ValueError(f"{scale}: item IDs must be a nonempty list of strings") if len(value) != len(set(value)): raise ValueError(f"{scale}: duplicate item IDs") return value def load_item_texts(config: dict[str, Any], config_path: Path) -> dict[str, Any]: """Return the builder's text-bearing config, preserving every item order. Missing inputs/items and copied inline text are errors; no remote request, text fallback, output file, or change to the caller's configuration is made. """ scale = config["meta"]["name"] if scale not in _SCALES: raise ValueError(f"Unsupported OpenPsychometrics codebook scale: {scale!r}") items = config["items"] codebook = items.get("codebook") if not isinstance(codebook, str) or not codebook: raise ValueError(f"{scale}: items.codebook must name a local codebook file") path = (Path(config_path).resolve().parent / codebook).resolve() entries = _read_codebook(path, scale) restored = copy.deepcopy(config) rebuilt: dict[str, Any] = {} for key, value in restored["items"].items(): if key == "codebook": continue if key == "texts": raise ValueError(f"{scale}: use item_ids instead of inline questionnaire text") if key == "item_ids": rebuilt["texts"] = {code: _item_text(scale, code, entries) for code in _item_ids(value, scale)} elif key == "item_groups": groups = {} for name, group in value.items(): updated = {} for field, content in group.items(): if field in {"item_texts", "item_specific_texts"}: raise ValueError(f"{scale}: use choice_item_ids instead of inline group text") if field == "choice_item_ids": codes = _item_ids(content, scale) if codes != group["items"]: raise ValueError(f"{scale}: forced-choice item IDs must match the group's item order") updated["item_specific_texts"] = {code: _item_pair(scale, code, entries) for code in codes} else: updated[field] = content groups[name] = updated rebuilt[key] = groups else: rebuilt[key] = value for name, group in rebuilt.get("item_groups", {}).items(): available = set(rebuilt.get("texts", {})) | set(group.get("item_specific_texts", {})) missing = [code for code in group["items"] if code not in available] if missing: raise ValueError(f"{scale}: unresolved items in group {name!r}: {missing}") restored["items"] = rebuilt return restored