完善: CSRF安全修复 + 后台任务管理 + 压测全模块覆盖 + 文档
This commit is contained in:
+121
@@ -0,0 +1,121 @@
|
||||
import zipfile
|
||||
import os
|
||||
import hashlib
|
||||
import re
|
||||
import io
|
||||
|
||||
|
||||
class DocxImageExtractor:
|
||||
"""从 docx 中提取图片到 uploads 目录,返回 Markdown"""
|
||||
|
||||
NS = {
|
||||
'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
|
||||
'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
|
||||
'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
|
||||
'pic': 'http://schemas.openxmlformats.org/drawingml/2006/picture',
|
||||
'wp': 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
|
||||
}
|
||||
RELS_NS = {'r': 'http://schemas.openxmlformats.org/package/2006/relationships'}
|
||||
|
||||
def __init__(self, upload_dir='uploads'):
|
||||
self.upload_dir = upload_dir
|
||||
os.makedirs(upload_dir, exist_ok=True)
|
||||
|
||||
def parse(self, data):
|
||||
"""解析 docx 文件,返回 Markdown 文本"""
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
||||
return self._process(z)
|
||||
except Exception as e:
|
||||
raise ValueError('docx 解析失败: {}'.format(e))
|
||||
|
||||
def _process(self, z):
|
||||
# 1. 解析 rels 建立 rId → 图片路径映射
|
||||
rels_xml = z.read('word/_rels/document.xml.rels').decode('utf-8')
|
||||
rId_to_target = {}
|
||||
for m in re.finditer(r'<Relationship\s+Id="([^"]+)"\s+Type="[^"]*image[^"]*"\s+Target="([^"]+)"', rels_xml):
|
||||
rId_to_target[m.group(1)] = m.group(2)
|
||||
for m in re.finditer(r'<Relationship\s+Type="[^"]*image[^"]*"\s+Target="([^"]+)"\s+Id="([^"]+)"', rels_xml):
|
||||
rId_to_target[m.group(2)] = m.group(1)
|
||||
|
||||
# 2. 提取所有图片到 uploads 目录,建立 rId → URL 映射
|
||||
rId_to_url = {}
|
||||
for rId, target in rId_to_target.items():
|
||||
media_path = 'word/' + target
|
||||
try:
|
||||
img_data = z.read(media_path)
|
||||
except KeyError:
|
||||
continue
|
||||
# 用 MD5 生成唯一文件名
|
||||
md5 = hashlib.md5(img_data).hexdigest()[:12]
|
||||
ext = target.rsplit('.', 1)[-1].lower() if '.' in target else 'png'
|
||||
safe_name = 'docx_{}.{}'.format(md5, ext)
|
||||
dest_path = os.path.join(self.upload_dir, safe_name)
|
||||
if not os.path.exists(dest_path):
|
||||
with open(dest_path, 'wb') as f:
|
||||
f.write(img_data)
|
||||
rId_to_url[rId] = '/uploads/' + safe_name
|
||||
|
||||
# 3. 解析 document.xml 生成 Markdown
|
||||
doc_xml = z.read('word/document.xml').decode('utf-8')
|
||||
return self._xml_to_markdown(doc_xml, rId_to_url)
|
||||
|
||||
def _xml_to_markdown(self, xml, rId_to_url):
|
||||
"""将 docx XML 转换为 Markdown"""
|
||||
lines = []
|
||||
# 提取所有段落
|
||||
paras = re.findall(r'<w:p\b[^>]*>.*?</w:p>', xml, re.DOTALL)
|
||||
|
||||
for para in paras:
|
||||
# 检查是否包含图片
|
||||
blip_match = re.search(r'<a:blip\s+r:embed="([^"]+)"', para)
|
||||
if blip_match:
|
||||
rId = blip_match.group(1)
|
||||
img_url = rId_to_url.get(rId)
|
||||
if img_url:
|
||||
lines.append(''.format(img_url))
|
||||
lines.append('')
|
||||
continue
|
||||
|
||||
# 提取文本
|
||||
texts = []
|
||||
for t in re.findall(r'<w:t[^>]*>([^<]+)</w:t>', para):
|
||||
texts.append(t)
|
||||
|
||||
if not texts:
|
||||
lines.append('')
|
||||
continue
|
||||
|
||||
text = ''.join(texts)
|
||||
|
||||
# 检查是否加粗
|
||||
is_bold = bool(re.search(r'<w:b\b', para))
|
||||
if is_bold:
|
||||
text = '**{}**'.format(text)
|
||||
|
||||
# 检查是否编号列表
|
||||
num_match = re.search(r'<w:numPr', para)
|
||||
if num_match:
|
||||
lines.append('1. ' + text)
|
||||
else:
|
||||
lines.append(text)
|
||||
|
||||
return '\n'.join(lines).strip()
|
||||
|
||||
|
||||
class XlsxToMarkdown:
|
||||
"""解析 xlsx 为 Markdown 表格(复用 xlsreader)"""
|
||||
def parse(self, data):
|
||||
from xlsreader import XLSXReader
|
||||
rows = XLSXReader().read(data)
|
||||
if not rows:
|
||||
return ''
|
||||
md_lines = []
|
||||
# 表头
|
||||
md_lines.append('| ' + ' | '.join(str(c) for c in rows[0]) + ' |')
|
||||
# 分隔行
|
||||
md_lines.append('| ' + ' | '.join('---' for _ in rows[0]) + ' |')
|
||||
# 数据行
|
||||
for row in rows[1:]:
|
||||
md_lines.append('| ' + ' | '.join(str(c) for c in row) + ' |')
|
||||
return '\n'.join(md_lines)
|
||||
Reference in New Issue
Block a user