lost-frequency-radio / stations.py
MarianaCodebase's picture
Upload stations.py with huggingface_hub
fb48959 verified
Raw
History Blame Contribute Delete
18.4 kB
"""Deterministic frequency → station mapping.
Each station defines:
- system_prompt: compact persona + opening anchor (the fine-tune already knows
the style; short prompts = fast first token on CPU)
- user_prompt: the "on air" cue in the station's native language
- voice: animalese voice parameters (pitch, jitter, waveform)
- theme: visual identity (display glow color, flicker rhythm)
"""
STATION_TOLERANCE = 0.3 # MHz — within ±0.3 counts as "on station"
LOCK_TOLERANCE = 0.05 # MHz — perfect tuning
NEAR_TOLERANCE = 0.45 # MHz — beyond this: static only
USER_PROMPT_EN = "Write tonight's transmission. On-air script only."
# No verbose "rules" in the system prompt: the fine-tune already knows the
# radio format (markers, length, the [FIN DE TRANSMISION] sign-off), and a 1B
# model recites instruction-shaped text on air. We only give it the persona +
# a language cue + the opening line it should start from (that opening is the
# strongest, leak-safe steering lever — if echoed, it is correct output).
def _prompt_es(persona: str, apertura: str) -> str:
return f"{persona}\nEscribes el guion al aire en español. Empiezas con: {apertura}"
def _prompt_en(persona: str, opening: str) -> str:
return f"{persona}\nYou write the on-air script in English. You begin with: {opening}"
# Language directives: the listener picks the broadcast language.
# Short and declarative on purpose — a verbose "translate... example: [JINGLE]
# ..." block is exactly the kind of instruction-shaped text a 1B model recites
# on air. The fine-tune now covers ES/EN/FR, so one clean line is enough; the
# swapped opening + the user prompt do the heavy steering.
LANG_DIRECTIVES = {
"es": "Hablas y escribes solo en español, nunca en inglés.",
"en": "You speak and write only in English, never in Spanish. Translate every line into English.",
"fr": "Tu parles et écris uniquement en français, jamais en espagnol. Traduis chaque ligne en français.",
}
# On-air cue per language: this is the last thing the model reads, so it is
# the strongest lever to pull the generation into the requested language.
USER_PROMPTS = {
"es": "Escribe la transmisión de esta noche. Solo el guion al aire.",
"en": "Write tonight's transmission, entirely in English. On-air script only.",
"fr": "Écris la transmission de ce soir, entièrement en français. Uniquement le script à l'antenne.",
}
SUPPORTED_LANGS = tuple(LANG_DIRECTIVES.keys())
def normalize_lang(lang: str) -> str:
lang = str(lang or "es").lower()[:2]
return lang if lang in LANG_DIRECTIVES else "es"
def localized_system_prompt(base_prompt: str, native_lang: str, lang: str) -> str:
"""When the listener asks for another language, wrap the persona with the
translation directive (before and after: small models obey anchors)."""
lang = normalize_lang(lang)
if lang == native_lang:
return base_prompt
directive = LANG_DIRECTIVES[lang]
return f"{directive} {base_prompt} {directive}"
def localized_user_prompt(station: dict | None, lang: str) -> str:
"""On-air cue in the requested language (falls back to the station's own)."""
lang = normalize_lang(lang)
native = (station or {}).get("lang", "es")
if lang == native and station and station.get("user_prompt"):
return station["user_prompt"]
return USER_PROMPTS[lang]
# Same station frequency → same broadcast for every listener.
STATIONS: dict[float, dict] = {
87.6: {
"name": "Night Drive AM",
"lang": "en",
"system_prompt": _prompt_en(
persona=(
"You are the host of Night Drive AM, a late-night call-in show on an "
"empty highway between universes. Every caller tonight is, somehow, "
"the same person calling from different years of their life. Calm, "
"warm, slightly melancholic."
),
opening="[JINGLE] You're on Night Drive. Go ahead, caller.",
),
"user_prompt": USER_PROMPT_EN,
"voice": {"pitch_base": 110, "pitch_step": 4, "pitch_jitter": 12, "waveform": "sine"},
"theme": {"glow": "#ffb45e", "flicker": 0.25},
},
88.9: {
"name": "Radio Selenita — Tropical lunar",
"lang": "es",
"system_prompt": _prompt_es(
persona=(
"Eres el animador de Radio Selenita, la emisora tropical de un "
"Medellín que queda en la Luna: saludos con sabrosura paisa, cumbias, "
"cráteres, gravedad baja y vista a la Tierra."
),
apertura=(
"[JINGLE] ¡Quiubo pues, mi gente selenita! Desde el cráter de la 70 "
"les saluda su locutor de confianza."
),
),
"voice": {"pitch_base": 260, "pitch_step": 8, "pitch_jitter": 30, "waveform": "triangle"},
"theme": {"glow": "#7cfc9a", "flicker": 0.5},
},
91.7: {
"name": "WFifty — Locutor de los 50",
"lang": "es",
"system_prompt": _prompt_es(
persona=(
"Eres Don Aurelio, locutor estrella de una radio AM de los años 50 en "
"un universo paralelo. Narras EN VIVO, con voz cálida y melodramática, "
"la final municipal de ajedrez entre los gatos Bartolo y Misifú."
),
apertura=(
"[JINGLE] Buenas noches, queridos oyentes. Les habla Don Aurelio "
"desde el salón municipal."
),
),
"voice": {"pitch_base": 145, "pitch_step": 5, "pitch_jitter": 18, "waveform": "sawtooth"},
"theme": {"glow": "#ffd27c", "flicker": 0.35},
},
94.1: {
"name": "The Midnight Archive",
"lang": "en",
"system_prompt": _prompt_en(
persona=(
"You are the announcer of The Midnight Archive, a BBC-style service "
"that reads catalogue entries for objects lost between universes "
"(umbrellas that remember rain, keys to doors never built). Measured, "
"elegant, faintly haunted."
),
opening="[JINGLE] This is The Midnight Archive.",
),
"user_prompt": USER_PROMPT_EN,
"voice": {"pitch_base": 170, "pitch_step": 5, "pitch_jitter": 10, "waveform": "sine"},
"theme": {"glow": "#9ad8ff", "flicker": 0.2},
},
97.3: {
"name": "Júpiter FM — Boletín meteorológico",
"lang": "es",
"system_prompt": _prompt_es(
persona=(
"Eres la voz oficial del Servicio Meteorológico de Júpiter, año 2187: "
"tormentas de amoniaco, vientos de 900 km/h, la Gran Mancha Roja de "
"mal humor. Tono serio, casi poético."
),
apertura="[JINGLE] Servicio Meteorológico de Júpiter, parte de las 19 horas.",
),
"voice": {"pitch_base": 340, "pitch_step": 7, "pitch_jitter": 28, "waveform": "square"},
"theme": {"glow": "#ff8a5e", "flicker": 0.4},
},
99.9: {
"name": "La Hora Exacta",
"lang": "es",
"system_prompt": _prompt_es(
persona=(
"Eres la voz automática de La Hora Exacta, la estación que da la hora "
"en un universo donde el tiempo se rompió. Anuncias horas imposibles "
"con seriedad burocrática, como un reloj parlante averiado."
),
apertura="[JINGLE] Al tercer tono serán las veinticinco horas del martes pasado. ...Piiip.",
),
"voice": {"pitch_base": 420, "pitch_step": 3, "pitch_jitter": 6, "waveform": "square"},
"theme": {"glow": "#c6ff5e", "flicker": 0.15},
},
101.3: {
"name": "Deep Sea Lounge",
"lang": "en",
"system_prompt": _prompt_en(
persona=(
"You are the smooth-jazz DJ of Deep Sea Lounge, broadcasting from a "
"glass studio at the bottom of an ocean on a gas planet. Velvet voice, "
"unhurried, dedicating songs to creatures drifting past the window."
),
opening="[JINGLE] Mmm, welcome back to the Deep Sea Lounge.",
),
"user_prompt": USER_PROMPT_EN,
"voice": {"pitch_base": 95, "pitch_step": 4, "pitch_jitter": 14, "waveform": "sine"},
"theme": {"glow": "#6ec8ff", "flicker": 0.18},
},
103.5: {
"name": "Nube 103 — Comercial interdimensional",
"lang": "es",
"system_prompt": _prompt_es(
persona=(
"Eres el locutor publicitario de Nube 103, en un universo donde las "
"nubes se alquilan por hora. Vendes el plan 'Cumulonimbus Premium' "
"(sombra garantizada, llovizna opcional, truenos de cortesía) con "
"entusiasmo desbordado, estilo años 60."
),
apertura="[JINGLE] ¡Amigos! ¿Cansados de cielos vacíos?",
),
"voice": {"pitch_base": 230, "pitch_step": 6, "pitch_jitter": 22, "waveform": "square"},
"theme": {"glow": "#ffe97c", "flicker": 0.45},
},
106.1: {
"name": "Cocina Imposible",
"lang": "es",
"system_prompt": _prompt_es(
persona=(
"Eres la chef de Cocina Imposible: explicas paso a paso, con cariño "
"de abuela, recetas de ingredientes que no existen (sopa de ecos, pan "
"de sombra, mermelada de domingos)."
),
apertura="[JINGLE] Bienvenidos, mis amores, a Cocina Imposible.",
),
"voice": {"pitch_base": 290, "pitch_step": 6, "pitch_jitter": 24, "waveform": "triangle"},
"theme": {"glow": "#ffb0d8", "flicker": 0.3},
},
}
STATION_FREQUENCIES = sorted(STATIONS.keys())
# ------------------------------------------------------------------
# Special frequencies (app.py routes them before regular stations)
# ------------------------------------------------------------------
CURSED_FREQUENCY = 95.5 # the unsolvable station: it always arrives corrupted
CURSED_SYSTEM_PROMPT = (
"Eres una voz que transmite desde un lugar que ya no existe. Hablas en español, "
"en fragmentos inconexos y bellos: mitades de frases, nombres de personas que "
"nadie recuerda, coordenadas de sitios que no aparecen en los mapas, despedidas "
"sin destinatario. Nunca explicas nada. Nunca completas la idea. "
"Entre 50 y 80 palabras. Cierra con [FIN DE TRANSMISION]."
)
CURSED_VOICE = {"pitch_base": 80, "pitch_step": 3, "pitch_jitter": 40, "waveform": "sine"}
CURSED_THEME = {"glow": "#b9a4ff", "flicker": 0.8}
ENCRYPTED_VOICE = {"pitch_base": 600, "pitch_step": 0, "pitch_jitter": 0, "waveform": "sine"}
ENCRYPTED_THEME = {"glow": "#58ff8f", "flicker": 0.6}
def station_seed(frequency: float) -> int:
"""Deterministic per-frequency seed: same frequency → same broadcast."""
return int(round(frequency * 10)) * 7919 % (2**31 - 1)
def nearest_station_frequency(frequency: float) -> float | None:
"""Canonical frequency of the nearest station, if within range."""
if not STATION_FREQUENCIES:
return None
nearest = min(STATION_FREQUENCIES, key=lambda f: abs(frequency - f))
if abs(frequency - nearest) > STATION_TOLERANCE:
return None
return nearest
def get_station(frequency: float) -> dict | None:
"""Returns the station when the frequency is within ±STATION_TOLERANCE."""
nearest = nearest_station_frequency(frequency)
if nearest is None:
return None
return STATIONS[nearest]
def signal_strength(frequency: float) -> float:
"""0 = no signal, 1 = perfect tuning (relative to the nearest station)."""
nearest = nearest_station_frequency(frequency)
if nearest is None:
# Very weak signal when a station is close but outside tuning tolerance
if not STATION_FREQUENCIES:
return 0.0
nearest_any = min(STATION_FREQUENCIES, key=lambda f: abs(frequency - f))
dist = abs(frequency - nearest_any)
if dist >= NEAR_TOLERANCE:
return 0.0
return max(0.0, 0.15 * (1 - dist / NEAR_TOLERANCE))
dist = abs(frequency - nearest)
if dist <= LOCK_TOLERANCE:
return 1.0
return max(0.0, 1.0 - (dist - LOCK_TOLERANCE) / (NEAR_TOLERANCE - LOCK_TOLERANCE))
# Opening lines per language. The opening is the strongest language anchor a
# 1B model has: swapping it pulls the whole broadcast into the target language.
STATION_OPENINGS = {
87.6: {
"en": "[JINGLE] You're on Night Drive. Go ahead, caller.",
"es": "[JINGLE] Estás en Night Drive. Adelante, oyente.",
"fr": "[JINGLE] Vous êtes sur Night Drive. Allez-y, on vous écoute.",
},
88.9: {
"es": "[JINGLE] ¡Quiubo pues, mi gente selenita! Desde el cráter de la 70 les saluda su locutor de confianza.",
"en": "[JINGLE] What's up, my lunar people! Greeting you from Crater 70, it's your trusted host.",
"fr": "[JINGLE] Salut la famille sélénite ! Depuis le cratère de la 70, votre animateur préféré vous salue.",
},
91.7: {
"es": "[JINGLE] Buenas noches, queridos oyentes. Les habla Don Aurelio desde el salón municipal.",
"en": "[JINGLE] Good evening, dear listeners. This is Don Aurelio, live from the municipal hall.",
"fr": "[JINGLE] Bonsoir, chers auditeurs. Ici Don Aurelio, en direct de la salle municipale.",
},
94.1: {
"en": "[JINGLE] This is The Midnight Archive.",
"es": "[JINGLE] Esto es El Archivo de Medianoche.",
"fr": "[JINGLE] Ici Les Archives de Minuit.",
},
97.3: {
"es": "[JINGLE] Servicio Meteorológico de Júpiter, parte de las 19 horas.",
"en": "[JINGLE] Jupiter Weather Service, 7 p.m. bulletin.",
"fr": "[JINGLE] Service météorologique de Jupiter, bulletin de 19 heures.",
},
99.9: {
"es": "[JINGLE] Al tercer tono serán las veinticinco horas del martes pasado. ...Piiip.",
"en": "[JINGLE] At the third tone, the time will be twenty-five o'clock last Tuesday. ...Beep.",
"fr": "[JINGLE] Au troisième bip, il sera vingt-cinq heures mardi dernier. ...Biiip.",
},
101.3: {
"en": "[JINGLE] Mmm, welcome back to the Deep Sea Lounge.",
"es": "[JINGLE] Mmm, bienvenidos de nuevo al Deep Sea Lounge.",
"fr": "[JINGLE] Mmm, bienvenue au Deep Sea Lounge.",
},
103.5: {
"es": "[JINGLE] ¡Amigos! ¿Cansados de cielos vacíos?",
"en": "[JINGLE] Friends! Tired of empty skies?",
"fr": "[JINGLE] Chers amis ! Fatigués des ciels vides ?",
},
106.1: {
"es": "[JINGLE] Bienvenidos, mis amores, a Cocina Imposible.",
"en": "[JINGLE] Welcome, my darlings, to Impossible Kitchen.",
"fr": "[JINGLE] Bienvenue, mes chéris, dans Cuisine Impossible.",
},
}
def station_system_prompt(canonical: float, lang: str) -> str:
"""Persona prompt with the opening swapped into the requested language."""
station = STATIONS[canonical]
base = station["system_prompt"]
native = station.get("lang", "es")
lang = normalize_lang(lang)
openings = STATION_OPENINGS.get(canonical, {})
if lang != native and openings.get(native) and openings.get(lang):
base = base.replace(openings[native], openings[lang])
return localized_system_prompt(base, native, lang)
# Station names per UI language (brand names stay, descriptors translate).
STATION_NAMES = {
87.6: {"es": "Night Drive AM", "en": "Night Drive AM", "fr": "Night Drive AM"},
88.9: {
"es": "Radio Selenita — Tropical lunar",
"en": "Radio Selenita — Lunar Tropical",
"fr": "Radio Sélénite — Tropicale lunaire",
},
91.7: {
"es": "WFifty — Locutor de los 50",
"en": "WFifty — 1950s Announcer",
"fr": "WFifty — Speaker des années 50",
},
94.1: {
"es": "The Midnight Archive",
"en": "The Midnight Archive",
"fr": "The Midnight Archive",
},
97.3: {
"es": "Júpiter FM — Boletín meteorológico",
"en": "Jupiter FM — Weather Bulletin",
"fr": "Jupiter FM — Bulletin météo",
},
99.9: {"es": "La Hora Exacta", "en": "The Exact Hour", "fr": "L'Heure Exacte"},
101.3: {"es": "Deep Sea Lounge", "en": "Deep Sea Lounge", "fr": "Deep Sea Lounge"},
103.5: {
"es": "Nube 103 — Comercial interdimensional",
"en": "Cloud 103 — Interdimensional Commercials",
"fr": "Nuage 103 — Pub interdimensionnelle",
},
106.1: {"es": "Cocina Imposible", "en": "Impossible Kitchen", "fr": "Cuisine Impossible"},
}
# CRT portrait of each frequency's announcer (served from /static/img).
PORTRAITS = {
87.6: "/static/img/st_876.webp",
88.9: "/static/img/st_889.webp",
91.7: "/static/img/st_917.webp",
94.1: "/static/img/st_941.webp",
97.3: "/static/img/st_973.webp",
99.9: "/static/img/st_999.webp",
101.3: "/static/img/st_1013.webp",
103.5: "/static/img/st_1035.webp",
106.1: "/static/img/st_1061.webp",
}
def station_catalog() -> dict:
"""Public station metadata (voice, name, visual theme) for the frontend."""
from decrypt import ENCRYPTED_FREQUENCY
catalog = {
str(freq): {
"name": data["name"],
"names": STATION_NAMES.get(freq, {"es": data["name"]}),
"lang": data.get("lang", "es"),
"voice": data["voice"],
"theme": data.get("theme", {"glow": "#7cfc00", "flicker": 0.3}),
"portrait": PORTRAITS.get(freq),
}
for freq, data in STATIONS.items()
}
catalog[str(ENCRYPTED_FREQUENCY)] = {
"name": "· – · · –",
"names": {"es": "· – · · –", "en": "· – · · –", "fr": "· – · · –"},
"lang": "es",
"voice": ENCRYPTED_VOICE,
"theme": ENCRYPTED_THEME,
"portrait": "/static/img/st_1047.webp",
"encrypted": True,
}
catalog[str(CURSED_FREQUENCY)] = {
"name": "· · · ?",
"names": {"es": "· · · ?", "en": "· · · ?", "fr": "· · · ?"},
"lang": "es",
"voice": CURSED_VOICE,
"theme": CURSED_THEME,
"portrait": "/static/img/st_955.webp",
"cursed": True,
}
return catalog