样式处理器 处理的样式属性: - font_weight: normal / bold - font_style: normal / italic - font_color: 十六进制颜色(如 #1d1d1d) - background_color: 背景颜色
| 15 | |
| 16 | |
| 17 | class StyleProcessor: |
| 18 | """ |
| 19 | 样式处理器 |
| 20 | |
| 21 | 处理的样式属性: |
| 22 | - font_weight: normal / bold |
| 23 | - font_style: normal / italic |
| 24 | - font_color: 十六进制颜色(如 #1d1d1d) |
| 25 | - background_color: 背景颜色 |
| 26 | """ |
| 27 | |
| 28 | def __init__(self): |
| 29 | pass |
| 30 | |
| 31 | def process( |
| 32 | self, |
| 33 | text_blocks: List[Dict[str, Any]], |
| 34 | ocr_styles: List[Dict] = None, |
| 35 | unify: bool = True, |
| 36 | ) -> List[Dict[str, Any]]: |
| 37 | """ |
| 38 | 处理样式(主入口) |
| 39 | |
| 40 | Args: |
| 41 | text_blocks: 文字块列表 |
| 42 | ocr_styles: OCR 返回的全局 styles 列表(若有) |
| 43 | unify: 是否执行聚类统一 |
| 44 | """ |
| 45 | ocr_styles = ocr_styles or [] |
| 46 | |
| 47 | result = self.extract_styles(text_blocks, ocr_styles) |
| 48 | |
| 49 | # 步骤 2: 聚类统一 |
| 50 | if unify and len(result) > 1: |
| 51 | result = self.unify_by_clustering(result) |
| 52 | |
| 53 | return result |
| 54 | |
| 55 | def extract_styles( |
| 56 | self, |
| 57 | text_blocks: List[Dict[str, Any]], |
| 58 | ocr_styles: List[Dict], |
| 59 | ) -> List[Dict[str, Any]]: |
| 60 | """ |
| 61 | 从文字块和 OCR styles 中提取样式。 |
| 62 | 优先级:1. 文字块自身属性 2. OCR styles 的 spans 匹配 |
| 63 | """ |
| 64 | result = [] |
| 65 | |
| 66 | for block in text_blocks: |
| 67 | block = copy.copy(block) |
| 68 | |
| 69 | styles = self._extract_block_styles(block, ocr_styles) |
| 70 | |
| 71 | # 应用样式 |
| 72 | block["font_weight"] = "bold" if styles["is_bold"] else "normal" |
| 73 | block["font_style"] = "italic" if styles["is_italic"] else "normal" |
| 74 | block["is_bold"] = styles["is_bold"] |