diff --git a/backend/binaural/api.py b/backend/binaural/api.py new file mode 100644 index 0000000..c454d26 --- /dev/null +++ b/backend/binaural/api.py @@ -0,0 +1,133 @@ +"""API FastAPI: presets, schedule, loops de ruido, export y frontend estático.""" + +import os +import threading +from collections.abc import Iterator +from functools import lru_cache +from pathlib import Path +from typing import Literal + +import numpy as np +from fastapi import FastAPI, HTTPException +from fastapi.responses import FileResponse, StreamingResponse +from fastapi.staticfiles import StaticFiles + +from . import __version__ +from .export import tamano_wav, wav_streaming +from .noise import TipoRuido, generar_loop, wav_loop_cacheado +from .presets import Preset, cargar_presets +from .session import schedule_de_preset +from .synth import SR_DEFECTO + +SRS_VALIDOS = (44100, 48000) +DIR_WEB = Path(__file__).resolve().parents[2] / "web" + +app = FastAPI(title="collina-binaurals", version=__version__) +PRESETS = cargar_presets() +_export_ocupado = threading.Lock() # máximo 1 export concurrente por proceso + + +def _dir_cache() -> Path: + """Directorio de cache de loops (volumen en producción, var/ en local).""" + return Path(os.environ.get("BINAURAL_CACHE_DIR", str(Path(__file__).parents[1] / "var"))) + + +def _obtener_preset(nombre: str) -> Preset: + if nombre not in PRESETS: + disponibles = ", ".join(sorted(PRESETS)) + raise HTTPException(404, f"preset {nombre!r} no existe; disponibles: {disponibles}") + return PRESETS[nombre] + + +def _validar_sr(sr: int) -> None: + if sr not in SRS_VALIDOS: + raise HTTPException(422, f"sr {sr} no soportado; usa {SRS_VALIDOS[0]} o {SRS_VALIDOS[1]}") + + +@lru_cache(maxsize=4) +def _loop_en_memoria(tipo: TipoRuido, sr: int) -> np.ndarray: + return generar_loop(tipo, sr) + + +@app.get("/api/health") +def health() -> dict[str, str]: + """Latido para el healthcheck del contenedor.""" + return {"status": "ok", "version": __version__} + + +@app.get("/api/presets") +def listar_presets() -> list[dict[str, object]]: + """Tarjetas de presets: nombre, objetivo, duración y rango de batido.""" + return [ + { + "name": p.name, + "description": p.description, + "carrier_hz": p.carrier_hz, + "noise": p.noise, + "noise_db": p.noise_db, + "duracion_min": p.duracion_min, + "beat_min_hz": p.rango_batido[0], + "beat_max_hz": p.rango_batido[1], + } + for p in PRESETS.values() + ] + + +@app.get("/api/presets/{nombre}") +def detalle_preset(nombre: str, duration: float | None = None) -> dict[str, object]: + """Preset completo + schedule listo para el motor Web Audio.""" + preset = _obtener_preset(nombre) + try: + schedule = schedule_de_preset(preset, duration) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + return {"preset": preset.model_dump(), "schedule": schedule.model_dump()} + + +@app.get("/api/noise/{tipo}.wav") +def loop_ruido(tipo: Literal["pink", "rain"], sr: int = SR_DEFECTO) -> FileResponse: + """Loop de 20 s sin costura, generado una vez y cacheado en disco.""" + _validar_sr(sr) + ruta = wav_loop_cacheado(tipo, sr, _dir_cache()) + return FileResponse(ruta, media_type="audio/wav", filename=f"{tipo}.wav") + + +@app.get("/api/export") +def exportar( + preset: str, + duration: float | None = None, + format: Literal["wav", "flac"] = "wav", + sr: int = SR_DEFECTO, +) -> StreamingResponse: + """WAV en streaming: cabecera conocida de antemano, Content-Length exacto.""" + if format != "wav": + raise HTTPException(400, "por ahora solo format=wav; flac llega en la fase 5") + _validar_sr(sr) + p = _obtener_preset(preset) + try: + schedule = schedule_de_preset(p, duration) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + loop = _loop_en_memoria(p.noise, sr) if p.noise != "none" else None + if not _export_ocupado.acquire(blocking=False): + raise HTTPException(429, "ya hay un export en curso; espera a que termine") + + def generar() -> Iterator[bytes]: + try: + yield from wav_streaming(schedule, sr=sr, loop_ruido=loop) + finally: + _export_ocupado.release() + + return StreamingResponse( + generar(), + media_type="audio/wav", + headers={ + "Content-Length": str(tamano_wav(schedule, sr)), + "Content-Disposition": f'attachment; filename="{p.name}.wav"', + }, + ) + + + +if DIR_WEB.is_dir(): + app.mount("/", StaticFiles(directory=DIR_WEB, html=True), name="web") diff --git a/backend/binaural/cli.py b/backend/binaural/cli.py new file mode 100644 index 0000000..10baf9c --- /dev/null +++ b/backend/binaural/cli.py @@ -0,0 +1,48 @@ +"""CLI mínima: listar presets y exportar a WAV.""" + +from pathlib import Path +from typing import Annotated + +import typer + +from .export import exportar_wav +from .noise import generar_loop +from .presets import cargar_presets +from .session import schedule_de_preset +from .synth import SR_DEFECTO + +app = typer.Typer(help="Generador de tonos binaurales alpha/beta.", no_args_is_help=True) + + +@app.command() +def presets() -> None: + """Lista los presets disponibles.""" + for p in cargar_presets().values(): + lo, hi = p.rango_batido + rango = f"{lo:g} Hz" if lo == hi else f"{lo:g}-{hi:g} Hz" + linea = f"{p.name:<14} {p.duracion_min:>3.0f} min · batido {rango:<10} · {p.description}" + typer.echo(linea) + + +@app.command() +def export( + preset: Annotated[str, typer.Option(help="Nombre del preset.")], + out: Annotated[Path, typer.Option(help="Ruta del WAV de salida.")], + duration: Annotated[float | None, typer.Option(help="Duración en min (escala).")] = None, + sr: Annotated[int, typer.Option(help="Sample rate.")] = SR_DEFECTO, +) -> None: + """Exporta un preset a WAV.""" + todos = cargar_presets() + if preset not in todos: + disponibles = ", ".join(sorted(todos)) + typer.echo(f"preset {preset!r} no existe; disponibles: {disponibles}", err=True) + raise typer.Exit(1) + p = todos[preset] + schedule = schedule_de_preset(p, duration) + loop = generar_loop(p.noise, sr) if p.noise != "none" else None + exportar_wav(schedule, out, sr=sr, loop_ruido=loop) + typer.echo(f"{out} · {schedule.duration_s / 60:g} min + pre-roll · {sr} Hz") + + +if __name__ == "__main__": + app() diff --git a/backend/binaural/export.py b/backend/binaural/export.py new file mode 100644 index 0000000..6432c00 --- /dev/null +++ b/backend/binaural/export.py @@ -0,0 +1,64 @@ +"""Export de sesiones a WAV en streaming. + +La cabecera RIFF (44 bytes) se conoce de antemano a partir del número +exacto de samples, así que el `Content-Length` es exacto y los bloques se +generan bajo demanda: nunca se materializa la sesión completa en memoria. +""" + +import struct +from collections.abc import Iterator +from pathlib import Path + +import numpy as np + +from .session import Schedule +from .synth import SR_DEFECTO, bloques_sesion, total_muestras + +BITS = 16 +CANALES = 2 +BYTES_CABECERA = 44 + + +def cabecera_wav(n_muestras: int, sr: int) -> bytes: + """Cabecera RIFF/WAVE PCM 16-bit estéreo (44 bytes).""" + bytes_frame = CANALES * BITS // 8 + bytes_datos = n_muestras * bytes_frame + return b"".join( + ( + b"RIFF", + struct.pack(" int: + """Tamaño total del WAV en bytes (cabecera + datos), sin generarlo.""" + return BYTES_CABECERA + total_muestras(schedule, sr) * CANALES * BITS // 8 + + +def _a_pcm16(bloque: np.ndarray) -> bytes: + """float64 [−1, 1] → PCM int16 little-endian intercalado.""" + return (np.clip(bloque, -1.0, 1.0) * 32767.0).round().astype(" Iterator[bytes]: + """Genera el WAV completo por bloques: primero la cabecera, luego PCM.""" + yield cabecera_wav(total_muestras(schedule, sr), sr) + for bloque in bloques_sesion(schedule, sr=sr, loop_ruido=loop_ruido): + yield _a_pcm16(bloque) + + +def exportar_wav( + schedule: Schedule, ruta: Path, sr: int = SR_DEFECTO, loop_ruido: np.ndarray | None = None +) -> None: + """Escribe la sesión a un archivo WAV (CLI y tests).""" + with ruta.open("wb") as fh: + for trozo in wav_streaming(schedule, sr=sr, loop_ruido=loop_ruido): + fh.write(trozo) diff --git a/backend/binaural/noise.py b/backend/binaural/noise.py index 01b5613..c7eb3af 100644 --- a/backend/binaural/noise.py +++ b/backend/binaural/noise.py @@ -5,9 +5,11 @@ fija) y se antitransforma: la señal resultante es periódica en la longitud del loop por construcción → sin costura, sin crossfade. Solo numpy. """ +from pathlib import Path from typing import Literal import numpy as np +import soundfile as sf SR_DEFECTO = 44100 DUR_LOOP_S = 20.0 @@ -69,3 +71,12 @@ def generar_loop(tipo: TipoRuido, sr: int = SR_DEFECTO) -> np.ndarray: if tipo == "rain": return loop_rain(sr) raise ValueError(f"tipo de ruido desconocido: {tipo!r} (usa pink o rain)") + + +def wav_loop_cacheado(tipo: TipoRuido, sr: int, dir_cache: Path) -> Path: + """Devuelve la ruta del loop WAV, generándolo y cacheándolo si no existe.""" + ruta = dir_cache / f"{tipo}-{sr}.wav" + if not ruta.exists(): + dir_cache.mkdir(parents=True, exist_ok=True) + sf.write(str(ruta), generar_loop(tipo, sr), sr, subtype="PCM_16") + return ruta diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py new file mode 100644 index 0000000..b4f068e --- /dev/null +++ b/backend/tests/test_api.py @@ -0,0 +1,107 @@ +"""API completa con httpx/TestClient (criterios 7 y 9).""" + +import io + +import pytest +import soundfile as sf +from fastapi.testclient import TestClient + +from binaural import api + +NOMBRES = {"relajacion", "estudio", "foco", "foco_intenso", "descanso"} + + +@pytest.fixture() +def cliente(tmp_path, monkeypatch): + monkeypatch.setenv("BINAURAL_CACHE_DIR", str(tmp_path / "cache")) + with TestClient(api.app) as c: + yield c + + +def test_health(cliente): + r = cliente.get("/api/health") + assert r.status_code == 200 + assert r.json()["status"] == "ok" + + +def test_listado_de_presets(cliente): + """Criterio 7: /api/presets lista los 5 YAML.""" + r = cliente.get("/api/presets") + assert r.status_code == 200 + tarjetas = r.json() + assert {t["name"] for t in tarjetas} == NOMBRES + estudio = next(t for t in tarjetas if t["name"] == "estudio") + assert estudio["duracion_min"] == 30 + assert (estudio["beat_min_hz"], estudio["beat_max_hz"]) == (10, 14) + + +def test_detalle_con_schedule(cliente): + r = cliente.get("/api/presets/estudio") + assert r.status_code == 200 + sch = r.json()["schedule"] + assert [(p["t"], p["beat_hz"]) for p in sch["points"]] == [ + (0, 10), (300, 10), (900, 14), (1800, 14), + ] + assert sch["duration_s"] == 1800 + assert sch["preroll_s"] == 1.5 + + +def test_preset_inexistente(cliente): + r = cliente.get("/api/presets/zen") + assert r.status_code == 404 + assert "no existe" in r.json()["detail"] + + +def test_loops_de_ruido(cliente, tmp_path): + for tipo in ("pink", "rain"): + r = cliente.get(f"/api/noise/{tipo}.wav") + assert r.status_code == 200 + assert r.headers["content-type"].startswith("audio/wav") + datos, sr = sf.read(io.BytesIO(r.content)) + assert sr == 44100 + assert datos.ndim == 1 # mono + assert len(datos) == 20 * 44100 + assert (tmp_path / "cache" / "pink-44100.wav").exists() # cacheado en disco + + +def test_export_wav_valido(cliente): + """Criterio 9: cabecera WAV válida y Content-Length exacto.""" + r = cliente.get("/api/export", params={"preset": "foco", "duration": 0.1}) + assert r.status_code == 200 + assert int(r.headers["content-length"]) == len(r.content) + assert r.content[:4] == b"RIFF" and r.content[8:12] == b"WAVE" + datos, sr = sf.read(io.BytesIO(r.content)) + assert sr == 44100 + assert datos.shape[1] == 2 + assert abs(len(datos) / sr - (0.1 * 60 + 1.5)) <= 0.01 + + +def test_export_errores(cliente): + assert cliente.get("/api/export", params={"preset": "zen"}).status_code == 404 + assert ( + cliente.get("/api/export", params={"preset": "foco", "duration": 61}).status_code == 422 + ) + r = cliente.get("/api/export", params={"preset": "foco", "format": "flac"}) + assert r.status_code == 400 + assert "fase 5" in r.json()["detail"] + assert ( + cliente.get("/api/export", params={"preset": "foco", "sr": 22050}).status_code == 422 + ) + + +def test_export_concurrente_limitado(cliente): + """Solo 1 export a la vez por proceso: el segundo recibe 429.""" + assert api._export_ocupado.acquire(blocking=False) + try: + r = cliente.get("/api/export", params={"preset": "foco", "duration": 0.05}) + assert r.status_code == 429 + finally: + api._export_ocupado.release() + r = cliente.get("/api/export", params={"preset": "foco", "duration": 0.05}) + assert r.status_code == 200 # el lock quedó libre tras el streaming + + +def test_frontend_estatico(cliente): + r = cliente.get("/") + assert r.status_code == 200 + assert "text/html" in r.headers["content-type"] diff --git a/backend/tests/test_export.py b/backend/tests/test_export.py new file mode 100644 index 0000000..92f9856 --- /dev/null +++ b/backend/tests/test_export.py @@ -0,0 +1,40 @@ +"""Export WAV: cabecera, tamaño y duración exacta (criterio 5).""" + +import numpy as np +import soundfile as sf + +from binaural.export import BYTES_CABECERA, cabecera_wav, exportar_wav, tamano_wav +from binaural.noise import generar_loop +from binaural.session import schedule_de_preset +from binaural.synth import total_muestras + +SR = 44100 + + +def test_cabecera_wav(): + cab = cabecera_wav(1000, SR) + assert len(cab) == BYTES_CABECERA == 44 + assert cab[:4] == b"RIFF" and cab[8:12] == b"WAVE" and cab[36:40] == b"data" + assert int.from_bytes(cab[40:44], "little") == 1000 * 4 # estéreo 16-bit + assert int.from_bytes(cab[4:8], "little") == 36 + 1000 * 4 + + +def test_export_wav_completo(tmp_path, presets): + """Criterio 5: estéreo, sr correcto, 16-bit, duración = pedida + pre-roll ±0.01 s.""" + preset = presets["estudio"] + schedule = schedule_de_preset(preset, duracion_min=0.2) # 12 s escalados + loop = generar_loop(preset.noise, SR) + ruta = tmp_path / "estudio.wav" + exportar_wav(schedule, ruta, sr=SR, loop_ruido=loop) + + assert ruta.stat().st_size == tamano_wav(schedule, SR) + info = sf.info(str(ruta)) + assert info.samplerate == SR + assert info.channels == 2 + assert info.subtype == "PCM_16" + esperada = 0.2 * 60 + schedule.preroll_s + assert abs(info.frames / SR - esperada) <= 0.01 + + datos, _ = sf.read(str(ruta)) + assert np.max(np.abs(datos)) < 0.999 # sin clipping tras cuantizar + assert total_muestras(schedule, SR) == info.frames diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..99fb675 --- /dev/null +++ b/web/index.html @@ -0,0 +1,5 @@ + + +collina-binaurals +

Frontend en construcción (fase 3).

+