2024-08-15 09:17:36 +08:00
|
|
|
#
|
2026-03-24 19:24:41 +08:00
|
|
|
# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
|
2024-08-15 09:17:36 +08:00
|
|
|
#
|
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
|
#
|
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
#
|
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
|
# limitations under the License
|
|
|
|
|
#
|
2026-04-27 03:52:22 +00:00
|
|
|
import logging
|
2024-08-15 09:17:36 +08:00
|
|
|
import re
|
2026-03-20 20:32:00 +08:00
|
|
|
|
|
|
|
|
from quart import make_response, request
|
|
|
|
|
|
2025-11-18 17:05:16 +08:00
|
|
|
from api.apps import current_user, login_required
|
2026-04-27 10:18:16 +08:00
|
|
|
from api.constants import IMG_BASE64_PREFIX
|
2026-04-21 18:55:30 +08:00
|
|
|
from api.db import FileType
|
2025-11-03 19:59:18 +08:00
|
|
|
from api.db.db_models import Task
|
2026-03-20 20:32:00 +08:00
|
|
|
from api.db.services.document_service import DocumentService, doc_upload_and_parse
|
2024-08-15 09:17:36 +08:00
|
|
|
from api.db.services.file2document_service import File2DocumentService
|
|
|
|
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
2025-11-03 19:59:18 +08:00
|
|
|
from api.db.services.task_service import TaskService, cancel_all_task_of
|
2024-12-12 16:38:03 +08:00
|
|
|
from api.utils.api_utils import (
|
|
|
|
|
get_data_error_result,
|
2025-05-19 14:54:06 +08:00
|
|
|
get_json_result,
|
2026-03-20 20:32:00 +08:00
|
|
|
get_request_json,
|
2025-05-19 14:54:06 +08:00
|
|
|
server_error_response,
|
2026-01-20 13:29:37 +08:00
|
|
|
validate_request,
|
2024-12-12 16:38:03 +08:00
|
|
|
)
|
2026-04-27 18:54:49 +08:00
|
|
|
from api.utils.web_utils import CONTENT_TYPE_MAP, apply_safe_file_response_headers
|
2025-11-06 09:36:38 +08:00
|
|
|
from common import settings
|
2026-04-27 15:19:41 +08:00
|
|
|
from common.constants import RetCode, TaskStatus
|
2026-04-27 10:18:16 +08:00
|
|
|
from common.misc_utils import thread_pool_exec
|
2026-04-09 11:17:38 +08:00
|
|
|
from rag.nlp import search
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
2025-05-19 14:54:06 +08:00
|
|
|
@manager.route("/thumbnails", methods=["GET"]) # noqa: F821
|
2024-11-15 17:30:56 +08:00
|
|
|
# @login_required
|
2024-08-15 09:17:36 +08:00
|
|
|
def thumbnails():
|
2025-07-30 12:56:59 +08:00
|
|
|
doc_ids = request.args.getlist("doc_ids")
|
2024-08-15 09:17:36 +08:00
|
|
|
if not doc_ids:
|
2025-11-04 15:12:53 +08:00
|
|
|
return get_json_result(data=False, message='Lack of "Document ID"', code=RetCode.ARGUMENT_ERROR)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
docs = DocumentService.get_thumbnails(doc_ids)
|
2024-10-11 16:10:27 +08:00
|
|
|
|
|
|
|
|
for doc_item in docs:
|
2025-05-19 14:54:06 +08:00
|
|
|
if doc_item["thumbnail"] and not doc_item["thumbnail"].startswith(IMG_BASE64_PREFIX):
|
|
|
|
|
doc_item["thumbnail"] = f"/v1/document/image/{doc_item['kb_id']}-{doc_item['thumbnail']}"
|
2024-10-11 16:10:27 +08:00
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
return get_json_result(data={d["id"]: d["thumbnail"] for d in docs})
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return server_error_response(e)
|
|
|
|
|
|
|
|
|
|
|
2025-05-19 14:54:06 +08:00
|
|
|
@manager.route("/change_status", methods=["POST"]) # noqa: F821
|
2024-08-15 09:17:36 +08:00
|
|
|
@login_required
|
2025-07-11 10:38:59 +08:00
|
|
|
@validate_request("doc_ids", "status")
|
2025-11-18 17:05:16 +08:00
|
|
|
async def change_status():
|
2025-12-01 14:24:06 +08:00
|
|
|
req = await get_request_json()
|
2025-07-11 10:38:59 +08:00
|
|
|
doc_ids = req.get("doc_ids", [])
|
|
|
|
|
status = str(req.get("status", ""))
|
2024-10-18 13:48:57 +08:00
|
|
|
|
2025-07-11 10:38:59 +08:00
|
|
|
if status not in ["0", "1"]:
|
2025-11-04 15:12:53 +08:00
|
|
|
return get_json_result(data=False, message='"Status" must be either 0 or 1!', code=RetCode.ARGUMENT_ERROR)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-07-11 10:38:59 +08:00
|
|
|
result = {}
|
2026-01-20 19:11:21 +08:00
|
|
|
has_error = False
|
2025-07-11 10:38:59 +08:00
|
|
|
for doc_id in doc_ids:
|
|
|
|
|
if not DocumentService.accessible(doc_id, current_user.id):
|
|
|
|
|
result[doc_id] = {"error": "No authorization."}
|
2026-01-20 19:11:21 +08:00
|
|
|
has_error = True
|
2025-07-11 10:38:59 +08:00
|
|
|
continue
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-07-11 10:38:59 +08:00
|
|
|
try:
|
|
|
|
|
e, doc = DocumentService.get_by_id(doc_id)
|
|
|
|
|
if not e:
|
|
|
|
|
result[doc_id] = {"error": "No authorization."}
|
2026-01-20 19:11:21 +08:00
|
|
|
has_error = True
|
2025-07-11 10:38:59 +08:00
|
|
|
continue
|
|
|
|
|
e, kb = KnowledgebaseService.get_by_id(doc.kb_id)
|
|
|
|
|
if not e:
|
2025-12-17 10:03:33 +08:00
|
|
|
result[doc_id] = {"error": "Can't find this dataset!"}
|
2026-01-20 19:11:21 +08:00
|
|
|
has_error = True
|
|
|
|
|
continue
|
|
|
|
|
current_status = str(doc.status)
|
|
|
|
|
if current_status == status:
|
|
|
|
|
result[doc_id] = {"status": status}
|
2025-07-11 10:38:59 +08:00
|
|
|
continue
|
|
|
|
|
if not DocumentService.update_by_id(doc_id, {"status": str(status)}):
|
|
|
|
|
result[doc_id] = {"error": "Database error (Document update)!"}
|
2026-01-20 19:11:21 +08:00
|
|
|
has_error = True
|
2025-07-11 10:38:59 +08:00
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
status_int = int(status)
|
2026-01-20 19:11:21 +08:00
|
|
|
if getattr(doc, "chunk_num", 0) > 0:
|
|
|
|
|
try:
|
|
|
|
|
ok = settings.docStoreConn.update(
|
|
|
|
|
{"doc_id": doc_id},
|
|
|
|
|
{"available_int": status_int},
|
|
|
|
|
search.index_name(kb.tenant_id),
|
|
|
|
|
doc.kb_id,
|
|
|
|
|
)
|
2026-04-27 03:52:22 +00:00
|
|
|
except Exception:
|
|
|
|
|
logging.exception(
|
|
|
|
|
"Document store update failed in change_status: doc_id=%s kb_id=%s status=%s",
|
|
|
|
|
doc_id, doc.kb_id, status_int,
|
|
|
|
|
)
|
|
|
|
|
result[doc_id] = {"error": "Document store update failed."}
|
2026-01-20 19:11:21 +08:00
|
|
|
has_error = True
|
|
|
|
|
continue
|
|
|
|
|
if not ok:
|
2026-04-27 03:52:22 +00:00
|
|
|
logging.warning(
|
|
|
|
|
"Document store update returned False in change_status: doc_id=%s kb_id=%s status=%s",
|
|
|
|
|
doc_id, doc.kb_id, status_int,
|
|
|
|
|
)
|
|
|
|
|
result[doc_id] = {"error": "Document store table missing or update failed."}
|
2026-01-20 19:11:21 +08:00
|
|
|
has_error = True
|
|
|
|
|
continue
|
2025-07-11 10:38:59 +08:00
|
|
|
result[doc_id] = {"status": status}
|
|
|
|
|
except Exception as e:
|
|
|
|
|
result[doc_id] = {"error": f"Internal server error: {str(e)}"}
|
2026-01-20 19:11:21 +08:00
|
|
|
has_error = True
|
2025-07-11 10:38:59 +08:00
|
|
|
|
2026-01-20 19:11:21 +08:00
|
|
|
if has_error:
|
|
|
|
|
return get_json_result(data=result, message="Partial failure", code=RetCode.SERVER_ERROR)
|
2025-07-11 10:38:59 +08:00
|
|
|
return get_json_result(data=result)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
2025-05-19 14:54:06 +08:00
|
|
|
@manager.route("/run", methods=["POST"]) # noqa: F821
|
2024-08-15 09:17:36 +08:00
|
|
|
@login_required
|
|
|
|
|
@validate_request("doc_ids", "run")
|
2025-11-18 17:05:16 +08:00
|
|
|
async def run():
|
2025-12-01 14:24:06 +08:00
|
|
|
req = await get_request_json()
|
Fix: Not within a request context (#12723)
### What problem does this PR solve?
ERROR 1819426 Unhandled exception during request
Traceback (most recent call last):
File
"/home/qinling/[github.com/infiniflow/ragflow/api/apps/document_app.py](http://github.com/infiniflow/ragflow/api/apps/document_app.py)",
line 639, in run
return await thread_pool_exec(_run_sync)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/common/misc_utils.py](http://github.com/infiniflow/ragflow/common/misc_utils.py)",
line 132, in thread_pool_exec
return await loop.run_in_executor(_thread_pool_executor(), func, *args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.12/asyncio/futures.py", line 287, in __await__
yield self # This tells Task to wait for completion.
^^^^^^^^^^
File "/usr/lib/python3.12/asyncio/tasks.py", line 385, in __wakeup
future.result()
File "/usr/lib/python3.12/asyncio/futures.py", line 203, in result
raise self._exception.with_traceback(self._exception_tb)
File "/usr/lib/python3.12/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/api/apps/document_app.py](http://github.com/infiniflow/ragflow/api/apps/document_app.py)",
line 593, in _run_sync
if not DocumentService.accessible(doc_id,
[current_user.id](http://current_user.id/)):
^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py](http://github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py)",
line 318, in __get__
obj = instance._get_current_object()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py](http://github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py)",
line 526, in _get_current_object
return get_name(local())
^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/api/apps/__init__.py](http://github.com/infiniflow/ragflow/api/apps/__init__.py)",
line 97, in _load_user
authorization = request.headers.get("Authorization")
^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py](http://github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py)",
line 318, in __get__
obj = instance._get_current_object()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py](http://github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py)",
line 519, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Not within a request context
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
2026-01-20 16:56:41 +08:00
|
|
|
uid = current_user.id
|
2024-08-15 09:17:36 +08:00
|
|
|
try:
|
2026-03-20 20:32:00 +08:00
|
|
|
|
2025-12-03 14:19:53 +08:00
|
|
|
def _run_sync():
|
|
|
|
|
for doc_id in req["doc_ids"]:
|
Fix: Not within a request context (#12723)
### What problem does this PR solve?
ERROR 1819426 Unhandled exception during request
Traceback (most recent call last):
File
"/home/qinling/[github.com/infiniflow/ragflow/api/apps/document_app.py](http://github.com/infiniflow/ragflow/api/apps/document_app.py)",
line 639, in run
return await thread_pool_exec(_run_sync)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/common/misc_utils.py](http://github.com/infiniflow/ragflow/common/misc_utils.py)",
line 132, in thread_pool_exec
return await loop.run_in_executor(_thread_pool_executor(), func, *args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.12/asyncio/futures.py", line 287, in __await__
yield self # This tells Task to wait for completion.
^^^^^^^^^^
File "/usr/lib/python3.12/asyncio/tasks.py", line 385, in __wakeup
future.result()
File "/usr/lib/python3.12/asyncio/futures.py", line 203, in result
raise self._exception.with_traceback(self._exception_tb)
File "/usr/lib/python3.12/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/api/apps/document_app.py](http://github.com/infiniflow/ragflow/api/apps/document_app.py)",
line 593, in _run_sync
if not DocumentService.accessible(doc_id,
[current_user.id](http://current_user.id/)):
^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py](http://github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py)",
line 318, in __get__
obj = instance._get_current_object()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py](http://github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py)",
line 526, in _get_current_object
return get_name(local())
^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/api/apps/__init__.py](http://github.com/infiniflow/ragflow/api/apps/__init__.py)",
line 97, in _load_user
authorization = request.headers.get("Authorization")
^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py](http://github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py)",
line 318, in __get__
obj = instance._get_current_object()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/home/qinling/[github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py](http://github.com/infiniflow/ragflow/.venv/lib/python3.12/site-packages/werkzeug/local.py)",
line 519, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Not within a request context
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
2026-01-20 16:56:41 +08:00
|
|
|
if not DocumentService.accessible(doc_id, uid):
|
2025-12-03 14:19:53 +08:00
|
|
|
return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
|
|
|
|
|
|
|
|
|
|
kb_table_num_map = {}
|
|
|
|
|
for id in req["doc_ids"]:
|
|
|
|
|
info = {"run": str(req["run"]), "progress": 0}
|
|
|
|
|
if str(req["run"]) == TaskStatus.RUNNING.value and req.get("delete", False):
|
|
|
|
|
info["progress_msg"] = ""
|
|
|
|
|
info["chunk_num"] = 0
|
|
|
|
|
info["token_num"] = 0
|
|
|
|
|
|
|
|
|
|
tenant_id = DocumentService.get_tenant_id(id)
|
|
|
|
|
if not tenant_id:
|
|
|
|
|
return get_data_error_result(message="Tenant not found!")
|
|
|
|
|
e, doc = DocumentService.get_by_id(id)
|
|
|
|
|
if not e:
|
|
|
|
|
return get_data_error_result(message="Document not found!")
|
|
|
|
|
|
|
|
|
|
if str(req["run"]) == TaskStatus.CANCEL.value:
|
2026-02-06 14:48:24 +08:00
|
|
|
tasks = list(TaskService.query(doc_id=id))
|
|
|
|
|
has_unfinished_task = any((task.progress or 0) < 1 for task in tasks)
|
|
|
|
|
if str(doc.run) in [TaskStatus.RUNNING.value, TaskStatus.CANCEL.value] or has_unfinished_task:
|
2025-12-03 14:19:53 +08:00
|
|
|
cancel_all_task_of(id)
|
|
|
|
|
else:
|
|
|
|
|
return get_data_error_result(message="Cannot cancel a task that is not in RUNNING status")
|
|
|
|
|
if all([("delete" not in req or req["delete"]), str(req["run"]) == TaskStatus.RUNNING.value, str(doc.run) == TaskStatus.DONE.value]):
|
|
|
|
|
DocumentService.clear_chunk_num_when_rerun(doc.id)
|
|
|
|
|
|
|
|
|
|
DocumentService.update_by_id(id, info)
|
|
|
|
|
if req.get("delete", False):
|
|
|
|
|
TaskService.filter_delete([Task.doc_id == id])
|
2025-12-25 21:18:13 +08:00
|
|
|
if settings.docStoreConn.index_exist(search.index_name(tenant_id), doc.kb_id):
|
2025-12-03 14:19:53 +08:00
|
|
|
settings.docStoreConn.delete({"doc_id": id}, search.index_name(tenant_id), doc.kb_id)
|
|
|
|
|
|
|
|
|
|
if str(req["run"]) == TaskStatus.RUNNING.value:
|
2025-12-25 19:01:22 +08:00
|
|
|
if req.get("apply_kb"):
|
|
|
|
|
e, kb = KnowledgebaseService.get_by_id(doc.kb_id)
|
|
|
|
|
if not e:
|
|
|
|
|
raise LookupError("Can't find this dataset!")
|
2026-01-08 16:11:50 +08:00
|
|
|
doc.parser_config["llm_id"] = kb.parser_config.get("llm_id")
|
2025-12-25 19:01:22 +08:00
|
|
|
doc.parser_config["enable_metadata"] = kb.parser_config.get("enable_metadata", False)
|
|
|
|
|
doc.parser_config["metadata"] = kb.parser_config.get("metadata", {})
|
|
|
|
|
DocumentService.update_parser_config(doc.id, doc.parser_config)
|
2025-12-03 14:19:53 +08:00
|
|
|
doc_dict = doc.to_dict()
|
|
|
|
|
DocumentService.run(tenant_id, doc_dict, kb_table_num_map)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-12-03 14:19:53 +08:00
|
|
|
return get_json_result(data=True)
|
2025-12-02 19:42:05 +08:00
|
|
|
|
2026-01-20 13:29:37 +08:00
|
|
|
return await thread_pool_exec(_run_sync)
|
2024-08-15 09:17:36 +08:00
|
|
|
except Exception as e:
|
|
|
|
|
return server_error_response(e)
|
|
|
|
|
|
2025-05-19 14:54:06 +08:00
|
|
|
@manager.route("/get/<doc_id>", methods=["GET"]) # noqa: F821
|
2026-02-09 19:52:52 +08:00
|
|
|
@login_required
|
2025-11-18 17:05:16 +08:00
|
|
|
async def get(doc_id):
|
2024-08-15 09:17:36 +08:00
|
|
|
try:
|
|
|
|
|
e, doc = DocumentService.get_by_id(doc_id)
|
|
|
|
|
if not e:
|
2024-11-05 11:02:31 +08:00
|
|
|
return get_data_error_result(message="Document not found!")
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2024-09-19 19:19:27 +08:00
|
|
|
b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
|
2026-01-20 13:29:37 +08:00
|
|
|
data = await thread_pool_exec(settings.STORAGE_IMPL.get, b, n)
|
2025-12-03 14:19:53 +08:00
|
|
|
response = await make_response(data)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-07-11 18:47:19 +08:00
|
|
|
ext = re.search(r"\.([^.]+)$", doc.name.lower())
|
|
|
|
|
ext = ext.group(1) if ext else None
|
2026-02-25 09:46:48 +08:00
|
|
|
content_type = None
|
2024-08-15 09:17:36 +08:00
|
|
|
if ext:
|
2026-02-25 09:46:48 +08:00
|
|
|
fallback_prefix = "image" if doc.type == FileType.VISUAL.value else "application"
|
|
|
|
|
content_type = CONTENT_TYPE_MAP.get(ext, f"{fallback_prefix}/{ext}")
|
|
|
|
|
apply_safe_file_response_headers(response, content_type, ext)
|
2024-08-15 09:17:36 +08:00
|
|
|
return response
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return server_error_response(e)
|
|
|
|
|
|
|
|
|
|
|
2025-11-14 19:52:11 +08:00
|
|
|
@manager.route("/download/<attachment_id>", methods=["GET"]) # noqa: F821
|
|
|
|
|
@login_required
|
2025-11-18 17:05:16 +08:00
|
|
|
async def download_attachment(attachment_id):
|
2025-11-14 19:52:11 +08:00
|
|
|
try:
|
|
|
|
|
ext = request.args.get("ext", "markdown")
|
2026-01-20 13:29:37 +08:00
|
|
|
data = await thread_pool_exec(settings.STORAGE_IMPL.get, current_user.id, attachment_id)
|
2025-11-18 17:05:16 +08:00
|
|
|
response = await make_response(data)
|
2026-02-25 09:46:48 +08:00
|
|
|
content_type = CONTENT_TYPE_MAP.get(ext, f"application/{ext}")
|
|
|
|
|
apply_safe_file_response_headers(response, content_type, ext)
|
2025-11-14 19:52:11 +08:00
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return server_error_response(e)
|
|
|
|
|
|
|
|
|
|
|
2025-05-19 14:54:06 +08:00
|
|
|
@manager.route("/change_parser", methods=["POST"]) # noqa: F821
|
2024-08-15 09:17:36 +08:00
|
|
|
@login_required
|
2025-10-09 12:36:19 +08:00
|
|
|
@validate_request("doc_id")
|
2025-11-18 17:05:16 +08:00
|
|
|
async def change_parser():
|
2025-12-01 14:24:06 +08:00
|
|
|
req = await get_request_json()
|
2024-10-18 13:48:57 +08:00
|
|
|
if not DocumentService.accessible(req["doc_id"], current_user.id):
|
2025-11-04 15:12:53 +08:00
|
|
|
return get_json_result(data=False, message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-10-09 12:36:19 +08:00
|
|
|
e, doc = DocumentService.get_by_id(req["doc_id"])
|
|
|
|
|
if not e:
|
|
|
|
|
return get_data_error_result(message="Document not found!")
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-10-09 12:36:19 +08:00
|
|
|
def reset_doc():
|
|
|
|
|
nonlocal doc
|
2025-10-14 15:49:05 +08:00
|
|
|
e = DocumentService.update_by_id(doc.id, {"pipeline_id": req["pipeline_id"], "parser_id": req["parser_id"], "progress": 0, "progress_msg": "", "run": TaskStatus.UNSTART.value})
|
2024-08-15 09:17:36 +08:00
|
|
|
if not e:
|
2024-11-05 11:02:31 +08:00
|
|
|
return get_data_error_result(message="Document not found!")
|
2024-08-15 09:17:36 +08:00
|
|
|
if doc.token_num > 0:
|
2025-07-07 14:11:47 +08:00
|
|
|
e = DocumentService.increment_chunk_num(doc.id, doc.kb_id, doc.token_num * -1, doc.chunk_num * -1, doc.process_duration * -1)
|
2024-08-15 09:17:36 +08:00
|
|
|
if not e:
|
2024-11-05 11:02:31 +08:00
|
|
|
return get_data_error_result(message="Document not found!")
|
2024-08-15 09:17:36 +08:00
|
|
|
tenant_id = DocumentService.get_tenant_id(req["doc_id"])
|
|
|
|
|
if not tenant_id:
|
2024-11-05 11:02:31 +08:00
|
|
|
return get_data_error_result(message="Tenant not found!")
|
2025-12-29 12:54:11 +08:00
|
|
|
DocumentService.delete_chunk_images(doc, tenant_id)
|
2025-12-25 21:18:13 +08:00
|
|
|
if settings.docStoreConn.index_exist(search.index_name(tenant_id), doc.kb_id):
|
2025-11-06 09:36:38 +08:00
|
|
|
settings.docStoreConn.delete({"doc_id": doc.id}, search.index_name(tenant_id), doc.kb_id)
|
2025-11-13 16:11:07 +08:00
|
|
|
return None
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-10-09 12:36:19 +08:00
|
|
|
try:
|
2025-10-09 19:03:12 +08:00
|
|
|
if "pipeline_id" in req and req["pipeline_id"] != "":
|
2025-10-09 12:36:19 +08:00
|
|
|
if doc.pipeline_id == req["pipeline_id"]:
|
|
|
|
|
return get_json_result(data=True)
|
|
|
|
|
DocumentService.update_by_id(doc.id, {"pipeline_id": req["pipeline_id"]})
|
|
|
|
|
reset_doc()
|
|
|
|
|
return get_json_result(data=True)
|
|
|
|
|
|
|
|
|
|
if doc.parser_id.lower() == req["parser_id"].lower():
|
|
|
|
|
if "parser_config" in req:
|
|
|
|
|
if req["parser_config"] == doc.parser_config:
|
|
|
|
|
return get_json_result(data=True)
|
|
|
|
|
else:
|
|
|
|
|
return get_json_result(data=True)
|
|
|
|
|
|
|
|
|
|
if (doc.type == FileType.VISUAL and req["parser_id"] != "picture") or (re.search(r"\.(ppt|pptx|pages)$", doc.name) and req["parser_id"] != "presentation"):
|
|
|
|
|
return get_data_error_result(message="Not supported yet!")
|
|
|
|
|
if "parser_config" in req:
|
|
|
|
|
DocumentService.update_parser_config(doc.id, req["parser_config"])
|
|
|
|
|
reset_doc()
|
2024-08-15 09:17:36 +08:00
|
|
|
return get_json_result(data=True)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return server_error_response(e)
|
|
|
|
|
|
|
|
|
|
|
2025-05-19 14:54:06 +08:00
|
|
|
@manager.route("/image/<image_id>", methods=["GET"]) # noqa: F821
|
2024-08-15 09:17:36 +08:00
|
|
|
# @login_required
|
2025-11-18 17:05:16 +08:00
|
|
|
async def get_image(image_id):
|
2024-08-15 09:17:36 +08:00
|
|
|
try:
|
2024-12-09 15:24:58 +08:00
|
|
|
arr = image_id.split("-")
|
|
|
|
|
if len(arr) != 2:
|
|
|
|
|
return get_data_error_result(message="Image not found.")
|
2024-08-15 09:17:36 +08:00
|
|
|
bkt, nm = image_id.split("-")
|
2026-01-20 13:29:37 +08:00
|
|
|
data = await thread_pool_exec(settings.STORAGE_IMPL.get, bkt, nm)
|
2025-12-03 14:19:53 +08:00
|
|
|
response = await make_response(data)
|
2025-05-19 14:54:06 +08:00
|
|
|
response.headers.set("Content-Type", "image/JPEG")
|
2024-08-15 09:17:36 +08:00
|
|
|
return response
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return server_error_response(e)
|
|
|
|
|
|
|
|
|
|
|
2025-05-19 14:54:06 +08:00
|
|
|
@manager.route("/upload_and_parse", methods=["POST"]) # noqa: F821
|
2024-08-15 09:17:36 +08:00
|
|
|
@login_required
|
|
|
|
|
@validate_request("conversation_id")
|
2025-11-18 17:05:16 +08:00
|
|
|
async def upload_and_parse():
|
2025-11-28 19:25:32 +08:00
|
|
|
files = await request.files
|
2025-11-18 17:05:16 +08:00
|
|
|
if "file" not in files:
|
2025-11-04 15:12:53 +08:00
|
|
|
return get_json_result(data=False, message="No file part!", code=RetCode.ARGUMENT_ERROR)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-11-18 17:05:16 +08:00
|
|
|
file_objs = files.getlist("file")
|
2024-08-15 09:17:36 +08:00
|
|
|
for file_obj in file_objs:
|
2025-05-19 14:54:06 +08:00
|
|
|
if file_obj.filename == "":
|
2025-11-04 15:12:53 +08:00
|
|
|
return get_json_result(data=False, message="No file selected!", code=RetCode.ARGUMENT_ERROR)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
2025-11-18 17:05:16 +08:00
|
|
|
form = await request.form
|
|
|
|
|
doc_ids = doc_upload_and_parse(form.get("conversation_id"), file_objs, current_user.id)
|
2024-08-15 19:30:43 +08:00
|
|
|
return get_json_result(data=doc_ids)
|