document.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import json
  2. from flask import request
  3. from flask_restful import marshal, reqparse # type: ignore
  4. from sqlalchemy import desc
  5. from werkzeug.exceptions import NotFound
  6. import services.dataset_service
  7. from controllers.common.errors import FilenameNotExistsError
  8. from controllers.service_api import api
  9. from controllers.service_api.app.error import (
  10. FileTooLargeError,
  11. NoFileUploadedError,
  12. ProviderNotInitializeError,
  13. TooManyFilesError,
  14. UnsupportedFileTypeError,
  15. )
  16. from controllers.service_api.dataset.error import (
  17. ArchivedDocumentImmutableError,
  18. DocumentIndexingError,
  19. InvalidMetadataError,
  20. )
  21. from controllers.service_api.wraps import DatasetApiResource, cloud_edition_billing_resource_check
  22. from core.errors.error import ProviderTokenNotInitError
  23. from extensions.ext_database import db
  24. from fields.document_fields import document_fields, document_status_fields
  25. from libs.login import current_user
  26. from models.dataset import Dataset, Document, DocumentSegment
  27. from services.dataset_service import DocumentService
  28. from services.entities.knowledge_entities.knowledge_entities import KnowledgeConfig
  29. from services.file_service import FileService
  30. class DocumentAddByTextApi(DatasetApiResource):
  31. """Resource for documents."""
  32. @cloud_edition_billing_resource_check("vector_space", "dataset")
  33. @cloud_edition_billing_resource_check("documents", "dataset")
  34. def post(self, tenant_id, dataset_id):
  35. """Create document by text."""
  36. parser = reqparse.RequestParser()
  37. parser.add_argument("name", type=str, required=True, nullable=False, location="json")
  38. parser.add_argument("text", type=str, required=True, nullable=False, location="json")
  39. parser.add_argument("process_rule", type=dict, required=False, nullable=True, location="json")
  40. parser.add_argument("original_document_id", type=str, required=False, location="json")
  41. parser.add_argument("doc_form", type=str, default="text_model", required=False, nullable=False, location="json")
  42. parser.add_argument(
  43. "doc_language", type=str, default="English", required=False, nullable=False, location="json"
  44. )
  45. parser.add_argument(
  46. "indexing_technique", type=str, choices=Dataset.INDEXING_TECHNIQUE_LIST, nullable=False, location="json"
  47. )
  48. parser.add_argument("retrieval_model", type=dict, required=False, nullable=False, location="json")
  49. parser.add_argument("doc_type", type=str, required=False, nullable=True, location="json")
  50. parser.add_argument("doc_metadata", type=dict, required=False, nullable=True, location="json")
  51. args = parser.parse_args()
  52. dataset_id = str(dataset_id)
  53. tenant_id = str(tenant_id)
  54. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  55. if not dataset:
  56. raise ValueError("Dataset is not exist.")
  57. if not dataset.indexing_technique and not args["indexing_technique"]:
  58. raise ValueError("indexing_technique is required.")
  59. # Validate metadata if provided
  60. if args.get("doc_type") or args.get("doc_metadata"):
  61. if not args.get("doc_type") or not args.get("doc_metadata"):
  62. raise InvalidMetadataError("Both doc_type and doc_metadata must be provided when adding metadata")
  63. if args["doc_type"] not in DocumentService.DOCUMENT_METADATA_SCHEMA:
  64. raise InvalidMetadataError(
  65. "Invalid doc_type. Must be one of: " + ", ".join(DocumentService.DOCUMENT_METADATA_SCHEMA.keys())
  66. )
  67. if not isinstance(args["doc_metadata"], dict):
  68. raise InvalidMetadataError("doc_metadata must be a dictionary")
  69. # Validate metadata schema based on doc_type
  70. if args["doc_type"] != "others":
  71. metadata_schema = DocumentService.DOCUMENT_METADATA_SCHEMA[args["doc_type"]]
  72. for key, value in args["doc_metadata"].items():
  73. if key in metadata_schema and not isinstance(value, metadata_schema[key]):
  74. raise InvalidMetadataError(f"Invalid type for metadata field {key}")
  75. # set to MetaDataConfig
  76. args["metadata"] = {"doc_type": args["doc_type"], "doc_metadata": args["doc_metadata"]}
  77. text = args.get("text")
  78. name = args.get("name")
  79. if text is None or name is None:
  80. raise ValueError("Both 'text' and 'name' must be non-null values.")
  81. upload_file = FileService.upload_text(text=str(text), text_name=str(name))
  82. data_source = {
  83. "type": "upload_file",
  84. "info_list": {"data_source_type": "upload_file", "file_info_list": {"file_ids": [upload_file.id]}},
  85. }
  86. args["data_source"] = data_source
  87. knowledge_config = KnowledgeConfig(**args)
  88. # validate args
  89. DocumentService.document_create_args_validate(knowledge_config)
  90. try:
  91. documents, batch = DocumentService.save_document_with_dataset_id(
  92. dataset=dataset,
  93. knowledge_config=knowledge_config,
  94. account=current_user,
  95. dataset_process_rule=dataset.latest_process_rule if "process_rule" not in args else None,
  96. created_from="api",
  97. )
  98. except ProviderTokenNotInitError as ex:
  99. raise ProviderNotInitializeError(ex.description)
  100. document = documents[0]
  101. documents_and_batch_fields = {"document": marshal(document, document_fields), "batch": batch}
  102. return documents_and_batch_fields, 200
  103. class DocumentUpdateByTextApi(DatasetApiResource):
  104. """Resource for update documents."""
  105. @cloud_edition_billing_resource_check("vector_space", "dataset")
  106. def post(self, tenant_id, dataset_id, document_id):
  107. """Update document by text."""
  108. parser = reqparse.RequestParser()
  109. parser.add_argument("name", type=str, required=False, nullable=True, location="json")
  110. parser.add_argument("text", type=str, required=False, nullable=True, location="json")
  111. parser.add_argument("process_rule", type=dict, required=False, nullable=True, location="json")
  112. parser.add_argument("doc_form", type=str, default="text_model", required=False, nullable=False, location="json")
  113. parser.add_argument(
  114. "doc_language", type=str, default="English", required=False, nullable=False, location="json"
  115. )
  116. parser.add_argument("retrieval_model", type=dict, required=False, nullable=False, location="json")
  117. parser.add_argument("doc_type", type=str, required=False, nullable=True, location="json")
  118. parser.add_argument("doc_metadata", type=dict, required=False, nullable=True, location="json")
  119. args = parser.parse_args()
  120. dataset_id = str(dataset_id)
  121. tenant_id = str(tenant_id)
  122. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  123. if not dataset:
  124. raise ValueError("Dataset is not exist.")
  125. # indexing_technique is already set in dataset since this is an update
  126. args["indexing_technique"] = dataset.indexing_technique
  127. # Validate metadata if provided
  128. if args.get("doc_type") or args.get("doc_metadata"):
  129. if not args.get("doc_type") or not args.get("doc_metadata"):
  130. raise InvalidMetadataError("Both doc_type and doc_metadata must be provided when adding metadata")
  131. if args["doc_type"] not in DocumentService.DOCUMENT_METADATA_SCHEMA:
  132. raise InvalidMetadataError(
  133. "Invalid doc_type. Must be one of: " + ", ".join(DocumentService.DOCUMENT_METADATA_SCHEMA.keys())
  134. )
  135. if not isinstance(args["doc_metadata"], dict):
  136. raise InvalidMetadataError("doc_metadata must be a dictionary")
  137. # Validate metadata schema based on doc_type
  138. if args["doc_type"] != "others":
  139. metadata_schema = DocumentService.DOCUMENT_METADATA_SCHEMA[args["doc_type"]]
  140. for key, value in args["doc_metadata"].items():
  141. if key in metadata_schema and not isinstance(value, metadata_schema[key]):
  142. raise InvalidMetadataError(f"Invalid type for metadata field {key}")
  143. # set to MetaDataConfig
  144. args["metadata"] = {"doc_type": args["doc_type"], "doc_metadata": args["doc_metadata"]}
  145. if args["text"]:
  146. text = args.get("text")
  147. name = args.get("name")
  148. if text is None or name is None:
  149. raise ValueError("Both text and name must be strings.")
  150. upload_file = FileService.upload_text(text=str(text), text_name=str(name))
  151. data_source = {
  152. "type": "upload_file",
  153. "info_list": {"data_source_type": "upload_file", "file_info_list": {"file_ids": [upload_file.id]}},
  154. }
  155. args["data_source"] = data_source
  156. # validate args
  157. args["original_document_id"] = str(document_id)
  158. knowledge_config = KnowledgeConfig(**args)
  159. DocumentService.document_create_args_validate(knowledge_config)
  160. try:
  161. documents, batch = DocumentService.save_document_with_dataset_id(
  162. dataset=dataset,
  163. knowledge_config=knowledge_config,
  164. account=current_user,
  165. dataset_process_rule=dataset.latest_process_rule if "process_rule" not in args else None,
  166. created_from="api",
  167. )
  168. except ProviderTokenNotInitError as ex:
  169. raise ProviderNotInitializeError(ex.description)
  170. document = documents[0]
  171. documents_and_batch_fields = {"document": marshal(document, document_fields), "batch": batch}
  172. return documents_and_batch_fields, 200
  173. class DocumentAddByFileApi(DatasetApiResource):
  174. """Resource for documents."""
  175. @cloud_edition_billing_resource_check("vector_space", "dataset")
  176. @cloud_edition_billing_resource_check("documents", "dataset")
  177. def post(self, tenant_id, dataset_id):
  178. """Create document by upload file."""
  179. args = {}
  180. if "data" in request.form:
  181. args = json.loads(request.form["data"])
  182. if "doc_form" not in args:
  183. args["doc_form"] = "text_model"
  184. if "doc_language" not in args:
  185. args["doc_language"] = "English"
  186. # Validate metadata if provided
  187. if args.get("doc_type") or args.get("doc_metadata"):
  188. if not args.get("doc_type") or not args.get("doc_metadata"):
  189. raise InvalidMetadataError("Both doc_type and doc_metadata must be provided when adding metadata")
  190. if args["doc_type"] not in DocumentService.DOCUMENT_METADATA_SCHEMA:
  191. raise InvalidMetadataError(
  192. "Invalid doc_type. Must be one of: " + ", ".join(DocumentService.DOCUMENT_METADATA_SCHEMA.keys())
  193. )
  194. if not isinstance(args["doc_metadata"], dict):
  195. raise InvalidMetadataError("doc_metadata must be a dictionary")
  196. # Validate metadata schema based on doc_type
  197. if args["doc_type"] != "others":
  198. metadata_schema = DocumentService.DOCUMENT_METADATA_SCHEMA[args["doc_type"]]
  199. for key, value in args["doc_metadata"].items():
  200. if key in metadata_schema and not isinstance(value, metadata_schema[key]):
  201. raise InvalidMetadataError(f"Invalid type for metadata field {key}")
  202. # set to MetaDataConfig
  203. args["metadata"] = {"doc_type": args["doc_type"], "doc_metadata": args["doc_metadata"]}
  204. # get dataset info
  205. dataset_id = str(dataset_id)
  206. tenant_id = str(tenant_id)
  207. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  208. if not dataset:
  209. raise ValueError("Dataset is not exist.")
  210. if not dataset.indexing_technique and not args.get("indexing_technique"):
  211. raise ValueError("indexing_technique is required.")
  212. # save file info
  213. file = request.files["file"]
  214. # check file
  215. if "file" not in request.files:
  216. raise NoFileUploadedError()
  217. if len(request.files) > 1:
  218. raise TooManyFilesError()
  219. if not file.filename:
  220. raise FilenameNotExistsError
  221. upload_file = FileService.upload_file(
  222. filename=file.filename,
  223. content=file.read(),
  224. mimetype=file.mimetype,
  225. user=current_user,
  226. source="datasets",
  227. )
  228. data_source = {
  229. "type": "upload_file",
  230. "info_list": {"data_source_type": "upload_file", "file_info_list": {"file_ids": [upload_file.id]}},
  231. }
  232. args["data_source"] = data_source
  233. # validate args
  234. knowledge_config = KnowledgeConfig(**args)
  235. DocumentService.document_create_args_validate(knowledge_config)
  236. try:
  237. documents, batch = DocumentService.save_document_with_dataset_id(
  238. dataset=dataset,
  239. knowledge_config=knowledge_config,
  240. account=dataset.created_by_account,
  241. dataset_process_rule=dataset.latest_process_rule if "process_rule" not in args else None,
  242. created_from="api",
  243. )
  244. except ProviderTokenNotInitError as ex:
  245. raise ProviderNotInitializeError(ex.description)
  246. document = documents[0]
  247. documents_and_batch_fields = {"document": marshal(document, document_fields), "batch": batch}
  248. return documents_and_batch_fields, 200
  249. class DocumentUpdateByFileApi(DatasetApiResource):
  250. """Resource for update documents."""
  251. @cloud_edition_billing_resource_check("vector_space", "dataset")
  252. def post(self, tenant_id, dataset_id, document_id):
  253. """Update document by upload file."""
  254. args = {}
  255. if "data" in request.form:
  256. args = json.loads(request.form["data"])
  257. if "doc_form" not in args:
  258. args["doc_form"] = "text_model"
  259. if "doc_language" not in args:
  260. args["doc_language"] = "English"
  261. # Validate metadata if provided
  262. if args.get("doc_type") or args.get("doc_metadata"):
  263. if not args.get("doc_type") or not args.get("doc_metadata"):
  264. raise InvalidMetadataError("Both doc_type and doc_metadata must be provided when adding metadata")
  265. if args["doc_type"] not in DocumentService.DOCUMENT_METADATA_SCHEMA:
  266. raise InvalidMetadataError(
  267. "Invalid doc_type. Must be one of: " + ", ".join(DocumentService.DOCUMENT_METADATA_SCHEMA.keys())
  268. )
  269. if not isinstance(args["doc_metadata"], dict):
  270. raise InvalidMetadataError("doc_metadata must be a dictionary")
  271. # Validate metadata schema based on doc_type
  272. if args["doc_type"] != "others":
  273. metadata_schema = DocumentService.DOCUMENT_METADATA_SCHEMA[args["doc_type"]]
  274. for key, value in args["doc_metadata"].items():
  275. if key in metadata_schema and not isinstance(value, metadata_schema[key]):
  276. raise InvalidMetadataError(f"Invalid type for metadata field {key}")
  277. # set to MetaDataConfig
  278. args["metadata"] = {"doc_type": args["doc_type"], "doc_metadata": args["doc_metadata"]}
  279. # get dataset info
  280. dataset_id = str(dataset_id)
  281. tenant_id = str(tenant_id)
  282. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  283. if not dataset:
  284. raise ValueError("Dataset is not exist.")
  285. # indexing_technique is already set in dataset since this is an update
  286. args["indexing_technique"] = dataset.indexing_technique
  287. if "file" in request.files:
  288. # save file info
  289. file = request.files["file"]
  290. if len(request.files) > 1:
  291. raise TooManyFilesError()
  292. if not file.filename:
  293. raise FilenameNotExistsError
  294. try:
  295. upload_file = FileService.upload_file(
  296. filename=file.filename,
  297. content=file.read(),
  298. mimetype=file.mimetype,
  299. user=current_user,
  300. source="datasets",
  301. )
  302. except services.errors.file.FileTooLargeError as file_too_large_error:
  303. raise FileTooLargeError(file_too_large_error.description)
  304. except services.errors.file.UnsupportedFileTypeError:
  305. raise UnsupportedFileTypeError()
  306. data_source = {
  307. "type": "upload_file",
  308. "info_list": {"data_source_type": "upload_file", "file_info_list": {"file_ids": [upload_file.id]}},
  309. }
  310. args["data_source"] = data_source
  311. # validate args
  312. args["original_document_id"] = str(document_id)
  313. knowledge_config = KnowledgeConfig(**args)
  314. DocumentService.document_create_args_validate(knowledge_config)
  315. try:
  316. documents, batch = DocumentService.save_document_with_dataset_id(
  317. dataset=dataset,
  318. knowledge_config=knowledge_config,
  319. account=dataset.created_by_account,
  320. dataset_process_rule=dataset.latest_process_rule if "process_rule" not in args else None,
  321. created_from="api",
  322. )
  323. except ProviderTokenNotInitError as ex:
  324. raise ProviderNotInitializeError(ex.description)
  325. document = documents[0]
  326. documents_and_batch_fields = {"document": marshal(document, document_fields), "batch": document.batch}
  327. return documents_and_batch_fields, 200
  328. class DocumentDeleteApi(DatasetApiResource):
  329. def delete(self, tenant_id, dataset_id, document_id):
  330. """Delete document."""
  331. document_id = str(document_id)
  332. dataset_id = str(dataset_id)
  333. tenant_id = str(tenant_id)
  334. # get dataset info
  335. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  336. if not dataset:
  337. raise ValueError("Dataset is not exist.")
  338. document = DocumentService.get_document(dataset.id, document_id)
  339. # 404 if document not found
  340. if document is None:
  341. raise NotFound("Document Not Exists.")
  342. # 403 if document is archived
  343. if DocumentService.check_archived(document):
  344. raise ArchivedDocumentImmutableError()
  345. try:
  346. # delete document
  347. DocumentService.delete_document(document)
  348. except services.errors.document.DocumentIndexingError:
  349. raise DocumentIndexingError("Cannot delete document during indexing.")
  350. return {"result": "success"}, 200
  351. class DocumentListApi(DatasetApiResource):
  352. def get(self, tenant_id, dataset_id):
  353. dataset_id = str(dataset_id)
  354. tenant_id = str(tenant_id)
  355. page = request.args.get("page", default=1, type=int)
  356. limit = request.args.get("limit", default=20, type=int)
  357. search = request.args.get("keyword", default=None, type=str)
  358. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  359. if not dataset:
  360. raise NotFound("Dataset not found.")
  361. query = Document.query.filter_by(dataset_id=str(dataset_id), tenant_id=tenant_id)
  362. if search:
  363. search = f"%{search}%"
  364. query = query.filter(Document.name.like(search))
  365. query = query.order_by(desc(Document.created_at))
  366. paginated_documents = query.paginate(page=page, per_page=limit, max_per_page=100, error_out=False)
  367. documents = paginated_documents.items
  368. response = {
  369. "data": marshal(documents, document_fields),
  370. "has_more": len(documents) == limit,
  371. "limit": limit,
  372. "total": paginated_documents.total,
  373. "page": page,
  374. }
  375. return response
  376. class DocumentIndexingStatusApi(DatasetApiResource):
  377. def get(self, tenant_id, dataset_id, batch):
  378. dataset_id = str(dataset_id)
  379. batch = str(batch)
  380. tenant_id = str(tenant_id)
  381. # get dataset
  382. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  383. if not dataset:
  384. raise NotFound("Dataset not found.")
  385. # get documents
  386. documents = DocumentService.get_batch_documents(dataset_id, batch)
  387. if not documents:
  388. raise NotFound("Documents not found.")
  389. documents_status = []
  390. for document in documents:
  391. completed_segments = DocumentSegment.query.filter(
  392. DocumentSegment.completed_at.isnot(None),
  393. DocumentSegment.document_id == str(document.id),
  394. DocumentSegment.status != "re_segment",
  395. ).count()
  396. total_segments = DocumentSegment.query.filter(
  397. DocumentSegment.document_id == str(document.id), DocumentSegment.status != "re_segment"
  398. ).count()
  399. document.completed_segments = completed_segments
  400. document.total_segments = total_segments
  401. if document.is_paused:
  402. document.indexing_status = "paused"
  403. documents_status.append(marshal(document, document_status_fields))
  404. data = {"data": documents_status}
  405. return data
  406. api.add_resource(
  407. DocumentAddByTextApi,
  408. "/datasets/<uuid:dataset_id>/document/create_by_text",
  409. "/datasets/<uuid:dataset_id>/document/create-by-text",
  410. )
  411. api.add_resource(
  412. DocumentAddByFileApi,
  413. "/datasets/<uuid:dataset_id>/document/create_by_file",
  414. "/datasets/<uuid:dataset_id>/document/create-by-file",
  415. )
  416. api.add_resource(
  417. DocumentUpdateByTextApi,
  418. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/update_by_text",
  419. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/update-by-text",
  420. )
  421. api.add_resource(
  422. DocumentUpdateByFileApi,
  423. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/update_by_file",
  424. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/update-by-file",
  425. )
  426. api.add_resource(DocumentDeleteApi, "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>")
  427. api.add_resource(DocumentListApi, "/datasets/<uuid:dataset_id>/documents")
  428. api.add_resource(DocumentIndexingStatusApi, "/datasets/<uuid:dataset_id>/documents/<string:batch>/indexing-status")