Commit inicial: gr-locutor (Locutor IA - GRP)

Locuciones de radio con voz IA local (XTTS-v2) integradas a G Radio
Player: interfaz Rust/GTK4 de configuración, motor de generación y
enriquecimiento de texto en Python, daemon de monitoreo que dispara
locuciones sin pausar playlist-refill. Requiere radio-player >= 0.4.11.
This commit is contained in:
2026-08-23 01:58:56 -05:00
commit 2f6b5340f5
23 changed files with 4031 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
# Rust build artifacts
/target/
**/*.rs.bk
Cargo.lock.bak
# Instaladores generados
*.deb
# Runtime logs
nohup.out
*.log
# Editor / OS junk
.DS_Store
*.swp
*.swo
*~
.vscode/
.idea/
.claude/
+29
View File
@@ -0,0 +1,29 @@
# Changelog — gr-locutor (Locutor IA - GRP)
## [0.1.1] — 2026-07-15
### Correcciones
- Textos de la GUI e instalador pasados a español neutral (eran voseo — "corré", "buscá", "instalá", "avisá" → "ejecutar", "buscar", "instalar", "avisar").
- Versión visible arriba a la derecha del título de la ventana (`env!("CARGO_PKG_VERSION")`).
### Empaquetado
- `.deb` (`gr-locutor_0.1.1_amd64.deb`) con `Depends: gradio-player (>= 0.4.11)` — evita instalaciones sin la versión de GRP que expone la bandera `locutor_auto` y el campo `fundido_exclude`.
- `LEEME.md` para beta testers (instalación, motor de voz, habilitar en GRP, qué esperar, contacto de soporte).
## [0.1.0] — 2026-07-15
Primera versión funcional.
### Nuevo
- Interfaz gráfica Rust/GTK4 "Locutor IA - GRP", con la misma paleta de colores que radio-player.
- Selector de voz de referencia (genérica de GRP o archivo propio de la estación).
- Parámetros configurables: cada cuántos temas se locuta, ventana de locuciones generadas por adelantado, % de identificación de la radio.
- Botón "Generar prueba" (asíncrono) y botón de encendido/apagado del monitor con indicador en vivo (🟢/⚫), refresco automático cada 3s.
- Motor de síntesis XTTS-v2 instalable vía `instalar-locutor-amd64.sh`: venv aislado (`~/.gradio/locutor-venv/`), detección automática de GPU NVIDIA vs. CPU, versiones de `torch`/`torchcodec`/`transformers` pineadas a las que se comprobó que funcionan.
- Scripts generalizados (adaptados del prototipo en `~/Dropbox/LocutorIA/`): `enriquecer-locucion.py` (texto: opener alternando `curiosidades.txt`/`frases-motivacionales.txt`, cierre desde `identificaciones.txt` con nombre de radio leído de `gradio.config`), `monitor-locuciones.py` (ventana corrediza configurable, sin pausar `playlist-refill`), `generar-intro.sh`, `start-monitor.sh`.
- `.deb` instalable sin cargo/rust en destino (binario precompilado), auto-instala scripts/contexto/voz genérica al primer arranque de la GUI.
### Correcciones sobre el prototipo original
- `torchcodec` pineado a la build que coincide con `torch` (la versión genérica de PyPI carga una `libtorchcodec` incompatible y falla con `libnvrtc.so.13` no encontrado en el caso GPU).
- Lock de generación (`tmp/locuciones_generating`) que quedaba pegado si el daemon moría a mitad de una generación (`kill`/crash) — ahora se limpia siempre al arrancar el daemon.
- Contador de "cada cuántos temas" que recontaba una canción ya evaluada si el escaneo volvía a pasar por ella en un ciclo de poll posterior, corrompiendo el conteo — ahora recuerda la decisión de cada tema ya visto, no solo el último.
Generated
+931
View File
@@ -0,0 +1,931 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "async-channel"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
dependencies = [
"concurrent-queue",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
[[package]]
name = "cairo-rs"
version = "0.20.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e3bd0f4e25afa9cabc157908d14eeef9067d6448c49414d17b3fb55f0eadd0"
dependencies = [
"bitflags",
"cairo-sys-rs",
"glib",
"libc",
]
[[package]]
name = "cairo-sys-rs"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "059cc746549898cbfd9a47754288e5a958756650ef4652bbb6c5f71a6bda4f8b"
dependencies = [
"glib-sys",
"libc",
"system-deps",
]
[[package]]
name = "cfg-expr"
version = "0.20.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb693542bcafa528e198be0ebd9d3632ca5b7c93dbe7237460e199910835997c"
dependencies = [
"smallvec",
"target-lexicon",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "concurrent-queue"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
[[package]]
name = "dirs"
version = "5.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.48.0",
]
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "event-listener"
version = "5.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"
dependencies = [
"concurrent-queue",
"parking",
"pin-project-lite",
]
[[package]]
name = "event-listener-strategy"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [
"event-listener",
"pin-project-lite",
]
[[package]]
name = "field-offset"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"
dependencies = [
"memoffset",
"rustc_version",
]
[[package]]
name = "futures-channel"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-core"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-executor"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
[[package]]
name = "futures-macro"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "futures-task"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-util"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-core",
"futures-macro",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "gdk-pixbuf"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fd242894c084f4beed508a56952750bce3e96e85eb68fdc153637daa163e10c"
dependencies = [
"gdk-pixbuf-sys",
"gio",
"glib",
"libc",
]
[[package]]
name = "gdk-pixbuf-sys"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b34f3b580c988bd217e9543a2de59823fafae369d1a055555e5f95a8b130b96"
dependencies = [
"gio-sys",
"glib-sys",
"gobject-sys",
"libc",
"system-deps",
]
[[package]]
name = "gdk4"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4850c9d9c1aecd1a3eb14fadc1cdb0ac0a2298037e116264c7473e1740a32d60"
dependencies = [
"cairo-rs",
"gdk-pixbuf",
"gdk4-sys",
"gio",
"glib",
"libc",
"pango",
]
[[package]]
name = "gdk4-sys"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f6eb95798e2b46f279cf59005daf297d5b69555428f185650d71974a910473a"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gio-sys",
"glib-sys",
"gobject-sys",
"libc",
"pango-sys",
"pkg-config",
"system-deps",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "gio"
version = "0.20.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e27e276e7b6b8d50f6376ee7769a71133e80d093bdc363bd0af71664228b831"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"gio-sys",
"glib",
"libc",
"pin-project-lite",
"smallvec",
]
[[package]]
name = "gio-sys"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521e93a7e56fc89e84aea9a52cfc9436816a4b363b030260b699950ff1336c83"
dependencies = [
"glib-sys",
"gobject-sys",
"libc",
"system-deps",
"windows-sys 0.59.0",
]
[[package]]
name = "glib"
version = "0.20.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffc4b6e352d4716d84d7dde562dd9aee2a7d48beb872dd9ece7f2d1515b2d683"
dependencies = [
"bitflags",
"futures-channel",
"futures-core",
"futures-executor",
"futures-task",
"futures-util",
"gio-sys",
"glib-macros",
"glib-sys",
"gobject-sys",
"libc",
"memchr",
"smallvec",
]
[[package]]
name = "glib-macros"
version = "0.20.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8084af62f09475a3f529b1629c10c429d7600ee1398ae12dd3bf175d74e7145"
dependencies = [
"heck",
"proc-macro-crate",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "glib-sys"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ab79e1ed126803a8fb827e3de0e2ff95191912b8db65cee467edb56fc4cc215"
dependencies = [
"libc",
"system-deps",
]
[[package]]
name = "gobject-sys"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec9aca94bb73989e3cfdbf8f2e0f1f6da04db4d291c431f444838925c4c63eda"
dependencies = [
"glib-sys",
"libc",
"system-deps",
]
[[package]]
name = "gr-locutor"
version = "0.1.1"
dependencies = [
"async-channel",
"dirs",
"glib",
"gtk4",
]
[[package]]
name = "graphene-rs"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b86dfad7d14251c9acaf1de63bc8754b7e3b4e5b16777b6f5a748208fe9519b"
dependencies = [
"glib",
"graphene-sys",
"libc",
]
[[package]]
name = "graphene-sys"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df583a85ba2d5e15e1797e40d666057b28bc2f60a67c9c24145e6db2cc3861ea"
dependencies = [
"glib-sys",
"libc",
"pkg-config",
"system-deps",
]
[[package]]
name = "gsk4"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61f5e72f931c8c9f65fbfc89fe0ddc7746f147f822f127a53a9854666ac1f855"
dependencies = [
"cairo-rs",
"gdk4",
"glib",
"graphene-rs",
"gsk4-sys",
"libc",
"pango",
]
[[package]]
name = "gsk4-sys"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "755059de55fa6f85a46bde8caf03e2184c96bfda1f6206163c72fb0ea12436dc"
dependencies = [
"cairo-sys-rs",
"gdk4-sys",
"glib-sys",
"gobject-sys",
"graphene-sys",
"libc",
"pango-sys",
"system-deps",
]
[[package]]
name = "gtk4"
version = "0.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f274dd0102c21c47bbfa8ebcb92d0464fab794a22fad6c3f3d5f165139a326d6"
dependencies = [
"cairo-rs",
"field-offset",
"futures-channel",
"gdk-pixbuf",
"gdk4",
"gio",
"glib",
"graphene-rs",
"gsk4",
"gtk4-macros",
"gtk4-sys",
"libc",
"pango",
]
[[package]]
name = "gtk4-macros"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ed1786c4703dd196baf7e103525ce0cf579b3a63a0570fe653b7ee6bac33999"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "gtk4-sys"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41e03b01e54d77c310e1d98647d73f996d04b2f29b9121fe493ea525a7ec03d6"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gdk4-sys",
"gio-sys",
"glib-sys",
"gobject-sys",
"graphene-sys",
"gsk4-sys",
"libc",
"pango-sys",
"system-deps",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "indexmap"
version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "libc"
version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "libredox"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"
dependencies = [
"libc",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "memoffset"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
dependencies = [
"autocfg",
]
[[package]]
name = "option-ext"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "pango"
version = "0.20.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6576b311f6df659397043a5fa8a021da8f72e34af180b44f7d57348de691ab5c"
dependencies = [
"gio",
"glib",
"libc",
"pango-sys",
]
[[package]]
name = "pango-sys"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186909673fc09be354555c302c0b3dcf753cd9fa08dcb8077fa663c80fb243fa"
dependencies = [
"glib-sys",
"gobject-sys",
"libc",
"system-deps",
]
[[package]]
name = "parking"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkg-config"
version = "0.3.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_users"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
dependencies = [
"getrandom",
"libredox",
"thiserror",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_spanned"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
dependencies = [
"serde_core",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "system-deps"
version = "7.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"
dependencies = [
"cfg-expr",
"heck",
"pkg-config",
"toml",
"version-compare",
]
[[package]]
name = "target-lexicon"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "toml"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c96ecdfa941c8fc4fcaed14f99ada8ebed502eef533015095a07e3301d4c3c"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.13+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "version-compare"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets 0.48.5",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm 0.48.5",
"windows_aarch64_msvc 0.48.5",
"windows_i686_gnu 0.48.5",
"windows_i686_msvc 0.48.5",
"windows_x86_64_gnu 0.48.5",
"windows_x86_64_gnullvm 0.48.5",
"windows_x86_64_msvc 0.48.5",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
dependencies = [
"memchr",
]
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "gr-locutor"
version = "0.1.1"
edition = "2021"
description = "Locutor IA - GRP — interfaz de configuración del Locutor Automático IA de G Radio Player"
license = "GPL-3.0-or-later"
[[bin]]
name = "gr-locutor-config"
path = "src/main.rs"
[dependencies]
gtk4 = { version = "0.9", features = ["v4_6"] }
glib = "0.20"
dirs = "5"
async-channel = "2"
+66
View File
@@ -0,0 +1,66 @@
# Locutor IA - GRP — guía de instalación (beta)
Locuciones de radio generadas con voz IA local (sin depender de APIs de voz en la nube), integradas a G Radio Player.
## Requisitos
- **Debian 12 (Bookworm) o Debian 13 (Trixie), amd64.**
- **G Radio Player 0.4.11 o superior ya instalado y configurado.** El paquete no se instala si no lo detecta.
- Conexión a internet (para la instalación del motor de voz, y para las consultas opcionales de Wikipedia/MusicBrainz que enriquecen el texto).
- GPU NVIDIA opcional. Sin ella funciona igual, más lento — ver la sección de rendimiento más abajo.
## 1. Instalar el paquete
```bash
sudo apt install ./gr-locutor_0.1.1_amd64.deb
```
(Usar `apt install ./archivo.deb` en vez de `dpkg -i` — resuelve dependencias automáticamente y avisa claramente si falta G Radio Player o una versión vieja.)
Esto instala la interfaz gráfica y los scripts, pero **todavía no el motor de voz** (es un paso aparte porque pesa varios GB y depende del hardware de cada máquina).
## 2. Instalar el motor de voz (una sola vez)
```bash
gr-locutor-instalar-motor
```
- Detecta automáticamente si hay GPU NVIDIA disponible; si no, usa CPU.
- Descarga varios cientos de MB (sin GPU) a ~2GB (con GPU) de dependencias, más ~1.8GB del modelo de voz (XTTS-v2) — la primera vez. Puede tardar varios minutos según la conexión.
- Muestra el progreso paso a paso (`[N/10]`), no debería parecer colgado — si una descarga tarda, va a mostrar el progreso de `pip`/la barra de descarga del modelo.
## 3. Habilitar el Locutor Automático en GRP
En **G Radio Player → Configuración → Locutor Automático**, activar la opción (aparece un aviso para aceptar explícitamente, ya que la locución la genera este componente aparte, no GRP).
## 4. Abrir la interfaz "Locutor IA - GRP"
Buscarla en el menú de aplicaciones, o ejecutar:
```bash
gr-locutor-config
```
Ahí se puede:
- Elegir la voz de referencia (la genérica de GRP, o subir un WAV propio de 15-30s de la persona a clonar).
- Definir cada cuántos temas se locuta, cuántas locuciones se generan por adelantado, y qué porcentaje de las locuciones cierra identificando la radio.
- **Guardar** (aplica la configuración).
- **Generar prueba** (sintetiza un audio de prueba y lo reproduce, para confirmar que el motor funciona).
- El botón grande verde/gris arranca o detiene el locutor (🟢 "Locutor al aire" / ⚫ "Locutor detenido").
## Qué esperar (para no confundir con un bug)
- **Sin GPU, cada locución tarda entre ~30 y ~100 segundos en generarse.** Es normal — entra igual dentro del tiempo que dura una canción (3-4 min), pero no es instantáneo como con GPU.
- **La primera locución de una sesión tarda más** (carga el modelo en memoria, ~10-120s según CPU/GPU) — las siguientes son más rápidas si el proceso queda corriendo.
- El locutor **no reemplaza música**: se inserta como un tema más en la cola, antes de la canción que le corresponda narrar.
- `playlist-refill` (el relleno automático de la cola de GRP) sigue funcionando en paralelo sin problema — no hace falta pausar nada a mano.
- Si Wikipedia/MusicBrainz no responden o no encuentran nada, la locución sigue generándose igual (con menos datos, no falla).
## Cómo reportar problemas
Escribir a Telegram: **[@liberaturadio](https://t.me/liberaturadio)**
Anotar:
- Qué esperabas que pasara vs. qué pasó.
- Si aplica: el archivo `~/.gradio/data/tmp/locuciones-monitor.log` (el log del daemon que genera las locuciones).
- Si la interfaz gráfica se comporta raro: cualquier mensaje que haya quedado en la franja de estado (debajo de los botones "Generar prueba"/"Guardar").
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+45
View File
@@ -0,0 +1,45 @@
# gr-locutor (Locutor IA - GRP)
Locuciones de radio generadas con voz IA local (XTTS-v2, sin depender de
APIs de voz en la nube), integradas a
[G Radio Player](https://git.gradio.net/cescobar/G-Radio-Player). Anuncia
temas, identifica la radio y agrega contenido (curiosidades, frases
motivacionales, datos de Wikipedia/MusicBrainz) sin cortar la música — se
inserta como un tema más en la cola.
> **¿Solo querés instalarlo?** Ver [`LEEME.md`](./LEEME.md) — guía paso a
> paso para usuarios finales (requisitos, instalación del paquete y del
> motor de voz, cómo habilitarlo en GRP).
## Componentes
| Parte | Qué es |
|---|---|
| `gr-locutor-config` (Rust/GTK4, `src/main.rs`) | Interfaz gráfica: elegir voz de referencia, parámetros (cada cuántos temas, ventana de locuciones adelantadas, % de identificación), botón de prueba y encendido/apagado del monitor |
| `assets/locutor-ia/generar.py` | Genera el audio de una locución con XTTS-v2 |
| `assets/locutor-ia/scripts/monitor-locuciones.py` | Daemon: decide cuándo tocan locución y dispara la generación, sin pausar `playlist-refill` |
| `assets/locutor-ia/scripts/enriquecer-locucion.py` | Arma el texto (opener + cuerpo + cierre con identificación de la radio) |
| `assets/locutor-ia/{curiosidades,frases-motivacionales,identificaciones}.txt` | Bancos de texto usados por el enriquecimiento |
| `instalar-locutor-amd64.sh` | Instala el motor XTTS-v2 en un venv aislado (`~/.gradio/locutor-venv/`), detecta GPU NVIDIA vs. CPU |
Requiere G Radio Player **0.4.11 o superior** ya instalado (expone la
bandera `locutor_auto` y el campo `fundido_exclude` que usa el locutor).
## Compilar
```bash
cargo build --release
```
## Empaquetar
```bash
./package-deb.sh 0.1.1
```
Genera `gr-locutor_<versión>_amd64.deb` con `Depends: gradio-player (>= 0.4.11)`.
## Licencia
Distribuido bajo los términos de la **GNU General Public License v3.0 o posterior**
(GPL-3.0-or-later). Ver el archivo [`LICENSE`](./LICENSE).
+24
View File
@@ -0,0 +1,24 @@
# Locutor Automático IA — contexto para opencode
Este directorio (`~/.gradio/data/locutor-ia/`) es el contexto y los scripts del **Locutor Automático IA** de G Radio Player: locuciones de radio generadas con voz sintética local (XTTS-v2), sin depender de APIs de voz en la nube.
## Antes de nada: ¿está habilitado?
```bash
cat ~/.gradio/data/tmp/locutor_auto # "1" = habilitado, "0" o inexistente = no
```
No generes locuciones ni inicies el monitor si está en `0`.
## Agente
Usa el agente `agents/locutor-ia.md` para operar esta función (menú, comandos, verificaciones). Cárgalo cuando el usuario pida algo relacionado con locuciones/voz IA.
## Archivos de contexto (carga solo el necesario)
| Cuándo leerlo | Archivo |
|---|---|
| Cómo está armado, rendimiento, coordinación con `playlist-refill` | `context/01-arquitectura.md` |
| Formato del texto generado (opener/tema/info/cierre) | `context/02-formato-locucion.md` |
**No leas los `context/` de entrada. Léelos solo cuando el usuario elija esa opción o pregunte algo específico.**
+92
View File
@@ -0,0 +1,92 @@
---
description: >-
Agente para el Locutor Automático IA de G Radio Player: genera locuciones
de radio (texto enriquecido + voz sintetizada) e inicia/detiene el daemon
que las mantiene listas en la cola. Responde siempre en español.
mode: all
permission:
webfetch: deny
websearch: deny
lsp: deny
task: deny
skill: deny
---
Eres el operador del **Locutor Automático IA** de G Radio Player (GRP). Generás locuciones de radio (presentación de temas, datos curiosos, cierres con el nombre de la emisora) usando síntesis de voz local (XTTS-v2), clonando el timbre de una voz de referencia — la genérica de GRP por defecto, o la propia de la estación si la reemplazaron.
## Antes de hacer nada: verificar que está habilitado
La bandera vive en `~/.gradio/data/tmp/locutor_auto` (`1` = habilitado, `0` o ausente = deshabilitado). Se activa desde el diálogo de Configuración de GRP ("Locutor Automático"). **No generes ni inicies nada si está en `0`** — respeta la decisión del operador.
## Verificar que el motor está instalado
```bash
test -x ~/.gradio/locutor-venv/gr-locutor.sh && echo OK || echo "FALTA INSTALAR"
```
Si falta, indícale al usuario que corra el instalador (`instalar-locutor-amd64.sh` del paquete `gr-locutor`) y no intentes generar nada.
## Menú
```
🎙 LOCUTOR AUTOMÁTICO IA
1. ▶ Iniciar el monitor (mantiene 3 locuciones listas en la cola)
2. ⏹ Detener el monitor
3. 📊 Ver estado del monitor
4. 🎤 Generar una locución de prueba (texto libre)
5. 🎙 Cambiar la voz de referencia de la estación
6. 📖 Ver cómo funciona (formato, arquitectura)
Elige un número o describe lo que necesitas:
```
## Opción 1 — Iniciar el monitor
```bash
~/.gradio/data/locutor-ia/scripts/start-monitor.sh start
```
Esto also crea `~/.gradio/data/tmp/pause_refill` para que `playlist-refill` no compita agregando canciones mientras el monitor gestiona la cola — es automático, no hace falta nada aparte.
## Opción 2 — Detener el monitor
```bash
~/.gradio/data/locutor-ia/scripts/start-monitor.sh stop
```
Esto libera `pause_refill` automáticamente (`playlist-refill` vuelve a rellenar la cola normalmente).
## Opción 3 — Ver estado
```bash
~/.gradio/data/locutor-ia/scripts/start-monitor.sh status
```
## Opción 4 — Generar una locución de prueba
```bash
~/.gradio/locutor-venv/gr-locutor.sh "Texto de la locución" nombre_opcional
```
Imprime la ruta del MP3 generado. Con GPU tarda unos segundos; en CPU puede tardar 30-100+ segundos — avisar al usuario que espere y no interrumpir el proceso.
## Opción 5 — Cambiar la voz de referencia
La voz activa es `~/.gradio/data/locutor-ia/referencia/voz_referencia.wav`. Para cambiarla:
1. Pedir la ruta de un WAV de 15-30 segundos, limpio (sin música de fondo), de la persona a clonar.
2. Verificar que existe: `ls -la "<ruta>"`.
3. Confirmar y reemplazar: `cp "<ruta>" ~/.gradio/data/locutor-ia/referencia/voz_referencia.wav`
4. Avisar que las próximas locuciones usarán la nueva voz (no hace falta reiniciar nada).
## Opción 6 — Cómo funciona
Leer `context/01-arquitectura.md` y `context/02-formato-locucion.md` según lo que pregunte el usuario. No cargar esos archivos de entrada — solo cuando el usuario elige esta opción o pregunta algo específico.
## Reglas de calidad
- **Nunca generes locuciones si `tmp/locutor_auto` está en `0`.**
- Verificar que el motor esté instalado antes de intentar generar (ver arriba).
- No interrumpir una generación en curso (puede tardar más de un minuto en CPU).
- Si el usuario pide clonar una voz, confirmar la ruta del WAV antes de sobreescribir la actual.
- Responder siempre en **español**.
@@ -0,0 +1,45 @@
# Arquitectura del Locutor Automático IA
## Componentes instalados
| Ruta | Rol |
|---|---|
| `~/.gradio/locutor-venv/` | Entorno virtual Python con el motor XTTS-v2 (torch, coqui-tts, transformers) |
| `~/.gradio/locutor-venv/gr-locutor.sh` | Wrapper: `gr-locutor.sh "texto" [nombre]` → genera un MP3 |
| `~/.gradio/data/locutor-ia/generar.py` | Script real de síntesis (llamado por el wrapper) |
| `~/.gradio/data/locutor-ia/referencia/voz_referencia.wav` | Voz de referencia activa (genérica de GRP o la de la estación) |
| `~/.gradio/data/locutor-ia/salida/` | MP3 generados |
| `~/.gradio/data/locutor-ia/scripts/enriquecer-locucion.py` | Genera el texto: metadata ID3 + Wikipedia + MusicBrainz |
| `~/.gradio/data/locutor-ia/scripts/generar-intro.sh` | Orquesta: texto enriquecido → `gr-locutor.sh` |
| `~/.gradio/data/locutor-ia/scripts/monitor-locuciones.py` | Daemon: mantiene 3 locuciones listas en `playlist4` |
| `~/.gradio/data/locutor-ia/scripts/start-monitor.sh` | start / stop / status del monitor |
## Flujo de una locución
```
monitor-locuciones.py detecta que faltan locuciones en la ventana
└── generar-intro.sh "/ruta/tema.mp3"
├── enriquecer-locucion.py → texto (metadata + Wikipedia + MusicBrainz)
└── gr-locutor.sh "texto" → generar.py → XTTS-v2 → MP3 en salida/
└── monitor inserta el MP3 en playlist4 delante de la canción
```
## Coordinación con `playlist-refill`
`playlist-refill` (proceso de GRP) agrega canciones al final de `playlist4` hasta llegar a 14 temas. Si corre a la vez que el monitor inserta locuciones, puede haber una carrera (leer-generar-escribir tarda varios segundos, y mientras tanto el player puede haber consumido temas).
Solución ya implementada: `monitor-locuciones.py` crea `~/.gradio/data/tmp/pause_refill` al iniciar (GRP ya respeta este archivo — es el mismo mecanismo del botón "Automático" de la UI) y lo borra al detenerse. **No hace falta ninguna acción manual**`start-monitor.sh start/stop` lo maneja solo.
## Bandera de habilitación
`~/.gradio/data/tmp/locutor_auto` (`1`/`0`) — se controla desde el diálogo de Configuración de GRP ("Locutor Automático"). El monitor y el generador no deberían correr si está en `0`.
## Rendimiento medido (texto de referencia ~10s de audio)
| Máquina | Generar | Cargar modelo (1 vez) |
|---|---|---|
| Escritorio con GPU NVIDIA | ~2s | ~10s |
| Escritorio CPU (20 hilos, sin GPU) | ~29s | ~10s |
| RPi5 real (CPU, sin GPU) | ~104s | ~120s |
Todos entran en el margen de una canción de 3-4 minutos. La recomendación es **no correr el generador en la misma máquina que reproduce en vivo** salvo que tenga GPU o de sobra de RAM/CPU — en el RPi5 se midió presión real de memoria (swap) al generar en aislamiento.
@@ -0,0 +1,44 @@
# Formato de la locución enriquecida
Generado por `scripts/enriquecer-locucion.py`. Cada locución tiene 3 partes:
```
{OPENER}, {TEMA}, {INFO ENRIQUECIDA}
```
Y opcionalmente (50% de las veces) un **cierre** con el nombre de la emisora (leído de `gradio.config`, no hardcodeado) y un saludo según la hora del día.
## 1. Opener (aleatorio, uno de tres)
- **Curiosidad del país** (si MusicBrainz devuelve país de origen): *"¿Sabías que {país} es conocido por {dato}?"*
- **Consejo ecológico**: *"Recuerda: {consejo}."* (banco fijo de frases sobre reducir huella de carbono)
- **Dato turístico del país**: *"{País} ofrece {dato turístico}."*
## 2. Tema (siempre presente)
```
"Escuchas {título} de {artista}"
```
## 3. Info enriquecida
Según los datos disponibles: año de grabación, género, país de lanzamiento, y un dato de Wikipedia (1-2 oraciones) sobre el artista o la canción.
## 4. Cierre opcional (~50%)
```
"Estás en sintonía con {nombre de la radio}. {saludo según hora}"
```
El nombre de la radio se lee de `~/.gradio/data/tmp/gradio.config` (línea 3, campo `station_name`) — **nunca lo hardcodees**, cada estación tiene el suyo.
## Ejemplo completo
> "¿Sabías que México es el país con más patrimonios de la humanidad en América Latina? Escuchas Muriendo Lento de Moderatto con Belinda, un tema pop lanzado en México en 2007. Estás en sintonía con Radio Ejemplo. ¡Buenos días!"
## Fuentes de datos
- **Metadata ID3**: `mutagen` (título, artista, año, género) — si el archivo no tiene tags, se infiere del nombre `Artista - Título.mp3`.
- **Wikipedia** (`es.wikipedia.org`): dato curioso, solo si hay artículo en español; si no, se omite (nunca se usa inglés).
- **MusicBrainz**: país y año de lanzamiento.
- **Caché**: `~/.gradio/data/tmp/locuciones_cache.json` — evita repetir consultas online del mismo artista/tema. Borrarlo fuerza consultas frescas.
+30
View File
@@ -0,0 +1,30 @@
¿Sabías que el corazón humano late aproximadamente 100 mil veces al día?
¿Sabías que la miel nunca se echa a perder? Se han encontrado frascos de miel en tumbas egipcias de hace 3000 años aún comestibles.
¿Sabías que los pulpos tienen tres corazones?
¿Sabías que la canción más larga jamás grabada dura más de 48 horas?
¿Sabías que el argentino es el país con más psicólogos per cápita del mundo?
¿Sabías que las jirafas solo duermen 30 minutos al día?
¿Sabías que el Internet pesa físicamente lo mismo que una fresa?
¿Sabías que un día en Venus es más largo que un año en Venus?
¿Sabías que la música clásica ayuda a las plantas a crecer mejor?
¿Sabías que Freddie Mercury tenía un rango vocal de 4 octavas?
¿Sabías que el Himno de la Alegría de Beethoven fue el primer tema musical en enviarse al espacio?
¿Sabías que los elefantes son los únicos mamíferos que no pueden saltar?
¿Sabías que el español es el segundo idioma más hablado del mundo por nativos?
¿Sabías que la canción más versionada de la historia es Yesterday de The Beatles?
¿Sabías que las estrellas de mar pueden regenerar sus brazos si los pierden?
¿Sabías que el 90% de la información que existe en el mundo se generó en los últimos 2 años?
¿Sabías que la hormiga puede levantar hasta 50 veces su propio peso?
¿Sabías que el oído humano sigue procesando sonidos incluso mientras dormimos?
¿Sabías que el primer disco compacto comercial fue el 52nd Street de Billy Joel en 1982?
¿Sabías que el papel higiénico fue inventado en China en el siglo sexto?
¿Sabías que la risa reduce las hormonas del estrés y fortalece el sistema inmunológico?
¿Sabías que los Beatles nunca aprendieron a leer música?
¿Sabías que hay más estrellas en el universo que granos de arena en todas las playas de la Tierra?
¿Sabías que la palabra 'música' viene del griego 'mousiké', que significa 'el arte de las musas'?
¿Sabías que Michael Jackson ganó 13 premios Grammy?
¿Sabías que los flamencos son rosados por lo que comen, principalmente camarones y algas?
¿Sabías que tu ADN puede almacenar hasta 700 terabytes de información?
¿Sabías que la música favorita de Albert Einstein era Mozart?
¿Sabías que el sistema braille fue inventado por Louis Braille cuando tenía solo 15 años?
¿Sabías que los delfines se ponen nombres propios y se llaman entre ellos?
@@ -0,0 +1,15 @@
¡Échale ganas que la vida es una sola!
Nunca es tarde para empezar de nuevo, ¡el momento es ahora!
Hoy es un buen día para ser feliz, ¡decídete!
Recuerda: todo esfuerzo tiene su recompensa, ¡sigue adelante!
La música es el alma de la vida, y hoy vamos a celebrarla.
No hay meta imposible cuando pones el corazón.
Cada día es una nueva oportunidad para brillar.
La actitud lo es todo, ¡ponle buena vibra a tu día!
Lo mejor de la vida está en los pequeños momentos, disfrútalos.
Si puedes soñarlo, puedes lograrlo, ¡nunca te rindas!
El éxito no es casualidad, es perseverancia. ¡Tú puedes!
La felicidad no es un destino, es el camino. ¡Disfrútalo!
Sonríe, que la vida es bella y hoy tenemos buena música.
Agradece lo que tienes mientras trabajas por lo que quieres.
La música une corazones y hoy estamos conectados por ella.
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Genera una locución con XTTS-v2 usando la voz de referencia de GRP (o una
voz de referencia propia de la estación, si reemplazó el archivo).
Uso:
generar.py "texto de la locución" [nombre_salida]
Salida: ruta del MP3 generado, impresa en stdout (para que scripts la capturen).
Variables de entorno:
GR_LOCUTOR_VOZ ruta al WAV de referencia (default: ~/.gradio/data/locutor-ia/referencia/voz_referencia.wav)
GR_LOCUTOR_DIR carpeta de datos (default: ~/.gradio/data/locutor-ia)
"""
import os
import socket
import subprocess
import sys
import time
# Forzar resolución IPv4: en la prueba real en RPi5 una conexión IPv6 mal
# enrutada dejó el proceso colgado ~53 minutos esperando una respuesta que
# nunca llegó. Esto evita ese modo de falla en cualquier red similar.
_orig_getaddrinfo = socket.getaddrinfo
def _ipv4_only_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
return _orig_getaddrinfo(host, port, socket.AF_INET, type, proto, flags)
socket.getaddrinfo = _ipv4_only_getaddrinfo
DATA_DIR = os.environ.get("GR_LOCUTOR_DIR", os.path.expanduser("~/.gradio/data/locutor-ia"))
SALIDA_DIR = os.path.join(DATA_DIR, "salida")
def log(msg):
print(f"[gr-locutor] {msg}", file=sys.stderr, flush=True)
def voz_referencia():
"""Prioridad: variable de entorno GR_LOCUTOR_VOZ > locutor.config
(voz_modo=propia + voz_propia_path, escrito por gr-locutor-config) >
voz genérica de GRP por defecto."""
env = os.environ.get("GR_LOCUTOR_VOZ")
if env:
return env
config_path = os.path.join(DATA_DIR, "locutor.config")
modo = "generica"
ruta_propia = ""
try:
with open(config_path) as f:
for line in f:
if "=" not in line or line.strip().startswith("#"):
continue
clave, valor = line.split("=", 1)
clave, valor = clave.strip(), valor.strip()
if clave == "voz_modo":
modo = valor
elif clave == "voz_propia_path":
ruta_propia = valor
except FileNotFoundError:
pass
if modo == "propia" and ruta_propia:
return ruta_propia
return os.path.join(DATA_DIR, "referencia", "voz_referencia.wav")
REF_VOICE = voz_referencia()
def has_gpu():
try:
import torch
return torch.cuda.is_available()
except Exception:
return False
def main():
if len(sys.argv) < 2:
print(f"Uso: {sys.argv[0]} \"texto de la locución\" [nombre_salida]", file=sys.stderr)
sys.exit(1)
texto = sys.argv[1]
nombre = sys.argv[2] if len(sys.argv) > 2 else time.strftime("locucion_%Y%m%d_%H%M%S")
if not os.path.isfile(REF_VOICE):
log(f"ERROR: no existe la voz de referencia en {REF_VOICE}")
log("Ejecuta el instalador o coloca un WAV de 15-30s en esa ruta.")
sys.exit(1)
os.makedirs(SALIDA_DIR, exist_ok=True)
wav_path = f"/tmp/{nombre}.wav"
mp3_path = os.path.join(SALIDA_DIR, f"{nombre}.mp3")
device = "cuda" if has_gpu() else "cpu"
log(f"Dispositivo: {device} | Voz de referencia: {REF_VOICE}")
t0 = time.time()
from TTS.api import TTS
tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(device)
t_load = time.time()
tts.tts_to_file(text=texto, speaker_wav=REF_VOICE, language="es", file_path=wav_path)
t_gen = time.time()
log(f"Cargar modelo: {t_load - t0:.1f}s | Generar: {t_gen - t_load:.1f}s")
subprocess.run(
["ffmpeg", "-y", "-loglevel", "error", "-i", wav_path, "-ar", "44100", "-b:a", "320k", mp3_path],
check=True,
)
os.remove(wav_path)
print(mp3_path)
if __name__ == "__main__":
main()
+10
View File
@@ -0,0 +1,10 @@
Estás en sintonía con {radio}.
Sigues conectado con {radio}, la mejor música.
{radio} te acompaña en todo momento.
Gracias por sintonizar {radio}.
Esto es {radio}, tu emisora de siempre.
{radio}, la música que te gusta escuchar.
Quédate con nosotros, esto es {radio}.
{radio} — siempre contigo.
Sigue disfrutando de la mejor música en {radio}.
Estás escuchando {radio}, gracias por acompañarnos.
Binary file not shown.
@@ -0,0 +1,368 @@
#!/usr/bin/env python3
"""Toma la ruta de un tema, extrae metadata y datos online, genera texto enriquecido.
Uso:
./enriquecer-locucion.py /ruta/al/tema.mp3
Salida (stdout): texto enriquecido listo para locución
Estructura de la locución:
1. Opener: una línea aleatoria, alternando entre curiosidades.txt y
frases-motivacionales.txt (nunca se repite el mismo banco dos veces seguidas).
2. Tema: título/artista + info enriquecida (año/género/país/dato Wikipedia).
3. Cierre opcional: una línea de identificaciones.txt (con {radio} sustituido
por el nombre real de la emisora, leído de gradio.config) — aparece según
el porcentaje configurado en locutor.config (50% por defecto).
"""
import json, os, random, re, requests, sys
try:
import mutagen
except ImportError:
mutagen = None
DATA_DIR = os.environ.get("GR_LOCUTOR_DIR", os.path.expanduser("~/.gradio/data/locutor-ia"))
CACHE_FILE = os.path.expanduser("~/.gradio/data/tmp/locuciones_cache.json")
GRADIO_CONFIG_FILE = os.path.expanduser("~/.gradio/data/tmp/gradio.config")
LOCUTOR_CONFIG_FILE = os.path.join(DATA_DIR, "locutor.config")
ALTERNANCIA_FILE = os.path.expanduser("~/.gradio/data/tmp/locutor_ultimo_banco")
MB_USER_AGENT = "GRadio-LocutorIA/1.0"
TIMEOUT = 8
def log(msg):
print(f"[enriquecer] {msg}", file=sys.stderr, flush=True)
def station_name():
"""Lee el nombre de la radio desde gradio.config (línea 3), igual que GRP.
Default 'G Radio' si no existe el archivo o la línea está vacía."""
try:
with open(GRADIO_CONFIG_FILE) as f:
lines = f.read().splitlines()
if len(lines) >= 3 and lines[2].strip():
return lines[2].strip()
except FileNotFoundError:
pass
return "G Radio"
def porcentaje_identificacion():
"""Lee porcentaje_identificacion de locutor.config (clave=valor). Default 50."""
try:
with open(LOCUTOR_CONFIG_FILE) as f:
for line in f:
if line.strip().startswith("porcentaje_identificacion"):
return int(line.split("=", 1)[1].strip())
except (FileNotFoundError, ValueError, IndexError):
pass
return 50
def leer_banco(nombre_archivo):
path = os.path.join(DATA_DIR, nombre_archivo)
try:
with open(path, encoding="utf-8") as f:
return [l.strip() for l in f if l.strip()]
except FileNotFoundError:
return []
def elegir_opener():
"""Alterna entre curiosidades.txt y frases-motivacionales.txt: nunca
repite el mismo banco dos veces seguidas (se persiste cuál tocó última vez)."""
bancos = {"curiosidades": "curiosidades.txt", "frases": "frases-motivacionales.txt"}
ultimo = ""
try:
with open(ALTERNANCIA_FILE) as f:
ultimo = f.read().strip()
except FileNotFoundError:
pass
opciones = [b for b in bancos if b != ultimo] or list(bancos)
elegido = random.choice(opciones)
lineas = leer_banco(bancos[elegido])
if not lineas:
# Fallback: probar el otro banco si el elegido está vacío/falta
otro = [b for b in bancos if b != elegido]
if otro:
lineas = leer_banco(bancos[otro[0]])
elegido = otro[0]
if not lineas:
return ""
try:
with open(ALTERNANCIA_FILE, "w") as f:
f.write(elegido)
except OSError:
pass
return random.choice(lineas)
def elegir_identificacion():
lineas = leer_banco("identificaciones.txt")
if not lineas:
return f"Estás en sintonía con {station_name()}."
return random.choice(lineas).replace("{radio}", station_name())
def extract_metadata(song_path):
title = artist = album = year = genre = None
if mutagen:
try:
tags = mutagen.File(song_path, easy=True)
if tags:
title = tags.get("title", [None])[0]
artist = tags.get("artist", [None])[0]
album = tags.get("album", [None])[0]
year = tags.get("date", [None])[0]
genre = tags.get("genre", [None])[0]
if title and artist:
return title.strip(), artist.strip(), album, year, genre
except Exception as e:
log(f"mutagen error: {e}")
name = os.path.splitext(os.path.basename(song_path))[0]
name = re.sub(r"\(.*?\)", "", name)
name = re.sub(r"www\..*", "", name)
name = name.strip()
artist = title = None
if " - " in name:
parts = name.split(" - ", 1)
artist = parts[0].strip()
title = parts[1].strip()
else:
title = name
return title, artist, album, year, genre
def load_cache():
try:
with open(CACHE_FILE) as f:
return json.load(f)
except Exception:
return {}
def save_cache(cache):
try:
with open(CACHE_FILE, "w") as f:
json.dump(cache, f)
except Exception:
pass
def lookup_wikipedia(artist, title, cache):
if not title:
return None
key = f"wiki:{artist}:{title}"
if key in cache:
return cache[key]
queries = []
if artist:
queries.append(f'"{artist}" "{title}" canción')
queries.append(f'"{artist}" "{title}" música')
queries.append(f'"{artist}" músico')
else:
queries.append(f'"{title}" canción')
WIKI = "https://es.wikipedia.org/w/api.php"
for q in queries:
try:
r = requests.get(WIKI,
params={
"action": "query",
"list": "search",
"srsearch": q,
"format": "json",
"srlimit": 3,
},
timeout=TIMEOUT,
headers={"User-Agent": "GRadio-LocutorIA/1.0 (radio-automation)"},
)
data = r.json()
pages = data.get("query", {}).get("search", [])
if not pages:
continue
for page in pages:
page_title = page["title"]
r2 = requests.get(
WIKI,
params={
"action": "query",
"prop": "extracts",
"exintro": True,
"explaintext": True,
"titles": page_title,
"format": "json",
"exsentences": 3,
},
timeout=TIMEOUT,
headers={"User-Agent": "GRadio-LocutorIA/1.0 (radio-automation)"},
)
pg_data = r2.json().get("query", {}).get("pages", {})
for pid, pg in pg_data.items():
if pid == "-1" or "extract" not in pg:
continue
extract = pg["extract"].strip()
sentences = re.split(r"(?<=[.!?])\s+", extract)
for s in sentences:
s = s.strip()
if 40 <= len(s) <= 200:
cache[key] = s
save_cache(cache)
return s
except Exception as e:
log(f"wiki error ({q[:30]}...): {e}")
cache[key] = None
save_cache(cache)
return None
def lookup_musicbrainz(artist, title, cache):
if not artist or not title:
return None
key = f"mb:{artist}:{title}"
if key in cache:
return cache[key]
try:
r = requests.get(
"https://musicbrainz.org/ws/2/recording/",
params={
"query": f'artist:"{artist}" AND recording:"{title}"',
"fmt": "json",
"limit": 1,
},
timeout=TIMEOUT + 2,
headers={"User-Agent": MB_USER_AGENT},
)
data = r.json()
recs = data.get("recordings", [])
if not recs:
cache[key] = None
save_cache(cache)
return None
rec = recs[0]
info = {}
if "releases" in rec and rec["releases"]:
rel = rec["releases"][0]
date = rel.get("date", "")
info["year"] = date[:4] if date and len(date) >= 4 else ""
info["country"] = rel.get("country", "")
if "artist-credit" in rec:
ac = rec["artist-credit"][0]
if isinstance(ac, dict) and "artist" in ac:
info["artist_type"] = ac["artist"].get("type", "")
cache[key] = info if info else None
save_cache(cache)
return info
except Exception as e:
log(f"musicbrainz error: {e}")
cache[key] = None
save_cache(cache)
return None
_PAISES = {
"US": "Estados Unidos", "GB": "Reino Unido", "UK": "Reino Unido",
"ES": "España", "MX": "México", "AR": "Argentina", "CO": "Colombia",
"CL": "Chile", "PE": "Perú", "CU": "Cuba", "PR": "Puerto Rico",
"DE": "Alemania", "FR": "Francia", "IT": "Italia", "BR": "Brasil",
"CA": "Canadá", "AU": "Australia", "JP": "Japón", "MY": "Malasia",
"SE": "Suecia", "NL": "Países Bajos", "IE": "Irlanda", "NO": "Noruega",
"DK": "Dinamarca", "PT": "Portugal", "RU": "Rusia",
}
def generate_text(artist, title, album, year, genre, wiki_fact, mb_info):
anyo = mb_info.get("year", "") if mb_info and isinstance(mb_info, dict) else ""
nombre_pais = ""
pa_mb = mb_info.get("country", "") if mb_info and isinstance(mb_info, dict) else ""
if pa_mb:
nombre_pais = _PAISES.get(pa_mb, pa_mb)
# --- 1. Opener (alternando curiosidades.txt / frases-motivacionales.txt) ---
opener = elegir_opener()
# --- 2. Tema ---
if artist and title:
tema = f"Escuchas {title} de {artist}"
elif title:
tema = f"Escuchas {title}"
else:
tema = ""
# --- 3. Info enriquecida ---
infos = []
if anyo and anyo not in ("?", ""):
infos.append(f"grabada en {anyo}")
if genre and genre not in ("?", ""):
infos.append(f"un tema de {genre}")
if nombre_pais:
infos.append(f"lanzada en {nombre_pais}")
info_str = ", ".join(infos) if infos else ""
wiki_str = ""
if wiki_fact:
fact = wiki_fact.strip()
if len(fact) > 160:
fact = fact[:157] + "..."
wiki_str = fact
if tema and info_str:
cuerpo = f"{tema}, {info_str}."
elif tema:
cuerpo = f"{tema}."
elif info_str:
cuerpo = info_str
else:
cuerpo = ""
if wiki_str:
cuerpo = f"{cuerpo} {wiki_str}" if cuerpo else wiki_str
# --- 4. Cierre opcional (según porcentaje_identificacion de locutor.config) ---
cierre = ""
if random.randint(1, 100) <= porcentaje_identificacion():
cierre = elegir_identificacion()
oraciones = [o for o in (opener, cuerpo, cierre) if o]
return " ".join(oraciones)
def main():
if len(sys.argv) < 2:
log("Uso: enriquecer-locucion.py /ruta/al/tema.mp3")
sys.exit(1)
song_path = os.path.abspath(sys.argv[1])
if not os.path.exists(song_path):
log(f"no existe: {song_path}")
sys.exit(1)
title, artist, album, year, genre = extract_metadata(song_path)
log(f"metadata: artist={artist} title={title} album={album} year={year} genre={genre}")
cache = load_cache()
wiki_fact = lookup_wikipedia(artist or title, title, cache)
mb_info = lookup_musicbrainz(artist or title, title, cache)
text = generate_text(artist, title, album, year, genre, wiki_fact, mb_info)
log(f"wiki={'' if wiki_fact else 'no'} mb={'' if mb_info else 'no'}")
log(f"texto ({len(text)} chars): {text[:100]}...")
print(text)
if __name__ == "__main__":
main()
@@ -0,0 +1,60 @@
#!/bin/bash
# Genera una locución de introducción para un tema musical
# Uso: ./generar-intro.sh "/ruta/al/tema.mp3"
# Imprime la ruta del MP3 generado en stdout
#
# 1. Lee metadata ID3 del tema + enriquece con Wikipedia/MusicBrainz
# 2. Sintetiza con el motor instalado (~/.gradio/locutor/gr-locutor.sh),
# usando la voz de referencia configurada (genérica de GRP o la propia
# de la estación si fue reemplazada)
set -e
cd "$(dirname "$0")"
TEMA="$1"
LOCUTOR_BIN="$HOME/.gradio/locutor-venv/gr-locutor.sh"
ENRIQUECER="enriquecer-locucion.py"
SALIDA_DIR="$HOME/.gradio/data/locutor-ia/salida"
if [ -z "$TEMA" ]; then
echo "Uso: $0 \"/ruta/al/tema.mp3\""
exit 1
fi
if [ ! -f "$TEMA" ]; then
echo "Error: no existe el archivo $TEMA"
exit 1
fi
if [ ! -x "$LOCUTOR_BIN" ]; then
echo "Error: no está instalado el motor de voz ($LOCUTOR_BIN)."
echo "Ejecuta primero el instalador (instalar-locutor-amd64.sh)."
exit 1
fi
TEXTO=""
if [ -f "$ENRIQUECER" ]; then
TEXTO=$(python3 "$ENRIQUECER" "$TEMA" 2>/dev/null || true)
fi
if [ -z "$TEXTO" ]; then
BASENAME=$(basename "$TEMA" .mp3)
BASENAME="${BASENAME%.*}"
ARTISTA=""
TITULO="$BASENAME"
if echo "$BASENAME" | grep -q " - "; then
ARTISTA=$(echo "$BASENAME" | sed 's/ - .*//')
TITULO=$(echo "$BASENAME" | sed 's/.* - //')
fi
if [ -n "$ARTISTA" ]; then
TEXTO="Y ahora, disfruta de ${TITULO} de ${ARTISTA}."
else
TEXTO="Y ahora, disfruta de ${TITULO}."
fi
fi
NOMBRE="intro_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$SALIDA_DIR"
MP3=$("$LOCUTOR_BIN" "$TEXTO" "$NOMBRE")
echo "$MP3"
@@ -0,0 +1,339 @@
#!/usr/bin/env python3
"""Monitor de Locuciones — Ventana corrediza configurable.
Cuando una locución+song se consume (desaparece del tope de playlist4),
genera la siguiente locución para el próximo song sin locución que le
corresponda narrar (según `cada_cuantos_temas`). Solo genera UNA a la vez
para no saturar el motor de TTS.
Lee `ventana_previas` y `cada_cuantos_temas` de locutor.config en cada
ciclo (permite reconfigurar sin reiniciar el daemon).
No pausa `playlist-refill` (el daemon de GRP que rellena la cola desde la
parrilla): ese proceso solo agrega canciones al final hasta un largo
objetivo, sin importar el contenido existente — conviven sin conflicto,
igual que si se agregaran temas a mano. La única carrera real posible
(el player consume temas mientras este monitor genera una locución, que
puede tardar decenas de segundos) se resuelve re-leyendo `playlist4` justo
antes de escribir, no pausando nada — pausar indefinidamente dejaría de
rellenar la cola y la estación se quedaría sin música.
"""
import json
import os
import subprocess
import sys
import time
TMP_DIR = os.path.expanduser("~/.gradio/data/tmp")
DATA_DIR = os.path.expanduser("~/.gradio/data/locutor-ia")
ESTADO_FILE = os.path.join(TMP_DIR, "estado.json")
PLAYLIST_FILE = os.path.join(TMP_DIR, "playlist4")
LOCUTOR_AUTO_FILE = os.path.join(TMP_DIR, "locutor_auto")
LOCUTOR_CONFIG_FILE = os.path.join(DATA_DIR, "locutor.config")
CONTADOR_FILE = os.path.join(TMP_DIR, "locutor_song_counter.json")
SCRIPT_DIR = os.path.join(DATA_DIR, "scripts")
GENERAR_SCRIPT = os.path.join(SCRIPT_DIR, "generar-intro.sh")
LOCK_FILE = os.path.join(TMP_DIR, "locuciones_generating")
POLL_INTERVAL = 3
DEFAULT_WINDOW_SIZE = 3
DEFAULT_CADA_CUANTOS = 3
def log(msg):
ts = time.strftime("%Y-%m-%d %H:%M:%S")
print(f"[{ts}] {msg}", flush=True)
def leer_locutor_config():
"""Lee ventana_previas y cada_cuantos_temas de locutor.config (clave=valor)."""
ventana = DEFAULT_WINDOW_SIZE
cada_cuantos = DEFAULT_CADA_CUANTOS
try:
with open(LOCUTOR_CONFIG_FILE) as f:
for line in f:
line = line.strip()
if "=" not in line or line.startswith("#"):
continue
clave, valor = line.split("=", 1)
clave, valor = clave.strip(), valor.strip()
if clave == "ventana_previas":
ventana = max(1, int(valor))
elif clave == "cada_cuantos_temas":
cada_cuantos = max(1, int(valor))
except (FileNotFoundError, ValueError):
pass
return ventana, cada_cuantos
def read_playlist():
try:
with open(PLAYLIST_FILE) as f:
return [l.strip() for l in f if l.strip()]
except FileNotFoundError:
return []
def write_playlist(lines):
with open(PLAYLIST_FILE, "w") as f:
for line in lines:
f.write(line + "\n")
def is_locution(entry):
ruta = entry.split("\t")[0]
return "intro_" in os.path.basename(ruta)
def get_song_path(entry):
return entry.split("\t")[0]
MAX_DECISIONES = 300 # tope para que el archivo no crezca sin límite
def load_contador():
try:
with open(CONTADOR_FILE) as f:
state = json.load(f)
state.setdefault("count", 0)
state.setdefault("decisiones", {})
return state
except Exception:
return {"count": 0, "decisiones": {}}
def save_contador(state):
try:
with open(CONTADOR_FILE, "w") as f:
json.dump(state, f)
except OSError:
pass
def corresponde_narrar(song_path, cada_cuantos):
"""Decide si a este tema le toca locución, contando temas distintos vistos.
Recuerda la decisión de CADA tema ya evaluado (no solo el último): el
escaneo de ensure_window() reinicia desde el principio en cada ciclo de
poll, así que un tema ya decidido puede volver a aparecer como "primer
candidato" en ciclos siguientes — si solo se recordara el último tema
visto, ese tema se recontaría como si fuera nuevo cada vez, corrompiendo
el conteo de "cada N temas".
"""
state = load_contador()
decisiones = state["decisiones"]
if song_path not in decisiones:
state["count"] += 1
decisiones[song_path] = (state["count"] % cada_cuantos == 0)
# Podar entradas más viejas si crece demasiado (dict preserva orden de inserción)
while len(decisiones) > MAX_DECISIONES:
decisiones.pop(next(iter(decisiones)))
save_contador(state)
return decisiones[song_path]
def generate_locution(song_path):
if not os.path.exists(GENERAR_SCRIPT):
log(f"ERROR: no existe {GENERAR_SCRIPT}")
return None, None
if not os.path.exists(song_path):
log(f"ERROR: no existe {song_path}")
return None, None
try:
result = subprocess.run(
["bash", GENERAR_SCRIPT, song_path],
capture_output=True, text=True, timeout=300,
cwd=SCRIPT_DIR
)
if result.returncode == 0:
rel_path = result.stdout.strip().split("\n")[-1]
mp3_path = rel_path if os.path.isabs(rel_path) else os.path.join(SCRIPT_DIR, rel_path)
if mp3_path and mp3_path.endswith(".mp3") and os.path.exists(mp3_path):
dur = get_duration(mp3_path)
return mp3_path, dur
err = result.stderr.strip() or "(sin stderr)"
log(f"ERROR generar-intro (rc={result.returncode}): {err[:150]}")
return None, None
except subprocess.TimeoutExpired:
log("ERROR: generar-intro TIMEOUT (>300s)")
return None, None
except Exception as e:
log(f"ERROR: {e}")
return None, None
def get_duration(mp3_path):
try:
r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", mp3_path],
capture_output=True, text=True, timeout=5)
secs = float(r.stdout.strip())
mins = int(secs // 60)
secs = secs % 60
return f"{mins:02d}:{secs:05.3f}"[:11]
except Exception:
pass
return "00:00:16.000"
LOCK_MAX_AGE = 300 # 5 min — la generación real tarda como mucho ~2 min (CPU)
def ensure_window():
"""Mantiene `ventana_previas` locuciones al inicio de la playlist, solo
para los temas que correspondan según `cada_cuantos_temas`. Genera UNA
a la vez para evitar saturar el motor de TTS.
"""
if os.path.exists(LOCK_FILE):
# Si el lock es viejo, quedó de una generación que murió sin pasar
# por el `finally` (kill -9, crash) — lo consideramos obsoleto y lo
# limpiamos, sino el monitor queda trabado para siempre sin avisar.
edad = time.time() - os.path.getmtime(LOCK_FILE)
if edad > LOCK_MAX_AGE:
log(f"Lock de generación obsoleto ({edad:.0f}s) — se limpia y se continúa")
os.unlink(LOCK_FILE)
else:
return # ya hay una generación en curso
ventana, cada_cuantos = leer_locutor_config()
pl = read_playlist()
if len(pl) < 1:
return
pairs = 0
start_i = 1 if (len(pl) > 0 and not is_locution(pl[0])) else 0
i = start_i
while i < len(pl) - 1:
if is_locution(pl[i]) and not is_locution(pl[i + 1]):
pairs += 1
i += 2
else:
break
if pairs >= ventana:
return # ventana completa
# El primer item de la playlist es el que está sonando (o por sonar).
# Si es un song sin locución, su intro ya fue consumida → omitir (evita loop).
start = 1 if (len(pl) > 0 and not is_locution(pl[0])) else 0
for i in range(start, len(pl)):
entry = pl[i]
if is_locution(entry):
continue
if i > 0 and is_locution(pl[i - 1]):
continue
song_path = get_song_path(entry)
if not corresponde_narrar(song_path, cada_cuantos):
continue # a este tema no le toca, seguir buscando el próximo candidato
song_name = os.path.basename(song_path)
log(f"Generando locución para: {song_name} ({pairs+1}/{ventana})")
open(LOCK_FILE, "w").close()
try:
mp3, dur = generate_locution(song_path)
finally:
os.unlink(LOCK_FILE)
if not mp3:
log(" ✗ falló generación, reintentando después")
return
loc_entry = f"{mp3}\t{dur}"
# Re-leer playlist actual para evitar race condition: el player pudo
# haber consumido items durante la generación (decenas de segundos).
current_pl = read_playlist()
if not current_pl:
current_pl = [loc_entry]
log(" ✓ playlist vacía, insertando única línea")
else:
target_path = get_song_path(entry)
inserted = False
for j, line in enumerate(current_pl):
if get_song_path(line) == target_path:
if j > 0 and is_locution(current_pl[j - 1]):
log(" ✗ la canción ya tiene locución, omitiendo")
return
current_pl.insert(j, loc_entry)
inserted = True
break
if not inserted:
current_pl.append(loc_entry)
log(" ✓ canción ya consumida, insertada al final")
else:
log(f" ✓ insertada en playlist: {len(current_pl)} líneas")
write_playlist(current_pl)
return # solo una por ciclo
log("(no se encontraron temas pendientes de narrar)")
def locutor_habilitado():
try:
with open(LOCUTOR_AUTO_FILE) as f:
return f.read().strip() == "1"
except FileNotFoundError:
return False
def main():
log("=== Monitor de Locuciones (gr-locutor) iniciado ===")
# Un lock encontrado al arrancar es, por definición, de una instancia
# anterior (este proceso recién empieza, no pudo haber creado ninguno
# todavía) — por ejemplo si el daemon anterior murió por SIGTERM en
# medio de una generación, sin pasar por el `finally` que lo libera.
if os.path.exists(LOCK_FILE):
log("Lock de generación de una instancia anterior encontrado al iniciar — se limpia")
os.unlink(LOCK_FILE)
if not locutor_habilitado():
log("tmp/locutor_auto no está en '1' — el monitor no generará nada.")
log("Activalo en GRP → Configuración → Locutor Automático.")
ventana, cada_cuantos = leer_locutor_config()
log(f"Ventana de {ventana} locuciones · narra 1 de cada {cada_cuantos} temas")
log("playlist-refill sigue activo — no se pausa (conviven sin conflicto)")
last_track = ""
while True:
try:
if locutor_habilitado():
ensure_window()
except Exception as e:
log(f"Error: {e}")
try:
with open(ESTADO_FILE) as f:
estado = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
estado = None
if estado:
track = estado.get("track_actual", "")
reproduciendo = estado.get("reproduciendo", False)
if track and track != last_track and reproduciendo:
name = os.path.basename(track)
if "intro_" in name:
log(f"▶ Locución: {name}")
else:
log(f"▶ Tema: {name}")
last_track = track
time.sleep(POLL_INTERVAL)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
log("Monitor detenido por el usuario")
sys.exit(0)
@@ -0,0 +1,54 @@
#!/bin/bash
# Inicia/detiene el monitor de locuciones (gr-locutor)
# Uso: start-monitor.sh [start|stop|status]
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PIDFILE="$HOME/.gradio/data/tmp/pids/locuciones-monitor.pid"
MONITOR="$SCRIPT_DIR/monitor-locuciones.py"
LOCUTOR_VENV="$HOME/.gradio/locutor-venv"
case "${1:-start}" in
start)
if [ -f "$PIDFILE" ]; then
pid=$(cat "$PIDFILE" 2>/dev/null)
if kill -0 "$pid" 2>/dev/null; then
echo "Monitor ya está corriendo (PID $pid)"
exit 0
fi
rm -f "$PIDFILE"
fi
mkdir -p "$(dirname "$PIDFILE")"
# shellcheck source=/dev/null
source "$LOCUTOR_VENV/bin/activate"
nohup python3 "$MONITOR" > "$HOME/.gradio/data/tmp/locuciones-monitor.log" 2>&1 &
echo $! > "$PIDFILE"
echo "Monitor de locuciones iniciado (PID $!)"
;;
stop)
if [ -f "$PIDFILE" ]; then
pid=$(cat "$PIDFILE" 2>/dev/null)
kill "$pid" 2>/dev/null && echo "Monitor detenido" || echo "No se pudo detener"
rm -f "$PIDFILE"
else
pkill -f "monitor-locuciones.py" 2>/dev/null && echo "Monitor detenido" || echo "Monitor no estaba corriendo"
fi
;;
status)
if [ -f "$PIDFILE" ]; then
pid=$(cat "$PIDFILE" 2>/dev/null)
if kill -0 "$pid" 2>/dev/null; then
echo "Monitor ACTIVO (PID $pid)"
tail -3 "$HOME/.gradio/data/tmp/locuciones-monitor.log" 2>/dev/null
else
echo "Monitor INACTIVO (PID file obsoleto)"
rm -f "$PIDFILE"
fi
else
echo "Monitor INACTIVO"
fi
;;
*)
echo "Uso: $0 [start|stop|status]"
exit 1
;;
esac
+218
View File
@@ -0,0 +1,218 @@
#!/bin/bash
# instalar-locutor-amd64.sh — Instalador del paquete gr-locutor (Locutor Automático IA), amd64
#
# 1. Instala el motor XTTS-v2 en un venv aislado (~/.gradio/locutor-venv/),
# con GPU NVIDIA si está disponible, o CPU si no.
# 2. Copia los scripts, contexto (para opencode) y voz de referencia genérica
# de GRP a ~/.gradio/data/locutor-ia/ (no sobreescribe si el usuario ya
# reemplazó la voz de referencia por la de su estación).
#
# Descarga varios cientos de MB a varios GB según haya o no GPU — puede
# tardar minutos. Cada paso numerado (N/TOTAL) muestra su propio progreso
# (pip/tqdm) y cuánto tardó al terminar, para que no parezca colgado.
#
# Uso: ./instalar-locutor-amd64.sh
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Ubicación de los assets: primero la de sistema (instalada por el .deb),
# si no existe cae a la del repo (ejecutando el script a mano desde el fuente).
if [ -d "/usr/local/share/gr-locutor/locutor-ia" ]; then
ASSETS_DIR="/usr/local/share/gr-locutor/locutor-ia"
else
ASSETS_DIR="$SCRIPT_DIR/assets/locutor-ia"
fi
VENV_DIR="$HOME/.gradio/locutor-venv"
DATA_DIR="$HOME/.gradio/data/locutor-ia"
REF_VOICE="$DATA_DIR/referencia/voz_referencia.wav"
TOTAL_PASOS=10
paso_n=0
paso() {
paso_n=$((paso_n + 1))
paso_t0=$SECONDS
echo ""
echo "── [$paso_n/$TOTAL_PASOS] $1"
}
paso_fin() {
echo " listo en $((SECONDS - paso_t0))s"
}
echo "======================================================"
echo " Instalador gr-locutor — Locutor Automático IA (GRP)"
echo " Plataforma: amd64"
echo "======================================================"
# ── 1. Requisitos básicos ─────────────────────────────────────────────────────
paso "Verificando requisitos..."
if ! command -v python3 &>/dev/null; then
echo "ERROR: python3 no está instalado."
exit 1
fi
if ! command -v ffmpeg &>/dev/null; then
echo "ERROR: ffmpeg no está instalado (ya debería estarlo si tenés GRP instalado)."
exit 1
fi
ARCH="$(uname -m)"
if [ "$ARCH" != "x86_64" ]; then
echo "AVISO: este instalador es para amd64 (x86_64); se detectó '$ARCH'."
fi
paso_fin
# ── 2. Copiar scripts, contexto y voz de referencia ───────────────────────────
paso "Instalando contexto/scripts en $DATA_DIR..."
mkdir -p "$DATA_DIR/scripts" "$DATA_DIR/context" "$DATA_DIR/agents" "$DATA_DIR/referencia" "$DATA_DIR/salida"
cp "$ASSETS_DIR/AGENTS.md" "$DATA_DIR/"
cp "$ASSETS_DIR/generar.py" "$DATA_DIR/"
cp "$ASSETS_DIR/scripts/"* "$DATA_DIR/scripts/"
cp "$ASSETS_DIR/context/"* "$DATA_DIR/context/"
cp "$ASSETS_DIR/agents/"* "$DATA_DIR/agents/"
cp "$ASSETS_DIR/curiosidades.txt" "$ASSETS_DIR/frases-motivacionales.txt" "$ASSETS_DIR/identificaciones.txt" "$DATA_DIR/"
chmod +x "$DATA_DIR/scripts/"*.sh "$DATA_DIR/scripts/"*.py "$DATA_DIR/generar.py"
if [ ! -f "$REF_VOICE" ]; then
cp "$ASSETS_DIR/referencia/voz_referencia.wav" "$REF_VOICE"
echo " Voz genérica de GRP instalada en: $REF_VOICE"
else
echo " Ya existe una voz de referencia en $REF_VOICE — no se sobreescribe"
echo " (la estación ya puso la suya propia)."
fi
LOCUTOR_CFG="$DATA_DIR/locutor.config"
if [ ! -f "$LOCUTOR_CFG" ]; then
cat > "$LOCUTOR_CFG" << 'DEFAULTCFG'
# Configuración del Locutor Automático IA — valores por defecto
voz_modo=generica
voz_propia_path=
cada_cuantos_temas=3
ventana_previas=3
porcentaje_identificacion=50
DEFAULTCFG
echo " Configuración por defecto creada en: $LOCUTOR_CFG"
else
echo " Ya existe locutor.config — no se sobreescribe (configuración previa respetada)."
fi
paso_fin
# ── 3. Detección de GPU NVIDIA ────────────────────────────────────────────────
paso "Detectando GPU NVIDIA..."
HAS_GPU=0
if command -v nvidia-smi &>/dev/null && nvidia-smi &>/dev/null; then
HAS_GPU=1
echo " GPU detectada:"
nvidia-smi --query-gpu=name,memory.total --format=csv,noheader | sed 's/^/ /'
else
echo " No se detectó GPU NVIDIA — se instalará el stack CPU."
echo " (Probado: ~29-104s por locución de ~10s según el CPU. Entra en el"
echo " margen de una canción de 3-4 min, pero es más lento que con GPU.)"
fi
paso_fin
# ── 4. Crear entorno virtual aislado ───────────────────────────────────────────
paso "Creando entorno virtual en $VENV_DIR..."
python3 -m venv "$VENV_DIR"
# shellcheck source=/dev/null
source "$VENV_DIR/bin/activate"
pip install --upgrade pip
paso_fin
# ── 5. PyTorch + torchaudio (versión pineada, probada en GPU y en RPi5) ────────
if [ "$HAS_GPU" = "1" ]; then
paso "Instalando PyTorch 2.11.0 + CUDA 12.8 (descarga ~1-2GB, puede tardar varios minutos)..."
pip install torch==2.11.0 torchaudio==2.11.0 --index-url https://download.pytorch.org/whl/cu128
else
paso "Instalando PyTorch 2.8.0 CPU (descarga ~100-200MB)..."
pip install torch==2.8.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cpu
fi
paso_fin
# ── 6. coqui-tts + transformers pineado + torchcodec ──────────────────────────
paso "Instalando coqui-tts y dependencias (varios paquetes, ~1-2 min)..."
pip install coqui-tts
echo " Fijando transformers==4.56.2 (versiones más nuevas rompen la capa"
echo " 'tortoise' que usa XTTS-v2 internamente — verificado en dos máquinas)."
echo " El aviso de pip sobre conflicto de versiones es esperado, se ignora."
pip install transformers==4.56.2
echo " Instalando torchcodec (pineado a la build que coincide con torch,"
echo " la versión genérica de PyPI carga una libtorchcodec incompatible)."
if [ "$HAS_GPU" = "1" ]; then
pip install torchcodec==0.11.1 --index-url https://download.pytorch.org/whl/cu128
else
pip install torchcodec==0.11.1 --index-url https://download.pytorch.org/whl/cpu
fi
paso_fin
# ── 7. Wrapper ejecutable ──────────────────────────────────────────────────────
paso "Creando wrapper ejecutable..."
cat > "$VENV_DIR/gr-locutor.sh" << WRAPPER
#!/bin/bash
# Wrapper: gr-locutor.sh "texto" [nombre_salida]
source "$VENV_DIR/bin/activate"
exec python3 "$DATA_DIR/generar.py" "\$@"
WRAPPER
chmod +x "$VENV_DIR/gr-locutor.sh"
paso_fin
# ── 8. Descargar el modelo XTTS-v2 ahora (no esperar a la primera locución) ───
paso "Descargando modelo XTTS-v2 (~1.8GB — se salta si ya está en caché)..."
COQUI_TOS_AGREED=1 python3 -c "
from TTS.api import TTS
TTS('tts_models/multilingual/multi-dataset/xtts_v2')
print('Modelo listo.')
"
paso_fin
deactivate
# ── 9. Interfaz gráfica (Locutor IA - GRP) ────────────────────────────────────
paso "Instalando la interfaz gráfica (Locutor IA - GRP)..."
BIN_PREBUILT="$SCRIPT_DIR/target/release/gr-locutor-config"
mkdir -p "$HOME/.local/bin"
if [ -f "$BIN_PREBUILT" ]; then
cp "$BIN_PREBUILT" "$HOME/.local/bin/gr-locutor-config"
echo " Binario preconstruido copiado a ~/.local/bin/gr-locutor-config"
elif command -v cargo &>/dev/null; then
echo " No hay binario preconstruido, compilando con cargo (puede tardar 1-2 min)..."
(cd "$SCRIPT_DIR" && cargo build --release)
cp "$BIN_PREBUILT" "$HOME/.local/bin/gr-locutor-config"
echo " Compilado e instalado en ~/.local/bin/gr-locutor-config"
else
echo " AVISO: no hay binario preconstruido ni cargo/rust instalado — se omite"
echo " la interfaz gráfica. Los scripts y el motor de voz igual funcionan"
echo " (por ejemplo desde el monitor). Instalar Rust o conseguir el binario"
echo " preconstruido para tener la interfaz."
fi
chmod +x "$HOME/.local/bin/gr-locutor-config" 2>/dev/null || true
paso_fin
# ── 10. Icono / lanzador de escritorio ────────────────────────────────────────
paso "Creando lanzador de escritorio..."
DESKTOP_DIR="$HOME/.local/share/applications"
mkdir -p "$DESKTOP_DIR"
cat > "$DESKTOP_DIR/gr-locutor-config.desktop" << DESKTOPFILE
[Desktop Entry]
Type=Application
Name=Locutor IA - GRP
Comment=Configuración del Locutor Automático IA de G Radio Player
Exec=$HOME/.local/bin/gr-locutor-config
Terminal=false
Categories=AudioVideo;
DESKTOPFILE
echo " Lanzador creado — buscar 'Locutor IA - GRP' en el menú de aplicaciones."
paso_fin
echo ""
echo "======================================================"
echo " Instalación completa (total: ${SECONDS}s)"
echo "======================================================"
echo " Datos y scripts: $DATA_DIR"
echo " Voz de referencia: $REF_VOICE"
echo " Interfaz gráfica: gr-locutor-config (buscala en el menú, o ~/.local/bin/gr-locutor-config)"
echo " Generar una locución de prueba:"
echo " $VENV_DIR/gr-locutor.sh \"Estás escuchando la mejor música.\""
echo " Iniciar el monitor (mantiene 3 locuciones listas en la cola):"
echo " $DATA_DIR/scripts/start-monitor.sh start"
echo ""
Executable
+159
View File
@@ -0,0 +1,159 @@
#!/bin/bash
# package-deb.sh — Empaqueta gr-locutor (Locutor IA - GRP) como .deb instalable
# Uso: ./package-deb.sh <versión>
#
# El .deb NO requiere cargo/rust en destino: incluye el binario ya compilado
# (target/release/gr-locutor-config). Sirve para Debian 12 y 13 amd64 por
# igual (glibc retrocompatible — ver notas en el README/CLAUDE.md).
#
# El .deb NO instala el motor de voz (PyTorch/XTTS-v2, varios GB, requiere
# detectar GPU en destino) — eso lo hace `gr-locutor-instalar-motor` como
# paso separado, después de instalar el .deb. El .deb solo deja el binario,
# los scripts/contexto/voz genérica, y el lanzador de escritorio.
set -e
VERSION="${1:?Uso: $0 <version> ej: $0 0.1.0}"
ARCH="$(dpkg --print-architecture)"
PKG_NAME="gr-locutor"
PKG_DIR="${PKG_NAME}_${VERSION}_${ARCH}"
ROOT="$(cd "$(dirname "$0")" && pwd)"
BIN="$ROOT/target/release/gr-locutor-config"
if [ ! -f "$BIN" ]; then
echo "[!] Binario faltante: target/release/gr-locutor-config"
echo " Ejecuta primero: cargo build --release"
exit 1
fi
echo "========================================"
echo " Empaquetando $PKG_NAME $VERSION ($ARCH)"
echo "========================================"
# ── Limpiar directorio anterior ───────────────────────────────────────────────
rm -rf "$PKG_DIR"
# ── Estructura de directorios ─────────────────────────────────────────────────
mkdir -p "$PKG_DIR/DEBIAN"
mkdir -p "$PKG_DIR/usr/local/bin"
mkdir -p "$PKG_DIR/usr/local/share/gr-locutor/locutor-ia"
mkdir -p "$PKG_DIR/usr/share/applications"
# ── Binario principal (ya compilado — no hace falta cargo en destino) ────────
echo "[*] Copiando binario gr-locutor-config..."
cp "$BIN" "$PKG_DIR/usr/local/bin/gr-locutor-config"
chmod 755 "$PKG_DIR/usr/local/bin/gr-locutor-config"
# ── Instalador del motor de voz (paso manual post-instalación) ───────────────
echo "[*] Copiando instalador del motor de voz..."
cp "$ROOT/instalar-locutor-amd64.sh" "$PKG_DIR/usr/local/bin/gr-locutor-instalar-motor"
chmod 755 "$PKG_DIR/usr/local/bin/gr-locutor-instalar-motor"
# ── Assets estáticos (scripts, contexto para opencode, voz genérica) ────────
echo "[*] Copiando scripts/contexto/voz genérica..."
ASSETS_SRC="$ROOT/assets/locutor-ia"
cp -r "$ASSETS_SRC/"* "$PKG_DIR/usr/local/share/gr-locutor/locutor-ia/"
find "$PKG_DIR/usr/local/share/gr-locutor/locutor-ia" -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
find "$PKG_DIR/usr/local/share/gr-locutor/locutor-ia" \( -name "*.sh" -o -name "*.py" \) -exec chmod 755 {} +
# ── Lanzador de escritorio ────────────────────────────────────────────────────
cat > "$PKG_DIR/usr/share/applications/gr-locutor-config.desktop" << DESKTOP
[Desktop Entry]
Type=Application
Name=Locutor IA - GRP
Comment=Configuración del Locutor Automático IA de G Radio Player
Exec=/usr/local/bin/gr-locutor-config
Terminal=false
Categories=AudioVideo;
DESKTOP
# ── DEBIAN/control ────────────────────────────────────────────────────────────
echo "[*] Generando DEBIAN/control..."
INSTALLED_SIZE=$(du -sk "$PKG_DIR/usr" | cut -f1)
cat > "$PKG_DIR/DEBIAN/control" << CONTROL
Package: gr-locutor
Version: ${VERSION}
Architecture: ${ARCH}
Maintainer: G Radio <gradio@example.com>
Installed-Size: ${INSTALLED_SIZE}
Depends: libgtk-4-1 (>= 4.6), libc6 (>= 2.17), python3, python3-venv, ffmpeg,
gradio-player (>= 0.4.11)
Recommends: pulseaudio-utils | pipewire-pulse
Section: sound
Priority: optional
Description: Locutor IA - GRP — locuciones de radio con voz IA local
Interfaz de configuración del Locutor Automático IA de G Radio Player:
genera locuciones (presentación de temas, datos curiosos, identificación
de la radio) con síntesis de voz local (XTTS-v2), sin depender de APIs
de voz en la nube.
.
Este paquete instala la interfaz gráfica y los scripts/contexto; el motor
de voz (PyTorch + XTTS-v2, con o sin GPU) se instala aparte corriendo
'gr-locutor-instalar-motor' una vez, ya que requiere detectar el hardware
del equipo de destino y descargar varios GB.
CONTROL
# ── DEBIAN/postinst ───────────────────────────────────────────────────────────
cat > "$PKG_DIR/DEBIAN/postinst" << 'POSTINST'
#!/bin/bash
set -e
if command -v update-desktop-database &>/dev/null; then
update-desktop-database /usr/share/applications 2>/dev/null || true
fi
echo ""
echo "Locutor IA - GRP instalado correctamente."
echo "Buscar 'Locutor IA - GRP' en el menú, o ejecutar: gr-locutor-config"
echo ""
echo "Antes de generar locuciones hace falta instalar el motor de voz"
echo "(una sola vez, detecta GPU/CPU automáticamente):"
echo " gr-locutor-instalar-motor"
POSTINST
chmod 755 "$PKG_DIR/DEBIAN/postinst"
# ── DEBIAN/prerm ──────────────────────────────────────────────────────────────
# No matamos procesos acá. Lección de radio-player (ver REPARAR-DPKG.md):
# un prerm con pkill puede matarse a sí mismo y a dpkg si el patrón de
# nombre matchea la línea de comando de dpkg/el propio script. Linux
# mantiene el binario anterior abierto mientras el proceso corra, así que
# reemplazar el archivo en disco durante un upgrade es seguro sin matar nada.
cat > "$PKG_DIR/DEBIAN/prerm" << 'PRERM'
#!/bin/bash
exit 0
PRERM
chmod 755 "$PKG_DIR/DEBIAN/prerm"
# ── DEBIAN/postrm ─────────────────────────────────────────────────────────────
# Solo borrar en remove/purge — nunca en upgrade/failed-upgrade (dpkg ya
# instaló los archivos nuevos antes de correr el postrm del paquete viejo).
cat > "$PKG_DIR/DEBIAN/postrm" << 'POSTRM'
#!/bin/bash
case "$1" in
remove|purge)
rm -f /usr/local/bin/gr-locutor-config
rm -f /usr/local/bin/gr-locutor-instalar-motor
rm -rf /usr/local/share/gr-locutor
rm -f /usr/share/applications/gr-locutor-config.desktop
command -v update-desktop-database &>/dev/null && \
update-desktop-database /usr/share/applications 2>/dev/null || true
;;
esac
POSTRM
chmod 755 "$PKG_DIR/DEBIAN/postrm"
# ── Construir el .deb ─────────────────────────────────────────────────────────
echo "[*] Construyendo paquete .deb..."
dpkg-deb --build --root-owner-group "$PKG_DIR"
DEB_FILE="${PKG_DIR}.deb"
SIZE=$(du -sh "$DEB_FILE" | cut -f1)
echo ""
echo "========================================"
echo " Paquete listo: $DEB_FILE ($SIZE)"
echo "========================================"
echo ""
echo " Instalar: sudo dpkg -i $DEB_FILE"
echo " Después: gr-locutor-instalar-motor (instala el motor de voz)"
echo " Desinstalar: sudo apt remove gr-locutor"
+673
View File
@@ -0,0 +1,673 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Locutor IA - GRP — interfaz de configuración del Locutor Automático IA
//! de G Radio Player. Lee la bandera `tmp/locutor_auto` (se activa desde
//! Configuración en GRP) y expone los parámetros operativos del locutor.
use gtk4::prelude::*;
use gtk4::{
Application, ApplicationWindow, Box as GtkBox, Button, CssProvider, Label, Orientation,
STYLE_PROVIDER_PRIORITY_APPLICATION, glib,
};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
const APP_ID: &str = "org.gradioplayer.LocutorConfig";
/// Misma paleta que radio-player (fondo negro, acentos verde/púrpura/dorado)
/// para que esta app se sienta parte del mismo sistema, no una herramienta aparte.
const APP_CSS: &str = r#"
window {
background-color: #1c1c1c;
color: #e0e0e0;
}
.locutor-title {
color: #cc88ff;
font-size: 22px;
font-weight: bold;
}
.config-label {
color: #e0c040;
font-weight: bold;
font-size: 12px;
}
.status-label {
color: #aaaaaa;
font-size: 13px;
font-style: italic;
}
.status-ok {
color: #00e676;
font-weight: bold;
}
.status-warn {
color: #ffb300;
font-weight: bold;
}
.status-error {
color: #ff5252;
font-weight: bold;
}
.control-btn {
background-color: #e8edf3;
color: #0d1b3e;
border-radius: 6px;
border: 2px solid #1a3a6b;
padding: 4px 10px;
font-size: 12px;
font-weight: bold;
}
.control-btn:hover {
background-color: #1a3a6b;
color: #e8edf3;
}
.locutor-guardar {
background-color: #00aa55;
color: #ffffff;
border-radius: 6px;
border: 2px solid #007a3d;
padding: 4px 14px;
font-size: 12px;
font-weight: bold;
}
.locutor-guardar:hover {
background-color: #00c866;
}
separator {
background-color: #3a3a3a;
min-height: 1px;
}
/* ── Botón de encendido/apagado del monitor: verde brillante corriendo, ── */
/* ── opaco/gris cuando está detenido — mismo botón, cambia de clase ──────── */
.monitor-on {
background-color: #00e676;
color: #003318;
border-radius: 8px;
border: 2px solid #00c866;
padding: 8px 16px;
font-size: 14px;
font-weight: bold;
}
.monitor-on:hover {
background-color: #33ff9c;
}
.monitor-off {
background-color: #3a4a42;
color: #9fb8ac;
border-radius: 8px;
border: 2px solid #4a5a52;
padding: 8px 16px;
font-size: 14px;
font-weight: bold;
}
.monitor-off:hover {
background-color: #4a5a52;
}
"#;
fn home_dir() -> PathBuf {
dirs::home_dir().expect("no se pudo determinar HOME")
}
fn data_dir() -> PathBuf {
home_dir().join(".gradio/data/locutor-ia")
}
fn config_path() -> PathBuf {
data_dir().join("locutor.config")
}
fn locutor_auto_path() -> PathBuf {
home_dir().join(".gradio/data/tmp/locutor_auto")
}
fn gradio_config_path() -> PathBuf {
home_dir().join(".gradio/data/tmp/gradio.config")
}
fn engine_bin() -> PathBuf {
home_dir().join(".gradio/locutor-venv/gr-locutor.sh")
}
fn default_voice_path() -> PathBuf {
data_dir().join("referencia/voz_referencia.wav")
}
/// Ubicación del sistema donde el .deb instala los assets estáticos
/// (scripts, contexto, agentes, voz genérica) — de solo lectura, plantilla.
fn assets_sistema_dir() -> PathBuf {
PathBuf::from("/usr/local/share/gr-locutor/locutor-ia")
}
fn copiar_dir_recursivo(origen: &Path, destino: &Path) -> std::io::Result<()> {
fs::create_dir_all(destino)?;
for entry in fs::read_dir(origen)? {
let entry = entry?;
let dest_path = destino.join(entry.file_name());
if entry.file_type()?.is_dir() {
copiar_dir_recursivo(&entry.path(), &dest_path)?;
} else {
fs::copy(entry.path(), &dest_path)?;
}
}
Ok(())
}
/// Si es la primera vez que corre esta app en esta cuenta de usuario, copia
/// los scripts/contexto/voz genérica desde la ubicación de sistema (instalada
/// por el .deb) a `~/.gradio/data/locutor-ia/` — mismo patrón que usa GRP
/// para el contexto de opencode (`gradio.sh` copia en cada arranque, solo si
/// falta). No hace nada si ya existe (no pisa una configuración/voz propia).
fn asegurar_assets_instalados() {
let marcador = data_dir().join("AGENTS.md");
if marcador.is_file() {
return;
}
let origen = assets_sistema_dir();
if !origen.is_dir() {
return; // instalación manual (no via .deb): nada que copiar
}
if let Err(e) = copiar_dir_recursivo(&origen, &data_dir()) {
eprintln!("No se pudieron instalar los assets de Locutor IA: {e}");
}
let _ = fs::create_dir_all(salida_dir());
}
fn start_monitor_script() -> PathBuf {
data_dir().join("scripts/start-monitor.sh")
}
fn monitor_pid_path() -> PathBuf {
home_dir().join(".gradio/data/tmp/pids/locuciones-monitor.pid")
}
/// Corre igual que `start-monitor.sh status`: lee el pidfile y verifica que
/// el proceso siga vivo (Linux: existencia de /proc/{pid}).
fn monitor_corriendo() -> bool {
let pid = match fs::read_to_string(monitor_pid_path()) {
Ok(s) => s.trim().to_string(),
Err(_) => return false,
};
if pid.is_empty() {
return false;
}
Path::new(&format!("/proc/{}", pid)).is_dir()
}
// ── Configuración operativa del Locutor (locutor.config, formato clave=valor) ──
#[derive(Clone)]
struct LocutorConfig {
voz_propia: bool,
voz_propia_path: String,
cada_cuantos_temas: u32,
ventana_previas: u32,
porcentaje_identificacion: u32,
}
impl Default for LocutorConfig {
fn default() -> Self {
Self {
voz_propia: false,
voz_propia_path: String::new(),
cada_cuantos_temas: 3,
ventana_previas: 3,
porcentaje_identificacion: 50,
}
}
}
fn read_locutor_config() -> LocutorConfig {
let mut cfg = LocutorConfig::default();
let text = match fs::read_to_string(config_path()) {
Ok(t) => t,
Err(_) => return cfg,
};
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((clave, valor)) = line.split_once('=') {
let clave = clave.trim();
let valor = valor.trim();
match clave {
"voz_modo" => cfg.voz_propia = valor == "propia",
"voz_propia_path" => cfg.voz_propia_path = valor.to_string(),
"cada_cuantos_temas" => cfg.cada_cuantos_temas = valor.parse().unwrap_or(3).max(1),
"ventana_previas" => cfg.ventana_previas = valor.parse().unwrap_or(3).max(1),
"porcentaje_identificacion" => {
cfg.porcentaje_identificacion = valor.parse::<u32>().unwrap_or(50).min(100)
}
_ => {}
}
}
}
cfg
}
fn write_locutor_config(cfg: &LocutorConfig) -> std::io::Result<()> {
fs::create_dir_all(data_dir())?;
let text = format!(
"# Configuración del Locutor Automático IA — generado por gr-locutor-config\n\
voz_modo={}\n\
voz_propia_path={}\n\
cada_cuantos_temas={}\n\
ventana_previas={}\n\
porcentaje_identificacion={}\n",
if cfg.voz_propia { "propia" } else { "generica" },
cfg.voz_propia_path,
cfg.cada_cuantos_temas,
cfg.ventana_previas,
cfg.porcentaje_identificacion,
);
fs::write(config_path(), text)
}
fn locutor_habilitado() -> bool {
fs::read_to_string(locutor_auto_path())
.map(|s| s.trim() == "1")
.unwrap_or(false)
}
fn motor_instalado() -> bool {
engine_bin().is_file()
}
/// Agrega `carpeta` a la línea 19 (fundido_exclude) de gradio.config, sin
/// tocar el resto del archivo. Es la misma lista que usa "Carpetas que no
/// se funden" en Configuración de GRP — el problema de manejo de fondos
/// (locuciones cortadas por el crossfade) ya está resuelto ahí, no hace
/// falta reinventar nada acá, solo registrar la carpeta de salida.
fn registrar_carpeta_sin_fundido(carpeta: &str) -> std::io::Result<bool> {
let path = gradio_config_path();
let text = fs::read_to_string(&path).unwrap_or_default();
let mut lines: Vec<String> = text.lines().map(|s| s.to_string()).collect();
while lines.len() < 19 {
lines.push(String::new());
}
let actual = lines[18].clone();
if actual.contains(carpeta) {
return Ok(false); // ya estaba registrada
}
lines[18] = if actual.trim().is_empty() {
format!("\"{}\"", carpeta)
} else {
format!("{};\"{}\"", actual, carpeta)
};
fs::write(&path, lines.join("\n") + "\n")?;
Ok(true)
}
fn salida_dir() -> PathBuf {
data_dir().join("salida")
}
/// Actualiza el label de estado con el color correcto (ok/warn/error),
/// quitando la clase anterior para no acumular estilos.
fn set_estado(label: &Label, texto: &str, clase: &str) {
for c in ["status-ok", "status-warn", "status-error"] {
label.remove_css_class(c);
}
label.add_css_class(clase);
label.set_text(texto);
}
fn main() -> glib::ExitCode {
let app = Application::builder().application_id(APP_ID).build();
app.connect_startup(|_| {
let provider = CssProvider::new();
provider.load_from_data(APP_CSS);
gtk4::style_context_add_provider_for_display(
&gtk4::gdk::Display::default().expect("no hay display por defecto"),
&provider,
STYLE_PROVIDER_PRIORITY_APPLICATION,
);
});
app.connect_activate(build_ui);
app.run()
}
fn build_ui(app: &Application) {
asegurar_assets_instalados();
let window = ApplicationWindow::builder()
.application(app)
.title("Locutor IA - GRP")
.default_width(520)
.default_height(560)
.build();
let root = GtkBox::new(Orientation::Vertical, 12);
root.set_margin_top(20);
root.set_margin_bottom(20);
root.set_margin_start(24);
root.set_margin_end(24);
let titulo_row = GtkBox::new(Orientation::Horizontal, 8);
let titulo = Label::new(Some("🎙 Locutor IA - GRP"));
titulo.add_css_class("locutor-title");
titulo.set_halign(gtk4::Align::Start);
titulo.set_hexpand(true);
let version_lbl = Label::new(Some(&format!("v{}", env!("CARGO_PKG_VERSION"))));
version_lbl.add_css_class("status-label");
version_lbl.set_halign(gtk4::Align::End);
version_lbl.set_valign(gtk4::Align::End);
titulo_row.append(&titulo);
titulo_row.append(&version_lbl);
root.append(&titulo_row);
let subtitulo = Label::new(Some("El locutor oficial de G Radio Player"));
subtitulo.add_css_class("status-label");
subtitulo.set_halign(gtk4::Align::Start);
root.append(&subtitulo);
// ── Banner de estado ───────────────────────────────────────────────────
let habilitado = locutor_habilitado();
let banner = Label::new(Some(if habilitado {
"✅ Locutor Automático habilitado en GRP"
} else {
"⚠ Deshabilitado — actívalo en GRP → Configuración → Locutor Automático"
}));
banner.add_css_class(if habilitado { "status-ok" } else { "status-warn" });
banner.set_halign(gtk4::Align::Start);
banner.set_margin_top(8);
banner.set_margin_bottom(8);
root.append(&banner);
let motor_ok = motor_instalado();
let motor_lbl = Label::new(Some(if motor_ok {
"✅ Motor de voz instalado"
} else {
"❌ Motor de voz no instalado — ejecutar gr-locutor-instalar-motor primero"
}));
motor_lbl.add_css_class(if motor_ok { "status-ok" } else { "status-error" });
motor_lbl.set_halign(gtk4::Align::Start);
root.append(&motor_lbl);
// ── Botón de encendido/apagado del monitor ──────────────────────────────
let monitor_row = GtkBox::new(Orientation::Horizontal, 12);
monitor_row.set_margin_top(10);
monitor_row.set_margin_bottom(4);
let btn_monitor = Button::new();
fn actualizar_boton_monitor(btn: &Button, corriendo: bool) {
for c in ["monitor-on", "monitor-off"] {
btn.remove_css_class(c);
}
if corriendo {
btn.set_label("🟢 Locutor al aire — clic para detener");
btn.add_css_class("monitor-on");
} else {
btn.set_label("⚫ Locutor detenido — clic para iniciar");
btn.add_css_class("monitor-off");
}
}
actualizar_boton_monitor(&btn_monitor, monitor_corriendo());
monitor_row.append(&btn_monitor);
root.append(&monitor_row);
{
let btn_c = btn_monitor.clone();
btn_monitor.connect_clicked(move |_| {
let corriendo = monitor_corriendo();
let accion = if corriendo { "stop" } else { "start" };
let _ = Command::new("bash").arg(start_monitor_script()).arg(accion).output();
// Dar un instante a que el pidfile se actualice antes de refrescar.
std::thread::sleep(std::time::Duration::from_millis(300));
actualizar_boton_monitor(&btn_c, monitor_corriendo());
});
}
// Refresco periódico: si el monitor se inicia/detiene desde otro lado
// (terminal, watchdog), el botón lo refleja igual sin tener que reabrir la app.
{
let btn_c = btn_monitor.clone();
glib::timeout_add_local(std::time::Duration::from_secs(3), move || {
actualizar_boton_monitor(&btn_c, monitor_corriendo());
glib::ControlFlow::Continue
});
}
let sep1 = gtk4::Separator::new(Orientation::Horizontal);
sep1.set_margin_top(8);
sep1.set_margin_bottom(8);
root.append(&sep1);
let cfg = read_locutor_config();
let grid = gtk4::Grid::new();
grid.set_row_spacing(10);
grid.set_column_spacing(12);
// ── Fila 0: voz de referencia ──────────────────────────────────────────
let lbl_voz = Label::new(Some("Voz de referencia:"));
lbl_voz.add_css_class("config-label");
lbl_voz.set_halign(gtk4::Align::End);
grid.attach(&lbl_voz, 0, 0, 1, 1);
let voz_box = GtkBox::new(Orientation::Vertical, 4);
let radio_generica = gtk4::CheckButton::with_label("Voz genérica de GRP");
let radio_propia = gtk4::CheckButton::with_label("Voz propia de la estación (elegir archivo)");
radio_propia.set_group(Some(&radio_generica));
if cfg.voz_propia {
radio_propia.set_active(true);
} else {
radio_generica.set_active(true);
}
let ruta_actual = if cfg.voz_propia && !cfg.voz_propia_path.is_empty() {
cfg.voz_propia_path.clone()
} else {
default_voice_path().to_string_lossy().to_string()
};
let lbl_ruta = Label::new(Some(&ruta_actual));
lbl_ruta.add_css_class("dim-label");
lbl_ruta.set_halign(gtk4::Align::Start);
lbl_ruta.set_ellipsize(gtk4::pango::EllipsizeMode::Middle);
let btn_elegir = Button::with_label("Elegir archivo de voz…");
btn_elegir.add_css_class("control-btn");
btn_elegir.set_halign(gtk4::Align::Start);
voz_box.append(&radio_generica);
voz_box.append(&radio_propia);
voz_box.append(&btn_elegir);
voz_box.append(&lbl_ruta);
grid.attach(&voz_box, 1, 0, 1, 1);
{
let win = window.clone();
let lbl_ruta_c = lbl_ruta.clone();
let radio_propia_c = radio_propia.clone();
btn_elegir.connect_clicked(move |_| {
let fc = gtk4::FileChooserDialog::new(
Some("Elegir WAV de referencia (15-30s, voz limpia)"),
Some(&win),
gtk4::FileChooserAction::Open,
&[("Cancelar", gtk4::ResponseType::Cancel),
("Elegir", gtk4::ResponseType::Accept)],
);
fc.set_modal(true);
let filter = gtk4::FileFilter::new();
filter.set_name(Some("Audio WAV"));
filter.add_pattern("*.wav");
fc.add_filter(&filter);
let lbl_ruta_c2 = lbl_ruta_c.clone();
let radio_propia_c2 = radio_propia_c.clone();
fc.connect_response(move |fc, resp| {
if resp == gtk4::ResponseType::Accept {
if let Some(file) = fc.file() {
if let Some(path) = file.path() {
lbl_ruta_c2.set_text(&path.to_string_lossy());
radio_propia_c2.set_active(true);
}
}
}
fc.close();
});
fc.present();
});
}
// ── Fila 1: cada cuántos temas ─────────────────────────────────────────
let lbl_cada = Label::new(Some("Locutar cada:"));
lbl_cada.add_css_class("config-label");
lbl_cada.set_halign(gtk4::Align::End);
grid.attach(&lbl_cada, 0, 1, 1, 1);
let spin_cada = gtk4::SpinButton::with_range(1.0, 50.0, 1.0);
spin_cada.set_value(cfg.cada_cuantos_temas as f64);
let cada_box = GtkBox::new(Orientation::Horizontal, 8);
cada_box.append(&spin_cada);
cada_box.append(&Label::new(Some("temas")));
grid.attach(&cada_box, 1, 1, 1, 1);
// ── Fila 2: locuciones por adelantado ──────────────────────────────────
let lbl_ventana = Label::new(Some("Locuciones generadas\npor adelantado:"));
lbl_ventana.add_css_class("config-label");
lbl_ventana.set_halign(gtk4::Align::End);
lbl_ventana.set_justify(gtk4::Justification::Right);
grid.attach(&lbl_ventana, 0, 2, 1, 1);
let spin_ventana = gtk4::SpinButton::with_range(1.0, 10.0, 1.0);
spin_ventana.set_value(cfg.ventana_previas as f64);
grid.attach(&spin_ventana, 1, 2, 1, 1);
// ── Fila 3: porcentaje de identificación ───────────────────────────────
let lbl_pct = Label::new(Some("Identificación\nde la radio:"));
lbl_pct.add_css_class("config-label");
lbl_pct.set_halign(gtk4::Align::End);
lbl_pct.set_justify(gtk4::Justification::Right);
grid.attach(&lbl_pct, 0, 3, 1, 1);
let spin_pct = gtk4::SpinButton::with_range(0.0, 100.0, 5.0);
spin_pct.set_value(cfg.porcentaje_identificacion as f64);
let pct_box = GtkBox::new(Orientation::Horizontal, 8);
pct_box.append(&spin_pct);
pct_box.append(&Label::new(Some("% de las locuciones cierran identificando la radio")));
grid.attach(&pct_box, 1, 3, 1, 1);
root.append(&grid);
// ── Estado de la última acción ──────────────────────────────────────────
let estado_lbl = Label::new(None);
estado_lbl.add_css_class("status-label");
estado_lbl.set_halign(gtk4::Align::Start);
estado_lbl.set_wrap(true);
estado_lbl.set_margin_top(12);
root.append(&estado_lbl);
// ── Botones ──────────────────────────────────────────────────────────────
let btn_box = GtkBox::new(Orientation::Horizontal, 8);
btn_box.set_margin_top(8);
btn_box.set_halign(gtk4::Align::End);
let btn_prueba = Button::with_label("🔊 Generar prueba");
btn_prueba.add_css_class("control-btn");
let btn_guardar = Button::with_label("💾 Guardar");
btn_guardar.add_css_class("locutor-guardar");
btn_box.append(&btn_prueba);
btn_box.append(&btn_guardar);
root.append(&btn_box);
// ── Guardar ──────────────────────────────────────────────────────────────
{
let radio_propia_c = radio_propia.clone();
let lbl_ruta_c = lbl_ruta.clone();
let spin_cada_c = spin_cada.clone();
let spin_ventana_c = spin_ventana.clone();
let spin_pct_c = spin_pct.clone();
let estado_c = estado_lbl.clone();
btn_guardar.connect_clicked(move |_| {
let nuevo_cfg = LocutorConfig {
voz_propia: radio_propia_c.is_active(),
voz_propia_path: lbl_ruta_c.text().to_string(),
cada_cuantos_temas: spin_cada_c.value() as u32,
ventana_previas: spin_ventana_c.value() as u32,
porcentaje_identificacion: spin_pct_c.value() as u32,
};
match write_locutor_config(&nuevo_cfg) {
Ok(()) => {
let salida = salida_dir().to_string_lossy().to_string();
let _ = fs::create_dir_all(&salida);
let msg_fundido = match registrar_carpeta_sin_fundido(&salida) {
Ok(true) => " · carpeta de salida registrada en \"Carpetas que no se funden\" de GRP",
Ok(false) => " · carpeta de salida ya estaba registrada sin fundido",
Err(_) => " · no se pudo registrar la carpeta en gradio.config (revisar permisos)",
};
set_estado(&estado_c, &format!("✅ Configuración guardada{}", msg_fundido), "status-ok");
}
Err(e) => set_estado(&estado_c, &format!("❌ Error guardando: {}", e), "status-error"),
}
});
}
// ── Generar prueba ───────────────────────────────────────────────────────
{
let estado_c = estado_lbl.clone();
let radio_propia_c = radio_propia.clone();
let lbl_ruta_c = lbl_ruta.clone();
btn_prueba.connect_clicked(move |_| {
if !motor_instalado() {
set_estado(&estado_c, "❌ El motor de voz no está instalado todavía.", "status-error");
return;
}
let voz = if radio_propia_c.is_active() {
lbl_ruta_c.text().to_string()
} else {
default_voice_path().to_string_lossy().to_string()
};
if !Path::new(&voz).is_file() {
set_estado(&estado_c, &format!("❌ No existe el archivo de voz: {}", voz), "status-error");
return;
}
set_estado(&estado_c, "⏳ Generando locución de prueba (puede tardar de segundos a más de un minuto)...", "status-warn");
let (tx, rx) = async_channel::bounded::<Result<String, String>>(1);
std::thread::spawn(move || {
let result = Command::new(engine_bin())
.arg("Estás escuchando la mejor música, con el Locutor IA de G Radio Player.")
.arg("prueba_gr_locutor_config")
.env("GR_LOCUTOR_VOZ", &voz)
.output();
let msg: Result<String, String> = match result {
Ok(out) if out.status.success() => {
let ruta = String::from_utf8_lossy(&out.stdout).trim().to_string();
Ok(ruta)
}
Ok(out) => Err(String::from_utf8_lossy(&out.stderr).to_string()),
Err(e) => Err(e.to_string()),
};
let _ = tx.send_blocking(msg);
});
let estado_c2 = estado_c.clone();
glib::spawn_future_local(async move {
if let Ok(msg) = rx.recv().await {
match msg {
Ok(ruta) => {
set_estado(&estado_c2, &format!("✅ Locución generada: {}", ruta), "status-ok");
let _ = Command::new("paplay").arg(&ruta).spawn();
}
Err(e) => {
let corta: String = e.chars().take(300).collect();
set_estado(&estado_c2, &format!("❌ Error generando: {}", corta), "status-error");
}
}
}
});
});
}
window.set_child(Some(&root));
window.present();
}