import json import hashlib import math import os import random import re import shutil import sys import threading import time from datetime import datetime from functools import wraps from html import escape from pathlib import Path from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit from flask import g, has_request_context, jsonify, make_response, redirect, request, send_from_directory, session from potato import flask_server from potato.phase import UserPhase from potato.user_state_management import InMemoryUserState _configure_app = flask_server.configure_app _load_all_data = flask_server.load_all_data _original_has_remaining_assignments = InMemoryUserState.has_remaining_assignments _original_add_label_annotation = InMemoryUserState.add_label_annotation MATHVISION_IMAGE_ROUTE = "/mathvision_images" MATHVISION_IMAGE_DIR = Path(__file__).resolve().parent / "my-annotation-task" / "images" / "mathvision" HF_USER_PARAM = "hf_user" PROLIFIC_PID_PARAM = "PROLIFIC_PID" PROLIFIC_STUDY_PARAM = "STUDY_ID" PROLIFIC_SESSION_PARAM = "SESSION_ID" SUBSET_ID_PARAM = "subset_id" FOLLOWUP_MODE_ENV = "FOLLOWUP_MODE" FOLLOWUP_PARTICIPANT_ENV = "FOLLOWUP_PARTICIPANT_ID" FOLLOWUP_SUBSET_ENV = "FOLLOWUP_SUBSET_ID" FOLLOWUP_ROUND_ENV = "FOLLOWUP_ROUND_ID" FOLLOWUP_USER_MARKER = "__tte_followup_" # Continuation rounds: a participant who completed a subset can open the Space # again with ROUND=2, 3, ... (e.g. from a follow-up Prolific study) and gets a # new subset that shares no dialogue with the ones they already did. CONTINUATION_ROUND_PARAM = "ROUND" CONTINUATION_USER_MARKER = "__tte_round" CONTINUATION_USER_PATTERN = re.compile(rf"^(.+){re.escape(CONTINUATION_USER_MARKER)}(\d+)$") SUBSET_ASSIGNMENT_FILE = "subset_assignment.json" SUBSET_SLOTS_FILE = "subset_slots.json" SUBSET_MANIFEST_CACHE = {} SUBSET_SLOT_LOCK = threading.Lock() SUBSET_ACTIVE_SLOT_STATUSES = {"reserved", "completed"} SUBSET_TERMINAL_SLOT_STATUSES = {"failed"} ANNOTATION_OUTPUT_RESTORE_DONE = False USER_OUTPUT_RESTORE_ATTEMPTED = set() TESTING_GATE_MIN_WEIGHTED_ACCURACY = float( os.environ.get("TESTING_GATE_MIN_WEIGHTED_ACCURACY", os.environ.get("TESTING_GATE_MIN_ACCURACY", "0.70")) ) TESTING_GATE_MAX_WEIGHTED_MISTAKE_RATE = float( os.environ.get("TESTING_GATE_MAX_WEIGHTED_MISTAKE_RATE", "0.30") ) TESTING_GATE_MAX_SERIOUS_MISTAKE_RATE = float( os.environ.get("TESTING_GATE_MAX_SERIOUS_MISTAKE_RATE", "0.30") ) TESTING_GATE_SERIOUS_MISTAKE_WEIGHT = float(os.environ.get("TESTING_GATE_SERIOUS_MISTAKE_WEIGHT", "1.0")) TESTING_GATE_TSE_MISTAKE_WEIGHT = float(os.environ.get("TESTING_GATE_TSE_MISTAKE_WEIGHT", "0.5")) TESTING_GATE_POLICY_VERSION = os.environ.get("TESTING_GATE_POLICY_VERSION", "weighted_70_30_v1") TESTING_GATE_FILE = "testing_gate.json" TESTING_GATE_VALID_LABELS = {"Yes", "To some extent", "No"} CONTROL_GATE_MAX_WEIGHTED_MISTAKE_RATE = float( os.environ.get("CONTROL_GATE_MAX_WEIGHTED_MISTAKE_RATE", os.environ.get("CONTROL_GATE_MAX_MISTAKE_RATE", "0.30")) ) CONTROL_GATE_SERIOUS_MISTAKE_WEIGHT = float(os.environ.get("CONTROL_GATE_SERIOUS_MISTAKE_WEIGHT", "1.0")) CONTROL_GATE_TSE_MISTAKE_WEIGHT = float(os.environ.get("CONTROL_GATE_TSE_MISTAKE_WEIGHT", "0.5")) CONTROL_GATE_POLICY_VERSION = os.environ.get("CONTROL_GATE_POLICY_VERSION", "two_control_weighted_30_percent_v1") CONTROL_GATE_FILE = "control_gate.json" TIME_GATE_MIN_SECONDS = float(os.environ.get("TIME_GATE_MIN_SECONDS", "20")) TIME_GATE_MAX_FAST_INSTANCES = int(os.environ.get("TIME_GATE_MAX_FAST_INSTANCES", "3")) TIME_GATE_POLICY_VERSION = os.environ.get( "TIME_GATE_POLICY_VERSION", "navigation_start_20s_v1", ) TIME_GATE_FILE = "time_gate.json" TIME_GATE_LOCK = threading.RLock() TSE_PATTERN_GATE_FILE = "tse_pattern_gate.json" TSE_PATTERN_GATE_POLICY_VERSION = os.environ.get( "TSE_PATTERN_GATE_POLICY_VERSION", "two_consecutive_all_tse_v1", ) TSE_PATTERN_GATE_CONSECUTIVE_INSTANCES = int( os.environ.get("TSE_PATTERN_GATE_CONSECUTIVE_INSTANCES", "2") ) TSE_PATTERN_GATE_LOCK = threading.RLock() PROLIFIC_COMPLETION_FILE = "prolific_completion.json" PROLIFIC_COMPLETION_BASE_URL = "https://app.prolific.com/submissions/complete" PROLIFIC_COMPLETION_OUTCOMES = { "success", "failed_test", } NONBLOCKING_QUALITY_REASONS = { "control_gate_failed", "time_gate_failed", "tse_pattern_gate_failed", } TESTING_GATE_FAILED_TITLE = "Sorry, you haven't passed the test" TESTING_GATE_FAILED_MESSAGE = ( "As you didn't get the scores needed, we are sorry to say that you can't proceed with annotation." ) TIME_GATE_FAILED_MESSAGE = "A quality flag was recorded for later review." GOLD_ANNOTATIONS_FILE = os.environ.get("GOLD_ANNOTATIONS_FILE", "gold_annotations.json") GOLD_ANNOTATIONS_CACHE = {} VERIFIED_REMOTE_GOLD_PATHS = set() PARTICIPANT_EXPORT_LOCK = threading.Lock() def _write_json_atomic(path, payload): """Atomically write JSON without sharing a temp file across requests.""" path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name( f".{path.name}.{os.getpid()}.{threading.get_ident()}.{time.time_ns()}.tmp" ) try: with tmp.open("w", encoding="utf-8") as handle: json.dump(payload, handle, indent=2, ensure_ascii=False) # On Windows the replace fails while another request is reading the # target file; retry briefly instead of losing the write. for attempt in range(20): try: tmp.replace(path) break except PermissionError: if attempt == 19: raise time.sleep(0.05) finally: if tmp.exists(): tmp.unlink() def _json_safe_value(value): if isinstance(value, float) and not math.isfinite(value): return None if isinstance(value, dict): return {key: _json_safe_value(item) for key, item in value.items()} if isinstance(value, list): return [_json_safe_value(item) for item in value] if isinstance(value, tuple): return tuple(_json_safe_value(item) for item in value) return value def _normalize_loaded_item_json_data(): item_manager = flask_server.get_item_state_manager() for item_id in list(getattr(item_manager, "instance_id_ordering", [])): item = item_manager.get_item(item_id) data = item.get_data() if item is not None else None if not isinstance(data, dict): continue normalized = _json_safe_value(data) data.clear() data.update(normalized) class ProlificJSONExporter: """Export annotations with participant and assignment identifiers.""" format_name = "json" description = "JSON annotations enriched with Prolific participant metadata" file_extensions = [".json"] def can_export(self, context): if not context.annotations: return False, "No annotations to export" return True, "" def export(self, context, output_path, options=None): from potato.export.base import ExportResult output_dir = Path(context.output_dir) metadata_by_user = {} records = [] for annotation in context.annotations: user_id = str(annotation.get("user_id", "")).strip() if user_id not in metadata_by_user: assignment_path = output_dir / user_id / SUBSET_ASSIGNMENT_FILE try: with assignment_path.open("r", encoding="utf-8") as handle: assignment = json.load(handle) except (OSError, ValueError, TypeError): assignment = {} metadata_by_user[user_id] = assignment if isinstance(assignment, dict) else {} assignment = metadata_by_user[user_id] instance_id = str(annotation.get("instance_id", "")) record = { "PROLIFIC_PID": str(assignment.get("prolific_pid", "")), "STUDY_ID": str(assignment.get("study_id", "")), "SESSION_ID": str(assignment.get("session_id", "")), "subset_id": str(assignment.get("subset_id", "")), "round_id": str(assignment.get("round_id", "")), "followup": bool(assignment.get("followup_mode", False)), "item_id": instance_id, "id": instance_id, } record.update(annotation) records.append(record) export_dir = Path(output_path) export_file = export_dir / "annotations.json" tmp_file = export_file.with_suffix(".json.tmp") with PARTICIPANT_EXPORT_LOCK: export_dir.mkdir(parents=True, exist_ok=True) try: with tmp_file.open("w", encoding="utf-8") as handle: json.dump(records, handle, indent=2, ensure_ascii=False) tmp_file.replace(export_file) finally: if tmp_file.exists(): tmp_file.unlink() return ExportResult( success=True, format_name=self.format_name, files_written=[str(export_file)], stats={"num_records": len(records)}, ) def _register_prolific_json_exporter(): from potato.export.registry import export_registry existing = export_registry.get(ProlificJSONExporter.format_name) if existing is None: export_registry.register(ProlificJSONExporter()) elif not isinstance(existing, ProlificJSONExporter): export_registry._exporters[ProlificJSONExporter.format_name] = ProlificJSONExporter() def _routes_module(): return sys.modules.get("routes") def _clean_user(value): if value is None: return "" return str(value).strip()[:200] def _truthy(value): return str(value).strip().lower() in {"1", "true", "yes", "y"} def _followup_mode_enabled(): return _truthy(os.environ.get(FOLLOWUP_MODE_ENV, "")) def _followup_participant_id(): return _clean_user(os.environ.get(FOLLOWUP_PARTICIPANT_ENV, "")) def _followup_subset_id(): return _clean_user(os.environ.get(FOLLOWUP_SUBSET_ENV, "")) def _followup_round_id(): return _clean_user(os.environ.get(FOLLOWUP_ROUND_ENV, "")) def _followup_round_token(): token = "".join( character if character.isalnum() or character in {"-", "_"} else "_" for character in _followup_round_id() ).strip("_") return token[:60] def _followup_internal_user(): participant_id = _followup_participant_id() round_token = _followup_round_token() if not participant_id or not round_token: return "" return _clean_user(f"{participant_id}{FOLLOWUP_USER_MARKER}{round_token}") def _continuation_context(user="", prolific_pid=""): """Context for round 2+ of a participant, or None for their first round. The round comes from the ROUND URL parameter on the first visit; afterwards the internal user name (__tte_round) carries it. """ raw_user = _clean_user(user) match = CONTINUATION_USER_PATTERN.match(raw_user) if match: target_pid, round_number = match.group(1), int(match.group(2)) else: raw_round = _request_value(CONTINUATION_ROUND_PARAM, "round") if has_request_context() else "" round_number = int(raw_round) if raw_round.isdigit() else 1 target_pid = _clean_user(prolific_pid) or raw_user if round_number < 2 or not target_pid: return None internal_user = _clean_user(f"{target_pid}{CONTINUATION_USER_MARKER}{round_number}") return { "followup_mode": True, "continuation": True, "round": round_number, "prolific_pid": target_pid, "participant_id": internal_user, "hf_user": internal_user, "requested_subset_id": "", "round_id": f"round{round_number}", "skip_pretest": True, } def _followup_context(user="", prolific_pid=""): if not _followup_mode_enabled(): return _continuation_context(user, prolific_pid) target_pid = _followup_participant_id() internal_user = _followup_internal_user() raw_user = _clean_user(user) raw_pid = _clean_user(prolific_pid) if not target_pid or not internal_user: return None if raw_pid == target_pid or raw_user in {target_pid, internal_user}: return { "followup_mode": True, "prolific_pid": target_pid, "participant_id": internal_user, "hf_user": internal_user, "requested_subset_id": _followup_subset_id(), "round_id": _followup_round_id(), "skip_pretest": True, } return None def _validate_followup_config(routes=None): if not _followup_mode_enabled(): return missing = [] if not _followup_participant_id(): missing.append(FOLLOWUP_PARTICIPANT_ENV) if not _followup_subset_id(): missing.append(FOLLOWUP_SUBSET_ENV) if not _followup_round_id(): missing.append(FOLLOWUP_ROUND_ENV) if missing: raise RuntimeError( "Follow-up mode is enabled but required configuration is missing: " + ", ".join(missing) ) if routes is not None and _followup_subset_id() not in _subset_ids(routes): raise RuntimeError( f"Configured follow-up subset {_followup_subset_id()!r} is not present in the subset manifest." ) def _normalize_label(value): value = "" if value is None else str(value).strip() lowered = value.lower() if lowered == "yes": return "Yes" if lowered in {"to some extent", "some extent", "partial", "partially"}: return "To some extent" if lowered == "no": return "No" return value def _task_dir(routes): return Path(routes.config.get("task_dir") or ".") def _output_dir(routes): output_dir = Path(routes.config.get("output_annotation_dir") or "annotation_output") if output_dir.is_absolute(): return output_dir return _task_dir(routes) / output_dir def _configure_persistent_memo_storage(): """Store Potato's memo database inside the privately backed-up output.""" from potato.memos import api as memos_api if getattr(memos_api, "_tte_persistent_storage", False): return original_context = memos_api._ctx def persistent_context(): task_dir, project, username, privileged, error = original_context() if error: return task_dir, project, username, privileged, error routes = _routes_module() if routes is None: return task_dir, project, username, privileged, error memo_dir = _output_dir(routes) memo_dir.mkdir(parents=True, exist_ok=True) return str(memo_dir.resolve()), project, username, privileged, None memos_api._ctx = persistent_context memos_api._tte_persistent_storage = True def _testing_gate_path(routes, user): return _output_dir(routes) / _clean_user(user) / TESTING_GATE_FILE def _control_gate_path(routes, user): return _output_dir(routes) / _clean_user(user) / CONTROL_GATE_FILE def _time_gate_path(routes, user): return _output_dir(routes) / _clean_user(user) / TIME_GATE_FILE def _tse_pattern_gate_path(routes, user): return _output_dir(routes) / _clean_user(user) / TSE_PATTERN_GATE_FILE def _subset_assignment_path(routes, user): return _output_dir(routes) / _clean_user(user) / SUBSET_ASSIGNMENT_FILE def _read_gate_decision(path): if not path.exists(): return None try: with path.open("r", encoding="utf-8") as handle: return json.load(handle) except Exception: return None def _write_gate_decision(path, decision): _write_json_atomic(path, decision) def _read_testing_gate_decision(routes, user): return _read_gate_decision(_testing_gate_path(routes, user)) def _write_testing_gate_decision(routes, user, decision): _write_gate_decision(_testing_gate_path(routes, user), decision) def _is_current_testing_gate_failure(decision): return ( isinstance(decision, dict) and decision.get("decision") == "failed" and decision.get("policy_version") == TESTING_GATE_POLICY_VERSION ) def _is_current_testing_gate_pass(decision): return ( isinstance(decision, dict) and decision.get("decision") == "passed" and decision.get("policy_version") == TESTING_GATE_POLICY_VERSION and not decision.get("inferred_from") ) def _read_control_gate_decision(routes, user): return _read_gate_decision(_control_gate_path(routes, user)) def _write_control_gate_decision(routes, user, decision): _write_gate_decision(_control_gate_path(routes, user), decision) def _is_current_control_gate_failure(decision): return ( isinstance(decision, dict) and decision.get("decision") == "failed" and decision.get("policy_version") == CONTROL_GATE_POLICY_VERSION ) def _read_tse_pattern_gate_decision(routes, user): return _read_gate_decision(_tse_pattern_gate_path(routes, user)) def _write_tse_pattern_gate_decision(routes, user, decision): _write_gate_decision(_tse_pattern_gate_path(routes, user), decision) def _is_current_tse_pattern_gate_failure(decision): return ( isinstance(decision, dict) and decision.get("decision") == "failed" and decision.get("policy_version") == TSE_PATTERN_GATE_POLICY_VERSION ) def _empty_time_gate_state(): return { "decision": "active", "ready": True, "policy_version": TIME_GATE_POLICY_VERSION, "started_at": {}, "completed": {}, "fast_instances": {}, "thresholds": { "min_seconds": TIME_GATE_MIN_SECONDS, "max_fast_instances": TIME_GATE_MAX_FAST_INSTANCES, }, } def _migrate_time_gate_threshold_state(state): migrated = _empty_time_gate_state() migrated["started_at"] = ( dict(state.get("started_at", {})) if isinstance(state.get("started_at"), dict) else {} ) completed = state.get("completed", {}) if isinstance(completed, dict): for instance_id, details in completed.items(): if not isinstance(details, dict): continue try: elapsed_seconds = max(0.0, float(details.get("elapsed_seconds"))) except (TypeError, ValueError): continue completion = dict(details) completion["elapsed_seconds"] = elapsed_seconds completion["fast"] = elapsed_seconds < TIME_GATE_MIN_SECONDS migrated["completed"][instance_id] = completion if completion["fast"]: migrated["fast_instances"][instance_id] = { "elapsed_seconds": elapsed_seconds, "completed_at": details.get("completed_at", ""), } if len(migrated["fast_instances"]) >= TIME_GATE_MAX_FAST_INSTANCES: migrated.update({ "decision": "failed", "message": TIME_GATE_FAILED_MESSAGE, "gate_type": "time_gate", "evaluated_at": _utc_now_iso(), }) migrated.update({ "migrated_from_policy_version": state.get("policy_version", ""), "migrated_from_decision": state.get("decision", ""), "migrated_at": _utc_now_iso(), }) return migrated def _read_time_gate_state(routes, user): path = _time_gate_path(routes, user) if not path.exists(): return _empty_time_gate_state() try: with path.open("r", encoding="utf-8") as handle: state = json.load(handle) except Exception: return _empty_time_gate_state() if ( isinstance(state, dict) and state.get("policy_version") == "navigation_start_v2" and state.get("policy_version") != TIME_GATE_POLICY_VERSION ): migrated = _migrate_time_gate_threshold_state(state) _write_json_atomic(path, migrated) return migrated if not isinstance(state, dict) or state.get("policy_version") != TIME_GATE_POLICY_VERSION: reset = _empty_time_gate_state() reset.update({ "invalidated_policy_version": ( state.get("policy_version", "legacy_without_version") if isinstance(state, dict) else "invalid_state" ), "invalidated_decision": state.get("decision", "") if isinstance(state, dict) else "", "invalidated_at": _utc_now_iso(), }) _write_json_atomic(path, reset) return reset base = _empty_time_gate_state() base.update(state if isinstance(state, dict) else {}) for key in ("started_at", "completed", "fast_instances"): if not isinstance(base.get(key), dict): base[key] = {} base["thresholds"] = { "min_seconds": TIME_GATE_MIN_SECONDS, "max_fast_instances": TIME_GATE_MAX_FAST_INSTANCES, } if base.get("decision") == "failed": base["message"] = _time_gate_message({"decision": "failed"}) base["gate_type"] = "time_gate" return base def _write_time_gate_state(routes, user, state): _write_json_atomic(_time_gate_path(routes, user), state) def _record_time_gate_completion(state, instance_id, elapsed_seconds, completed_at, inferred=False): elapsed_seconds = max(0.0, float(elapsed_seconds)) is_fast = elapsed_seconds < TIME_GATE_MIN_SECONDS completion = { "completed_at": completed_at, "elapsed_seconds": elapsed_seconds, "fast": is_fast, } if inferred: completion["inferred_from_next_start"] = True state["completed"][instance_id] = completion if is_fast: state["fast_instances"][instance_id] = { "elapsed_seconds": elapsed_seconds, "completed_at": completed_at, } def _apply_time_gate_threshold(routes, user, state): if len(state["fast_instances"]) < TIME_GATE_MAX_FAST_INSTANCES: return False newly_failed = state.get("decision") != "failed" state["decision"] = "failed" state["message"] = _time_gate_message({"decision": "failed"}) state["gate_type"] = "time_gate" state["evaluated_at"] = state.get("evaluated_at") or _utc_now_iso() return newly_failed def _reconcile_time_gate_state(routes, user, state=None): """Recover completions missed while fast annotation saves were still settling.""" user = _clean_user(user) if not user: return state or _empty_time_gate_state() with TIME_GATE_LOCK: state = state or _read_time_gate_state(routes, user) if state.get("decision") == "failed": return state ordered_starts = [] for instance_id, started_at in state["started_at"].items(): try: ordered_starts.append((instance_id, float(started_at))) except (TypeError, ValueError): continue ordered_starts.sort(key=lambda entry: entry[1]) changed = False for index, (instance_id, started_at) in enumerate(ordered_starts[:-1]): if instance_id in state["completed"]: continue next_started_at = ordered_starts[index + 1][1] completed_at = datetime.utcfromtimestamp(next_started_at).isoformat() + "Z" _record_time_gate_completion( state, instance_id, next_started_at - started_at, completed_at, inferred=True, ) changed = True if _apply_time_gate_threshold(routes, user, state): changed = True if changed: _write_time_gate_state(routes, user, state) return state def _gate_schemas(routes): return [ scheme.get("name") for scheme in routes.config.get("annotation_schemes", []) if scheme.get("name") and scheme.get("annotation_type") == "radio" ] def _gold_annotations_config(routes): return routes.config.get("gold_annotations", {}) or {} def _is_hugging_face_space(): return any( os.environ.get(name) for name in ( "SPACE_ID", "HF_SPACE_ID", "SPACE_AUTHOR_NAME", "SPACE_REPO_NAME", ) ) def _restore_annotation_output_from_hub_config(config): global ANNOTATION_OUTPUT_RESTORE_DONE if ANNOTATION_OUTPUT_RESTORE_DONE: return ANNOTATION_OUTPUT_RESTORE_DONE = True backup_config = config.get("huggingface_backup", {}) or {} override = os.environ.get("ANNOTATION_OUTPUT_RESTORE_ON_STARTUP") if override is None: restore_enabled = ( _truthy(backup_config.get("restore_on_startup", True)) and (_is_hugging_face_space() or _truthy(os.environ.get("ANNOTATION_OUTPUT_RESTORE_LOCALLY"))) ) else: restore_enabled = _truthy(override) if not restore_enabled: return repo_id = ( os.environ.get("ANNOTATION_OUTPUT_RESTORE_REPO_ID") or backup_config.get("repo_id") or (config.get("gold_annotations", {}) or {}).get("repo_id") ) token = backup_config.get("token") or os.environ.get("HF_TOKEN") repo_type = backup_config.get("repo_type") if not repo_id or not token: missing = [] if not repo_id: missing.append("repo_id") if not token: missing.append("HF_TOKEN") print( "WARNING: annotation output restore skipped because " f"{' and '.join(missing)} is missing.", flush=True, ) return task_dir = Path(config.get("task_dir") or ".") output_dir = Path(config.get("output_annotation_dir") or "annotation_output") if not output_dir.is_absolute(): output_dir = task_dir / output_dir output_dir.mkdir(parents=True, exist_ok=True) output_root = output_dir.resolve() overwrite = _truthy(os.environ.get("ANNOTATION_OUTPUT_RESTORE_OVERWRITE")) try: from huggingface_hub import HfApi, hf_hub_download except ImportError: print( "WARNING: annotation output restore skipped because huggingface_hub is not installed.", flush=True, ) return try: files = HfApi(token=token).list_repo_files( repo_id=repo_id, repo_type=repo_type, ) except Exception as error: print(f"WARNING: failed to list annotation backup repo {repo_id}: {error}", flush=True) return restored = 0 skipped_existing = 0 for filename in files: filename = str(filename).strip() if not filename or filename.endswith("/"): continue if filename.startswith(".") or filename in {"README.md"}: continue relative = Path(filename) parts = list(relative.parts) if parts and parts[0] == output_dir.name: parts = parts[1:] if not parts or any(part in {"", ".", ".."} for part in parts): continue target = output_dir.joinpath(*parts) try: resolved_target = target.resolve() except OSError: continue if resolved_target != output_root and output_root not in resolved_target.parents: continue if target.exists() and not overwrite: skipped_existing += 1 continue try: downloaded = Path(hf_hub_download( repo_id=repo_id, filename=filename, repo_type=repo_type, token=token, )) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(downloaded, target) restored += 1 except Exception as error: print(f"WARNING: failed to restore {filename} from {repo_id}: {error}", flush=True) print( f"Annotation output restore from {repo_id}: restored {restored} files" + (f", skipped {skipped_existing} existing files" if skipped_existing else ""), flush=True, ) def _annotation_restore_enabled_from_config(config): backup_config = config.get("huggingface_backup", {}) or {} override = os.environ.get("ANNOTATION_OUTPUT_RESTORE_ON_STARTUP") if override is not None: return _truthy(override) return ( _truthy(backup_config.get("restore_on_startup", True)) and (_is_hugging_face_space() or _truthy(os.environ.get("ANNOTATION_OUTPUT_RESTORE_LOCALLY"))) ) def _annotation_backup_repo_config(config): backup_config = config.get("huggingface_backup", {}) or {} return { "repo_id": ( os.environ.get("ANNOTATION_OUTPUT_RESTORE_REPO_ID") or backup_config.get("repo_id") or (config.get("gold_annotations", {}) or {}).get("repo_id") ), "repo_type": backup_config.get("repo_type"), "token": backup_config.get("token") or os.environ.get("HF_TOKEN"), } def _restore_user_output_from_hub(routes, user): user = _clean_user(user) if not user or not _annotation_restore_enabled_from_config(routes.config): return False if user in USER_OUTPUT_RESTORE_ATTEMPTED: return False USER_OUTPUT_RESTORE_ATTEMPTED.add(user) repo = _annotation_backup_repo_config(routes.config) if not repo.get("repo_id") or not repo.get("token"): return False try: from huggingface_hub import hf_hub_download except ImportError: return False output_dir = _output_dir(routes) user_dir = output_dir / user file_candidates = [] for filename in ( "user_state.json", SUBSET_ASSIGNMENT_FILE, TESTING_GATE_FILE, CONTROL_GATE_FILE, TIME_GATE_FILE, TSE_PATTERN_GATE_FILE, PROLIFIC_COMPLETION_FILE, ): file_candidates.extend([ (f"{user}/{filename}", user_dir / filename), (f"{output_dir.name}/{user}/{filename}", user_dir / filename), ]) file_candidates.extend([ (SUBSET_SLOTS_FILE, output_dir / SUBSET_SLOTS_FILE), (f"{output_dir.name}/{SUBSET_SLOTS_FILE}", output_dir / SUBSET_SLOTS_FILE), ]) restored = 0 seen_targets = set() for repo_filename, target in file_candidates: target_key = str(target) if target_key in seen_targets and target.exists(): continue seen_targets.add(target_key) if target.exists(): continue try: downloaded = Path(hf_hub_download( repo_id=repo["repo_id"], filename=repo_filename, repo_type=repo.get("repo_type"), token=repo["token"], )) except Exception: continue try: target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(downloaded, target) restored += 1 except Exception as error: print(f"WARNING: failed to restore {repo_filename} for {user}: {error}", flush=True) if restored: print(f"Restored {restored} backed-up files for participant {user}.", flush=True) return restored > 0 def _gold_annotations_require_remote(routes): override = os.environ.get("GOLD_ANNOTATIONS_REQUIRE_REMOTE") if override is not None: if str(override).strip().lower() in {"hf_only", "huggingface_only", "space_only"}: return _is_hugging_face_space() return _truthy(override) config = _gold_annotations_config(routes) setting = str(config.get("require_remote") or "").strip().lower() if setting in {"hf_only", "huggingface_only", "space_only"}: return _is_hugging_face_space() return _truthy(config.get("require_remote")) or _truthy(config.get("require_private_repo")) def _gold_annotations_path(routes): config = _gold_annotations_config(routes) local_path = ( os.environ.get("GOLD_ANNOTATIONS_LOCAL_PATH") or config.get("local_path") or f"annotation_output/{GOLD_ANNOTATIONS_FILE}" ) path = Path(local_path) if not path.is_absolute(): path = _task_dir(routes) / path return path def _ensure_gold_annotations_file(routes): path = _gold_annotations_path(routes) require_remote = _gold_annotations_require_remote(routes) cache_key = str(path.resolve()) if path.exists() and not require_remote: return path if path.exists() and cache_key in VERIFIED_REMOTE_GOLD_PATHS: return path config = _gold_annotations_config(routes) repo_id = ( os.environ.get("GOLD_ANNOTATIONS_REPO_ID") or config.get("repo_id") or (routes.config.get("huggingface_backup", {}) or {}).get("repo_id") ) filename = os.environ.get("GOLD_ANNOTATIONS_FILE") or config.get("filename") or GOLD_ANNOTATIONS_FILE token = config.get("token") or os.environ.get("HF_TOKEN") if not repo_id or not token: if require_remote: missing = [] if not repo_id: missing.append("repo_id") if not token: missing.append("HF_TOKEN") print( "WARNING: private gold annotations are required, " f"but {' and '.join(missing)} is missing.", flush=True, ) return None return path try: from huggingface_hub import hf_hub_download downloaded = Path(hf_hub_download( repo_id=repo_id, filename=filename, repo_type=config.get("repo_type"), token=token, )) path.parent.mkdir(parents=True, exist_ok=True) if downloaded.resolve() != path.resolve(): shutil.copyfile(downloaded, path) VERIFIED_REMOTE_GOLD_PATHS.add(cache_key) except Exception as error: print(f"WARNING: failed to load private gold annotations from {repo_id}/{filename}: {error}", flush=True) if path.exists() and cache_key in VERIFIED_REMOTE_GOLD_PATHS: return path if require_remote: return None return path def _gold_items(routes): path = _ensure_gold_annotations_file(routes) if path is None or not path.exists(): return {} try: mtime = path.stat().st_mtime except OSError: return {} cache_key = str(path.resolve()) cached = GOLD_ANNOTATIONS_CACHE.get(cache_key) if cached and cached.get("mtime") == mtime: return cached.get("items", {}) try: with path.open("r", encoding="utf-8") as handle: payload = json.load(handle) except Exception as error: print(f"WARNING: failed to parse private gold annotations at {path}: {error}", flush=True) return {} items = payload.get("items", {}) if isinstance(payload, dict) else {} if not isinstance(items, dict): items = {} GOLD_ANNOTATIONS_CACHE[cache_key] = {"mtime": mtime, "items": items} return items def _gold_item(routes, instance_id): return _gold_items(routes).get(_clean_user(instance_id), {}) or {} def _gold_labels_for(routes, instance_id): labels = _gold_item(routes, instance_id).get("labels", {}) return labels if isinstance(labels, dict) else {} def _gold_explanations_for(routes, instance_id): explanations = _gold_item(routes, instance_id).get("explanations", {}) return explanations if isinstance(explanations, dict) else {} def _subset_assignment_config(routes): return routes.config.get("subset_assignment", {}) or {} def _subset_assignment_enabled(routes): return _truthy(_subset_assignment_config(routes).get("enabled")) def _subset_manifest_path(routes): config = _subset_assignment_config(routes) manifest_path = config.get("manifest_path") if not manifest_path: return None path = Path(manifest_path) if not path.is_absolute(): path = _task_dir(routes) / path return path def _load_subset_manifest(routes): path = _subset_manifest_path(routes) if path is None or not path.exists(): return {} try: mtime = path.stat().st_mtime except OSError: return {} cache_key = str(path.resolve()) cached = SUBSET_MANIFEST_CACHE.get(cache_key) if cached and cached.get("mtime") == mtime: return cached.get("manifest", {}) try: with path.open("r", encoding="utf-8") as handle: manifest = json.load(handle) except Exception as error: print(f"WARNING: failed to load subset manifest at {path}: {error}", flush=True) return {} if not isinstance(manifest, dict): manifest = {} SUBSET_MANIFEST_CACHE[cache_key] = {"mtime": mtime, "manifest": manifest} return manifest def _subset_blocks(routes, subset_id): """Row-level subset ids (blocks) that make up a subset; the subset itself if none are listed.""" for subset in _load_subset_manifest(routes).get("subsets", []): if isinstance(subset, dict) and str(subset.get("subset_id", "")).strip() == subset_id: blocks = [str(block).strip() for block in subset.get("blocks") or [] if str(block).strip()] return blocks or [subset_id] return [subset_id] def _subset_ids(routes): manifest = _load_subset_manifest(routes) ids = [ str(subset.get("subset_id", "")).strip() for subset in manifest.get("subsets", []) if isinstance(subset, dict) and str(subset.get("subset_id", "")).strip() ] if ids: return sorted(set(ids)) try: item_manager = routes.get_item_state_manager() item_ids = item_manager.instance_id_ordering except Exception: item_manager = None item_ids = [] discovered = set() for item_id in item_ids: try: data = item_manager.get_item(item_id).get_data() except Exception: data = {} subset_id = str(data.get("subset_id", "")).strip() if isinstance(data, dict) else "" if subset_id and subset_id.lower() != "all": discovered.add(subset_id) return sorted(discovered) def _request_value(*names): for name in names: value = request.args.get(name) or request.form.get(name) or request.headers.get(f"X-{name}") if value: return _clean_user(value) return "" def _participant_context_from_request(user=""): prolific_pid = _request_value(PROLIFIC_PID_PARAM, "prolific_pid") study_id = _request_value(PROLIFIC_STUDY_PARAM, "study_id") session_id = _request_value(PROLIFIC_SESSION_PARAM, "session_id") subset_id = _request_value(SUBSET_ID_PARAM) hf_user = _request_value(HF_USER_PARAM) or _clean_user(user) followup = _followup_context(hf_user or user, prolific_pid) if followup: return { **followup, "study_id": study_id, "session_id": session_id, } participant_id = prolific_pid or hf_user or _clean_user(user) return { "participant_id": participant_id, "prolific_pid": prolific_pid, "study_id": study_id, "session_id": session_id, "hf_user": hf_user, "requested_subset_id": subset_id, "followup_mode": False, "round_id": "", "skip_pretest": False, } def _stable_subset_id(participant_id, subset_ids): if not subset_ids: return "" key = _clean_user(participant_id) or "anonymous" digest = hashlib.sha256(key.encode("utf-8")).hexdigest() return subset_ids[int(digest, 16) % len(subset_ids)] def _read_subset_assignment(routes, user): path = _subset_assignment_path(routes, user) if not path.exists(): return None try: with path.open("r", encoding="utf-8") as handle: payload = json.load(handle) except Exception: return None return payload if isinstance(payload, dict) else None def _write_subset_assignment(routes, user, assignment): _write_json_atomic(_subset_assignment_path(routes, user), assignment) def _utc_now_iso(): return datetime.utcnow().isoformat() + "Z" def _parse_utc_iso(value): if not value: return None try: cleaned = str(value).strip() if cleaned.endswith("Z"): cleaned = cleaned[:-1] return datetime.fromisoformat(cleaned) except Exception: return None def _subset_slots_path(routes): config = _subset_assignment_config(routes) raw_path = os.environ.get("SUBSET_SLOTS_FILE") or config.get("slots_path") or SUBSET_SLOTS_FILE path = Path(str(raw_path)) if not path.is_absolute(): path = _output_dir(routes) / path return path def _subset_target_completed(routes): config = _subset_assignment_config(routes) raw = os.environ.get("SUBSET_TARGET_COMPLETED") or config.get("target_completed_per_subset", 2) try: return max(1, int(raw)) except (TypeError, ValueError): return 2 def _subset_reservation_ttl_hours(routes): config = _subset_assignment_config(routes) raw = os.environ.get("SUBSET_RESERVATION_TTL_HOURS") or config.get("reservation_ttl_hours", 24) try: return max(0.0, float(raw)) except (TypeError, ValueError): return 24.0 def _empty_subset_slots(routes): return { "version": 1, "target_completed_per_subset": _subset_target_completed(routes), "reservation_ttl_hours": _subset_reservation_ttl_hours(routes), "updated_at": _utc_now_iso(), "reservations": {}, } def _read_subset_slots(routes): path = _subset_slots_path(routes) if not path.exists(): return _empty_subset_slots(routes) try: with path.open("r", encoding="utf-8") as handle: payload = json.load(handle) except Exception: payload = {} if not isinstance(payload, dict): payload = {} base = _empty_subset_slots(routes) base.update(payload) if not isinstance(base.get("reservations"), dict): base["reservations"] = {} base["target_completed_per_subset"] = _subset_target_completed(routes) base["reservation_ttl_hours"] = _subset_reservation_ttl_hours(routes) return base def _write_subset_slots(routes, slots): path = _subset_slots_path(routes) slots["updated_at"] = _utc_now_iso() _write_json_atomic(path, slots) def _slot_participant_key(user, participant_id=""): return _clean_user(participant_id) or _clean_user(user) def _expire_stale_subset_reservations(routes, slots): ttl_hours = _subset_reservation_ttl_hours(routes) if ttl_hours <= 0: return False now = datetime.utcnow() changed = False for reservation in list(slots.get("reservations", {}).values()): if not isinstance(reservation, dict) or reservation.get("status") != "reserved": continue timestamp = ( _parse_utc_iso(reservation.get("updated_at")) or _parse_utc_iso(reservation.get("reserved_at")) ) if timestamp is None: continue elapsed_hours = (now - timestamp).total_seconds() / 3600.0 if elapsed_hours > ttl_hours: reservation["status"] = "expired" reservation["reason"] = "reservation_ttl_expired" reservation["updated_at"] = _utc_now_iso() changed = True return changed def _participant_failure_state(routes, user): testing = _read_testing_gate_decision(routes, user) if _is_current_testing_gate_failure(testing): return { "reason": "testing_gate_failed", "failed_at": testing.get("evaluated_at") or _utc_now_iso(), } return None def _reconcile_failed_subset_reservations(routes, slots): changed = False for key, reservation in slots.get("reservations", {}).items(): if not isinstance(reservation, dict) or reservation.get("status") == "completed": continue if ( reservation.get("status") == "failed" and reservation.get("reason") in NONBLOCKING_QUALITY_REASONS ): reservation.update({ "status": "reserved", "reason": "main_quality_flag_nonblocking", "reopened_at": _utc_now_iso(), "updated_at": _utc_now_iso(), }) reservation.pop("failed_at", None) changed = True continue user = _clean_user(reservation.get("hf_user") or reservation.get("participant_id") or key) failure = _participant_failure_state(routes, user) if not failure: continue if ( reservation.get("status") == "failed" and reservation.get("reason") == failure["reason"] ): continue reservation.update({ "status": "failed", "reason": failure["reason"], "failed_at": reservation.get("failed_at") or failure["failed_at"], "updated_at": _utc_now_iso(), }) changed = True return changed def _reconcile_subset_slots_file(routes): with SUBSET_SLOT_LOCK: slots = _read_subset_slots(routes) changed = _expire_stale_subset_reservations(routes, slots) changed = _reconcile_failed_subset_reservations(routes, slots) or changed if changed: _write_subset_slots(routes, slots) return slots def _subset_slot_counts(routes, slots=None): slots = slots or _read_subset_slots(routes) counts = { subset_id: { "active": 0, "reserved": 0, "completed": 0, "failed": 0, "expired": 0, } for subset_id in _subset_ids(routes) } for reservation in slots.get("reservations", {}).values(): if not isinstance(reservation, dict): continue subset_id = str(reservation.get("subset_id", "")).strip() status = str(reservation.get("status", "")).strip() if subset_id not in counts: continue if status in counts[subset_id]: counts[subset_id][status] += 1 if status in SUBSET_ACTIVE_SLOT_STATUSES: counts[subset_id]["active"] += 1 return counts def _previous_round_reservations(slots, context): """Reservations of the same Prolific participant from their other rounds.""" prolific_pid = _clean_user((context or {}).get("prolific_pid")) own_key = _clean_user((context or {}).get("participant_id")) if not prolific_pid: return [] return [ reservation for key, reservation in (slots.get("reservations", {}) or {}).items() if isinstance(reservation, dict) and key != own_key and _clean_user(reservation.get("prolific_pid")) == prolific_pid and reservation.get("status") in SUBSET_ACTIVE_SLOT_STATUSES ] def _choose_subset_for_reservation(routes, participant_id, slots, requested_subset_id="", context=None): subset_ids = _subset_ids(routes) if not subset_ids: return "" requested_subset_id = str(requested_subset_id or "").strip() if requested_subset_id in subset_ids: return requested_subset_id counts = _subset_slot_counts(routes, slots) seed_prefix = str(_subset_assignment_config(routes).get("assignment_seed") or "subset_slot_v1") # A continuing participant never gets a subset sharing a block with one they # already did; among the rest, prefer the next one along the chain. previous_subsets = [ str(reservation.get("subset_id", "")).strip() for reservation in _previous_round_reservations(slots, context) ] previous_subsets = [subset_id for subset_id in previous_subsets if subset_id in subset_ids] if previous_subsets: seen_blocks = {block for subset_id in previous_subsets for block in _subset_blocks(routes, subset_id)} subset_ids = [ subset_id for subset_id in subset_ids if not seen_blocks & set(_subset_blocks(routes, subset_id)) ] if not subset_ids: return "" all_subset_ids = _subset_ids(routes) last_index = all_subset_ids.index(previous_subsets[-1]) if previous_subsets else 0 def sort_key(subset_id): tie_key = f"{seed_prefix}:{_clean_user(participant_id) or 'anonymous'}:{subset_id}" tie_breaker = int(hashlib.sha256(tie_key.encode("utf-8")).hexdigest(), 16) subset_counts = counts.get(subset_id, {}) chain_distance = ( (all_subset_ids.index(subset_id) - last_index) % len(all_subset_ids) if previous_subsets else 0 ) return ( subset_counts.get("active", 0), subset_counts.get("completed", 0), chain_distance, tie_breaker, ) return min(subset_ids, key=sort_key) def _continuation_eligibility(routes, context): """Round N is open once the participant has completed N-1 earlier subsets.""" if not _truthy((context or {}).get("continuation")): return {"eligible": True} slots = _read_subset_slots(routes) own = (slots.get("reservations", {}) or {}).get(_clean_user(context.get("participant_id"))) if isinstance(own, dict) and own.get("status") in SUBSET_ACTIVE_SLOT_STATUSES: return {"eligible": True} completed = [ reservation for reservation in _previous_round_reservations(slots, context) if reservation.get("status") == "completed" ] round_number = int(context.get("round") or 2) return { "eligible": len(completed) >= round_number - 1, "round": round_number, "completed_rounds": len(completed), } def _reserve_subset_slot(routes, user, context=None, reason="testing_passed"): context = context or _participant_context_from_request(user) participant_id = context.get("participant_id") or user key = _slot_participant_key(user, participant_id) subset_ids = _subset_ids(routes) if not key or not subset_ids: return None with SUBSET_SLOT_LOCK: slots = _read_subset_slots(routes) changed = _expire_stale_subset_reservations(routes, slots) changed = _reconcile_failed_subset_reservations(routes, slots) or changed reservations = slots.setdefault("reservations", {}) existing = reservations.get(key) if ( isinstance(existing, dict) and existing.get("status") in SUBSET_TERMINAL_SLOT_STATUSES ): failed_user = context.get("hf_user") or user legacy_time_failure = ( existing.get("status") == "failed" and existing.get("reason") == "time_gate_failed" and _read_time_gate_state(routes, failed_user).get("decision") != "failed" ) if not legacy_time_failure: if changed: _write_subset_slots(routes, slots) return dict(existing) existing.update({ "status": "reserved", "reason": "time_gate_policy_reset", "reopened_at": _utc_now_iso(), "updated_at": _utc_now_iso(), }) existing.pop("failed_at", None) changed = True if ( isinstance(existing, dict) and existing.get("status") in SUBSET_ACTIVE_SLOT_STATUSES and str(existing.get("subset_id", "")).strip() in subset_ids ): existing.update({ "participant_id": participant_id, "prolific_pid": context.get("prolific_pid", ""), "study_id": context.get("study_id", ""), "session_id": context.get("session_id", ""), "hf_user": context.get("hf_user", "") or user, "updated_at": _utc_now_iso(), }) _write_subset_slots(routes, slots) return dict(existing) failure = _participant_failure_state(routes, context.get("hf_user") or user) if failure: if changed: _write_subset_slots(routes, slots) return { "participant_key": key, "participant_id": participant_id, "status": "failed", "reason": failure["reason"], "failed_at": failure["failed_at"], } subset_id = _choose_subset_for_reservation( routes, participant_id, slots, requested_subset_id=context.get("requested_subset_id", ""), context=context, ) if not subset_id: if changed: _write_subset_slots(routes, slots) return None reservation = { "participant_key": key, "participant_id": participant_id, "prolific_pid": context.get("prolific_pid", ""), "study_id": context.get("study_id", ""), "session_id": context.get("session_id", ""), "hf_user": context.get("hf_user", "") or user, "subset_id": subset_id, "status": "reserved", "reason": reason, "reserved_at": _utc_now_iso(), "updated_at": _utc_now_iso(), } reservations[key] = reservation _write_subset_slots(routes, slots) return dict(reservation) def _update_subset_reservation_status(routes, user, status, reason=""): assignment = _read_subset_assignment(routes, user) or {} participant_id = assignment.get("participant_id") or user key = _slot_participant_key(user, participant_id) subset_id = str(assignment.get("subset_id", "")).strip() if not key: return None with SUBSET_SLOT_LOCK: slots = _read_subset_slots(routes) changed = _expire_stale_subset_reservations(routes, slots) changed = _reconcile_failed_subset_reservations(routes, slots) or changed reservations = slots.setdefault("reservations", {}) reservation = reservations.get(key) if not isinstance(reservation, dict): if not subset_id: if changed: _write_subset_slots(routes, slots) return None reservation = { "participant_key": key, "participant_id": participant_id, "subset_id": subset_id, "reserved_at": assignment.get("assigned_at") or _utc_now_iso(), } reservations[key] = reservation if reservation.get("status") == "completed" and status == "failed": if changed: _write_subset_slots(routes, slots) return dict(reservation) if reservation.get("status") == "failed" and status != "failed": if changed: _write_subset_slots(routes, slots) return dict(reservation) reservation.update({ "status": status, "reason": reason or reservation.get("reason", ""), "updated_at": _utc_now_iso(), }) if status == "completed": reservation["completed_at"] = _utc_now_iso() if status == "failed": reservation["failed_at"] = _utc_now_iso() _write_subset_slots(routes, slots) return dict(reservation) def _active_subset_reservation(routes, user, context=None): context = context or {} participant_id = context.get("participant_id") or user key = _slot_participant_key(user, participant_id) if not key: return None slots = _read_subset_slots(routes) reservation = (slots.get("reservations", {}) or {}).get(key) if not isinstance(reservation, dict): return None subset_id = str(reservation.get("subset_id", "")).strip() if reservation.get("status") not in SUBSET_ACTIVE_SLOT_STATUSES: return None if subset_id not in _subset_ids(routes): return None return reservation def _release_premature_subset_reservation(routes, user, context=None): context = context or {} participant_id = context.get("participant_id") or user key = _slot_participant_key(user, participant_id) if not key: return None with SUBSET_SLOT_LOCK: slots = _read_subset_slots(routes) reservation = (slots.get("reservations", {}) or {}).get(key) if not isinstance(reservation, dict) or reservation.get("status") != "reserved": return reservation reservation.update({ "status": "expired", "reason": "testing_not_passed", "updated_at": _utc_now_iso(), }) _write_subset_slots(routes, slots) return dict(reservation) def _role_counts_for_ids(routes, item_ids): counts = {} for item_id in item_ids: role = str(_item_data(routes, item_id).get("role", "")).strip() or "unknown" counts[role] = counts.get(role, 0) + 1 return counts def _subset_order_seed(routes, subset_id, participant_id): config = _subset_assignment_config(routes) seed_prefix = str(config.get("order_seed") or "subset_order_v1") seed_key = f"{seed_prefix}:{_clean_user(participant_id)}:{_clean_user(subset_id)}" return int(hashlib.sha256(seed_key.encode("utf-8")).hexdigest(), 16) def _control_pair_insertion_positions(dialog_count, pair_count): if pair_count <= 0: return [] if dialog_count <= 1: return [max(0, dialog_count)] * pair_count denominator = pair_count + 1 return [ min(dialog_count - 1, (pair_index * dialog_count + denominator - 1) // denominator) for pair_index in range(1, pair_count + 1) ] def _shuffle_groups(groups, seed, enabled=True): groups = list(groups) if enabled and len(groups) > 1: random.Random(seed).shuffle(groups) return groups def _visible_item_ids_for_subset(routes, subset_id, participant_id="", include_pretest=True): try: item_manager = routes.get_item_state_manager() item_ids = list(item_manager.instance_id_ordering) except Exception: return [] config = _subset_assignment_config(routes) shuffle_annotation_dialogs = not (config.get("shuffle_annotation_dialogs") is False) shuffle_control_pairs = not (config.get("shuffle_control_pairs") is False) training_ids = [] testing_ids = [] annotation_dialog_ids = {} control_pair_ids = {} other_ids = [] subset_blocks = set(_subset_blocks(routes, subset_id)) for item_id in item_ids: try: data = item_manager.get_item(item_id).get_data() except Exception: data = {} if not isinstance(data, dict): other_ids.append(item_id) continue row_subset = str(data.get("subset_id", "")).strip() if row_subset and row_subset.lower() != "all" and row_subset not in subset_blocks: continue role = str(data.get("role", "")).strip() if role == "training" or _truthy(data.get("training")): training_ids.append(item_id) elif role == "testing" or _truthy(data.get("testing")): testing_ids.append(item_id) elif role == "control" or _truthy(data.get("control")): pair_id = str(data.get("control_pair_id", "")).strip() or item_id control_pair_ids.setdefault(pair_id, []).append(item_id) elif role == "annotation" or _is_annotation_instance(data): dialog_id = str(data.get("dialog_id", "")).strip() or item_id annotation_dialog_ids.setdefault(dialog_id, []).append(item_id) else: other_ids.append(item_id) seed = _subset_order_seed(routes, subset_id, participant_id) annotation_dialogs = _shuffle_groups( annotation_dialog_ids.values(), seed, enabled=shuffle_annotation_dialogs, ) control_pairs = _shuffle_groups( control_pair_ids.values(), seed ^ 0xC0FFEE, enabled=shuffle_control_pairs, ) control_positions = _control_pair_insertion_positions( len(annotation_dialogs), len(control_pairs), ) controls_by_position = {} for position, pair_item_ids in zip(control_positions, control_pairs): controls_by_position.setdefault(position, []).append(pair_item_ids) main_ids = [] for dialog_index, dialog_item_ids in enumerate(annotation_dialogs, start=1): main_ids.extend(dialog_item_ids) for pair_item_ids in controls_by_position.get(dialog_index, []): main_ids.extend(pair_item_ids) if not annotation_dialogs: for pair_item_ids in control_pairs: main_ids.extend(pair_item_ids) pretest_ids = training_ids + testing_ids if include_pretest else [] return pretest_ids + main_ids + other_ids def _pretest_item_ids(routes): try: item_manager = routes.get_item_state_manager() item_ids = list(item_manager.instance_id_ordering) except Exception: return [] pretest_ids = [] for item_id in item_ids: try: data = item_manager.get_item(item_id).get_data() except Exception: data = {} if not isinstance(data, dict): continue role = str(data.get("role", "")).strip() if role in {"training", "testing"} or _truthy(data.get("training")) or _truthy(data.get("testing")): pretest_ids.append(item_id) return pretest_ids def _testing_gate_passed(routes, user): decision = _read_testing_gate_decision(routes, user) if _is_current_testing_gate_pass(decision): return True if _is_current_testing_gate_failure(decision): return False decision = _score_testing_gate(routes, user) if decision.get("ready") and decision.get("decision") == "passed": _write_testing_gate_decision(routes, user, decision) return True return False def _set_user_assignment_to_ids(routes, user_state, item_ids, preserve_current_id=None): item_manager = routes.get_item_state_manager() annotated_ids = set(user_state.get_annotated_instance_ids()) if hasattr(user_state, "get_annotated_instance_ids") else set() preserve_current_id = _clean_user(preserve_current_id) user_state.instance_id_ordering = [] user_state.instance_id_to_order = {} user_state.assigned_instance_ids = set() user_state.current_instance_index = -1 for item_id in item_ids: if item_manager.has_item(item_id): user_state.assign_instance(item_manager.get_item(item_id)) if item_ids: if preserve_current_id and preserve_current_id in item_ids: next_index = item_ids.index(preserve_current_id) else: next_index = 0 for index, item_id in enumerate(item_ids): if item_id not in annotated_ids: next_index = index break else: next_index = len(item_ids) - 1 user_state.current_instance_index = next_index if hasattr(user_state, "set_max_assignments"): user_state.set_max_assignments(len(item_ids)) else: user_state.max_assignments = len(item_ids) def _build_subset_assignment(routes, user, context=None, allow_main_transition=False): subset_ids = _subset_ids(routes) if not subset_ids: return None context = context or _participant_context_from_request(user) followup_mode = _truthy(context.get("followup_mode")) continuation = _truthy(context.get("continuation")) existing = _read_subset_assignment(routes, user) or {} existing_subset = str(existing.get("subset_id", "")).strip() requested_subset = str(context.get("requested_subset_id", "")).strip() if followup_mode and not continuation: requested_subset = _followup_subset_id() participant_id = context.get("participant_id") or existing.get("participant_id") or user prolific_pid = context.get("prolific_pid") or existing.get("prolific_pid") or "" study_id = context.get("study_id") or existing.get("study_id") or "" session_id = context.get("session_id") or existing.get("session_id") or "" hf_user = context.get("hf_user") or existing.get("hf_user") or user manifest = _load_subset_manifest(routes) active_reservation = _active_subset_reservation(routes, user, context) active_subset = str((active_reservation or {}).get("subset_id", "")).strip() existing_main_assignment = ( existing.get("assignment_stage") == "main" and existing_subset in subset_ids ) testing_passed = True if followup_mode else _testing_gate_passed(routes, user) if not followup_mode and ( not testing_passed or (not allow_main_transition and not existing_main_assignment) ): if not testing_passed and active_reservation: _release_premature_subset_reservation(routes, user, context) item_ids = _pretest_item_ids(routes) return { "participant_id": participant_id, "prolific_pid": prolific_pid, "study_id": study_id, "session_id": session_id, "hf_user": hf_user, "subset_id": "", "subset_count": len(subset_ids), "assignment_stage": "pretest", "assignment_strategy": "training and testing only until testing gate is passed", "ordering_strategy": "training, testing", "manifest_version": manifest.get("version"), "assigned_instance_count": len(item_ids), "role_counts": _role_counts_for_ids(routes, item_ids), "assigned_at": existing.get("assigned_at") or _utc_now_iso(), } reservation_context = dict(context) if followup_mode and requested_subset in subset_ids: reservation_context["requested_subset_id"] = requested_subset elif existing_subset in subset_ids: reservation_context["requested_subset_id"] = existing_subset elif active_subset in subset_ids: reservation_context["requested_subset_id"] = active_subset elif requested_subset in subset_ids: reservation_context["requested_subset_id"] = requested_subset reservation_reason = "followup_assignment" if followup_mode else "testing_passed" reservation = _reserve_subset_slot(routes, user, reservation_context, reason=reservation_reason) subset_id = str((reservation or {}).get("subset_id", "")).strip() if subset_id not in subset_ids: if existing_subset in subset_ids: subset_id = existing_subset elif active_subset in subset_ids: subset_id = active_subset else: subset_id = _stable_subset_id(participant_id, subset_ids) item_ids = _visible_item_ids_for_subset( routes, subset_id, participant_id=participant_id, include_pretest=not followup_mode, ) return { "participant_id": participant_id, "prolific_pid": prolific_pid, "study_id": study_id, "session_id": session_id, "hf_user": hf_user, "subset_id": subset_id, "subset_count": len(subset_ids), "assignment_stage": "main", "assignment_strategy": ( "fixed follow-up subset without repeated training or testing" if followup_mode else "reserve the subset with the fewest active slots after testing is passed" ), "ordering_strategy": ( "shuffled annotation dialogs with evenly spaced control pairs" if followup_mode else "training, testing, shuffled annotation dialogs with evenly spaced control pairs" ), "control_pair_distribution": "evenly_spaced_between_annotation_dialogues", "followup_mode": followup_mode, "round_id": context.get("round_id", "") if followup_mode else "", "skip_pretest": followup_mode, "continuation": continuation, "round": context.get("round", 1) if continuation else 1, "manifest_version": manifest.get("version"), "assigned_instance_count": len(item_ids), "role_counts": _role_counts_for_ids(routes, item_ids), "slot_status": (reservation or {}).get("status", ""), "slot_reserved_at": (reservation or {}).get("reserved_at", ""), "target_completed_per_subset": _subset_target_completed(routes), "assigned_at": existing.get("assigned_at") or _utc_now_iso(), } def _subset_id_for_user(routes, user): existing = _read_subset_assignment(routes, user) or {} subset_id = str(existing.get("subset_id", "")).strip() if subset_id: return subset_id return "" def _apply_subset_assignment( routes, user, context=None, preserve_current_id=False, allow_main_transition=False, ): user = _clean_user(user) if not user or not _subset_assignment_enabled(routes): return None user_state = routes.get_user_state_manager().get_user_state(user) if user_state is None: return None assignment = _build_subset_assignment( routes, user, context, allow_main_transition=allow_main_transition, ) if not assignment: return None if assignment.get("assignment_stage") == "pretest": item_ids = _pretest_item_ids(routes) else: item_ids = _visible_item_ids_for_subset( routes, assignment["subset_id"], participant_id=assignment.get("participant_id") or user, include_pretest=not _truthy(assignment.get("skip_pretest")), ) current_ids = list(getattr(user_state, "instance_id_ordering", [])) annotated_ids = set(user_state.get_annotated_instance_ids()) if hasattr(user_state, "get_annotated_instance_ids") else set() if current_ids != item_ids: visible_set = set(item_ids) item_manager = routes.get_item_state_manager() annotated_outside_visible = { item_id for item_id in annotated_ids - visible_set if item_manager.has_item(item_id) } if annotated_outside_visible: assignment["status"] = "kept_existing_in_progress_assignment" assignment["existing_assigned_instance_count"] = len(current_ids) else: current_id = "" if preserve_current_id and hasattr(user_state, "get_current_instance_id"): current_id = user_state.get_current_instance_id() _set_user_assignment_to_ids(routes, user_state, item_ids, preserve_current_id=current_id) assignment["status"] = "assigned" else: if hasattr(user_state, "set_max_assignments"): user_state.set_max_assignments(len(item_ids)) else: user_state.max_assignments = len(item_ids) assignment["status"] = "already_assigned" _write_subset_assignment(routes, user, assignment) try: routes.get_user_state_manager().save_user_state(user_state) except Exception as error: print(f"WARNING: failed to save subset assignment for {user}: {error}", flush=True) return assignment def _public_gate_decision(decision): if not isinstance(decision, dict): return decision public = dict(decision) public.pop("details", None) return public def _public_nonblocking_quality_flag(decision, gate_type): public = _public_gate_decision(decision) if not isinstance(public, dict): return public public["gate_type"] = gate_type if public.get("decision") == "failed": public["decision"] = "flagged" public["quality_flag"] = True public["blocking"] = False public["message"] = "A quality flag was recorded for later review." return public def _testing_rows(routes): schemas = _gate_schemas(routes) rows = [] for item_id, item in _gold_items(routes).items(): if not _truthy(item.get("testing")): continue labels = item.get("labels", {}) if not isinstance(labels, dict): labels = {} rows.append({ "id": str(item_id).strip(), "gold": { schema: _normalize_label(labels.get(schema, "")) for schema in schemas }, }) return rows def _control_rows(routes, user=None, control_pair_id=None): schemas = _gate_schemas(routes) user = _clean_user(user) control_pair_id = _clean_user(control_pair_id) allowed_ids = None if user and _subset_assignment_enabled(routes): subset_id = _subset_id_for_user(routes, user) if subset_id: assignment = _read_subset_assignment(routes, user) or {} allowed_ids = set(_visible_item_ids_for_subset( routes, subset_id, participant_id=assignment.get("participant_id") or user, include_pretest=not _truthy(assignment.get("skip_pretest")), )) rows = [] for item_id, item in _gold_items(routes).items(): if not _truthy(item.get("control")): continue item_id = str(item_id).strip() if allowed_ids is not None and item_id not in allowed_ids: continue item_data = _item_data(routes, item_id) item_pair_id = str(item_data.get("control_pair_id", "")).strip() if control_pair_id and item_pair_id != control_pair_id: continue labels = item.get("labels", {}) if not isinstance(labels, dict): labels = {} rows.append({ "id": item_id, "control_pair_id": item_pair_id, "gold": { schema: _normalize_label(labels.get(schema, "")) for schema in schemas }, }) return rows def _item_data(routes, instance_id): try: item = routes.get_item_state_manager().get_item(instance_id) except Exception: item = None if item is None: return {} data = item.get_data() return data if isinstance(data, dict) else {} def _is_annotation_instance(data): return ( _truthy(data.get("annotation")) and not _truthy(data.get("training")) and not _truthy(data.get("testing")) and not _truthy(data.get("control")) ) def _is_control_instance(data): return _truthy(data.get("control")) def _annotation_map(user_state, instance_id): raw = user_state.get_label_annotations(instance_id) or {} selected = {} if isinstance(raw, dict): iterable = raw.items() else: iterable = raw for key, value in iterable: schema = getattr(key, "schema", None) label_name = getattr(key, "name", None) if schema is None and isinstance(key, dict): schema = key.get("schema") label_name = key.get("name") if schema is None: continue normalized_value = _normalize_label(value) normalized_label = _normalize_label(label_name) selected[schema] = ( normalized_value if normalized_value in TESTING_GATE_VALID_LABELS else normalized_label ) return selected def _score_testing_gate(routes, user): user = _clean_user(user) if not user: return {"decision": "unknown", "ready": False, "message": "No user is logged in."} rows = _testing_rows(routes) schemas = _gate_schemas(routes) if not rows or not schemas: return { "decision": "not_configured", "ready": False, "message": "Testing gate is not configured.", } user_state = routes.get_user_state_manager().get_user_state(user) if user_state is None: return {"decision": "unknown", "ready": False, "message": "User state is not available."} missing = [] correct = 0 bad_mistakes = 0 ok_mistakes = 0 other_mistakes = 0 details = [] for row in rows: item_id = row["id"] annotations = _annotation_map(user_state, item_id) for schema in schemas: gold = row["gold"].get(schema) actual = annotations.get(schema) if gold not in TESTING_GATE_VALID_LABELS: missing.append({"id": item_id, "schema": schema, "reason": "missing_gold"}) continue if actual not in TESTING_GATE_VALID_LABELS: missing.append({"id": item_id, "schema": schema}) continue if actual == gold: correct += 1 outcome = "correct" elif (gold, actual) in {("Yes", "No"), ("No", "Yes")}: bad_mistakes += 1 outcome = "bad_mistake" elif ( gold in {"Yes", "No"} and actual == "To some extent" ) or ( gold == "To some extent" and actual in {"Yes", "No"} ): ok_mistakes += 1 outcome = "ok_mistake" else: other_mistakes += 1 outcome = "other_mistake" details.append({ "id": item_id, "schema": schema, "gold": gold, "actual": actual, "outcome": outcome, }) total = len(rows) * len(schemas) if missing: return { "decision": "incomplete", "ready": False, "testing_dialogs": len(rows), "total": total, "completed": total - len(missing), "missing": missing, "message": "Testing dialogs are not fully annotated yet.", } mistakes = bad_mistakes + ok_mistakes + other_mistakes weighted_mistakes = ( (bad_mistakes + other_mistakes) * TESTING_GATE_SERIOUS_MISTAKE_WEIGHT + ok_mistakes * TESTING_GATE_TSE_MISTAKE_WEIGHT ) accuracy = correct / total if total else 0.0 weighted_mistake_rate = weighted_mistakes / total if total else 0.0 weighted_accuracy = 1.0 - weighted_mistake_rate if total else 0.0 bad_mistake_rate = bad_mistakes / total if total else 0.0 failed = ( weighted_accuracy < TESTING_GATE_MIN_WEIGHTED_ACCURACY or weighted_mistake_rate > TESTING_GATE_MAX_WEIGHTED_MISTAKE_RATE or bad_mistake_rate > TESTING_GATE_MAX_SERIOUS_MISTAKE_RATE ) decision = { "decision": "failed" if failed else "passed", "policy_version": TESTING_GATE_POLICY_VERSION, "ready": True, "evaluated_at": datetime.utcnow().isoformat() + "Z", "testing_dialogs": len(rows), "total": total, "correct": correct, "bad_mistakes": bad_mistakes, "ok_mistakes": ok_mistakes, "other_mistakes": other_mistakes, "mistakes": mistakes, "weighted_mistakes": weighted_mistakes, "accuracy": accuracy, "weighted_accuracy": weighted_accuracy, "weighted_mistake_rate": weighted_mistake_rate, "bad_mistake_rate": bad_mistake_rate, "thresholds": { "min_weighted_accuracy": TESTING_GATE_MIN_WEIGHTED_ACCURACY, "max_weighted_mistake_rate": TESTING_GATE_MAX_WEIGHTED_MISTAKE_RATE, "max_serious_mistake_rate": TESTING_GATE_MAX_SERIOUS_MISTAKE_RATE, "serious_mistake_weight": TESTING_GATE_SERIOUS_MISTAKE_WEIGHT, "tse_mistake_weight": TESTING_GATE_TSE_MISTAKE_WEIGHT, }, "details": details, } decision["message"] = _testing_gate_message(decision) return decision def _score_control_gate(routes, user, instance_id=None): user = _clean_user(user) instance_id = _clean_user(instance_id) if not user: return {"decision": "unknown", "ready": False, "message": "No user is logged in."} if instance_id: data = _item_data(routes, instance_id) gold_item = _gold_item(routes, instance_id) if not _is_control_instance(data) and not _truthy(gold_item.get("control")): return {"decision": "not_control", "ready": False} control_pair_id = str(data.get("control_pair_id", "")).strip() else: control_pair_id = "" rows = _control_rows(routes, user=user, control_pair_id=control_pair_id) if not rows: return {"decision": "not_control", "ready": False} schemas = _gate_schemas(routes) if not schemas: return {"decision": "not_configured", "ready": False, "message": "Control gate is not configured."} user_state = routes.get_user_state_manager().get_user_state(user) if user_state is None: return {"decision": "unknown", "ready": False, "message": "User state is not available."} correct = 0 bad_mistakes = 0 ok_mistakes = 0 other_mistakes = 0 missing = [] details = [] for row in rows: item_id = row["id"] annotations = _annotation_map(user_state, item_id) for schema in schemas: gold = row["gold"].get(schema) actual = annotations.get(schema) if gold not in TESTING_GATE_VALID_LABELS: missing.append({"id": item_id, "schema": schema, "reason": "missing_gold"}) continue if actual not in TESTING_GATE_VALID_LABELS: missing.append({"id": item_id, "schema": schema}) continue if actual == gold: correct += 1 outcome = "correct" elif (gold, actual) in {("Yes", "No"), ("No", "Yes")}: bad_mistakes += 1 outcome = "bad_mistake" elif ( gold in {"Yes", "No"} and actual == "To some extent" ) or ( gold == "To some extent" and actual in {"Yes", "No"} ): ok_mistakes += 1 outcome = "ok_mistake" else: other_mistakes += 1 outcome = "other_mistake" details.append({ "id": item_id, "schema": schema, "gold": gold, "actual": actual, "outcome": outcome, }) total = len(rows) * len(schemas) if missing: return { "decision": "incomplete", "ready": False, "control_dialogs": len(rows), "control_pair_id": control_pair_id, "total": total, "completed": total - len(missing), "missing": missing, "message": "Control dialogs are not fully annotated yet.", } mistakes = bad_mistakes + ok_mistakes + other_mistakes weighted_mistakes = ( (bad_mistakes + other_mistakes) * CONTROL_GATE_SERIOUS_MISTAKE_WEIGHT + ok_mistakes * CONTROL_GATE_TSE_MISTAKE_WEIGHT ) mistake_rate = mistakes / total if total else 0.0 weighted_mistake_rate = weighted_mistakes / total if total else 0.0 weighted_accuracy = 1.0 - weighted_mistake_rate if total else 0.0 failed = weighted_mistake_rate >= CONTROL_GATE_MAX_WEIGHTED_MISTAKE_RATE decision = { "decision": "failed" if failed else "passed", "policy_version": CONTROL_GATE_POLICY_VERSION, "ready": True, "gate_type": "control_gate", "evaluated_at": datetime.utcnow().isoformat() + "Z", "control_dialogs": len(rows), "control_pair_id": control_pair_id, "total": total, "correct": correct, "bad_mistakes": bad_mistakes, "ok_mistakes": ok_mistakes, "other_mistakes": other_mistakes, "mistakes": mistakes, "weighted_mistakes": weighted_mistakes, "mistake_rate": mistake_rate, "weighted_mistake_rate": weighted_mistake_rate, "weighted_accuracy": weighted_accuracy, "thresholds": { "max_weighted_mistake_rate": CONTROL_GATE_MAX_WEIGHTED_MISTAKE_RATE, "serious_mistake_weight": CONTROL_GATE_SERIOUS_MISTAKE_WEIGHT, "tse_mistake_weight": CONTROL_GATE_TSE_MISTAKE_WEIGHT, }, "details": details, } decision["message"] = _control_gate_message(decision) return decision def _evaluate_control_gate(routes, user, instance_id): existing = _read_control_gate_decision(routes, user) if _is_current_control_gate_failure(existing): existing["message"] = _control_gate_message(existing) existing["gate_type"] = "control_gate" return existing decision = _score_control_gate(routes, user, instance_id) if decision.get("decision") == "failed": _write_control_gate_decision(routes, user, decision) return decision def _evaluate_tse_pattern_gate(routes, user, instance_id): user = _clean_user(user) instance_id = _clean_user(instance_id) existing = _read_tse_pattern_gate_decision(routes, user) if _is_current_tse_pattern_gate_failure(existing): existing["message"] = _tse_pattern_gate_message(existing) existing["gate_type"] = "tse_pattern_gate" return existing if not user or not instance_id or not _is_annotation_instance(_item_data(routes, instance_id)): return {"decision": "active", "ready": True, "gate_type": "tse_pattern_gate"} user_state = routes.get_user_state_manager().get_user_state(user) schemas = _gate_schemas(routes) if user_state is None or not schemas: return {"decision": "active", "ready": False, "gate_type": "tse_pattern_gate"} required_count = max(2, TSE_PATTERN_GATE_CONSECUTIVE_INSTANCES) ordered_annotation_ids = [ item_id for item_id in getattr(user_state, "instance_id_ordering", []) if _is_annotation_instance(_item_data(routes, item_id)) ] try: current_index = ordered_annotation_ids.index(instance_id) except ValueError: return {"decision": "active", "ready": True, "gate_type": "tse_pattern_gate"} start_index = current_index - required_count + 1 if start_index < 0: return {"decision": "active", "ready": True, "gate_type": "tse_pattern_gate"} candidate_ids = ordered_annotation_ids[start_index:current_index + 1] annotations_by_id = { item_id: _annotation_map(user_state, item_id) for item_id in candidate_ids } if any( annotations_by_id[item_id].get(schema) not in TESTING_GATE_VALID_LABELS for item_id in candidate_ids for schema in schemas ): return {"decision": "active", "ready": False, "gate_type": "tse_pattern_gate"} all_tse = all( annotations_by_id[item_id].get(schema) == "To some extent" for item_id in candidate_ids for schema in schemas ) if not all_tse: return {"decision": "active", "ready": True, "gate_type": "tse_pattern_gate"} decision = { "decision": "failed", "policy_version": TSE_PATTERN_GATE_POLICY_VERSION, "ready": True, "gate_type": "tse_pattern_gate", "evaluated_at": _utc_now_iso(), "instance_ids": candidate_ids, "consecutive_instances": required_count, "dimensions_per_instance": len(schemas), "trigger_label": "To some extent", "message": _tse_pattern_gate_message({"decision": "failed"}), } with TSE_PATTERN_GATE_LOCK: current = _read_tse_pattern_gate_decision(routes, user) if _is_current_tse_pattern_gate_failure(current): return current _write_tse_pattern_gate_decision(routes, user, decision) return decision def _mark_time_gate_started(routes, user, instance_id, now=None): user = _clean_user(user) instance_id = _clean_user(instance_id) if not user or not instance_id: return _read_time_gate_state(routes, user) data = _item_data(routes, instance_id) if not _is_annotation_instance(data): return _read_time_gate_state(routes, user) with TIME_GATE_LOCK: state = _read_time_gate_state(routes, user) if state.get("decision") == "failed": return state now = time.time() if now is None else now if instance_id not in state["started_at"] and instance_id not in state["completed"]: state["started_at"][instance_id] = now _write_time_gate_state(routes, user, state) return _reconcile_time_gate_state(routes, user, state) def _evaluate_time_gate_completion(routes, user, instance_id, now=None): user = _clean_user(user) instance_id = _clean_user(instance_id) if not user or not instance_id: return _read_time_gate_state(routes, user) data = _item_data(routes, instance_id) if not _is_annotation_instance(data): return _read_time_gate_state(routes, user) with TIME_GATE_LOCK: state = _reconcile_time_gate_state(routes, user) if state.get("decision") == "failed": state["message"] = _time_gate_message({"decision": "failed"}) state["gate_type"] = "time_gate" return state if instance_id in state["completed"]: return state user_state = routes.get_user_state_manager().get_user_state(user) if user_state is None: return state annotations = _annotation_map(user_state, instance_id) schemas = _gate_schemas(routes) if not schemas or any(annotations.get(schema) not in TESTING_GATE_VALID_LABELS for schema in schemas): return state now = time.time() if now is None else now started_at = state["started_at"].get(instance_id) if started_at is None: return state completed_at = datetime.utcfromtimestamp(now).isoformat() + "Z" _record_time_gate_completion( state, instance_id, now - float(started_at), completed_at, ) _apply_time_gate_threshold(routes, user, state) _write_time_gate_state(routes, user, state) return state def _evaluate_testing_gate(routes, user): existing = _read_testing_gate_decision(routes, user) if _is_current_testing_gate_pass(existing): existing["message"] = _testing_gate_message(existing) return existing if _is_current_testing_gate_failure(existing): existing["message"] = _testing_gate_message(existing) return existing decision = _score_testing_gate(routes, user) if decision.get("ready"): _write_testing_gate_decision(routes, user, decision) if decision.get("decision") == "failed": _update_subset_reservation_status(routes, user, "failed", reason="testing_gate_failed") return decision def _instance_fully_annotated(routes, user_state, instance_id): schemas = _gate_schemas(routes) if not schemas: return False annotations = _annotation_map(user_state, instance_id) return all(annotations.get(schema) in TESTING_GATE_VALID_LABELS for schema in schemas) def _mark_subset_reservation_completed_if_done(routes, user): user = _clean_user(user) if not user or not _subset_assignment_enabled(routes): return None assignment = _read_subset_assignment(routes, user) or {} if assignment.get("assignment_stage") != "main": return None subset_id = str(assignment.get("subset_id", "")).strip() if not subset_id: return None user_state = routes.get_user_state_manager().get_user_state(user) if user_state is None: return None item_ids = _visible_item_ids_for_subset( routes, subset_id, participant_id=assignment.get("participant_id") or user, include_pretest=not _truthy(assignment.get("skip_pretest")), ) if not item_ids: return None if not all(_instance_fully_annotated(routes, user_state, item_id) for item_id in item_ids): return None reservation = _update_subset_reservation_status( routes, user, "completed", reason="all_assigned_items_annotated", ) if reservation: assignment["slot_status"] = reservation.get("status", "") assignment["completed_at"] = reservation.get("completed_at", "") _write_subset_assignment(routes, user, assignment) return reservation def _testing_gate_message(decision): if decision.get("decision") == "passed": if decision.get("inferred_from"): return "Testing check already passed." return ( "Testing check passed: " f"{decision.get('correct', 0)}/{decision.get('total', 0)} labels matched, " f"{decision.get('bad_mistakes', 0)} bad mistakes, " f"{decision.get('ok_mistakes', 0)} ok mistakes." ) if decision.get("decision") == "failed": return TESTING_GATE_FAILED_MESSAGE return decision.get("message", "Testing check is not complete yet.") def _control_gate_message(decision): if decision.get("decision") == "failed": return "A quality flag was recorded for later review." if decision.get("decision") == "passed": return "Control check passed." return decision.get("message", "Control check is not complete yet.") def _time_gate_message(decision): if decision.get("decision") == "failed": return TIME_GATE_FAILED_MESSAGE return decision.get("message", "Time check is active.") def _tse_pattern_gate_message(decision): if decision.get("decision") == "failed": return TIME_GATE_FAILED_MESSAGE return decision.get("message", "Response-pattern check is active.") def _testing_gate_block_json(decision, routes=None, user=""): public_decision = _public_gate_decision(decision) payload = { "status": "blocked", "decision": "failed", "gate_type": "testing_gate", "message": _testing_gate_message(decision), "qc_result": { "type": "testing_gate", "blocked": True, "message": _testing_gate_message(decision), }, "testing_gate": public_decision, } return _add_prolific_completion(payload, routes, user, "failed_test") def _testing_gate_block_page(decision, routes=None, user=""): completion_url = _prolific_completion_path(routes, user, "failed_test") if completion_url: return redirect(completion_url) title = TESTING_GATE_FAILED_TITLE message = _testing_gate_message(decision) html = f""" {title}

