dataset_service.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  1. import datetime
  2. import json
  3. import logging
  4. import random
  5. import time
  6. import uuid
  7. from typing import Any, Optional
  8. from flask_login import current_user
  9. from sqlalchemy import func
  10. from werkzeug.exceptions import NotFound
  11. from configs import dify_config
  12. from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
  13. from core.model_manager import ModelManager
  14. from core.model_runtime.entities.model_entities import ModelType
  15. from core.rag.retrieval.retrieval_methods import RetrievalMethod
  16. from events.dataset_event import dataset_was_deleted
  17. from events.document_event import document_was_deleted
  18. from extensions.ext_database import db
  19. from extensions.ext_redis import redis_client
  20. from libs import helper
  21. from models.account import Account, TenantAccountRole
  22. from models.dataset import (
  23. AppDatasetJoin,
  24. Dataset,
  25. DatasetCollectionBinding,
  26. DatasetPermission,
  27. DatasetPermissionEnum,
  28. DatasetProcessRule,
  29. DatasetQuery,
  30. Document,
  31. DocumentSegment,
  32. ExternalKnowledgeBindings,
  33. )
  34. from models.model import UploadFile
  35. from models.source import DataSourceOauthBinding
  36. from services.entities.knowledge_entities.knowledge_entities import SegmentUpdateEntity
  37. from services.errors.account import NoPermissionError
  38. from services.errors.dataset import DatasetNameDuplicateError
  39. from services.errors.document import DocumentIndexingError
  40. from services.errors.file import FileNotExistsError
  41. from services.external_knowledge_service import ExternalDatasetService
  42. from services.feature_service import FeatureModel, FeatureService
  43. from services.tag_service import TagService
  44. from services.vector_service import VectorService
  45. from tasks.clean_notion_document_task import clean_notion_document_task
  46. from tasks.deal_dataset_vector_index_task import deal_dataset_vector_index_task
  47. from tasks.delete_segment_from_index_task import delete_segment_from_index_task
  48. from tasks.disable_segment_from_index_task import disable_segment_from_index_task
  49. from tasks.document_indexing_task import document_indexing_task
  50. from tasks.document_indexing_update_task import document_indexing_update_task
  51. from tasks.duplicate_document_indexing_task import duplicate_document_indexing_task
  52. from tasks.recover_document_indexing_task import recover_document_indexing_task
  53. from tasks.retry_document_indexing_task import retry_document_indexing_task
  54. from tasks.sync_website_document_indexing_task import sync_website_document_indexing_task
  55. class DatasetService:
  56. @staticmethod
  57. def get_datasets(page, per_page, tenant_id=None, user=None, search=None, tag_ids=None):
  58. query = Dataset.query.filter(Dataset.tenant_id == tenant_id).order_by(Dataset.created_at.desc())
  59. if user:
  60. # get permitted dataset ids
  61. dataset_permission = DatasetPermission.query.filter_by(account_id=user.id, tenant_id=tenant_id).all()
  62. permitted_dataset_ids = {dp.dataset_id for dp in dataset_permission} if dataset_permission else None
  63. if user.current_role == TenantAccountRole.DATASET_OPERATOR:
  64. # only show datasets that the user has permission to access
  65. if permitted_dataset_ids:
  66. query = query.filter(Dataset.id.in_(permitted_dataset_ids))
  67. else:
  68. return [], 0
  69. else:
  70. # show all datasets that the user has permission to access
  71. if permitted_dataset_ids:
  72. query = query.filter(
  73. db.or_(
  74. Dataset.permission == DatasetPermissionEnum.ALL_TEAM,
  75. db.and_(Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id),
  76. db.and_(
  77. Dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM,
  78. Dataset.id.in_(permitted_dataset_ids),
  79. ),
  80. )
  81. )
  82. else:
  83. query = query.filter(
  84. db.or_(
  85. Dataset.permission == DatasetPermissionEnum.ALL_TEAM,
  86. db.and_(Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id),
  87. )
  88. )
  89. else:
  90. # if no user, only show datasets that are shared with all team members
  91. query = query.filter(Dataset.permission == DatasetPermissionEnum.ALL_TEAM)
  92. if search:
  93. query = query.filter(Dataset.name.ilike(f"%{search}%"))
  94. if tag_ids:
  95. target_ids = TagService.get_target_ids_by_tag_ids("knowledge", tenant_id, tag_ids)
  96. if target_ids:
  97. query = query.filter(Dataset.id.in_(target_ids))
  98. else:
  99. return [], 0
  100. datasets = query.paginate(page=page, per_page=per_page, max_per_page=100, error_out=False)
  101. return datasets.items, datasets.total
  102. @staticmethod
  103. def get_process_rules(dataset_id):
  104. # get the latest process rule
  105. dataset_process_rule = (
  106. db.session.query(DatasetProcessRule)
  107. .filter(DatasetProcessRule.dataset_id == dataset_id)
  108. .order_by(DatasetProcessRule.created_at.desc())
  109. .limit(1)
  110. .one_or_none()
  111. )
  112. if dataset_process_rule:
  113. mode = dataset_process_rule.mode
  114. rules = dataset_process_rule.rules_dict
  115. else:
  116. mode = DocumentService.DEFAULT_RULES["mode"]
  117. rules = DocumentService.DEFAULT_RULES["rules"]
  118. return {"mode": mode, "rules": rules}
  119. @staticmethod
  120. def get_datasets_by_ids(ids, tenant_id):
  121. datasets = Dataset.query.filter(Dataset.id.in_(ids), Dataset.tenant_id == tenant_id).paginate(
  122. page=1, per_page=len(ids), max_per_page=len(ids), error_out=False
  123. )
  124. return datasets.items, datasets.total
  125. @staticmethod
  126. def create_empty_dataset(
  127. tenant_id: str,
  128. name: str,
  129. description: Optional[str],
  130. indexing_technique: Optional[str],
  131. account: Account,
  132. permission: Optional[str] = None,
  133. provider: str = "vendor",
  134. external_knowledge_api_id: Optional[str] = None,
  135. external_knowledge_id: Optional[str] = None,
  136. ):
  137. # check if dataset name already exists
  138. if Dataset.query.filter_by(name=name, tenant_id=tenant_id).first():
  139. raise DatasetNameDuplicateError(f"Dataset with name {name} already exists.")
  140. embedding_model = None
  141. if indexing_technique == "high_quality":
  142. model_manager = ModelManager()
  143. embedding_model = model_manager.get_default_model_instance(
  144. tenant_id=tenant_id, model_type=ModelType.TEXT_EMBEDDING
  145. )
  146. dataset = Dataset(name=name, indexing_technique=indexing_technique)
  147. # dataset = Dataset(name=name, provider=provider, config=config)
  148. dataset.description = description
  149. dataset.created_by = account.id
  150. dataset.updated_by = account.id
  151. dataset.tenant_id = tenant_id
  152. dataset.embedding_model_provider = embedding_model.provider if embedding_model else None
  153. dataset.embedding_model = embedding_model.model if embedding_model else None
  154. dataset.permission = permission or DatasetPermissionEnum.ONLY_ME
  155. dataset.provider = provider
  156. db.session.add(dataset)
  157. db.session.flush()
  158. if provider == "external" and external_knowledge_api_id:
  159. external_knowledge_api = ExternalDatasetService.get_external_knowledge_api(external_knowledge_api_id)
  160. if not external_knowledge_api:
  161. raise ValueError("External API template not found.")
  162. external_knowledge_binding = ExternalKnowledgeBindings(
  163. tenant_id=tenant_id,
  164. dataset_id=dataset.id,
  165. external_knowledge_api_id=external_knowledge_api_id,
  166. external_knowledge_id=external_knowledge_id,
  167. created_by=account.id,
  168. )
  169. db.session.add(external_knowledge_binding)
  170. db.session.commit()
  171. return dataset
  172. @staticmethod
  173. def get_dataset(dataset_id) -> Dataset:
  174. return Dataset.query.filter_by(id=dataset_id).first()
  175. @staticmethod
  176. def check_dataset_model_setting(dataset):
  177. if dataset.indexing_technique == "high_quality":
  178. try:
  179. model_manager = ModelManager()
  180. model_manager.get_model_instance(
  181. tenant_id=dataset.tenant_id,
  182. provider=dataset.embedding_model_provider,
  183. model_type=ModelType.TEXT_EMBEDDING,
  184. model=dataset.embedding_model,
  185. )
  186. except LLMBadRequestError:
  187. raise ValueError(
  188. "No Embedding Model available. Please configure a valid provider "
  189. "in the Settings -> Model Provider."
  190. )
  191. except ProviderTokenNotInitError as ex:
  192. raise ValueError(f"The dataset in unavailable, due to: {ex.description}")
  193. @staticmethod
  194. def check_embedding_model_setting(tenant_id: str, embedding_model_provider: str, embedding_model: str):
  195. try:
  196. model_manager = ModelManager()
  197. model_manager.get_model_instance(
  198. tenant_id=tenant_id,
  199. provider=embedding_model_provider,
  200. model_type=ModelType.TEXT_EMBEDDING,
  201. model=embedding_model,
  202. )
  203. except LLMBadRequestError:
  204. raise ValueError(
  205. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  206. )
  207. except ProviderTokenNotInitError as ex:
  208. raise ValueError(f"The dataset in unavailable, due to: {ex.description}")
  209. @staticmethod
  210. def update_dataset(dataset_id, data, user):
  211. dataset = DatasetService.get_dataset(dataset_id)
  212. DatasetService.check_dataset_permission(dataset, user)
  213. if dataset.provider == "external":
  214. dataset.retrieval_model = data.get("external_retrieval_model", None)
  215. dataset.name = data.get("name", dataset.name)
  216. dataset.description = data.get("description", "")
  217. external_knowledge_id = data.get("external_knowledge_id", None)
  218. dataset.permission = data.get("permission")
  219. db.session.add(dataset)
  220. if not external_knowledge_id:
  221. raise ValueError("External knowledge id is required.")
  222. external_knowledge_api_id = data.get("external_knowledge_api_id", None)
  223. if not external_knowledge_api_id:
  224. raise ValueError("External knowledge api id is required.")
  225. external_knowledge_binding = ExternalKnowledgeBindings.query.filter_by(dataset_id=dataset_id).first()
  226. if (
  227. external_knowledge_binding.external_knowledge_id != external_knowledge_id
  228. or external_knowledge_binding.external_knowledge_api_id != external_knowledge_api_id
  229. ):
  230. external_knowledge_binding.external_knowledge_id = external_knowledge_id
  231. external_knowledge_binding.external_knowledge_api_id = external_knowledge_api_id
  232. db.session.add(external_knowledge_binding)
  233. db.session.commit()
  234. else:
  235. data.pop("partial_member_list", None)
  236. data.pop("external_knowledge_api_id", None)
  237. data.pop("external_knowledge_id", None)
  238. data.pop("external_retrieval_model", None)
  239. filtered_data = {k: v for k, v in data.items() if v is not None or k == "description"}
  240. action = None
  241. if dataset.indexing_technique != data["indexing_technique"]:
  242. # if update indexing_technique
  243. if data["indexing_technique"] == "economy":
  244. action = "remove"
  245. filtered_data["embedding_model"] = None
  246. filtered_data["embedding_model_provider"] = None
  247. filtered_data["collection_binding_id"] = None
  248. elif data["indexing_technique"] == "high_quality":
  249. action = "add"
  250. # get embedding model setting
  251. try:
  252. model_manager = ModelManager()
  253. embedding_model = model_manager.get_model_instance(
  254. tenant_id=current_user.current_tenant_id,
  255. provider=data["embedding_model_provider"],
  256. model_type=ModelType.TEXT_EMBEDDING,
  257. model=data["embedding_model"],
  258. )
  259. filtered_data["embedding_model"] = embedding_model.model
  260. filtered_data["embedding_model_provider"] = embedding_model.provider
  261. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  262. embedding_model.provider, embedding_model.model
  263. )
  264. filtered_data["collection_binding_id"] = dataset_collection_binding.id
  265. except LLMBadRequestError:
  266. raise ValueError(
  267. "No Embedding Model available. Please configure a valid provider "
  268. "in the Settings -> Model Provider."
  269. )
  270. except ProviderTokenNotInitError as ex:
  271. raise ValueError(ex.description)
  272. else:
  273. if (
  274. data["embedding_model_provider"] != dataset.embedding_model_provider
  275. or data["embedding_model"] != dataset.embedding_model
  276. ):
  277. action = "update"
  278. try:
  279. model_manager = ModelManager()
  280. embedding_model = model_manager.get_model_instance(
  281. tenant_id=current_user.current_tenant_id,
  282. provider=data["embedding_model_provider"],
  283. model_type=ModelType.TEXT_EMBEDDING,
  284. model=data["embedding_model"],
  285. )
  286. filtered_data["embedding_model"] = embedding_model.model
  287. filtered_data["embedding_model_provider"] = embedding_model.provider
  288. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  289. embedding_model.provider, embedding_model.model
  290. )
  291. filtered_data["collection_binding_id"] = dataset_collection_binding.id
  292. except LLMBadRequestError:
  293. raise ValueError(
  294. "No Embedding Model available. Please configure a valid provider "
  295. "in the Settings -> Model Provider."
  296. )
  297. except ProviderTokenNotInitError as ex:
  298. raise ValueError(ex.description)
  299. filtered_data["updated_by"] = user.id
  300. filtered_data["updated_at"] = datetime.datetime.now()
  301. # update Retrieval model
  302. filtered_data["retrieval_model"] = data["retrieval_model"]
  303. dataset.query.filter_by(id=dataset_id).update(filtered_data)
  304. db.session.commit()
  305. if action:
  306. deal_dataset_vector_index_task.delay(dataset_id, action)
  307. return dataset
  308. @staticmethod
  309. def delete_dataset(dataset_id, user):
  310. dataset = DatasetService.get_dataset(dataset_id)
  311. if dataset is None:
  312. return False
  313. DatasetService.check_dataset_permission(dataset, user)
  314. dataset_was_deleted.send(dataset)
  315. db.session.delete(dataset)
  316. db.session.commit()
  317. return True
  318. @staticmethod
  319. def dataset_use_check(dataset_id) -> bool:
  320. count = AppDatasetJoin.query.filter_by(dataset_id=dataset_id).count()
  321. if count > 0:
  322. return True
  323. return False
  324. @staticmethod
  325. def check_dataset_permission(dataset, user):
  326. if dataset.tenant_id != user.current_tenant_id:
  327. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  328. raise NoPermissionError("You do not have permission to access this dataset.")
  329. if dataset.permission == DatasetPermissionEnum.ONLY_ME and dataset.created_by != user.id:
  330. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  331. raise NoPermissionError("You do not have permission to access this dataset.")
  332. if dataset.permission == "partial_members":
  333. user_permission = DatasetPermission.query.filter_by(dataset_id=dataset.id, account_id=user.id).first()
  334. if not user_permission and dataset.tenant_id != user.current_tenant_id and dataset.created_by != user.id:
  335. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  336. raise NoPermissionError("You do not have permission to access this dataset.")
  337. @staticmethod
  338. def check_dataset_operator_permission(user: Account = None, dataset: Dataset = None):
  339. if dataset.permission == DatasetPermissionEnum.ONLY_ME:
  340. if dataset.created_by != user.id:
  341. raise NoPermissionError("You do not have permission to access this dataset.")
  342. elif dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM:
  343. if not any(
  344. dp.dataset_id == dataset.id for dp in DatasetPermission.query.filter_by(account_id=user.id).all()
  345. ):
  346. raise NoPermissionError("You do not have permission to access this dataset.")
  347. @staticmethod
  348. def get_dataset_queries(dataset_id: str, page: int, per_page: int):
  349. dataset_queries = (
  350. DatasetQuery.query.filter_by(dataset_id=dataset_id)
  351. .order_by(db.desc(DatasetQuery.created_at))
  352. .paginate(page=page, per_page=per_page, max_per_page=100, error_out=False)
  353. )
  354. return dataset_queries.items, dataset_queries.total
  355. @staticmethod
  356. def get_related_apps(dataset_id: str):
  357. return (
  358. AppDatasetJoin.query.filter(AppDatasetJoin.dataset_id == dataset_id)
  359. .order_by(db.desc(AppDatasetJoin.created_at))
  360. .all()
  361. )
  362. class DocumentService:
  363. DEFAULT_RULES = {
  364. "mode": "custom",
  365. "rules": {
  366. "pre_processing_rules": [
  367. {"id": "remove_extra_spaces", "enabled": True},
  368. {"id": "remove_urls_emails", "enabled": False},
  369. ],
  370. "segmentation": {"delimiter": "\n", "max_tokens": 500, "chunk_overlap": 50},
  371. },
  372. "limits": {
  373. "indexing_max_segmentation_tokens_length": dify_config.INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH,
  374. },
  375. }
  376. DOCUMENT_METADATA_SCHEMA = {
  377. "book": {
  378. "title": str,
  379. "language": str,
  380. "author": str,
  381. "publisher": str,
  382. "publication_date": str,
  383. "isbn": str,
  384. "category": str,
  385. },
  386. "web_page": {
  387. "title": str,
  388. "url": str,
  389. "language": str,
  390. "publish_date": str,
  391. "author/publisher": str,
  392. "topic/keywords": str,
  393. "description": str,
  394. },
  395. "paper": {
  396. "title": str,
  397. "language": str,
  398. "author": str,
  399. "publish_date": str,
  400. "journal/conference_name": str,
  401. "volume/issue/page_numbers": str,
  402. "doi": str,
  403. "topic/keywords": str,
  404. "abstract": str,
  405. },
  406. "social_media_post": {
  407. "platform": str,
  408. "author/username": str,
  409. "publish_date": str,
  410. "post_url": str,
  411. "topic/tags": str,
  412. },
  413. "wikipedia_entry": {
  414. "title": str,
  415. "language": str,
  416. "web_page_url": str,
  417. "last_edit_date": str,
  418. "editor/contributor": str,
  419. "summary/introduction": str,
  420. },
  421. "personal_document": {
  422. "title": str,
  423. "author": str,
  424. "creation_date": str,
  425. "last_modified_date": str,
  426. "document_type": str,
  427. "tags/category": str,
  428. },
  429. "business_document": {
  430. "title": str,
  431. "author": str,
  432. "creation_date": str,
  433. "last_modified_date": str,
  434. "document_type": str,
  435. "department/team": str,
  436. },
  437. "im_chat_log": {
  438. "chat_platform": str,
  439. "chat_participants/group_name": str,
  440. "start_date": str,
  441. "end_date": str,
  442. "summary": str,
  443. },
  444. "synced_from_notion": {
  445. "title": str,
  446. "language": str,
  447. "author/creator": str,
  448. "creation_date": str,
  449. "last_modified_date": str,
  450. "notion_page_link": str,
  451. "category/tags": str,
  452. "description": str,
  453. },
  454. "synced_from_github": {
  455. "repository_name": str,
  456. "repository_description": str,
  457. "repository_owner/organization": str,
  458. "code_filename": str,
  459. "code_file_path": str,
  460. "programming_language": str,
  461. "github_link": str,
  462. "open_source_license": str,
  463. "commit_date": str,
  464. "commit_author": str,
  465. },
  466. "others": dict,
  467. }
  468. @staticmethod
  469. def get_document(dataset_id: str, document_id: str) -> Optional[Document]:
  470. document = (
  471. db.session.query(Document).filter(Document.id == document_id, Document.dataset_id == dataset_id).first()
  472. )
  473. return document
  474. @staticmethod
  475. def get_document_by_id(document_id: str) -> Optional[Document]:
  476. document = db.session.query(Document).filter(Document.id == document_id).first()
  477. return document
  478. @staticmethod
  479. def get_document_by_dataset_id(dataset_id: str) -> list[Document]:
  480. documents = db.session.query(Document).filter(Document.dataset_id == dataset_id, Document.enabled == True).all()
  481. return documents
  482. @staticmethod
  483. def get_error_documents_by_dataset_id(dataset_id: str) -> list[Document]:
  484. documents = (
  485. db.session.query(Document)
  486. .filter(Document.dataset_id == dataset_id, Document.indexing_status.in_(["error", "paused"]))
  487. .all()
  488. )
  489. return documents
  490. @staticmethod
  491. def get_batch_documents(dataset_id: str, batch: str) -> list[Document]:
  492. documents = (
  493. db.session.query(Document)
  494. .filter(
  495. Document.batch == batch,
  496. Document.dataset_id == dataset_id,
  497. Document.tenant_id == current_user.current_tenant_id,
  498. )
  499. .all()
  500. )
  501. return documents
  502. @staticmethod
  503. def get_document_file_detail(file_id: str):
  504. file_detail = db.session.query(UploadFile).filter(UploadFile.id == file_id).one_or_none()
  505. return file_detail
  506. @staticmethod
  507. def check_archived(document):
  508. if document.archived:
  509. return True
  510. else:
  511. return False
  512. @staticmethod
  513. def delete_document(document):
  514. # trigger document_was_deleted signal
  515. file_id = None
  516. if document.data_source_type == "upload_file":
  517. if document.data_source_info:
  518. data_source_info = document.data_source_info_dict
  519. if data_source_info and "upload_file_id" in data_source_info:
  520. file_id = data_source_info["upload_file_id"]
  521. document_was_deleted.send(
  522. document.id, dataset_id=document.dataset_id, doc_form=document.doc_form, file_id=file_id
  523. )
  524. db.session.delete(document)
  525. db.session.commit()
  526. @staticmethod
  527. def rename_document(dataset_id: str, document_id: str, name: str) -> Document:
  528. dataset = DatasetService.get_dataset(dataset_id)
  529. if not dataset:
  530. raise ValueError("Dataset not found.")
  531. document = DocumentService.get_document(dataset_id, document_id)
  532. if not document:
  533. raise ValueError("Document not found.")
  534. if document.tenant_id != current_user.current_tenant_id:
  535. raise ValueError("No permission.")
  536. document.name = name
  537. db.session.add(document)
  538. db.session.commit()
  539. return document
  540. @staticmethod
  541. def pause_document(document):
  542. if document.indexing_status not in {"waiting", "parsing", "cleaning", "splitting", "indexing"}:
  543. raise DocumentIndexingError()
  544. # update document to be paused
  545. document.is_paused = True
  546. document.paused_by = current_user.id
  547. document.paused_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  548. db.session.add(document)
  549. db.session.commit()
  550. # set document paused flag
  551. indexing_cache_key = "document_{}_is_paused".format(document.id)
  552. redis_client.setnx(indexing_cache_key, "True")
  553. @staticmethod
  554. def recover_document(document):
  555. if not document.is_paused:
  556. raise DocumentIndexingError()
  557. # update document to be recover
  558. document.is_paused = False
  559. document.paused_by = None
  560. document.paused_at = None
  561. db.session.add(document)
  562. db.session.commit()
  563. # delete paused flag
  564. indexing_cache_key = "document_{}_is_paused".format(document.id)
  565. redis_client.delete(indexing_cache_key)
  566. # trigger async task
  567. recover_document_indexing_task.delay(document.dataset_id, document.id)
  568. @staticmethod
  569. def retry_document(dataset_id: str, documents: list[Document]):
  570. for document in documents:
  571. # add retry flag
  572. retry_indexing_cache_key = "document_{}_is_retried".format(document.id)
  573. cache_result = redis_client.get(retry_indexing_cache_key)
  574. if cache_result is not None:
  575. raise ValueError("Document is being retried, please try again later")
  576. # retry document indexing
  577. document.indexing_status = "waiting"
  578. db.session.add(document)
  579. db.session.commit()
  580. redis_client.setex(retry_indexing_cache_key, 600, 1)
  581. # trigger async task
  582. document_ids = [document.id for document in documents]
  583. retry_document_indexing_task.delay(dataset_id, document_ids)
  584. @staticmethod
  585. def sync_website_document(dataset_id: str, document: Document):
  586. # add sync flag
  587. sync_indexing_cache_key = "document_{}_is_sync".format(document.id)
  588. cache_result = redis_client.get(sync_indexing_cache_key)
  589. if cache_result is not None:
  590. raise ValueError("Document is being synced, please try again later")
  591. # sync document indexing
  592. document.indexing_status = "waiting"
  593. data_source_info = document.data_source_info_dict
  594. data_source_info["mode"] = "scrape"
  595. document.data_source_info = json.dumps(data_source_info, ensure_ascii=False)
  596. db.session.add(document)
  597. db.session.commit()
  598. redis_client.setex(sync_indexing_cache_key, 600, 1)
  599. sync_website_document_indexing_task.delay(dataset_id, document.id)
  600. @staticmethod
  601. def get_documents_position(dataset_id):
  602. document = Document.query.filter_by(dataset_id=dataset_id).order_by(Document.position.desc()).first()
  603. if document:
  604. return document.position + 1
  605. else:
  606. return 1
  607. @staticmethod
  608. def save_document_with_dataset_id(
  609. dataset: Dataset,
  610. document_data: dict,
  611. account: Account | Any,
  612. dataset_process_rule: Optional[DatasetProcessRule] = None,
  613. created_from: str = "web",
  614. ):
  615. # check document limit
  616. features = FeatureService.get_features(current_user.current_tenant_id)
  617. if features.billing.enabled:
  618. if "original_document_id" not in document_data or not document_data["original_document_id"]:
  619. count = 0
  620. if document_data["data_source"]["type"] == "upload_file":
  621. upload_file_list = document_data["data_source"]["info_list"]["file_info_list"]["file_ids"]
  622. count = len(upload_file_list)
  623. elif document_data["data_source"]["type"] == "notion_import":
  624. notion_info_list = document_data["data_source"]["info_list"]["notion_info_list"]
  625. for notion_info in notion_info_list:
  626. count = count + len(notion_info["pages"])
  627. elif document_data["data_source"]["type"] == "website_crawl":
  628. website_info = document_data["data_source"]["info_list"]["website_info_list"]
  629. count = len(website_info["urls"])
  630. batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  631. if count > batch_upload_limit:
  632. raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  633. DocumentService.check_documents_upload_quota(count, features)
  634. # if dataset is empty, update dataset data_source_type
  635. if not dataset.data_source_type:
  636. dataset.data_source_type = document_data["data_source"]["type"]
  637. if not dataset.indexing_technique:
  638. if (
  639. "indexing_technique" not in document_data
  640. or document_data["indexing_technique"] not in Dataset.INDEXING_TECHNIQUE_LIST
  641. ):
  642. raise ValueError("Indexing technique is required")
  643. dataset.indexing_technique = document_data["indexing_technique"]
  644. if document_data["indexing_technique"] == "high_quality":
  645. model_manager = ModelManager()
  646. embedding_model = model_manager.get_default_model_instance(
  647. tenant_id=current_user.current_tenant_id, model_type=ModelType.TEXT_EMBEDDING
  648. )
  649. dataset.embedding_model = embedding_model.model
  650. dataset.embedding_model_provider = embedding_model.provider
  651. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  652. embedding_model.provider, embedding_model.model
  653. )
  654. dataset.collection_binding_id = dataset_collection_binding.id
  655. if not dataset.retrieval_model:
  656. default_retrieval_model = {
  657. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  658. "reranking_enable": False,
  659. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  660. "top_k": 2,
  661. "score_threshold_enabled": False,
  662. }
  663. dataset.retrieval_model = document_data.get("retrieval_model") or default_retrieval_model
  664. documents = []
  665. if document_data.get("original_document_id"):
  666. document = DocumentService.update_document_with_dataset_id(dataset, document_data, account)
  667. documents.append(document)
  668. batch = document.batch
  669. else:
  670. batch = time.strftime("%Y%m%d%H%M%S") + str(random.randint(100000, 999999))
  671. # save process rule
  672. if not dataset_process_rule:
  673. process_rule = document_data["process_rule"]
  674. if process_rule["mode"] == "custom":
  675. dataset_process_rule = DatasetProcessRule(
  676. dataset_id=dataset.id,
  677. mode=process_rule["mode"],
  678. rules=json.dumps(process_rule["rules"]),
  679. created_by=account.id,
  680. )
  681. elif process_rule["mode"] == "automatic":
  682. dataset_process_rule = DatasetProcessRule(
  683. dataset_id=dataset.id,
  684. mode=process_rule["mode"],
  685. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  686. created_by=account.id,
  687. )
  688. db.session.add(dataset_process_rule)
  689. db.session.commit()
  690. lock_name = "add_document_lock_dataset_id_{}".format(dataset.id)
  691. with redis_client.lock(lock_name, timeout=600):
  692. position = DocumentService.get_documents_position(dataset.id)
  693. document_ids = []
  694. duplicate_document_ids = []
  695. if document_data["data_source"]["type"] == "upload_file":
  696. upload_file_list = document_data["data_source"]["info_list"]["file_info_list"]["file_ids"]
  697. for file_id in upload_file_list:
  698. file = (
  699. db.session.query(UploadFile)
  700. .filter(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  701. .first()
  702. )
  703. # raise error if file not found
  704. if not file:
  705. raise FileNotExistsError()
  706. file_name = file.name
  707. data_source_info = {
  708. "upload_file_id": file_id,
  709. }
  710. # check duplicate
  711. if document_data.get("duplicate", False):
  712. document = Document.query.filter_by(
  713. dataset_id=dataset.id,
  714. tenant_id=current_user.current_tenant_id,
  715. data_source_type="upload_file",
  716. enabled=True,
  717. name=file_name,
  718. ).first()
  719. if document:
  720. document.dataset_process_rule_id = dataset_process_rule.id
  721. document.updated_at = datetime.datetime.utcnow()
  722. document.created_from = created_from
  723. document.doc_form = document_data["doc_form"]
  724. document.doc_language = document_data["doc_language"]
  725. document.data_source_info = json.dumps(data_source_info)
  726. document.batch = batch
  727. document.indexing_status = "waiting"
  728. db.session.add(document)
  729. documents.append(document)
  730. duplicate_document_ids.append(document.id)
  731. continue
  732. document = DocumentService.build_document(
  733. dataset,
  734. dataset_process_rule.id,
  735. document_data["data_source"]["type"],
  736. document_data["doc_form"],
  737. document_data["doc_language"],
  738. data_source_info,
  739. created_from,
  740. position,
  741. account,
  742. file_name,
  743. batch,
  744. )
  745. db.session.add(document)
  746. db.session.flush()
  747. document_ids.append(document.id)
  748. documents.append(document)
  749. position += 1
  750. elif document_data["data_source"]["type"] == "notion_import":
  751. notion_info_list = document_data["data_source"]["info_list"]["notion_info_list"]
  752. exist_page_ids = []
  753. exist_document = {}
  754. documents = Document.query.filter_by(
  755. dataset_id=dataset.id,
  756. tenant_id=current_user.current_tenant_id,
  757. data_source_type="notion_import",
  758. enabled=True,
  759. ).all()
  760. if documents:
  761. for document in documents:
  762. data_source_info = json.loads(document.data_source_info)
  763. exist_page_ids.append(data_source_info["notion_page_id"])
  764. exist_document[data_source_info["notion_page_id"]] = document.id
  765. for notion_info in notion_info_list:
  766. workspace_id = notion_info["workspace_id"]
  767. data_source_binding = DataSourceOauthBinding.query.filter(
  768. db.and_(
  769. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  770. DataSourceOauthBinding.provider == "notion",
  771. DataSourceOauthBinding.disabled == False,
  772. DataSourceOauthBinding.source_info["workspace_id"] == f'"{workspace_id}"',
  773. )
  774. ).first()
  775. if not data_source_binding:
  776. raise ValueError("Data source binding not found.")
  777. for page in notion_info["pages"]:
  778. if page["page_id"] not in exist_page_ids:
  779. data_source_info = {
  780. "notion_workspace_id": workspace_id,
  781. "notion_page_id": page["page_id"],
  782. "notion_page_icon": page["page_icon"],
  783. "type": page["type"],
  784. }
  785. document = DocumentService.build_document(
  786. dataset,
  787. dataset_process_rule.id,
  788. document_data["data_source"]["type"],
  789. document_data["doc_form"],
  790. document_data["doc_language"],
  791. data_source_info,
  792. created_from,
  793. position,
  794. account,
  795. page["page_name"],
  796. batch,
  797. )
  798. db.session.add(document)
  799. db.session.flush()
  800. document_ids.append(document.id)
  801. documents.append(document)
  802. position += 1
  803. else:
  804. exist_document.pop(page["page_id"])
  805. # delete not selected documents
  806. if len(exist_document) > 0:
  807. clean_notion_document_task.delay(list(exist_document.values()), dataset.id)
  808. elif document_data["data_source"]["type"] == "website_crawl":
  809. website_info = document_data["data_source"]["info_list"]["website_info_list"]
  810. urls = website_info["urls"]
  811. for url in urls:
  812. data_source_info = {
  813. "url": url,
  814. "provider": website_info["provider"],
  815. "job_id": website_info["job_id"],
  816. "only_main_content": website_info.get("only_main_content", False),
  817. "mode": "crawl",
  818. }
  819. if len(url) > 255:
  820. document_name = url[:200] + "..."
  821. else:
  822. document_name = url
  823. document = DocumentService.build_document(
  824. dataset,
  825. dataset_process_rule.id,
  826. document_data["data_source"]["type"],
  827. document_data["doc_form"],
  828. document_data["doc_language"],
  829. data_source_info,
  830. created_from,
  831. position,
  832. account,
  833. document_name,
  834. batch,
  835. )
  836. db.session.add(document)
  837. db.session.flush()
  838. document_ids.append(document.id)
  839. documents.append(document)
  840. position += 1
  841. db.session.commit()
  842. # trigger async task
  843. if document_ids:
  844. document_indexing_task.delay(dataset.id, document_ids)
  845. if duplicate_document_ids:
  846. duplicate_document_indexing_task.delay(dataset.id, duplicate_document_ids)
  847. return documents, batch
  848. @staticmethod
  849. def check_documents_upload_quota(count: int, features: FeatureModel):
  850. can_upload_size = features.documents_upload_quota.limit - features.documents_upload_quota.size
  851. if count > can_upload_size:
  852. raise ValueError(
  853. f"You have reached the limit of your subscription. Only {can_upload_size} documents can be uploaded."
  854. )
  855. @staticmethod
  856. def build_document(
  857. dataset: Dataset,
  858. process_rule_id: str,
  859. data_source_type: str,
  860. document_form: str,
  861. document_language: str,
  862. data_source_info: dict,
  863. created_from: str,
  864. position: int,
  865. account: Account,
  866. name: str,
  867. batch: str,
  868. ):
  869. document = Document(
  870. tenant_id=dataset.tenant_id,
  871. dataset_id=dataset.id,
  872. position=position,
  873. data_source_type=data_source_type,
  874. data_source_info=json.dumps(data_source_info),
  875. dataset_process_rule_id=process_rule_id,
  876. batch=batch,
  877. name=name,
  878. created_from=created_from,
  879. created_by=account.id,
  880. doc_form=document_form,
  881. doc_language=document_language,
  882. )
  883. return document
  884. @staticmethod
  885. def get_tenant_documents_count():
  886. documents_count = Document.query.filter(
  887. Document.completed_at.isnot(None),
  888. Document.enabled == True,
  889. Document.archived == False,
  890. Document.tenant_id == current_user.current_tenant_id,
  891. ).count()
  892. return documents_count
  893. @staticmethod
  894. def update_document_with_dataset_id(
  895. dataset: Dataset,
  896. document_data: dict,
  897. account: Account,
  898. dataset_process_rule: Optional[DatasetProcessRule] = None,
  899. created_from: str = "web",
  900. ):
  901. DatasetService.check_dataset_model_setting(dataset)
  902. document = DocumentService.get_document(dataset.id, document_data["original_document_id"])
  903. if document is None:
  904. raise NotFound("Document not found")
  905. if document.display_status != "available":
  906. raise ValueError("Document is not available")
  907. # save process rule
  908. if document_data.get("process_rule"):
  909. process_rule = document_data["process_rule"]
  910. if process_rule["mode"] == "custom":
  911. dataset_process_rule = DatasetProcessRule(
  912. dataset_id=dataset.id,
  913. mode=process_rule["mode"],
  914. rules=json.dumps(process_rule["rules"]),
  915. created_by=account.id,
  916. )
  917. elif process_rule["mode"] == "automatic":
  918. dataset_process_rule = DatasetProcessRule(
  919. dataset_id=dataset.id,
  920. mode=process_rule["mode"],
  921. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  922. created_by=account.id,
  923. )
  924. db.session.add(dataset_process_rule)
  925. db.session.commit()
  926. document.dataset_process_rule_id = dataset_process_rule.id
  927. # update document data source
  928. if document_data.get("data_source"):
  929. file_name = ""
  930. data_source_info = {}
  931. if document_data["data_source"]["type"] == "upload_file":
  932. upload_file_list = document_data["data_source"]["info_list"]["file_info_list"]["file_ids"]
  933. for file_id in upload_file_list:
  934. file = (
  935. db.session.query(UploadFile)
  936. .filter(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  937. .first()
  938. )
  939. # raise error if file not found
  940. if not file:
  941. raise FileNotExistsError()
  942. file_name = file.name
  943. data_source_info = {
  944. "upload_file_id": file_id,
  945. }
  946. elif document_data["data_source"]["type"] == "notion_import":
  947. notion_info_list = document_data["data_source"]["info_list"]["notion_info_list"]
  948. for notion_info in notion_info_list:
  949. workspace_id = notion_info["workspace_id"]
  950. data_source_binding = DataSourceOauthBinding.query.filter(
  951. db.and_(
  952. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  953. DataSourceOauthBinding.provider == "notion",
  954. DataSourceOauthBinding.disabled == False,
  955. DataSourceOauthBinding.source_info["workspace_id"] == f'"{workspace_id}"',
  956. )
  957. ).first()
  958. if not data_source_binding:
  959. raise ValueError("Data source binding not found.")
  960. for page in notion_info["pages"]:
  961. data_source_info = {
  962. "notion_workspace_id": workspace_id,
  963. "notion_page_id": page["page_id"],
  964. "notion_page_icon": page["page_icon"],
  965. "type": page["type"],
  966. }
  967. elif document_data["data_source"]["type"] == "website_crawl":
  968. website_info = document_data["data_source"]["info_list"]["website_info_list"]
  969. urls = website_info["urls"]
  970. for url in urls:
  971. data_source_info = {
  972. "url": url,
  973. "provider": website_info["provider"],
  974. "job_id": website_info["job_id"],
  975. "only_main_content": website_info.get("only_main_content", False),
  976. "mode": "crawl",
  977. }
  978. document.data_source_type = document_data["data_source"]["type"]
  979. document.data_source_info = json.dumps(data_source_info)
  980. document.name = file_name
  981. # update document name
  982. if document_data.get("name"):
  983. document.name = document_data["name"]
  984. # update document to be waiting
  985. document.indexing_status = "waiting"
  986. document.completed_at = None
  987. document.processing_started_at = None
  988. document.parsing_completed_at = None
  989. document.cleaning_completed_at = None
  990. document.splitting_completed_at = None
  991. document.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  992. document.created_from = created_from
  993. document.doc_form = document_data["doc_form"]
  994. db.session.add(document)
  995. db.session.commit()
  996. # update document segment
  997. update_params = {DocumentSegment.status: "re_segment"}
  998. DocumentSegment.query.filter_by(document_id=document.id).update(update_params)
  999. db.session.commit()
  1000. # trigger async task
  1001. document_indexing_update_task.delay(document.dataset_id, document.id)
  1002. return document
  1003. @staticmethod
  1004. def save_document_without_dataset_id(tenant_id: str, document_data: dict, account: Account):
  1005. features = FeatureService.get_features(current_user.current_tenant_id)
  1006. if features.billing.enabled:
  1007. count = 0
  1008. if document_data["data_source"]["type"] == "upload_file":
  1009. upload_file_list = document_data["data_source"]["info_list"]["file_info_list"]["file_ids"]
  1010. count = len(upload_file_list)
  1011. elif document_data["data_source"]["type"] == "notion_import":
  1012. notion_info_list = document_data["data_source"]["info_list"]["notion_info_list"]
  1013. for notion_info in notion_info_list:
  1014. count = count + len(notion_info["pages"])
  1015. elif document_data["data_source"]["type"] == "website_crawl":
  1016. website_info = document_data["data_source"]["info_list"]["website_info_list"]
  1017. count = len(website_info["urls"])
  1018. batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  1019. if count > batch_upload_limit:
  1020. raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  1021. DocumentService.check_documents_upload_quota(count, features)
  1022. dataset_collection_binding_id = None
  1023. retrieval_model = None
  1024. if document_data["indexing_technique"] == "high_quality":
  1025. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  1026. document_data["embedding_model_provider"], document_data["embedding_model"]
  1027. )
  1028. dataset_collection_binding_id = dataset_collection_binding.id
  1029. if document_data.get("retrieval_model"):
  1030. retrieval_model = document_data["retrieval_model"]
  1031. else:
  1032. default_retrieval_model = {
  1033. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  1034. "reranking_enable": False,
  1035. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  1036. "top_k": 2,
  1037. "score_threshold_enabled": False,
  1038. }
  1039. retrieval_model = default_retrieval_model
  1040. # save dataset
  1041. dataset = Dataset(
  1042. tenant_id=tenant_id,
  1043. name="",
  1044. data_source_type=document_data["data_source"]["type"],
  1045. indexing_technique=document_data.get("indexing_technique", "high_quality"),
  1046. created_by=account.id,
  1047. embedding_model=document_data.get("embedding_model"),
  1048. embedding_model_provider=document_data.get("embedding_model_provider"),
  1049. collection_binding_id=dataset_collection_binding_id,
  1050. retrieval_model=retrieval_model,
  1051. )
  1052. db.session.add(dataset)
  1053. db.session.flush()
  1054. documents, batch = DocumentService.save_document_with_dataset_id(dataset, document_data, account)
  1055. cut_length = 18
  1056. cut_name = documents[0].name[:cut_length]
  1057. dataset.name = cut_name + "..."
  1058. dataset.description = "useful for when you want to answer queries about the " + documents[0].name
  1059. db.session.commit()
  1060. return dataset, documents, batch
  1061. @classmethod
  1062. def document_create_args_validate(cls, args: dict):
  1063. if "original_document_id" not in args or not args["original_document_id"]:
  1064. DocumentService.data_source_args_validate(args)
  1065. DocumentService.process_rule_args_validate(args)
  1066. else:
  1067. if ("data_source" not in args or not args["data_source"]) and (
  1068. "process_rule" not in args or not args["process_rule"]
  1069. ):
  1070. raise ValueError("Data source or Process rule is required")
  1071. else:
  1072. if args.get("data_source"):
  1073. DocumentService.data_source_args_validate(args)
  1074. if args.get("process_rule"):
  1075. DocumentService.process_rule_args_validate(args)
  1076. @classmethod
  1077. def data_source_args_validate(cls, args: dict):
  1078. if "data_source" not in args or not args["data_source"]:
  1079. raise ValueError("Data source is required")
  1080. if not isinstance(args["data_source"], dict):
  1081. raise ValueError("Data source is invalid")
  1082. if "type" not in args["data_source"] or not args["data_source"]["type"]:
  1083. raise ValueError("Data source type is required")
  1084. if args["data_source"]["type"] not in Document.DATA_SOURCES:
  1085. raise ValueError("Data source type is invalid")
  1086. if "info_list" not in args["data_source"] or not args["data_source"]["info_list"]:
  1087. raise ValueError("Data source info is required")
  1088. if args["data_source"]["type"] == "upload_file":
  1089. if (
  1090. "file_info_list" not in args["data_source"]["info_list"]
  1091. or not args["data_source"]["info_list"]["file_info_list"]
  1092. ):
  1093. raise ValueError("File source info is required")
  1094. if args["data_source"]["type"] == "notion_import":
  1095. if (
  1096. "notion_info_list" not in args["data_source"]["info_list"]
  1097. or not args["data_source"]["info_list"]["notion_info_list"]
  1098. ):
  1099. raise ValueError("Notion source info is required")
  1100. if args["data_source"]["type"] == "website_crawl":
  1101. if (
  1102. "website_info_list" not in args["data_source"]["info_list"]
  1103. or not args["data_source"]["info_list"]["website_info_list"]
  1104. ):
  1105. raise ValueError("Website source info is required")
  1106. @classmethod
  1107. def process_rule_args_validate(cls, args: dict):
  1108. if "process_rule" not in args or not args["process_rule"]:
  1109. raise ValueError("Process rule is required")
  1110. if not isinstance(args["process_rule"], dict):
  1111. raise ValueError("Process rule is invalid")
  1112. if "mode" not in args["process_rule"] or not args["process_rule"]["mode"]:
  1113. raise ValueError("Process rule mode is required")
  1114. if args["process_rule"]["mode"] not in DatasetProcessRule.MODES:
  1115. raise ValueError("Process rule mode is invalid")
  1116. if args["process_rule"]["mode"] == "automatic":
  1117. args["process_rule"]["rules"] = {}
  1118. else:
  1119. if "rules" not in args["process_rule"] or not args["process_rule"]["rules"]:
  1120. raise ValueError("Process rule rules is required")
  1121. if not isinstance(args["process_rule"]["rules"], dict):
  1122. raise ValueError("Process rule rules is invalid")
  1123. if (
  1124. "pre_processing_rules" not in args["process_rule"]["rules"]
  1125. or args["process_rule"]["rules"]["pre_processing_rules"] is None
  1126. ):
  1127. raise ValueError("Process rule pre_processing_rules is required")
  1128. if not isinstance(args["process_rule"]["rules"]["pre_processing_rules"], list):
  1129. raise ValueError("Process rule pre_processing_rules is invalid")
  1130. unique_pre_processing_rule_dicts = {}
  1131. for pre_processing_rule in args["process_rule"]["rules"]["pre_processing_rules"]:
  1132. if "id" not in pre_processing_rule or not pre_processing_rule["id"]:
  1133. raise ValueError("Process rule pre_processing_rules id is required")
  1134. if pre_processing_rule["id"] not in DatasetProcessRule.PRE_PROCESSING_RULES:
  1135. raise ValueError("Process rule pre_processing_rules id is invalid")
  1136. if "enabled" not in pre_processing_rule or pre_processing_rule["enabled"] is None:
  1137. raise ValueError("Process rule pre_processing_rules enabled is required")
  1138. if not isinstance(pre_processing_rule["enabled"], bool):
  1139. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  1140. unique_pre_processing_rule_dicts[pre_processing_rule["id"]] = pre_processing_rule
  1141. args["process_rule"]["rules"]["pre_processing_rules"] = list(unique_pre_processing_rule_dicts.values())
  1142. if (
  1143. "segmentation" not in args["process_rule"]["rules"]
  1144. or args["process_rule"]["rules"]["segmentation"] is None
  1145. ):
  1146. raise ValueError("Process rule segmentation is required")
  1147. if not isinstance(args["process_rule"]["rules"]["segmentation"], dict):
  1148. raise ValueError("Process rule segmentation is invalid")
  1149. if (
  1150. "separator" not in args["process_rule"]["rules"]["segmentation"]
  1151. or not args["process_rule"]["rules"]["segmentation"]["separator"]
  1152. ):
  1153. raise ValueError("Process rule segmentation separator is required")
  1154. if not isinstance(args["process_rule"]["rules"]["segmentation"]["separator"], str):
  1155. raise ValueError("Process rule segmentation separator is invalid")
  1156. if (
  1157. "max_tokens" not in args["process_rule"]["rules"]["segmentation"]
  1158. or not args["process_rule"]["rules"]["segmentation"]["max_tokens"]
  1159. ):
  1160. raise ValueError("Process rule segmentation max_tokens is required")
  1161. if not isinstance(args["process_rule"]["rules"]["segmentation"]["max_tokens"], int):
  1162. raise ValueError("Process rule segmentation max_tokens is invalid")
  1163. @classmethod
  1164. def estimate_args_validate(cls, args: dict):
  1165. if "info_list" not in args or not args["info_list"]:
  1166. raise ValueError("Data source info is required")
  1167. if not isinstance(args["info_list"], dict):
  1168. raise ValueError("Data info is invalid")
  1169. if "process_rule" not in args or not args["process_rule"]:
  1170. raise ValueError("Process rule is required")
  1171. if not isinstance(args["process_rule"], dict):
  1172. raise ValueError("Process rule is invalid")
  1173. if "mode" not in args["process_rule"] or not args["process_rule"]["mode"]:
  1174. raise ValueError("Process rule mode is required")
  1175. if args["process_rule"]["mode"] not in DatasetProcessRule.MODES:
  1176. raise ValueError("Process rule mode is invalid")
  1177. if args["process_rule"]["mode"] == "automatic":
  1178. args["process_rule"]["rules"] = {}
  1179. else:
  1180. if "rules" not in args["process_rule"] or not args["process_rule"]["rules"]:
  1181. raise ValueError("Process rule rules is required")
  1182. if not isinstance(args["process_rule"]["rules"], dict):
  1183. raise ValueError("Process rule rules is invalid")
  1184. if (
  1185. "pre_processing_rules" not in args["process_rule"]["rules"]
  1186. or args["process_rule"]["rules"]["pre_processing_rules"] is None
  1187. ):
  1188. raise ValueError("Process rule pre_processing_rules is required")
  1189. if not isinstance(args["process_rule"]["rules"]["pre_processing_rules"], list):
  1190. raise ValueError("Process rule pre_processing_rules is invalid")
  1191. unique_pre_processing_rule_dicts = {}
  1192. for pre_processing_rule in args["process_rule"]["rules"]["pre_processing_rules"]:
  1193. if "id" not in pre_processing_rule or not pre_processing_rule["id"]:
  1194. raise ValueError("Process rule pre_processing_rules id is required")
  1195. if pre_processing_rule["id"] not in DatasetProcessRule.PRE_PROCESSING_RULES:
  1196. raise ValueError("Process rule pre_processing_rules id is invalid")
  1197. if "enabled" not in pre_processing_rule or pre_processing_rule["enabled"] is None:
  1198. raise ValueError("Process rule pre_processing_rules enabled is required")
  1199. if not isinstance(pre_processing_rule["enabled"], bool):
  1200. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  1201. unique_pre_processing_rule_dicts[pre_processing_rule["id"]] = pre_processing_rule
  1202. args["process_rule"]["rules"]["pre_processing_rules"] = list(unique_pre_processing_rule_dicts.values())
  1203. if (
  1204. "segmentation" not in args["process_rule"]["rules"]
  1205. or args["process_rule"]["rules"]["segmentation"] is None
  1206. ):
  1207. raise ValueError("Process rule segmentation is required")
  1208. if not isinstance(args["process_rule"]["rules"]["segmentation"], dict):
  1209. raise ValueError("Process rule segmentation is invalid")
  1210. if (
  1211. "separator" not in args["process_rule"]["rules"]["segmentation"]
  1212. or not args["process_rule"]["rules"]["segmentation"]["separator"]
  1213. ):
  1214. raise ValueError("Process rule segmentation separator is required")
  1215. if not isinstance(args["process_rule"]["rules"]["segmentation"]["separator"], str):
  1216. raise ValueError("Process rule segmentation separator is invalid")
  1217. if (
  1218. "max_tokens" not in args["process_rule"]["rules"]["segmentation"]
  1219. or not args["process_rule"]["rules"]["segmentation"]["max_tokens"]
  1220. ):
  1221. raise ValueError("Process rule segmentation max_tokens is required")
  1222. if not isinstance(args["process_rule"]["rules"]["segmentation"]["max_tokens"], int):
  1223. raise ValueError("Process rule segmentation max_tokens is invalid")
  1224. class SegmentService:
  1225. @classmethod
  1226. def segment_create_args_validate(cls, args: dict, document: Document):
  1227. if document.doc_form == "qa_model":
  1228. if "answer" not in args or not args["answer"]:
  1229. raise ValueError("Answer is required")
  1230. if not args["answer"].strip():
  1231. raise ValueError("Answer is empty")
  1232. if "content" not in args or not args["content"] or not args["content"].strip():
  1233. raise ValueError("Content is empty")
  1234. @classmethod
  1235. def create_segment(cls, args: dict, document: Document, dataset: Dataset):
  1236. content = args["content"]
  1237. doc_id = str(uuid.uuid4())
  1238. segment_hash = helper.generate_text_hash(content)
  1239. tokens = 0
  1240. if dataset.indexing_technique == "high_quality":
  1241. model_manager = ModelManager()
  1242. embedding_model = model_manager.get_model_instance(
  1243. tenant_id=current_user.current_tenant_id,
  1244. provider=dataset.embedding_model_provider,
  1245. model_type=ModelType.TEXT_EMBEDDING,
  1246. model=dataset.embedding_model,
  1247. )
  1248. # calc embedding use tokens
  1249. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])
  1250. lock_name = "add_segment_lock_document_id_{}".format(document.id)
  1251. with redis_client.lock(lock_name, timeout=600):
  1252. max_position = (
  1253. db.session.query(func.max(DocumentSegment.position))
  1254. .filter(DocumentSegment.document_id == document.id)
  1255. .scalar()
  1256. )
  1257. segment_document = DocumentSegment(
  1258. tenant_id=current_user.current_tenant_id,
  1259. dataset_id=document.dataset_id,
  1260. document_id=document.id,
  1261. index_node_id=doc_id,
  1262. index_node_hash=segment_hash,
  1263. position=max_position + 1 if max_position else 1,
  1264. content=content,
  1265. word_count=len(content),
  1266. tokens=tokens,
  1267. status="completed",
  1268. indexing_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1269. completed_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1270. created_by=current_user.id,
  1271. )
  1272. if document.doc_form == "qa_model":
  1273. segment_document.word_count += len(args["answer"])
  1274. segment_document.answer = args["answer"]
  1275. db.session.add(segment_document)
  1276. # update document word count
  1277. document.word_count += segment_document.word_count
  1278. db.session.add(document)
  1279. db.session.commit()
  1280. # save vector index
  1281. try:
  1282. VectorService.create_segments_vector([args["keywords"]], [segment_document], dataset)
  1283. except Exception as e:
  1284. logging.exception("create segment index failed")
  1285. segment_document.enabled = False
  1286. segment_document.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1287. segment_document.status = "error"
  1288. segment_document.error = str(e)
  1289. db.session.commit()
  1290. segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment_document.id).first()
  1291. return segment
  1292. @classmethod
  1293. def multi_create_segment(cls, segments: list, document: Document, dataset: Dataset):
  1294. lock_name = "multi_add_segment_lock_document_id_{}".format(document.id)
  1295. increment_word_count = 0
  1296. with redis_client.lock(lock_name, timeout=600):
  1297. embedding_model = None
  1298. if dataset.indexing_technique == "high_quality":
  1299. model_manager = ModelManager()
  1300. embedding_model = model_manager.get_model_instance(
  1301. tenant_id=current_user.current_tenant_id,
  1302. provider=dataset.embedding_model_provider,
  1303. model_type=ModelType.TEXT_EMBEDDING,
  1304. model=dataset.embedding_model,
  1305. )
  1306. max_position = (
  1307. db.session.query(func.max(DocumentSegment.position))
  1308. .filter(DocumentSegment.document_id == document.id)
  1309. .scalar()
  1310. )
  1311. pre_segment_data_list = []
  1312. segment_data_list = []
  1313. keywords_list = []
  1314. position = max_position + 1 if max_position else 1
  1315. for segment_item in segments:
  1316. content = segment_item["content"]
  1317. doc_id = str(uuid.uuid4())
  1318. segment_hash = helper.generate_text_hash(content)
  1319. tokens = 0
  1320. if dataset.indexing_technique == "high_quality" and embedding_model:
  1321. # calc embedding use tokens
  1322. if document.doc_form == "qa_model":
  1323. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content + segment_item["answer"]])
  1324. else:
  1325. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])
  1326. segment_document = DocumentSegment(
  1327. tenant_id=current_user.current_tenant_id,
  1328. dataset_id=document.dataset_id,
  1329. document_id=document.id,
  1330. index_node_id=doc_id,
  1331. index_node_hash=segment_hash,
  1332. position=position,
  1333. content=content,
  1334. word_count=len(content),
  1335. tokens=tokens,
  1336. status="completed",
  1337. indexing_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1338. completed_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1339. created_by=current_user.id,
  1340. )
  1341. if document.doc_form == "qa_model":
  1342. segment_document.answer = segment_item["answer"]
  1343. segment_document.word_count += len(segment_item["answer"])
  1344. increment_word_count += segment_document.word_count
  1345. db.session.add(segment_document)
  1346. segment_data_list.append(segment_document)
  1347. position += 1
  1348. pre_segment_data_list.append(segment_document)
  1349. if "keywords" in segment_item:
  1350. keywords_list.append(segment_item["keywords"])
  1351. else:
  1352. keywords_list.append(None)
  1353. # update document word count
  1354. document.word_count += increment_word_count
  1355. db.session.add(document)
  1356. try:
  1357. # save vector index
  1358. VectorService.create_segments_vector(keywords_list, pre_segment_data_list, dataset)
  1359. except Exception as e:
  1360. logging.exception("create segment index failed")
  1361. for segment_document in segment_data_list:
  1362. segment_document.enabled = False
  1363. segment_document.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1364. segment_document.status = "error"
  1365. segment_document.error = str(e)
  1366. db.session.commit()
  1367. return segment_data_list
  1368. @classmethod
  1369. def update_segment(cls, args: dict, segment: DocumentSegment, document: Document, dataset: Dataset):
  1370. segment_update_entity = SegmentUpdateEntity(**args)
  1371. indexing_cache_key = "segment_{}_indexing".format(segment.id)
  1372. cache_result = redis_client.get(indexing_cache_key)
  1373. if cache_result is not None:
  1374. raise ValueError("Segment is indexing, please try again later")
  1375. if segment_update_entity.enabled is not None:
  1376. action = segment_update_entity.enabled
  1377. if segment.enabled != action:
  1378. if not action:
  1379. segment.enabled = action
  1380. segment.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1381. segment.disabled_by = current_user.id
  1382. db.session.add(segment)
  1383. db.session.commit()
  1384. # Set cache to prevent indexing the same segment multiple times
  1385. redis_client.setex(indexing_cache_key, 600, 1)
  1386. disable_segment_from_index_task.delay(segment.id)
  1387. return segment
  1388. if not segment.enabled:
  1389. if segment_update_entity.enabled is not None:
  1390. if not segment_update_entity.enabled:
  1391. raise ValueError("Can't update disabled segment")
  1392. else:
  1393. raise ValueError("Can't update disabled segment")
  1394. try:
  1395. word_count_change = segment.word_count
  1396. content = segment_update_entity.content
  1397. if segment.content == content:
  1398. segment.word_count = len(content)
  1399. if document.doc_form == "qa_model":
  1400. segment.answer = segment_update_entity.answer
  1401. segment.word_count += len(segment_update_entity.answer)
  1402. word_count_change = segment.word_count - word_count_change
  1403. if segment_update_entity.keywords:
  1404. segment.keywords = segment_update_entity.keywords
  1405. segment.enabled = True
  1406. segment.disabled_at = None
  1407. segment.disabled_by = None
  1408. db.session.add(segment)
  1409. db.session.commit()
  1410. # update document word count
  1411. if word_count_change != 0:
  1412. document.word_count = max(0, document.word_count + word_count_change)
  1413. db.session.add(document)
  1414. # update segment index task
  1415. if segment_update_entity.enabled:
  1416. VectorService.create_segments_vector([segment_update_entity.keywords], [segment], dataset)
  1417. else:
  1418. segment_hash = helper.generate_text_hash(content)
  1419. tokens = 0
  1420. if dataset.indexing_technique == "high_quality":
  1421. model_manager = ModelManager()
  1422. embedding_model = model_manager.get_model_instance(
  1423. tenant_id=current_user.current_tenant_id,
  1424. provider=dataset.embedding_model_provider,
  1425. model_type=ModelType.TEXT_EMBEDDING,
  1426. model=dataset.embedding_model,
  1427. )
  1428. # calc embedding use tokens
  1429. if document.doc_form == "qa_model":
  1430. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content + segment.answer])
  1431. else:
  1432. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])
  1433. segment.content = content
  1434. segment.index_node_hash = segment_hash
  1435. segment.word_count = len(content)
  1436. segment.tokens = tokens
  1437. segment.status = "completed"
  1438. segment.indexing_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1439. segment.completed_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1440. segment.updated_by = current_user.id
  1441. segment.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1442. segment.enabled = True
  1443. segment.disabled_at = None
  1444. segment.disabled_by = None
  1445. if document.doc_form == "qa_model":
  1446. segment.answer = segment_update_entity.answer
  1447. segment.word_count += len(segment_update_entity.answer)
  1448. word_count_change = segment.word_count - word_count_change
  1449. # update document word count
  1450. if word_count_change != 0:
  1451. document.word_count = max(0, document.word_count + word_count_change)
  1452. db.session.add(document)
  1453. db.session.add(segment)
  1454. db.session.commit()
  1455. # update segment vector index
  1456. VectorService.update_segment_vector(segment_update_entity.keywords, segment, dataset)
  1457. except Exception as e:
  1458. logging.exception("update segment index failed")
  1459. segment.enabled = False
  1460. segment.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1461. segment.status = "error"
  1462. segment.error = str(e)
  1463. db.session.commit()
  1464. segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment.id).first()
  1465. return segment
  1466. @classmethod
  1467. def delete_segment(cls, segment: DocumentSegment, document: Document, dataset: Dataset):
  1468. indexing_cache_key = "segment_{}_delete_indexing".format(segment.id)
  1469. cache_result = redis_client.get(indexing_cache_key)
  1470. if cache_result is not None:
  1471. raise ValueError("Segment is deleting.")
  1472. # enabled segment need to delete index
  1473. if segment.enabled:
  1474. # send delete segment index task
  1475. redis_client.setex(indexing_cache_key, 600, 1)
  1476. delete_segment_from_index_task.delay(segment.id, segment.index_node_id, dataset.id, document.id)
  1477. db.session.delete(segment)
  1478. # update document word count
  1479. document.word_count -= segment.word_count
  1480. db.session.add(document)
  1481. db.session.commit()
  1482. class DatasetCollectionBindingService:
  1483. @classmethod
  1484. def get_dataset_collection_binding(
  1485. cls, provider_name: str, model_name: str, collection_type: str = "dataset"
  1486. ) -> DatasetCollectionBinding:
  1487. dataset_collection_binding = (
  1488. db.session.query(DatasetCollectionBinding)
  1489. .filter(
  1490. DatasetCollectionBinding.provider_name == provider_name,
  1491. DatasetCollectionBinding.model_name == model_name,
  1492. DatasetCollectionBinding.type == collection_type,
  1493. )
  1494. .order_by(DatasetCollectionBinding.created_at)
  1495. .first()
  1496. )
  1497. if not dataset_collection_binding:
  1498. dataset_collection_binding = DatasetCollectionBinding(
  1499. provider_name=provider_name,
  1500. model_name=model_name,
  1501. collection_name=Dataset.gen_collection_name_by_id(str(uuid.uuid4())),
  1502. type=collection_type,
  1503. )
  1504. db.session.add(dataset_collection_binding)
  1505. db.session.commit()
  1506. return dataset_collection_binding
  1507. @classmethod
  1508. def get_dataset_collection_binding_by_id_and_type(
  1509. cls, collection_binding_id: str, collection_type: str = "dataset"
  1510. ) -> DatasetCollectionBinding:
  1511. dataset_collection_binding = (
  1512. db.session.query(DatasetCollectionBinding)
  1513. .filter(
  1514. DatasetCollectionBinding.id == collection_binding_id, DatasetCollectionBinding.type == collection_type
  1515. )
  1516. .order_by(DatasetCollectionBinding.created_at)
  1517. .first()
  1518. )
  1519. return dataset_collection_binding
  1520. class DatasetPermissionService:
  1521. @classmethod
  1522. def get_dataset_partial_member_list(cls, dataset_id):
  1523. user_list_query = (
  1524. db.session.query(
  1525. DatasetPermission.account_id,
  1526. )
  1527. .filter(DatasetPermission.dataset_id == dataset_id)
  1528. .all()
  1529. )
  1530. user_list = []
  1531. for user in user_list_query:
  1532. user_list.append(user.account_id)
  1533. return user_list
  1534. @classmethod
  1535. def update_partial_member_list(cls, tenant_id, dataset_id, user_list):
  1536. try:
  1537. db.session.query(DatasetPermission).filter(DatasetPermission.dataset_id == dataset_id).delete()
  1538. permissions = []
  1539. for user in user_list:
  1540. permission = DatasetPermission(
  1541. tenant_id=tenant_id,
  1542. dataset_id=dataset_id,
  1543. account_id=user["user_id"],
  1544. )
  1545. permissions.append(permission)
  1546. db.session.add_all(permissions)
  1547. db.session.commit()
  1548. except Exception as e:
  1549. db.session.rollback()
  1550. raise e
  1551. @classmethod
  1552. def check_permission(cls, user, dataset, requested_permission, requested_partial_member_list):
  1553. if not user.is_dataset_editor:
  1554. raise NoPermissionError("User does not have permission to edit this dataset.")
  1555. if user.is_dataset_operator and dataset.permission != requested_permission:
  1556. raise NoPermissionError("Dataset operators cannot change the dataset permissions.")
  1557. if user.is_dataset_operator and requested_permission == "partial_members":
  1558. if not requested_partial_member_list:
  1559. raise ValueError("Partial member list is required when setting to partial members.")
  1560. local_member_list = cls.get_dataset_partial_member_list(dataset.id)
  1561. request_member_list = [user["user_id"] for user in requested_partial_member_list]
  1562. if set(local_member_list) != set(request_member_list):
  1563. raise ValueError("Dataset operators cannot change the dataset permissions.")
  1564. @classmethod
  1565. def clear_partial_member_list(cls, dataset_id):
  1566. try:
  1567. db.session.query(DatasetPermission).filter(DatasetPermission.dataset_id == dataset_id).delete()
  1568. db.session.commit()
  1569. except Exception as e:
  1570. db.session.rollback()
  1571. raise e