UnisKB/apps/system_manage/ai_hub.py

454 lines
22 KiB
Python
Raw 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.

"""AI hub business operations. Secrets never cross the browser boundary."""
from urllib.parse import urlsplit
from django.db import transaction
from rest_framework.exceptions import ValidationError, PermissionDenied, NotFound
from system_manage.models.ai_hub import AIParserResource, AIFlow, AIService, AITask, AIArtifact
MAX_TEXT = 2_000_000
MAX_INLINE_TEXT = MAX_TEXT + 140_000_000
MAX_FILE = 20 * 1024 * 1024
KINDS = {'parsers': AIParserResource, 'flows': AIFlow, 'services': AIService,
'tasks': AITask, 'artifacts': AIArtifact}
def admin(user):
from common.constants.permission_constants import RoleConstants
return user.role == str(RoleConstants.ADMIN.value)
def require_admin(user):
if not admin(user):
raise PermissionDenied('仅管理员可操作')
def visible(query, user):
# Sharing is explicit, with no implicit public access.
if admin(user):
return query
if query.model in (AIParserResource, AIService):
ids = [obj.id for obj in query if str(obj.owner_id) == str(user.id)
or str(user.id) in obj.allowed_users]
return query.filter(id__in=ids)
return query.filter(owner_id=user.id)
def one(kind, pk, workspace, user, edit=False):
from rest_framework.serializers import UUIDField
pk = UUIDField().run_validation(pk)
model = KINDS.get(kind)
if not model:
raise NotFound()
obj = visible(model.objects.filter(workspace_id=workspace), user).filter(id=pk).first()
if not obj:
raise NotFound('记录不存在或无权访问')
if edit and not admin(user) and str(obj.owner_id) != str(user.id):
raise PermissionDenied('无权修改')
return obj
def text(value, label, required=True, limit=MAX_TEXT):
if not isinstance(value, str) or len(value) > limit or (required and not value.strip()):
raise ValidationError(f'{label}无效')
return value
def integer(value, minimum, maximum, label):
if isinstance(value, bool) or not isinstance(value, int) or not minimum <= value <= maximum:
raise ValidationError(f'{label}无效')
return value
def users(value):
from users.models import User
if not isinstance(value, list) or len(value) > 500:
raise ValidationError('授权用户无效')
values = {str(item) for item in value}
try:
allowed = set(str(pk) for pk in User.objects.filter(id__in=values, is_active=True).values_list('id', flat=True))
except (ValueError, TypeError):
raise ValidationError('授权用户无效')
# Registration approval is enforced by the existing activation extension.
from users.models.user_manage_ext import UserActivationApplication
pending = set(str(pk) for pk in UserActivationApplication.objects.exclude(status='APPROVED').values_list('user_id', flat=True))
if values - (allowed - pending):
raise ValidationError('只能授权已激活且启用的用户')
return sorted(values)
def authorized_models(workspace, user):
from models_provider.models import Model
from system_manage.models import WorkspaceUserResourcePermission, AuthTargetType
query = Model.objects.filter(workspace_id=workspace, status='SUCCESS')
if not admin(user):
grants = WorkspaceUserResourcePermission.objects.filter(
workspace_id=workspace, user_id=user.id, auth_target_type=AuthTargetType.MODEL)
ids = [g.target for g in grants if 'VIEW' in g.permission_list]
query = query.filter(id__in=ids)
return query
def model_for(workspace, user, model_id):
from rest_framework.serializers import UUIDField
model_id = UUIDField().run_validation(model_id)
obj = authorized_models(workspace, user).filter(id=model_id, model_type='LLM').first()
if not obj:
raise PermissionDenied('模型不可用或未授权')
return obj
def serialize(obj, detail=False):
data = {'id': str(obj.id), 'name': obj.name, 'updated_at': obj.updated_at.isoformat()}
if isinstance(obj, AIParserResource):
data.update(enabled=obj.enabled, allowed_users=obj.allowed_users,
options=obj.options, credential_configured=bool(obj.credential))
# Only callers of admin management endpoints receive endpoint addresses.
elif isinstance(obj, AIFlow):
data.update(revision=obj.revision, nodes=obj.nodes)
elif isinstance(obj, AIService):
data.update(flow_id=str(obj.flow_id), enabled=obj.enabled, allowed_users=obj.allowed_users,
requests_per_minute=obj.requests_per_minute,
key_configured=bool(obj.key_hash), url=f'ai_hub/published/{obj.id}/run')
elif isinstance(obj, AITask):
from system_manage.ai_hub_progress import task_progress
data.update(status=obj.status, steps=obj.steps, error=obj.error, attempt=obj.attempt,
started_at=obj.started_at, finished_at=obj.finished_at)
if detail:
data.update(snapshot=obj.snapshot, result=obj.result, progress=task_progress(obj))
elif isinstance(obj, AIArtifact):
data.update(revision=obj.revision, layout=obj.layout, task_id=str(obj.task_id) if obj.task_id else None)
if detail:
data.update(original=obj.original, markdown=obj.markdown, history=obj.history)
return data
def parser_save(workspace, user, data, obj=None):
require_admin(user)
endpoint = text(data.get('endpoint', getattr(obj, 'endpoint', '')), '地址', limit=1024).rstrip('/')
parsed = urlsplit(endpoint)
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValidationError('解析服务地址无效')
obj = obj or AIParserResource(workspace_id=workspace, owner_id=user.id)
obj.name = text(data.get('name', obj.name), '名称', limit=128)
obj.endpoint = endpoint
if 'api_key' in data:
from common.utils.rsa_util import rsa_long_encrypt
key = text(data['api_key'], '密钥', required=False, limit=4096)
obj.credential = rsa_long_encrypt(key) if key else ''
enabled = data.get('enabled', obj.enabled)
if not isinstance(enabled, bool):
raise ValidationError('启用状态无效')
obj.enabled = enabled
if 'allowed_users' in data:
obj.allowed_users = users(data['allowed_users'])
options = data.get('options', obj.options)
if not isinstance(options, dict) or set(options) - {'backend', 'language', 'ocr', 'formula', 'table', 'protocol', 'tier'}:
raise ValidationError('解析参数无效')
if options.get('protocol', 'legacy') not in ('legacy', 'v1') or options.get('tier', 'standard') not in ('flash', 'basic', 'standard', 'advanced'):
raise ValidationError('解析接口或档位无效')
if options.get('backend', 'pipeline') not in ('pipeline', 'hybrid-auto-engine', 'vlm-auto-engine'):
raise ValidationError('不支持的解析后端')
if options.get('language', 'ch') not in ('ch', 'en', 'japan', 'korean', 'chinese_cht'):
raise ValidationError('识别语言无效')
if any(not isinstance(options[k], bool) for k in ('ocr', 'formula', 'table') if k in options):
raise ValidationError('解析参数无效')
obj.options = options
obj.save()
return obj
def parser_test(parser):
"""Probe the registered service API, without submitting files or returning service content."""
import time
import requests
from urllib.parse import urlunsplit
from common.utils.rsa_util import rsa_long_decrypt
parsed = urlsplit(parser.endpoint.rstrip('/'))
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password:
raise ValidationError('解析服务地址无效')
base_path = parsed.path
for suffix in ('/v1', '/api'):
if base_path.endswith(suffix):
base_path = base_path[:-len(suffix)]
break
url = urlunsplit((parsed.scheme, parsed.netloc, base_path + '/openapi.json', '', ''))
headers = {'Authorization': 'Bearer ' + rsa_long_decrypt(parser.credential)} if parser.credential else {}
started = time.monotonic()
try:
response = requests.get(url, headers=headers, timeout=(3, 7), allow_redirects=False)
if response.status_code != 200:
raise ValidationError(f'连接测试失败(HTTP {response.status_code})')
data = response.json()
except requests.RequestException as exc:
raise ValidationError('解析服务连接失败或超时') from exc
except ValueError as exc:
raise ValidationError('解析服务未返回有效接口定义') from exc
paths = data.get('paths') if isinstance(data, dict) else None
v1 = parser.options.get('protocol') == 'v1' or parsed.path.endswith('/v1')
suffix = '/tasks' if v1 else '/file_parse'
if not isinstance(paths, dict) or not any(path.endswith(suffix) and 'post' in methods
for path, methods in paths.items() if isinstance(methods, dict)):
raise ValidationError('未识别到对应的解析接口')
return {'connected': True, 'elapsed_ms': round((time.monotonic() - started) * 1000),
'message': '解析接口连接正常'}
def validate_nodes(workspace, user, nodes):
if not isinstance(nodes, list) or not 1 <= len(nodes) <= 3:
raise ValidationError('请选择处理节点')
types = [n.get('type') for n in nodes if isinstance(n, dict)]
if len(types) != len(nodes) or types[-1] != 'render' or len(set(types)) != len(types):
raise ValidationError('流程须以导图生成为终点,节点不可重复')
if types != [t for t in ('parse', 'organize', 'render') if t in types]:
raise ValidationError('节点顺序应为解析、整理、导图生成')
result = []
for node in nodes:
kind = node['type']
clean = {'type': kind}
if kind == 'parse':
parser = one('parsers', node.get('resource_id'), workspace, user)
if not parser.enabled:
raise ValidationError('解析服务已停用')
clean['resource_id'] = str(parser.id)
if kind == 'organize':
clean['model_id'] = str(model_for(workspace, user, node.get('model_id')).id)
clean['prompt'] = text(node.get('prompt', '保留事实、数值和原文语言,将以下文档整理成分级Markdown标题和要点。'), '提示词', limit=16000)
temperature = node.get('temperature', 0.2)
if isinstance(temperature, bool) or not isinstance(temperature, (int, float)) or not 0 <= temperature <= 2:
raise ValidationError('温度无效')
clean['temperature'] = temperature
result.append(clean)
return result
@transaction.atomic
def flow_create(workspace, user, data):
nodes = validate_nodes(workspace, user, data.get('nodes'))
# Every save is immutable; published services always reference a fixed row.
previous = one('flows', data['previous_id'], workspace, user, edit=True) if data.get('previous_id') else None
return AIFlow.objects.create(workspace_id=workspace, owner_id=user.id,
name=text(data.get('name'), '名称', limit=128), nodes=nodes,
revision=previous.revision + 1 if previous else 1)
@transaction.atomic
def service_create(workspace, user, data):
require_admin(user)
flow = one('flows', data.get('flow_id'), workspace, user)
validate_nodes(workspace, user, flow.nodes)
return AIService.objects.create(workspace_id=workspace, owner_id=user.id,
name=text(data.get('name'), '名称', limit=128), flow=flow,
allowed_users=users(data.get('allowed_users', [])),
requests_per_minute=integer(data.get('requests_per_minute', 20), 1, 600, '调用频率'))
def make_snapshot(workspace, user, nodes):
clean = validate_nodes(workspace, user, nodes)
for node in clean:
if node['type'] == 'parse':
parser = one('parsers', node['resource_id'], workspace, user)
node['options'] = dict(parser.options)
node['resource_version'] = parser.updated_at.isoformat()
if node['type'] == 'organize':
model = model_for(workspace, user, node['model_id'])
node.update(model_name=model.model_name, provider=model.provider, resource_version=model.update_time.isoformat())
return clean
@transaction.atomic
def submit(workspace, user, data, upload=None, service=None):
from users.models import User
current_user = User.objects.select_for_update().get(id=user.id)
if not current_user.is_active:
raise PermissionDenied('用户已停用')
if AITask.objects.filter(owner_id=user.id, status__in=['PENDING', 'RUNNING']).count() >= 10:
raise ValidationError('待处理任务已达上限')
if service:
if not service.enabled:
raise ValidationError('服务已停用')
nodes = service.flow.nodes
else:
nodes = one('flows', data['flow_id'], workspace, user).nodes if data.get('flow_id') else data.get('nodes')
snapshot = make_snapshot(workspace, user, nodes)
markdown = text(data.get('markdown', ''), '文档内容', required=False, limit=MAX_INLINE_TEXT)
if upload and upload.size > MAX_FILE:
raise ValidationError('文件不能超过20MB')
if upload and snapshot[0]['type'] != 'parse':
raise ValidationError('文件任务需要解析节点')
if not upload and snapshot[0]['type'] == 'parse':
raise ValidationError('请选择文件')
if not upload and not markdown.strip():
raise ValidationError('文档内容不能为空')
from system_manage.ai_hub_assets import asset_lock, normalize
with asset_lock():
markdown = text(normalize(markdown, workspace, user), '文档内容', required=False)
return AITask.objects.create(workspace_id=workspace, owner_id=user.id,
name=text(data.get('name') or (upload.name if upload else '导图任务'), '名称', limit=128), service=service,
snapshot={'nodes': snapshot, 'flow_id': str(service.flow_id) if service else data.get('flow_id'),
'flow_revision': service.flow.revision if service else None},
input_data={'markdown': markdown}, file_name=upload.name[:255] if upload else '',
file_data=upload.read() if upload else None)
@transaction.atomic
def artifact_save(workspace, user, data, obj=None):
if obj:
obj = AIArtifact.objects.select_for_update().get(pk=obj.pk)
if data.get('revision') != obj.revision:
raise ValidationError('内容已更新,请重新打开')
history = list(obj.history)
if len(history) >= 30:
raise ValidationError('修订已达30次,请另存为新图谱')
history.append({'revision': obj.revision, 'markdown': obj.markdown, 'layout': obj.layout,
'operator': str(user.id), 'updated_at': obj.updated_at.isoformat()})
obj.history = history
obj.revision += 1
else:
task = one('tasks', data['task_id'], workspace, user) if data.get('task_id') else None
if task and task.status != 'SUCCESS':
raise ValidationError('任务尚未成功')
obj = AIArtifact(workspace_id=workspace, owner_id=user.id, task=task,
original=task.result.get('original', '') if task else text(data.get('original', ''), '原始内容', False, MAX_INLINE_TEXT))
obj.name = text(data.get('name'), '名称', limit=128)
obj.markdown = text(data.get('markdown'), '修订内容', limit=MAX_INLINE_TEXT)
obj.layout = data.get('layout', 'tree')
if obj.layout not in ('tree', 'radial', 'horizontal', 'vertical'):
raise ValidationError('布局无效')
from system_manage.ai_hub_assets import asset_lock, normalize
with asset_lock():
obj.markdown = text(normalize(obj.markdown, workspace, user), '修订内容')
obj.original = text(normalize(obj.original, workspace, user), '原始内容', required=False)
for entry in obj.history:
entry['markdown'] = normalize(entry.get('markdown', ''), workspace, user)
obj.save()
return obj
def parse_file(parser, name, content, options=None, progress_callback=None):
import requests
from common.utils.rsa_util import rsa_long_decrypt
opts = options if options is not None else parser.options
headers = {'Authorization': 'Bearer ' + rsa_long_decrypt(parser.credential)} if parser.credential else {}
if opts.get('protocol') == 'v1' or parser.endpoint.rstrip('/').endswith('/v1'):
from system_manage.ai_hub_parser_v1 import parse
return parse(parser, name, content, opts, headers, progress_callback=progress_callback)
try:
response = requests.post(parser.endpoint + '/file_parse', files={'files': (name, content)}, headers=headers,
data={'backend': opts.get('backend', 'pipeline'), 'lang_list': opts.get('language', 'ch'),
'parse_method': 'ocr' if opts.get('ocr') else 'auto', 'return_md': 'true',
'return_middle_json': 'true', 'response_format_zip': 'false', 'return_images': 'true',
'formula_enable': str(opts.get('formula', True)).lower(),
'table_enable': str(opts.get('table', True)).lower()}, timeout=(10, 300), allow_redirects=False)
except Exception as exc:
raise ValidationError('解析服务连接失败或超时') from exc
if not 200 <= response.status_code < 300:
raise ValidationError('解析服务调用失败')
try:
payload = response.json()
except ValueError as exc:
raise ValidationError('解析服务返回格式无效') from exc
if not isinstance(payload, dict):
raise ValidationError('解析服务返回格式无效')
entries = payload.get('results', {})
if not isinstance(entries, dict) or len(entries) != 1:
raise ValidationError('解析结果格式无效')
result = next(iter(entries.values()))
if not isinstance(result, dict):
raise ValidationError('解析结果格式无效')
markdown = text(result.get('md_content'), '解析结果', limit=MAX_INLINE_TEXT)
return {'markdown': markdown, 'source': result.get('middle_json', {}), 'parser_id': str(parser.id),
'images': result.get('images', {})}
def markdown_tree(markdown):
"""Markdown转稳定ID结构树:标题层级、嵌套列表、表格;围栏内容不参与结构。"""
import re
root = {'id': 'root', 'text': '文档', 'children': []}
heading_stack = [(0, root)]
list_stack = []
fence = None
table_buffer, table_start = [], None
def container():
return list_stack[-1][1] if list_stack else heading_stack[-1][1]
def flush_table():
nonlocal table_buffer, table_start
if not table_buffer:
return
index, lines = table_start, table_buffer
table_buffer, table_start = [], None
def cells(raw):
return [cell.strip() for cell in raw.strip().strip('|').split('|')]
if len(lines) >= 2 and re.match(r'^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$', lines[1]):
headers = cells(lines[0])
aligns = []
for cell in cells(lines[1]):
left, right = cell.startswith(':'), cell.endswith(':')
aligns.append('center' if left and right else 'right' if right else 'left')
rows = [cells(raw) for raw in lines[2:]]
node = {'id': f'n{index}', 'type': 'table', 'text': '表格:' + '、'.join(headers),
'table': {'headers': headers, 'aligns': aligns, 'rows': rows,
'row_count': len(rows), 'column_count': len(headers)},
'children': []}
container()['children'].append(node)
else:
for offset, raw in enumerate(lines):
container()['children'].append({'id': f'n{index + offset}', 'text': raw.strip(), 'children': []})
list_pattern = re.compile(r'^(\s*)(?:([-*+])|(\d{1,9})[.)])\s+(.+)$')
for index, line in enumerate(markdown.splitlines()):
fence_match = re.match(r'^\s{0,3}(`{3,}|~{3,})', line)
if fence_match:
token = fence_match.group(1)
if fence is None:
fence = token
flush_table()
list_stack.clear()
elif token[0] == fence[0] and len(token) >= len(fence):
fence = None
continue
if fence:
continue
stripped = line.strip()
if stripped.startswith('|') and stripped.count('|') >= 2:
if table_start is None:
table_start = index
list_stack.clear()
table_buffer.append(line)
continue
flush_table()
if not stripped:
continue
heading = re.match(r'^\s{0,3}(#{1,6})\s+(.+)', line)
if heading:
level = len(heading.group(1))
list_stack.clear()
while heading_stack[-1][0] >= level:
heading_stack.pop()
node = {'id': f'n{index}', 'text': heading.group(2).rstrip('# ').strip(), 'children': []}
heading_stack[-1][1]['children'].append(node)
heading_stack.append((level, node))
continue
item = list_pattern.match(line)
if item:
indent = len(item.group(1).expandtabs(4))
while list_stack and list_stack[-1][0] >= indent:
list_stack.pop()
ordered = item.group(3)
node = {'id': f'n{index}', 'type': 'list-item',
'text': item.group(4).strip(),
'list': {'type': 'ol' if ordered else 'ul', 'index': int(ordered) if ordered else None},
'children': []}
container()['children'].append(node)
list_stack.append((indent, node))
continue
if line[:1].isspace() and list_stack:
list_stack[-1][1]['children'].append({'id': f'n{index}', 'text': stripped, 'children': []})
continue
list_stack.clear()
heading_stack[-1][1]['children'].append({'id': f'n{index}', 'text': stripped, 'children': []})
flush_table()
return root