import requests
import io
import librosa.core as core
import torch

class AudioLoadPath:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { "path": ("STRING", {"default": "X://insert/path/here.mp4"}),
                              "sample_rate": ("INT", {"default": 22050, "min": 6000, "max": 192000, "step": 1}),
                              "offset": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1e6, "step": 0.001}),
                              "duration": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1e6, "step": 0.001})}}

    RETURN_TYPES = ("AUDIO", )
    CATEGORY = "EasyAI"
    FUNCTION = "load"

    def load(self, path: str, sample_rate: int, offset: float, duration: float|None):
        if duration == 0.0:
            duration = None

        try:
            if path.startswith(('http://', 'https://')):
                response = requests.get(path)
                response.raise_for_status()
                audio_data = io.BytesIO(response.content)

                import warnings
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    audio, _ = core.load(audio_data, sr=sample_rate, offset=offset, duration=duration)
            else:
                audio, _ = core.load(path, sr=sample_rate, offset=offset, duration=duration)

                # 使用与参考代码相同的维度转换方式
            audio = torch.from_numpy(audio)[None,:,None]

            # 构建音频字典
            # audio_dict = {
            #     "waveform": audio,
            #     "sample_rate": sample_rate
            # }

            return (audio,)

        except Exception as e:
            raise Exception(f"加载音频失败: {str(e)}")

NODE_CLASS_MAPPINGS = {
    "AudioLoadPath": AudioLoadPath,
}