base.py 21.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
# -*- coding: utf-8 -*-
"""
音乐分析器抽象基类
定义统一的分析器接口
"""

from abc import ABC, abstractmethod
from typing import Dict, Optional, Any, List, Set


# 字典定义:所有有效的字段值
VALID_GENRES: Set[str] = {
    "流行",
    "电子/舞曲",
    "摇滚/金属",
    "说唱",
    "民谣/原声",
    "国风",
    "爵士/Soul",
    "古典",
    "轻音乐/Ambient",
    "二次元/ACG",
    "其它",
}

VALID_SUB_GENRES: Dict[str, Set[str]] = {
    "流行": {"华语流行", "欧美流行", "日韩流行", "R&B", "抒情"},
    "电子/舞曲": {"House", "Future Bass", "Dubstep", "Synthwave", "Trance", "Techno"},
    "摇滚/金属": {"流行摇滚", "独立摇滚", "重金属", "朋克", "后摇"},
    "说唱": {"Trap", "Old School", "Boombap", "Melodic Rap", "中文说唱"},
    "民谣/原声": {"城市民谣", "校园民谣", "故事民谣", "乡村", "Indie Folk"},
    "国风": {"古风", "戏腔", "新中式", "水墨风", "国潮"},
    "爵士/Soul": {"传统爵士", "Smooth Jazz", "Fusion", "Neo-Soul", "Blues"},
    "古典": {"管弦乐", "钢琴曲", "协奏曲", "室内乐", "歌剧"},
    "轻音乐/Ambient": {"钢琴独奏", "Lo-fi", "冥想音乐", "氛围电子", "白噪音"},
    "二次元/ACG": {"动画OST", "Vocaloid", "游戏音乐", "萌系", "燃系"},
    "其它": {"世界音乐", "实验音乐", "儿歌", "戏曲", "网络热歌"},
}

VALID_LANGUAGES: Set[str] = {
    "普通话",
    "粤语",
    "英语",
    "韩语",
    "闽南语",
    "蒙语",
    "俄语",
    "藏语",
    "其他",
}

LANGUAGE_MAPPING: Dict[str, str] = {
    "国语": "普通话",
    "中文": "普通话",
    "汉语": "普通话",
    "普通话": "普通话",
    "广东话": "粤语",
    "粤语": "粤语",
    "英文": "英语",
    "英语": "英语",
    "韩文": "韩语",
    "朝鲜语": "韩语",
    "韩语": "韩语",
    "闽南话": "闽南语",
    "台语": "闽南语",
    "闽南语": "闽南语",
    "蒙语": "蒙语",
    "蒙古语": "蒙语",
    "俄文": "俄语",
    "俄语": "俄语",
    "藏文": "藏语",
    "藏语": "藏语",
    "其它": "其他",
    "其他": "其他",
    "地方语言": "其他",
    "日语": "其他",
}

VALID_EMOTIONS: Set[str] = {
    "喜庆",
    "浪漫",
    "雄壮",
    "庄重",
    "激情",
    "快乐",
    "励志",
    "期待",
    "甜蜜",
    "感动",
    "搞笑",
    "祝福",
    "温暖",
    "宣泄",
    "悲壮",
    "愤怒",
    "沉重",
    "思念",
    "紧张",
    "恐怖",
    "孤独",
    "伤感",
    "忧郁",
    "蛊惑",
    "恶搞",
    "怀念",
    "悬疑",
    "佛系",
    "舒缓",
    "悠扬",
}

VALID_SCENES: Set[str] = {
    "餐厅",
    "汽车",
    "跳舞",
    "旅行",
    "工作",
    "校园",
    "夜店",
    "运动",
    "休闲",
    "live house",
    "广场舞",
    "抖音",
    "婚礼",
    "约会",
}

VALID_DOUYIN_TAGS: Set[str] = {
    "草原",
    "故乡",
    "神曲",
    "文艺",
    "青春",
    "治愈系",
    "清新",
    "奇幻",
}

VALID_MUSIC_STYLE_TAGS: Set[str] = {
    "世界音乐",
    "雷鬼",
    "R&B/Soul",
    "MC喊麦",
    "另类音乐",
    "民歌",
    "戏曲",
    "古风",
    "古典音乐",
    "HipHop",
    "Rap",
    "摇滚",
    "DJ嗨曲",
    "布鲁斯/蓝调",
    "拉丁",
    "舞曲",
    "爵士",
    "乡村",
    "民谣",
    "流行",
    "轻音乐",
    "国风",
    "儿歌",
}

