154 lines
7.5 KiB
Python
154 lines
7.5 KiB
Python
"""Native structural evidence, kept separate from knowledge-base chunking."""
|
|
import base64
|
|
from collections import defaultdict
|
|
from statistics import median
|
|
import re
|
|
|
|
|
|
def word_level(paragraph):
|
|
from docx.oxml.ns import qn
|
|
chain = [paragraph._p]
|
|
style, seen = paragraph.style, set()
|
|
while style is not None and style.style_id not in seen:
|
|
seen.add(style.style_id)
|
|
chain.append(style.element)
|
|
style = style.base_style
|
|
for element in chain:
|
|
prop = element.find(qn('w:pPr'))
|
|
outline = prop.find(qn('w:outlineLvl')) if prop is not None else None
|
|
if outline is not None:
|
|
value = int(outline.get(qn('w:val'), '9'))
|
|
return (min(value + 1, 6), 'word_outline') if 0 <= value <= 8 else (None, '')
|
|
name = paragraph.style.name if paragraph.style else ''
|
|
match = re.fullmatch(r'(?:Heading\s*|标题\s*)(\d+)', name, re.I)
|
|
if match:
|
|
return min(6, int(match[1])), 'word_style'
|
|
return None, ''
|
|
|
|
|
|
def word_markdown(document, handler, capture):
|
|
from docx.oxml.ns import qn
|
|
from docx.table import Table
|
|
from docx.text.paragraph import Paragraph
|
|
from common.handle.impl.text.doc_split_handle import get_image_id_func
|
|
images, blocks, parts = [], [], []
|
|
image_id, cursor = get_image_id_func(), 0
|
|
counters = defaultdict(dict)
|
|
try:
|
|
numbering = document.part.numbering_part.element
|
|
except Exception:
|
|
numbering = None
|
|
|
|
def number_prefix(paragraph):
|
|
if numbering is None:
|
|
return ''
|
|
prop = paragraph._p.find(qn('w:pPr'))
|
|
num = prop.find(qn('w:numPr')) if prop is not None else None
|
|
if num is None and paragraph.style is not None and paragraph.style.element.pPr is not None:
|
|
num = paragraph.style.element.pPr.find(qn('w:numPr'))
|
|
if num is None or num.find(qn('w:numId')) is None:
|
|
return ''
|
|
num_id = num.find(qn('w:numId')).get(qn('w:val'))
|
|
ilvl = num.find(qn('w:ilvl'))
|
|
depth = int(ilvl.get(qn('w:val'), '0')) if ilvl is not None else 0
|
|
instance = next((x for x in numbering.findall(qn('w:num')) if x.get(qn('w:numId')) == num_id), None)
|
|
abstract_id = instance.find(qn('w:abstractNumId')) if instance is not None else None
|
|
abstract = next((x for x in numbering.findall(qn('w:abstractNum')) if abstract_id is not None and x.get(qn('w:abstractNumId')) == abstract_id.get(qn('w:val'))), None)
|
|
if abstract is None:
|
|
return ''
|
|
levels = {int(x.get(qn('w:ilvl'))): x for x in abstract.findall(qn('w:lvl'))}
|
|
entry = levels.get(depth)
|
|
if entry is None:
|
|
return ''
|
|
fmt, template = entry.find(qn('w:numFmt')), entry.find(qn('w:lvlText'))
|
|
if fmt is None or template is None or fmt.get(qn('w:val')) != 'decimal':
|
|
return ''
|
|
start = entry.find(qn('w:start'))
|
|
counts = counters[num_id]
|
|
counts[depth] = counts.get(depth, int(start.get(qn('w:val'), '1')) - 1 if start is not None else 0) + 1
|
|
for key in list(counts):
|
|
if key > depth:
|
|
del counts[key]
|
|
return re.sub(r'%(\d)', lambda m: str(counts.get(int(m[1]) - 1, 1)), template.get(qn('w:val'), '')) + ' '
|
|
|
|
for element in document.element.body:
|
|
if element.tag.endswith('}tbl'):
|
|
rendered = handler.table_to_md(Table(element, document), document, images, image_id)
|
|
elif element.tag.endswith('}p'):
|
|
paragraph = Paragraph(element, document)
|
|
rendered = handler.paragraph_to_md(paragraph, document, images, image_id)
|
|
level, origin = word_level(paragraph)
|
|
prefix = number_prefix(paragraph)
|
|
if level and paragraph.text.strip():
|
|
first, *rest = rendered.split('\n')
|
|
first = re.sub(r'^#{1,9}\s+', '', first)
|
|
if prefix and not first.startswith(prefix.strip()):
|
|
first = prefix + first
|
|
rendered = '#' * level + ' ' + first + ('\n' + '\n'.join(rest) if rest else '')
|
|
elif prefix and paragraph.text.strip():
|
|
rendered = prefix + rendered
|
|
sizes = [run.font.size.pt for run in paragraph.runs if run.font.size is not None]
|
|
if not sizes and paragraph.style and paragraph.style.font.size:
|
|
sizes = [paragraph.style.font.size.pt]
|
|
first = re.sub(r'^#{1,6}\s+', '', rendered.split('\n')[0]).strip()
|
|
blocks.append({'text': first, 'line': cursor, 'kind': 'heading' if level else 'text',
|
|
'level': level, 'level_source': origin, 'font_size': median(sizes) if sizes else 0,
|
|
'bold': any(run.bold for run in paragraph.runs) or bool(paragraph.style and paragraph.style.font.bold),
|
|
'indent': paragraph.paragraph_format.left_indent.pt if paragraph.paragraph_format.left_indent else 0})
|
|
else:
|
|
continue
|
|
parts.append(rendered)
|
|
cursor += rendered.count('\n') + 1
|
|
capture(images)
|
|
return '\n'.join(parts), {'blocks': blocks}
|
|
|
|
|
|
def html_evidence(content):
|
|
from bs4 import BeautifulSoup
|
|
document = BeautifulSoup(content, 'html.parser')
|
|
blocks = [{'text': h.get_text(' ', strip=True), 'kind': 'heading',
|
|
'level': int(h.name[1]), 'level_source': 'html_heading'}
|
|
for h in document.find_all(re.compile(r'^h[1-6]$'))]
|
|
for p in document.find_all(['p', 'div']):
|
|
if p.find(['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']):
|
|
continue
|
|
style = p.get('style', '')
|
|
size = re.search(r'font-size\s*:\s*([\d.]+)\s*(pt|px)', style, re.I)
|
|
blocks.append({'text': p.get_text(' ', strip=True), 'kind': 'text',
|
|
'bold': bool(p.find(['strong', 'b'])) or bool(re.search(r'font-weight\s*:\s*(bold|[6-9]00)', style, re.I)),
|
|
'font_size': float(size[1]) * (.75 if size[2].lower() == 'px' else 1) if size else 0})
|
|
return {'blocks': blocks}
|
|
|
|
|
|
def pdf_markdown(content):
|
|
import fitz
|
|
parts, blocks = [], []
|
|
cursor = 0
|
|
with fitz.open(stream=content, filetype='pdf') as document:
|
|
bookmarks = [{'level': min(6, level), 'text': title, 'page': page - 1}
|
|
for level, title, page in document.get_toc() if 1 <= level and page >= 1]
|
|
for page in document:
|
|
for block in page.get_text('dict', sort=True)['blocks']:
|
|
if block.get('type') == 1 and block.get('image'):
|
|
image = base64.b64encode(block['image']).decode()
|
|
parts.append(' + ';base64,' + image + ')')
|
|
cursor += 1
|
|
continue
|
|
for line in block.get('lines', []):
|
|
spans = line.get('spans', [])
|
|
text = ''.join(s.get('text', '') for s in spans).strip()
|
|
if not text:
|
|
continue
|
|
blocks.append({'text': text, 'kind': 'text', 'line': cursor, 'page': page.number,
|
|
'bbox': list(line['bbox']), 'page_height': page.rect.height,
|
|
'font_size': median([s['size'] for s in spans] or [0]),
|
|
'bold': any(s.get('flags', 0) & 16 for s in spans)})
|
|
parts.append(text)
|
|
cursor += 1
|
|
parts.append('')
|
|
cursor += 1
|
|
parts.append('')
|
|
cursor += 1
|
|
# Keep the existing OCR fallback for PDFs without a text layer.
|
|
return ('\n'.join(parts) if blocks else None), {'blocks': blocks, 'bookmarks': bookmarks}
|