Spaces:
Paused
Paused
Download routes/upload.py from SamilG2/BACKEND-CheckScan: direct link, hf CLI and curl.
- Browser
- Download file 3.43 kB
-
https://huggingface.co/spaces/SamilG2/BACKEND-CheckScan/resolve/main/routes/upload.py
- Command line
-
hf download hf://spaces/SamilG2/BACKEND-CheckScan/routes/upload.py
-
curl -L -o upload.py https://huggingface.co/spaces/SamilG2/BACKEND-CheckScan/resolve/main/routes/upload.py
3.43 kB
| 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 | |
| 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) | |
| 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), | |
| }) | |