import cv2 import numpy as np from flask import Blueprint, request, jsonify from modules.vision.aligner import rectify_scoresheet from modules.vision.segmenter import segment_scoresheet, preprocess_for_trocr from modules.transcription.trocr_model import transcribe_batch from modules.transcription.validator import validate_moves from config import MAX_UPLOAD_MB, ALLOWED_EXTENSIONS upload_bp = Blueprint('upload', __name__) def _allowed_file(filename: str) -> bool: return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @upload_bp.route('/validate', methods=['POST']) def validate(): """Revalida jugadas editadas por el usuario. Recibe moves en español, devuelve PGN en inglés.""" data = request.get_json() if not data or 'moves' not in data: return jsonify({'error': 'Se esperaba {moves: [...]}'}), 400 result = validate_moves(data['moves']) return jsonify(result) @upload_bp.route('/upload', methods=['POST']) def upload(): if 'planilla' not in request.files: return jsonify({'error': 'No se recibio archivo'}), 400 file = request.files['planilla'] if not file or not _allowed_file(file.filename): return jsonify({'error': 'Formato no soportado. Use JPG o PNG'}), 400 file_bytes = file.read() if not file_bytes: return jsonify({'error': 'No se pudo leer la imagen'}), 400 if len(file_bytes) > MAX_UPLOAD_MB * 1024 * 1024: return jsonify({'error': f'Archivo demasiado grande. Maximo {MAX_UPLOAD_MB}MB'}), 413 # cv2.imdecode devuelve None ante datos no-imagen, pero LANZA cv2.error si el # buffer llega vacio o corrupto. Atrapamos ambos para responder siempre el # 400 amigable en vez de dejar que la excepcion se vuelva un 500 crudo. try: img = cv2.imdecode(np.frombuffer(file_bytes, np.uint8), cv2.IMREAD_COLOR) except cv2.error: img = None if img is None: return jsonify({'error': 'No se pudo leer la imagen'}), 400 img_rect, method = rectify_scoresheet(img) print(f"[upload] Rectificacion: {method} | shape: {img_rect.shape}") cells = segment_scoresheet(img_rect) if not cells: return jsonify({'error': 'No se detecto la cuadricula de la planilla'}), 422 # Preprocesar todas las celdas y luego transcribirlas en un solo batch. prepped: list = [] cell_meta: list[dict] = [] for cell in cells: preprocessed = preprocess_for_trocr(cell['image']) if preprocessed is None: continue prepped.append(preprocessed) cell_meta.append({'move_number': cell['move_number'], 'color': cell['color']}) texts = transcribe_batch(prepped) moves_raw: dict[int, dict] = {} for meta, text in zip(cell_meta, texts): n = meta['move_number'] if n not in moves_raw: moves_raw[n] = {'number': n, 'white': '', 'black': ''} moves_raw[n][meta['color']] = text moves = [moves_raw[n] for n in sorted(moves_raw)] validation = validate_moves(moves) return jsonify({ 'moves': moves, # jugadas en español (para el editor) 'pgn_en': validation['pgn_en'], # PGN en inglés listo para Stockfish 'errors': validation['errors'], # jugadas ilegales detectadas 'is_valid': validation['is_valid'], 'method': method, 'total': len(moves), })