Spaces:
Configuration error
Configuration error
Upload 2 files
Browse files
app.py
CHANGED
|
@@ -6,317 +6,174 @@ import numpy as np
|
|
| 6 |
import io
|
| 7 |
import re
|
| 8 |
from io import BytesIO
|
| 9 |
-
import tempfile
|
| 10 |
-
import os
|
| 11 |
|
| 12 |
-
# Configurar matplotlib
|
| 13 |
plt.switch_backend('Agg')
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
class AnalizadorAjedrez:
|
| 16 |
def __init__(self):
|
| 17 |
self.datos_jugadas = []
|
| 18 |
-
|
| 19 |
-
def corregir_pgn_automatico(self, pgn_text):
|
| 20 |
-
"""Corrección AGGRESIVA de errores comunes"""
|
| 21 |
-
correcciones = {
|
| 22 |
-
# Piezas mal escritas
|
| 23 |
-
'nf3': 'Nf3', 'nc3': 'Nc3', 'ng5': 'Ng5', 'hc6': 'Nc6', 'hf6': 'Nf6',
|
| 24 |
-
'he7': 'Ne7', 'fxd5': 'Nxd5', 'fxf7': 'Nxf7',
|
| 25 |
-
'kxf7': 'Kxf7', 'ke6': 'Ke6', 'kd6': 'Kd6', 'kc6': 'Kc6', 'kb6': 'Kb6', 'ka6': 'Ka6',
|
| 26 |
-
'of3': 'Qf3', 'oc6': 'Qc6', 'oc4': 'Qc4',
|
| 27 |
-
'hf8': 'Rf8', 'fxf2': 'Rxf2', 'fxd5': 'Rxd5', 'fb5': 'Rb5',
|
| 28 |
-
# Notación de enroque
|
| 29 |
-
'o-o-o': 'O-O-O', 'o-o': 'O-O',
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
for error, correccion in correcciones.items():
|
| 33 |
-
pgn_text = re.sub(r'\b' + error + r'\b', correccion, pgn_text, flags=re.IGNORECASE)
|
| 34 |
-
|
| 35 |
-
return pgn_text
|
| 36 |
-
|
| 37 |
def analizar_partida(self, pgn_string):
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
resultado = game.headers.get("Result", "*")
|
| 50 |
-
|
| 51 |
-
# Analizar jugadas
|
| 52 |
-
tablero = game.board()
|
| 53 |
-
self.datos_jugadas = []
|
| 54 |
-
jugada_num = 0
|
| 55 |
-
|
| 56 |
-
for move in game.mainline_moves():
|
| 57 |
-
tablero.push(move)
|
| 58 |
-
jugada_num += 1
|
| 59 |
-
analisis = self._evaluar_posicion(tablero, jugada_num)
|
| 60 |
-
self.datos_jugadas.append(analisis)
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
def _evaluar_posicion(self, tablero, jugada_num):
|
| 68 |
-
"""Evaluación simple
|
| 69 |
valores = {'p': 1, 'n': 3, 'b': 3, 'r': 5, 'q': 9, 'k': 0}
|
| 70 |
|
| 71 |
-
material_blancas = 0
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
material_blancas += valor
|
| 78 |
-
else:
|
| 79 |
-
material_negras += valor
|
| 80 |
|
| 81 |
ventaja_material = material_blancas - material_negras
|
| 82 |
-
|
| 83 |
-
# Movilidad
|
| 84 |
movilidad = len(list(tablero.legal_moves))
|
| 85 |
|
| 86 |
-
evaluacion = ventaja_material + (movilidad * 0.1)
|
| 87 |
-
|
| 88 |
return {
|
| 89 |
'jugada': jugada_num,
|
| 90 |
-
'evaluacion':
|
| 91 |
'material_blancas': material_blancas,
|
| 92 |
'material_negras': material_negras,
|
| 93 |
'ventaja_material': ventaja_material,
|
| 94 |
-
'movilidad': movilidad
|
| 95 |
-
'es_blancas': jugada_num % 2 == 1
|
| 96 |
}
|
| 97 |
|
| 98 |
-
def
|
| 99 |
-
"""Genera
|
| 100 |
if not self.datos_jugadas:
|
|
|
|
| 101 |
fig, ax = plt.subplots(figsize=(10, 6))
|
| 102 |
-
ax.text(0.5, 0.5, '
|
| 103 |
-
ha='center', va='center', fontsize=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
return fig
|
| 105 |
|
|
|
|
| 106 |
jugadas = [d['jugada'] for d in self.datos_jugadas]
|
| 107 |
evaluaciones = [d['evaluacion'] for d in self.datos_jugadas]
|
| 108 |
-
material = [d['ventaja_material'] for d in self.datos_jugadas]
|
| 109 |
-
movilidad_b = [d['movilidad'] if d['es_blancas'] else 0 for d in self.datos_jugadas]
|
| 110 |
-
movilidad_n = [d['movilidad'] if not d['es_blancas'] else 0 for d in self.datos_jugadas]
|
| 111 |
|
| 112 |
-
fig, (
|
| 113 |
|
| 114 |
-
|
| 115 |
-
ax1.plot(jugadas, evaluaciones, 'b-', linewidth=2, label='Evaluación')
|
| 116 |
ax1.fill_between(jugadas, evaluaciones, alpha=0.3)
|
| 117 |
ax1.axhline(y=0, color='black', linestyle='--')
|
| 118 |
-
ax1.set_title('📊
|
| 119 |
-
ax1.set_ylabel('Ventaja
|
| 120 |
-
ax1.legend()
|
| 121 |
ax1.grid(True, alpha=0.3)
|
| 122 |
|
| 123 |
-
|
| 124 |
ax2.bar(jugadas, material, alpha=0.7, color=['green' if x >= 0 else 'red' for x in material])
|
| 125 |
-
ax2.
|
| 126 |
-
ax2.set_title('⚖️ Ventaja Material', fontweight='bold')
|
| 127 |
ax2.set_ylabel('Material')
|
| 128 |
ax2.grid(True, alpha=0.3)
|
| 129 |
|
| 130 |
-
# Gráfico 3: Movilidad
|
| 131 |
-
ax3.plot(jugadas, movilidad_b, 'blue', label=blancas, linewidth=2)
|
| 132 |
-
ax3.plot(jugadas, movilidad_n, 'red', label=negras, linewidth=2)
|
| 133 |
-
ax3.set_title('🎯 Movilidad de Piezas', fontweight='bold')
|
| 134 |
-
ax3.set_xlabel('Jugada')
|
| 135 |
-
ax3.set_ylabel('Movimientos Legales')
|
| 136 |
-
ax3.legend()
|
| 137 |
-
ax3.grid(True, alpha=0.3)
|
| 138 |
-
|
| 139 |
-
# Gráfico 4: Resumen final
|
| 140 |
-
ultimo = self.datos_jugadas[-1]
|
| 141 |
-
categorias = ['Material', 'Movilidad']
|
| 142 |
-
blancas_stats = [ultimo['material_blancas'], ultimo['movilidad']]
|
| 143 |
-
negras_stats = [ultimo['material_negras'], ultimo['movilidad']]
|
| 144 |
-
|
| 145 |
-
x = np.arange(len(categorias))
|
| 146 |
-
ax4.bar(x - 0.2, blancas_stats, 0.4, label=blancas, color='blue', alpha=0.7)
|
| 147 |
-
ax4.bar(x + 0.2, negras_stats, 0.4, label=negras, color='red', alpha=0.7)
|
| 148 |
-
ax4.set_title('📋 Comparación Final', fontweight='bold')
|
| 149 |
-
ax4.set_xticks(x)
|
| 150 |
-
ax4.set_xticklabels(categorias)
|
| 151 |
-
ax4.legend()
|
| 152 |
-
|
| 153 |
plt.tight_layout()
|
| 154 |
return fig
|
| 155 |
|
| 156 |
-
def
|
| 157 |
if not self.datos_jugadas:
|
| 158 |
-
return "
|
| 159 |
-
|
| 160 |
-
total_jugadas = len(self.datos_jugadas)
|
| 161 |
-
eval_final = self.datos_jugadas[-1]['evaluacion']
|
| 162 |
-
mat_final = self.datos_jugadas[-1]['ventaja_material']
|
| 163 |
-
|
| 164 |
-
# Calcular precision aproximada
|
| 165 |
-
cambios_bruscos = 0
|
| 166 |
-
for i in range(1, len(self.datos_jugadas)):
|
| 167 |
-
cambio = abs(self.datos_jugadas[i]['evaluacion'] - self.datos_jugadas[i-1]['evaluacion'])
|
| 168 |
-
if cambio > 3: # Cambio brusco
|
| 169 |
-
cambios_bruscos += 1
|
| 170 |
-
|
| 171 |
-
precision = max(0, 100 - (cambios_bruscos * 5))
|
| 172 |
-
|
| 173 |
-
reporte = f"""
|
| 174 |
-
## ♟️ ANÁLISIS DE PARTIDA
|
| 175 |
-
|
| 176 |
-
**Jugadores:** {blancas} vs {negras}
|
| 177 |
-
**Resultado:** {resultado}
|
| 178 |
-
**Total de jugadas:** {total_jugadas}
|
| 179 |
-
|
| 180 |
-
### 📊 Métricas Finales:
|
| 181 |
-
- **Evaluación final:** {eval_final:+.2f}
|
| 182 |
-
- **Ventaja material:** {mat_final:+d}
|
| 183 |
-
- **Precisión estimada:** {precision:.0f}%
|
| 184 |
-
|
| 185 |
-
### 🎯 Resumen:
|
| 186 |
-
"""
|
| 187 |
-
|
| 188 |
-
if eval_final > 3:
|
| 189 |
-
reporte += "• ✅ **Victoria clara de las Blancas**\n"
|
| 190 |
-
reporte += "• Las Blancas mantuvieron ventaja consistente\n"
|
| 191 |
-
elif eval_final < -3:
|
| 192 |
-
reporte += "• ✅ **Victoria clara de las Negras**\n"
|
| 193 |
-
reporte += "• Las Negras dominaron la partida\n"
|
| 194 |
-
else:
|
| 195 |
-
reporte += "• ⚖️ **Partida equilibrada**\n"
|
| 196 |
-
reporte += "• Ambos bandos jugaron a un nivel similar\n"
|
| 197 |
-
|
| 198 |
-
if cambios_bruscos > 5:
|
| 199 |
-
reporte += "• ⚠️ **Varios cambios bruscos** - Posibles errores tácticos\n"
|
| 200 |
-
|
| 201 |
-
reporte += f"\n*Análisis generado automáticamente*"
|
| 202 |
-
|
| 203 |
-
return reporte
|
| 204 |
-
|
| 205 |
-
def procesar_pgn(pgn_text, archivo_pgn=None):
|
| 206 |
-
"""Procesa PGN desde texto o archivo"""
|
| 207 |
-
try:
|
| 208 |
-
# Si se subió un archivo, leer su contenido
|
| 209 |
-
if archivo_pgn is not None:
|
| 210 |
-
with open(archivo_pgn.name, 'r', encoding='utf-8') as f:
|
| 211 |
-
pgn_text = f.read()
|
| 212 |
-
|
| 213 |
-
if not pgn_text.strip():
|
| 214 |
-
return None, "❌ Por favor, ingresa un PGN o sube un archivo"
|
| 215 |
-
|
| 216 |
-
analizador = AnalizadorAjedrez()
|
| 217 |
-
blancas, negras, resultado, error = analizador.analizar_partida(pgn_text)
|
| 218 |
-
|
| 219 |
-
if error:
|
| 220 |
-
return None, f"❌ Error al procesar: {error}"
|
| 221 |
-
|
| 222 |
-
# Generar gráfico
|
| 223 |
-
fig = analizador.generar_grafico_completo(blancas, negras)
|
| 224 |
-
buf = BytesIO()
|
| 225 |
-
fig.savefig(buf, format='png', dpi=100, bbox_inches='tight')
|
| 226 |
-
buf.seek(0)
|
| 227 |
-
plt.close(fig)
|
| 228 |
-
|
| 229 |
-
# Generar reporte
|
| 230 |
-
reporte = analizador.generar_reporte_detallado(blancas, negras, resultado)
|
| 231 |
-
|
| 232 |
-
return buf, reporte
|
| 233 |
-
|
| 234 |
-
except Exception as e:
|
| 235 |
-
return None, f"❌ Error inesperado: {str(e)}"
|
| 236 |
|
| 237 |
-
|
| 238 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 239 |
-
gr.Markdown("""
|
| 240 |
-
# ♟️ Analizador de Partidas de Ajedrez
|
| 241 |
-
**Carga archivos PGN o pega el texto directamente - Análisis completo con gráficos profesionales**
|
| 242 |
-
""")
|
| 243 |
-
|
| 244 |
-
with gr.Row():
|
| 245 |
-
with gr.Column(scale=1):
|
| 246 |
-
gr.Markdown("### 📁 Subir archivo PGN")
|
| 247 |
-
uploader = gr.File(
|
| 248 |
-
label="Selecciona tu archivo .pgn",
|
| 249 |
-
file_types=[".pgn"],
|
| 250 |
-
type="filepath",
|
| 251 |
-
height=100
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
gr.Markdown("### 📝 O pegar PGN como texto")
|
| 255 |
-
pgn_input = gr.Textbox(
|
| 256 |
-
label="Pega tu partida PGN aquí",
|
| 257 |
-
lines=15,
|
| 258 |
-
placeholder="""[Event \"Mi Torneo\"]
|
| 259 |
-
[White \"Jugador Blanco\"]
|
| 260 |
-
[Black \"Jugador Negro\"]
|
| 261 |
-
[Result \"1-0\"]
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
)
|
| 269 |
-
|
| 270 |
-
btn_analizar = gr.Button("🧠 Analizar Partida", variant="primary", size="lg")
|
| 271 |
-
btn_limpiar = gr.Button("🗑️ Limpiar Todo", variant="secondary")
|
| 272 |
-
|
| 273 |
-
with gr.Column(scale=1):
|
| 274 |
-
gr.Markdown("### 📊 Resultados del Análisis")
|
| 275 |
-
image_output = gr.Image(
|
| 276 |
-
label="Análisis Gráfico",
|
| 277 |
-
type="filepath",
|
| 278 |
-
height=400
|
| 279 |
-
)
|
| 280 |
-
report_output = gr.Markdown(
|
| 281 |
-
label="Reporte Detallado",
|
| 282 |
-
value="### 📋 Reporte de Análisis\n\n*Los resultados aparecerán aquí después del análisis...*"
|
| 283 |
-
)
|
| 284 |
-
|
| 285 |
-
# Ejemplos
|
| 286 |
-
gr.Markdown("### 💡 Partidas de Ejemplo")
|
| 287 |
-
with gr.Row():
|
| 288 |
-
gr.Examples(
|
| 289 |
-
examples=[[
|
| 290 |
-
"""[Event "Ejemplo Clásico"]
|
| 291 |
-
[White "Fischer"]
|
| 292 |
-
[Black "Spassky"]
|
| 293 |
-
[Result "1-0"]
|
| 294 |
-
|
| 295 |
-
1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O
|
| 296 |
-
9. h3 Nb8 10. d4 Nbd7 11. Nbd2 Bb7 12. Bc2 Re8 13. Nf1 Bf8 14. Ng3 g6 15. a4 c5
|
| 297 |
-
16. d5 c4 17. Bg5 h6 18. Be3 Nc5 19. Qd2 h5 20. Bh6 Nh7 21. g3 Bd7 22. Rf1 Qc7
|
| 298 |
-
23. Ne2 Rec8 24. Ng5 Nxg5 25. Bxg5 Bg7 26. f4 exf4 27. gxf4 f6 28. Bf3 Be5
|
| 299 |
-
29. fxe5 fxe5 30. Bg5 Qd7 31. e6 Qe7 32. Bf6 Qf8 33. e7 1-0"""]],
|
| 300 |
-
inputs=pgn_input,
|
| 301 |
-
label="Partida de Ejemplo"
|
| 302 |
-
)
|
| 303 |
-
|
| 304 |
-
# Funcionalidades
|
| 305 |
-
def limpiar_todo():
|
| 306 |
-
return None, None, "### 📋 Reporte de Análisis\n\n*Los resultados aparecerán aquí después del análisis...*"
|
| 307 |
-
|
| 308 |
-
# Conectores
|
| 309 |
-
btn_analizar.click(
|
| 310 |
-
fn=procesar_pgn,
|
| 311 |
-
inputs=[pgn_input, uploader],
|
| 312 |
-
outputs=[image_output, report_output]
|
| 313 |
-
)
|
| 314 |
-
|
| 315 |
-
btn_limpiar.click(
|
| 316 |
-
fn=limpiar_todo,
|
| 317 |
-
inputs=[],
|
| 318 |
-
outputs=[uploader, pgn_input, report_output]
|
| 319 |
-
)
|
| 320 |
|
| 321 |
-
|
| 322 |
-
demo.launch(share=True)
|
|
|
|
| 6 |
import io
|
| 7 |
import re
|
| 8 |
from io import BytesIO
|
|
|
|
|
|
|
| 9 |
|
|
|
|
| 10 |
plt.switch_backend('Agg')
|
| 11 |
|
| 12 |
+
class ReparadorPGN:
|
| 13 |
+
@staticmethod
|
| 14 |
+
def reparar_pgn(pgn_text):
|
| 15 |
+
"""Repara PGNs extremadamente corruptos"""
|
| 16 |
+
lineas = pgn_text.split('\n')
|
| 17 |
+
lineas_reparadas = []
|
| 18 |
+
|
| 19 |
+
for linea in lineas:
|
| 20 |
+
linea = linea.strip()
|
| 21 |
+
|
| 22 |
+
# Reparar headers corruptos
|
| 23 |
+
if linea.startswith('['):
|
| 24 |
+
# Corregir comillas y paréntesis
|
| 25 |
+
linea = re.sub(r"\[(.*?)[')](.*?)[')]", r"[\1 '\2']", linea)
|
| 26 |
+
# Corregir nombres de headers
|
| 27 |
+
linea = re.sub(r'\[Ulnite', '[White', linea)
|
| 28 |
+
linea = re.sub(r'\[Result "I-0"\]', '[Result "1-0"]', linea)
|
| 29 |
+
linea = re.sub(r'\[Result "O-I"\]', '[Result "0-1"]', linea)
|
| 30 |
+
linea = re.sub(r'\[Result "I/2-I/2"\]', '[Result "1/2-1/2"]', linea)
|
| 31 |
+
|
| 32 |
+
# Reparar notación de movimientos
|
| 33 |
+
else:
|
| 34 |
+
# Corregir piezas mal escritas
|
| 35 |
+
correcciones = {
|
| 36 |
+
r'\bnf3\b': 'Nf3', r'\bnc3\b': 'Nc3', r'\bng5\b': 'Ng5',
|
| 37 |
+
r'\bhc6\b': 'Nc6', r'\bhf6\b': 'Nf6', r'\bhba\b': 'Nb8',
|
| 38 |
+
r'\bhbe7\b': 'Nbd7', r'\bnn1\b': 'Nf1', r'\bhe2\b': 'Ne2',
|
| 39 |
+
r'\bnh7\b': 'Nh7', r'\bhc5\b': 'Nc5', r'\bqu2\b': 'Qd2',
|
| 40 |
+
r'\bre1\b': 'Re1', r'\brn\b': 'Rf1', r'\bbe4:\b': 'Be4',
|
| 41 |
+
r'\bo-o-o\b': 'O-O-O', r'\bo-o\b': 'O-O'
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
for error, correccion in correcciones.items():
|
| 45 |
+
linea = re.sub(error, correccion, linea, flags=re.IGNORECASE)
|
| 46 |
+
|
| 47 |
+
lineas_reparadas.append(linea)
|
| 48 |
+
|
| 49 |
+
return '\n'.join(lineas_reparadas)
|
| 50 |
+
|
| 51 |
class AnalizadorAjedrez:
|
| 52 |
def __init__(self):
|
| 53 |
self.datos_jugadas = []
|
| 54 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
def analizar_partida(self, pgn_string):
|
| 56 |
+
"""Analiza partida con múltiples intentos y reparación"""
|
| 57 |
+
intentos = [
|
| 58 |
+
pgn_string, # Intento 1: Original
|
| 59 |
+
ReparadorPGN.reparar_pgn(pgn_string), # Intento 2: Reparado
|
| 60 |
+
self._crear_pgn_minimo(pgn_string) # Intento 3: PGN mínimo
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
for i, pgn_intento in enumerate(intentos):
|
| 64 |
+
try:
|
| 65 |
+
pgn = io.StringIO(pgn_intento)
|
| 66 |
+
game = chess.pgn.read_game(pgn)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
if game and len(list(game.mainline_moves())) > 0:
|
| 69 |
+
blancas = game.headers.get("White", "Anónimo")
|
| 70 |
+
negras = game.headers.get("Black", "Anónimo")
|
| 71 |
+
resultado = game.headers.get("Result", "*")
|
| 72 |
+
|
| 73 |
+
# Analizar jugadas
|
| 74 |
+
tablero = game.board()
|
| 75 |
+
self.datos_jugadas = []
|
| 76 |
+
|
| 77 |
+
for jugada_num, move in enumerate(game.mainline_moves(), 1):
|
| 78 |
+
tablero.push(move)
|
| 79 |
+
analisis = self._evaluar_posicion(tablero, jugada_num)
|
| 80 |
+
self.datos_jugadas.append(analisis)
|
| 81 |
+
|
| 82 |
+
print(f"✅ Análisis exitoso (Intento {i+1})")
|
| 83 |
+
return blancas, negras, resultado, ""
|
| 84 |
+
|
| 85 |
+
except Exception as e:
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
return "Anónimo", "Anónimo", "*", "No se pudo analizar el PGN (formato muy corrupto)"
|
| 89 |
+
|
| 90 |
+
def _crear_pgn_minimo(self, pgn_text):
|
| 91 |
+
"""Crea un PGN mínimo desde los movimientos"""
|
| 92 |
+
# Extraer solo movimientos numéricos
|
| 93 |
+
movimientos = re.findall(r'\d+\.\s*(\S+)\s+(\S+)', pgn_text)
|
| 94 |
+
if not movimientos:
|
| 95 |
+
movimientos = re.findall(r'\b([NBRQK]?[a-h]?[1-8]?x?[a-h][1-8]\+?\+?#?)\b', pgn_text, re.IGNORECASE)
|
| 96 |
+
|
| 97 |
+
pgn_minimo = """[Event "Partida Reparada"]
|
| 98 |
+
[White "Blancas"]
|
| 99 |
+
[Black "Negras"]
|
| 100 |
+
[Result "*"]
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
for i, (blanca, negra) in enumerate(movimientos[:50], 1): # Máximo 50 jugadas
|
| 104 |
+
pgn_minimo += f"{i}. {blanca} {negra} "
|
| 105 |
+
|
| 106 |
+
return pgn_minimo.strip()
|
| 107 |
|
| 108 |
def _evaluar_posicion(self, tablero, jugada_num):
|
| 109 |
+
"""Evaluación simple pero robusta"""
|
| 110 |
valores = {'p': 1, 'n': 3, 'b': 3, 'r': 5, 'q': 9, 'k': 0}
|
| 111 |
|
| 112 |
+
material_blancas = sum(valores.get(p.symbol().lower(), 0)
|
| 113 |
+
for p in tablero.piece_map().values()
|
| 114 |
+
if p.color == chess.WHITE)
|
| 115 |
+
material_negras = sum(valores.get(p.symbol().lower(), 0)
|
| 116 |
+
for p in tablero.piece_map().values()
|
| 117 |
+
if p.color == chess.BLACK)
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
ventaja_material = material_blancas - material_negras
|
|
|
|
|
|
|
| 120 |
movilidad = len(list(tablero.legal_moves))
|
| 121 |
|
|
|
|
|
|
|
| 122 |
return {
|
| 123 |
'jugada': jugada_num,
|
| 124 |
+
'evaluacion': ventaja_material + (movilidad * 0.1),
|
| 125 |
'material_blancas': material_blancas,
|
| 126 |
'material_negras': material_negras,
|
| 127 |
'ventaja_material': ventaja_material,
|
| 128 |
+
'movilidad': movilidad
|
|
|
|
| 129 |
}
|
| 130 |
|
| 131 |
+
def generar_grafico(self, blancas, negras):
|
| 132 |
+
"""Genera gráfico incluso con datos mínimos"""
|
| 133 |
if not self.datos_jugadas:
|
| 134 |
+
# Gráfico de error informativo
|
| 135 |
fig, ax = plt.subplots(figsize=(10, 6))
|
| 136 |
+
ax.text(0.5, 0.5, '⚠️ PGN no analizable\n\nEl archivo PGN está corrupto\no tiene formato inválido',
|
| 137 |
+
ha='center', va='center', fontsize=14, transform=ax.transAxes,
|
| 138 |
+
bbox=dict(boxstyle="round,pad=0.3", facecolor="lightcoral", alpha=0.7))
|
| 139 |
+
ax.set_xlim(0, 1)
|
| 140 |
+
ax.set_ylim(0, 1)
|
| 141 |
+
ax.set_xticks([])
|
| 142 |
+
ax.set_yticks([])
|
| 143 |
return fig
|
| 144 |
|
| 145 |
+
# Gráfico normal con datos
|
| 146 |
jugadas = [d['jugada'] for d in self.datos_jugadas]
|
| 147 |
evaluaciones = [d['evaluacion'] for d in self.datos_jugadas]
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
+
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
|
| 150 |
|
| 151 |
+
ax1.plot(jugadas, evaluaciones, 'b-', linewidth=2)
|
|
|
|
| 152 |
ax1.fill_between(jugadas, evaluaciones, alpha=0.3)
|
| 153 |
ax1.axhline(y=0, color='black', linestyle='--')
|
| 154 |
+
ax1.set_title(f'📊 Análisis: {blancas} vs {negras}', fontweight='bold')
|
| 155 |
+
ax1.set_ylabel('Ventaja')
|
|
|
|
| 156 |
ax1.grid(True, alpha=0.3)
|
| 157 |
|
| 158 |
+
material = [d['ventaja_material'] for d in self.datos_jugadas]
|
| 159 |
ax2.bar(jugadas, material, alpha=0.7, color=['green' if x >= 0 else 'red' for x in material])
|
| 160 |
+
ax2.set_xlabel('Jugada')
|
|
|
|
| 161 |
ax2.set_ylabel('Material')
|
| 162 |
ax2.grid(True, alpha=0.3)
|
| 163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
plt.tight_layout()
|
| 165 |
return fig
|
| 166 |
|
| 167 |
+
def generar_reporte(self, blancas, negras, resultado):
|
| 168 |
if not self.datos_jugadas:
|
| 169 |
+
return """## ❌ PGN NO ANALIZABLE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
**El archivo PGN está corrupto o tiene formato inválido.**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
+
### 🔧 Posibles soluciones:
|
| 174 |
+
1. **Verifica que el PGN sea de una partida real**
|
| 175 |
+
2. **Comprueba que la notación de movimientos sea correcta**
|
| 176 |
+
3. **Intenta con otro archivo PGN**
|
| 177 |
+
4. **Los headers deben usar comillas: [Event "Nombre"]**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
### 📝 Formato PGN correcto:
|
|
|