VALID_INSTRUMENT_TAGS: Set[str] = {
    "二胡",
    "竹笛",
    "琵琶",
    "音效",
    "口琴",
    "电子",
    "木吉他",
    "鼓组",
    "弦乐",
    "电吉他",
    "古筝",
    "钢琴",
}

VALID_AGES: Set[str] = {"少年", "青年", "中年", "老年", "全年龄段"}

VALID_RHYTHM_INTENSITIES: Set[str] = {"极慢", "慢", "中", "快", "极速"}

VALID_EMOTIONAL_INTENSITIES: Set[str] = {"平缓", "中等", "强烈"}

VALID_VOICE_TYPES: Set[str] = {"男声", "女声", "童声", "合唱", "无人声"}
VALID_PERFORMER_TYPES: Set[str] = {"男声", "女声", "童声", "合唱"}

# sub_genre 常见变体映射
SUB_GENRE_MAPPING: Dict[str, str] = {
    "韩语流行": "日韩流行",
    "韩国流行": "日韩流行",
    "K-Pop": "日韩流行",
    "K-pop": "日韩流行",
    "Kpop": "日韩流行",
    "韩流": "日韩流行",
    "日语流行": "日韩流行",
    "日本流行": "日韩流行",
    "J-Pop": "日韩流行",
    "J-pop": "日韩流行",
    "Jpop": "日韩流行",
    "中文流行": "华语流行",
    "国语流行": "华语流行",
    "中国流行": "华语流行",
    "英语流行": "欧美流行",
    "英文流行": "欧美流行",
    "西方流行": "欧美流行",
    "Pop": "欧美流行",
}


