dataset_service.py 79 KB

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