#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Divid Teacher - Deterministic Question Executor Strategic rule: - Qwen owns semantic/linguistic content only. - The platform owns deterministic mechanics. - Contract / Recipe / Schema are authoritative. - Never guess missing semantic truth. This pure executor compiles model semantic content into the canonical mechanics expected by question_interaction_contract. It does not select skills, recipes, diagnostic conditions, models, media, or student progress. """ from __future__ import annotations import copy import hashlib import json import re from typing import Any, Dict, List, Tuple from question_interaction_contract import ( VERSION as INTERACTION_CONTRACT_VERSION, canonical_family, canonicalize_question, ) VERSION = "deterministic_question_executor_v7_hidden_audio_sequence_units" def _text(value: Any) -> str: return str(value or "").strip() def _lower(value: Any) -> str: return _text(value).lower() def _as_dict(value: Any) -> Dict[str, Any]: return dict(value) if isinstance(value, dict) else {} def _as_list(value: Any) -> List[Any]: if value in (None, ""): return [] if isinstance(value, list): return list(value) if isinstance(value, (tuple, set)): return list(value) return [value] def _norm(value: Any) -> str: if isinstance(value, (dict, list, tuple, set)): try: value = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str) except Exception: value = str(value) text = _text(value).casefold().replace("ـ", "") text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا") text = text.replace("ة", "ه").replace("ى", "ي") return re.sub(r"\s+", " ", text).strip() def _label(value: Any) -> str: if isinstance(value, dict): return _text( value.get("label_ar") or value.get("label") or value.get("text") or value.get("semantic_value") or value.get("value") or value.get("id") or value.get("key") ) return _text(value) def _semantic_key(value: Any) -> str: if isinstance(value, dict): return _text( value.get("semantic_value") or value.get("value") or value.get("id") or value.get("key") or _label(value) ) return _text(value) def _record(value: Any, index: int, prefix: str) -> Dict[str, Any]: if isinstance(value, dict): out = copy.deepcopy(value) label = _label(value) semantic = _semantic_key(value) or label rid = _text(value.get("id") or value.get("key")) if not rid: rid = f"{prefix}_{index + 1}" out["id"] = rid if label: out["label"] = label out.setdefault("label_ar", label) out["semantic_value"] = semantic or rid out.setdefault("value", semantic or rid) return out label = _text(value) return { "id": f"{prefix}_{index + 1}", "label": label, "label_ar": label, "semantic_value": label, "value": label, } def _records(values: Any, prefix: str) -> List[Dict[str, Any]]: rows = _as_list(values) out: List[Dict[str, Any]] = [] seen = set() for idx, row in enumerate(rows): rec = _record(row, idx, prefix) key = _norm(rec.get("semantic_value") or rec.get("label") or rec.get("id")) if not key or key in seen: continue seen.add(key) out.append(rec) return out def _relation_rows(value: Any) -> List[Tuple[Any, Any]]: rows: List[Tuple[Any, Any]] = [] for row in _as_list(value): if isinstance(row, dict): left = ( row.get("left") or row.get("source") or row.get("item") or row.get("from") or row.get("key") ) right = ( row.get("right") or row.get("target") or row.get("match") or row.get("to") or row.get("value") ) if left not in (None, "", [], {}) and right not in (None, "", [], {}): rows.append((copy.deepcopy(left), copy.deepcopy(right))) elif isinstance(row, (list, tuple)) and len(row) >= 2: rows.append((copy.deepcopy(row[0]), copy.deepcopy(row[1]))) return rows def _mapping_rows(value: Any) -> List[Tuple[Any, Any]]: if isinstance(value, dict): return [ (copy.deepcopy(k), copy.deepcopy(v)) for k, v in value.items() if _text(k) and _text(v) ] return _relation_rows(value) def _lookup(records: List[Dict[str, Any]]) -> Dict[str, str]: out: Dict[str, str] = {} for rec in records: rid = _text(rec.get("id")) for value in ( rec.get("id"), rec.get("key"), rec.get("semantic_value"), rec.get("value"), rec.get("label"), rec.get("label_ar"), rec.get("text"), ): key = _norm(value) if key and rid: out.setdefault(key, rid) return out def _ensure_record( records: List[Dict[str, Any]], value: Any, prefix: str, ) -> Dict[str, Any]: key = _norm(_semantic_key(value) or _label(value)) existing = _lookup(records) if key and key in existing: rid = existing[key] return next(rec for rec in records if _text(rec.get("id")) == rid) rec = _record(value, len(records), prefix) records.append(rec) return rec def _stable_shuffle(records: List[Dict[str, Any]], seed: str) -> List[Dict[str, Any]]: if len(records) < 2: return copy.deepcopy(records) decorated = [] for index, rec in enumerate(records): raw = f"{seed}|{index}|{_text(rec.get('id'))}|{_text(rec.get('semantic_value'))}" digest = hashlib.sha256(raw.encode("utf-8")).hexdigest() decorated.append((digest, index, copy.deepcopy(rec))) shuffled = [row[2] for row in sorted(decorated)] if [_text(x.get("id")) for x in shuffled] == [_text(x.get("id")) for x in records]: shuffled = shuffled[1:] + shuffled[:1] return shuffled def build_semantic_model_schema( final_schema: Dict[str, Any], ownership: Dict[str, Any], *, family: str, recipe: Dict[str, Any] | None = None, ) -> Dict[str, Any]: """Build the model-facing semantic schema. Final mechanics are intentionally absent for pair/sequence. The executor compiles them after Qwen returns semantic content. """ final = copy.deepcopy(final_schema or {}) ownership = copy.deepcopy(ownership or {}) writable = set(str(x) for x in (ownership.get("model_writable_fields") or [])) final_props = final.get("properties") if isinstance(final.get("properties"), dict) else {} props: Dict[str, Any] = {} required: List[str] = [] # Common semantic fields that may already exist in the final schema. for key in ("question", "audio_text", "stimulus"): if key in writable: props[key] = copy.deepcopy(final_props.get(key) or {"type": "string"}) if key in (final.get("required") or []): required.append(key) family = _lower(family) recipe = _as_dict(recipe) response_contract = _as_dict(recipe.get("response_contract")) response_kind = _lower(response_contract.get("kind")) allowed_visual_tokens = [ _text(x) for x in _as_list(response_contract.get("allowed_visual_tokens")) if _text(x) ] system_visual_word_mechanics = bool( family == "pair" and response_kind in { "visual_word_segmentation_mapping", "visual_word_boundary_mapping", "visual_word_unit_mapping", } and response_contract.get("text_word_options_forbidden") is True and allowed_visual_tokens ) if family == "pair" and system_visual_word_mechanics: # Qwen generates linguistic stimulus only. The platform derives all visible # tokens and pair mechanics from the declared Recipe. props.pop("stimulus", None) required = [x for x in required if x != "stimulus"] elif family == "pair": # Qwen supplies semantic relationships; platform creates ids, payload and mapping. props["pairs"] = { "type": "array", "minItems": 1, "description": ( "العلاقات الدلالية الصحيحة فقط. كل عنصر يحتوي left وright. " "لا تنشئ interaction_payload أو mapping ids." ), "items": { "type": "object", "required": ["left", "right"], "properties": { "left": {}, "right": {}, }, "additionalProperties": False, }, } props["items"] = { "type": "array", "description": "محتوى العناصر اليسرى إن احتجت بيانات عرض إضافية.", "items": {}, } props["targets"] = { "type": "array", "description": "محتوى الأهداف اليمنى إن احتجت بيانات عرض إضافية.", "items": {}, } required.append("pairs") elif family == "sequence": hidden_audio_sequence = bool( ownership.get("hidden_audio_sequence_scope_guard") is True or ( ownership.get("stimulus_audio_text_required") is True and "items" not in writable ) ) if not hidden_audio_sequence: props["items"] = { "type": "array", "minItems": 2, "description": ( "العناصر الدلالية بالترتيب الصحيح. النظام ينشئ IDs ويخلط ترتيب العرض " "ويحفظ correct_order." ), "items": {}, } required.append("items") # Hidden-audio sequences are different: Qwen supplies audio_text only. # The deterministic executor derives internal spoken units after submission. elif family in {"single_choice", "multi_choice"}: # Options and semantic answer remain model content unless the Recipe made them system-owned. if "options" in writable: props["options"] = copy.deepcopy(final_props.get("options") or {"type": "array"}) required.append("options") elif "choices" in writable: props["choices"] = {"type": "array"} required.append("choices") if "correct_answer" in writable: props["correct_answer"] = copy.deepcopy(final_props.get("correct_answer") or {}) required.append("correct_answer") elif family in {"numeric", "text"}: if "correct_answer" in writable: props["correct_answer"] = copy.deepcopy(final_props.get("correct_answer") or {}) required.append("correct_answer") elif family in {"oral", "external"}: # Preserve an explicitly allowed semantic payload only for families whose # evaluator/tool state is inherently external. if "interaction_payload" in writable: props["interaction_payload"] = copy.deepcopy( final_props.get("interaction_payload") or {"type": "object"} ) # Audio text can be mandatory even if the final mechanical schema does not # explicitly make the model responsible for anything else. if ownership.get("stimulus_audio_text_required") and "audio_text" in writable: props.setdefault("audio_text", {"type": "string"}) if "audio_text" not in required: required.append("audio_text") return { "type": "object", "required": list(dict.fromkeys(required)), "properties": props, "additionalProperties": False, "model_output_scope": ownership.get("scope", "bounded_question_content"), "semantic_contract_input": True, "mechanics_compiled_by_system": True, "response_family": family, "response_kind": response_kind, "system_visual_word_mechanics": system_visual_word_mechanics, } _ARABIC_DIACRITICS_RE = re.compile(r"[\u064b-\u065f\u0670]") def _spoken_words(value: Any) -> List[str]: """Whitespace lexical units for already-generated spoken stimulus. This is a deterministic mechanical count only. It does not create or correct linguistic content. """ text = _text(value) if not text: return [] text = _ARABIC_DIACRITICS_RE.sub("", text) # Strip punctuation at token boundaries but preserve letters/numbers. raw = re.split(r"\s+", text) out: List[str] = [] for token in raw: cleaned = re.sub(r"^[^\w\u0600-\u06FF]+|[^\w\u0600-\u06FF]+$", "", token, flags=re.UNICODE) if cleaned: out.append(cleaned) return out def _visual_pattern(unit: str, boundary: str, count: int) -> str: count = max(1, int(count or 1)) if count == 1: return unit return f" {boundary} ".join([unit] * count) def _visual_pattern_without_one_boundary(unit: str, boundary: str, count: int) -> str: """A merge-error distractor using only declared visual tokens.""" count = max(2, int(count or 2)) parts = [unit] * count # Merge first two word tokens by omitting one boundary. merged_head = unit + unit if count == 2: return merged_head return merged_head + f" {boundary} " + f" {boundary} ".join(parts[2:]) def _token_only_visual(value: Any, allowed_tokens: List[str]) -> bool: """True only when visible text is composed exclusively of declared tokens.""" text = _text(value) if not text: return True remainder = re.sub(r"\s+", "", text) for token in sorted([x for x in allowed_tokens if x], key=len, reverse=True): remainder = remainder.replace(token, "") return remainder == "" def _compile_declared_visual_word_mapping( q: Dict[str, Any], *, response: Dict[str, Any], stimulus_contract: Dict[str, Any], audit: Dict[str, Any], ) -> Tuple[Dict[str, Any], List[str]]: """Compile spoken-word visual mapping from Recipe declarations only. No written stimulus words are exposed. The semantic sentence remains in audio_text for media generation; the student sees only allowed_visual_tokens. """ out = copy.deepcopy(q) errors: List[str] = [] allowed = [ _text(x) for x in _as_list(response.get("allowed_visual_tokens")) if _text(x) ] if not allowed: return out, ["contract_visual_tokens_missing"] unit = next((x for x in allowed if x != "|"), allowed[0]) boundary = "|" if "|" in allowed else (allowed[1] if len(allowed) > 1 else allowed[0]) words = _spoken_words(out.get("audio_text")) word_count = len(words) min_words = int( stimulus_contract.get("spoken_phrase_words_min") or stimulus_contract.get("word_count_min") or 1 ) max_words_raw = ( stimulus_contract.get("spoken_phrase_words_max") or stimulus_contract.get("word_count_max") or 0 ) max_words = int(max_words_raw or 0) if not words: errors.append("semantic_required:audio_text") return out, errors if word_count < min_words: errors.append(f"stimulus_word_count_below_min:{word_count}<{min_words}") return out, errors if max_words and word_count > max_words: errors.append(f"stimulus_word_count_above_max:{word_count}>{max_words}") return out, errors correct_pattern = _visual_pattern(unit, boundary, word_count) diagnostic_condition = _lower(out.get("diagnostic_condition")) # V6: the diagnostic condition must change the observable probe operation. # Previously correct/merge/split conditions all compiled to the same target set, # so different slot names could masquerade as independent evidence. operation_id = "segment_spoken_sentence" distractors: List[str] = [] if diagnostic_condition == "merge_error_candidate": operation_id = "discriminate_merged_word_boundary" if word_count >= 2: distractors.append( _visual_pattern_without_one_boundary(unit, boundary, word_count) ) # Strong merge: all spoken units shown with no boundaries. distractors.append(unit * max(2, word_count)) elif diagnostic_condition == "split_error_candidate": operation_id = "discriminate_oversegmented_word_boundary" distractors.append(_visual_pattern(unit, boundary, word_count + 1)) distractors.append(_visual_pattern(unit, boundary, word_count + 2)) else: # Baseline / general segmentation keeps balanced merge + split alternatives. if word_count >= 2: distractors.append( _visual_pattern_without_one_boundary(unit, boundary, word_count) ) distractors.append(_visual_pattern(unit, boundary, word_count + 1)) if word_count >= 3: distractors.append(_visual_pattern(unit, boundary, max(1, word_count - 1))) visible_patterns: List[str] = [] for pattern in [correct_pattern] + distractors: if pattern and pattern not in visible_patterns: visible_patterns.append(pattern) if len(visible_patterns) < 2: errors.append("contract_visual_distractors_insufficient") return out, errors source = { "id": "stimulus_audio", "label": "🔊 الجملة المسموعة", "label_ar": "🔊 الجملة المسموعة", "semantic_value": "audio_stimulus", "value": "audio_stimulus", "audio_asset_role": "prompt_audio", } targets: List[Dict[str, Any]] = [] correct_target_id = "" for index, pattern in enumerate(visible_patterns): target_id = f"target_{index + 1}" if index == 0: correct_target_id = target_id targets.append({ "id": target_id, # Keep structural identity separate from student-facing meaning. # QuestionInteractionEngine uses semantic_value when it canonicalizes # pair-zone display, so target_1/target_2 must never live there. "label": pattern, "label_ar": pattern, "semantic_value": pattern, "value": target_id, "internal_id": target_id, }) # Stable deterministic shuffle for presentation while preserving target IDs. seed = _text(out.get("audio_text")) + "|" + _text(out.get("diagnostic_condition")) targets = _stable_shuffle(targets, seed) mapping = {"stimulus_audio": correct_target_id} response_kind = _lower(response.get("kind")) if response_kind == "visual_word_segmentation_mapping": if diagnostic_condition == "merge_error_candidate": instruction = "استمع واختر الفصل دون دمج الكلمات." elif diagnostic_condition == "split_error_candidate": instruction = "استمع واختر الفصل دون تقسيم زائد." else: # Six Arabic whitespace tokens exactly. instruction = "استمع واختر شكل فصل الكلمات الصحيح." elif response_kind == "visual_word_boundary_mapping": if diagnostic_condition == "merge_error_candidate": instruction = "استمع واختر الحدود دون دمج الكلمات." elif diagnostic_condition == "split_error_candidate": instruction = "استمع واختر الحدود دون تقسيم زائد." else: instruction = "استمع واختر شكل حدود الكلمات الصحيح." else: instruction = "استمع واختر تمثيل الكلمات الصحيح." out["question"] = instruction out["prompt"] = instruction out["text"] = instruction if operation_id == "discriminate_merged_word_boundary": student_help = "اختر الشكل الذي يحافظ على كل حدود الكلمات." elif operation_id == "discriminate_oversegmented_word_boundary": student_help = "اختر الشكل دون إضافة فاصل زائد." else: student_help = "اختر الشكل الموافق للجملة المسموعة." out["evidence_operation_id"] = operation_id out["interaction_payload"] = { "left_items": [copy.deepcopy(source)], "drag_items": [copy.deepcopy(source)], "targets": copy.deepcopy(targets), "drop_zones": copy.deepcopy(targets), "mapping_answer": copy.deepcopy(mapping), "correct_mapping": copy.deepcopy(mapping), "evidence_operation_id": operation_id, "student_help": student_help, "student_legend": "● = كلمة، | = فاصل", "internal_labels_visible": False, } out["correct_mapping"] = copy.deepcopy(mapping) out["correct_answer"] = copy.deepcopy(mapping) out["correct_response"] = copy.deepcopy(mapping) out["answer"] = copy.deepcopy(mapping) # No model semantic pair/items/targets may leak into rendering. out.pop("pairs", None) out.pop("items", None) out.pop("targets", None) out["options"] = [] out["choices"] = [] # Only target answers must be token-only. The neutral source descriptor # does not reveal the hidden audio transcript. for record in targets: for key in ("label", "label_ar"): value = record.get(key) if not _token_only_visual(value, allowed): errors.append(f"visual_token_contract_violation:{key}") audit["compiled_fields"].extend([ "interaction_payload", "correct_mapping", "correct_answer", "correct_response", "answer", ]) audit["semantic_inputs_consumed"].append("audio_text") audit["visual_policy"] = { "kind": _text(response.get("kind")), "allowed_visual_tokens": allowed, "written_word_labels_exposed": False, "word_count": word_count, "diagnostic_condition": diagnostic_condition, "evidence_operation_id": operation_id, } return out, list(dict.fromkeys(errors)) def _validate_declared_visual_surface( q: Dict[str, Any], response: Dict[str, Any], ) -> List[str]: """Fail closed if forbidden written labels reach any visible interaction field.""" allowed = [ _text(x) for x in _as_list(response.get("allowed_visual_tokens")) if _text(x) ] if not allowed or response.get("text_word_options_forbidden") is not True: return [] errors: List[str] = [] payload = _as_dict(q.get("interaction_payload")) visible_records: List[Dict[str, Any]] = [] for key in ("left_items", "drag_items", "targets", "drop_zones", "items"): for row in _as_list(payload.get(key)): if isinstance(row, dict): visible_records.append(row) for row in visible_records: is_audio_source = bool( _text(row.get("audio_asset_role")) == "prompt_audio" or _text(row.get("id")) in {"stimulus_audio", "stimulus_media"} ) for key in ("label", "label_ar", "text", "visual_token"): if key not in row: continue if is_audio_source and key in {"label", "label_ar", "text"}: continue if not _token_only_visual(row.get(key), allowed): errors.append(f"visual_surface_forbidden_text:{key}") for key in ("options", "choices"): for value in _as_list(q.get(key)): label = _label(value) if label and not _token_only_visual(label, allowed): errors.append(f"visual_surface_forbidden_text:{key}") return list(dict.fromkeys(errors)) def _hidden_audio_sequence_enabled( *, family: str, ownership: Dict[str, Any], response: Dict[str, Any], stimulus_contract: Dict[str, Any], recipe: Dict[str, Any], ) -> bool: """Generic contract/ownership test for audio-only sequence mechanics.""" if _lower(family) != "sequence": return False if ownership.get("hidden_audio_sequence_scope_guard") is True: return True writable = { str(x) for x in _as_list(ownership.get("model_writable_fields")) if _text(x) } audio_required = bool( ownership.get("stimulus_audio_text_required") is True or stimulus_contract.get("audio_text_required") is True ) model_items_forbidden = bool(writable and "items" not in writable) # Declarative recipe signals. Keep these generic; no skill/template ids. hidden_text_flags = any( source.get(key) is True for source in (recipe, response, stimulus_contract) for key in ( "reading_dependency_forbidden", "avoid_visual_text_dependency", "visible_orthographic_word_tokens_forbidden_when_decoding_not_target", "semantic_audio_labels_must_not_be_used_as_visible_mechanics", "visible_transcript_forbidden", "visible_audio_transcript_forbidden", "text_word_options_forbidden", ) if isinstance(source, dict) ) spoken_units = any( source.get(key) is True for source in (recipe, response, stimulus_contract) for key in ( "spoken_word_units_required", "audio_for_word_units_required", ) if isinstance(source, dict) ) return bool( audio_required and ( model_items_forbidden or hidden_text_flags or spoken_units ) ) def _compile_hidden_audio_sequence( q: Dict[str, Any], *, src: Dict[str, Any], audit: Dict[str, Any], ) -> Tuple[Dict[str, Any], List[str]]: """Compile a spoken sentence into audio-only ordering units. Qwen owns the linguistic sentence in ``audio_text``. The platform performs the deterministic split, creates internal ids, shuffles presentation order, and stores the correct id order. Written stimulus words are never copied into any visible label/semantic_value/value field. Each ordering record retains its word only in ``audio_text`` so downstream media generation can synthesize/play the individual spoken unit. """ out = copy.deepcopy(q) errors: List[str] = [] words = _spoken_words(out.get("audio_text")) if len(words) < 2: return out, ["semantic_required:audio_text_sequence_units"] records: List[Dict[str, Any]] = [] for index, word in enumerate(words): rid = f"audio_item_{index + 1}" records.append({ "id": rid, # Neutral visible surface. No correct-position numbering and no # transcript word in renderer-facing semantic fields. "label": "🔊", "label_ar": "🔊", "semantic_value": rid, "value": rid, "visual_token": "🔊", # Hidden semantic/media source only. "audio_text": word, "audio_asset_role": "sequence_item_audio", "transcript_visible": False, }) correct_ids = [_text(x.get("id")) for x in records] seed = _text( src.get("runtime_generation_seed") or src.get("seed") or _as_dict(src.get("assessment_generation_contract")).get("runtime_generation_seed") or src.get("skill_id") or out.get("audio_text") or "hidden_audio_sequence" ) display_records = _stable_shuffle(records, seed) out["interaction_payload"] = { "ordering_items": copy.deepcopy(display_records), "items": copy.deepcopy(display_records), "correct_order": list(correct_ids), "audio_only_sequence": True, "visible_transcript": False, "internal_labels_visible": False, } out["correct_answer"] = list(correct_ids) out["correct_response"] = list(correct_ids) out["answer"] = list(correct_ids) # No semantic transport arrays may compete with deterministic mechanics. out.pop("items", None) out.pop("targets", None) out.pop("pairs", None) out["options"] = [] out["choices"] = [] audit["semantic_inputs_consumed"].append("audio_text") audit["compiled_fields"].extend([ "interaction_payload", "correct_answer", "correct_response", "answer", ]) audit["hidden_audio_sequence"] = { "enabled": True, "spoken_unit_count": len(records), "written_word_labels_exposed": False, "media_source_field": "ordering_items[].audio_text", "visible_token": "🔊", } return out, errors def _validate_hidden_audio_sequence_surface(q: Dict[str, Any]) -> List[str]: """Fail closed if a hidden-audio sequence exposes transcript text visibly.""" payload = _as_dict(q.get("interaction_payload")) if payload.get("audio_only_sequence") is not True: return [] errors: List[str] = [] for row in _as_list(payload.get("ordering_items") or payload.get("items")): if not isinstance(row, dict): continue hidden_audio = _text(row.get("audio_text")) hidden_norm = _norm(hidden_audio) for key in ("label", "label_ar", "text", "semantic_value", "value"): visible = _text(row.get(key)) if not visible: continue # Internal ids are allowed in semantic/value; transcript words are not. if hidden_norm and _norm(visible) == hidden_norm: errors.append(f"hidden_audio_sequence_visible_transcript:{key}") if row.get("transcript_visible") is True: errors.append("hidden_audio_sequence_transcript_visible_flag") return list(dict.fromkeys(errors)) def execute( candidate: Dict[str, Any], payload: Dict[str, Any], ) -> Tuple[Dict[str, Any], List[str], Dict[str, Any]]: """Compile semantic model output into deterministic question mechanics. Returns: (compiled_question, errors, audit) Errors use ``semantic_required:`` when only Qwen can supply missing semantic truth. Structural mechanics are never requested from Qwen. """ q = copy.deepcopy(candidate if isinstance(candidate, dict) else {}) src = dict(payload or {}) if isinstance(payload, dict) else {} recipe = ( src.get("generation_recipe") or src.get("resolved_generation_recipe") or {} ) recipe = recipe if isinstance(recipe, dict) else {} response = _as_dict(recipe.get("response_contract")) stimulus_contract = _as_dict(recipe.get("stimulus_contract")) response_kind = _lower(response.get("kind")) ownership = ( src.get("model_output_ownership") if isinstance(src.get("model_output_ownership"), dict) else {} ) system_values = _as_dict(ownership.get("system_owned_values")) # Immutable mechanics/identity. for key in ("template_id", "item_type", "difficulty", "response_mode", "scoring_mode"): if src.get(key) not in (None, ""): q[key] = copy.deepcopy(src.get(key)) q["question_type"] = q.get("item_type") if system_values.get("question") not in (None, ""): instruction = _text(system_values.get("question")) q["question"] = instruction q["prompt"] = instruction q["text"] = instruction text_options_forbidden = bool( response.get("options_forbidden") is True or response.get("text_word_options_forbidden") is True ) if text_options_forbidden: q["options"] = [] q["choices"] = [] family = canonical_family( q.get("response_family"), q.get("response_mode") or src.get("response_mode"), q.get("item_type") or src.get("item_type"), q.get("scoring_mode") or src.get("scoring_mode"), ) q["response_family"] = family hidden_audio_sequence = _hidden_audio_sequence_enabled( family=family, ownership=ownership, response=response, stimulus_contract=stimulus_contract, recipe=recipe, ) audit: Dict[str, Any] = { "executor_version": VERSION, "family": family, "mechanics_owner": "system", "semantic_owner": "qwen_or_authoritative_source", "compiled_fields": [], "semantic_inputs_consumed": [], "guessed_semantic_truth": False, } errors: List[str] = [] declared_visual_word_mapping = bool( family == "pair" and response_kind in { "visual_word_segmentation_mapping", "visual_word_boundary_mapping", "visual_word_unit_mapping", } and response.get("text_word_options_forbidden") is True and _as_list(response.get("allowed_visual_tokens")) ) if declared_visual_word_mapping: q, visual_errors = _compile_declared_visual_word_mapping( q, response=response, stimulus_contract=stimulus_contract, audit=audit, ) errors.extend(visual_errors) elif family == "pair": existing_payload = _as_dict(q.get("interaction_payload")) left = _records( q.get("items") or existing_payload.get("drag_items") or existing_payload.get("left_items") or existing_payload.get("items") or [], "item", ) targets = _records( q.get("targets") or existing_payload.get("drop_zones") or existing_payload.get("right_items") or existing_payload.get("targets") or [], "target", ) relations = _relation_rows(q.get("pairs")) if relations: audit["semantic_inputs_consumed"].append("pairs") if not relations: relations = _mapping_rows( q.get("correct_mapping") or existing_payload.get("correct_mapping") or existing_payload.get("mapping_answer") or ( q.get("correct_answer") if isinstance(q.get("correct_answer"), dict) else {} ) ) if relations: audit["semantic_inputs_consumed"].append("existing_semantic_mapping") # A scalar answer can deterministically select one target only when there is # exactly one source item. The scalar itself is semantic truth supplied upstream. scalar_answer = q.get("correct_answer") if not relations and scalar_answer not in (None, "", [], {}) and not isinstance(scalar_answer, (dict, list, tuple, set)): if not left and _text(q.get("audio_text")): left = [{ "id": "stimulus_audio", "label": "", "label_ar": "", "semantic_value": "audio_stimulus", "value": "audio_stimulus", "visual_token": "🔊", "audio_asset_role": "prompt_audio", }] if len(left) == 1 and targets: relations = [(left[0].get("semantic_value") or left[0].get("id"), scalar_answer)] audit["semantic_inputs_consumed"].append("scalar_correct_answer") # Semantic pair rows can themselves create the content records. for lval, rval in relations: _ensure_record(left, lval, "item") _ensure_record(targets, rval, "target") if not relations: errors.append("semantic_required:pairs") if not left: errors.append("semantic_required:items") if len(targets) < 2: # Pair renderer requires at least two possible targets. errors.append("semantic_required:targets") if not errors: left_lookup = _lookup(left) target_lookup = _lookup(targets) mapping: Dict[str, str] = {} for lval, rval in relations: lid = left_lookup.get(_norm(_semantic_key(lval) or _label(lval))) tid = target_lookup.get(_norm(_semantic_key(rval) or _label(rval))) if not lid: errors.append("semantic_relation_unknown:left") continue if not tid: errors.append("semantic_relation_unknown:right") continue mapping[lid] = tid if not mapping: errors.append("semantic_required:pairs") elif set(mapping.keys()) != {_text(x.get("id")) for x in left}: errors.append("semantic_required:pairs_complete_coverage") else: payload_out = { "left_items": copy.deepcopy(left), "drag_items": copy.deepcopy(left), "targets": copy.deepcopy(targets), "drop_zones": copy.deepcopy(targets), "mapping_answer": copy.deepcopy(mapping), "correct_mapping": copy.deepcopy(mapping), } q["interaction_payload"] = payload_out q["correct_mapping"] = copy.deepcopy(mapping) q["correct_answer"] = copy.deepcopy(mapping) q["correct_response"] = copy.deepcopy(mapping) q["answer"] = copy.deepcopy(mapping) q["scoring_mode"] = q.get("scoring_mode") or "pair_match" audit["compiled_fields"].extend([ "interaction_payload", "correct_mapping", "correct_answer", "correct_response", "answer", ]) elif family == "sequence": if hidden_audio_sequence: q, sequence_errors = _compile_hidden_audio_sequence( q, src=src, audit=audit, ) errors.extend(sequence_errors) else: semantic_items = q.get("items") if semantic_items in (None, "", [], {}): existing = _as_dict(q.get("interaction_payload")) semantic_items = ( existing.get("semantic_items") or existing.get("ordering_items") or q.get("correct_answer") or [] ) records = _records(semantic_items, "item") if len(records) < 2: errors.append("semantic_required:items") else: correct_ids = [_text(x.get("id")) for x in records] seed = _text( src.get("runtime_generation_seed") or src.get("seed") or _as_dict(src.get("assessment_generation_contract")).get("runtime_generation_seed") or src.get("skill_id") or "sequence" ) display_records = _stable_shuffle(records, seed) q["interaction_payload"] = { "ordering_items": copy.deepcopy(display_records), "items": copy.deepcopy(display_records), "correct_order": list(correct_ids), } q["correct_answer"] = list(correct_ids) q["correct_response"] = list(correct_ids) q["answer"] = list(correct_ids) audit["semantic_inputs_consumed"].append("items") audit["compiled_fields"].extend([ "interaction_payload", "correct_answer", "correct_response", "answer", ]) elif family in {"single_choice", "multi_choice"}: opts = q.get("options") if opts in (None, "", [], {}): opts = q.get("choices") if isinstance(opts, dict): opts = list(opts.values()) opts = list(opts) if isinstance(opts, list) else [] if len(opts) < 2: errors.append("semantic_required:options") answer = q.get("correct_answer") if answer in (None, "", [], {}): errors.append("semantic_required:correct_answer") if not errors: q["options"] = copy.deepcopy(opts) q["choices"] = copy.deepcopy(opts) q["correct_response"] = copy.deepcopy(answer) q["answer"] = copy.deepcopy(answer) audit["compiled_fields"].extend(["options", "choices", "correct_response", "answer"]) elif family in {"numeric", "text"}: answer = q.get("correct_answer") if answer in (None, "", [], {}): errors.append("semantic_required:correct_answer") else: q["correct_response"] = copy.deepcopy(answer) q["answer"] = copy.deepcopy(answer) audit["compiled_fields"].extend(["correct_response", "answer"]) # oral/external mechanics are evaluator/tool-owned and need no fabricated answer. # Semantic-only transport fields never reach renderer/scoring as competing truth. for key in ("pairs", "items", "targets"): if key in q: q.pop(key, None) errors.extend(_validate_declared_visual_surface(q, response)) if hidden_audio_sequence: errors.extend(_validate_hidden_audio_sequence_surface(q)) errors = list(dict.fromkeys(errors)) q = canonicalize_question(q) q["deterministic_executor_version"] = VERSION q["deterministic_mechanics_compiled"] = not bool(errors) return q, list(dict.fromkeys(errors)), audit def summary() -> Dict[str, Any]: return { "success": True, "version": VERSION, "qwen_scope": "semantic_linguistic_content_only", "system_scope": "deterministic_mechanics", "families": [ "single_choice", "multi_choice", "pair", "sequence", "numeric", "text", "oral", "external", ], "interaction_contract_version": INTERACTION_CONTRACT_VERSION, "zero_semantic_guess": True, "declared_visual_modality_guard": True, "written_word_label_leakage_forbidden": True, "student_facing_internal_ids_forbidden": True, "hidden_audio_sequence_from_audio_text": True, "hidden_audio_sequence_written_words_visible": False, "hidden_audio_sequence_item_media_field": "ordering_items[].audio_text", "pair_display_semantic_separate_from_structural_id": True, "clear_audio_source_descriptor": True, }