import gradio as gr
import numpy as np

import numpy as np
from suno_utils.audio import Audio


from suno_utils.gpt.chirp_v2_5 import (
    generate_audio_stream,
    preload_models,
    GenerationConfig,
)

sampling_rate = 48000

gr.Info("Loading models...")

_ = preload_models(
    gpt_ckpt_path="/app/suno/checkpoints/2024-03-01_03-56-14/last_ckpt_infer.pt",  # v3 IPO
    load_whisper=False,
    load_semantic=False,
)
gr.Info("Models loaded")


def generate(
    text_prompt,
    genre=None,
    text_control_tags=None,
    neg_tags=None,
    cfg_coef=None,
    cfg_coef_tags=None,
    cfg_coef_neg_tags=None,
):
    """Gradio audio streaming has artifacts, see
    https://github.com/gradio-app/gradio/pull/5077#issuecomment-1670321414"""
    global models_loaded
    print(text_prompt, genre, cfg_coef, cfg_coef_tags)

    for audio in generate_audio_stream(
        GenerationConfig(
            text=text_prompt if text_prompt else None,
            text_tags=genre if genre else None,
            text_start_control_tags=text_control_tags if text_control_tags else None,
            text_neg_tags=neg_tags if neg_tags else None,
            n_batch=1,
            max_gen_duration_s=120,
            stream=True,
            n_stride_tokens=25 * 4,  # longer chunk since gradio clicks
            cfg_coef=cfg_coef,
            cfg_coef_tags=cfg_coef_tags,
            cfg_coef_neg_tags=cfg_coef_neg_tags,
            cfg_coef_max_steps=None,
            cfg_coef_tags_max_steps=None,
        )
    ):
        yield (sampling_rate, audio[0].array.T)
    print("done")


lyrics = [
    """
(Verse 1)
In the morning light, I wake up with a yawn,
The world's still asleep, but I'm already drawn,
To that caffeinated potion, that cup of brown delight,
It's my daily dose of magic, helps me take flight.

(Chorus)
Coffee, you're my drug, but you're not so bad,
You pick me up when I'm feeling sad,
But I know the difference, I won't be misled,
Coffee's my addiction, but drugs are bad, it's said.

(Verse 2)
I take that sip, it courses through my veins,
A boost of energy, like a runaway train,
But I'm aware, it's not a path I'll tread,
'Cause I know the dangers of those paths widespread.

(Chorus)
Coffee, you're my drug, but you're not so bad,
You pick me up when I'm feeling sad,
But I know the difference, I won't be misled,
Coffee's my addiction, but drugs are bad, it's said.

(Bridge)
Some folks seek escape in substances they crave,
But it's a risky game, it can be a dark wave,
Let's stay mindful of the choices we make,
And the lives we lead, for our future's sake.

(Verse 3)
So let's raise our mugs, in the morning sun,
Enjoy our coffee, and have some fun,
But let's remember, as we go on this ride,
There are better ways to feel alive inside.

(Chorus)
Coffee, you're my drug, but you're not so bad,
You pick me up when I'm feeling sad,
But I know the difference, I won't be misled,
Coffee's my addiction, but drugs are bad, it's said.

(Outro)
So, coffee, my friend, you'll always be near,
A boost in my morning, a friend, I hold dear,
But I won't be swayed by those paths that mislead,
Coffee's my addiction, but drugs are bad, indeed.
""",
    """
[Verse 1]
Almost Heaven, West Virginia
Blue Ridge Mountains, Shenandoah River
Life is old there, older than the trees
Younger than the mountains, growing like a breeze

[Chorus]
Country roads, take me home
To the place I belong
West Virginia, mountain mama
Take me home, country roads

[Verse 2]
All my memories gather 'round her
Miner's lady, stranger to blue water
Dark and dusty, painted on the sky
Misty taste of moonshine, teardrop in my eye

[Chorus]
Country roads, take me home
To the place I belong
West Virginia, mountain mama
Take me home, country roads

[Bridge]
I hear her voice in the morning hour, she calls me
The radio reminds me of my home far away
Driving down the road, I get a feeling
That I should have been home yesterday, yesterday
""",
    """
(Verse 1)
In the heart of New England, a legend stands tall,
A place where dreams and knowledge enthrall,
With crimson banners, and ivy-covered halls,
Harvard, the beacon, where excellence calls.

(Chorus)
Harvard, Harvard, your legacy's grand,
A symbol of learning in this noble land,
With scholars and vision, you truly command,
Harvard, Harvard, where greatness is planned.

(Verse 2)
From Harvard Yard to Widener's dome,
The pursuit of wisdom finds its home,
In Cambridge's embrace, where the brightest minds roam,
Harvard's where intellect continues to bloom.

(Chorus)
Harvard, Harvard, your legacy's grand,
A symbol of learning in this noble land,
With scholars and vision, you truly command,
Harvard, Harvard, where greatness is planned.

(Bridge)
Through centuries, you've shaped the world's way,
With innovation and progress, come what may,
From arts to science, in every display,
Harvard's the torch that lights our day.

(Verse 3)
Harvard Square bustles, as stories unfold,
In classrooms and libraries, the secrets are told,
With the promise of change, and futures untold,
Harvard's embrace, a treasure to hold.

(Chorus)
Harvard, Harvard, your legacy's grand,
A symbol of learning in this noble land,
With scholars and vision, you truly command,
Harvard, Harvard, where greatness is planned.

(Outro)
So, here's to Harvard, where knowledge ignites,
A beacon of hope and academic heights,
In the crimson and veritas, our shared delights,
Harvard, you're a guiding star in our educational nights.
""",
]

demo = gr.Interface(
    fn=generate,
    inputs=[
        gr.Textbox(label="Prompt", value=lyrics[0], lines=10),
        gr.Text(label="Tags", value="pop"),
        gr.Text(label="Control Tags", value=""),
        gr.Text(label="Negative Tags", value=""),
        gr.Slider(label="CFG Coef", minimum=-3.0, maximum=3.0, step=0.01, value=1.0),
        gr.Slider(
            label="CFG Coef Tags", minimum=-3.0, maximum=3.0, step=0.01, value=1.0
        ),
        gr.Slider(
            label="CFG Coef Neg Tags",
            minimum=-3.0,
            maximum=3.0,
            step=0.01,
            value=-2.5,
        ),
    ],
    outputs=[gr.Audio(label="Generated Music", streaming=True, autoplay=True)],
    examples=[
        [lyrics[0], "pop"],
        [lyrics[1], "rock"],
        [lyrics[2], "country"],
    ],
    title="Chirp by Suno (Streaming Beta)",
    description="Generate music from text prompts.",
    # article=article,
    allow_flagging=False,
    cache_examples=False,
)


demo.queue().launch(share=True)

demo.launch(share=True)
