1
0
Files
PPTX/validators/resource.py
lanyuanxiaoyao 83ff827ad1 feat: add YAML validation with check command and auto-validation
Implements comprehensive validation before PPTX conversion to catch errors early. Includes element-level validation (colors, fonts, table consistency) and system-level validation (geometry, resources). Supports standalone check command and automatic validation during conversion.
2026-03-02 18:14:45 +08:00

123 lines
3.5 KiB
Python

"""
资源验证器
验证 YAML 文件引用的外部资源是否存在。
"""
from pathlib import Path
from validators.result import ValidationIssue
from loaders.yaml_loader import load_yaml_file, validate_template_yaml
class ResourceValidator:
"""资源验证器"""
def __init__(self, yaml_dir: Path, template_dir: Path = None):
"""
初始化资源验证器
Args:
yaml_dir: YAML 文件所在目录
template_dir: 模板文件目录(可选)
"""
self.yaml_dir = yaml_dir
self.template_dir = template_dir
def validate_image(self, element, slide_index: int, elem_index: int) -> list:
"""
验证图片文件是否存在
Args:
element: 图片元素对象
slide_index: 幻灯片索引(从 1 开始)
elem_index: 元素索引(从 1 开始)
Returns:
验证问题列表
"""
issues = []
location = f"幻灯片 {slide_index}, 元素 {elem_index}"
if not hasattr(element, 'src'):
return issues
src = element.src
if not src:
return issues
# 解析路径(支持相对路径和绝对路径)
src_path = Path(src)
if not src_path.is_absolute():
src_path = self.yaml_dir / src
# 检查文件是否存在
if not src_path.exists():
issues.append(ValidationIssue(
level="ERROR",
message=f"图片文件不存在: {src}",
location=location,
code="IMAGE_FILE_NOT_FOUND"
))
return issues
def validate_template(self, slide_data: dict, slide_index: int) -> list:
"""
验证模板文件是否存在且结构正确
Args:
slide_data: 幻灯片数据字典
slide_index: 幻灯片索引(从 1 开始)
Returns:
验证问题列表
"""
issues = []
location = f"幻灯片 {slide_index}"
if 'template' not in slide_data:
return issues
template_name = slide_data['template']
if not template_name:
return issues
# 检查是否提供了模板目录
if not self.template_dir:
issues.append(ValidationIssue(
level="ERROR",
message=f"使用了模板但未指定模板目录: {template_name}",
location=location,
code="TEMPLATE_DIR_NOT_SPECIFIED"
))
return issues
# 解析模板文件路径
template_path = self.template_dir / template_name
if not template_path.suffix:
template_path = template_path.with_suffix('.yaml')
# 检查模板文件是否存在
if not template_path.exists():
issues.append(ValidationIssue(
level="ERROR",
message=f"模板文件不存在: {template_name}",
location=location,
code="TEMPLATE_FILE_NOT_FOUND"
))
return issues
# 验证模板文件结构
try:
template_data = load_yaml_file(template_path)
validate_template_yaml(template_data, str(template_path))
except Exception as e:
issues.append(ValidationIssue(
level="ERROR",
message=f"模板文件结构错误: {template_name} - {str(e)}",
location=location,
code="TEMPLATE_STRUCTURE_ERROR"
))
return issues