54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
|
|
# @line_count 100
|
|||
|
|
"""解析器工厂"""
|
|||
|
|
from typing import Dict, Any, Type, List
|
|||
|
|
from .base_adapter import BaseParserAdapter
|
|||
|
|
from .section_array_adapter import SectionArrayAdapter
|
|||
|
|
from .requirement_tree_adapter import RequirementTreeAdapter
|
|||
|
|
|
|||
|
|
|
|||
|
|
class ParserFactory:
|
|||
|
|
"""解析器工厂,自动检测格式并创建合适的适配器"""
|
|||
|
|
|
|||
|
|
# 注册所有适配器(按优先级排序)
|
|||
|
|
_adapters: List[Type[BaseParserAdapter]] = [
|
|||
|
|
RequirementTreeAdapter, # 新格式优先
|
|||
|
|
SectionArrayAdapter, # 旧格式
|
|||
|
|
# 未来可以在这里添加更多适配器
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
@classmethod
|
|||
|
|
def create_adapter(cls, data: Dict[str, Any]) -> BaseParserAdapter:
|
|||
|
|
"""
|
|||
|
|
创建合适的适配器
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
data: JSON数据
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
适配器实例
|
|||
|
|
|
|||
|
|
Raises:
|
|||
|
|
ValueError: 如果无法识别格式
|
|||
|
|
"""
|
|||
|
|
for adapter_class in cls._adapters:
|
|||
|
|
if adapter_class.can_parse(data):
|
|||
|
|
return adapter_class(data)
|
|||
|
|
|
|||
|
|
raise ValueError(
|
|||
|
|
"无法识别JSON格式。支持的格式:\n"
|
|||
|
|
"- 需求树格式(包含'需求内容'和'文档元数据')\n"
|
|||
|
|
"- 章节数组格式(包含'sections'数组)"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
@classmethod
|
|||
|
|
def register_adapter(cls, adapter_class: Type[BaseParserAdapter],
|
|||
|
|
priority: int = 0):
|
|||
|
|
"""
|
|||
|
|
注册新的适配器
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
adapter_class: 适配器类
|
|||
|
|
priority: 优先级(越小越优先,0为最高优先级)
|
|||
|
|
"""
|
|||
|
|
cls._adapters.insert(priority, adapter_class)
|