2025-08-11 18:22:01 +02:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
"""
|
2025-08-11 19:02:01 +02:00
|
|
|
|
exercise_router.py – v1.6.2
|
|
|
|
|
|
|
|
|
|
|
|
Fix:
|
|
|
|
|
|
- Entfernt Import von `WithPayloadSelector` (nicht in allen qdrant-client Builds exportiert)
|
|
|
|
|
|
- Scroll-Aufrufe liefern Payload jetzt über `with_payload=True` (breit kompatibel)
|
|
|
|
|
|
- Rest wie v1.6.1: Capability-Facetten + Listen-Normalisierung, Idempotenz via external_id
|
2025-08-11 18:22:01 +02:00
|
|
|
|
"""
|
2025-08-10 13:39:27 +02:00
|
|
|
|
|
2025-08-10 08:06:10 +02:00
|
|
|
|
from fastapi import APIRouter, HTTPException, Query
|
|
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
|
|
from typing import List, Optional, Dict, Any
|
|
|
|
|
|
from uuid import uuid4
|
2025-08-11 06:42:59 +02:00
|
|
|
|
from datetime import datetime
|
2025-08-10 08:06:10 +02:00
|
|
|
|
from clients import model, qdrant
|
2025-08-11 06:42:59 +02:00
|
|
|
|
from qdrant_client.models import (
|
|
|
|
|
|
PointStruct,
|
|
|
|
|
|
VectorParams,
|
|
|
|
|
|
Distance,
|
|
|
|
|
|
PointIdsList,
|
2025-08-11 18:59:27 +02:00
|
|
|
|
Filter,
|
|
|
|
|
|
FieldCondition,
|
|
|
|
|
|
MatchValue,
|
2025-08-11 06:42:59 +02:00
|
|
|
|
)
|
|
|
|
|
|
import os
|
2025-08-10 08:06:10 +02:00
|
|
|
|
|
|
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
# =========================
|
|
|
|
|
|
# Models
|
|
|
|
|
|
# =========================
|
2025-08-10 08:06:10 +02:00
|
|
|
|
class Exercise(BaseModel):
|
|
|
|
|
|
id: str = Field(default_factory=lambda: str(uuid4()))
|
2025-08-11 18:22:01 +02:00
|
|
|
|
# Upsert-Metadaten
|
2025-08-11 06:42:59 +02:00
|
|
|
|
external_id: Optional[str] = None # z.B. "mw:12345"
|
|
|
|
|
|
fingerprint: Optional[str] = None # sha256 über Kernfelder
|
|
|
|
|
|
source: Optional[str] = None # Herkunft, z.B. "MediaWiki"
|
2025-08-11 18:59:27 +02:00
|
|
|
|
imported_at: Optional[datetime] = None # vom Import gesetzt (ISO-String wird akzeptiert)
|
2025-08-11 06:42:59 +02:00
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
# Domain-Felder
|
2025-08-10 08:06:10 +02:00
|
|
|
|
title: str
|
|
|
|
|
|
summary: str
|
|
|
|
|
|
short_description: str
|
|
|
|
|
|
keywords: List[str] = []
|
|
|
|
|
|
link: Optional[str] = None
|
|
|
|
|
|
discipline: str
|
|
|
|
|
|
group: Optional[str] = None
|
|
|
|
|
|
age_group: str
|
|
|
|
|
|
target_group: str
|
|
|
|
|
|
min_participants: int
|
|
|
|
|
|
duration_minutes: int
|
|
|
|
|
|
capabilities: Dict[str, int] = {}
|
|
|
|
|
|
category: str
|
|
|
|
|
|
purpose: str
|
|
|
|
|
|
execution: str
|
|
|
|
|
|
notes: str
|
|
|
|
|
|
preparation: str
|
|
|
|
|
|
method: str
|
|
|
|
|
|
equipment: List[str] = []
|
|
|
|
|
|
|
|
|
|
|
|
class DeleteResponse(BaseModel):
|
|
|
|
|
|
status: str
|
|
|
|
|
|
count: int
|
|
|
|
|
|
collection: str
|
|
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
# =========================
|
|
|
|
|
|
# Helpers
|
|
|
|
|
|
# =========================
|
|
|
|
|
|
COLLECTION = os.getenv("EXERCISE_COLLECTION", "exercises")
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
def _ensure_collection():
|
2025-08-11 18:22:01 +02:00
|
|
|
|
"""Sicherstellen, dass die Collection existiert (kein Drop)."""
|
2025-08-11 06:42:59 +02:00
|
|
|
|
if not qdrant.collection_exists(COLLECTION):
|
2025-08-10 08:06:10 +02:00
|
|
|
|
qdrant.recreate_collection(
|
2025-08-11 06:42:59 +02:00
|
|
|
|
collection_name=COLLECTION,
|
2025-08-10 08:06:10 +02:00
|
|
|
|
vectors_config=VectorParams(
|
|
|
|
|
|
size=model.get_sentence_embedding_dimension(),
|
2025-08-11 06:42:59 +02:00
|
|
|
|
distance=Distance.COSINE,
|
|
|
|
|
|
),
|
2025-08-10 08:06:10 +02:00
|
|
|
|
)
|
2025-08-11 06:42:59 +02:00
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
def _lookup_by_external_id(external_id: str) -> Optional[Dict[str, Any]]:
|
2025-08-11 18:59:27 +02:00
|
|
|
|
"""Lookup via Payload-Filter. Liefert die gespeicherte Payload (mit allen Feldern)."""
|
2025-08-11 06:42:59 +02:00
|
|
|
|
_ensure_collection()
|
|
|
|
|
|
flt = Filter(must=[FieldCondition(key="external_id", match=MatchValue(value=external_id))])
|
2025-08-11 18:59:27 +02:00
|
|
|
|
pts, _ = qdrant.scroll(
|
|
|
|
|
|
collection_name=COLLECTION,
|
|
|
|
|
|
scroll_filter=flt,
|
|
|
|
|
|
limit=1,
|
2025-08-11 19:02:01 +02:00
|
|
|
|
with_payload=True,
|
2025-08-11 18:59:27 +02:00
|
|
|
|
)
|
2025-08-11 06:42:59 +02:00
|
|
|
|
if not pts:
|
|
|
|
|
|
return None
|
2025-08-11 18:22:01 +02:00
|
|
|
|
doc = dict(pts[0].payload or {})
|
2025-08-11 06:42:59 +02:00
|
|
|
|
doc.setdefault("id", str(pts[0].id))
|
|
|
|
|
|
return doc
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
|
|
|
|
|
|
_DEF_EMBED_FIELDS = ("title", "summary", "short_description", "purpose", "execution", "notes")
|
|
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
|
|
|
|
|
|
def _make_vector(ex: Exercise) -> List[float]:
|
2025-08-11 18:22:01 +02:00
|
|
|
|
text = ". ".join([getattr(ex, f, "") for f in _DEF_EMBED_FIELDS if getattr(ex, f, None)])
|
2025-08-11 06:42:59 +02:00
|
|
|
|
vec = model.encode(text).tolist()
|
|
|
|
|
|
return vec
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
|
|
|
|
|
|
def _norm_list(xs: List[Any]) -> List[str]:
|
|
|
|
|
|
"""Trim + Duplikate entfernen + sortieren (stabil für Filter & Fingerprint)."""
|
|
|
|
|
|
out = []
|
|
|
|
|
|
seen = set()
|
|
|
|
|
|
for x in xs or []:
|
|
|
|
|
|
s = str(x).strip()
|
|
|
|
|
|
if not s:
|
|
|
|
|
|
continue
|
2025-08-11 18:59:27 +02:00
|
|
|
|
key = s.casefold()
|
|
|
|
|
|
if key in seen:
|
2025-08-11 18:22:01 +02:00
|
|
|
|
continue
|
2025-08-11 18:59:27 +02:00
|
|
|
|
seen.add(key)
|
2025-08-11 18:22:01 +02:00
|
|
|
|
out.append(s)
|
|
|
|
|
|
return sorted(out, key=str.casefold)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _facet_capabilities(caps: Dict[str, Any]) -> Dict[str, List[str]]:
|
|
|
|
|
|
caps = caps or {}
|
|
|
|
|
|
def ge(n: int) -> List[str]:
|
|
|
|
|
|
out = []
|
|
|
|
|
|
for k, v in caps.items():
|
|
|
|
|
|
try:
|
|
|
|
|
|
if int(v) >= n:
|
|
|
|
|
|
out.append(str(k))
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
return sorted({s.strip() for s in out if s.strip()}, key=str.casefold)
|
|
|
|
|
|
all_keys = sorted({str(k).strip() for k in caps.keys() if str(k).strip()}, key=str.casefold)
|
|
|
|
|
|
return {
|
|
|
|
|
|
"capability_keys": all_keys,
|
|
|
|
|
|
"capability_ge1": ge(1),
|
|
|
|
|
|
"capability_ge2": ge(2),
|
|
|
|
|
|
"capability_ge3": ge(3),
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _response_strip_extras(payload: Dict[str, Any]) -> Dict[str, Any]:
|
2025-08-11 18:59:27 +02:00
|
|
|
|
"""Nur Felder zurückgeben, die im Pydantic-Modell existieren (Extra-Felder bleiben im Qdrant-Payload)."""
|
|
|
|
|
|
allowed = set(Exercise.model_fields.keys()) # Pydantic v2
|
2025-08-11 18:22:01 +02:00
|
|
|
|
return {k: v for k, v in payload.items() if k in allowed}
|
|
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
# =========================
|
|
|
|
|
|
# Endpoints
|
|
|
|
|
|
# =========================
|
2025-08-11 18:22:01 +02:00
|
|
|
|
@router.get("/exercise/by-external-id")
|
2025-08-11 06:42:59 +02:00
|
|
|
|
def get_exercise_by_external_id(external_id: str = Query(..., min_length=3)):
|
|
|
|
|
|
"""Lookup für Idempotenz im Importer. Liefert 404, wenn nicht vorhanden."""
|
|
|
|
|
|
found = _lookup_by_external_id(external_id)
|
|
|
|
|
|
if not found:
|
|
|
|
|
|
raise HTTPException(status_code=404, detail="not found")
|
|
|
|
|
|
return found
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
@router.post("/exercise", response_model=Exercise)
|
|
|
|
|
|
def create_or_update_exercise(ex: Exercise):
|
|
|
|
|
|
"""
|
2025-08-11 18:22:01 +02:00
|
|
|
|
Upsert-Semantik. Wenn `external_id` existiert und bereits in Qdrant gefunden wird,
|
2025-08-11 06:42:59 +02:00
|
|
|
|
wird dieselbe Point-ID überschrieben (echtes Update). Ansonsten neuer Eintrag.
|
|
|
|
|
|
API-Signatur bleibt identisch (POST /exercise, Body = Exercise).
|
|
|
|
|
|
"""
|
|
|
|
|
|
_ensure_collection()
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
# Bestehende Point-ID übernehmen, falls external_id bereits vorhanden ist
|
2025-08-11 06:42:59 +02:00
|
|
|
|
point_id = ex.id
|
|
|
|
|
|
if ex.external_id:
|
|
|
|
|
|
prior = _lookup_by_external_id(ex.external_id)
|
|
|
|
|
|
if prior:
|
|
|
|
|
|
point_id = prior.get("id", point_id)
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
# Embedding
|
2025-08-11 06:42:59 +02:00
|
|
|
|
vector = _make_vector(ex)
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
# Payload stabilisieren + Facetten einfügen
|
2025-08-11 18:59:27 +02:00
|
|
|
|
payload: Dict[str, Any] = ex.model_dump()
|
2025-08-11 06:42:59 +02:00
|
|
|
|
payload["id"] = str(point_id)
|
2025-08-11 18:22:01 +02:00
|
|
|
|
payload["keywords"] = _norm_list(payload.get("keywords") or [])
|
|
|
|
|
|
payload["equipment"] = _norm_list(payload.get("equipment") or [])
|
|
|
|
|
|
|
|
|
|
|
|
facet = _facet_capabilities(payload.get("capabilities") or {})
|
|
|
|
|
|
# Extra-Felder nur im gespeicherten Payload verwenden (für Filter), nicht in der Response
|
|
|
|
|
|
payload.update(facet)
|
2025-08-11 06:42:59 +02:00
|
|
|
|
|
|
|
|
|
|
# Upsert in Qdrant
|
|
|
|
|
|
qdrant.upsert(
|
|
|
|
|
|
collection_name=COLLECTION,
|
|
|
|
|
|
points=[PointStruct(id=str(point_id), vector=vector, payload=payload)],
|
2025-08-10 08:06:10 +02:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
return Exercise(**_response_strip_extras(payload))
|
|
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
|
|
|
|
|
|
@router.get("/exercise/{exercise_id}", response_model=Exercise)
|
|
|
|
|
|
def get_exercise(exercise_id: str):
|
|
|
|
|
|
_ensure_collection()
|
|
|
|
|
|
pts, _ = qdrant.scroll(
|
|
|
|
|
|
collection_name=COLLECTION,
|
|
|
|
|
|
scroll_filter=Filter(must=[FieldCondition(key="id", match=MatchValue(value=exercise_id))]),
|
|
|
|
|
|
limit=1,
|
2025-08-11 19:02:01 +02:00
|
|
|
|
with_payload=True,
|
2025-08-11 06:42:59 +02:00
|
|
|
|
)
|
|
|
|
|
|
if not pts:
|
|
|
|
|
|
raise HTTPException(status_code=404, detail="not found")
|
|
|
|
|
|
payload = dict(pts[0].payload or {})
|
|
|
|
|
|
payload.setdefault("id", str(pts[0].id))
|
2025-08-11 18:22:01 +02:00
|
|
|
|
return Exercise(**_response_strip_extras(payload))
|
|
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
|
|
|
|
|
|
@router.delete("/exercise/delete-by-external-id", response_model=DeleteResponse)
|
|
|
|
|
|
def delete_by_external_id(external_id: str = Query(...)):
|
|
|
|
|
|
_ensure_collection()
|
|
|
|
|
|
flt = Filter(must=[FieldCondition(key="external_id", match=MatchValue(value=external_id))])
|
2025-08-11 19:02:01 +02:00
|
|
|
|
pts, _ = qdrant.scroll(collection_name=COLLECTION, scroll_filter=flt, limit=10000, with_payload=False)
|
2025-08-10 08:06:10 +02:00
|
|
|
|
ids = [str(p.id) for p in pts]
|
|
|
|
|
|
if not ids:
|
2025-08-11 06:42:59 +02:00
|
|
|
|
return DeleteResponse(status="🔍 Keine Einträge gefunden.", count=0, collection=COLLECTION)
|
|
|
|
|
|
qdrant.delete(collection_name=COLLECTION, points_selector=PointIdsList(points=ids))
|
|
|
|
|
|
return DeleteResponse(status="🗑️ gelöscht", count=len(ids), collection=COLLECTION)
|
|
|
|
|
|
|
2025-08-11 18:22:01 +02:00
|
|
|
|
|
2025-08-11 06:42:59 +02:00
|
|
|
|
@router.delete("/exercise/delete-collection", response_model=DeleteResponse)
|
|
|
|
|
|
def delete_collection(collection: str = Query(default=COLLECTION)):
|
2025-08-10 08:06:10 +02:00
|
|
|
|
if not qdrant.collection_exists(collection):
|
|
|
|
|
|
raise HTTPException(status_code=404, detail=f"Collection '{collection}' nicht gefunden.")
|
|
|
|
|
|
qdrant.delete_collection(collection_name=collection)
|
|
|
|
|
|
return DeleteResponse(status="🗑️ gelöscht", count=0, collection=collection)
|