Spaces:
Paused
Paused
Download modules/llm/guardrails.py from SamilG2/BACKEND-CheckScan: direct link, hf CLI and curl.
- Browser
- Download file 4.09 kB
-
https://huggingface.co/spaces/SamilG2/BACKEND-CheckScan/resolve/main/modules/llm/guardrails.py
- Command line
-
hf download hf://spaces/SamilG2/BACKEND-CheckScan/modules/llm/guardrails.py
-
curl -L -o guardrails.py https://huggingface.co/spaces/SamilG2/BACKEND-CheckScan/resolve/main/modules/llm/guardrails.py
4.09 kB
| """Validación de salida del LLM + plantillas deterministas (estilo chess.com). | |
| Plantillas BREVE para jugadas rutinarias (Excelente/Buena): siempre deterministas, | |
| no se llama al LLM. Plantillas FALLBACK para Brillante/Imprecisión/Error: se usan | |
| si la salida del LLM falla la validación. | |
| El entrenador SOLO comenta el patrón estratégico: no menciona números ni | |
| recomienda jugadas (eso lo muestra Stockfish por separado en la UI). | |
| """ | |
| import re | |
| # Comentarios breves deterministas: jugadas que no requieren LLM. | |
| _BRIEF = { | |
| "Excelente": "{move} es la mejor jugada en esta posición.", | |
| "Buena": "{move} es sólida y mantiene el equilibrio.", | |
| } | |
| # Fallback para categorías que sí piden LLM (si la generación falla validación). | |
| # Sin recomendación de jugada: la mejor jugada la muestra Stockfish en la UI. | |
| _FALLBACK = { | |
| "Brillante": "{move} es un hallazgo táctico que gana ventaja. ¡Muy bien encontrado!", | |
| "Imprecisión": "{move} cede algo de ventaja posicional.", | |
| "Error": "{move} entrega ventaja y debilita tu posición.", | |
| } | |
| def brief(move: dict, clasificacion: str) -> str: | |
| """Comentario corto determinista para jugadas no-interesantes (Excelente/Buena).""" | |
| tmpl = _BRIEF.get(clasificacion, "Jugada procesada.") | |
| return tmpl.format(move=move.get("move", "")) | |
| _PREFIX_RE = re.compile( | |
| r'^(?:Contexto[^\n]*\n?\s*)?' # línea de contexto si el modelo la repite | |
| r'(?:Tendencia[^\n]*\n?\s*)?' # línea de tendencia si la repite | |
| r'Jugada\s+(?:actual|\d+)\s*[(,][^\n)]*\)?\s*:?\s*\S+[.,]?\s*' | |
| r'(?:Clasificaci[oó]n\s*:\s*\w+[.,]?\s*)?' | |
| r'(?:Evaluaci[oó]n[^.]+\.\s*)?' | |
| r'(?:Mejor jugada\s*:\s*\S+[.,]?\s*)?', | |
| re.IGNORECASE, | |
| ) | |
| # Por si el modelo solo repite la línea de contexto/tendencia, sin el resto. | |
| _CONTEXT_RE = re.compile(r'^(?:Contexto|Tendencia)[^\n]*\n?\s*', re.IGNORECASE) | |
| # Evaluaciones numéricas que el modelo pueda filtrar: "-1.2", "+0.3", "M3", "+M". | |
| _EVAL_RE = re.compile(r'[+-]?\d+\.\d+|[+-]?M\d*|[+-]\d+') | |
| # Muletillas que el modelo a veces antepone. | |
| _FILLER_RE = re.compile( | |
| r'\b(?:teniendo en cuenta|considerando|a pesar de(?:l)?|dado que)\b[^,.]*[,.]?\s*', | |
| re.IGNORECASE, | |
| ) | |
| # Caracteres CJK (chino/japonés/coreano y fullwidth). El base de Qwen a veces | |
| # deriva a chino en generaciones largas; este filtro garantiza que eso NUNCA | |
| # llegue al usuario aunque ocurra. | |
| _CJK_RE = re.compile('[ -鿿-]') | |
| def strip_cjk(text: str) -> str: | |
| """Si aparece un carácter CJK, corta el texto ahí y lo recorta a la última | |
| oración completa (para no dejar una frase a medias).""" | |
| m = _CJK_RE.search(text or "") | |
| if not m: | |
| return text | |
| cortado = text[:m.start()] | |
| fin = max(cortado.rfind('.'), cortado.rfind('!'), cortado.rfind('?')) | |
| return (cortado[:fin + 1] if fin != -1 else cortado).strip() | |
| def _limpiar(text: str) -> str: | |
| """Borra evaluaciones numéricas y muletillas que se hayan filtrado.""" | |
| text = strip_cjk(text) | |
| text = _EVAL_RE.sub('', text) | |
| text = _FILLER_RE.sub('', text) | |
| # Limpia puntuación huérfana y espacios dobles que deja el borrado. | |
| text = re.sub(r'\(\s*\)', '', text) # paréntesis vacíos | |
| text = re.sub(r'\s+([,.;:!?])', r'\1', text) # espacio antes de puntuación | |
| text = re.sub(r'[,;:]\s*(?=[.])', '', text) # coma pegada a punto | |
| text = re.sub(r'\s{2,}', ' ', text) | |
| text = text.strip(' ,;:.-').strip() | |
| if text and not text.endswith(('.', '!', '?')): | |
| text += '.' | |
| return text | |
| def validate(text: str, move: dict, clasificacion: str) -> str: | |
| """Valida la salida del LLM. Elimina prefijo de metadatos y números filtrados.""" | |
| text = (text or "").strip() | |
| text = _PREFIX_RE.sub('', text).strip() | |
| text = _CONTEXT_RE.sub('', text).strip() | |
| text = _limpiar(text) | |
| if len(text) < 15: | |
| return _make_fallback(move, clasificacion) | |
| return text | |
| def _make_fallback(move: dict, clasificacion: str) -> str: | |
| tmpl = _FALLBACK.get(clasificacion, "Jugada procesada.") | |
| return tmpl.format(move=move.get("move", "")) | |