UnisKB/apps/system_manage/parsers/legacy.py

73 lines
4.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Official MinerU 2.x sync HTTP, executed inside the Hub's durable background task."""
import json
import re
import time
import requests
from rest_framework.exceptions import ValidationError
def parse(parser, name, content, options, headers, progress_callback=None):
from system_manage.ai_hub import text, MAX_INLINE_TEXT
if progress_callback:
progress_callback({'stage': 'MinerU 正在解析文档', 'percent': None})
backend = options.get('backend', 'pipeline')
if options.get('engine_version') == '3.4.5':
backend = {'hybrid-auto-engine': 'hybrid-engine', 'vlm-auto-engine': 'vlm-engine'}.get(backend, backend)
fields = {'backend': backend, 'lang_list': options.get('language', 'ch'),
'parse_method': 'ocr' if options.get('ocr') else 'auto', 'return_md': 'true',
'return_middle_json': 'true', 'response_format_zip': 'false', 'return_images': 'true',
'formula_enable': str(options.get('formula', True)).lower(),
'table_enable': str(options.get('table', True)).lower()}
if backend.endswith('-http-client'):
fields['server_url'] = options['server_url']
if options.get('engine_version') == '3.4.5':
fields['effort'] = options.get('effort', 'medium')
try:
response = requests.post(parser.endpoint.rstrip('/') + '/file_parse', files={'files': (name, content)}, headers=headers,
data=fields, timeout=(10, 300), allow_redirects=False)
except requests.RequestException as exc:
raise ValidationError('解析服务连接失败或超时') from exc
if response.status_code == 202 and options.get('engine_version') == '3.4.5':
try:
task_id = response.json().get('task_id')
if not isinstance(task_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,128}', task_id):
raise ValidationError('解析服务返回任务 ID 无效')
deadline = time.monotonic() + 300
while response.status_code == 202:
if time.monotonic() >= deadline:
raise ValidationError('解析等待超时,后台任务 ID:' + task_id)
if progress_callback:
progress_callback({'stage': '等待远程解析完成', 'percent': None})
time.sleep(2)
response = requests.get(parser.endpoint.rstrip('/') + '/tasks/' + task_id + '/result',
headers=headers, timeout=(10, 30), allow_redirects=False)
except requests.RequestException as exc:
raise ValidationError('解析服务连接失败或超时') from exc
except ValueError as exc:
raise ValidationError('解析任务响应无效') from exc
if response.status_code != 200:
raise ValidationError(f'解析服务调用失败(HTTP {response.status_code})')
try:
payload = response.json()
except ValueError as exc:
raise ValidationError('解析服务返回格式无效') from exc
entries = payload.get('results') if isinstance(payload, dict) else None
if not isinstance(entries, dict) or len(entries) != 1:
raise ValidationError('解析结果格式无效')
result = next(iter(entries.values()))
if not isinstance(result, dict):
raise ValidationError('解析结果格式无效')
middle = result.get('middle_json') or {}
if isinstance(middle, str):
try:
middle = json.loads(middle)
except ValueError as exc:
raise ValidationError('解析结构数据无效') from exc
if not isinstance(middle, dict):
raise ValidationError('解析结构数据无效')
if progress_callback:
progress_callback({'stage': '整理解析结果和图片', 'percent': None})
return {'markdown': text(result.get('md_content'), '解析结果', limit=MAX_INLINE_TEXT),
'source': {'version': payload.get('version', ''), 'backend': payload.get('backend', ''), 'middle_json': middle},
'parser_id': str(parser.id), 'images': result.get('images', {})}