import os
import gradio as gr
from utils import (
    generate_song,
    change_tempo,
)
os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
DESCRIPTION = """
🎵 Multitrack Music Generator 🎶
"""
genres = ["ROCK", "POP", "JAZZ", "RANDOM"]
demo = gr.Blocks()
def run():
    with demo:
        gr.HTML(DESCRIPTION)
        with gr.Row():
            with gr.Column():
                temp = gr.Slider(
                    minimum=0, maximum=1, step=0.05, value=0.85, label="Temperature"
                )
                genre = gr.Dropdown(
                    choices=genres, value="POP", label="Select the genre"
                )
                with gr.Row():
                    btn_from_scratch = gr.Button("Start")
                    btn_continue = gr.Button("Generate More")
            with gr.Column():
                with gr.Group():
                    audio_output = gr.Video(show_share_button=True)
                    midi_file = gr.File()
                    with gr.Row():
                        qpm = gr.Slider(
                            minimum=60, maximum=140, step=10, value=120, label="Tempo"
                        )
                        btn_qpm = gr.Button("Change Tempo")
        with gr.Row():
            with gr.Column():
                plot_output = gr.Plot()
            with gr.Column():
                instruments_output = gr.Markdown("# List of generated instruments")
        with gr.Row():
            text_sequence = gr.Text()
            empty_sequence = gr.Text(visible=False)
        with gr.Row():
            num_tokens = gr.Text(visible=False)
        btn_from_scratch.click(
            fn=generate_song,
            inputs=[genre, temp, empty_sequence, qpm],
            outputs=[
                audio_output,
                midi_file,
                plot_output,
                instruments_output,
                text_sequence,
                num_tokens,
            ],
        )
        btn_continue.click(
            fn=generate_song,
            inputs=[genre, temp, text_sequence, qpm],
            outputs=[
                audio_output,
                midi_file,
                plot_output,
                instruments_output,
                text_sequence,
                num_tokens,
            ],
        )
        btn_qpm.click(
            fn=change_tempo,
            inputs=[text_sequence, qpm],
            outputs=[
                audio_output,
                midi_file,
                plot_output,
                instruments_output,
                text_sequence,
                num_tokens,
            ],
        )
    demo.launch(server_name="0.0.0.0", server_port=7860)
if __name__ == "__main__":
    run()