"""Read saved source answers without calling a model service.""" from __future__ import annotations import json from pathlib import Path def read_initial_responses(path, studies): """Restore condition arrays in trajectory order and validate their coverage.""" conditions = {} for study, definition in studies.items(): for prompt in definition["prompts"]: key = prompt["condition_key"] if key in conditions: raise ValueError(f"Duplicate condition: {key}") conditions[key] = (study, prompt, {}) with Path(path).open(encoding="utf-8") as handle: for line_number, line in enumerate(handle, 1): if not line.strip(): continue row = json.loads(line) if set(row) != {"condition_key", "trajectory_index", "option_ids", "status"}: raise ValueError(f"Unexpected initial-response fields at line {line_number}") key = row["condition_key"] if key not in conditions or row["status"] != "ok": raise ValueError(f"Unknown or failed initial response at line {line_number}") _, prompt, saved = conditions[key] index, answers = row["trajectory_index"], row["option_ids"] if type(index) is not int or not 0 <= index < prompt["original_n"] or index in saved: raise ValueError(f"Invalid or duplicate trajectory index: {key}/{index}") questions = prompt["questions"] if not isinstance(answers, list) or len(answers) != len(questions): raise ValueError(f"Wrong initial-response width: {key}/{index}") for value, question in zip(answers, questions): if type(value) is not int or value not in {option["id"] for option in question["options"]}: raise ValueError(f"Invalid initial-response option: {key}/{index}") saved[index] = answers result = {study: {} for study in studies} for key, (study, prompt, saved) in conditions.items(): if len(saved) != prompt["original_n"]: raise ValueError(f"Incomplete initial responses: {key}") result[study][key] = [saved[index] for index in range(prompt["original_n"])] return result def read_model_responses(path, studies, *, workbooks=None): """Read derived model arrays and use the separately archived Chiron answers.""" path = Path(path) if workbooks is not None: readout = Path(__file__).resolve().parents[2] / "data/raw/population/source_readout.json" return read_workbook_responses(workbooks, studies, path.with_name("initial_responses.jsonl"), readout) responses = {} with path.open(encoding="utf-8") as handle: for line in handle: if not line.strip(): continue row = json.loads(line) study = row["study"] if study in responses: raise ValueError(f"Duplicate model-response study: {study}") responses[study] = row["sources"] if responses.keys() != studies.keys(): raise ValueError("Model-response coverage does not match the study definitions") initial = read_initial_responses(path.with_name("initial_responses.jsonl"), studies) for study, values in responses.items(): if values.get("Chiron") != initial[study]: raise ValueError(f"Derived Chiron answers disagree with the saved responses: {study}") values["Chiron"] = initial[study] return responses class WorkbookSource: """Read the provider's relative workbook paths from a directory or ZIP.""" def __init__(self, path): from collections import OrderedDict from zipfile import ZipFile self.path = Path(path) self.archive = None if self.path.is_dir() else ZipFile(self.path) self.names = (None if self.archive is None else set(self.archive.namelist())) self.cache = OrderedDict() def close(self): if self.archive is not None: self.archive.close() def api_path(self, model, study, condition): prefix = f"01 LLM API Calls/output/{model}/{study}_{condition}_" if self.archive is None: matches = [str(p.relative_to(self.path)) for p in self.path.glob(prefix + "*.xlsx")] else: matches = [p for p in self.names if p.startswith(prefix) and p.endswith(".xlsx")] if len(matches) != 1: raise ValueError(f"Expected one API workbook: {model}/{study}/{condition}; found {len(matches)}") return matches[0] def rows(self, relative): from io import BytesIO from openpyxl import load_workbook relative = str(relative) if Path(relative).is_absolute() or ".." in Path(relative).parts: raise ValueError(f"Workbook path must be relative: {relative}") if relative not in self.cache: source = self.path / relative if self.archive is None else BytesIO(self.archive.read(relative)) book = load_workbook(source, read_only=True, data_only=True) try: iterator = book[book.sheetnames[0]].iter_rows(values_only=True) headers = [str(v).strip() if v is not None else "" for v in next(iterator)] if len({v for v in headers if v}) != sum(bool(v) for v in headers): raise ValueError(f"Duplicate workbook columns: {relative}") self.cache[relative] = ({v: i for i, v in enumerate(headers) if v}, list(iterator)) finally: book.close() if len(self.cache) > 12: self.cache.popitem(last=False) else: self.cache.move_to_end(relative) return self.cache[relative] def _option_id(question, value, tolerance=1e-8): import math if value is None or isinstance(value, bool): raise ValueError(f"Invalid response value: {value!r}") number = float(value) matches = [int(option["id"]) for option in question["options"] if math.isclose(float(option["analysis_value"]), number, rel_tol=0., abs_tol=tolerance)] if not math.isfinite(number) or len(matches) != 1: raise ValueError(f"Response does not identify one option: {value!r}") return matches[0] def _label_patterns(question): text = " ".join(str(o.get("text") or "") for o in question["options"]).lower() for key, patterns in (("authentic", ["authentic", "authenticity"]), ("sincere", ["sincere", "sincerity"]), ("genuine", ["genuine", "genuineness"])): if key in text: return patterns return [] def _free_text_option(question, value): import re labels = _label_patterns(question) if not labels or not isinstance(value, str): raise ValueError("No parsed response or supported source label") label = "(?:" + "|".join(labels) + ")" patterns = [ rf"(?is)\b{label}\b.{{0,220}}?\brating\b\s*[:=]?\s*\**([1-7])(?:\s*/\s*7)?", rf"(?is)\b{label}\b\s+(?:rating|score)\s*[:=]?\s*\**([1-7])(?:\s*/\s*7)?", rf"(?is)\b{label}\b\s*[:=(\-]\s*(?:rating\s*[:=]?\s*)?\**([1-7])(?:\s*/\s*7)?", ] matches = [(m.end() - m.start(), m.start(), int(m.group(1))) for pattern in patterns for m in re.finditer(pattern, value)] if not matches: raise ValueError("Source model response has no unambiguous rating") return _option_id(question, min(matches)[2]) def _api_answers(source, path, questions, n): import re index, rows = source.rows(path) lowered = {name.lower(): position for name, position in index.items()} positions = [] for question in questions: column = question["source_column"] match = re.fullmatch(r"item_?(\d+)(?:_1)?", column, flags=re.IGNORECASE) aliases = [column] if match: item = int(match.group(1)) aliases += [f"item{item}", f"item_{item}", f"item{item}_1", f"item_{item}_1"] found = {lowered[a.lower()] for a in aliases if a.lower() in lowered} positions.append(next(iter(found)) if len(found) == 1 else None) model = Path(path).parent.name output_column = next((i for key, i in index.items() if key.lower() == model.lower()), None) if None in positions and (output_column is None or not all(_label_patterns(q) for q in questions)): raise ValueError(f"Missing reviewed API response columns: {path}") answers = [] for row in rows: try: values = [_option_id(q, row[i]) if i is not None else _free_text_option(q, row[output_column]) for q, i in zip(questions, positions)] except (TypeError, ValueError, IndexError): continue answers.append(values) if len(answers) == n: break if len(answers) != n: raise ValueError(f"Incomplete valid API responses: {path}: {len(answers)} != {n}") return answers def _first_n_answers(source, path, questions, n, spec): import math index, rows = source.rows(path) if len(rows) < n: raise ValueError(f"Incomplete first-N API responses: {path}") allowed = set(spec["allowed_projection_questions"]) answers = [] for row in rows[:n]: values = [] for question in questions: value = row[index[question["source_column"]]] try: answer = _option_id(question, value, 1e-9) except (TypeError, ValueError): if question["prediction_id"] not in allowed: raise ValueError(f"Unapproved invalid API response: {path}/{question['prediction_id']}") if isinstance(value, bool) or not math.isfinite(float(value)): raise ValueError(f"Nonfinite or boolean API response: {path}/{question['prediction_id']}") ranked = sorted(question["options"], key=lambda o: (abs(float(o["analysis_value"]) - float(value)), int(o["id"]))) answer = int(ranked[0]["id"]) values.append(answer) answers.append(values) return answers def _model_spec(spec, model): models = {"gpt", "claude", "deepseek"} return {key: value[model] if isinstance(value, dict) and set(value) >= models else value for key, value in spec.items()} def _released_rows(source, spec, model): import math import re from collections import defaultdict path = spec["released_tables"][model] spec = _model_spec(spec, model) index, rows = source.rows(path) method = spec.get("released_condition_from_id") or "leading_condition_id" id_column = spec.get("released_id_column") columns = spec["released_analysis_columns"] transforms = spec.get("released_analysis_value_transforms") or [None] * len(columns) if len(transforms) != len(columns): raise ValueError(f"Response transform count disagrees with columns: {path}") missing_allowed = set(spec.get("released_allow_missing_columns") or []) result = defaultdict(list) for excel_row, row in enumerate(rows, 2): row_id = str(row[index[id_column]]).strip() if id_column is not None else f"row{excel_row}" if method == "leading_condition_id": match = re.fullmatch(r"([^0-9]+)([0-9]+)", row_id) if not match: if spec.get("released_skip_invalid_rows"): continue raise ValueError(f"Unsupported released row ID: {path}/{row_id}") condition, ordinal = match.group(1), int(match.group(2)) else: raw_condition = row[index[spec["released_condition_column"]]] if method == "leading_group_label": match = re.match(r"([^:]+):", str(raw_condition).strip()) if not match: raise ValueError(f"Unsupported condition label: {path}/{raw_condition}") condition = match.group(1).strip() elif method == "column_value_map": lookup = {str(k): str(v) for k, v in spec["released_condition_value_map"].items()} keys = [str(raw_condition)] if isinstance(raw_condition, (int, float)) and float(raw_condition).is_integer(): keys.append(str(int(raw_condition))) found = {lookup[k] for k in keys if k in lookup} if len(found) != 1: raise ValueError(f"Unmapped condition: {path}/{raw_condition}") condition = next(iter(found)) else: raise ValueError(f"Unsupported condition method: {method}") number = re.search(r"([0-9]+)$", row_id) ordinal = int(number.group(1)) if number else excel_row values = [] for column, transform in zip(columns, transforms): if column is None: values.append(None) continue raw = row[index[column]] try: number = float(raw) if isinstance(raw, bool): raise ValueError("Boolean response") if transform is not None: number = float(transform.get("intercept", 0.)) + float(transform.get("coefficient", 1.)) * number if not math.isfinite(number) or not number.is_integer(): raise ValueError("Noninteger released response") values.append(int(number)) except (TypeError, ValueError): if column not in missing_allowed or (raw is not None and str(raw).strip()): raise ValueError(f"Invalid released value: {path}/{excel_row}/{column}") values.append(None) targets = {c["column"]: float(row[index[c["column"]]]) for c in spec.get("released_composite_constraints") or []} result[condition].append((ordinal, values, targets)) for condition in result: result[condition].sort(key=lambda row: row[0]) return result, spec def _released_answers(rows, questions, baseline, spec): import math from itertools import product if len(rows) != len(baseline): raise ValueError("Released response count disagrees with condition sample size") result = [] question_index = {q["prediction_id"]: i for i, q in enumerate(questions)} for (_, values, targets), original in zip(rows, baseline): if len(values) != len(questions): raise ValueError("Released column count disagrees with the questionnaire") answers = [] for question, value, old in zip(questions, values, original): if value is None: answer = old else: try: answer = _option_id(question, value, 1e-9) except ValueError: if not spec.get("released_out_of_range_fallback"): raise answer = old answers.append(answer) for constraint in spec.get("released_composite_constraints") or []: indices = [question_index[key] for key in constraint["question_ids"]] selected_questions = [questions[i] for i in indices] old_ids = [original[i] for i in indices] old_values = [next(float(o["analysis_value"]) for o in q["options"] if o["id"] == i) for q, i in zip(selected_questions, old_ids)] feasible = [] if constraint.get("aggregation", "mean") != "mean": raise ValueError("Unsupported released composite aggregation") for options in product(*(q["options"] for q in selected_questions)): values = [float(o["analysis_value"]) for o in options] average = sum(values) / len(values) if constraint.get("reported_decimals") is not None: average = round(average, int(constraint["reported_decimals"])) if math.isclose(average, targets[constraint["column"]], rel_tol=0., abs_tol=1e-9): feasible.append((sum(o["id"] != i for o, i in zip(options, old_ids)), sum(abs(v - old) for v, old in zip(values, old_values)), tuple(int(o["id"]) for o in options))) if not feasible: raise ValueError("Released composite has no feasible option tuple") for index, value in zip(indices, min(feasible)[2]): answers[index] = value result.append(answers) return result def read_workbook_responses(path, studies, initial_path, readout_path): """Restore source-paper model arrays using recorded item/column mappings.""" rules = json.loads(Path(readout_path).read_text(encoding="utf-8")) initial = read_initial_responses(initial_path, studies) source = WorkbookSource(path) result = {} try: for study, definition in studies.items(): spec = rules["studies"].get(study) released = {} if spec: for model in spec.get("released_override_models") or ("gpt", "claude", "deepseek"): released[model] = _released_rows(source, spec, model) sources = {"gpt": {}, "Chiron": initial[study], "deepseek": {}, "claude": {}} recovery = rules["api_row_recovery"].get(study, {}).get("models", {}) for prompt in definition["prompts"]: key, questions, n = prompt["condition_key"], prompt["questions"], prompt["original_n"] for model in ("gpt", "deepseek", "claude"): workbook = source.api_path(model, study, prompt["condition_id"]) answers = _api_answers(source, workbook, questions, n) if model in recovery: answers = _first_n_answers(source, workbook, questions, n, recovery[model]) if model in released: rows, model_spec = released[model] answers = _released_answers(rows[prompt["condition_id"]], questions, answers, model_spec) sources[model][key] = answers result[study] = sources finally: source.close() return result