Spaces:
Sleeping

Suno / app.py
Cvlmv's picture
Create app.py
1116703 verified
Raw History Blame Contribute Delete
7.62 kB
# app.py
# Para ejecutar:
# 1. Guarda como 'app.py'
# 2. Ejecuta: pip install gradio deep_translator
# 3. Ejecuta: gradio app.py
import gradio as gr
from deep_translator import GoogleTranslator
# --- FUNCIONES DE TRADUCCIÓN Y CORRECCIÓN ---
def translate_text(text, max_length=1000):
"""Traduce y trunca texto al inglés manteniendo la integridad de las palabras"""
if not text or len(text) > max_length * 3: # Evitar textos excesivamente largos
return text
try:
# Traducir preservando formato básico
translated = GoogleTranslator(source='auto', target='en').translate(text)
return translated[:max_length] if translated and len(translated) > max_length else translated
except Exception:
return text[:max_length] # Fallback seguro
def process_and_translate(text, field_type):
"""Procesa campos según su tipo con límite de caracteres"""
if not text:
return ""
# Reglas específicas por tipo de campo
if field_type == "lyrics":
# Conservar estructura de letras (versos, coros, etc.)
return translate_text(text, 2000)
else:
# Aplicar formato especial para campos de estilo
processed = text.replace(',', ' y').replace(';', ' con')
return translate_text(processed, 200)
# --- GENERADOR DE PROMPT ---
def generate_structured_prompt(
is_cover,
genre_text,
style_text,
mood_text,
singer_voice_text,
instrumentation_text,
mastering_text,
lyrics_text
):
"""Construye el prompt estructurado para Suno"""
prompt_parts = []
# Procesar cada campo con su tipo específico
fields = [
("genre", genre_text),
("style", style_text),
("mood", mood_text),
("voice", singer_voice_text),
("instrumentation", instrumentation_text),
("mastering", mastering_text)
]
for field_type, text in fields:
if text and (not is_cover or field_type in ["genre", "voice", "instrumentation", "mastering"]):
processed = process_and_translate(text, field_type)
prompt_parts.append(f"**{field_type.capitalize()}:** {processed.strip('.')}.")
# Unir secciones y truncar a 1000 caracteres
final_style_prompt = "\n\n".join(prompt_parts)
if len(final_style_prompt) > 1000:
final_style_prompt = final_style_prompt[:1000].rsplit(' ', 1)[0] + "."
# Procesar letras manteniendo estructura
processed_lyrics = process_and_translate(lyrics_text, "lyrics")
return final_style_prompt, processed_lyrics
# --- INTERFAZ DE USUARIO ---
theme = gr.themes.Soft(primary_hue="blue", secondary_hue="sky")
with gr.Blocks(theme=theme, title="Creador de Prompts Definitivo para Suno") as demo:
gr.Markdown("""
# 🚀 Creador de Prompts Definitivo para Suno v4.5
**Traducción automática a inglés · Límite 1000 caracteres · Optimizado para resultados de calidad**
""")
with gr.Tabs() as tabs:
# PESTAÑA NUEVA CANCIÓN
with gr.TabItem("🎵 Crear Nueva Canción", id=0):
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("### 🌍 Texto en español (se traduce automáticamente)")
input_genre = gr.Textbox(label="Género", placeholder="Ej: Fusión de Reggae de los 70 y Dancehall con Rock alternativo...")
input_style = gr.Textbox(label="Estilo", placeholder="Ej: Melodías pegadizas y groovy con toques dinámicos...")
input_mood = gr.Textbox(label="Ambiente", placeholder="Ej: Calmado pero alegre con toques nostálgicos...")
input_singer_voice = gr.Textbox(label="Voz del Cantante", placeholder="Ej: Voz profunda y conmovedora con tono reggae...")
input_instrumentation = gr.Textbox(label="Instrumentación", placeholder="Ej: Batería acústica realista con guitarras reverberantes...")
input_mastering = gr.Textbox(label="Masterización", placeholder="Ej: Sonido limpio con efectos estéreo profesionales...")
with gr.Column(scale=3):
gr.Markdown("### 📝 Letra en español (se traduce manteniendo estructura)")
input_lyrics_new = gr.Textbox(lines=22, label="Letra de la Canción",
placeholder="[Verso]\nLinea en español...\n\n[Coro]\nFrase en español...")
generate_button_new = gr.Button("✅ Generar Prompt para Canción Nueva", variant="primary")
# PESTAÑA COVER/REMASTER
with gr.TabItem("🎛️ Remasterizar (vía Cover)", id=1):
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("### 🌍 Texto en español (se traduce automáticamente)")
cover_input_genre = gr.Textbox(label="Género", placeholder="Ej: Kawaii Metal fusionado con Death Metal...")
cover_input_singer_voice = gr.Textbox(label="Voz del Cantante", placeholder="Ej: Voz aguda y adorable con vibra anime...")
cover_input_instrumentation = gr.Textbox(label="Instrumentación", placeholder="Ej: Batería acústica con sonido realista...")
cover_input_mastering = gr.Textbox(label="Masterización", placeholder="Ej: Sonido limpio con mastering profesional...")
gr.Textbox(label="Estilo (Omitido)", interactive=False, visible=False)
gr.Textbox(label="Ambiente (Omitido)", interactive=False, visible=False)
with gr.Column(scale=3):
gr.Markdown("### 📝 Letra original (se traduce manteniendo estructura)")
input_lyrics_cover = gr.Textbox(lines=22, label="Letra Original",
placeholder="[Verse]\nOriginal lyrics...\n\n[Chorus]\nOriginal lyrics...")
generate_button_cover = gr.Button("✅ Generar Prompt para Remasterizar", variant="primary")
# SALIDA
gr.Markdown("## 👇 Resultado Final (Traducido al inglés) 👇")
with gr.Row():
with gr.Column():
gr.Markdown("### 🎶 Style of Music (max 1000 caracteres)")
output_style_prompt = gr.Textbox(label="Copia esto en 'Style of Music':", lines=6, max_lines=6)
gr.Markdown(f"Caracteres: <span id='style-counter'>0</span>/1000", elem_id="counter-style")
with gr.Column():
gr.Markdown("### 🎤 Lyrics")
output_lyrics_prompt = gr.Textbox(label="Copia esto en 'Lyrics':", lines=6, max_lines=6)
# LÓGICA
generate_button_new.click(
fn=lambda g, s, m, v, i, mas, l: generate_structured_prompt(False, g, s, m, v, i, mas, l),
inputs=[input_genre, input_style, input_mood, input_singer_voice, input_instrumentation, input_mastering, input_lyrics_new],
outputs=[output_style_prompt, output_lyrics_prompt]
)
generate_button_cover.click(
fn=lambda g, v, i, mas, l: generate_structured_prompt(True, g, None, None, v, i, mas, l),
inputs=[cover_input_genre, cover_input_singer_voice, cover_input_instrumentation, cover_input_mastering, input_lyrics_cover],
outputs=[output_style_prompt, output_lyrics_prompt]
)
# Contador de caracteres en tiempo real
output_style_prompt.change(
fn=lambda text: f"{len(text)}/1000",
inputs=output_style_prompt,
outputs=gr.HTML(elem_id="counter-style")
)
if __name__ == "__main__":
demo.launch()