# -*- coding: utf-8 -*- """Deterministic two-design resolver and capability preflight for SmartPaper. U1-R2C intentionally limits production research design to two supported paths: qualitative research and survey-based quantitative research. Specialized cues such as fsQCA, panel data/econometrics, meta-analysis, and bibliometric/review methods are detected only to provide a reader-facing scope notice; they are not exposed as selectable method families and are redirected to the qualitative framework before task creation. This module never selects providers/models and never rewrites Title/Keywords. """ from __future__ import annotations import os import re from typing import Any, Iterable METHOD_RESOLVER_VERSION = "smartpaper-auto-method-resolver-v4" METHOD_CAPABILITY_REGISTRY_VERSION = "smartpaper-method-capability-registry-v3" # Reader-visible / task-owning method families. Order is intentional: # qualitative is the product default and appears first in the selector. METHOD_FAMILIES = ( "qualitative", "survey_path", ) _METHOD_CAPABILITIES: dict[str, dict[str, Any]] = { "qualitative": { "legacy_policy_lane": "asq", "capability_status": "production_supported", "evidence_timing": "pre_literature", "engine_family": "qualitative_engine", }, "survey_path": { "legacy_policy_lane": "amj", "capability_status": "production_supported", "evidence_timing": "pre_literature", "engine_family": "quantitative_engine", }, } # Specialized methods are deliberately NOT method families in U1-R2C. They # are scope cues only. A hit triggers a notice and a qualitative fallback. _SPECIALIZED_METHOD_PATTERNS: tuple[tuple[str, tuple[str, ...]], ...] = ( ( "fsqca", ( r"\bfsqca\b", r"\bfuzzy[- ]set\s+qca\b", r"\bfuzzy[- ]set\s+qualitative\s+comparative\s+analysis\b", r"\bconfigurational\s+(?:analysis|paths?|approach)\b", r"\btruth\s+table\b", r"模糊集定性比较分析", r"定性比较分析", r"组态(?:分析|路径)", r"нечетк\w*.{0,18}сравнительн\w*.{0,18}анализ", r"конфигурационн\w*.{0,12}анализ", r"бұлыңғыр.{0,16}сапалық.{0,16}салыстырмалы.{0,16}талдау", r"конфигурациялық.{0,12}талдау", ), ), ( "meta_analysis", ( r"\bmeta[- ]analysis\b", r"\bmeta[- ]analytic\b", r"\bmeta analysis\b", r"元分析", r"荟萃分析", r"мета[- ]?анализ", r"метааналитическ", r"мета[- ]?талдау", r"метааналитикалық", ), ), ( "panel_econometrics", ( r"\bpanel\s+data\b", r"\bfirm[- ]year\b", r"\bentity\s+fixed\s+effects?\b", r"\bfixed\s+effects?\b", r"\brandom\s+effects?\b", r"\bpanel\s+econometrics?\b", r"\btwo[- ]way\s+fixed\s+effects?\b", r"面板数据", r"固定效应", r"双向固定效应", r"公司[-—– ]?年度", r"панельн\w*.{0,8}данн", r"фиксированн\w*.{0,8}эффект", r"панельдік.{0,8}дерек", r"тұрақты.{0,8}әсер", ), ), ( "bibliometric_review", ( r"\bbibliometric\b", r"\bscience\s+mapping\b", r"\bco[- ]citation\b", r"\bco[- ]word\b", r"\bintegrative\s+(?:theory\s+)?review\b", r"\btheory\s+review\b", r"\bsystematic\s+literature\s+review\b", r"文献计量", r"科学知识图谱", r"共被引", r"共词", r"整合性(?:理论)?综述", r"系统性文献综述", r"文献综述", r"библиометр", r"научн\w*.{0,8}картирован", r"коцитирован", r"интегративн\w*.{0,8}обзор", r"систематическ\w*.{0,8}обзор", r"библиометр", r"ғылыми.{0,8}карталау", r"бірлескен.{0,8}дәйексөз", r"интегративті.{0,8}шолу", r"жүйелі.{0,8}әдебиет.{0,8}шолу", ), ), ) _SUPPORTED_METHOD_PATTERNS: tuple[tuple[str, tuple[str, ...]], ...] = ( ( "qualitative", ( r"\bqualitative\s+(?:study|research|analysis)\b", r"\bgioia\b", r"\bgrounded\s+theory\b", r"\bcase\s+study\b", r"\bcomparative\s+case\b", r"\bprocess\s+study\b", r"\bethnograph", r"\bsemi[- ]structured\s+interviews?\b", r"\binterviews?\b", r"定性研究", r"质性研究", r"扎根理论", r"案例研究", r"个案研究", r"访谈", r"民族志", r"качественн\w*.{0,8}(?:исследован|анализ)", r"обоснованн\w*.{0,8}теори", r"интервью", r"кейс[- ]?исследован", r"сапалық.{0,8}(?:зерттеу|талдау)", r"негізделген.{0,8}теори", r"сұхбат", r"кейс.{0,8}зерттеу", ), ), ( "survey_path", ( r"\bsurvey\b", r"\bquestionnaire\b", r"\bstructural\s+equation\s+model", r"\bsem\b", r"\bpls[- ]sem\b", r"\bregression\b", r"\bmediating\s+role\b", r"\bmoderating\s+role\b", r"\bmediation\b", r"\bmoderation\b", r"问卷", r"结构方程", r"回归", r"中介(?:作用|效应|变量)?", r"调节(?:作用|效应|变量)?", r"опрос", r"анкет", r"структурн\w*.{0,10}уравнен", r"регресс", r"медиирующ", r"модерирующ", r"сауалнама", r"құрылымдық.{0,10}теңдеу", r"регресс", r"медиаторлық", r"модераторлық", ), ), ) def _normalized_text(value: Any) -> str: return re.sub(r"\s+", " ", str(value or "")).strip() def _keyword_items(value: Any) -> list[str]: if isinstance(value, (list, tuple)): raw = list(value) else: raw = re.split(r"[;\n|]+", str(value or "")) if len(raw) == 1: raw = re.split(r"[,]", str(value or "")) return [_normalized_text(item) for item in raw if _normalized_text(item)] def _material_descriptors(materials: Iterable[Any] | None) -> list[dict[str, str]]: out: list[dict[str, str]] = [] for item in materials or []: if isinstance(item, dict): name = _normalized_text(item.get("name") or item.get("filename")) mime = _normalized_text(item.get("mime_type") or item.get("type")) else: name = _normalized_text(getattr(item, "name", "")) mime = _normalized_text(getattr(item, "type", "")) if not name and not mime: continue out.append({ "name": name, "mime_type": mime, "extension": os.path.splitext(name)[1].lower().lstrip("."), }) return out def method_capability(method_family: str) -> dict[str, Any]: """Return a copy of versioned capability metadata for one supported family.""" family = str(method_family or "").strip().casefold() row = dict(_METHOD_CAPABILITIES.get(family) or {}) if not row: return { "registry_version": METHOD_CAPABILITY_REGISTRY_VERSION, "method_family": "undetermined", "legacy_policy_lane": None, "capability_status": "ambiguous", "evidence_timing": "undetermined", "engine_family": "undetermined", } row.update({ "registry_version": METHOD_CAPABILITY_REGISTRY_VERSION, "method_family": family, }) return row def _pattern_hits(text: str, pattern_rows: tuple[tuple[str, tuple[str, ...]], ...]) -> list[dict[str, Any]]: hits: list[dict[str, Any]] = [] for family, patterns in pattern_rows: matched = [pattern for pattern in patterns if re.search(pattern, text, flags=re.I | re.UNICODE)] if matched: hits.append({"method_family": family, "source": "title_keywords", "match_count": len(matched)}) return hits def resolve_method_family( title: Any, keywords: Any, *, materials: Iterable[Any] | None = None, ) -> dict[str, Any]: """Resolve one of SmartPaper's two supported production research designs. Title + Keywords remain the design authority. Uploaded Research Materials do not alter automatic design selection. Specialized-method cues are kept only as an advisory classification and redirect to qualitative research. """ source_title = _normalized_text(title) source_keywords = _keyword_items(keywords) text = " ; ".join([source_title] + source_keywords) descriptors = _material_descriptors(materials) specialized_hits = _pattern_hits(text, _SPECIALIZED_METHOD_PATTERNS) if specialized_hits: capability = method_capability("qualitative") return { "resolver_version": METHOD_RESOLVER_VERSION, "shadow_only": False, "method_family": "qualitative", "confidence": "SPECIALIZED_METHOD_REDIRECT", "reason_codes": ["specialized_method_cue_detected", "redirect_to_qualitative"], "title_keyword_hits": [], "specialized_method_detected": True, "specialized_method_families": [row["method_family"] for row in specialized_hits], "specialized_method_hits": specialized_hits, "material_hint_families": [], "material_count": len(descriptors), "derived_policy_lane": capability.get("legacy_policy_lane"), "capability": capability, } supported_hits = _pattern_hits(text, _SUPPORTED_METHOD_PATTERNS) chosen = str((supported_hits[0] if supported_hits else {}).get("method_family") or "qualitative") confidence = "AUTO_DETECTED" if supported_hits else "DEFAULT_QUALITATIVE" reason_codes = ["explicit_title_keyword_method_cue"] if supported_hits else ["no_explicit_method_cue", "default_qualitative"] if len(supported_hits) > 1: reason_codes.append("lower_priority_method_cues_present") capability = method_capability(chosen) return { "resolver_version": METHOD_RESOLVER_VERSION, "shadow_only": False, "method_family": chosen, "confidence": confidence, "reason_codes": reason_codes, "title_keyword_hits": supported_hits, "specialized_method_detected": False, "specialized_method_families": [], "specialized_method_hits": [], "material_hint_families": [], "material_count": len(descriptors), "derived_policy_lane": capability.get("legacy_policy_lane"), "capability": capability, } def compare_shadow_to_legacy_lane(resolution: dict[str, Any], selected_lane: Any) -> dict[str, Any]: """Compare inferred design with a legacy AMJ/ASQ lane.""" selected = str(selected_lane or "").strip().casefold() derived = str((resolution or {}).get("derived_policy_lane") or "").strip().casefold() return { "selected_legacy_lane": selected or None, "derived_policy_lane": derived or None, "lane_match": bool(selected and derived and selected == derived), "comparable": bool(selected and derived), } def resolve_generation_preflight( title: Any, keywords: Any, *, materials: Iterable[Any] | None = None, confirmed_method_family: Any = None, ) -> dict[str, Any]: """Resolve the two supported designs before any task/quota creation. Manual adjustment is available only between qualitative and survey-based quantitative research. Specialized-method cues intentionally pin the current topic to the qualitative fallback so a user cannot silently turn a panel/meta/fsQCA/review topic into an ordinary survey manuscript. """ resolution = resolve_method_family(title, keywords, materials=materials) family = str(resolution.get("method_family") or "qualitative").strip().casefold() confirmed = str(confirmed_method_family or "").strip().casefold() specialized = bool(resolution.get("specialized_method_detected")) if not specialized and confirmed in METHOD_FAMILIES and confirmed != family: family = confirmed capability = method_capability(family) resolution = dict(resolution) resolution.update({ "method_family": family, "confidence": "USER_OVERRIDE", "derived_policy_lane": capability.get("legacy_policy_lane"), "capability": capability, "reason_codes": list(resolution.get("reason_codes") or []) + ["user_override_method_family"], }) elif specialized: resolution = dict(resolution) resolution["manual_override_locked"] = True capability = method_capability(family) lane = str(capability.get("legacy_policy_lane") or "").strip().casefold() or None status = str(capability.get("capability_status") or "").strip().casefold() if family not in METHOD_FAMILIES or not lane or status != "production_supported": return { "can_start_generation": False, "block_reason": "method_resolution_invalid", "resolution": resolution, "method_family": family or "qualitative", "legacy_policy_lane": None, "capability": capability, } return { "can_start_generation": True, "block_reason": "", "resolution": resolution, "method_family": family, "legacy_policy_lane": lane, "capability": capability, }