File size: 6,025 Bytes
37d841f
 
8ccac0b
 
 
 
 
 
 
 
37d841f
ec62aa2
 
37d841f
 
8ccac0b
ec62aa2
 
37d841f
98abdf7
ec62aa2
8ccac0b
37d841f
ec62aa2
 
 
 
 
 
98abdf7
 
ec62aa2
 
37d841f
 
8ccac0b
 
 
 
 
ec62aa2
 
 
 
 
8ccac0b
 
 
 
 
ec62aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ccac0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d841f
 
 
 
 
 
8ccac0b
 
 
37d841f
 
8ccac0b
 
37d841f
8ccac0b
 
 
37d841f
 
 
8ccac0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d841f
 
8ccac0b
37d841f
8ccac0b
 
37d841f
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""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})