Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

dataset_service.py 78KB

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