import os
import time
import gradio as gr
import numpy as np
import torch
from inference.tts.base_tts_infer import BaseTTSInfer
from utils.commons.ckpt_utils import load_ckpt
from utils.commons.hparams import hparams
from utils.text.text_encoder import build_token_encoder
from modules.TCSinger.tcsinger import SADecoder
from modules.TCSinger.sdlm import SDLM
from tasks.tts.vocoder_infer.base_vocoder import get_vocoder_cls
from utils.audio import librosa_wav2spec
from utils.commons.hparams import set_hparams
from utils.audio.io import save_wav
import json

class StyleControlApp(BaseTTSInfer):
    def build_model(self):
        dict_size = len(self.ph_encoder)
        model = SDLM(dict_size, self.hparams)
        self.model_decoder = SADecoder()
        model.eval()
        # Check if binary_data_dir is present in hparams
        binary_data_dir = hparams.get('binary_data_dir', './default_binary_data')
        if not os.path.exists(binary_data_dir):
            raise FileNotFoundError(f"[ERROR] binary_data_dir '{binary_data_dir}' not found. Please check your hparams configuration.")

        print(f"[DEBUG] Using binary_data_dir: {binary_data_dir}")


        load_ckpt(model, hparams['exp_name'], strict=False)
        load_ckpt(self.model_decoder, hparams['decoder_ckpt_dir'], strict=False)
        self.model_decoder.to(self.device)
        self.ph_encoder = build_token_encoder('./ZHEN_checkpoint_phone_set.json')
        return model

    def build_vocoder(self):
        vocoder = get_vocoder_cls(hparams["vocoder"])()
        return vocoder

    def forward_model(self, inp):
        sample = self.input_to_batch(inp)
        txt_tokens = sample['txt_tokens']
        notes, note_durs, note_types = sample["notes"], sample["note_durs"], sample['note_types']
        mel_prompt = sample['mel_prompt']

        print("[DEBUG] Forward model inputs prepared")
        
        with torch.no_grad():
            try:
                output = self.model.infer(
                    txt_tokens, None, tgt_mels=None, infer=True, mel_prompt=mel_prompt,
                    note=notes, note_dur=note_durs, note_type=note_types, control=True)
                self.model_decoder(tgt_mels=None, infer=True, ret=output, spk_embed=None)

                mel_out = output['mel_out'][0]
                pred_f0 = output.get('f0_denorm_pred')[0]
                wav_out = self.vocoder.spec2wav(mel_out.cpu(), f0=pred_f0.cpu())

                print("[DEBUG] Forward model inference successful")

            except Exception as e:
                print(f"[ERROR] Forward model error: {str(e)}")
                raise e

        return wav_out, mel_out

    def preprocess_input(self, inp):
        ph = ' '.join(inp['text_gen'])
        ph_token = self.ph_encoder.encode(ph.replace('_en', ''))
        note = inp['note_gen']
        note_dur = inp['note_dur_gen']
        note_type = inp['note_type_gen']

        print("[DEBUG] Preprocessing input")

        wav2spec_dict = librosa_wav2spec(
            inp['ref_audio'],
            fft_size=hparams['fft_size'],
            hop_size=hparams['hop_size'],
            win_length=hparams['win_size'],
            num_mels=hparams['audio_num_mel_bins'],
            fmin=hparams['fmin'],
            fmax=hparams['fmax'],
            sample_rate=hparams['audio_sample_rate'],
            loud_norm=hparams['loud_norm']
        )
        mel = np.clip(wav2spec_dict['mel'], hparams['mel_vmin'], hparams['mel_vmax'])

        print("[DEBUG] Input preprocessing completed")

        return {
            'item_name': inp['item_name'],
            'text': ph,
            'ph_token': ph_token,
            'mel': mel,
            'notes': note,
            'note_durs': note_dur,
            'note_types': note_type
        }
def infer(input_prompt, target_audio, target_json):
    print("[DEBUG] Infer function called")

    try:
        print(f"[DEBUG] target_audio: {target_audio}")
        print(f"[DEBUG] target_json: {target_json}")

        with open(target_json.name, 'r') as f:
            target_info = json.load(f)
        print("[DEBUG] Loaded target JSON metadata")

        ref_audio = target_audio
        print(f"[DEBUG] target_audio: {target_audio}")
        print(f"[DEBUG] target_info: {target_info}")
        #inp = next(item for item in target_info if ref_audio in item['wav_fn'])
        #inp['ref_audio'] = ref_audio

        print("[DEBUG] Input prepared for inference")
        hparams['binary_data_dir']="./default_binary_data"
        infer_ins = StyleControlApp(hparams)
        wav_out, _ = infer_ins.forward_model(target_info)

        timestamp = time.strftime('%Y%m%d-%H%M%S')
        output_path = f"generated/output_{timestamp}.wav"
        os.makedirs('generated', exist_ok=True)
        save_wav(wav_out, output_path, hparams['audio_sample_rate'])

        print(f"[DEBUG] Inference completed, file saved at {output_path}")

        return output_path
    except Exception as e:
        print(f"[ERROR] Infer function error: {str(e)}")
        return f"Error: {str(e)}"


def main():
    with gr.Blocks() as app:
        gr.Markdown("## Style-Control Song Generation")
        with gr.Row():
            prompt_file = gr.Audio(label="Prompt Audio File", type="filepath")
            target_audio = gr.Audio(label="Target Audio File", type="filepath")
            target_json = gr.File(label="Target JSON Metadata", type="filepath")
        generate_btn = gr.Button("Generate")
        output_audio = gr.Audio(label="Generated Audio File", type="filepath")

        generate_btn.click(
            infer,
            inputs=[prompt_file, target_audio, target_json],
            outputs=[output_audio]
        )

    app.launch(server_port=7777, root_path="/sing", auth=("singer", "SingeR"))

if __name__ == "__main__":
    main()

