document.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. if "file" in request.files:
  286. # save file info
  287. file = request.files["file"]
  288. if len(request.files) > 1:
  289. raise TooManyFilesError()
  290. if not file.filename:
  291. raise FilenameNotExistsError
  292. try:
  293. upload_file = FileService.upload_file(
  294. filename=file.filename,
  295. content=file.read(),
  296. mimetype=file.mimetype,
  297. user=current_user,
  298. source="datasets",
  299. )
  300. except services.errors.file.FileTooLargeError as file_too_large_error:
  301. raise FileTooLargeError(file_too_large_error.description)
  302. except services.errors.file.UnsupportedFileTypeError:
  303. raise UnsupportedFileTypeError()
  304. data_source = {
  305. "type": "upload_file",
  306. "info_list": {"data_source_type": "upload_file", "file_info_list": {"file_ids": [upload_file.id]}},
  307. }
  308. args["data_source"] = data_source
  309. # validate args
  310. args["original_document_id"] = str(document_id)
  311. knowledge_config = KnowledgeConfig(**args)
  312. DocumentService.document_create_args_validate(knowledge_config)
  313. try:
  314. documents, batch = DocumentService.save_document_with_dataset_id(
  315. dataset=dataset,
  316. knowledge_config=knowledge_config,
  317. account=dataset.created_by_account,
  318. dataset_process_rule=dataset.latest_process_rule if "process_rule" not in args else None,
  319. created_from="api",
  320. )
  321. except ProviderTokenNotInitError as ex:
  322. raise ProviderNotInitializeError(ex.description)
  323. document = documents[0]
  324. documents_and_batch_fields = {"document": marshal(document, document_fields), "batch": document.batch}
  325. return documents_and_batch_fields, 200
  326. class DocumentDeleteApi(DatasetApiResource):
  327. def delete(self, tenant_id, dataset_id, document_id):
  328. """Delete document."""
  329. document_id = str(document_id)
  330. dataset_id = str(dataset_id)
  331. tenant_id = str(tenant_id)
  332. # get dataset info
  333. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  334. if not dataset:
  335. raise ValueError("Dataset is not exist.")
  336. document = DocumentService.get_document(dataset.id, document_id)
  337. # 404 if document not found
  338. if document is None:
  339. raise NotFound("Document Not Exists.")
  340. # 403 if document is archived
  341. if DocumentService.check_archived(document):
  342. raise ArchivedDocumentImmutableError()
  343. try:
  344. # delete document
  345. DocumentService.delete_document(document)
  346. except services.errors.document.DocumentIndexingError:
  347. raise DocumentIndexingError("Cannot delete document during indexing.")
  348. return {"result": "success"}, 200
  349. class DocumentListApi(DatasetApiResource):
  350. def get(self, tenant_id, dataset_id):
  351. dataset_id = str(dataset_id)
  352. tenant_id = str(tenant_id)
  353. page = request.args.get("page", default=1, type=int)
  354. limit = request.args.get("limit", default=20, type=int)
  355. search = request.args.get("keyword", default=None, type=str)
  356. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  357. if not dataset:
  358. raise NotFound("Dataset not found.")
  359. query = Document.query.filter_by(dataset_id=str(dataset_id), tenant_id=tenant_id)
  360. if search:
  361. search = f"%{search}%"
  362. query = query.filter(Document.name.like(search))
  363. query = query.order_by(desc(Document.created_at))
  364. paginated_documents = query.paginate(page=page, per_page=limit, max_per_page=100, error_out=False)
  365. documents = paginated_documents.items
  366. response = {
  367. "data": marshal(documents, document_fields),
  368. "has_more": len(documents) == limit,
  369. "limit": limit,
  370. "total": paginated_documents.total,
  371. "page": page,
  372. }
  373. return response
  374. class DocumentIndexingStatusApi(DatasetApiResource):
  375. def get(self, tenant_id, dataset_id, batch):
  376. dataset_id = str(dataset_id)
  377. batch = str(batch)
  378. tenant_id = str(tenant_id)
  379. # get dataset
  380. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  381. if not dataset:
  382. raise NotFound("Dataset not found.")
  383. # get documents
  384. documents = DocumentService.get_batch_documents(dataset_id, batch)
  385. if not documents:
  386. raise NotFound("Documents not found.")
  387. documents_status = []
  388. for document in documents:
  389. completed_segments = DocumentSegment.query.filter(
  390. DocumentSegment.completed_at.isnot(None),
  391. DocumentSegment.document_id == str(document.id),
  392. DocumentSegment.status != "re_segment",
  393. ).count()
  394. total_segments = DocumentSegment.query.filter(
  395. DocumentSegment.document_id == str(document.id), DocumentSegment.status != "re_segment"
  396. ).count()
  397. document.completed_segments = completed_segments
  398. document.total_segments = total_segments
  399. if document.is_paused:
  400. document.indexing_status = "paused"
  401. documents_status.append(marshal(document, document_status_fields))
  402. data = {"data": documents_status}
  403. return data
  404. api.add_resource(
  405. DocumentAddByTextApi,
  406. "/datasets/<uuid:dataset_id>/document/create_by_text",
  407. "/datasets/<uuid:dataset_id>/document/create-by-text",
  408. )
  409. api.add_resource(
  410. DocumentAddByFileApi,
  411. "/datasets/<uuid:dataset_id>/document/create_by_file",
  412. "/datasets/<uuid:dataset_id>/document/create-by-file",
  413. )
  414. api.add_resource(
  415. DocumentUpdateByTextApi,
  416. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/update_by_text",
  417. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/update-by-text",
  418. )
  419. api.add_resource(
  420. DocumentUpdateByFileApi,
  421. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/update_by_file",
  422. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/update-by-file",
  423. )
  424. api.add_resource(DocumentDeleteApi, "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>")
  425. api.add_resource(DocumentListApi, "/datasets/<uuid:dataset_id>/documents")
  426. api.add_resource(DocumentIndexingStatusApi, "/datasets/<uuid:dataset_id>/documents/<string:batch>/indexing-status")