{title}

{message}

""" return make_response(html, 403) def _url_with_user(location, user, context=None): if not location or not user: return location parts = urlsplit(location) query = dict(parse_qsl(parts.query, keep_blank_values=True)) query[HF_USER_PARAM] = user context = context or {} param_map = { PROLIFIC_PID_PARAM: context.get("prolific_pid"), PROLIFIC_STUDY_PARAM: context.get("study_id"), PROLIFIC_SESSION_PARAM: context.get("session_id"), SUBSET_ID_PARAM: context.get("requested_subset_id"), } for key, value in param_map.items(): if value: query[key] = value return urlunsplit( (parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment) ) def _prolific_context_for_user(routes, user): request_context = _participant_context_from_request(user) assignment = _read_subset_assignment(routes, user) if routes is not None else {} assignment = assignment or {} return { "participant_id": ( request_context.get("participant_id") or assignment.get("participant_id") or user ), "prolific_pid": ( request_context.get("prolific_pid") or assignment.get("prolific_pid") or "" ), "study_id": request_context.get("study_id") or assignment.get("study_id") or "", "session_id": request_context.get("session_id") or assignment.get("session_id") or "", "hf_user": request_context.get("hf_user") or assignment.get("hf_user") or user, "requested_subset_id": assignment.get("subset_id") or request_context.get("requested_subset_id") or "", "followup_mode": bool( request_context.get("followup_mode") or assignment.get("followup_mode") ), "round_id": request_context.get("round_id") or assignment.get("round_id") or "", "skip_pretest": bool( request_context.get("skip_pretest") or assignment.get("skip_pretest") ), } def _prolific_completion_path(routes, user, outcome): user = _clean_user(user) if not routes or not user or outcome not in PROLIFIC_COMPLETION_OUTCOMES: return "" context = _prolific_context_for_user(routes, user) if not context.get("prolific_pid"): return "" path = "/prolific/complete?" + urlencode({"outcome": outcome}) return _url_with_user(path, user, context) def _add_prolific_completion(payload, routes, user, outcome): completion_url = _prolific_completion_path(routes, user, outcome) if completion_url: payload["prolific_completion_url"] = completion_url payload["prolific_completion_outcome"] = outcome return payload def _valid_prolific_url(value): if not value: return "" try: parts = urlsplit(str(value).strip()) except ValueError: return "" hostname = (parts.hostname or "").lower() if parts.scheme != "https" or not (hostname == "prolific.com" or hostname.endswith(".prolific.com")): return "" return urlunsplit(parts) def _completion_env_value(outcome, kind, continuation=False): suffixes = { "success": ["CONTINUATION_SUCCESS", "SUCCESS"] if continuation else ["SUCCESS"], "failed_test": ["FAILED_TEST"], }.get(outcome, []) for suffix in suffixes: value = os.environ.get(f"PROLIFIC_{suffix}_COMPLETION_{kind}", "").strip() if value: return value return "" def _external_prolific_completion_url(outcome, continuation=False): configured_url = _valid_prolific_url(_completion_env_value(outcome, "URL", continuation)) if configured_url: return configured_url completion_code = _completion_env_value(outcome, "CODE", continuation) if not completion_code: return "" base_url = _valid_prolific_url( os.environ.get("PROLIFIC_COMPLETION_BASE_URL", PROLIFIC_COMPLETION_BASE_URL) ) if not base_url: return "" parts = urlsplit(base_url) query = dict(parse_qsl(parts.query, keep_blank_values=True)) query["cc"] = completion_code return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment)) def _prolific_completion_outcome(routes, user): if _is_current_testing_gate_failure(_read_testing_gate_decision(routes, user)): return "failed_test" assignment = _read_subset_assignment(routes, user) or {} if assignment.get("assignment_stage") != "main": return "" if assignment.get("slot_status") == "completed" or assignment.get("completed_at"): return "success" reservation = _mark_subset_reservation_completed_if_done(routes, user) if reservation and reservation.get("status") == "completed": return "success" return "" def _write_prolific_completion(routes, user, outcome, redirect_url): path = _output_dir(routes) / _clean_user(user) / PROLIFIC_COMPLETION_FILE path.parent.mkdir(parents=True, exist_ok=True) existing = _read_gate_decision(path) or {} assignment = _read_subset_assignment(routes, user) or {} context = _prolific_context_for_user(routes, user) payload = { "outcome": outcome, "prolific_pid": context.get("prolific_pid", ""), "study_id": context.get("study_id", ""), "session_id": context.get("session_id", ""), "subset_id": assignment.get("subset_id", ""), "round_id": assignment.get("round_id", ""), "followup": bool(assignment.get("followup_mode", False)), "redirect_configured": bool(redirect_url), "first_reached_at": existing.get("first_reached_at") or _utc_now_iso(), "last_reached_at": _utc_now_iso(), } _write_gate_decision(path, payload) return payload def _continuation_invite_enabled(): return _truthy(os.environ.get("CONTINUATION_ENABLED", "")) def _continuation_direct_link_enabled(): return _truthy(os.environ.get("CONTINUATION_DIRECT_LINK", "")) def _next_round_url(user, context): """Start URL of the participant's next round (used when direct links are enabled).""" match = CONTINUATION_USER_PATTERN.match(_clean_user(user)) prolific_pid = match.group(1) if match else _clean_user(context.get("prolific_pid") or user) next_round = (int(match.group(2)) if match else 1) + 1 return "/?" + urlencode({PROLIFIC_PID_PARAM: prolific_pid, CONTINUATION_ROUND_PARAM: next_round}) def _prolific_completion_page(outcome, redirect_url, followup=False, next_round_url="", set_size=0): failed = outcome != "success" title = "Annotation complete" if not failed else "Annotation ended" if failed: message = TESTING_GATE_FAILED_MESSAGE elif followup: message = "Thank you for completing the follow-up annotation. Your responses have been saved." else: message = "Thank you for completing the annotation." invite = "" next_button = "" more = f"{set_size} more conversations" if set_size else "more conversations" if not failed and next_round_url: invite = f"Would you like to annotate {more}? You can continue with the next set now." next_button = ( f'' f'Annotate {escape(more)}' ) elif not failed and _continuation_invite_enabled(): invite = ( f"Would you like to annotate {more}? Participants who complete this study " "are invited to a follow-up study on Prolific with the next set." ) if redirect_url: follow_up = "You will now be returned to Prolific." button = f'Return to Prolific' # With a direct next-round link the participant chooses; otherwise redirect # automatically (later when there is an invitation to read). redirect_script = "" if next_button else f""" """ if next_button: follow_up = "Otherwise, return to Prolific to finish." elif followup or next_button: follow_up = "Otherwise, you may now close this page." if next_button else "You may now close this page." button = "" redirect_script = "" else: follow_up = "The Prolific return link is not configured. Please contact the study organizer." button = "" redirect_script = "" if invite: follow_up = f"{invite} {follow_up}" button = next_button + button accent = "#2d7a46" if not failed else "#c93535" html = f""" {escape(title)}

