system_voice_service.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """
  2. 系统音色服务
  3. 提供系统预置音色的查询功能,支持按模型和场景分类筛选
  4. 所有系统音色数据均从数据库获取,不包含任何硬编码
  5. 需求: 4.1, 4.2, 4.3, 4.4
  6. """
  7. import logging
  8. from typing import List, Optional
  9. from sqlalchemy.orm import Session
  10. from app.models.audio import SystemVoice
  11. from app.schemas.audio_schema import SystemVoiceResponse, SystemVoiceFeatures
  12. logger = logging.getLogger(__name__)
  13. class SystemVoiceService:
  14. """
  15. 系统音色服务类
  16. 所有系统音色数据均从数据库 system_voice 表获取,不包含任何硬编码。
  17. 系统音色数据通过初始化脚本 scripts/init_system_voices.py 初始化到数据库。
  18. """
  19. def __init__(self, db: Session):
  20. """
  21. 初始化系统音色服务
  22. Args:
  23. db: 数据库会话
  24. """
  25. self.db = db
  26. def get_system_voices(
  27. self,
  28. model: Optional[str] = None,
  29. category: Optional[str] = None
  30. ) -> List[SystemVoiceResponse]:
  31. """
  32. 获取系统音色列表
  33. 从数据库 system_voice 表查询所有启用的系统音色,支持按模型和场景分类筛选。
  34. 所有数据均从数据库获取,不包含任何硬编码。
  35. Args:
  36. model: 按模型筛选,返回支持该模型的音色(如:cosyvoice-v3-flash、cosyvoice-v3-plus)
  37. category: 按场景分类筛选,返回该分类下的音色(如:社交陪伴、客服、新闻播报等)
  38. Returns:
  39. 系统音色响应列表
  40. 需求:
  41. 4.1 - 返回所有启用的系统音色
  42. 4.2 - 按模型筛选
  43. 4.3 - 按场景分类筛选
  44. 4.4 - 返回完整的音色信息
  45. """
  46. # 从数据库查询:只查询启用的音色
  47. query = self.db.query(SystemVoice).filter(SystemVoice.is_active == True)
  48. # 按模型筛选:检查models JSONB数组是否包含指定模型
  49. if model:
  50. # PostgreSQL JSONB数组包含查询
  51. query = query.filter(SystemVoice.models.contains([model]))
  52. # 按场景分类筛选
  53. if category:
  54. query = query.filter(SystemVoice.category == category)
  55. # 执行数据库查询
  56. voices = query.all()
  57. # 将数据库记录转换为响应对象
  58. result = []
  59. for voice in voices:
  60. # 构建功能特性对象
  61. features = SystemVoiceFeatures(
  62. ssml=voice.ssml_support or False,
  63. instruct=voice.instruct_support or False,
  64. timestamp=voice.timestamp_support or False
  65. )
  66. # 构建响应对象
  67. response = SystemVoiceResponse(
  68. voice_id=voice.voice_id,
  69. name=voice.name,
  70. trait=voice.trait or "",
  71. age=voice.age or "",
  72. category=voice.category or "",
  73. languages=voice.languages or [],
  74. models=voice.models or [],
  75. features=features
  76. )
  77. result.append(response)
  78. logger.debug(
  79. f"从数据库查询系统音色: model={model}, category={category}, "
  80. f"返回{len(result)}条记录"
  81. )
  82. return result