60 lines
3.1 KiB
Python
60 lines
3.1 KiB
Python
"""MinerU v1 task API adapter. Only follows paths built from the registered endpoint."""
|
||
import re
|
||
import time
|
||
import requests
|
||
from rest_framework.exceptions import ValidationError
|
||
|
||
|
||
def _json(response):
|
||
if response.status_code not in (200, 201, 202):
|
||
raise ValidationError(f'解析服务调用失败(HTTP {response.status_code})')
|
||
try:
|
||
body = response.json()
|
||
except ValueError as exc:
|
||
raise ValidationError('解析服务返回格式无效') from exc
|
||
if not isinstance(body, dict):
|
||
raise ValidationError('解析服务返回格式无效')
|
||
return body
|
||
|
||
|
||
def parse(parser, name, content, options, headers, progress_callback=None):
|
||
from system_manage.ai_hub import text, MAX_INLINE_TEXT
|
||
endpoint = parser.endpoint.rstrip('/')
|
||
deadline = time.monotonic() + 300
|
||
try:
|
||
response = requests.post(endpoint + '/tasks', files={'files': (name, content)}, headers=headers,
|
||
params=[('tier', options.get('tier', 'standard')), ('ocr_mode', 'ocr' if options.get('ocr') else 'auto'),
|
||
('output_formats', 'markdown'), ('output_formats', 'middle_json')],
|
||
timeout=(10, 30), allow_redirects=False)
|
||
task = _json(response)
|
||
from system_manage.ai_hub_progress import parser_progress
|
||
task_id = task.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')
|
||
if progress_callback:
|
||
progress_callback(parser_progress(task))
|
||
while task.get('status') in ('queued', 'running'):
|
||
if time.monotonic() >= deadline:
|
||
raise ValidationError('解析等待超时,后台任务ID:' + task_id)
|
||
time.sleep(2)
|
||
task = _json(requests.get(endpoint + '/tasks/' + task_id, headers=headers,
|
||
timeout=(10, 20), allow_redirects=False))
|
||
if progress_callback:
|
||
progress_callback(parser_progress(task))
|
||
if task.get('status') != 'completed':
|
||
raise ValidationError('解析任务未成功,后台任务ID:' + task_id)
|
||
result = _json(requests.get(endpoint + '/tasks/' + task_id + '/result', headers=headers,
|
||
timeout=(10, 30), allow_redirects=False))
|
||
except requests.RequestException as exc:
|
||
raise ValidationError('解析服务连接失败或超时') from exc
|
||
files = result.get('files', [])
|
||
if not isinstance(files, list) or len(files) != 1 or not isinstance(files[0], dict) or files[0].get('status') != 'completed':
|
||
raise ValidationError('解析文件结果无效')
|
||
output = files[0].get('content', {})
|
||
if not isinstance(output, dict):
|
||
raise ValidationError('解析文件内容无效')
|
||
markdown = text(output.get('markdown'), '解析结果', limit=MAX_INLINE_TEXT)
|
||
return {'markdown': markdown, 'parser_id': str(parser.id), 'images': output.get('images', {}),
|
||
'source': {'task_id': task_id, 'parse': files[0].get('parse'),
|
||
'middle_json': output.get('middle_json', {})}}
|