{escape(title)}

{escape(message)}

{escape(follow_up)}

{button}
{redirect_script} """ response = make_response(html, 200) response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0" return response def _ensure_user_session(user): user = _clean_user(user) if not user: return routes = _routes_module() if routes is None: session["username"] = user session.permanent = True session["created_at"] = datetime.now() return if not routes.config.get("require_password", True): authenticator = routes.UserAuthenticator.get_instance() if not authenticator.is_valid_username(user): authenticator.add_user(user, None) session["username"] = user session.permanent = True session["created_at"] = datetime.now() usm = routes.get_user_state_manager() if not usm.has_user(user): _restore_user_output_from_hub(routes, user) restored_state = usm.get_user_state(user) if restored_state is not None: if restored_state.get_phase() == routes.UserPhase.LOGIN: usm.advance_phase(user) return usm.add_user(user) usm.advance_phase(user) return user_state = usm.get_user_state(user) if user_state and user_state.get_phase() == routes.UserPhase.LOGIN: usm.advance_phase(user) def _hf_user_from_request(): raw_user = _clean_user( request.args.get(HF_USER_PARAM) or request.args.get(PROLIFIC_PID_PARAM) or request.args.get("prolific_pid") or request.headers.get("X-HF-User") or request.headers.get(f"X-{PROLIFIC_PID_PARAM}") or request.form.get(HF_USER_PARAM) or request.form.get(PROLIFIC_PID_PARAM) or request.form.get("prolific_pid") ) prolific_pid = _clean_user( request.args.get(PROLIFIC_PID_PARAM) or request.args.get("prolific_pid") or request.headers.get(f"X-{PROLIFIC_PID_PARAM}") or request.form.get(PROLIFIC_PID_PARAM) or request.form.get("prolific_pid") ) followup = _followup_context(raw_user, prolific_pid) return followup["hf_user"] if followup else raw_user def _hf_user_script(user, context=None): safe_user = user.replace("\\", "\\\\").replace("'", "\\'") initial_context = json.dumps(context or {}, ensure_ascii=True) return f""" """ def configure_app_with_hf_cookies(app): configured_app = _configure_app(app) _configure_persistent_memo_storage() routes = _routes_module() _validate_followup_config(routes) if routes is not None and _subset_assignment_enabled(routes): _reconcile_subset_slots_file(routes) if os.environ.get("POTATO_HF_COOKIE_COMPAT", "1") == "1": configured_app.config.update( SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_PARTITIONED=True, SESSION_COOKIE_SAMESITE="None", SESSION_COOKIE_SECURE=True, ) @configured_app.before_request def enforce_followup_allowlist(): if not _followup_mode_enabled(): return None prolific_pid = _request_value(PROLIFIC_PID_PARAM, "prolific_pid") if prolific_pid and prolific_pid != _followup_participant_id(): return make_response("This follow-up study is not assigned to this participant.", 403) return None @configured_app.before_request def enforce_continuation_eligibility(): if request.path.startswith((MATHVISION_IMAGE_ROUTE, "/static")): return None routes = _routes_module() user = _hf_user_from_request() or _clean_user(session.get("username")) if routes is None or not user: return None context = _participant_context_from_request(user) eligibility = _continuation_eligibility(routes, context) if eligibility.get("eligible"): return None round_number = eligibility.get("round", 2) message = ( f"Round {round_number} opens after you have completed " f"{round_number - 1} earlier annotation round{'s' if round_number > 2 else ''} with this Prolific ID." ) return make_response( "Not available yet" "
" f"

Not available yet

{escape(message)}

", 403, ) @configured_app.route(f"{MATHVISION_IMAGE_ROUTE}/", methods=["GET"]) def mathvision_image(filename): return send_from_directory(MATHVISION_IMAGE_DIR, filename, max_age=86400) @configured_app.route("/prolific/complete", methods=["GET"]) def prolific_completion(): user = _hf_user_from_request() or _clean_user(session.get("username")) routes = _routes_module() if not user or routes is None: return make_response("Completion is unavailable because no participant is logged in.", 403) context = _prolific_context_for_user(routes, user) if not context.get("prolific_pid"): return make_response("Completion is available only for Prolific participants.", 403) actual_outcome = _prolific_completion_outcome(routes, user) requested_outcome = str(request.args.get("outcome") or "").strip() if not actual_outcome or ( requested_outcome in PROLIFIC_COMPLETION_OUTCOMES and requested_outcome != actual_outcome ): return make_response("This annotation is not ready for Prolific completion.", 403) followup = bool(context.get("followup_mode")) continuation = bool(CONTINUATION_USER_PATTERN.match(user)) completion_url = _external_prolific_completion_url(actual_outcome, continuation=continuation) _write_prolific_completion(routes, user, actual_outcome, completion_url) next_round_url = ( _next_round_url(user, context) if actual_outcome == "success" and _continuation_direct_link_enabled() else "" ) subsets = _load_subset_manifest(routes).get("subsets") or [{}] return _prolific_completion_page( actual_outcome, completion_url, followup=followup, next_round_url=next_round_url, set_size=int(subsets[0].get("annotation_dialogs") or 0), ) @configured_app.before_request def enforce_quality_gate_block(): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return None followup_context = _followup_context(user=user) if request.path in { "/testing_gate/status", "/control_gate/status", "/time_gate/status", "/tse_pattern_gate/status", "/subset_assignment/status", }: return None routes = _routes_module() if routes is None or request.path not in {"/annotate", "/updateinstance"}: return None existing = _read_testing_gate_decision(routes, user) if not followup_context and _is_current_testing_gate_failure(existing): _update_subset_reservation_status(routes, user, "failed", reason="testing_gate_failed") if request.path == "/updateinstance": return jsonify(_testing_gate_block_json(existing, routes, user)) if request.method == "GET": return _testing_gate_block_page(existing, routes=routes, user=user) payload = _testing_gate_block_json(existing, routes, user) payload["status"] = "validation_error" return jsonify(payload), 400 if request.path == "/annotate" and request.method == "POST": payload = request.get_json(silent=True) or {} action = payload.get("action") or request.form.get("action") if action == "next_instance": user_state = routes.get_user_state_manager().get_user_state(user) instance_id = _clean_user(payload.get("instance_id")) or ( user_state.get_current_instance_id() if user_state else "" ) g.time_gate_departing_instance_id = instance_id _evaluate_tse_pattern_gate(routes, user, instance_id) _evaluate_time_gate_completion(routes, user, instance_id) _evaluate_control_gate(routes, user, instance_id) if followup_context: return None decision = _evaluate_testing_gate(routes, user) if decision.get("decision") == "failed": payload = _testing_gate_block_json(decision, routes, user) payload["status"] = "validation_error" return jsonify(payload), 400 if decision.get("decision") == "passed": _apply_subset_assignment( routes, user, _participant_context_from_request(user), preserve_current_id=True, allow_main_transition=True, ) g.subset_assignment_applied = True return None @configured_app.route("/testing_gate/status", methods=["GET"]) def testing_gate_status(): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return jsonify({"decision": "unknown", "ready": False, "message": "No user is logged in."}), 401 if _followup_context(user=user): return jsonify({ "decision": "passed", "ready": True, "followup": True, "message": "Training and testing were completed in the previous round.", }) routes = _routes_module() if routes is None: return jsonify({"decision": "unknown", "ready": False, "message": "App routes are not ready."}), 503 decision = _public_gate_decision(_evaluate_testing_gate(routes, user)) if decision.get("decision") == "failed": _add_prolific_completion(decision, routes, user, "failed_test") return jsonify(decision) @configured_app.route("/training_feedback", methods=["GET"]) def training_feedback(): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return jsonify({"error": "No user is logged in."}), 401 routes = _routes_module() if routes is None: return jsonify({"error": "App routes are not ready."}), 503 instance_id = _clean_user(request.args.get("instance_id")) if not instance_id: return jsonify({"error": "No instance id was provided."}), 400 data = _item_data(routes, instance_id) gold_item = _gold_item(routes, instance_id) if not _truthy(data.get("training")) and not _truthy(gold_item.get("training")): return jsonify({"error": "Training feedback is not available for this item."}), 404 labels = { schema: _normalize_label(_gold_labels_for(routes, instance_id).get(schema)) for schema in _gate_schemas(routes) } if not any(labels.values()): return jsonify({"error": "Training feedback gold labels are not available for this item."}), 503 return jsonify({ "id": instance_id, "labels": labels, "explanations": { schema: str(_gold_explanations_for(routes, instance_id).get(schema, "")) for schema in _gate_schemas(routes) }, }) @configured_app.route("/control_gate/status", methods=["GET"]) def control_gate_status(): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return jsonify({"decision": "unknown", "ready": False, "message": "No user is logged in."}), 401 routes = _routes_module() if routes is None: return jsonify({"decision": "unknown", "ready": False, "message": "App routes are not ready."}), 503 instance_id = request.args.get("instance_id") if instance_id: return jsonify(_public_nonblocking_quality_flag( _evaluate_control_gate(routes, user, instance_id), "control_gate", )) state = _read_control_gate_decision(routes, user) if _is_current_control_gate_failure(state): state["message"] = _control_gate_message(state) state["gate_type"] = "control_gate" return jsonify(_public_nonblocking_quality_flag(state, "control_gate")) return jsonify({"decision": "active", "ready": True, "gate_type": "control_gate"}) @configured_app.route("/time_gate/status", methods=["GET"]) def time_gate_status(): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return jsonify({"decision": "unknown", "ready": False, "message": "No user is logged in."}), 401 routes = _routes_module() if routes is None: return jsonify({"decision": "unknown", "ready": False, "message": "App routes are not ready."}), 503 state = _reconcile_time_gate_state(routes, user) if state.get("decision") == "failed": state["message"] = _time_gate_message({"decision": "failed"}) state["gate_type"] = "time_gate" return jsonify(_public_nonblocking_quality_flag(state, "time_gate")) @configured_app.route("/tse_pattern_gate/status", methods=["GET"]) def tse_pattern_gate_status(): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return jsonify({"decision": "unknown", "ready": False, "message": "No user is logged in."}), 401 routes = _routes_module() if routes is None: return jsonify({"decision": "unknown", "ready": False, "message": "App routes are not ready."}), 503 state = _read_tse_pattern_gate_decision(routes, user) if _is_current_tse_pattern_gate_failure(state): state["message"] = _tse_pattern_gate_message(state) state["gate_type"] = "tse_pattern_gate" return jsonify(_public_nonblocking_quality_flag(state, "tse_pattern_gate")) return jsonify({"decision": "active", "ready": True, "gate_type": "tse_pattern_gate"}) @configured_app.route("/subset_assignment/status", methods=["GET"]) def subset_assignment_status(): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return jsonify({"status": "unknown", "message": "No user is logged in."}), 401 routes = _routes_module() if routes is None: return jsonify({"status": "unknown", "message": "App routes are not ready."}), 503 if not _subset_assignment_enabled(routes): return jsonify({"status": "disabled"}) _ensure_user_session(user) assignment = _apply_subset_assignment(routes, user, _participant_context_from_request(user)) if not assignment: return jsonify({"status": "not_configured"}) assignment["slot_counts"] = _subset_slot_counts(routes) return jsonify(assignment) original_update_instance = configured_app.view_functions.get("update_instance") if original_update_instance: @wraps(original_update_instance) def update_instance_with_testing_gate(*args, **kwargs): return original_update_instance(*args, **kwargs) configured_app.view_functions["update_instance"] = update_instance_with_testing_gate @configured_app.before_request def restore_hf_user_from_request(): user = _hf_user_from_request() if user: _ensure_user_session(user) routes = _routes_module() if routes is not None and not getattr(g, "subset_assignment_applied", False): _apply_subset_assignment(routes, user, _participant_context_from_request(user)) @configured_app.before_request def redirect_finished_prolific_participant(): if request.method != "GET" or request.path not in {"/", "/annotate"}: return None user = _hf_user_from_request() or _clean_user(session.get("username")) routes = _routes_module() if not user or routes is None: return None outcome = _prolific_completion_outcome(routes, user) completion_path = _prolific_completion_path(routes, user, outcome) if completion_path: return redirect(completion_path) return None @configured_app.before_request def apply_subset_assignment_for_session_user(): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return None routes = _routes_module() if routes is None or request.path not in {"/annotate", "/updateinstance", "/subset_assignment/status"}: return None if getattr(g, "subset_assignment_applied", False): return None _apply_subset_assignment(routes, user, _participant_context_from_request(user)) return None @configured_app.after_request def preserve_hf_user(response): user = _hf_user_from_request() or _clean_user(session.get("username")) if not user: return response routes = _routes_module() departing_instance_id = getattr(g, "time_gate_departing_instance_id", "") if ( routes is not None and request.path == "/annotate" and request.method == "POST" and response.status_code < 400 and departing_instance_id ): _evaluate_time_gate_completion(routes, user, departing_instance_id) if ( routes is not None and request.path in {"/annotate", "/updateinstance"} and response.status_code < 400 ): _mark_subset_reservation_completed_if_done(routes, user) if routes is not None and response.status_code < 400 and ( (request.path in {"/", "/annotate"} and request.method == "GET") or request.path == "/updateinstance" ): user_state = routes.get_user_state_manager().get_user_state(user) instance_id = user_state.get_current_instance_id() if user_state else "" _mark_time_gate_started(routes, user, instance_id) if ( request.method == "POST" and request.path in ("/", "/auth", "/login") and response.status_code in (301, 302, 303, 307, 308) ): response.headers["Location"] = _url_with_user( response.headers.get("Location"), user, _participant_context_from_request(user) ) return response content_type = response.headers.get("Content-Type", "") if "text/html" in content_type.lower(): html = response.get_data(as_text=True) script = _hf_user_script(user, _participant_context_from_request(user)) if "" in html: html = html.replace("", script + "", 1) else: html += script response.set_data(html) response.headers["Content-Length"] = str(len(response.get_data())) return response return configured_app def load_all_data_with_hf_restore(config): _restore_annotation_output_from_hub_config(config) result = _load_all_data(config) _normalize_loaded_item_json_data() return result # Final-item save fix. Potato counts an item as annotated once it has any entry # in instance_id_to_label_to_value, even an empty one. In the programming study # the unanswered last item got such an entry, the count reached max_assignments, # and the participant was moved to the "done" phase. Labels for that last item # were then stored on the "done" phase page instead of the item. Here the assignment only finishes once every assigned # item has all radio dimensions answered, and labels for an assigned item are # always stored on the item, whatever phase the user is in. def _has_remaining_assignments_until_fully_annotated(self): routes = _routes_module() ordering = list(getattr(self, "instance_id_ordering", []) or []) if routes is None or not ordering or not _gate_schemas(routes): return _original_has_remaining_assignments(self) return not all(_instance_fully_annotated(routes, self, item_id) for item_id in ordering) def _add_label_annotation_to_assigned_item(self, instance_id, label, value): phase = (getattr(self, "current_phase_and_page", None) or (None, None))[0] if phase != UserPhase.ANNOTATION and instance_id in (getattr(self, "instance_id_to_order", None) or {}): self.instance_id_to_label_to_value[instance_id][label] = value return None return _original_add_label_annotation(self, instance_id, label, value) InMemoryUserState.has_remaining_assignments = _has_remaining_assignments_until_fully_annotated InMemoryUserState.add_label_annotation = _add_label_annotation_to_assigned_item _register_prolific_json_exporter() flask_server.load_all_data = load_all_data_with_hf_restore flask_server.configure_app = configure_app_with_hf_cookies if __name__ == "__main__": cookie_mode = "enabled" if os.environ.get("POTATO_HF_COOKIE_COMPAT", "1") == "1" else "disabled" print(f"Starting Potato via hf_start.py with Hugging Face cookie compatibility {cookie_mode}.", flush=True) if len(sys.argv) == 1: port = os.environ.get("PORT", "7860") sys.argv = ["potato", "start", "config.yaml", "-p", port] else: sys.argv[0] = "potato" raise SystemExit(flask_server.main())