parakeet-es 0.1.0: Spanish-locked decoding (es / es-MX / es-ES) for Parakeet TDT 0.6B v3
5de8da7 verified Download eval/evaluar.py from solucionesft/parakeet-es: direct link, hf CLI and curl.
- Browser
- Download file 6.21 kB
-
https://huggingface.co/solucionesft/parakeet-es/resolve/main/eval/evaluar.py
- Command line
-
hf download hf://solucionesft/parakeet-es/eval/evaluar.py
-
curl -L -o evaluar.py https://huggingface.co/solucionesft/parakeet-es/resolve/main/eval/evaluar.py
6.21 kB
| """Evaluación reproducible de parakeet-es contra Parakeet TDT 0.6B v3 original. | |
| Uso: python eval/evaluar.py --datos <carpeta> [--n 150] | |
| <carpeta> debe contener: | |
| sinteticas/<voz>/<id>.(wav|mp3) frases de eval/frases.json con varias voces | |
| parquet-data/es_419/test-*.parquet FLEURS es_419 (google/fleurs, voces humanas) | |
| spanish/test-*.parquet Multilingual LibriSpeech español (facebook/multilingual_librispeech) | |
| Métricas: WER (minúsculas, sin puntuación), % de deriva a otro alfabeto, aciertos en palabras regionales. | |
| """ | |
| import argparse | |
| import glob | |
| import io | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import time | |
| import unicodedata | |
| import numpy as np | |
| import pyarrow.parquet as pq | |
| import soundfile as sf | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| import onnx_asr # noqa: E402 | |
| import parakeet_es # noqa: E402 | |
| SR = 16000 | |
| AQUI = os.path.dirname(os.path.abspath(__file__)) | |
| def a16k(x, sr): | |
| if x.ndim > 1: | |
| x = x.mean(1) | |
| if sr != SR: | |
| n = int(len(x) * SR / sr) | |
| x = np.interp(np.linspace(0, len(x) - 1, n), np.arange(len(x)), x) | |
| return np.asarray(x, np.float32) | |
| def leer_archivo(p): | |
| if p.endswith(".mp3"): | |
| import av | |
| c = av.open(p) | |
| r = av.AudioResampler(format="flt", layout="mono", rate=SR) | |
| out = [y.to_ndarray().reshape(-1) for fr in c.decode(audio=0) for y in r.resample(fr)] | |
| return np.concatenate(out).astype(np.float32) | |
| x, sr = sf.read(p, dtype="float32") | |
| return a16k(x, sr) | |
| def normalizar(t): | |
| t = t.lower() | |
| t = re.sub(r"[¿?¡!.,;:\"«»“”()\[\]…\-—]", " ", t) | |
| return re.sub(r"\s+", " ", t).strip() | |
| def errores(ref, hyp): | |
| r, h = normalizar(ref).split(), normalizar(hyp).split() | |
| d = list(range(len(h) + 1)) | |
| for i in range(1, len(r) + 1): | |
| prev, d[0] = d[0], i | |
| for j in range(1, len(h) + 1): | |
| prev, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, prev + (r[i - 1] != h[j - 1])) | |
| return d[len(h)], len(r) | |
| ESPANOL = set("abcdefghijklmnopqrstuvwxyzáéíóúüñ") | |
| def deriva(t): | |
| return any(ch.isalpha() and ch.lower() not in ESPANOL for ch in t) | |
| def cargar(datos, n): | |
| conjuntos = {} | |
| frases = {f["id"]: f for f in json.load(open(os.path.join(AQUI, "frases.json"), encoding="utf-8"))} | |
| sint = [] | |
| for p in sorted(glob.glob(os.path.join(datos, "sinteticas", "*", "*.*"))): | |
| fid = int(os.path.splitext(os.path.basename(p))[0]) | |
| voz = os.path.basename(os.path.dirname(p)) | |
| sint.append({"audio": leer_archivo(p), "ref": frases[fid]["texto"], "tipo": frases[fid]["tipo"], "voz": voz}) | |
| conjuntos["frases (9 voces)"] = sint | |
| for nombre, patron, col in [("FLEURS es_419", "parquet-data/es_419/test-*.parquet", "transcription"), | |
| ("MLS español", "spanish/test-*.parquet", "transcript")]: | |
| archivos = sorted(glob.glob(os.path.join(datos, patron))) | |
| if not archivos: | |
| continue | |
| tabla = pq.read_table(archivos[0]).slice(0, n).to_pylist() | |
| filas = [] | |
| for f in tabla: | |
| x, sr = sf.read(io.BytesIO(f["audio"]["bytes"]), dtype="float32") | |
| filas.append({"audio": a16k(x, sr), "ref": f.get(col) or f.get("raw_transcription") or "", "tipo": "real"}) | |
| conjuntos[nombre] = filas | |
| return conjuntos | |
| REGIONALES = {"es-MX": ["tianguis", "jitomate", "aguacate", "cuate", "culiacán", "neta", "güey", "celular", | |
| "chilaquiles", "pozole", "guadalajara", "sheinbaum", "ciudad de méxico"], | |
| "es-ES": ["tío", "aparca", "coche", "coge", "móvil", "vosotros", "tenéis", "madrid", "ordenador", | |
| "piso", "barcelona", "sevilla", "vale"]} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--datos", required=True) | |
| ap.add_argument("--n", type=int, default=150) | |
| ap.add_argument("--salida", default=os.path.join(AQUI, "resultados.json")) | |
| a = ap.parse_args() | |
| conj = cargar(a.datos, a.n) | |
| print({k: len(v) for k, v in conj.items()}, flush=True) | |
| configs = [("Parakeet v3 original", None), ("parakeet-es (solo bloqueo)", "es"), | |
| ("parakeet-es es-MX", "es-MX"), ("parakeet-es es-ES", "es-ES")] | |
| res = {} | |
| for nombre, var in configs: | |
| modelo = onnx_asr.load_model("nemo-parakeet-tdt-0.6b-v3", quantization="int8") | |
| asr = modelo if var is None else parakeet_es.load(var, model=modelo) | |
| rec = (lambda w: modelo.recognize(w, sample_rate=SR)) if var is None else asr.recognize | |
| res[nombre] = {} | |
| for cnom, filas in conj.items(): | |
| e = n = der = 0 | |
| cortas_e = cortas_n = 0 | |
| hits = {"es-MX": [0, 0], "es-ES": [0, 0]} | |
| t0 = time.time() | |
| ejemplos = [] | |
| for f in filas: | |
| hyp = rec(f["audio"]) or "" | |
| ee, nn = errores(f["ref"], hyp) | |
| e += ee; n += nn; der += deriva(hyp) | |
| if f["tipo"] == "corta": | |
| cortas_e += ee; cortas_n += nn | |
| if f["tipo"] in hits: | |
| for w in REGIONALES[f["tipo"]]: | |
| if w in normalizar(f["ref"]): | |
| hits[f["tipo"]][1] += 1 | |
| hits[f["tipo"]][0] += w in normalizar(hyp) | |
| if deriva(hyp) and len(ejemplos) < 6: | |
| ejemplos.append({"ref": f["ref"], "hyp": hyp, "voz": f.get("voz", "")}) | |
| r = {"WER": round(100 * e / max(n, 1), 2), "deriva_%": round(100 * der / len(filas), 2), | |
| "seg": round(time.time() - t0, 1), "ejemplos_deriva": ejemplos} | |
| if cortas_n: | |
| r["WER_frases_cortas"] = round(100 * cortas_e / cortas_n, 2) | |
| for k, (h, t) in hits.items(): | |
| if t: | |
| r[f"aciertos_{k}_%"] = round(100 * h / t, 1) | |
| res[nombre][cnom] = r | |
| print(nombre, "|", cnom, "|", {k: v for k, v in r.items() if k != "ejemplos_deriva"}, flush=True) | |
| json.dump(res, open(a.salida, "w", encoding="utf-8"), ensure_ascii=False, indent=2) | |
| print("resultados ->", a.salida) | |
| if __name__ == "__main__": | |
| main() | |