""" Mehrstufiges Retrieval für Planungs-Übungssuche (Phase A). Stufen: S1b-0 Gesamte sichtbare Bibliothek (Governance + Hard-Filter, kein Profil-OR-Pool) S1b-1 Deterministischer Hybrid-Score auf allen Kandidaten → sortiert """ from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple from planning_exercise_profiles import ( PlanningTargetProfile, load_exercise_match_profiles_bulk, score_exercise_against_target, ) _MAX_LIBRARY_ROWS = 8000 _PROFILE_LOAD_BATCH = 400 def _skill_jaccard(a: Set[int], b: Set[int]) -> float: if not a or not b: return 0.0 inter = len(a & b) union = len(a | b) return inter / union if union else 0.0 def _normalize_exercise_kind_filter(exercise_kind_any: Optional[List[str]]) -> List[str]: out: List[str] = [] if not exercise_kind_any: return out for raw in exercise_kind_any: s = str(raw or "").strip().lower() if s in ("simple", "combination") and s not in out: out.append(s) return out def fetch_all_visible_exercise_rows( cur, *, vis_sql: str, vis_params: Sequence[Any], query: str, exercise_kind_any: Optional[List[str]], max_rows: int = _MAX_LIBRARY_ROWS, ) -> List[Dict[str, Any]]: """ S1b-0: Alle sichtbaren Übungen (ohne Profil-/Volltext-Pool-Vorselektion). Hard-Filter: Governance, nicht archiviert, optional exercise_kind. Volltext-Rank nur als Score-Signal in SELECT, nicht als WHERE-Filter. """ where = [vis_sql, "COALESCE(e.status, '') <> %s"] params: List[Any] = [] if query: ft_select = "ts_rank_cd(e.search_vector, plainto_tsquery('german', %s)) AS ft_rank" params.append(query) else: ft_select = "0.0::float AS ft_rank" params.extend(vis_params) params.append("archived") ek_filtered = _normalize_exercise_kind_filter(exercise_kind_any) if ek_filtered: ph = ",".join(["%s"] * len(ek_filtered)) where.append(f"(LOWER(TRIM(COALESCE(e.exercise_kind::text,''))) IN ({ph}))") params.extend(ek_filtered) sql = f""" SELECT e.id, e.title, e.summary, ( SELECT fa.name FROM exercise_focus_areas efa JOIN focus_areas fa ON fa.id = efa.focus_area_id WHERE efa.exercise_id = e.id ORDER BY efa.is_primary DESC NULLS LAST, fa.name ASC LIMIT 1 ) AS primary_focus_name, {ft_select} FROM exercises e WHERE {' AND '.join(where)} ORDER BY e.id ASC LIMIT %s """ params.append(int(max_rows)) cur.execute(sql, params) return [dict(r) for r in cur.fetchall()] def _load_match_profiles_chunked(cur, exercise_ids: Sequence[int], *, batch: int = _PROFILE_LOAD_BATCH): ids = sorted({int(x) for x in exercise_ids if int(x) > 0}) if not ids: return {} out: Dict[int, Any] = {} for i in range(0, len(ids), batch): chunk = ids[i : i + batch] out.update(load_exercise_match_profiles_bulk(cur, chunk)) return out def _load_skill_sets_chunked(cur, exercise_ids: Sequence[int], *, batch: int = _PROFILE_LOAD_BATCH) -> Dict[int, Set[int]]: ids = sorted({int(x) for x in exercise_ids if int(x) > 0}) out: Dict[int, Set[int]] = {eid: set() for eid in ids} if not ids: return out for i in range(0, len(ids), batch): chunk = ids[i : i + batch] ph = ",".join(["%s"] * len(chunk)) cur.execute( f"SELECT exercise_id, skill_id FROM exercise_skills WHERE exercise_id IN ({ph})", chunk, ) for row in cur.fetchall(): eid = int(row["exercise_id"]) sid = row.get("skill_id") if sid is not None: out.setdefault(eid, set()).add(int(sid)) return out def rank_visible_library_hits( cur, rows: Sequence[Dict[str, Any]], *, query: str, intent: str, intent_weights: Mapping[str, float], target: PlanningTargetProfile, pack: Mapping[str, Any], ) -> Tuple[List[Dict[str, Any]], Dict[int, Set[int]]]: """S1b-1: Hybrid-Score auf der gesamten sichtbaren Bibliothek.""" planned_set = set(pack.get("planned_exercise_ids") or []) group_recent_set = set(pack.get("group_recent_exercise_ids") or []) progression_set = set(pack.get("progression_successor_ids") or []) anchor_skills = set(pack.get("anchor_skill_ids") or []) anchor_id = pack.get("anchor_exercise_id") progression_notes = pack.get("progression_edge_notes") or {} last_planned_skills: Set[int] = set() planned_ids = pack.get("planned_exercise_ids") or [] if planned_ids: cur.execute( "SELECT skill_id FROM exercise_skills WHERE exercise_id = %s", (int(planned_ids[-1]),), ) last_planned_skills = {int(r["skill_id"]) for r in cur.fetchall() if r.get("skill_id")} cand_rows: List[Dict[str, Any]] = [] for row in rows: eid = int(row["id"]) if anchor_id and eid == int(anchor_id): continue cand_rows.append(row) cand_ids = [int(r["id"]) for r in cand_rows] match_profiles = _load_match_profiles_chunked(cur, cand_ids) skills_by_ex = _load_skill_sets_chunked(cur, cand_ids) max_ft = 0.0 scored_items: List[Dict[str, Any]] = [] for row in cand_rows: eid = int(row["id"]) ft = float(row.get("ft_rank") or 0.0) if ft > max_ft: max_ft = ft scored_items.append( { "row": row, "eid": eid, "ft": ft, "skills": skills_by_ex.get(eid, set()), } ) weights = dict(intent_weights) hits: List[Dict[str, Any]] = [] for item in scored_items: eid = item["eid"] row = item["row"] ft_norm = (item["ft"] / max_ft) if max_ft > 0 else 0.0 prog_hit = 1.0 if eid in progression_set else 0.0 skill_sim = _skill_jaccard(anchor_skills, item["skills"]) if anchor_skills else 0.0 plan_aff = 0.0 if last_planned_skills and item["skills"]: plan_aff = _skill_jaccard(last_planned_skills, item["skills"]) repeat_unit = 1.0 if eid in planned_set else 0.0 repeat_group = 1.0 if eid in group_recent_set else 0.0 profile_score = 0.0 profile_reasons: List[str] = [] emp = match_profiles.get(eid) if emp: profile_score, profile_reasons = score_exercise_against_target( emp, target, intent=intent ) score = ( weights["fulltext"] * ft_norm + weights["progression"] * prog_hit + weights["skill"] * skill_sim + weights["plan"] * plan_aff + weights["profile"] * profile_score + weights["repeat_unit"] * repeat_unit + weights["repeat_group"] * repeat_group ) reasons: List[str] = [] if query and ft_norm >= 0.35: reasons.append("Volltext-Treffer") if prog_hit > 0: note = progression_notes.get(eid) reasons.append( f"Nachfolger im Progressionsgraph{f': {note}' if note else ''}" ) if skill_sim >= 0.2 and anchor_id: reasons.append("Fähigkeiten passen zur Anker-Übung") if plan_aff >= 0.25: reasons.append("Schließt an Skills der letzten geplanten Übung an") if repeat_unit > 0: reasons.append("Bereits in dieser Einheit eingeplant") if repeat_group > 0 and repeat_unit <= 0: reasons.append("Kürzlich in der Gruppe verwendet") for pr in profile_reasons: if pr not in reasons: reasons.append(pr) if score <= 0 and not reasons and not query: if prog_hit or skill_sim or plan_aff or profile_score: score = 0.05 + prog_hit * 0.3 + skill_sim * 0.2 + profile_score * 0.25 hits.append( { "id": eid, "title": row.get("title"), "summary": row.get("summary"), "focus_area": row.get("primary_focus_name"), "score": round(max(0.0, min(1.0, score)), 4), "reasons": reasons, } ) hits.sort(key=lambda h: (-h["score"], h.get("title") or "")) return hits, skills_by_ex def run_multistage_planning_retrieval( cur, *, vis_sql: str, vis_params: Sequence[Any], query: str, exercise_kind_any: Optional[List[str]], target: PlanningTargetProfile, intent: str, intent_weights: Mapping[str, float], pack: Mapping[str, Any], ) -> Tuple[List[Dict[str, Any]], Dict[int, Set[int]], bool]: """Orchestriert S1b-0 → S1b-1 (Voll-Library-Ranking).""" rows = fetch_all_visible_exercise_rows( cur, vis_sql=vis_sql, vis_params=vis_params, query=query, exercise_kind_any=exercise_kind_any, ) hits, skills_by_ex = rank_visible_library_hits( cur, rows, query=query, intent=intent, intent_weights=intent_weights, target=target, pack=pack, ) full_library_ranked = len(rows) > 0 return hits, skills_by_ex, full_library_ranked # Legacy-Alias für Tests / externe Imports fetch_retrieval_candidate_rows = fetch_all_visible_exercise_rows hybrid_score_planning_hits = rank_visible_library_hits def profile_preselect_rows( cur, rows: Sequence[Dict[str, Any]], *, target: PlanningTargetProfile, intent: str, progression_successor_ids: Set[int], query: str, preselect_limit: int = 160, ) -> Tuple[List[Dict[str, Any]], bool]: """Deprecated: Phase A rankt die volle Library — keine separate Vorselektion.""" _ = (cur, target, intent, progression_successor_ids, query, preselect_limit) return list(rows), False __all__ = [ "fetch_all_visible_exercise_rows", "fetch_retrieval_candidate_rows", "hybrid_score_planning_hits", "profile_preselect_rows", "rank_visible_library_hits", "run_multistage_planning_retrieval", ]