config.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Data Modules - 配置文件
  5. API 配置通过环境变量读取(支持 .env 文件):
  6. - EMBED_BASE_URL, EMBED_MODEL, EMBED_API_KEY
  7. - RERANK_BASE_URL, RERANK_MODEL, RERANK_API_KEY
  8. """
  9. import os
  10. from pathlib import Path
  11. from dataclasses import dataclass, field
  12. from typing import Optional
  13. # 加载 .env 文件
  14. def _load_dotenv():
  15. """从项目根目录加载 .env 文件"""
  16. # 尝试多个可能的位置
  17. possible_paths = [
  18. Path.cwd() / ".env",
  19. Path(__file__).parent.parent.parent.parent / ".env", # .claude/scripts/data_modules -> 项目根目录
  20. ]
  21. for env_path in possible_paths:
  22. if env_path.exists():
  23. with open(env_path, "r", encoding="utf-8") as f:
  24. for line in f:
  25. line = line.strip()
  26. if line and not line.startswith("#") and "=" in line:
  27. key, _, value = line.partition("=")
  28. key = key.strip()
  29. value = value.strip()
  30. # 只在环境变量未设置时才从 .env 加载
  31. if key and key not in os.environ:
  32. os.environ[key] = value
  33. break
  34. _load_dotenv()
  35. @dataclass
  36. class DataModulesConfig:
  37. """数据模块配置"""
  38. # ================= 项目路径 =================
  39. project_root: Path = field(default_factory=lambda: Path.cwd())
  40. @property
  41. def webnovel_dir(self) -> Path:
  42. return self.project_root / ".webnovel"
  43. @property
  44. def state_file(self) -> Path:
  45. return self.webnovel_dir / "state.json"
  46. @property
  47. def index_db(self) -> Path:
  48. return self.webnovel_dir / "index.db"
  49. @property
  50. def alias_index_file(self) -> Path:
  51. return self.webnovel_dir / "alias_index.json"
  52. @property
  53. def chapters_dir(self) -> Path:
  54. return self.project_root / "正文"
  55. @property
  56. def settings_dir(self) -> Path:
  57. return self.project_root / "设定集"
  58. @property
  59. def outline_dir(self) -> Path:
  60. return self.project_root / "大纲"
  61. # ================= Embedding API 配置 =================
  62. embed_api_type: str = "openai"
  63. embed_base_url: str = field(default_factory=lambda: os.getenv("EMBED_BASE_URL", "https://api-inference.modelscope.cn/v1"))
  64. embed_model: str = field(default_factory=lambda: os.getenv("EMBED_MODEL", "Qwen/Qwen3-Embedding-8B"))
  65. embed_api_key: str = field(default_factory=lambda: os.getenv("EMBED_API_KEY", ""))
  66. @property
  67. def embed_url(self) -> str:
  68. return self.embed_base_url
  69. # ================= Rerank API 配置 =================
  70. rerank_api_type: str = "openai"
  71. rerank_base_url: str = field(default_factory=lambda: os.getenv("RERANK_BASE_URL", "https://api.jina.ai/v1"))
  72. rerank_model: str = field(default_factory=lambda: os.getenv("RERANK_MODEL", "jina-reranker-v3"))
  73. rerank_api_key: str = field(default_factory=lambda: os.getenv("RERANK_API_KEY", ""))
  74. @property
  75. def rerank_url(self) -> str:
  76. return self.rerank_base_url
  77. # ================= 并发配置 =================
  78. embed_concurrency: int = 64
  79. rerank_concurrency: int = 32
  80. embed_batch_size: int = 64
  81. # ================= 超时配置 =================
  82. cold_start_timeout: int = 300
  83. normal_timeout: int = 180
  84. # ================= 重试配置 =================
  85. api_max_retries: int = 3 # 最大重试次数
  86. api_retry_delay: float = 1.0 # 初始重试延迟(秒),使用指数退避
  87. # ================= 检索配置 =================
  88. vector_top_k: int = 30
  89. bm25_top_k: int = 20
  90. rerank_top_n: int = 10
  91. rrf_k: int = 60
  92. vector_full_scan_max_vectors: int = 500
  93. vector_prefilter_bm25_candidates: int = 200
  94. vector_prefilter_recent_candidates: int = 200
  95. # ================= 实体提取配置 =================
  96. extraction_confidence_high: float = 0.8
  97. extraction_confidence_medium: float = 0.5
  98. # ================= 列表截断限制 =================
  99. max_disambiguation_warnings: int = 500
  100. max_disambiguation_pending: int = 1000
  101. max_state_changes: int = 2000
  102. context_recent_summaries_window: int = 5
  103. context_alerts_slice: int = 10
  104. context_max_appearing_characters: int = 10
  105. context_max_urgent_foreshadowing: int = 5
  106. export_recent_changes_slice: int = 20
  107. export_disambiguation_slice: int = 20
  108. # ================= 查询默认限制 =================
  109. query_recent_chapters_limit: int = 10
  110. query_scenes_by_location_limit: int = 20
  111. query_entity_appearances_limit: int = 50
  112. query_recent_appearances_limit: int = 20
  113. # ================= 伏笔紧急度 =================
  114. foreshadowing_urgency_pending_high: int = 100
  115. foreshadowing_urgency_pending_medium: int = 50
  116. foreshadowing_urgency_target_proximity: int = 5
  117. foreshadowing_urgency_score_high: int = 100
  118. foreshadowing_urgency_score_medium: int = 60
  119. foreshadowing_urgency_score_target: int = 80
  120. foreshadowing_urgency_score_low: int = 20
  121. foreshadowing_urgency_threshold_show: int = 60
  122. foreshadowing_tier_weight_core: float = 3.0
  123. foreshadowing_tier_weight_sub: float = 2.0
  124. foreshadowing_tier_weight_decor: float = 1.0
  125. # ================= 角色活跃度 =================
  126. character_absence_warning: int = 30
  127. character_absence_critical: int = 100
  128. character_candidates_limit: int = 800
  129. # ================= Strand Weave 节奏 =================
  130. strand_quest_max_consecutive: int = 5
  131. strand_fire_max_gap: int = 10
  132. strand_constellation_max_gap: int = 15
  133. strand_quest_ratio_min: int = 55
  134. strand_quest_ratio_max: int = 65
  135. strand_fire_ratio_min: int = 20
  136. strand_fire_ratio_max: int = 30
  137. strand_constellation_ratio_min: int = 10
  138. strand_constellation_ratio_max: int = 20
  139. # ================= 爽点节奏 =================
  140. pacing_segment_size: int = 100
  141. pacing_words_per_point_excellent: int = 1000
  142. pacing_words_per_point_good: int = 1500
  143. pacing_words_per_point_acceptable: int = 2000
  144. # ================= RAG 存储 =================
  145. @property
  146. def rag_db(self) -> Path:
  147. return self.webnovel_dir / "rag.db"
  148. @property
  149. def vector_db(self) -> Path:
  150. return self.webnovel_dir / "vectors.db"
  151. def ensure_dirs(self):
  152. self.webnovel_dir.mkdir(parents=True, exist_ok=True)
  153. @classmethod
  154. def from_project_root(cls, project_root: str | Path) -> "DataModulesConfig":
  155. return cls(project_root=Path(project_root))
  156. _default_config: Optional[DataModulesConfig] = None
  157. def get_config(project_root: Optional[Path] = None) -> DataModulesConfig:
  158. global _default_config
  159. if project_root is not None:
  160. return DataModulesConfig.from_project_root(project_root)
  161. if _default_config is None:
  162. _default_config = DataModulesConfig()
  163. return _default_config
  164. def set_project_root(project_root: str | Path):
  165. global _default_config
  166. _default_config = DataModulesConfig.from_project_root(project_root)