File size: 7,027 Bytes
1b86964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""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"<tr\b[^>]*>(.*?)</tr>", source, re.I | re.S):
            cells = re.findall(r"<td\b[^>]*>(.*?)</td>", 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