"""Endpoint /api/comment — genera clasificación y comentario por jugada. Dos modelos INTERCAMBIABLES generan el comentario de las jugadas interesantes (Brillante/Imprecisión/Error), según config.COACH_MODEL: - "deterministic" → Experimento A: modelo determinístico propio (modules.deterministic) - "qwen" → Experimento B: LLM Qwen2.5 (modules.llm) Las jugadas rutinarias (Excelente/Buena) usan plantilla breve determinista. Ambos modelos consideran el HISTORIAL reciente (no la jugada en aislado) y devuelven {corto, expandido} para que la salida sea homogénea y comparable. """ import re from flask import Blueprint, request, jsonify from modules.analysis.classifier import classify from modules.deterministic import comentar as comentar_deterministico from modules.analysis.move_facts import describe_best_move from modules.llm.prompt_builder import build, build_expandido, SYSTEM_EXPANDIDO from modules.llm.qwen import generate from modules.llm.guardrails import validate, brief, strip_cjk from modules.transcription.validator import translate_move_en_es from config import COACH_MODEL # Evaluaciones numéricas a filtrar del expandido (los nombres de jugada como # "Cf3" NO matchean: requieren +/- o decimal). _EVAL_RE = re.compile(r'[+-]?\d+\.\d+|[+-]?M\d*|[+-]\d+') def _limpiar_expandido(text: str) -> str: text = strip_cjk((text or "").strip()) # corta cualquier deriva a chino text = _EVAL_RE.sub('', text) return re.sub(r'\s{2,}', ' ', text).strip() comment_bp = Blueprint('comment', __name__) # Solo estas clasificaciones disparan un modelo de comentarios. NEEDS_MODEL = {"Brillante", "Imprecisión", "Error"} def _comentar_qwen(move: dict, clasificacion: str, history: list) -> dict: """Comentario del LLM Qwen+LoRA (TA-002): el `corto` (1-2 oraciones con personalidad) y el `expandido` (2-4 oraciones que nombran la mejor jugada de Stockfish) los genera el MISMO modelo, con prompts/SYSTEM distintos. Si el expandido del LLM falla, cae al expandido determinístico (fiable). """ try: text = generate(build(move, clasificacion, history)) text = validate(text, move, clasificacion) except Exception: text = validate("", move, clasificacion) return {"corto": text, "expandido": _expandido_qwen(move, clasificacion, history)} def _expandido_qwen(move: dict, clasificacion: str, history: list) -> str: """Genera el texto largo con el LLM, nombrando la mejor jugada de Stockfish (traducida a español). Fallback al expandido determinístico si algo falla.""" try: mejor_en = move.get("mejor_jugada") mejor_es = translate_move_en_es(mejor_en) if mejor_en else None # Dato REAL de lo que logra la mejor jugada (python-chess, no inventado). detalle = describe_best_move([h.get("move") for h in history], mejor_en, move.get("color")) prompt = build_expandido(move, clasificacion, history, mejor_es, detalle) text = _limpiar_expandido(generate(prompt, system=SYSTEM_EXPANDIDO, max_tokens=240)) if len(text) >= 25: return text except Exception: pass return comentar_deterministico(move, clasificacion, history).get("expandido") def _comentar(move: dict, clasificacion: str, history: list) -> dict: """Genera {corto, expandido} para UNA jugada según el modelo configurado.""" if clasificacion in NEEDS_MODEL: if COACH_MODEL == "qwen": return _comentar_qwen(move, clasificacion, history) return comentar_deterministico(move, clasificacion, history) return {"corto": brief(move, clasificacion), "expandido": None} def _payload(move: dict, clasificacion: str, res: dict) -> dict: """Arma el objeto de respuesta de una jugada.""" return { 'number': move.get('number'), 'color': move.get('color'), 'clasificacion': clasificacion, 'comentario': res['corto'], 'comentario_expandido': res['expandido'], } @comment_bp.route('/comment', methods=['POST']) def comment(): """ Body JSON: { "moves": [...] } → comenta TODAS las jugadas (batch). { "moves": [...], "target": N } → comenta SOLO la jugada N (1-based), usando las anteriores como historial. Respuesta: { "comments": [{ number, color, clasificacion, comentario, comentario_expandido }, ...] } """ data = request.get_json(silent=True) or {} moves = data.get('moves') target = data.get('target') if not moves or not isinstance(moves, list): return jsonify({'error': "Se esperaba {'moves': [...]}"}), 400 # ── Modo target: una sola jugada con su historial ─────────────────────── if target is not None: try: idx = int(target) except (TypeError, ValueError): return jsonify({'error': 'target debe ser entero'}), 400 if not (1 <= idx <= len(moves)): return jsonify({'error': 'target fuera de rango'}), 400 move = moves[idx - 1] history = moves[:idx - 1] clasificacion = classify(move.get('diferencia_cp', 0)) res = _comentar(move, clasificacion, history) return jsonify({'comments': [_payload(move, clasificacion, res)]}) # ── Modo batch: todas las jugadas, cada una con su historial ──────────── n_modelo = sum(1 for m in moves if classify(m.get('diferencia_cp', 0)) in NEEDS_MODEL) print(f"[comment] {len(moves)} jugadas, {n_modelo} usan modelo '{COACH_MODEL}'", flush=True) comments = [] for i, move in enumerate(moves): clasificacion = classify(move.get('diferencia_cp', 0)) res = _comentar(move, clasificacion, moves[:i]) comments.append(_payload(move, clasificacion, res)) return jsonify({'comments': comments})