word_parser.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. """word_parser.py — 将 Word 文档解析为 Block 列表"""
  2. import base64
  3. import io
  4. from pathlib import Path
  5. from typing import Optional
  6. import zipfile
  7. from docx import Document as DocxDocument
  8. from docx.oxml.ns import qn
  9. from lxml import etree
  10. # 全局缓存:主题字体映射
  11. _theme_fonts_cache = {}
  12. # 当前文档的主题字体(用于在解析过程中传递)
  13. _current_theme_fonts = {}
  14. def _load_theme_fonts(docx_path: Path) -> dict:
  15. """从 Word 文档中加载主题字体定义"""
  16. # 检查缓存
  17. cache_key = str(docx_path)
  18. if cache_key in _theme_fonts_cache:
  19. return _theme_fonts_cache[cache_key]
  20. theme_fonts = {}
  21. try:
  22. with zipfile.ZipFile(docx_path, 'r') as docx_zip:
  23. # 查找主题文件
  24. theme_files = [name for name in docx_zip.namelist()
  25. if 'theme' in name.lower() and name.endswith('.xml')]
  26. if not theme_files:
  27. return theme_fonts
  28. # 读取主题 XML
  29. theme_xml = docx_zip.read(theme_files[0])
  30. root = etree.fromstring(theme_xml)
  31. # 命名空间
  32. ns = {'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'}
  33. # 解析 majorFont(标题字体)
  34. major_font = root.find('.//a:majorFont', ns)
  35. if major_font is not None:
  36. ea = major_font.find('.//a:ea', ns)
  37. if ea is not None and ea.get('typeface'):
  38. theme_fonts['majorEastAsia'] = ea.get('typeface')
  39. # 回退到简体中文
  40. hans = major_font.find('.//a:font[@script="Hans"]', ns)
  41. if hans is not None and hans.get('typeface'):
  42. if 'majorEastAsia' not in theme_fonts:
  43. theme_fonts['majorEastAsia'] = hans.get('typeface')
  44. # 解析 minorFont(正文字体)
  45. minor_font = root.find('.//a:minorFont', ns)
  46. if minor_font is not None:
  47. ea = minor_font.find('.//a:ea', ns)
  48. if ea is not None and ea.get('typeface'):
  49. theme_fonts['minorEastAsia'] = ea.get('typeface')
  50. # 回退到简体中文
  51. hans = minor_font.find('.//a:font[@script="Hans"]', ns)
  52. if hans is not None and hans.get('typeface'):
  53. if 'minorEastAsia' not in theme_fonts:
  54. theme_fonts['minorEastAsia'] = hans.get('typeface')
  55. except Exception:
  56. # 如果读取失败,返回空字典
  57. pass
  58. # 缓存结果
  59. _theme_fonts_cache[cache_key] = theme_fonts
  60. return theme_fonts
  61. def _extract_font_from_rfonts(rFonts, theme_fonts: dict = None):
  62. """从 w:rFonts 元素提取字体(优先级: eastAsia → 主题引用 → ascii/hAnsi)"""
  63. if rFonts is None:
  64. return None
  65. # 优先 eastAsia(中文)
  66. if font := rFonts.get(qn('w:eastAsia')):
  67. return font
  68. # 主题字体引用
  69. if theme_fonts:
  70. if theme_key := rFonts.get(qn('w:eastAsiaTheme')):
  71. if theme_font := theme_fonts.get(theme_key):
  72. return theme_font
  73. # 回退到 ascii/hAnsi(西文)
  74. return rFonts.get(qn('w:ascii')) or rFonts.get(qn('w:hAnsi'))
  75. def _get_font_name(run, theme_fonts: dict = None):
  76. """获取 run 的字体名(优先 eastAsia,其次 ascii,支持主题字体)"""
  77. if theme_fonts is None:
  78. theme_fonts = _current_theme_fonts
  79. # 从 run 的 XML 提取字体
  80. if hasattr(run._element, 'rPr') and run._element.rPr is not None:
  81. rFonts = run._element.rPr.find(qn('w:rFonts'))
  82. if font := _extract_font_from_rfonts(rFonts, theme_fonts):
  83. return font
  84. # 特殊情况:只定义了 ascii/hAnsi 但没有 eastAsia,返回 None 让调用者从段落样式提取
  85. if rFonts is not None and (rFonts.get(qn('w:ascii')) or rFonts.get(qn('w:hAnsi'))):
  86. return None
  87. # 回退到标准 API
  88. return run.font.name
  89. def _get_paragraph_style_font(para, theme_fonts: dict = None):
  90. """从段落样式中提取字体(递归查找基础样式)"""
  91. if theme_fonts is None:
  92. theme_fonts = _current_theme_fonts
  93. try:
  94. if not para.style or not hasattr(para.style, 'element'):
  95. return None
  96. return _get_style_font_recursive(para.style, theme_fonts)
  97. except Exception:
  98. return None
  99. def _get_style_font_recursive(style, theme_fonts: dict = None, depth: int = 0):
  100. """递归查找样式字体(限制深度防止死循环)"""
  101. if depth > 10 or not style or not hasattr(style, 'element'):
  102. return None
  103. try:
  104. rPr = style.element.find(qn('w:rPr'))
  105. if rPr is not None:
  106. rFonts = rPr.find(qn('w:rFonts'))
  107. if font := _extract_font_from_rfonts(rFonts, theme_fonts):
  108. return font
  109. # 递归查找基础样式
  110. if hasattr(style, 'base_style') and style.base_style:
  111. return _get_style_font_recursive(style.base_style, theme_fonts, depth + 1)
  112. except Exception:
  113. pass
  114. return None
  115. def _get_style_formatting(style):
  116. """从样式中提取格式属性(加粗、斜体、下划线等)"""
  117. formatting = {}
  118. if not style or not hasattr(style, 'element'):
  119. return formatting
  120. try:
  121. rPr = style.element.find(qn('w:rPr'))
  122. if rPr is None:
  123. return formatting
  124. # 检查加粗、斜体(w:val 为 None/'1'/'true' 表示启用)
  125. for prop_name in ['b', 'i']:
  126. if elem := rPr.find(qn(f'w:{prop_name}')):
  127. val = elem.get(qn('w:val'))
  128. if val is None or val in ('1', 'true'):
  129. formatting[{'b': 'bold', 'i': 'italic'}[prop_name]] = True
  130. # 检查下划线(有多种类型)
  131. if underline_elem := rPr.find(qn('w:u')):
  132. underline_val = underline_elem.get(qn('w:val'))
  133. if underline_val and underline_val != 'none':
  134. formatting['underline'] = True
  135. except Exception:
  136. pass
  137. return formatting
  138. def parse_word_to_blocks(docx_path: Path) -> list[dict]:
  139. """将 Word 文档解析为 Block 列表"""
  140. global _current_theme_fonts
  141. doc = DocxDocument(str(docx_path))
  142. _current_theme_fonts = _load_theme_fonts(docx_path)
  143. # 初始化解析上下文
  144. context = _init_parse_context()
  145. # 提取图片映射
  146. image_map = _build_image_map(doc)
  147. # 收集文档元素
  148. elements = _collect_document_elements(doc)
  149. # 建立段落索引映射
  150. para_idx_map = _build_paragraph_index_map(elements)
  151. # 转换元素为 blocks
  152. blocks = _convert_elements_to_blocks(elements, context, image_map, para_idx_map)
  153. return blocks
  154. def _init_parse_context():
  155. """初始化解析上下文"""
  156. return {
  157. 'blocks': [],
  158. 'block_order': 0,
  159. 'heading_counters': {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0},
  160. 'type_counters': {'paragraph': 0, 'image': 0, 'table': 0},
  161. 'parent_stack': []
  162. }
  163. def _build_image_map(doc):
  164. """构建图片位置映射"""
  165. from app.services.image_service import extract_images_from_word
  166. images = extract_images_from_word(doc)
  167. image_map = {}
  168. for img in images:
  169. para_idx = img['paragraph_index']
  170. if para_idx not in image_map:
  171. image_map[para_idx] = []
  172. image_map[para_idx].append(img)
  173. return image_map
  174. def _collect_document_elements(doc):
  175. """收集文档中的所有元素(段落、表格、SDT)"""
  176. elements = []
  177. body = doc.element.body
  178. para_map = {p._element: p for p in doc.paragraphs}
  179. table_map = {t._element: t for t in doc.tables}
  180. for child in body:
  181. tag = child.tag
  182. if tag.endswith('p'):
  183. if para := para_map.get(child):
  184. elements.append(('para', para))
  185. elif tag.endswith('tbl'):
  186. if table := table_map.get(child):
  187. elements.append(('table', table))
  188. elif tag.endswith('sdt'):
  189. elements.append(('sdt', child))
  190. return elements
  191. def _build_paragraph_index_map(elements):
  192. """建立段落索引映射"""
  193. para_idx_map = {}
  194. actual_para_idx = 0
  195. for elem_idx, (elem_type, elem) in enumerate(elements):
  196. if elem_type == "para":
  197. para_idx_map[actual_para_idx] = elem_idx
  198. actual_para_idx += 1
  199. return para_idx_map
  200. def _convert_elements_to_blocks(elements, context, image_map, para_idx_map):
  201. """将元素列表转换为 blocks"""
  202. for elem_idx, (elem_type, elem) in enumerate(elements):
  203. if elem_type == "para":
  204. _process_paragraph_element(elem, elem_idx, context, image_map, para_idx_map)
  205. elif elem_type == "table":
  206. _process_table_element(elem, context)
  207. elif elem_type == "sdt":
  208. _process_sdt_element(elem, context)
  209. return context['blocks']
  210. def _process_paragraph_element(para, elem_idx, context, image_map, para_idx_map):
  211. """处理段落元素"""
  212. style_name = para.style.name if para.style else "Normal"
  213. level = _identify_heading_level(para, style_name)
  214. if level:
  215. _process_heading_paragraph(para, style_name, level, context)
  216. else:
  217. _process_normal_paragraph(para, style_name, elem_idx, context, image_map, para_idx_map)
  218. def _process_heading_paragraph(para, style_name, level, context):
  219. """处理标题段落"""
  220. content = _extract_rich_text(para)
  221. if not content:
  222. return # 跳过空标题
  223. # 计算 index 并更新计数器
  224. index = context['heading_counters'][level] * 100
  225. context['heading_counters'][level] += 1
  226. # 更新父标题栈
  227. parent_stack = context['parent_stack']
  228. while parent_stack and parent_stack[-1]['level'] >= level:
  229. parent_stack.pop()
  230. parent_id = parent_stack[-1]['id'] if parent_stack else None
  231. para_style = _extract_paragraph_format(para)
  232. block = {
  233. 'id': f'block-h{level}-{index}',
  234. 'block_order': context['block_order'] * 100,
  235. 'type': 'heading',
  236. 'level': level,
  237. 'index': index,
  238. 'content': content,
  239. 'word_style': style_name,
  240. 'style': para_style,
  241. 'metadata': {'parent_heading_id': parent_id}
  242. }
  243. context['blocks'].append(block)
  244. parent_stack.append({'id': block['id'], 'level': level})
  245. context['block_order'] += 1
  246. def _process_normal_paragraph(para, style_name, elem_idx, context, image_map, para_idx_map):
  247. """处理普通段落(包括空行)"""
  248. content = _extract_rich_text(para)
  249. para_style = _extract_paragraph_format(para)
  250. # 查找当前段落索引
  251. current_para_idx = None
  252. for p_idx, e_idx in para_idx_map.items():
  253. if e_idx == elem_idx:
  254. current_para_idx = p_idx
  255. break
  256. # 空行处理
  257. if not content and (current_para_idx is None or current_para_idx - 1 not in image_map):
  258. _create_paragraph_block('', style_name, para_style, context)
  259. elif content:
  260. # 有内容的段落
  261. block_style = {} if isinstance(content, list) else para_style
  262. _create_paragraph_block(content, style_name, block_style, context)
  263. # 处理段落后的图片
  264. if current_para_idx is not None and current_para_idx in image_map:
  265. for img in image_map[current_para_idx]:
  266. _create_image_block(img, context)
  267. def _create_paragraph_block(content, style_name, style, context):
  268. """创建段落 block"""
  269. parent_id = context['parent_stack'][-1]['id'] if context['parent_stack'] else None
  270. index = context['type_counters']['paragraph'] * 100
  271. context['type_counters']['paragraph'] += 1
  272. block = {
  273. 'id': f'block-p-{index}',
  274. 'block_order': context['block_order'] * 100,
  275. 'type': 'paragraph',
  276. 'level': 0,
  277. 'index': index,
  278. 'content': content,
  279. 'word_style': style_name,
  280. 'style': style,
  281. 'metadata': {'parent_heading_id': parent_id}
  282. }
  283. context['blocks'].append(block)
  284. context['block_order'] += 1
  285. def _create_image_block(img, context):
  286. """创建图片 block"""
  287. parent_id = context['parent_stack'][-1]['id'] if context['parent_stack'] else None
  288. index = context['type_counters']['image'] * 100
  289. context['type_counters']['image'] += 1
  290. block = {
  291. 'id': f'block-img-{index}',
  292. 'block_order': context['block_order'] * 100,
  293. 'type': 'image',
  294. 'level': 0,
  295. 'index': index,
  296. 'content': img['data_url'],
  297. 'word_style': img['style'].get('para_style', 'Normal'),
  298. 'style': {
  299. 'width': img['style'].get('width', 10.0),
  300. 'height': img['style'].get('height', 7.0),
  301. 'unit': img['style'].get('unit', 'cm'),
  302. 'align': img['style'].get('align', 'left')
  303. },
  304. 'metadata': {
  305. 'alt': '图片',
  306. 'parent_heading_id': parent_id
  307. }
  308. }
  309. context['blocks'].append(block)
  310. context['block_order'] += 1
  311. def _process_table_element(table, context):
  312. """处理表格元素"""
  313. table_content = _extract_table(table, None)
  314. parent_id = context['parent_stack'][-1]['id'] if context['parent_stack'] else None
  315. # 计算表格列数
  316. rows = table_content.get('rows', [])
  317. max_cols = max(
  318. (sum(cell.get('colspan', 1) for cell in row_data.get('cells', []))
  319. for row_data in rows),
  320. default=0
  321. )
  322. index = context['type_counters']['table'] * 100
  323. context['type_counters']['table'] += 1
  324. block = {
  325. 'id': f'block-table-{index}',
  326. 'block_order': context['block_order'] * 100,
  327. 'type': 'table',
  328. 'level': 0,
  329. 'index': index,
  330. 'content': table_content,
  331. 'word_style': 'Table Grid',
  332. 'style': {},
  333. 'metadata': {
  334. 'cols': max_cols,
  335. 'rows': len(rows),
  336. 'table_width': 100,
  337. 'table_width_unit': 'percent',
  338. 'col_widths': [100 // max_cols] * max_cols if max_cols > 0 else [],
  339. 'parent_heading_id': parent_id
  340. }
  341. }
  342. context['blocks'].append(block)
  343. context['block_order'] += 1
  344. def _process_sdt_element(sdt, context):
  345. """处理 SDT 元素(目录)"""
  346. toc_block = _extract_toc_from_sdt(sdt, context['block_order'], context['parent_stack'])
  347. if toc_block:
  348. context['blocks'].append(toc_block)
  349. context['block_order'] += 1
  350. def _extract_toc_from_sdt(sdt, block_order: int, parent_stack: list) -> Optional[dict]:
  351. """从 SDT 中提取目录 Block
  352. Args:
  353. sdt: SDT XML 元素
  354. block_order: 当前 block 顺序
  355. parent_stack: 父标题栈
  356. Returns:
  357. TOC Block 字典,如果不是目录则返回 None
  358. """
  359. import re
  360. # 1. 检查 SDT 内是否包含 TOC 域
  361. instr_texts = sdt.findall('.//' + qn('w:instrText'))
  362. has_toc = False
  363. toc_levels = "1-1" # 默认值
  364. use_hyperlinks = False
  365. use_page_numbers = True
  366. hide_page_numbers_in_web = False
  367. use_outline_levels = False
  368. for instr in instr_texts:
  369. text = instr.text if instr.text else ''
  370. if 'TOC' in text.upper():
  371. has_toc = True
  372. # 提取层级参数
  373. # 例如:TOC \o "1-3" \h \z \u
  374. match = re.search(r'\\o\s+"(\d+-\d+)"', text)
  375. if match:
  376. toc_levels = match.group(1)
  377. # 提取开关
  378. use_hyperlinks = '\\h' in text
  379. hide_page_numbers_in_web = '\\z' in text
  380. use_outline_levels = '\\u' in text
  381. break
  382. if not has_toc:
  383. return None
  384. # 2. 提取目录标题(SDT 内第一个段落)
  385. toc_title = "目录"
  386. paragraphs = sdt.findall('.//' + qn('w:p'))
  387. if paragraphs:
  388. first_para = paragraphs[0]
  389. text_elems = first_para.findall('.//' + qn('w:t'))
  390. title_text = ''.join([t.text for t in text_elems if t.text])
  391. if title_text:
  392. toc_title = title_text.strip()
  393. # 3. 获取父标题 ID
  394. parent_id = parent_stack[-1]['id'] if parent_stack else None
  395. # 4. 构建 TOC Block
  396. toc_block = {
  397. 'id': 'block-toc-0',
  398. 'block_order': block_order * 100,
  399. 'type': 'toc',
  400. 'level': 0,
  401. 'index': 0,
  402. 'content': {
  403. 'title': toc_title
  404. },
  405. 'word_style': 'TOC',
  406. 'metadata': {
  407. 'toc_config': {
  408. 'levels': toc_levels,
  409. 'use_hyperlinks': use_hyperlinks,
  410. 'use_page_numbers': use_page_numbers,
  411. 'hide_page_numbers_in_web': hide_page_numbers_in_web,
  412. 'use_outline_levels': use_outline_levels,
  413. 'show_leader_dots': True,
  414. 'leader_char': '.'
  415. },
  416. 'is_auto_generated': True,
  417. 'readonly': True,
  418. 'deletable': True
  419. }
  420. }
  421. return toc_block
  422. def _identify_heading_level(para, style_name: str) -> Optional[int]:
  423. """识别段落的标题级别(1-6 或 None)"""
  424. # 方法1:检查样式名称(内置样式)
  425. if style_name.startswith('Heading'):
  426. try:
  427. level = int(style_name.split()[-1])
  428. return level
  429. except (ValueError, IndexError):
  430. pass
  431. # 方法2:检查样式的大纲级别
  432. style = para.style
  433. if hasattr(style, 'element') and hasattr(style.element, 'pPr'):
  434. pPr = style.element.pPr
  435. if pPr is not None:
  436. outline_lvl = pPr.find(qn('w:outlineLvl'))
  437. if outline_lvl is not None:
  438. try:
  439. level = int(outline_lvl.get(qn('w:val'))) + 1
  440. if 1 <= level <= 6:
  441. return level
  442. except (ValueError, TypeError):
  443. pass
  444. # 方法3:检查段落格式的大纲级别
  445. if para._element.pPr is not None:
  446. outline_lvl = para._element.pPr.find(qn('w:outlineLvl'))
  447. if outline_lvl is not None:
  448. try:
  449. level = int(outline_lvl.get(qn('w:val'))) + 1
  450. if 1 <= level <= 6:
  451. return level
  452. except (ValueError, TypeError):
  453. pass
  454. return None
  455. def _extract_paragraph_format(para) -> dict:
  456. """提取段落级样式(Block 级别的 style)"""
  457. style = {}
  458. # 对齐方式
  459. if para.alignment is not None:
  460. align_map = {0: 'left', 1: 'center', 2: 'right', 3: 'justify'}
  461. style['align'] = align_map.get(para.alignment, 'left')
  462. # 字体和字号(检查第一个 run,如果整段统一则提取到 Block 级)
  463. if para.runs:
  464. first_run = para.runs[0]
  465. # 检查是否整段使用相同字体(支持 eastAsia,忽略 None 值)
  466. first_font = _get_font_name(first_run)
  467. # 如果所有 runs 都没有字体设置(都是 None),从段落样式提取
  468. if first_font is None:
  469. # 检查是否所有 runs 都没有字体
  470. all_none = all(
  471. _get_font_name(run) is None
  472. for run in para.runs if run.text
  473. )
  474. if all_none:
  475. # 从段落样式提取字体
  476. style_font = _get_paragraph_style_font(para)
  477. if style_font:
  478. style['font_name'] = style_font
  479. elif first_font:
  480. # 如果第一个 run 有字体,检查是否整段统一
  481. all_same_font = all(
  482. _get_font_name(run) == first_font
  483. for run in para.runs if run.text and _get_font_name(run) is not None
  484. )
  485. if all_same_font:
  486. style['font_name'] = first_font
  487. # 检查是否整段使用相同字号(忽略 None 值)
  488. if first_run.font.size:
  489. # 只比较有字号的 runs
  490. all_same_size = all(
  491. run.font.size == first_run.font.size
  492. for run in para.runs if run.text and run.font.size is not None
  493. )
  494. if all_same_size:
  495. style['font_size'] = first_run.font.size.pt
  496. # 检查是否整段加粗
  497. if first_run.bold:
  498. all_bold = all(run.bold for run in para.runs if run.text)
  499. if all_bold:
  500. style['bold'] = True
  501. # 检查是否整段斜体
  502. if first_run.italic:
  503. all_italic = all(run.italic for run in para.runs if run.text)
  504. if all_italic:
  505. style['italic'] = True
  506. # 检查是否整段下划线
  507. if first_run.underline:
  508. all_underline = all(run.underline for run in para.runs if run.text)
  509. if all_underline:
  510. style['underline'] = True
  511. # 检查是否整段相同颜色
  512. if first_run.font.color and first_run.font.color.rgb:
  513. first_color = str(first_run.font.color.rgb)
  514. all_same_color = all(
  515. (run.font.color and str(run.font.color.rgb) == first_color)
  516. for run in para.runs if run.text
  517. )
  518. if all_same_color:
  519. style['color'] = first_color
  520. else:
  521. # 空段落(没有 runs):先尝试从段落属性 XML 中提取直接格式化的字体和字号
  522. pPr = para._element.find(qn('w:pPr'))
  523. if pPr is not None:
  524. rPr = pPr.find(qn('w:rPr'))
  525. if rPr is not None:
  526. # 从段落属性中提取字号(w:sz,单位是半磅)
  527. sz = rPr.find(qn('w:sz'))
  528. if sz is not None:
  529. size_val = sz.get(qn('w:val'))
  530. if size_val:
  531. try:
  532. style['font_size'] = int(size_val) / 2 # 转换为磅值
  533. except (ValueError, TypeError):
  534. pass
  535. # 从段落属性中提取字体
  536. rFonts = rPr.find(qn('w:rFonts'))
  537. if rFonts is not None:
  538. # 优先使用 eastAsia 字体(中文)
  539. eastAsia = rFonts.get(qn('w:eastAsia'))
  540. ascii_font = rFonts.get(qn('w:ascii'))
  541. # 如果有 eastAsia 字体就用,否则用 ascii
  542. if eastAsia:
  543. style['font_name'] = eastAsia
  544. elif ascii_font:
  545. style['font_name'] = ascii_font
  546. # 如果 XML 中没有找到,再从段落样式中提取默认字体和字号
  547. if 'font_name' not in style:
  548. style_font = _get_paragraph_style_font(para)
  549. if style_font:
  550. style['font_name'] = style_font
  551. if 'font_size' not in style:
  552. # 尝试从段落样式中提取字号
  553. try:
  554. if hasattr(para.style, 'font') and para.style.font.size:
  555. style['font_size'] = para.style.font.size.pt
  556. except Exception:
  557. pass
  558. return style
  559. def _extract_rich_text(para) -> str | list:
  560. """提取段落的富文本内容(纯文本字符串或富文本片段列表)"""
  561. text = para.text.strip()
  562. if not text:
  563. return ""
  564. # 没有 runs 或只有一个 run,返回纯文本
  565. if not para.runs or len(para.runs) == 0:
  566. return text
  567. # 提取所有 runs 的样式(用于判断是否统一)
  568. valid_runs = [run for run in para.runs if run.text]
  569. if len(valid_runs) <= 1:
  570. return text
  571. # 检查所有 runs 的样式是否完全相同
  572. def get_run_style_signature(run):
  573. """获取 run 的样式签名,用于比较"""
  574. return (
  575. _get_font_name(run),
  576. run.font.size.pt if run.font.size else None,
  577. run.bold,
  578. run.italic,
  579. run.underline,
  580. run.font.strike,
  581. str(run.font.color.rgb) if run.font.color and run.font.color.rgb else None
  582. )
  583. first_sig = get_run_style_signature(valid_runs[0])
  584. all_same = all(get_run_style_signature(run) == first_sig for run in valid_runs)
  585. if all_same:
  586. # 所有 runs 样式相同,返回纯文本
  587. return text
  588. # 样式不同,返回富文本数组
  589. # 每个 run 包含完整样式和 word_style
  590. segments = []
  591. for run in para.runs:
  592. if not run.text:
  593. continue
  594. style = {}
  595. # 字体
  596. font_name = _get_font_name(run)
  597. if font_name:
  598. style['font_name'] = font_name
  599. # 字号
  600. if run.font.size:
  601. style['font_size'] = run.font.size.pt
  602. # 加粗
  603. if run.bold:
  604. style['bold'] = True
  605. # 斜体
  606. if run.italic:
  607. style['italic'] = True
  608. # 删除线
  609. if run.font.strike:
  610. style['strike'] = True
  611. # 下划线
  612. if run.underline:
  613. style['underline'] = True
  614. # 颜色
  615. if run.font.color and run.font.color.rgb:
  616. style['color'] = str(run.font.color.rgb)
  617. # 提取 word_style(字符样式或段落样式)
  618. word_style = None
  619. if run.style:
  620. word_style = run.style.name
  621. else:
  622. # run 没有独立样式,使用段落样式
  623. word_style = para.style.name if para.style else None
  624. segment = {
  625. 'text': run.text,
  626. 'style': style
  627. }
  628. # 添加 word_style(方案 A:总是添加)
  629. if word_style:
  630. segment['word_style'] = word_style
  631. segments.append(segment)
  632. return segments if segments else text
  633. def _extract_table(table, doc=None) -> dict:
  634. """提取表格内容(包含合并单元格和尺寸信息)- 完整修复版
  635. Args:
  636. table: python-docx 表格对象
  637. doc: python-docx 文档对象(用于获取样式名称)
  638. """
  639. rows_data = []
  640. # 提取表格列宽(从 tblGrid)
  641. col_widths = []
  642. tbl_elem = table._element
  643. tbl_grid = tbl_elem.find(qn('w:tblGrid'))
  644. if tbl_grid is not None:
  645. for grid_col in tbl_grid.findall(qn('w:gridCol')):
  646. width = grid_col.get(qn('w:w'))
  647. if width:
  648. # twips 转 pt (1 pt = 20 twips)
  649. col_widths.append(int(width) / 20)
  650. # 创建 XML 元素到 python-docx 单元格对象的映射
  651. cell_map = {}
  652. for row in table.rows:
  653. for cell in row.cells:
  654. cell_map[id(cell._element)] = cell
  655. # 第一遍:从 XML 直接读取,建立列索引到行合并信息的映射
  656. # col_index -> [{start_row, end_row}, ...] # 可能有多个合并区间
  657. vmerge_map = {}
  658. trs = tbl_elem.findall(qn('w:tr'))
  659. for row_idx, tr in enumerate(trs):
  660. tcs = tr.findall(qn('w:tc'))
  661. col_offset = 0
  662. for tc in tcs:
  663. tcPr = tc.find(qn('w:tcPr'))
  664. colspan = 1
  665. has_vmerge_restart = False
  666. has_vmerge_continue = False
  667. is_empty = False
  668. if tcPr is not None:
  669. # 列合并
  670. grid_span = tcPr.find(qn('w:gridSpan'))
  671. if grid_span is not None:
  672. colspan = int(grid_span.get(qn('w:val')))
  673. # 行合并
  674. v_merge = tcPr.find(qn('w:vMerge'))
  675. if v_merge is not None:
  676. v_merge_val = v_merge.get(qn('w:val'))
  677. if v_merge_val == 'restart':
  678. has_vmerge_restart = True
  679. else:
  680. # 'continue' 或 None/空字符串都表示继续合并
  681. has_vmerge_continue = True
  682. # 检查是否为空单元格(用于判断行合并)
  683. paras = tc.findall(qn('w:p'))
  684. text_parts = []
  685. for p in paras:
  686. runs = p.findall(qn('w:r'))
  687. for r in runs:
  688. ts = r.findall(qn('w:t'))
  689. for t in ts:
  690. if t.text and t.text.strip():
  691. text_parts.append(t.text)
  692. is_empty = len(text_parts) == 0
  693. # 处理行合并逻辑 - 记录所有合并区间
  694. if col_offset not in vmerge_map:
  695. vmerge_map[col_offset] = []
  696. merges = vmerge_map[col_offset]
  697. if has_vmerge_restart:
  698. # 开始新的行合并
  699. merges.append({
  700. 'start_row': row_idx,
  701. 'end_row': row_idx # 初始结束行等于开始行,后续会扩展
  702. })
  703. elif has_vmerge_continue:
  704. # 明确标记为 continue - 扩展最后一个合并
  705. if merges:
  706. merges[-1]['end_row'] = row_idx
  707. # 注意:移除了 "is_empty" 的判断,因为空单元格不一定意味着合并
  708. col_offset += colspan
  709. # 第二遍:完全从 XML 提取单元格数据
  710. for row_idx, tr in enumerate(trs):
  711. cells_data = []
  712. # 提取行高(从 python-docx,因为 XML 提取行高比较复杂)
  713. row_height = None
  714. if row_idx < len(table.rows):
  715. row = table.rows[row_idx]
  716. if row.height:
  717. row_height = row.height.pt
  718. # 遍历 XML 的 tc 元素
  719. tcs = tr.findall(qn('w:tc'))
  720. col_offset = 0
  721. for tc in tcs:
  722. # 首先提取 colspan 和 vMerge 信息
  723. tcPr = tc.find(qn('w:tcPr'))
  724. # 提取 colspan
  725. colspan = 1
  726. if tcPr is not None:
  727. grid_span = tcPr.find(qn('w:gridSpan'))
  728. if grid_span is not None:
  729. colspan = int(grid_span.get(qn('w:val')))
  730. # 检查 vMerge - 如果是 continue,跳过这个单元格
  731. is_vmerge_continue = False
  732. if tcPr is not None:
  733. v_merge = tcPr.find(qn('w:vMerge'))
  734. if v_merge is not None:
  735. v_merge_val = v_merge.get(qn('w:val'))
  736. # 'continue' 或 None/空字符串都表示继续合并
  737. if v_merge_val != 'restart':
  738. is_vmerge_continue = True
  739. if is_vmerge_continue:
  740. # 这是被合并的单元格,跳过
  741. col_offset += colspan
  742. continue
  743. # 不需要跳过被占用的列,因为 XML 中已经包含了占位符
  744. # (上面的 is_vmerge_continue 检查已经处理了)
  745. # 检查是否为空单元格
  746. is_empty = True
  747. paras = tc.findall(qn('w:p'))
  748. text_parts = []
  749. for p in paras:
  750. runs = p.findall(qn('w:r'))
  751. for r in runs:
  752. ts = r.findall(qn('w:t'))
  753. for t in ts:
  754. if t.text and t.text.strip():
  755. is_empty = False
  756. text_parts.append(t.text)
  757. # 判断是否应该提取此单元格
  758. should_extract = True
  759. rowspan = 1
  760. # 查找该列该行所在的合并区间
  761. if col_offset in vmerge_map:
  762. merges = vmerge_map[col_offset]
  763. for merge in merges:
  764. if merge['start_row'] == row_idx:
  765. # 这是合并的起始行
  766. rowspan = merge['end_row'] - merge['start_row'] + 1
  767. break
  768. elif row_idx > merge['start_row'] and row_idx <= merge['end_row']:
  769. # 这是被合并的行
  770. should_extract = False # 跳过被合并的单元格
  771. break
  772. if should_extract:
  773. # 从 XML 提取文本(支持富文本)
  774. cell_text_segments = []
  775. for p in paras:
  776. para_segments = []
  777. runs = p.findall(qn('w:r'))
  778. for r in runs:
  779. # 提取文本
  780. run_text = []
  781. for t in r.findall(qn('w:t')):
  782. if t.text:
  783. run_text.append(t.text)
  784. if run_text:
  785. # 提取 run 级样式
  786. run_style = {}
  787. rPr = r.find(qn('w:rPr'))
  788. if rPr is not None:
  789. # 加粗
  790. if rPr.find(qn('w:b')) is not None:
  791. run_style['bold'] = True
  792. # 斜体
  793. if rPr.find(qn('w:i')) is not None:
  794. run_style['italic'] = True
  795. # 下划线
  796. if rPr.find(qn('w:u')) is not None:
  797. run_style['underline'] = True
  798. # 字号
  799. sz = rPr.find(qn('w:sz'))
  800. if sz is not None:
  801. size_val = sz.get(qn('w:val'))
  802. if size_val:
  803. run_style['font_size'] = int(size_val) / 2 # 半磅转磅
  804. # 颜色
  805. color = rPr.find(qn('w:color'))
  806. if color is not None:
  807. color_val = color.get(qn('w:val'))
  808. if color_val and color_val != 'auto':
  809. run_style['color'] = color_val
  810. para_segments.append({
  811. 'text': ''.join(run_text),
  812. 'style': run_style
  813. })
  814. if para_segments:
  815. cell_text_segments.extend(para_segments)
  816. # 合并文本
  817. if len(cell_text_segments) == 0:
  818. text_content = ""
  819. elif len(cell_text_segments) == 1 and not cell_text_segments[0]['style']:
  820. # 纯文本
  821. text_content = cell_text_segments[0]['text']
  822. else:
  823. # 富文本或多个片段 - 简化处理:合并为纯文本
  824. text_content = ''.join(seg['text'] for seg in cell_text_segments)
  825. # 提取单元格样式(从第一个段落的第一个 run)
  826. cell_style = {}
  827. cell_word_style = None
  828. # 尝试使用 python-docx API 获取样式
  829. cell_obj = cell_map.get(id(tc))
  830. if cell_obj and cell_obj.paragraphs:
  831. first_para = cell_obj.paragraphs[0]
  832. if first_para.style:
  833. cell_word_style = first_para.style.name
  834. # 如果没有通过 API 获取到,尝试从 XML 获取
  835. if not cell_word_style and paras:
  836. first_p = paras[0]
  837. pPr = first_p.find(qn('w:pPr'))
  838. if pPr is not None:
  839. # 段落样式名称 - 从 XML 获取样式 ID
  840. pStyle = pPr.find(qn('w:pStyle'))
  841. if pStyle is not None:
  842. style_id = pStyle.get(qn('w:val'))
  843. # 尝试从已知的样式映射中查找
  844. # 注意:这里只能使用样式 ID 作为备选
  845. cell_word_style = style_id
  846. # 提取其他样式属性
  847. if paras:
  848. first_p = paras[0]
  849. pPr = first_p.find(qn('w:pPr'))
  850. if pPr is not None:
  851. # 对齐方式
  852. jc = pPr.find(qn('w:jc'))
  853. if jc is not None:
  854. align_val = jc.get(qn('w:val'))
  855. align_map = {'left': 'left', 'center': 'center', 'right': 'right', 'both': 'justify'}
  856. cell_style['align'] = align_map.get(align_val, 'left')
  857. # 从第一个 run 提取样式
  858. runs = first_p.findall(qn('w:r'))
  859. if runs:
  860. first_r = runs[0]
  861. rPr = first_r.find(qn('w:rPr'))
  862. if rPr is not None:
  863. # 加粗
  864. if rPr.find(qn('w:b')) is not None:
  865. cell_style['bold'] = True
  866. # 斜体
  867. if rPr.find(qn('w:i')) is not None:
  868. cell_style['italic'] = True
  869. # 下划线
  870. if rPr.find(qn('w:u')) is not None:
  871. cell_style['underline'] = True
  872. # 字号
  873. sz = rPr.find(qn('w:sz'))
  874. if sz is not None:
  875. size_val = sz.get(qn('w:val'))
  876. if size_val:
  877. cell_style['font_size'] = int(size_val) / 2
  878. # 颜色
  879. color = rPr.find(qn('w:color'))
  880. if color is not None:
  881. color_val = color.get(qn('w:val'))
  882. if color_val and color_val != 'auto':
  883. cell_style['color'] = color_val
  884. # 字体(复杂,需要处理主题字体)
  885. rFonts = rPr.find(qn('w:rFonts'))
  886. if rFonts is not None:
  887. font_name = (rFonts.get(qn('w:eastAsia')) or
  888. rFonts.get(qn('w:ascii')) or
  889. rFonts.get(qn('w:hAnsi')))
  890. if font_name:
  891. cell_style['font_name'] = font_name
  892. # 提取单元格宽度
  893. cell_width = None
  894. if tcPr is not None:
  895. tcW = tcPr.find(qn('w:tcW'))
  896. if tcW is not None:
  897. width_val = tcW.get(qn('w:w'))
  898. width_type = tcW.get(qn('w:type'))
  899. if width_val and width_type != 'pct':
  900. cell_width = int(width_val) / 20
  901. if cell_width is None and col_offset < len(col_widths):
  902. if colspan == 1:
  903. cell_width = col_widths[col_offset]
  904. else:
  905. cell_width = sum(col_widths[col_offset:col_offset + colspan])
  906. # 构建单元格数据
  907. cell_data = {
  908. 'text': text_content,
  909. 'rowspan': rowspan,
  910. 'colspan': colspan,
  911. 'col_index': col_offset, # 记录该单元格的绝对列位置
  912. 'style': cell_style
  913. }
  914. if cell_word_style:
  915. cell_data['word_style'] = cell_word_style
  916. if cell_width is not None:
  917. cell_data['width'] = round(cell_width, 2)
  918. cells_data.append(cell_data)
  919. col_offset += colspan
  920. # 构建行数据
  921. row_data = {'cells': cells_data}
  922. if row_height is not None:
  923. row_data['height'] = round(row_height, 2)
  924. rows_data.append(row_data)
  925. return {
  926. 'rows': rows_data,
  927. 'col_widths': [round(w, 2) for w in col_widths] if col_widths else None
  928. }