Spaces:
Paused
Paused
feat: coach Qwen+LoRA en deploy
Browse files- Dockerfile +8 -3
- app.py +10 -0
- config.py +11 -1
- modules/analysis/move_facts.py +100 -0
- modules/analysis/stockfish_wrapper.py +13 -3
- modules/llm/guardrails.py +42 -8
- modules/llm/prompt_builder.py +66 -6
- modules/llm/qwen.py +55 -28
- modules/transcription/validator.py +18 -0
- routes/comment.py +37 -3
Dockerfile
CHANGED
|
@@ -20,15 +20,20 @@ RUN pip install --no-cache-dir --upgrade pip \
|
|
| 20 |
--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu121 \
|
| 21 |
&& pip install --no-cache-dir -r requirements.txt
|
| 22 |
|
| 23 |
-
# Pre-descarga del
|
|
|
|
|
|
|
|
|
|
| 24 |
RUN mkdir -p /app/models && \
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
# Código de la app
|
| 28 |
COPY . /app
|
| 29 |
|
| 30 |
ENV STOCKFISH_PATH=/usr/games/stockfish \
|
| 31 |
-
QWEN_MODEL_PATH=/app/models/
|
|
|
|
| 32 |
STOCKFISH_THREADS=2 \
|
| 33 |
STOCKFISH_HASH_MB=128 \
|
| 34 |
PYTHONUNBUFFERED=1
|
|
|
|
| 20 |
--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu121 \
|
| 21 |
&& pip install --no-cache-dir -r requirements.txt
|
| 22 |
|
| 23 |
+
# Pre-descarga del coach (LoRA fine-tuned, GGUF) en build → arranque rápido en
|
| 24 |
+
# runtime. Repo público en HF Hub; ajústalo con --build-arg si cambias el nombre.
|
| 25 |
+
ARG QWEN_COACH_REPO=SamilG2/qwen-coach-checkscan
|
| 26 |
+
ARG QWEN_COACH_FILENAME=qwen-coach-q4_k_m.gguf
|
| 27 |
RUN mkdir -p /app/models && \
|
| 28 |
+
QWEN_COACH_REPO="$QWEN_COACH_REPO" QWEN_COACH_FILENAME="$QWEN_COACH_FILENAME" \
|
| 29 |
+
python -c "from huggingface_hub import hf_hub_download; import os; hf_hub_download(repo_id=os.environ['QWEN_COACH_REPO'], filename=os.environ['QWEN_COACH_FILENAME'], local_dir='/app/models')"
|
| 30 |
|
| 31 |
# Código de la app
|
| 32 |
COPY . /app
|
| 33 |
|
| 34 |
ENV STOCKFISH_PATH=/usr/games/stockfish \
|
| 35 |
+
QWEN_MODEL_PATH=/app/models/qwen-coach-q4_k_m.gguf \
|
| 36 |
+
COACH_MODEL=qwen \
|
| 37 |
STOCKFISH_THREADS=2 \
|
| 38 |
STOCKFISH_HASH_MB=128 \
|
| 39 |
PYTHONUNBUFFERED=1
|
app.py
CHANGED
|
@@ -18,6 +18,16 @@ app.register_blueprint(upload_bp, url_prefix='/api')
|
|
| 18 |
app.register_blueprint(analyze_bp, url_prefix='/api')
|
| 19 |
app.register_blueprint(comment_bp, url_prefix='/api')
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
@app.route('/')
|
| 22 |
@app.route('/api')
|
| 23 |
def index():
|
|
|
|
| 18 |
app.register_blueprint(analyze_bp, url_prefix='/api')
|
| 19 |
app.register_blueprint(comment_bp, url_prefix='/api')
|
| 20 |
|
| 21 |
+
# Diagnóstico de arranque: qué modelo de comentarios leyó realmente el proceso.
|
| 22 |
+
from config import COACH_MODEL, QWEN_MODEL_PATH
|
| 23 |
+
print(
|
| 24 |
+
f"[config] COACH_MODEL={COACH_MODEL!r} | "
|
| 25 |
+
f"QWEN_MODEL_PATH={QWEN_MODEL_PATH!r} | "
|
| 26 |
+
f"gguf_existe={os.path.isfile(QWEN_MODEL_PATH)} | "
|
| 27 |
+
f"os.environ.COACH_MODEL={os.environ.get('COACH_MODEL')!r}",
|
| 28 |
+
flush=True,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
@app.route('/')
|
| 32 |
@app.route('/api')
|
| 33 |
def index():
|
config.py
CHANGED
|
@@ -4,7 +4,17 @@ _ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
|
| 4 |
|
| 5 |
# ─── Modelos ─────────────────────────────────────────────────────────────────
|
| 6 |
TROCR_MODEL_PATH = os.getenv("TROCR_MODEL_PATH", os.path.join(_ROOT, "data", "models", "trocr_finetuned"))
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# ─── Stockfish (motor UCI) ───────────────────────────────────────────────────
|
| 10 |
# En Windows colocar stockfish.exe en backend/engines/ (ver AGENTS.md).
|
|
|
|
| 4 |
|
| 5 |
# ─── Modelos ─────────────────────────────────────────────────────────────────
|
| 6 |
TROCR_MODEL_PATH = os.getenv("TROCR_MODEL_PATH", os.path.join(_ROOT, "data", "models", "trocr_finetuned"))
|
| 7 |
+
|
| 8 |
+
# Modelo Qwen para los comentarios (coach fine-tuned con LoRA, en GGUF).
|
| 9 |
+
# QWEN_MODEL_PATH es la ruta LOCAL del archivo. Si ese archivo no existe (p. ej.
|
| 10 |
+
# en el deploy, donde el GGUF no está en el repo por peso), qwen.py lo descarga
|
| 11 |
+
# automáticamente de QWEN_COACH_REPO en HF Hub — mismo patrón que TrOCR.
|
| 12 |
+
_QWEN_COACH = os.path.join(_ROOT, "data", "models", "qwen-coach-q4_k_m.gguf")
|
| 13 |
+
QWEN_MODEL_PATH = os.getenv("QWEN_MODEL_PATH") or _QWEN_COACH
|
| 14 |
+
|
| 15 |
+
# Repo público de HF Hub con el GGUF del coach. AJUSTA al nombre real de tu repo.
|
| 16 |
+
QWEN_COACH_REPO = os.getenv("QWEN_COACH_REPO", "SamilG2/qwen-coach-checkscan")
|
| 17 |
+
QWEN_COACH_FILENAME = os.getenv("QWEN_COACH_FILENAME", "qwen-coach-q4_k_m.gguf")
|
| 18 |
|
| 19 |
# ─── Stockfish (motor UCI) ───────────────────────────────────────────────────
|
| 20 |
# En Windows colocar stockfish.exe en backend/engines/ (ver AGENTS.md).
|
modules/analysis/move_facts.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hechos REALES de la mejor jugada (TA-002, expandido anclado a la posición).
|
| 2 |
+
|
| 3 |
+
Calcula, con python-chess sobre la posición real, qué logra la `mejor_jugada` de
|
| 4 |
+
Stockfish: si desarrolla, si va al centro, qué pieza rival ataca/captura, si da
|
| 5 |
+
jaque o enroca. Devuelve una frase corta en español que el LLM usa como DATO
|
| 6 |
+
(no inventa nada: todo sale del tablero).
|
| 7 |
+
|
| 8 |
+
Se reconstruye la posición ANTES de la jugada del jugador (a partir del historial
|
| 9 |
+
SAN), que es justo donde aplica la mejor jugada (Stockfish la calcula ahí).
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import chess
|
| 13 |
+
|
| 14 |
+
_PIEZA_ES = {
|
| 15 |
+
chess.PAWN: "peón", chess.KNIGHT: "caballo", chess.BISHOP: "alfil",
|
| 16 |
+
chess.ROOK: "torre", chess.QUEEN: "dama", chess.KING: "rey",
|
| 17 |
+
}
|
| 18 |
+
_HOME_MINOR = {
|
| 19 |
+
chess.WHITE: {chess.B1, chess.G1, chess.C1, chess.F1},
|
| 20 |
+
chess.BLACK: {chess.B8, chess.G8, chess.C8, chess.F8},
|
| 21 |
+
}
|
| 22 |
+
_CENTRO = {chess.D4, chess.E4, chess.D5, chess.E5}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _reconstruir(sans: list[str]) -> chess.Board | None:
|
| 26 |
+
board = chess.Board()
|
| 27 |
+
for san in sans:
|
| 28 |
+
if not san:
|
| 29 |
+
return None
|
| 30 |
+
try:
|
| 31 |
+
board.push_san(san)
|
| 32 |
+
except (ValueError, AssertionError):
|
| 33 |
+
return None
|
| 34 |
+
return board
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def describe_best_move(history_sans: list[str], mejor_en: str | None,
|
| 38 |
+
color_str: str) -> str | None:
|
| 39 |
+
"""Frase factual ('desarrolla tu caballo al centro y ataca el peón rival de
|
| 40 |
+
e5') de lo que logra la mejor jugada. None si no se puede calcular —el
|
| 41 |
+
expandido cae entonces a una explicación genérica."""
|
| 42 |
+
if not mejor_en:
|
| 43 |
+
return None
|
| 44 |
+
board = _reconstruir(list(history_sans))
|
| 45 |
+
if board is None:
|
| 46 |
+
return None
|
| 47 |
+
color = chess.WHITE if color_str == "white" else chess.BLACK
|
| 48 |
+
if board.turn != color: # la posición debe estar al turno del jugador
|
| 49 |
+
return None
|
| 50 |
+
try:
|
| 51 |
+
move = board.parse_san(mejor_en)
|
| 52 |
+
except (ValueError, AssertionError):
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
pieza = board.piece_at(move.from_square)
|
| 56 |
+
if pieza is None:
|
| 57 |
+
return None
|
| 58 |
+
es_enroque = board.is_castling(move)
|
| 59 |
+
es_captura = board.is_capture(move) and not board.is_en_passant(move)
|
| 60 |
+
cap_tipo = board.piece_at(move.to_square).piece_type if es_captura else None
|
| 61 |
+
desarrolla = (pieza.piece_type in (chess.KNIGHT, chess.BISHOP)
|
| 62 |
+
and move.from_square in _HOME_MINOR[color])
|
| 63 |
+
|
| 64 |
+
board.push(move)
|
| 65 |
+
da_jaque = board.is_check()
|
| 66 |
+
dest = move.to_square
|
| 67 |
+
central = dest in _CENTRO
|
| 68 |
+
|
| 69 |
+
# Pieza rival más valiosa que la jugada ataca desde su nueva casilla.
|
| 70 |
+
atacadas = []
|
| 71 |
+
for sq in board.attacks(dest):
|
| 72 |
+
p = board.piece_at(sq)
|
| 73 |
+
if p and p.color != color and p.piece_type != chess.KING:
|
| 74 |
+
atacadas.append((p.piece_type, sq))
|
| 75 |
+
atacadas.sort(key=lambda t: t[0], reverse=True) # dama > torre > menor > peón
|
| 76 |
+
|
| 77 |
+
# ── Redacción factual ─────────────────────────────────────────────────────
|
| 78 |
+
if es_enroque:
|
| 79 |
+
return "pone tu rey a salvo enrocando"
|
| 80 |
+
|
| 81 |
+
nombre = _PIEZA_ES.get(pieza.piece_type, "pieza")
|
| 82 |
+
if desarrolla and central:
|
| 83 |
+
base = f"desarrolla tu {nombre} al centro"
|
| 84 |
+
elif desarrolla:
|
| 85 |
+
base = f"desarrolla tu {nombre}"
|
| 86 |
+
elif central:
|
| 87 |
+
base = f"lleva tu {nombre} al centro"
|
| 88 |
+
else:
|
| 89 |
+
base = f"coloca tu {nombre} en {chess.square_name(dest)}"
|
| 90 |
+
|
| 91 |
+
extras = []
|
| 92 |
+
if cap_tipo is not None:
|
| 93 |
+
extras.append(f"captura el {_PIEZA_ES.get(cap_tipo, 'pieza')} rival")
|
| 94 |
+
elif atacadas:
|
| 95 |
+
tipo, sq = atacadas[0]
|
| 96 |
+
extras.append(f"ataca el {_PIEZA_ES.get(tipo, 'pieza')} rival de {chess.square_name(sq)}")
|
| 97 |
+
if da_jaque:
|
| 98 |
+
extras.append("da jaque")
|
| 99 |
+
|
| 100 |
+
return base + (" y " + " y ".join(extras) if extras else "")
|
modules/analysis/stockfish_wrapper.py
CHANGED
|
@@ -132,10 +132,19 @@ def analyze_pgn(pgn_text: str, depth: int | None = None) -> dict:
|
|
| 132 |
score_before = info_before.get("score")
|
| 133 |
eval_antes_cp = _score_to_cp(score_before) if score_before is not None else 0
|
| 134 |
pv = info_before.get("pv") or []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
if pv:
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
# eval_antes_cp ya representa el valor óptimo de esta posición
|
| 140 |
best_eval_cp = eval_antes_cp
|
| 141 |
|
|
@@ -164,6 +173,7 @@ def analyze_pgn(pgn_text: str, depth: int | None = None) -> dict:
|
|
| 164 |
'diferencia_cp': delta,
|
| 165 |
'mejor_jugada': best_move_san,
|
| 166 |
'mejor_eval_cp': best_eval_cp,
|
|
|
|
| 167 |
})
|
| 168 |
|
| 169 |
return {
|
|
|
|
| 132 |
score_before = info_before.get("score")
|
| 133 |
eval_antes_cp = _score_to_cp(score_before) if score_before is not None else 0
|
| 134 |
pv = info_before.get("pv") or []
|
| 135 |
+
best_move_san = board.san(pv[0]) if pv else None
|
| 136 |
+
# Línea principal (PV) en SAN, para el botón "Explicar" (HU-011): la
|
| 137 |
+
# secuencia de mejores jugadas desde esta posición, que el frontend
|
| 138 |
+
# reproduce en el tablero. Se limita para no inflar la respuesta.
|
| 139 |
+
pv_san = []
|
| 140 |
if pv:
|
| 141 |
+
tmp = board.copy()
|
| 142 |
+
for mv in pv[:8]: # hasta 8 medias jugadas (4 completas)
|
| 143 |
+
try:
|
| 144 |
+
pv_san.append(tmp.san(mv))
|
| 145 |
+
tmp.push(mv)
|
| 146 |
+
except ValueError:
|
| 147 |
+
break
|
| 148 |
# eval_antes_cp ya representa el valor óptimo de esta posición
|
| 149 |
best_eval_cp = eval_antes_cp
|
| 150 |
|
|
|
|
| 173 |
'diferencia_cp': delta,
|
| 174 |
'mejor_jugada': best_move_san,
|
| 175 |
'mejor_eval_cp': best_eval_cp,
|
| 176 |
+
'pv_san': pv_san,
|
| 177 |
})
|
| 178 |
|
| 179 |
return {
|
modules/llm/guardrails.py
CHANGED
|
@@ -3,6 +3,9 @@
|
|
| 3 |
Plantillas BREVE para jugadas rutinarias (Excelente/Buena): siempre deterministas,
|
| 4 |
no se llama al LLM. Plantillas FALLBACK para Brillante/Imprecisión/Error: se usan
|
| 5 |
si la salida del LLM falla la validación.
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
import re
|
| 8 |
|
|
@@ -13,10 +16,11 @@ _BRIEF = {
|
|
| 13 |
}
|
| 14 |
|
| 15 |
# Fallback para categorías que sí piden LLM (si la generación falla validación).
|
|
|
|
| 16 |
_FALLBACK = {
|
| 17 |
"Brillante": "{move} es un hallazgo táctico que gana ventaja. ¡Muy bien encontrado!",
|
| 18 |
-
"Imprecisión": "{move} cede algo de ventaja
|
| 19 |
-
"Error": "{move}
|
| 20 |
}
|
| 21 |
|
| 22 |
|
|
@@ -27,24 +31,54 @@ def brief(move: dict, clasificacion: str) -> str:
|
|
| 27 |
|
| 28 |
|
| 29 |
_PREFIX_RE = re.compile(
|
| 30 |
-
r'^
|
| 31 |
-
r'
|
|
|
|
|
|
|
| 32 |
r'(?:Evaluaci[oó]n[^.]+\.\s*)?'
|
| 33 |
r'(?:Mejor jugada\s*:\s*\S+[.,]?\s*)?',
|
| 34 |
re.IGNORECASE,
|
| 35 |
)
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
def validate(text: str, move: dict, clasificacion: str) -> str:
|
| 39 |
-
"""Valida la salida del LLM. Elimina prefijo de metadatos
|
| 40 |
text = (text or "").strip()
|
| 41 |
text = _PREFIX_RE.sub('', text).strip()
|
|
|
|
|
|
|
| 42 |
if len(text) < 15:
|
| 43 |
return _make_fallback(move, clasificacion)
|
| 44 |
return text
|
| 45 |
|
| 46 |
|
| 47 |
def _make_fallback(move: dict, clasificacion: str) -> str:
|
| 48 |
-
|
| 49 |
-
tmpl
|
| 50 |
-
return tmpl.format(move=move.get("move", ""), mejor=mejor)
|
|
|
|
| 3 |
Plantillas BREVE para jugadas rutinarias (Excelente/Buena): siempre deterministas,
|
| 4 |
no se llama al LLM. Plantillas FALLBACK para Brillante/Imprecisión/Error: se usan
|
| 5 |
si la salida del LLM falla la validación.
|
| 6 |
+
|
| 7 |
+
El entrenador SOLO comenta el patrón estratégico: no menciona números ni
|
| 8 |
+
recomienda jugadas (eso lo muestra Stockfish por separado en la UI).
|
| 9 |
"""
|
| 10 |
import re
|
| 11 |
|
|
|
|
| 16 |
}
|
| 17 |
|
| 18 |
# Fallback para categorías que sí piden LLM (si la generación falla validación).
|
| 19 |
+
# Sin recomendación de jugada: la mejor jugada la muestra Stockfish en la UI.
|
| 20 |
_FALLBACK = {
|
| 21 |
"Brillante": "{move} es un hallazgo táctico que gana ventaja. ¡Muy bien encontrado!",
|
| 22 |
+
"Imprecisión": "{move} cede algo de ventaja posicional.",
|
| 23 |
+
"Error": "{move} entrega ventaja y debilita tu posición.",
|
| 24 |
}
|
| 25 |
|
| 26 |
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
_PREFIX_RE = re.compile(
|
| 34 |
+
r'^(?:Contexto[^\n]*\n?\s*)?' # línea de contexto si el modelo la repite
|
| 35 |
+
r'(?:Tendencia[^\n]*\n?\s*)?' # línea de tendencia si la repite
|
| 36 |
+
r'Jugada\s+(?:actual|\d+)\s*[(,][^\n)]*\)?\s*:?\s*\S+[.,]?\s*'
|
| 37 |
+
r'(?:Clasificaci[oó]n\s*:\s*\w+[.,]?\s*)?'
|
| 38 |
r'(?:Evaluaci[oó]n[^.]+\.\s*)?'
|
| 39 |
r'(?:Mejor jugada\s*:\s*\S+[.,]?\s*)?',
|
| 40 |
re.IGNORECASE,
|
| 41 |
)
|
| 42 |
|
| 43 |
+
# Por si el modelo solo repite la línea de contexto/tendencia, sin el resto.
|
| 44 |
+
_CONTEXT_RE = re.compile(r'^(?:Contexto|Tendencia)[^\n]*\n?\s*', re.IGNORECASE)
|
| 45 |
+
|
| 46 |
+
# Evaluaciones numéricas que el modelo pueda filtrar: "-1.2", "+0.3", "M3", "+M".
|
| 47 |
+
_EVAL_RE = re.compile(r'[+-]?\d+\.\d+|[+-]?M\d*|[+-]\d+')
|
| 48 |
+
|
| 49 |
+
# Muletillas que el modelo a veces antepone.
|
| 50 |
+
_FILLER_RE = re.compile(
|
| 51 |
+
r'\b(?:teniendo en cuenta|considerando|a pesar de(?:l)?|dado que)\b[^,.]*[,.]?\s*',
|
| 52 |
+
re.IGNORECASE,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _limpiar(text: str) -> str:
|
| 57 |
+
"""Borra evaluaciones numéricas y muletillas que se hayan filtrado."""
|
| 58 |
+
text = _EVAL_RE.sub('', text)
|
| 59 |
+
text = _FILLER_RE.sub('', text)
|
| 60 |
+
# Limpia puntuación huérfana y espacios dobles que deja el borrado.
|
| 61 |
+
text = re.sub(r'\(\s*\)', '', text) # paréntesis vacíos
|
| 62 |
+
text = re.sub(r'\s+([,.;:!?])', r'\1', text) # espacio antes de puntuación
|
| 63 |
+
text = re.sub(r'[,;:]\s*(?=[.])', '', text) # coma pegada a punto
|
| 64 |
+
text = re.sub(r'\s{2,}', ' ', text)
|
| 65 |
+
text = text.strip(' ,;:.-').strip()
|
| 66 |
+
if text and not text.endswith(('.', '!', '?')):
|
| 67 |
+
text += '.'
|
| 68 |
+
return text
|
| 69 |
+
|
| 70 |
|
| 71 |
def validate(text: str, move: dict, clasificacion: str) -> str:
|
| 72 |
+
"""Valida la salida del LLM. Elimina prefijo de metadatos y números filtrados."""
|
| 73 |
text = (text or "").strip()
|
| 74 |
text = _PREFIX_RE.sub('', text).strip()
|
| 75 |
+
text = _CONTEXT_RE.sub('', text).strip()
|
| 76 |
+
text = _limpiar(text)
|
| 77 |
if len(text) < 15:
|
| 78 |
return _make_fallback(move, clasificacion)
|
| 79 |
return text
|
| 80 |
|
| 81 |
|
| 82 |
def _make_fallback(move: dict, clasificacion: str) -> str:
|
| 83 |
+
tmpl = _FALLBACK.get(clasificacion, "Jugada procesada.")
|
| 84 |
+
return tmpl.format(move=move.get("move", ""))
|
|
|
modules/llm/prompt_builder.py
CHANGED
|
@@ -4,13 +4,18 @@ from modules.analysis.classifier import classify
|
|
| 4 |
# evaluación numérica las muestra Stockfish por separado en la UI, así que el
|
| 5 |
# modelo NO debe mencionarlas (de hecho no se las pasamos en el prompt).
|
| 6 |
SYSTEM = (
|
| 7 |
-
"Eres un
|
| 8 |
-
"
|
| 9 |
-
"
|
| 10 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"Reglas estrictas: NO menciones números ni evaluaciones; NO recomiendes "
|
| 12 |
-
"ninguna jugada alternativa;
|
| 13 |
-
"
|
| 14 |
)
|
| 15 |
|
| 16 |
# Clasificaciones que cuentan como "mala jugada" para detectar tendencia.
|
|
@@ -36,10 +41,65 @@ def _tendencia(history: list, max_n: int = 4) -> str:
|
|
| 36 |
return "Tendencia: el juego venía equilibrado, sin un patrón marcado."
|
| 37 |
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def build(move: dict, clasificacion: str, history: list | None = None) -> str:
|
| 40 |
color_str = "Blancas" if move["color"] == "white" else "Negras"
|
| 41 |
return (
|
| 42 |
f"{_tendencia(history or [])}\n"
|
|
|
|
| 43 |
f"Jugada actual ({color_str}): {move['move']}, clasificada como {clasificacion}. "
|
| 44 |
f"Explica en una oración el mérito o el problema estratégico de esta jugada."
|
| 45 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
# evaluación numérica las muestra Stockfish por separado en la UI, así que el
|
| 5 |
# modelo NO debe mencionarlas (de hecho no se las pasamos en el prompt).
|
| 6 |
SYSTEM = (
|
| 7 |
+
"Eres un coach de ajedrez con muchísima energía y personalidad: dramático, "
|
| 8 |
+
"exagerado y divertido, con el estilo de los grandes comentaristas de "
|
| 9 |
+
"ajedrez de YouTube. Comentas las jugadas de tu alumno hablándole de 'tú' "
|
| 10 |
+
"en una o dos oraciones cortas, llenas de chispa y emoción, pero SIEMPRE "
|
| 11 |
+
"dejando una enseñanza clara. Reacciona en grande: festeja las jugadas "
|
| 12 |
+
"brillantes como si fueran un golazo, y dramatiza con humor las "
|
| 13 |
+
"imprecisiones y errores sin humillar al alumno. Explica en lenguaje "
|
| 14 |
+
"sencillo la idea estratégica (control del centro, seguridad del rey, "
|
| 15 |
+
"actividad de las piezas, iniciativa, estructura de peones). "
|
| 16 |
"Reglas estrictas: NO menciones números ni evaluaciones; NO recomiendes "
|
| 17 |
+
"ninguna jugada alternativa; nada de muletillas. Que el drama nunca tape la "
|
| 18 |
+
"idea estratégica."
|
| 19 |
)
|
| 20 |
|
| 21 |
# Clasificaciones que cuentan como "mala jugada" para detectar tendencia.
|
|
|
|
| 41 |
return "Tendencia: el juego venía equilibrado, sin un patrón marcado."
|
| 42 |
|
| 43 |
|
| 44 |
+
def _fase(numero: int) -> str:
|
| 45 |
+
"""Fase aproximada de la partida según el número de jugada. Señal simple y
|
| 46 |
+
CONSISTENTE entre entrenamiento e inferencia, para que el modelo no hable de
|
| 47 |
+
'el final' en pleno medio juego (bug observado en la v1)."""
|
| 48 |
+
if numero <= 10:
|
| 49 |
+
return "apertura"
|
| 50 |
+
if numero <= 25:
|
| 51 |
+
return "medio juego"
|
| 52 |
+
return "final"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
def build(move: dict, clasificacion: str, history: list | None = None) -> str:
|
| 56 |
color_str = "Blancas" if move["color"] == "white" else "Negras"
|
| 57 |
return (
|
| 58 |
f"{_tendencia(history or [])}\n"
|
| 59 |
+
f"Fase: {_fase(move.get('number', 0))}.\n"
|
| 60 |
f"Jugada actual ({color_str}): {move['move']}, clasificada como {clasificacion}. "
|
| 61 |
f"Explica en una oración el mérito o el problema estratégico de esta jugada."
|
| 62 |
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ── EXPANDIDO (botón "Explicar" / texto largo) ────────────────────────────────
|
| 66 |
+
# Rol distinto al corto: aquí SÍ puede nombrar la mejor jugada (que entrega
|
| 67 |
+
# Stockfish) y explicar el porqué en 2-4 oraciones. Regla dura: solo la jugada
|
| 68 |
+
# que se le pasa, nunca inventar. Es un SYSTEM aparte para no mezclar reglas
|
| 69 |
+
# contradictorias con el corto.
|
| 70 |
+
SYSTEM_EXPANDIDO = (
|
| 71 |
+
"Eres el mismo coach de ajedrez, pero ahora EXPLICAS el error con calma y en "
|
| 72 |
+
"palabras MUY SENCILLAS, pensando en un jugador principiante o intermedio que "
|
| 73 |
+
"quiere entender qué hizo mal. En 2 a 4 oraciones: (1) di con claridad qué "
|
| 74 |
+
"problema tuvo su jugada, (2) dile qué jugada era mejor —solo la que se te "
|
| 75 |
+
"indica— y por qué le convenía, y (3) cierra con una lección corta y fácil de "
|
| 76 |
+
"recordar. Evita tecnicismos; usa lenguaje cotidiano. Reglas CRÍTICAS: usa "
|
| 77 |
+
"ÚNICAMENTE la jugada que se te indica como mejor jugada (NUNCA inventes "
|
| 78 |
+
"otra); y si se te dan datos de lo que esa jugada logra (a qué pieza ataca, "
|
| 79 |
+
"qué casilla domina...), úsalos TAL CUAL y NO añadas piezas, casillas ni "
|
| 80 |
+
"amenazas que no se te hayan dado. No menciones evaluaciones numéricas. "
|
| 81 |
+
"Mantén tu chispa, pero aquí lo primero es que el alumno ENTIENDA su error."
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def build_expandido(move: dict, clasificacion: str, history: list | None = None,
|
| 86 |
+
mejor_es: str | None = None, detalle: str | None = None) -> str:
|
| 87 |
+
color_str = "Blancas" if move["color"] == "white" else "Negras"
|
| 88 |
+
base = (
|
| 89 |
+
f"{_tendencia(history or [])}\n"
|
| 90 |
+
f"Fase: {_fase(move.get('number', 0))}.\n"
|
| 91 |
+
f"Jugada actual ({color_str}): {move['move']}, clasificada como {clasificacion}. "
|
| 92 |
+
)
|
| 93 |
+
if clasificacion == "Brillante":
|
| 94 |
+
return base + "Explica con palabras sencillas por qué esta jugada fue tan buena."
|
| 95 |
+
if mejor_es:
|
| 96 |
+
dato = f", que {detalle}" if detalle else ""
|
| 97 |
+
return base + (
|
| 98 |
+
f"La mejor jugada era {mejor_es}{dato}. Explica con palabras sencillas "
|
| 99 |
+
f"qué estuvo mal en tu jugada, por qué {mejor_es} era mejor (usa ese "
|
| 100 |
+
f"dato), y deja una lección corta y fácil de recordar."
|
| 101 |
+
)
|
| 102 |
+
return base + (
|
| 103 |
+
"Explica con palabras sencillas qué estuvo mal en esta jugada, qué idea "
|
| 104 |
+
"era mejor, y deja una lección corta."
|
| 105 |
+
)
|
modules/llm/qwen.py
CHANGED
|
@@ -8,52 +8,79 @@ Descarga:
|
|
| 8 |
--local-dir data/models/
|
| 9 |
"""
|
| 10 |
import os
|
|
|
|
| 11 |
import torch
|
| 12 |
from llama_cpp import Llama
|
| 13 |
from modules.llm.prompt_builder import SYSTEM
|
| 14 |
|
| 15 |
_model: Llama | None = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
def _load() -> None:
|
| 19 |
global _model
|
| 20 |
if _model is not None:
|
| 21 |
return
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
print(
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
import time
|
| 48 |
_load()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
print(f"[Qwen] >>> generando (prompt {len(prompt)} chars)...", flush=True)
|
| 50 |
t0 = time.time()
|
| 51 |
out = _model.create_chat_completion(
|
| 52 |
messages=[
|
| 53 |
-
{"role": "system", "content":
|
| 54 |
{"role": "user", "content": prompt},
|
| 55 |
],
|
| 56 |
-
max_tokens=
|
| 57 |
temperature=0.7,
|
| 58 |
stop=["<|im_end|>", "\n\n\n"],
|
| 59 |
)
|
|
|
|
| 8 |
--local-dir data/models/
|
| 9 |
"""
|
| 10 |
import os
|
| 11 |
+
import threading
|
| 12 |
import torch
|
| 13 |
from llama_cpp import Llama
|
| 14 |
from modules.llm.prompt_builder import SYSTEM
|
| 15 |
|
| 16 |
_model: Llama | None = None
|
| 17 |
+
_load_lock = threading.Lock()
|
| 18 |
+
_infer_lock = threading.Lock() # llama-cpp no es thread-safe
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _resolve_model_path(local_path: str) -> str:
|
| 22 |
+
"""Devuelve la ruta local del GGUF. Si no existe (deploy: el modelo no está
|
| 23 |
+
en el repo por peso), lo descarga de HF Hub —mismo patrón que TrOCR— y cachea.
|
| 24 |
+
En local, si el archivo ya está, lo usa tal cual (sin red)."""
|
| 25 |
+
if os.path.isfile(local_path):
|
| 26 |
+
return local_path
|
| 27 |
+
from config import QWEN_COACH_REPO, QWEN_COACH_FILENAME
|
| 28 |
+
from huggingface_hub import hf_hub_download
|
| 29 |
+
print(f"[Qwen] '{local_path}' no está localmente. Descargando "
|
| 30 |
+
f"'{QWEN_COACH_FILENAME}' de '{QWEN_COACH_REPO}' (HF Hub)...")
|
| 31 |
+
path = hf_hub_download(
|
| 32 |
+
repo_id=QWEN_COACH_REPO,
|
| 33 |
+
filename=QWEN_COACH_FILENAME,
|
| 34 |
+
token=os.getenv("HF_TOKEN"), # None para repos públicos
|
| 35 |
+
)
|
| 36 |
+
print(f"[Qwen] Modelo descargado en {path}")
|
| 37 |
+
return path
|
| 38 |
|
| 39 |
|
| 40 |
def _load() -> None:
|
| 41 |
global _model
|
| 42 |
if _model is not None:
|
| 43 |
return
|
| 44 |
+
with _load_lock:
|
| 45 |
+
if _model is not None: # re-check inside lock
|
| 46 |
+
return
|
| 47 |
+
from config import QWEN_MODEL_PATH
|
| 48 |
+
model_path = _resolve_model_path(QWEN_MODEL_PATH)
|
| 49 |
+
cuda = torch.cuda.is_available()
|
| 50 |
+
n_gpu = int(os.getenv("QWEN_GPU_LAYERS", "-1" if cuda else "0"))
|
| 51 |
+
print(f"[Qwen] Cargando modelo: {model_path} ({'GPU' if cuda else 'CPU'}, gpu_layers={n_gpu})")
|
| 52 |
+
try:
|
| 53 |
+
_model = Llama(
|
| 54 |
+
model_path=model_path,
|
| 55 |
+
n_ctx=2048,
|
| 56 |
+
n_threads=int(os.getenv("QWEN_NUM_THREADS", "6")),
|
| 57 |
+
n_gpu_layers=n_gpu,
|
| 58 |
+
verbose=False,
|
| 59 |
+
)
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"[Qwen] ERROR al construir Llama: {type(e).__name__}: {e}")
|
| 62 |
+
raise
|
| 63 |
+
print("[Qwen] Modelo listo.")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def generate(prompt: str, system: str = SYSTEM, max_tokens: int = 150) -> str:
|
| 67 |
+
"""Genera texto con el modelo. `system` y `max_tokens` permiten reutilizar el
|
| 68 |
+
mismo modelo para el comentario corto y para el expandido (más largo)."""
|
|
|
|
| 69 |
_load()
|
| 70 |
+
with _infer_lock:
|
| 71 |
+
return _generate_locked(prompt, system, max_tokens)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _generate_locked(prompt: str, system: str, max_tokens: int) -> str:
|
| 75 |
+
import time
|
| 76 |
print(f"[Qwen] >>> generando (prompt {len(prompt)} chars)...", flush=True)
|
| 77 |
t0 = time.time()
|
| 78 |
out = _model.create_chat_completion(
|
| 79 |
messages=[
|
| 80 |
+
{"role": "system", "content": system},
|
| 81 |
{"role": "user", "content": prompt},
|
| 82 |
],
|
| 83 |
+
max_tokens=max_tokens,
|
| 84 |
temperature=0.7,
|
| 85 |
stop=["<|im_end|>", "\n\n\n"],
|
| 86 |
)
|
modules/transcription/validator.py
CHANGED
|
@@ -23,6 +23,24 @@ def translate_move(move_es: str) -> str:
|
|
| 23 |
return result
|
| 24 |
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def _strip_annotations(san: str) -> str:
|
| 27 |
return re.sub(r'[+#!?]', '', san).strip()
|
| 28 |
|
|
|
|
| 23 |
return result
|
| 24 |
|
| 25 |
|
| 26 |
+
# Mapeo inverso inglés → español (para mostrar la mejor jugada de Stockfish,
|
| 27 |
+
# que viene en SAN inglés, dentro de comentarios en español).
|
| 28 |
+
_PIECE_MAP_EN_ES = {'R': 'T', 'N': 'C', 'B': 'A', 'Q': 'D', 'K': 'R'}
|
| 29 |
+
_PROMO_MAP_EN_ES = {'R': 'T', 'N': 'C', 'B': 'A', 'Q': 'D'}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def translate_move_en_es(move_en: str) -> str:
|
| 33 |
+
"""Traduce una jugada de notacion inglesa (SAN) a notacion espanola."""
|
| 34 |
+
if not move_en:
|
| 35 |
+
return move_en
|
| 36 |
+
if move_en in ('O-O-O', 'O-O', '0-0-0', '0-0'):
|
| 37 |
+
return move_en
|
| 38 |
+
result = move_en
|
| 39 |
+
result = re.sub(r'=([RNBQ])', lambda m: '=' + _PROMO_MAP_EN_ES.get(m.group(1), m.group(1)), result)
|
| 40 |
+
result = re.sub(r'^([RNBQK])', lambda m: _PIECE_MAP_EN_ES.get(m.group(1), m.group(1)), result)
|
| 41 |
+
return result
|
| 42 |
+
|
| 43 |
+
|
| 44 |
def _strip_annotations(san: str) -> str:
|
| 45 |
return re.sub(r'[+#!?]', '', san).strip()
|
| 46 |
|
routes/comment.py
CHANGED
|
@@ -9,14 +9,27 @@ Las jugadas rutinarias (Excelente/Buena) usan plantilla breve determinista.
|
|
| 9 |
Ambos modelos consideran el HISTORIAL reciente (no la jugada en aislado) y
|
| 10 |
devuelven {corto, expandido} para que la salida sea homogénea y comparable.
|
| 11 |
"""
|
|
|
|
|
|
|
| 12 |
from flask import Blueprint, request, jsonify
|
| 13 |
from modules.analysis.classifier import classify
|
| 14 |
from modules.deterministic import comentar as comentar_deterministico
|
| 15 |
-
from modules.
|
|
|
|
| 16 |
from modules.llm.qwen import generate
|
| 17 |
from modules.llm.guardrails import validate, brief
|
|
|
|
| 18 |
from config import COACH_MODEL
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
comment_bp = Blueprint('comment', __name__)
|
| 21 |
|
| 22 |
# Solo estas clasificaciones disparan un modelo de comentarios.
|
|
@@ -24,13 +37,34 @@ NEEDS_MODEL = {"Brillante", "Imprecisión", "Error"}
|
|
| 24 |
|
| 25 |
|
| 26 |
def _comentar_qwen(move: dict, clasificacion: str, history: list) -> dict:
|
| 27 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
text = generate(build(move, clasificacion, history))
|
| 30 |
text = validate(text, move, clasificacion)
|
| 31 |
except Exception:
|
| 32 |
text = validate("", move, clasificacion)
|
| 33 |
-
return {"corto": text, "expandido":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
def _comentar(move: dict, clasificacion: str, history: list) -> dict:
|
|
|
|
| 9 |
Ambos modelos consideran el HISTORIAL reciente (no la jugada en aislado) y
|
| 10 |
devuelven {corto, expandido} para que la salida sea homogénea y comparable.
|
| 11 |
"""
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
from flask import Blueprint, request, jsonify
|
| 15 |
from modules.analysis.classifier import classify
|
| 16 |
from modules.deterministic import comentar as comentar_deterministico
|
| 17 |
+
from modules.analysis.move_facts import describe_best_move
|
| 18 |
+
from modules.llm.prompt_builder import build, build_expandido, SYSTEM_EXPANDIDO
|
| 19 |
from modules.llm.qwen import generate
|
| 20 |
from modules.llm.guardrails import validate, brief
|
| 21 |
+
from modules.transcription.validator import translate_move_en_es
|
| 22 |
from config import COACH_MODEL
|
| 23 |
|
| 24 |
+
# Evaluaciones numéricas a filtrar del expandido (los nombres de jugada como
|
| 25 |
+
# "Cf3" NO matchean: requieren +/- o decimal).
|
| 26 |
+
_EVAL_RE = re.compile(r'[+-]?\d+\.\d+|[+-]?M\d*|[+-]\d+')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _limpiar_expandido(text: str) -> str:
|
| 30 |
+
text = _EVAL_RE.sub('', (text or "").strip())
|
| 31 |
+
return re.sub(r'\s{2,}', ' ', text).strip()
|
| 32 |
+
|
| 33 |
comment_bp = Blueprint('comment', __name__)
|
| 34 |
|
| 35 |
# Solo estas clasificaciones disparan un modelo de comentarios.
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def _comentar_qwen(move: dict, clasificacion: str, history: list) -> dict:
|
| 40 |
+
"""Comentario del LLM Qwen+LoRA (TA-002): el `corto` (1-2 oraciones con
|
| 41 |
+
personalidad) y el `expandido` (2-4 oraciones que nombran la mejor jugada de
|
| 42 |
+
Stockfish) los genera el MISMO modelo, con prompts/SYSTEM distintos. Si el
|
| 43 |
+
expandido del LLM falla, cae al expandido determinístico (fiable).
|
| 44 |
+
"""
|
| 45 |
try:
|
| 46 |
text = generate(build(move, clasificacion, history))
|
| 47 |
text = validate(text, move, clasificacion)
|
| 48 |
except Exception:
|
| 49 |
text = validate("", move, clasificacion)
|
| 50 |
+
return {"corto": text, "expandido": _expandido_qwen(move, clasificacion, history)}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _expandido_qwen(move: dict, clasificacion: str, history: list) -> str:
|
| 54 |
+
"""Genera el texto largo con el LLM, nombrando la mejor jugada de Stockfish
|
| 55 |
+
(traducida a español). Fallback al expandido determinístico si algo falla."""
|
| 56 |
+
try:
|
| 57 |
+
mejor_en = move.get("mejor_jugada")
|
| 58 |
+
mejor_es = translate_move_en_es(mejor_en) if mejor_en else None
|
| 59 |
+
# Dato REAL de lo que logra la mejor jugada (python-chess, no inventado).
|
| 60 |
+
detalle = describe_best_move([h.get("move") for h in history], mejor_en, move.get("color"))
|
| 61 |
+
prompt = build_expandido(move, clasificacion, history, mejor_es, detalle)
|
| 62 |
+
text = _limpiar_expandido(generate(prompt, system=SYSTEM_EXPANDIDO, max_tokens=240))
|
| 63 |
+
if len(text) >= 25:
|
| 64 |
+
return text
|
| 65 |
+
except Exception:
|
| 66 |
+
pass
|
| 67 |
+
return comentar_deterministico(move, clasificacion, history).get("expandido")
|
| 68 |
|
| 69 |
|
| 70 |
def _comentar(move: dict, clasificacion: str, history: list) -> dict:
|