class AudioAnalyzer(ABC):
    """音乐音频分析器抽象基类"""

    @abstractmethod
    def get_provider_name(self) -> str:
        """获取提供商名称(如 qwen, doubao)"""
        pass

    @abstractmethod
    def get_model_name(self) -> str:
        """获取模型名称"""
        pass

    @abstractmethod
    def analyze(
        self,
        metadata: Dict[str, Any],
        music_url: str,
        extract_lyrics: bool = False,
        label_level: int = 0,
    ) -> Optional[Dict[str, Any]]:
        """
        分析音乐并返回标签结果

        Args:
            metadata: 音乐元数据字典
            music_url: 音乐文件 URL(支持音频 URL 或 Base64 编码)
            extract_lyrics: 是否识别歌词
            label_level: 标签级别(0: 一级标签, 1: 一级+二级标签)

        Returns:
            标准化分析结果字典,包含以下字段:
            - genre: 音乐风格(一级风格,如:流行、摇滚)
            - emotion: 情绪列表
            - emotional_intensity: 情绪强度
            - vocal_texture: 人声质感
            - vocal_description: 人声质感描述
            - visual_concept: 视觉概念
            - language: 语种
            - bpm: 节拍数(可选)
            - lyrics: 歌词列表(可选,仅当 extract_lyrics=True 时)
            - _model: 使用的模型名称
            - _token_info: Token 使用信息
        """
        pass

    def _parse_response(self, response_text: str) -> Optional[Dict[str, Any]]:
        """
        解析 LLM 返回的响应文本为 JSON

        Args:
            response_text: LLM 返回的原始文本

        Returns:
            解析后的字典,解析失败返回 None
        """
        import re
        import json
        import logging

        logger = logging.getLogger(__name__)

        if not response_text:
            return None

        # 打印原始响应用于调试
        logger.info(f"[_parse_response] 原始响应文本:\n{response_text[:500]}...")

        cleaned_text = response_text.strip()

        # 移除 markdown 代码块标记
        if cleaned_text.startswith("```json"):
            cleaned_text = cleaned_text[7:]
        elif cleaned_text.startswith("```"):
            cleaned_text = cleaned_text[3:]

        if cleaned_text.endswith("```"):
            cleaned_text = cleaned_text[:-3]

        cleaned_text = cleaned_text.strip()

        # 提取 JSON 对象
        try:
            # 尝试直接解析
            result = json.loads(cleaned_text)
            if isinstance(result, dict):
                logger.info(f"[_parse_response] 解析成功,字段: {list(result.keys())}")
            elif isinstance(result, list):
                logger.info(f"[_parse_response] 解析成功,列表长度: {len(result)}")
            else:
                logger.info(
                    f"[_parse_response] 解析成功,类型: {type(result).__name__}"
                )
            return result
        except json.JSONDecodeError:
            pass

        # 尝试提取 {...} 中的内容
        try:
            match = re.search(r"\{.*\}", cleaned_text, re.DOTALL)
            if match:
                json_str = match.group()
                result = json.loads(json_str)
                if isinstance(result, dict):
                    logger.info(
                        f"[_parse_response] 正则提取解析成功,字段: {list(result.keys())}"
                    )
                elif isinstance(result, list):
                    logger.info(
                        f"[_parse_response] 正则提取解析成功,列表长度: {len(result)}"
                    )
                else:
                    logger.info(
                        "[_parse_response] 正则提取解析成功,类型: %s",
                        type(result).__name__,
                    )
                return result
        except (re.error, json.JSONDecodeError):
            pass

        # 尝试修复常见的 JSON 格式问题
        try:
            fixed_text = re.sub(r",(\s*})", r"\1", cleaned_text)
            fixed_text = re.sub(r",(\s*])", r"\1", fixed_text)
            result = json.loads(fixed_text)
            if isinstance(result, dict):
                logger.info(
                    f"[_parse_response] 修复后解析成功,字段: {list(result.keys())}"
                )
            elif isinstance(result, list):
                logger.info(
                    f"[_parse_response] 修复后解析成功,列表长度: {len(result)}"
                )
            else:
                logger.info(
                    "[_parse_response] 修复后解析成功,类型: %s",
                    type(result).__name__,
                )
            return result
        except (re.error, json.JSONDecodeError):
            pass

        logger.warning(f"[_parse_response] 所有解析方法都失败")
        return None

    def _normalize_result(
        self,
        raw_result: Dict[str, Any],
        model_name: str,
        token_info: Optional[Dict[str, int]] = None,
    ) -> Dict[str, Any]:
        """
        标准化分析结果

        Args:
            raw_result: 原始解析结果
            model_name: 使用的模型名称
            token_info: Token 使用信息

        Returns:
            标准化后的结果字典
        """
        import logging

        logger = logging.getLogger(__name__)

        if not isinstance(raw_result, dict):
            if (
                isinstance(raw_result, list)
                and raw_result
                and isinstance(raw_result[0], dict)
            ):
                raw_result = raw_result[0]
            else:
                logger.warning(
                    f"[_normalize_result] 原始结果类型异常: {type(raw_result).__name__}"
                )
                return {"_model": model_name, "_raw": raw_result}

        logger.info(f"[_normalize_result] 原始结果字段: {list(raw_result.keys())}")
        logger.info(f"[_normalize_result] genre: {raw_result.get('genre')}")
        logger.info(f"[_normalize_result] emotion: {raw_result.get('emotion')}")
        logger.info(f"[_normalize_result] scene: {raw_result.get('scene')}")
        logger.info(f"[_normalize_result] token_info 参数: {token_info}")

        def _extract_style(raw_style) -> Optional[Dict[str, str]]:
            """提取音乐风格为标准格式"""
            if isinstance(raw_style, dict):
                return {"zh": raw_style.get("zh", ""), "en": raw_style.get("en", "")}
            elif isinstance(raw_style, str):
                # 字符串格式,直接使用作为中文名,英文名留空
                return {"zh": raw_style, "en": ""}
            return None

        def _extract_list_field(raw_value) -> list:
            """提取列表字段"""
            if isinstance(raw_value, list):
                return [v for v in raw_value if v]
            elif isinstance(raw_value, str):
                import re

                return [
                    v.strip()
                    for v in re.split(r"[,,、/|]+", raw_value)
                    if v and v.strip()
                ]
            return []

        def _extract_single_field(raw_value) -> str:
            """提取单值字段"""
            if raw_value and isinstance(raw_value, str):
                return raw_value
            return ""

        def _validate_and_map_sub_genre(sub_genre: str, genre: str) -> str:
            """验证并映射 sub_genre 到有效值"""
            if not sub_genre:
                return ""

            sub_genre = sub_genre.strip()

            if sub_genre in SUB_GENRE_MAPPING:
                mapped = SUB_GENRE_MAPPING[sub_genre]
                logger.info(
                    f"[_validate_and_map_sub_genre] 映射 '{sub_genre}' -> '{mapped}'"
                )
                return mapped

            if genre in VALID_SUB_GENRES:
                if sub_genre in VALID_SUB_GENRES[genre]:
                    return sub_genre

            for valid_subs in VALID_SUB_GENRES.values():
                if sub_genre in valid_subs:
                    return sub_genre

            logger.warning(
                f"[_validate_and_map_sub_genre] 无法映射 sub_genre: '{sub_genre}' (genre: '{genre}')"
            )
            return sub_genre

        def _validate_list_field(
            values: List[str], valid_set: Set[str], field_name: str
        ) -> List[str]:
            """严格验证列表字段中的值:仅保留字典内标签"""
            result = []
            for v in values:
                if v in valid_set:
                    result.append(v)
                else:
                    logger.warning(
                        f"[_validate_list_field] {field_name} 值 '{v}' 不在字典中,已过滤"
                    )
            return result

        def _validate_language(raw_value: Any) -> str:
            language = _extract_single_field(raw_value).strip()
            if not language:
                return ""
            mapped = LANGUAGE_MAPPING.get(language, language)
            if mapped in VALID_LANGUAGES:
                return mapped
            logger.warning(
                f"[_normalize_result] language '{language}' 不在字典中,已归并为空"
            )
            return ""

        result = {
            "genre": "",
            "sub_genre": "",
            "emotion": [],
            "voice_type": "",
            "vocal_texture": "",
            "vocal_description": "",
            "visual_concept": "",
            "language": "",
            "scene": [],
            "age": "",
            "is_sinking": None,
            "song_description": "",
            "performer_type": "",
            "music_style_tags": [],
            "douyin_tags": [],
            "instrument_tags": [],
        }

        # 音乐风格(一级风格和二级风格)
        # 优先使用新格式 genre/sub_genre,兼容旧格式 music_style
        raw_genre = raw_result.get("genre", "")
        raw_sub_genre = raw_result.get("sub_genre", "")
        raw_music_style = raw_result.get("music_style", [])

        # 优先从 genre 字段获取一级风格
        if isinstance(raw_genre, str) and raw_genre.strip():
            result["genre"] = raw_genre.strip()
        elif isinstance(raw_genre, dict):
            result["genre"] = raw_genre.get("zh", "") or raw_genre.get("en", "")
        # 兼容旧格式:从 music_style 数组提取
        elif (
            raw_music_style
            and isinstance(raw_music_style, list)
            and len(raw_music_style) > 0
        ):
            first_style = raw_music_style[0]
            if isinstance(first_style, dict):
                result["genre"] = first_style.get("zh", "") or first_style.get("en", "")
            elif isinstance(first_style, str):
                result["genre"] = first_style.strip()

        # 优先从 sub_genre 字段获取二级风格
        if isinstance(raw_sub_genre, str) and raw_sub_genre.strip():
            result["sub_genre"] = raw_sub_genre.strip()
        elif isinstance(raw_sub_genre, dict):
            result["sub_genre"] = raw_sub_genre.get("zh", "") or raw_sub_genre.get(
                "en", ""
            )
        # 兼容旧格式:从 music_style 数组第二个元素提取
        elif (
            raw_music_style
            and isinstance(raw_music_style, list)
            and len(raw_music_style) > 1
        ):
            second_style = raw_music_style[1]
            if isinstance(second_style, dict):
                result["sub_genre"] = second_style.get("zh", "") or second_style.get(
                    "en", ""
                )
            elif isinstance(second_style, str):
                result["sub_genre"] = second_style.strip()

        result["sub_genre"] = _validate_and_map_sub_genre(
            result["sub_genre"], result["genre"]
        )

        # 情绪
        raw_emotion = raw_result.get("emotion", [])
        if isinstance(raw_emotion, str):
            raw_emotion = [raw_emotion]
        result["emotion"] = _validate_list_field(
            _extract_list_field(raw_emotion), VALID_EMOTIONS, "emotion"
        )

        # 人声类型
        raw_voice_type = raw_result.get("voice_type", "")
        if raw_voice_type and isinstance(raw_voice_type, str):
            voice_type = raw_voice_type.strip()
            if voice_type in VALID_VOICE_TYPES:
                result["voice_type"] = voice_type
            else:
                logger.warning(
                    f"[_normalize_result] voice_type '{voice_type}' 不在有效值中,保留原值"
                )
                result["voice_type"] = voice_type
        else:
            result["voice_type"] = ""

        # 人声质感 (LLM返回的是vocal_type)
        result["vocal_texture"] = _extract_single_field(
            raw_result.get("vocal_type", "")
        )

        # 人声质感描述
        result["vocal_description"] = raw_result.get("vocal_description", "")

        # 聚音演唱者类型(优先 performer_type,回退 vocal_type)
        raw_performer_type = raw_result.get("performer_type", raw_result.get("vocal_type", ""))
        if isinstance(raw_performer_type, str):
            performer_type = raw_performer_type.strip()
            if performer_type in VALID_PERFORMER_TYPES:
                result["performer_type"] = performer_type
            elif performer_type in VALID_VOICE_TYPES:
                result["performer_type"] = performer_type

        # 聚音标签:音乐风格/网络抖音/配器
        result["music_style_tags"] = _extract_list_field(
            raw_result.get("music_style_tags", raw_result.get("music_style", []))
        )
        result["douyin_tags"] = _extract_list_field(
            raw_result.get("douyin_tags", raw_result.get("network_douyin_tags", []))
        )
        result["instrument_tags"] = _extract_list_field(
            raw_result.get("instrument_tags", raw_result.get("instruments", []))
        )
        result["music_style_tags"] = _validate_list_field(
            result["music_style_tags"], VALID_MUSIC_STYLE_TAGS, "music_style_tags"
        )
        result["douyin_tags"] = _validate_list_field(
            result["douyin_tags"], VALID_DOUYIN_TAGS, "douyin_tags"
        )
        result["instrument_tags"] = _validate_list_field(
            result["instrument_tags"], VALID_INSTRUMENT_TAGS, "instrument_tags"
        )

        # 视觉概念
        result["visual_concept"] = raw_result.get("visual_concept", "")

        # 语种
        result["language"] = _validate_language(raw_result.get("language", ""))

        # 场景(可多选)
        raw_scene = raw_result.get("scene", [])
        if isinstance(raw_scene, str):
            raw_scene = [raw_scene]
        if isinstance(raw_scene, list):
            scene_list = [s.strip() for s in raw_scene if s and isinstance(s, str)]
            result["scene"] = _validate_list_field(scene_list, VALID_SCENES, "scene")

        # 适合听众年龄段
        raw_age = raw_result.get("age", "")
        if raw_age and isinstance(raw_age, str):
            result["age"] = raw_age.strip()

        # 是否下沉
        raw_is_sinking = raw_result.get("is_sinking")
        if isinstance(raw_is_sinking, bool):
            result["is_sinking"] = raw_is_sinking
        elif isinstance(raw_is_sinking, str):
            is_sinking_lower = raw_is_sinking.strip().lower()
            if is_sinking_lower in ("是", "true", "1", "yes"):
                result["is_sinking"] = True
            elif is_sinking_lower in ("否", "false", "0", "no"):
                result["is_sinking"] = False

        # 歌曲描述
        raw_song_desc = raw_result.get("song_description", "")
        if raw_song_desc and isinstance(raw_song_desc, str):
            result["song_description"] = raw_song_desc.strip()

        # 情绪强度
        raw_emotional_intensity = raw_result.get("emotional_intensity", "")
        if raw_emotional_intensity and isinstance(raw_emotional_intensity, str):
            result["emotional_intensity"] = raw_emotional_intensity.strip()

        # 节奏强度
        raw_rhythm_intensity = raw_result.get("rhythm_intensity", "")
        if raw_rhythm_intensity and isinstance(raw_rhythm_intensity, str):
            result["rhythm_intensity"] = raw_rhythm_intensity.strip()

        # BPM 不从 LLM 结果中提取,统一由本地 bpm_analyzer_tools 提供

        # 歌词(可选)
        if "lyrics" in raw_result:
            result["lyrics"] = raw_result["lyrics"]

        # 添加模型信息
        result["_model"] = model_name
        if token_info:
            result["_token_info"] = token_info
        if "_token_info_parts" in raw_result and isinstance(
            raw_result["_token_info_parts"], dict
        ):
            result["_token_info_parts"] = raw_result["_token_info_parts"]
        if "_timing" in raw_result and isinstance(raw_result["_timing"], dict):
            result["_timing"] = raw_result["_timing"]

        return result