您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

dataset_service.py 107KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341
  1. import copy
  2. import datetime
  3. import json
  4. import logging
  5. import random
  6. import time
  7. import uuid
  8. from collections import Counter
  9. from typing import Any, Optional
  10. from flask_login import current_user # type: ignore
  11. from sqlalchemy import func
  12. from sqlalchemy.orm import Session
  13. from werkzeug.exceptions import NotFound
  14. from configs import dify_config
  15. from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
  16. from core.model_manager import ModelManager
  17. from core.model_runtime.entities.model_entities import ModelType
  18. from core.plugin.entities.plugin import ModelProviderID
  19. from core.rag.index_processor.constant.built_in_field import BuiltInField
  20. from core.rag.index_processor.constant.index_type import IndexType
  21. from core.rag.retrieval.retrieval_methods import RetrievalMethod
  22. from core.tools.entities.common_entities import I18nObject
  23. from events.dataset_event import dataset_was_deleted
  24. from events.document_event import document_was_deleted
  25. from extensions.ext_database import db
  26. from extensions.ext_redis import redis_client
  27. from libs import helper
  28. from models.account import Account, TenantAccountRole
  29. from models.dataset import (
  30. AppDatasetJoin,
  31. ChildChunk,
  32. Dataset,
  33. DatasetAutoDisableLog,
  34. DatasetCollectionBinding,
  35. DatasetPermission,
  36. DatasetPermissionEnum,
  37. DatasetProcessRule,
  38. DatasetQuery,
  39. Document,
  40. DocumentSegment,
  41. ExternalKnowledgeBindings,
  42. )
  43. from models.model import UploadFile
  44. from models.source import DataSourceOauthBinding
  45. from services.entities.knowledge_entities.knowledge_entities import (
  46. ChildChunkUpdateArgs,
  47. KnowledgeConfig,
  48. RerankingModel,
  49. RetrievalModel,
  50. SegmentUpdateArgs,
  51. )
  52. from services.errors.account import InvalidActionError, NoPermissionError
  53. from services.errors.chunk import ChildChunkDeleteIndexError, ChildChunkIndexingError
  54. from services.errors.dataset import DatasetNameDuplicateError
  55. from services.errors.document import DocumentIndexingError
  56. from services.errors.file import FileNotExistsError
  57. from services.external_knowledge_service import ExternalDatasetService
  58. from services.feature_service import FeatureModel, FeatureService
  59. from services.tag_service import TagService
  60. from services.vector_service import VectorService
  61. from tasks.batch_clean_document_task import batch_clean_document_task
  62. from tasks.clean_notion_document_task import clean_notion_document_task
  63. from tasks.deal_dataset_vector_index_task import deal_dataset_vector_index_task
  64. from tasks.delete_segment_from_index_task import delete_segment_from_index_task
  65. from tasks.disable_segment_from_index_task import disable_segment_from_index_task
  66. from tasks.disable_segments_from_index_task import disable_segments_from_index_task
  67. from tasks.document_indexing_task import document_indexing_task
  68. from tasks.document_indexing_update_task import document_indexing_update_task
  69. from tasks.duplicate_document_indexing_task import duplicate_document_indexing_task
  70. from tasks.enable_segments_to_index_task import enable_segments_to_index_task
  71. from tasks.recover_document_indexing_task import recover_document_indexing_task
  72. from tasks.retry_document_indexing_task import retry_document_indexing_task
  73. from tasks.sync_website_document_indexing_task import sync_website_document_indexing_task
  74. class DatasetService:
  75. @staticmethod
  76. def get_datasets(page, per_page, tenant_id=None, user=None, search=None, tag_ids=None, include_all=False):
  77. query = Dataset.query.filter(Dataset.tenant_id == tenant_id).order_by(Dataset.created_at.desc())
  78. if user:
  79. # get permitted dataset ids
  80. dataset_permission = DatasetPermission.query.filter_by(account_id=user.id, tenant_id=tenant_id).all()
  81. permitted_dataset_ids = {dp.dataset_id for dp in dataset_permission} if dataset_permission else None
  82. if user.current_role == TenantAccountRole.DATASET_OPERATOR:
  83. # only show datasets that the user has permission to access
  84. if permitted_dataset_ids:
  85. query = query.filter(Dataset.id.in_(permitted_dataset_ids))
  86. else:
  87. return [], 0
  88. else:
  89. if user.current_role != TenantAccountRole.OWNER or not include_all:
  90. # show all datasets that the user has permission to access
  91. if permitted_dataset_ids:
  92. query = query.filter(
  93. db.or_(
  94. Dataset.permission == DatasetPermissionEnum.ALL_TEAM,
  95. db.and_(
  96. Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id
  97. ),
  98. db.and_(
  99. Dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM,
  100. Dataset.id.in_(permitted_dataset_ids),
  101. ),
  102. )
  103. )
  104. else:
  105. query = query.filter(
  106. db.or_(
  107. Dataset.permission == DatasetPermissionEnum.ALL_TEAM,
  108. db.and_(
  109. Dataset.permission == DatasetPermissionEnum.ONLY_ME, Dataset.created_by == user.id
  110. ),
  111. )
  112. )
  113. else:
  114. # if no user, only show datasets that are shared with all team members
  115. query = query.filter(Dataset.permission == DatasetPermissionEnum.ALL_TEAM)
  116. if search:
  117. query = query.filter(Dataset.name.ilike(f"%{search}%"))
  118. if tag_ids:
  119. target_ids = TagService.get_target_ids_by_tag_ids("knowledge", tenant_id, tag_ids)
  120. if target_ids:
  121. query = query.filter(Dataset.id.in_(target_ids))
  122. else:
  123. return [], 0
  124. datasets = query.paginate(page=page, per_page=per_page, max_per_page=100, error_out=False)
  125. return datasets.items, datasets.total
  126. @staticmethod
  127. def get_process_rules(dataset_id):
  128. # get the latest process rule
  129. dataset_process_rule = (
  130. db.session.query(DatasetProcessRule)
  131. .filter(DatasetProcessRule.dataset_id == dataset_id)
  132. .order_by(DatasetProcessRule.created_at.desc())
  133. .limit(1)
  134. .one_or_none()
  135. )
  136. if dataset_process_rule:
  137. mode = dataset_process_rule.mode
  138. rules = dataset_process_rule.rules_dict
  139. else:
  140. mode = DocumentService.DEFAULT_RULES["mode"]
  141. rules = DocumentService.DEFAULT_RULES["rules"]
  142. return {"mode": mode, "rules": rules}
  143. @staticmethod
  144. def get_datasets_by_ids(ids, tenant_id):
  145. datasets = Dataset.query.filter(Dataset.id.in_(ids), Dataset.tenant_id == tenant_id).paginate(
  146. page=1, per_page=len(ids), max_per_page=len(ids), error_out=False
  147. )
  148. return datasets.items, datasets.total
  149. @staticmethod
  150. def create_empty_dataset(
  151. tenant_id: str,
  152. name: str,
  153. description: Optional[str],
  154. indexing_technique: Optional[str],
  155. account: Account,
  156. permission: Optional[str] = None,
  157. provider: str = "vendor",
  158. external_knowledge_api_id: Optional[str] = None,
  159. external_knowledge_id: Optional[str] = None,
  160. ):
  161. # check if dataset name already exists
  162. if Dataset.query.filter_by(name=name, tenant_id=tenant_id).first():
  163. raise DatasetNameDuplicateError(f"Dataset with name {name} already exists.")
  164. embedding_model = None
  165. if indexing_technique == "high_quality":
  166. model_manager = ModelManager()
  167. embedding_model = model_manager.get_default_model_instance(
  168. tenant_id=tenant_id, model_type=ModelType.TEXT_EMBEDDING
  169. )
  170. dataset = Dataset(name=name, indexing_technique=indexing_technique)
  171. # dataset = Dataset(name=name, provider=provider, config=config)
  172. dataset.description = description
  173. dataset.created_by = account.id
  174. dataset.updated_by = account.id
  175. dataset.tenant_id = tenant_id
  176. dataset.embedding_model_provider = embedding_model.provider if embedding_model else None
  177. dataset.embedding_model = embedding_model.model if embedding_model else None
  178. dataset.permission = permission or DatasetPermissionEnum.ONLY_ME
  179. dataset.provider = provider
  180. db.session.add(dataset)
  181. db.session.flush()
  182. if provider == "external" and external_knowledge_api_id:
  183. external_knowledge_api = ExternalDatasetService.get_external_knowledge_api(external_knowledge_api_id)
  184. if not external_knowledge_api:
  185. raise ValueError("External API template not found.")
  186. external_knowledge_binding = ExternalKnowledgeBindings(
  187. tenant_id=tenant_id,
  188. dataset_id=dataset.id,
  189. external_knowledge_api_id=external_knowledge_api_id,
  190. external_knowledge_id=external_knowledge_id,
  191. created_by=account.id,
  192. )
  193. db.session.add(external_knowledge_binding)
  194. db.session.commit()
  195. return dataset
  196. @staticmethod
  197. def get_dataset(dataset_id) -> Optional[Dataset]:
  198. dataset: Optional[Dataset] = Dataset.query.filter_by(id=dataset_id).first()
  199. return dataset
  200. @staticmethod
  201. def check_dataset_model_setting(dataset):
  202. if dataset.indexing_technique == "high_quality":
  203. try:
  204. model_manager = ModelManager()
  205. model_manager.get_model_instance(
  206. tenant_id=dataset.tenant_id,
  207. provider=dataset.embedding_model_provider,
  208. model_type=ModelType.TEXT_EMBEDDING,
  209. model=dataset.embedding_model,
  210. )
  211. except LLMBadRequestError:
  212. raise ValueError(
  213. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  214. )
  215. except ProviderTokenNotInitError as ex:
  216. raise ValueError(f"The dataset in unavailable, due to: {ex.description}")
  217. @staticmethod
  218. def check_embedding_model_setting(tenant_id: str, embedding_model_provider: str, embedding_model: str):
  219. try:
  220. model_manager = ModelManager()
  221. model_manager.get_model_instance(
  222. tenant_id=tenant_id,
  223. provider=embedding_model_provider,
  224. model_type=ModelType.TEXT_EMBEDDING,
  225. model=embedding_model,
  226. )
  227. except LLMBadRequestError:
  228. raise ValueError(
  229. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  230. )
  231. except ProviderTokenNotInitError as ex:
  232. raise ValueError(ex.description)
  233. @staticmethod
  234. def update_dataset(dataset_id, data, user):
  235. dataset = DatasetService.get_dataset(dataset_id)
  236. if not dataset:
  237. raise ValueError("Dataset not found")
  238. DatasetService.check_dataset_permission(dataset, user)
  239. if dataset.provider == "external":
  240. external_retrieval_model = data.get("external_retrieval_model", None)
  241. if external_retrieval_model:
  242. dataset.retrieval_model = external_retrieval_model
  243. dataset.name = data.get("name", dataset.name)
  244. dataset.description = data.get("description", "")
  245. permission = data.get("permission")
  246. if permission:
  247. dataset.permission = permission
  248. external_knowledge_id = data.get("external_knowledge_id", None)
  249. db.session.add(dataset)
  250. if not external_knowledge_id:
  251. raise ValueError("External knowledge id is required.")
  252. external_knowledge_api_id = data.get("external_knowledge_api_id", None)
  253. if not external_knowledge_api_id:
  254. raise ValueError("External knowledge api id is required.")
  255. with Session(db.engine) as session:
  256. external_knowledge_binding = (
  257. session.query(ExternalKnowledgeBindings).filter_by(dataset_id=dataset_id).first()
  258. )
  259. if not external_knowledge_binding:
  260. raise ValueError("External knowledge binding not found.")
  261. if (
  262. external_knowledge_binding.external_knowledge_id != external_knowledge_id
  263. or external_knowledge_binding.external_knowledge_api_id != external_knowledge_api_id
  264. ):
  265. external_knowledge_binding.external_knowledge_id = external_knowledge_id
  266. external_knowledge_binding.external_knowledge_api_id = external_knowledge_api_id
  267. db.session.add(external_knowledge_binding)
  268. db.session.commit()
  269. else:
  270. data.pop("partial_member_list", None)
  271. data.pop("external_knowledge_api_id", None)
  272. data.pop("external_knowledge_id", None)
  273. data.pop("external_retrieval_model", None)
  274. filtered_data = {k: v for k, v in data.items() if v is not None or k == "description"}
  275. action = None
  276. if dataset.indexing_technique != data["indexing_technique"]:
  277. # if update indexing_technique
  278. if data["indexing_technique"] == "economy":
  279. action = "remove"
  280. filtered_data["embedding_model"] = None
  281. filtered_data["embedding_model_provider"] = None
  282. filtered_data["collection_binding_id"] = None
  283. elif data["indexing_technique"] == "high_quality":
  284. action = "add"
  285. # get embedding model setting
  286. try:
  287. model_manager = ModelManager()
  288. embedding_model = model_manager.get_model_instance(
  289. tenant_id=current_user.current_tenant_id,
  290. provider=data["embedding_model_provider"],
  291. model_type=ModelType.TEXT_EMBEDDING,
  292. model=data["embedding_model"],
  293. )
  294. filtered_data["embedding_model"] = embedding_model.model
  295. filtered_data["embedding_model_provider"] = embedding_model.provider
  296. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  297. embedding_model.provider, embedding_model.model
  298. )
  299. filtered_data["collection_binding_id"] = dataset_collection_binding.id
  300. except LLMBadRequestError:
  301. raise ValueError(
  302. "No Embedding Model available. Please configure a valid provider "
  303. "in the Settings -> Model Provider."
  304. )
  305. except ProviderTokenNotInitError as ex:
  306. raise ValueError(ex.description)
  307. else:
  308. # add default plugin id to both setting sets, to make sure the plugin model provider is consistent
  309. # Skip embedding model checks if not provided in the update request
  310. if (
  311. "embedding_model_provider" not in data
  312. or "embedding_model" not in data
  313. or not data.get("embedding_model_provider")
  314. or not data.get("embedding_model")
  315. ):
  316. # If the dataset already has embedding model settings, use those
  317. if dataset.embedding_model_provider and dataset.embedding_model:
  318. # Keep existing values
  319. filtered_data["embedding_model_provider"] = dataset.embedding_model_provider
  320. filtered_data["embedding_model"] = dataset.embedding_model
  321. # If collection_binding_id exists, keep it too
  322. if dataset.collection_binding_id:
  323. filtered_data["collection_binding_id"] = dataset.collection_binding_id
  324. # Otherwise, don't try to update embedding model settings at all
  325. # Remove these fields from filtered_data if they exist but are None/empty
  326. if "embedding_model_provider" in filtered_data and not filtered_data["embedding_model_provider"]:
  327. del filtered_data["embedding_model_provider"]
  328. if "embedding_model" in filtered_data and not filtered_data["embedding_model"]:
  329. del filtered_data["embedding_model"]
  330. else:
  331. skip_embedding_update = False
  332. try:
  333. # Handle existing model provider
  334. plugin_model_provider = dataset.embedding_model_provider
  335. plugin_model_provider_str = None
  336. if plugin_model_provider:
  337. plugin_model_provider_str = str(ModelProviderID(plugin_model_provider))
  338. # Handle new model provider from request
  339. new_plugin_model_provider = data["embedding_model_provider"]
  340. new_plugin_model_provider_str = None
  341. if new_plugin_model_provider:
  342. new_plugin_model_provider_str = str(ModelProviderID(new_plugin_model_provider))
  343. # Only update embedding model if both values are provided and different from current
  344. if (
  345. plugin_model_provider_str != new_plugin_model_provider_str
  346. or data["embedding_model"] != dataset.embedding_model
  347. ):
  348. action = "update"
  349. model_manager = ModelManager()
  350. try:
  351. embedding_model = model_manager.get_model_instance(
  352. tenant_id=current_user.current_tenant_id,
  353. provider=data["embedding_model_provider"],
  354. model_type=ModelType.TEXT_EMBEDDING,
  355. model=data["embedding_model"],
  356. )
  357. except ProviderTokenNotInitError:
  358. # If we can't get the embedding model, skip updating it
  359. # and keep the existing settings if available
  360. if dataset.embedding_model_provider and dataset.embedding_model:
  361. filtered_data["embedding_model_provider"] = dataset.embedding_model_provider
  362. filtered_data["embedding_model"] = dataset.embedding_model
  363. if dataset.collection_binding_id:
  364. filtered_data["collection_binding_id"] = dataset.collection_binding_id
  365. # Skip the rest of the embedding model update
  366. skip_embedding_update = True
  367. if not skip_embedding_update:
  368. filtered_data["embedding_model"] = embedding_model.model
  369. filtered_data["embedding_model_provider"] = embedding_model.provider
  370. dataset_collection_binding = (
  371. DatasetCollectionBindingService.get_dataset_collection_binding(
  372. embedding_model.provider, embedding_model.model
  373. )
  374. )
  375. filtered_data["collection_binding_id"] = dataset_collection_binding.id
  376. except LLMBadRequestError:
  377. raise ValueError(
  378. "No Embedding Model available. Please configure a valid provider "
  379. "in the Settings -> Model Provider."
  380. )
  381. except ProviderTokenNotInitError as ex:
  382. raise ValueError(ex.description)
  383. filtered_data["updated_by"] = user.id
  384. filtered_data["updated_at"] = datetime.datetime.now()
  385. # update Retrieval model
  386. filtered_data["retrieval_model"] = data["retrieval_model"]
  387. dataset.query.filter_by(id=dataset_id).update(filtered_data)
  388. db.session.commit()
  389. if action:
  390. deal_dataset_vector_index_task.delay(dataset_id, action)
  391. return dataset
  392. @staticmethod
  393. def delete_dataset(dataset_id, user):
  394. dataset = DatasetService.get_dataset(dataset_id)
  395. if dataset is None:
  396. return False
  397. DatasetService.check_dataset_permission(dataset, user)
  398. dataset_was_deleted.send(dataset)
  399. db.session.delete(dataset)
  400. db.session.commit()
  401. return True
  402. @staticmethod
  403. def dataset_use_check(dataset_id) -> bool:
  404. count = AppDatasetJoin.query.filter_by(dataset_id=dataset_id).count()
  405. if count > 0:
  406. return True
  407. return False
  408. @staticmethod
  409. def check_dataset_permission(dataset, user):
  410. if dataset.tenant_id != user.current_tenant_id:
  411. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  412. raise NoPermissionError("You do not have permission to access this dataset.")
  413. if user.current_role != TenantAccountRole.OWNER:
  414. if dataset.permission == DatasetPermissionEnum.ONLY_ME and dataset.created_by != user.id:
  415. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  416. raise NoPermissionError("You do not have permission to access this dataset.")
  417. if dataset.permission == "partial_members":
  418. user_permission = DatasetPermission.query.filter_by(dataset_id=dataset.id, account_id=user.id).first()
  419. if (
  420. not user_permission
  421. and dataset.tenant_id != user.current_tenant_id
  422. and dataset.created_by != user.id
  423. ):
  424. logging.debug(f"User {user.id} does not have permission to access dataset {dataset.id}")
  425. raise NoPermissionError("You do not have permission to access this dataset.")
  426. @staticmethod
  427. def check_dataset_operator_permission(user: Optional[Account] = None, dataset: Optional[Dataset] = None):
  428. if not dataset:
  429. raise ValueError("Dataset not found")
  430. if not user:
  431. raise ValueError("User not found")
  432. if user.current_role != TenantAccountRole.OWNER:
  433. if dataset.permission == DatasetPermissionEnum.ONLY_ME:
  434. if dataset.created_by != user.id:
  435. raise NoPermissionError("You do not have permission to access this dataset.")
  436. elif dataset.permission == DatasetPermissionEnum.PARTIAL_TEAM:
  437. if not any(
  438. dp.dataset_id == dataset.id for dp in DatasetPermission.query.filter_by(account_id=user.id).all()
  439. ):
  440. raise NoPermissionError("You do not have permission to access this dataset.")
  441. @staticmethod
  442. def get_dataset_queries(dataset_id: str, page: int, per_page: int):
  443. dataset_queries = (
  444. DatasetQuery.query.filter_by(dataset_id=dataset_id)
  445. .order_by(db.desc(DatasetQuery.created_at))
  446. .paginate(page=page, per_page=per_page, max_per_page=100, error_out=False)
  447. )
  448. return dataset_queries.items, dataset_queries.total
  449. @staticmethod
  450. def get_related_apps(dataset_id: str):
  451. return (
  452. AppDatasetJoin.query.filter(AppDatasetJoin.dataset_id == dataset_id)
  453. .order_by(db.desc(AppDatasetJoin.created_at))
  454. .all()
  455. )
  456. @staticmethod
  457. def get_dataset_auto_disable_logs(dataset_id: str) -> dict:
  458. features = FeatureService.get_features(current_user.current_tenant_id)
  459. if not features.billing.enabled or features.billing.subscription.plan == "sandbox":
  460. return {
  461. "document_ids": [],
  462. "count": 0,
  463. }
  464. # get recent 30 days auto disable logs
  465. start_date = datetime.datetime.now() - datetime.timedelta(days=30)
  466. dataset_auto_disable_logs = DatasetAutoDisableLog.query.filter(
  467. DatasetAutoDisableLog.dataset_id == dataset_id,
  468. DatasetAutoDisableLog.created_at >= start_date,
  469. ).all()
  470. if dataset_auto_disable_logs:
  471. return {
  472. "document_ids": [log.document_id for log in dataset_auto_disable_logs],
  473. "count": len(dataset_auto_disable_logs),
  474. }
  475. return {
  476. "document_ids": [],
  477. "count": 0,
  478. }
  479. class DocumentService:
  480. DEFAULT_RULES: dict[str, Any] = {
  481. "mode": "custom",
  482. "rules": {
  483. "pre_processing_rules": [
  484. {"id": "remove_extra_spaces", "enabled": True},
  485. {"id": "remove_urls_emails", "enabled": False},
  486. ],
  487. "segmentation": {"delimiter": "\n", "max_tokens": 500, "chunk_overlap": 50},
  488. },
  489. "limits": {
  490. "indexing_max_segmentation_tokens_length": dify_config.INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH,
  491. },
  492. }
  493. DOCUMENT_METADATA_SCHEMA: dict[str, Any] = {
  494. "book": {
  495. "title": str,
  496. "language": str,
  497. "author": str,
  498. "publisher": str,
  499. "publication_date": str,
  500. "isbn": str,
  501. "category": str,
  502. },
  503. "web_page": {
  504. "title": str,
  505. "url": str,
  506. "language": str,
  507. "publish_date": str,
  508. "author/publisher": str,
  509. "topic/keywords": str,
  510. "description": str,
  511. },
  512. "paper": {
  513. "title": str,
  514. "language": str,
  515. "author": str,
  516. "publish_date": str,
  517. "journal/conference_name": str,
  518. "volume/issue/page_numbers": str,
  519. "doi": str,
  520. "topic/keywords": str,
  521. "abstract": str,
  522. },
  523. "social_media_post": {
  524. "platform": str,
  525. "author/username": str,
  526. "publish_date": str,
  527. "post_url": str,
  528. "topic/tags": str,
  529. },
  530. "wikipedia_entry": {
  531. "title": str,
  532. "language": str,
  533. "web_page_url": str,
  534. "last_edit_date": str,
  535. "editor/contributor": str,
  536. "summary/introduction": str,
  537. },
  538. "personal_document": {
  539. "title": str,
  540. "author": str,
  541. "creation_date": str,
  542. "last_modified_date": str,
  543. "document_type": str,
  544. "tags/category": str,
  545. },
  546. "business_document": {
  547. "title": str,
  548. "author": str,
  549. "creation_date": str,
  550. "last_modified_date": str,
  551. "document_type": str,
  552. "department/team": str,
  553. },
  554. "im_chat_log": {
  555. "chat_platform": str,
  556. "chat_participants/group_name": str,
  557. "start_date": str,
  558. "end_date": str,
  559. "summary": str,
  560. },
  561. "synced_from_notion": {
  562. "title": str,
  563. "language": str,
  564. "author/creator": str,
  565. "creation_date": str,
  566. "last_modified_date": str,
  567. "notion_page_link": str,
  568. "category/tags": str,
  569. "description": str,
  570. },
  571. "synced_from_github": {
  572. "repository_name": str,
  573. "repository_description": str,
  574. "repository_owner/organization": str,
  575. "code_filename": str,
  576. "code_file_path": str,
  577. "programming_language": str,
  578. "github_link": str,
  579. "open_source_license": str,
  580. "commit_date": str,
  581. "commit_author": str,
  582. },
  583. "others": dict,
  584. }
  585. @staticmethod
  586. def get_document(dataset_id: str, document_id: Optional[str] = None) -> Optional[Document]:
  587. if document_id:
  588. document = (
  589. db.session.query(Document).filter(Document.id == document_id, Document.dataset_id == dataset_id).first()
  590. )
  591. return document
  592. else:
  593. return None
  594. @staticmethod
  595. def get_document_by_id(document_id: str) -> Optional[Document]:
  596. document = db.session.query(Document).filter(Document.id == document_id).first()
  597. return document
  598. @staticmethod
  599. def get_document_by_ids(document_ids: list[str]) -> list[Document]:
  600. documents = (
  601. db.session.query(Document)
  602. .filter(
  603. Document.id.in_(document_ids),
  604. Document.enabled == True,
  605. Document.indexing_status == "completed",
  606. Document.archived == False,
  607. )
  608. .all()
  609. )
  610. return documents
  611. @staticmethod
  612. def get_document_by_dataset_id(dataset_id: str) -> list[Document]:
  613. documents = (
  614. db.session.query(Document)
  615. .filter(
  616. Document.dataset_id == dataset_id,
  617. Document.enabled == True,
  618. )
  619. .all()
  620. )
  621. return documents
  622. @staticmethod
  623. def get_working_documents_by_dataset_id(dataset_id: str) -> list[Document]:
  624. documents = (
  625. db.session.query(Document)
  626. .filter(
  627. Document.dataset_id == dataset_id,
  628. Document.enabled == True,
  629. Document.indexing_status == "completed",
  630. Document.archived == False,
  631. )
  632. .all()
  633. )
  634. return documents
  635. @staticmethod
  636. def get_error_documents_by_dataset_id(dataset_id: str) -> list[Document]:
  637. documents = (
  638. db.session.query(Document)
  639. .filter(Document.dataset_id == dataset_id, Document.indexing_status.in_(["error", "paused"]))
  640. .all()
  641. )
  642. return documents
  643. @staticmethod
  644. def get_batch_documents(dataset_id: str, batch: str) -> list[Document]:
  645. documents = (
  646. db.session.query(Document)
  647. .filter(
  648. Document.batch == batch,
  649. Document.dataset_id == dataset_id,
  650. Document.tenant_id == current_user.current_tenant_id,
  651. )
  652. .all()
  653. )
  654. return documents
  655. @staticmethod
  656. def get_document_file_detail(file_id: str):
  657. file_detail = db.session.query(UploadFile).filter(UploadFile.id == file_id).one_or_none()
  658. return file_detail
  659. @staticmethod
  660. def check_archived(document):
  661. if document.archived:
  662. return True
  663. else:
  664. return False
  665. @staticmethod
  666. def delete_document(document):
  667. # trigger document_was_deleted signal
  668. file_id = None
  669. if document.data_source_type == "upload_file":
  670. if document.data_source_info:
  671. data_source_info = document.data_source_info_dict
  672. if data_source_info and "upload_file_id" in data_source_info:
  673. file_id = data_source_info["upload_file_id"]
  674. document_was_deleted.send(
  675. document.id, dataset_id=document.dataset_id, doc_form=document.doc_form, file_id=file_id
  676. )
  677. db.session.delete(document)
  678. db.session.commit()
  679. @staticmethod
  680. def delete_documents(dataset: Dataset, document_ids: list[str]):
  681. documents = db.session.query(Document).filter(Document.id.in_(document_ids)).all()
  682. file_ids = [
  683. document.data_source_info_dict["upload_file_id"]
  684. for document in documents
  685. if document.data_source_type == "upload_file"
  686. ]
  687. batch_clean_document_task.delay(document_ids, dataset.id, dataset.doc_form, file_ids)
  688. for document in documents:
  689. db.session.delete(document)
  690. db.session.commit()
  691. @staticmethod
  692. def rename_document(dataset_id: str, document_id: str, name: str) -> Document:
  693. dataset = DatasetService.get_dataset(dataset_id)
  694. if not dataset:
  695. raise ValueError("Dataset not found.")
  696. document = DocumentService.get_document(dataset_id, document_id)
  697. if not document:
  698. raise ValueError("Document not found.")
  699. if document.tenant_id != current_user.current_tenant_id:
  700. raise ValueError("No permission.")
  701. if dataset.built_in_field_enabled:
  702. if document.doc_metadata:
  703. doc_metadata = copy.deepcopy(document.doc_metadata)
  704. doc_metadata[BuiltInField.document_name.value] = name
  705. document.doc_metadata = doc_metadata
  706. document.name = name
  707. db.session.add(document)
  708. db.session.commit()
  709. return document
  710. @staticmethod
  711. def pause_document(document):
  712. if document.indexing_status not in {"waiting", "parsing", "cleaning", "splitting", "indexing"}:
  713. raise DocumentIndexingError()
  714. # update document to be paused
  715. document.is_paused = True
  716. document.paused_by = current_user.id
  717. document.paused_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  718. db.session.add(document)
  719. db.session.commit()
  720. # set document paused flag
  721. indexing_cache_key = "document_{}_is_paused".format(document.id)
  722. redis_client.setnx(indexing_cache_key, "True")
  723. @staticmethod
  724. def recover_document(document):
  725. if not document.is_paused:
  726. raise DocumentIndexingError()
  727. # update document to be recover
  728. document.is_paused = False
  729. document.paused_by = None
  730. document.paused_at = None
  731. db.session.add(document)
  732. db.session.commit()
  733. # delete paused flag
  734. indexing_cache_key = "document_{}_is_paused".format(document.id)
  735. redis_client.delete(indexing_cache_key)
  736. # trigger async task
  737. recover_document_indexing_task.delay(document.dataset_id, document.id)
  738. @staticmethod
  739. def retry_document(dataset_id: str, documents: list[Document]):
  740. for document in documents:
  741. # add retry flag
  742. retry_indexing_cache_key = "document_{}_is_retried".format(document.id)
  743. cache_result = redis_client.get(retry_indexing_cache_key)
  744. if cache_result is not None:
  745. raise ValueError("Document is being retried, please try again later")
  746. # retry document indexing
  747. document.indexing_status = "waiting"
  748. db.session.add(document)
  749. db.session.commit()
  750. redis_client.setex(retry_indexing_cache_key, 600, 1)
  751. # trigger async task
  752. document_ids = [document.id for document in documents]
  753. retry_document_indexing_task.delay(dataset_id, document_ids)
  754. @staticmethod
  755. def sync_website_document(dataset_id: str, document: Document):
  756. # add sync flag
  757. sync_indexing_cache_key = "document_{}_is_sync".format(document.id)
  758. cache_result = redis_client.get(sync_indexing_cache_key)
  759. if cache_result is not None:
  760. raise ValueError("Document is being synced, please try again later")
  761. # sync document indexing
  762. document.indexing_status = "waiting"
  763. data_source_info = document.data_source_info_dict
  764. data_source_info["mode"] = "scrape"
  765. document.data_source_info = json.dumps(data_source_info, ensure_ascii=False)
  766. db.session.add(document)
  767. db.session.commit()
  768. redis_client.setex(sync_indexing_cache_key, 600, 1)
  769. sync_website_document_indexing_task.delay(dataset_id, document.id)
  770. @staticmethod
  771. def get_documents_position(dataset_id):
  772. document = Document.query.filter_by(dataset_id=dataset_id).order_by(Document.position.desc()).first()
  773. if document:
  774. return document.position + 1
  775. else:
  776. return 1
  777. @staticmethod
  778. def save_document_with_dataset_id(
  779. dataset: Dataset,
  780. knowledge_config: KnowledgeConfig,
  781. account: Account | Any,
  782. dataset_process_rule: Optional[DatasetProcessRule] = None,
  783. created_from: str = "web",
  784. ):
  785. # check document limit
  786. features = FeatureService.get_features(current_user.current_tenant_id)
  787. if features.billing.enabled:
  788. if not knowledge_config.original_document_id:
  789. count = 0
  790. if knowledge_config.data_source:
  791. if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  792. upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  793. count = len(upload_file_list)
  794. elif knowledge_config.data_source.info_list.data_source_type == "notion_import":
  795. notion_info_list = knowledge_config.data_source.info_list.notion_info_list
  796. for notion_info in notion_info_list: # type: ignore
  797. count = count + len(notion_info.pages)
  798. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  799. website_info = knowledge_config.data_source.info_list.website_info_list
  800. count = len(website_info.urls) # type: ignore
  801. batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  802. if features.billing.subscription.plan == "sandbox" and count > 1:
  803. raise ValueError("Your current plan does not support batch upload, please upgrade your plan.")
  804. if count > batch_upload_limit:
  805. raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  806. DocumentService.check_documents_upload_quota(count, features)
  807. # if dataset is empty, update dataset data_source_type
  808. if not dataset.data_source_type:
  809. dataset.data_source_type = knowledge_config.data_source.info_list.data_source_type # type: ignore
  810. if not dataset.indexing_technique:
  811. if knowledge_config.indexing_technique not in Dataset.INDEXING_TECHNIQUE_LIST:
  812. raise ValueError("Indexing technique is invalid")
  813. dataset.indexing_technique = knowledge_config.indexing_technique
  814. if knowledge_config.indexing_technique == "high_quality":
  815. model_manager = ModelManager()
  816. if knowledge_config.embedding_model and knowledge_config.embedding_model_provider:
  817. dataset_embedding_model = knowledge_config.embedding_model
  818. dataset_embedding_model_provider = knowledge_config.embedding_model_provider
  819. else:
  820. embedding_model = model_manager.get_default_model_instance(
  821. tenant_id=current_user.current_tenant_id, model_type=ModelType.TEXT_EMBEDDING
  822. )
  823. dataset_embedding_model = embedding_model.model
  824. dataset_embedding_model_provider = embedding_model.provider
  825. dataset.embedding_model = dataset_embedding_model
  826. dataset.embedding_model_provider = dataset_embedding_model_provider
  827. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  828. dataset_embedding_model_provider, dataset_embedding_model
  829. )
  830. dataset.collection_binding_id = dataset_collection_binding.id
  831. if not dataset.retrieval_model:
  832. default_retrieval_model = {
  833. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  834. "reranking_enable": False,
  835. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  836. "top_k": 2,
  837. "score_threshold_enabled": False,
  838. }
  839. dataset.retrieval_model = (
  840. knowledge_config.retrieval_model.model_dump()
  841. if knowledge_config.retrieval_model
  842. else default_retrieval_model
  843. ) # type: ignore
  844. documents = []
  845. if knowledge_config.original_document_id:
  846. document = DocumentService.update_document_with_dataset_id(dataset, knowledge_config, account)
  847. documents.append(document)
  848. batch = document.batch
  849. else:
  850. batch = time.strftime("%Y%m%d%H%M%S") + str(random.randint(100000, 999999))
  851. # save process rule
  852. if not dataset_process_rule:
  853. process_rule = knowledge_config.process_rule
  854. if process_rule:
  855. if process_rule.mode in ("custom", "hierarchical"):
  856. dataset_process_rule = DatasetProcessRule(
  857. dataset_id=dataset.id,
  858. mode=process_rule.mode,
  859. rules=process_rule.rules.model_dump_json() if process_rule.rules else None,
  860. created_by=account.id,
  861. )
  862. elif process_rule.mode == "automatic":
  863. dataset_process_rule = DatasetProcessRule(
  864. dataset_id=dataset.id,
  865. mode=process_rule.mode,
  866. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  867. created_by=account.id,
  868. )
  869. else:
  870. logging.warn(
  871. f"Invalid process rule mode: {process_rule.mode}, can not find dataset process rule"
  872. )
  873. return
  874. db.session.add(dataset_process_rule)
  875. db.session.commit()
  876. lock_name = "add_document_lock_dataset_id_{}".format(dataset.id)
  877. with redis_client.lock(lock_name, timeout=600):
  878. position = DocumentService.get_documents_position(dataset.id)
  879. document_ids = []
  880. duplicate_document_ids = []
  881. if knowledge_config.data_source.info_list.data_source_type == "upload_file": # type: ignore
  882. upload_file_list = knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  883. for file_id in upload_file_list:
  884. file = (
  885. db.session.query(UploadFile)
  886. .filter(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  887. .first()
  888. )
  889. # raise error if file not found
  890. if not file:
  891. raise FileNotExistsError()
  892. file_name = file.name
  893. data_source_info = {
  894. "upload_file_id": file_id,
  895. }
  896. # check duplicate
  897. if knowledge_config.duplicate:
  898. document = Document.query.filter_by(
  899. dataset_id=dataset.id,
  900. tenant_id=current_user.current_tenant_id,
  901. data_source_type="upload_file",
  902. enabled=True,
  903. name=file_name,
  904. ).first()
  905. if document:
  906. document.dataset_process_rule_id = dataset_process_rule.id # type: ignore
  907. document.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  908. document.created_from = created_from
  909. document.doc_form = knowledge_config.doc_form
  910. document.doc_language = knowledge_config.doc_language
  911. document.data_source_info = json.dumps(data_source_info)
  912. document.batch = batch
  913. document.indexing_status = "waiting"
  914. db.session.add(document)
  915. documents.append(document)
  916. duplicate_document_ids.append(document.id)
  917. continue
  918. document = DocumentService.build_document(
  919. dataset,
  920. dataset_process_rule.id, # type: ignore
  921. knowledge_config.data_source.info_list.data_source_type, # type: ignore
  922. knowledge_config.doc_form,
  923. knowledge_config.doc_language,
  924. data_source_info,
  925. created_from,
  926. position,
  927. account,
  928. file_name,
  929. batch,
  930. )
  931. db.session.add(document)
  932. db.session.flush()
  933. document_ids.append(document.id)
  934. documents.append(document)
  935. position += 1
  936. elif knowledge_config.data_source.info_list.data_source_type == "notion_import": # type: ignore
  937. notion_info_list = knowledge_config.data_source.info_list.notion_info_list # type: ignore
  938. if not notion_info_list:
  939. raise ValueError("No notion info list found.")
  940. exist_page_ids = []
  941. exist_document = {}
  942. documents = Document.query.filter_by(
  943. dataset_id=dataset.id,
  944. tenant_id=current_user.current_tenant_id,
  945. data_source_type="notion_import",
  946. enabled=True,
  947. ).all()
  948. if documents:
  949. for document in documents:
  950. data_source_info = json.loads(document.data_source_info)
  951. exist_page_ids.append(data_source_info["notion_page_id"])
  952. exist_document[data_source_info["notion_page_id"]] = document.id
  953. for notion_info in notion_info_list:
  954. workspace_id = notion_info.workspace_id
  955. data_source_binding = DataSourceOauthBinding.query.filter(
  956. db.and_(
  957. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  958. DataSourceOauthBinding.provider == "notion",
  959. DataSourceOauthBinding.disabled == False,
  960. DataSourceOauthBinding.source_info["workspace_id"] == f'"{workspace_id}"',
  961. )
  962. ).first()
  963. if not data_source_binding:
  964. raise ValueError("Data source binding not found.")
  965. for page in notion_info.pages:
  966. if page.page_id not in exist_page_ids:
  967. data_source_info = {
  968. "notion_workspace_id": workspace_id,
  969. "notion_page_id": page.page_id,
  970. "notion_page_icon": page.page_icon.model_dump() if page.page_icon else None,
  971. "type": page.type,
  972. }
  973. # Truncate page name to 255 characters to prevent DB field length errors
  974. truncated_page_name = page.page_name[:255] if page.page_name else "nopagename"
  975. document = DocumentService.build_document(
  976. dataset,
  977. dataset_process_rule.id, # type: ignore
  978. knowledge_config.data_source.info_list.data_source_type, # type: ignore
  979. knowledge_config.doc_form,
  980. knowledge_config.doc_language,
  981. data_source_info,
  982. created_from,
  983. position,
  984. account,
  985. truncated_page_name,
  986. batch,
  987. )
  988. db.session.add(document)
  989. db.session.flush()
  990. document_ids.append(document.id)
  991. documents.append(document)
  992. position += 1
  993. else:
  994. exist_document.pop(page.page_id)
  995. # delete not selected documents
  996. if len(exist_document) > 0:
  997. clean_notion_document_task.delay(list(exist_document.values()), dataset.id)
  998. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl": # type: ignore
  999. website_info = knowledge_config.data_source.info_list.website_info_list # type: ignore
  1000. if not website_info:
  1001. raise ValueError("No website info list found.")
  1002. urls = website_info.urls
  1003. for url in urls:
  1004. data_source_info = {
  1005. "url": url,
  1006. "provider": website_info.provider,
  1007. "job_id": website_info.job_id,
  1008. "only_main_content": website_info.only_main_content,
  1009. "mode": "crawl",
  1010. }
  1011. if len(url) > 255:
  1012. document_name = url[:200] + "..."
  1013. else:
  1014. document_name = url
  1015. document = DocumentService.build_document(
  1016. dataset,
  1017. dataset_process_rule.id, # type: ignore
  1018. knowledge_config.data_source.info_list.data_source_type, # type: ignore
  1019. knowledge_config.doc_form,
  1020. knowledge_config.doc_language,
  1021. data_source_info,
  1022. created_from,
  1023. position,
  1024. account,
  1025. document_name,
  1026. batch,
  1027. )
  1028. db.session.add(document)
  1029. db.session.flush()
  1030. document_ids.append(document.id)
  1031. documents.append(document)
  1032. position += 1
  1033. db.session.commit()
  1034. # trigger async task
  1035. if document_ids:
  1036. document_indexing_task.delay(dataset.id, document_ids)
  1037. if duplicate_document_ids:
  1038. duplicate_document_indexing_task.delay(dataset.id, duplicate_document_ids)
  1039. return documents, batch
  1040. @staticmethod
  1041. def check_documents_upload_quota(count: int, features: FeatureModel):
  1042. can_upload_size = features.documents_upload_quota.limit - features.documents_upload_quota.size
  1043. if count > can_upload_size:
  1044. raise ValueError(
  1045. f"You have reached the limit of your subscription. Only {can_upload_size} documents can be uploaded."
  1046. )
  1047. @staticmethod
  1048. def build_document(
  1049. dataset: Dataset,
  1050. process_rule_id: str,
  1051. data_source_type: str,
  1052. document_form: str,
  1053. document_language: str,
  1054. data_source_info: dict,
  1055. created_from: str,
  1056. position: int,
  1057. account: Account,
  1058. name: str,
  1059. batch: str,
  1060. ):
  1061. document = Document(
  1062. tenant_id=dataset.tenant_id,
  1063. dataset_id=dataset.id,
  1064. position=position,
  1065. data_source_type=data_source_type,
  1066. data_source_info=json.dumps(data_source_info),
  1067. dataset_process_rule_id=process_rule_id,
  1068. batch=batch,
  1069. name=name,
  1070. created_from=created_from,
  1071. created_by=account.id,
  1072. doc_form=document_form,
  1073. doc_language=document_language,
  1074. )
  1075. doc_metadata = {}
  1076. if dataset.built_in_field_enabled:
  1077. doc_metadata = {
  1078. BuiltInField.document_name: name,
  1079. BuiltInField.uploader: account.name,
  1080. BuiltInField.upload_date: datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S"),
  1081. BuiltInField.last_update_date: datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S"),
  1082. BuiltInField.source: data_source_type,
  1083. }
  1084. if doc_metadata:
  1085. document.doc_metadata = doc_metadata
  1086. return document
  1087. @staticmethod
  1088. def get_tenant_documents_count():
  1089. documents_count = Document.query.filter(
  1090. Document.completed_at.isnot(None),
  1091. Document.enabled == True,
  1092. Document.archived == False,
  1093. Document.tenant_id == current_user.current_tenant_id,
  1094. ).count()
  1095. return documents_count
  1096. @staticmethod
  1097. def update_document_with_dataset_id(
  1098. dataset: Dataset,
  1099. document_data: KnowledgeConfig,
  1100. account: Account,
  1101. dataset_process_rule: Optional[DatasetProcessRule] = None,
  1102. created_from: str = "web",
  1103. ):
  1104. DatasetService.check_dataset_model_setting(dataset)
  1105. document = DocumentService.get_document(dataset.id, document_data.original_document_id)
  1106. if document is None:
  1107. raise NotFound("Document not found")
  1108. if document.display_status != "available":
  1109. raise ValueError("Document is not available")
  1110. # save process rule
  1111. if document_data.process_rule:
  1112. process_rule = document_data.process_rule
  1113. if process_rule.mode in {"custom", "hierarchical"}:
  1114. dataset_process_rule = DatasetProcessRule(
  1115. dataset_id=dataset.id,
  1116. mode=process_rule.mode,
  1117. rules=process_rule.rules.model_dump_json() if process_rule.rules else None,
  1118. created_by=account.id,
  1119. )
  1120. elif process_rule.mode == "automatic":
  1121. dataset_process_rule = DatasetProcessRule(
  1122. dataset_id=dataset.id,
  1123. mode=process_rule.mode,
  1124. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  1125. created_by=account.id,
  1126. )
  1127. if dataset_process_rule is not None:
  1128. db.session.add(dataset_process_rule)
  1129. db.session.commit()
  1130. document.dataset_process_rule_id = dataset_process_rule.id
  1131. # update document data source
  1132. if document_data.data_source:
  1133. file_name = ""
  1134. data_source_info = {}
  1135. if document_data.data_source.info_list.data_source_type == "upload_file":
  1136. if not document_data.data_source.info_list.file_info_list:
  1137. raise ValueError("No file info list found.")
  1138. upload_file_list = document_data.data_source.info_list.file_info_list.file_ids
  1139. for file_id in upload_file_list:
  1140. file = (
  1141. db.session.query(UploadFile)
  1142. .filter(UploadFile.tenant_id == dataset.tenant_id, UploadFile.id == file_id)
  1143. .first()
  1144. )
  1145. # raise error if file not found
  1146. if not file:
  1147. raise FileNotExistsError()
  1148. file_name = file.name
  1149. data_source_info = {
  1150. "upload_file_id": file_id,
  1151. }
  1152. elif document_data.data_source.info_list.data_source_type == "notion_import":
  1153. if not document_data.data_source.info_list.notion_info_list:
  1154. raise ValueError("No notion info list found.")
  1155. notion_info_list = document_data.data_source.info_list.notion_info_list
  1156. for notion_info in notion_info_list:
  1157. workspace_id = notion_info.workspace_id
  1158. data_source_binding = DataSourceOauthBinding.query.filter(
  1159. db.and_(
  1160. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  1161. DataSourceOauthBinding.provider == "notion",
  1162. DataSourceOauthBinding.disabled == False,
  1163. DataSourceOauthBinding.source_info["workspace_id"] == f'"{workspace_id}"',
  1164. )
  1165. ).first()
  1166. if not data_source_binding:
  1167. raise ValueError("Data source binding not found.")
  1168. for page in notion_info.pages:
  1169. data_source_info = {
  1170. "notion_workspace_id": workspace_id,
  1171. "notion_page_id": page.page_id,
  1172. "notion_page_icon": page.page_icon.model_dump() if page.page_icon else None, # type: ignore
  1173. "type": page.type,
  1174. }
  1175. elif document_data.data_source.info_list.data_source_type == "website_crawl":
  1176. website_info = document_data.data_source.info_list.website_info_list
  1177. if website_info:
  1178. urls = website_info.urls
  1179. for url in urls:
  1180. data_source_info = {
  1181. "url": url,
  1182. "provider": website_info.provider,
  1183. "job_id": website_info.job_id,
  1184. "only_main_content": website_info.only_main_content, # type: ignore
  1185. "mode": "crawl",
  1186. }
  1187. document.data_source_type = document_data.data_source.info_list.data_source_type
  1188. document.data_source_info = json.dumps(data_source_info)
  1189. document.name = file_name
  1190. # update document name
  1191. if document_data.name:
  1192. document.name = document_data.name
  1193. # update document to be waiting
  1194. document.indexing_status = "waiting"
  1195. document.completed_at = None
  1196. document.processing_started_at = None
  1197. document.parsing_completed_at = None
  1198. document.cleaning_completed_at = None
  1199. document.splitting_completed_at = None
  1200. document.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1201. document.created_from = created_from
  1202. document.doc_form = document_data.doc_form
  1203. db.session.add(document)
  1204. db.session.commit()
  1205. # update document segment
  1206. update_params = {DocumentSegment.status: "re_segment"}
  1207. DocumentSegment.query.filter_by(document_id=document.id).update(update_params)
  1208. db.session.commit()
  1209. # trigger async task
  1210. document_indexing_update_task.delay(document.dataset_id, document.id)
  1211. return document
  1212. @staticmethod
  1213. def save_document_without_dataset_id(tenant_id: str, knowledge_config: KnowledgeConfig, account: Account):
  1214. features = FeatureService.get_features(current_user.current_tenant_id)
  1215. if features.billing.enabled:
  1216. count = 0
  1217. if knowledge_config.data_source.info_list.data_source_type == "upload_file": # type: ignore
  1218. upload_file_list = (
  1219. knowledge_config.data_source.info_list.file_info_list.file_ids # type: ignore
  1220. if knowledge_config.data_source.info_list.file_info_list # type: ignore
  1221. else []
  1222. )
  1223. count = len(upload_file_list)
  1224. elif knowledge_config.data_source.info_list.data_source_type == "notion_import": # type: ignore
  1225. notion_info_list = knowledge_config.data_source.info_list.notion_info_list # type: ignore
  1226. if notion_info_list:
  1227. for notion_info in notion_info_list:
  1228. count = count + len(notion_info.pages)
  1229. elif knowledge_config.data_source.info_list.data_source_type == "website_crawl": # type: ignore
  1230. website_info = knowledge_config.data_source.info_list.website_info_list # type: ignore
  1231. if website_info:
  1232. count = len(website_info.urls)
  1233. if features.billing.subscription.plan == "sandbox" and count > 1:
  1234. raise ValueError("Your current plan does not support batch upload, please upgrade your plan.")
  1235. batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
  1236. if count > batch_upload_limit:
  1237. raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")
  1238. DocumentService.check_documents_upload_quota(count, features)
  1239. dataset_collection_binding_id = None
  1240. retrieval_model = None
  1241. if knowledge_config.indexing_technique == "high_quality":
  1242. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  1243. knowledge_config.embedding_model_provider, # type: ignore
  1244. knowledge_config.embedding_model, # type: ignore
  1245. )
  1246. dataset_collection_binding_id = dataset_collection_binding.id
  1247. if knowledge_config.retrieval_model:
  1248. retrieval_model = knowledge_config.retrieval_model
  1249. else:
  1250. retrieval_model = RetrievalModel(
  1251. search_method=RetrievalMethod.SEMANTIC_SEARCH.value,
  1252. reranking_enable=False,
  1253. reranking_model=RerankingModel(reranking_provider_name="", reranking_model_name=""),
  1254. top_k=2,
  1255. score_threshold_enabled=False,
  1256. )
  1257. # save dataset
  1258. dataset = Dataset(
  1259. tenant_id=tenant_id,
  1260. name="",
  1261. data_source_type=knowledge_config.data_source.info_list.data_source_type, # type: ignore
  1262. indexing_technique=knowledge_config.indexing_technique,
  1263. created_by=account.id,
  1264. embedding_model=knowledge_config.embedding_model,
  1265. embedding_model_provider=knowledge_config.embedding_model_provider,
  1266. collection_binding_id=dataset_collection_binding_id,
  1267. retrieval_model=retrieval_model.model_dump() if retrieval_model else None,
  1268. )
  1269. db.session.add(dataset) # type: ignore
  1270. db.session.flush()
  1271. documents, batch = DocumentService.save_document_with_dataset_id(dataset, knowledge_config, account)
  1272. cut_length = 18
  1273. cut_name = documents[0].name[:cut_length]
  1274. dataset.name = cut_name + "..."
  1275. dataset.description = I18nObject(
  1276. en_US="useful for when you want to answer queries about the " + documents[0].name,
  1277. zh_Hans="用于回答关于 " + documents[0].name + " 的查询",
  1278. )
  1279. db.session.commit()
  1280. return dataset, documents, batch
  1281. @classmethod
  1282. def document_create_args_validate(cls, knowledge_config: KnowledgeConfig):
  1283. if not knowledge_config.data_source and not knowledge_config.process_rule:
  1284. raise ValueError("Data source or Process rule is required")
  1285. else:
  1286. if knowledge_config.data_source:
  1287. DocumentService.data_source_args_validate(knowledge_config)
  1288. if knowledge_config.process_rule:
  1289. DocumentService.process_rule_args_validate(knowledge_config)
  1290. @classmethod
  1291. def data_source_args_validate(cls, knowledge_config: KnowledgeConfig):
  1292. if not knowledge_config.data_source:
  1293. raise ValueError("Data source is required")
  1294. if knowledge_config.data_source.info_list.data_source_type not in Document.DATA_SOURCES:
  1295. raise ValueError("Data source type is invalid")
  1296. if not knowledge_config.data_source.info_list:
  1297. raise ValueError("Data source info is required")
  1298. if knowledge_config.data_source.info_list.data_source_type == "upload_file":
  1299. if not knowledge_config.data_source.info_list.file_info_list:
  1300. raise ValueError("File source info is required")
  1301. if knowledge_config.data_source.info_list.data_source_type == "notion_import":
  1302. if not knowledge_config.data_source.info_list.notion_info_list:
  1303. raise ValueError("Notion source info is required")
  1304. if knowledge_config.data_source.info_list.data_source_type == "website_crawl":
  1305. if not knowledge_config.data_source.info_list.website_info_list:
  1306. raise ValueError("Website source info is required")
  1307. @classmethod
  1308. def process_rule_args_validate(cls, knowledge_config: KnowledgeConfig):
  1309. if not knowledge_config.process_rule:
  1310. raise ValueError("Process rule is required")
  1311. if not knowledge_config.process_rule.mode:
  1312. raise ValueError("Process rule mode is required")
  1313. if knowledge_config.process_rule.mode not in DatasetProcessRule.MODES:
  1314. raise ValueError("Process rule mode is invalid")
  1315. if knowledge_config.process_rule.mode == "automatic":
  1316. knowledge_config.process_rule.rules = None
  1317. else:
  1318. if not knowledge_config.process_rule.rules:
  1319. raise ValueError("Process rule rules is required")
  1320. if knowledge_config.process_rule.rules.pre_processing_rules is None:
  1321. raise ValueError("Process rule pre_processing_rules is required")
  1322. unique_pre_processing_rule_dicts = {}
  1323. for pre_processing_rule in knowledge_config.process_rule.rules.pre_processing_rules:
  1324. if not pre_processing_rule.id:
  1325. raise ValueError("Process rule pre_processing_rules id is required")
  1326. if not isinstance(pre_processing_rule.enabled, bool):
  1327. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  1328. unique_pre_processing_rule_dicts[pre_processing_rule.id] = pre_processing_rule
  1329. knowledge_config.process_rule.rules.pre_processing_rules = list(unique_pre_processing_rule_dicts.values())
  1330. if not knowledge_config.process_rule.rules.segmentation:
  1331. raise ValueError("Process rule segmentation is required")
  1332. if not knowledge_config.process_rule.rules.segmentation.separator:
  1333. raise ValueError("Process rule segmentation separator is required")
  1334. if not isinstance(knowledge_config.process_rule.rules.segmentation.separator, str):
  1335. raise ValueError("Process rule segmentation separator is invalid")
  1336. if not (
  1337. knowledge_config.process_rule.mode == "hierarchical"
  1338. and knowledge_config.process_rule.rules.parent_mode == "full-doc"
  1339. ):
  1340. if not knowledge_config.process_rule.rules.segmentation.max_tokens:
  1341. raise ValueError("Process rule segmentation max_tokens is required")
  1342. if not isinstance(knowledge_config.process_rule.rules.segmentation.max_tokens, int):
  1343. raise ValueError("Process rule segmentation max_tokens is invalid")
  1344. @classmethod
  1345. def estimate_args_validate(cls, args: dict):
  1346. if "info_list" not in args or not args["info_list"]:
  1347. raise ValueError("Data source info is required")
  1348. if not isinstance(args["info_list"], dict):
  1349. raise ValueError("Data info is invalid")
  1350. if "process_rule" not in args or not args["process_rule"]:
  1351. raise ValueError("Process rule is required")
  1352. if not isinstance(args["process_rule"], dict):
  1353. raise ValueError("Process rule is invalid")
  1354. if "mode" not in args["process_rule"] or not args["process_rule"]["mode"]:
  1355. raise ValueError("Process rule mode is required")
  1356. if args["process_rule"]["mode"] not in DatasetProcessRule.MODES:
  1357. raise ValueError("Process rule mode is invalid")
  1358. if args["process_rule"]["mode"] == "automatic":
  1359. args["process_rule"]["rules"] = {}
  1360. else:
  1361. if "rules" not in args["process_rule"] or not args["process_rule"]["rules"]:
  1362. raise ValueError("Process rule rules is required")
  1363. if not isinstance(args["process_rule"]["rules"], dict):
  1364. raise ValueError("Process rule rules is invalid")
  1365. if (
  1366. "pre_processing_rules" not in args["process_rule"]["rules"]
  1367. or args["process_rule"]["rules"]["pre_processing_rules"] is None
  1368. ):
  1369. raise ValueError("Process rule pre_processing_rules is required")
  1370. if not isinstance(args["process_rule"]["rules"]["pre_processing_rules"], list):
  1371. raise ValueError("Process rule pre_processing_rules is invalid")
  1372. unique_pre_processing_rule_dicts = {}
  1373. for pre_processing_rule in args["process_rule"]["rules"]["pre_processing_rules"]:
  1374. if "id" not in pre_processing_rule or not pre_processing_rule["id"]:
  1375. raise ValueError("Process rule pre_processing_rules id is required")
  1376. if pre_processing_rule["id"] not in DatasetProcessRule.PRE_PROCESSING_RULES:
  1377. raise ValueError("Process rule pre_processing_rules id is invalid")
  1378. if "enabled" not in pre_processing_rule or pre_processing_rule["enabled"] is None:
  1379. raise ValueError("Process rule pre_processing_rules enabled is required")
  1380. if not isinstance(pre_processing_rule["enabled"], bool):
  1381. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  1382. unique_pre_processing_rule_dicts[pre_processing_rule["id"]] = pre_processing_rule
  1383. args["process_rule"]["rules"]["pre_processing_rules"] = list(unique_pre_processing_rule_dicts.values())
  1384. if (
  1385. "segmentation" not in args["process_rule"]["rules"]
  1386. or args["process_rule"]["rules"]["segmentation"] is None
  1387. ):
  1388. raise ValueError("Process rule segmentation is required")
  1389. if not isinstance(args["process_rule"]["rules"]["segmentation"], dict):
  1390. raise ValueError("Process rule segmentation is invalid")
  1391. if (
  1392. "separator" not in args["process_rule"]["rules"]["segmentation"]
  1393. or not args["process_rule"]["rules"]["segmentation"]["separator"]
  1394. ):
  1395. raise ValueError("Process rule segmentation separator is required")
  1396. if not isinstance(args["process_rule"]["rules"]["segmentation"]["separator"], str):
  1397. raise ValueError("Process rule segmentation separator is invalid")
  1398. if (
  1399. "max_tokens" not in args["process_rule"]["rules"]["segmentation"]
  1400. or not args["process_rule"]["rules"]["segmentation"]["max_tokens"]
  1401. ):
  1402. raise ValueError("Process rule segmentation max_tokens is required")
  1403. if not isinstance(args["process_rule"]["rules"]["segmentation"]["max_tokens"], int):
  1404. raise ValueError("Process rule segmentation max_tokens is invalid")
  1405. class SegmentService:
  1406. @classmethod
  1407. def segment_create_args_validate(cls, args: dict, document: Document):
  1408. if document.doc_form == "qa_model":
  1409. if "answer" not in args or not args["answer"]:
  1410. raise ValueError("Answer is required")
  1411. if not args["answer"].strip():
  1412. raise ValueError("Answer is empty")
  1413. if "content" not in args or not args["content"] or not args["content"].strip():
  1414. raise ValueError("Content is empty")
  1415. @classmethod
  1416. def create_segment(cls, args: dict, document: Document, dataset: Dataset):
  1417. content = args["content"]
  1418. doc_id = str(uuid.uuid4())
  1419. segment_hash = helper.generate_text_hash(content)
  1420. tokens = 0
  1421. if dataset.indexing_technique == "high_quality":
  1422. model_manager = ModelManager()
  1423. embedding_model = model_manager.get_model_instance(
  1424. tenant_id=current_user.current_tenant_id,
  1425. provider=dataset.embedding_model_provider,
  1426. model_type=ModelType.TEXT_EMBEDDING,
  1427. model=dataset.embedding_model,
  1428. )
  1429. # calc embedding use tokens
  1430. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])[0]
  1431. lock_name = "add_segment_lock_document_id_{}".format(document.id)
  1432. with redis_client.lock(lock_name, timeout=600):
  1433. max_position = (
  1434. db.session.query(func.max(DocumentSegment.position))
  1435. .filter(DocumentSegment.document_id == document.id)
  1436. .scalar()
  1437. )
  1438. segment_document = DocumentSegment(
  1439. tenant_id=current_user.current_tenant_id,
  1440. dataset_id=document.dataset_id,
  1441. document_id=document.id,
  1442. index_node_id=doc_id,
  1443. index_node_hash=segment_hash,
  1444. position=max_position + 1 if max_position else 1,
  1445. content=content,
  1446. word_count=len(content),
  1447. tokens=tokens,
  1448. status="completed",
  1449. indexing_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1450. completed_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1451. created_by=current_user.id,
  1452. )
  1453. if document.doc_form == "qa_model":
  1454. segment_document.word_count += len(args["answer"])
  1455. segment_document.answer = args["answer"]
  1456. db.session.add(segment_document)
  1457. # update document word count
  1458. document.word_count += segment_document.word_count
  1459. db.session.add(document)
  1460. db.session.commit()
  1461. # save vector index
  1462. try:
  1463. VectorService.create_segments_vector([args["keywords"]], [segment_document], dataset, document.doc_form)
  1464. except Exception as e:
  1465. logging.exception("create segment index failed")
  1466. segment_document.enabled = False
  1467. segment_document.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1468. segment_document.status = "error"
  1469. segment_document.error = str(e)
  1470. db.session.commit()
  1471. segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment_document.id).first()
  1472. return segment
  1473. @classmethod
  1474. def multi_create_segment(cls, segments: list, document: Document, dataset: Dataset):
  1475. lock_name = "multi_add_segment_lock_document_id_{}".format(document.id)
  1476. increment_word_count = 0
  1477. with redis_client.lock(lock_name, timeout=600):
  1478. embedding_model = None
  1479. if dataset.indexing_technique == "high_quality":
  1480. model_manager = ModelManager()
  1481. embedding_model = model_manager.get_model_instance(
  1482. tenant_id=current_user.current_tenant_id,
  1483. provider=dataset.embedding_model_provider,
  1484. model_type=ModelType.TEXT_EMBEDDING,
  1485. model=dataset.embedding_model,
  1486. )
  1487. max_position = (
  1488. db.session.query(func.max(DocumentSegment.position))
  1489. .filter(DocumentSegment.document_id == document.id)
  1490. .scalar()
  1491. )
  1492. pre_segment_data_list = []
  1493. segment_data_list = []
  1494. keywords_list = []
  1495. position = max_position + 1 if max_position else 1
  1496. for segment_item in segments:
  1497. content = segment_item["content"]
  1498. doc_id = str(uuid.uuid4())
  1499. segment_hash = helper.generate_text_hash(content)
  1500. tokens = 0
  1501. if dataset.indexing_technique == "high_quality" and embedding_model:
  1502. # calc embedding use tokens
  1503. if document.doc_form == "qa_model":
  1504. tokens = embedding_model.get_text_embedding_num_tokens(
  1505. texts=[content + segment_item["answer"]]
  1506. )[0]
  1507. else:
  1508. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])[0]
  1509. segment_document = DocumentSegment(
  1510. tenant_id=current_user.current_tenant_id,
  1511. dataset_id=document.dataset_id,
  1512. document_id=document.id,
  1513. index_node_id=doc_id,
  1514. index_node_hash=segment_hash,
  1515. position=position,
  1516. content=content,
  1517. word_count=len(content),
  1518. tokens=tokens,
  1519. keywords=segment_item.get("keywords", []),
  1520. status="completed",
  1521. indexing_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1522. completed_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  1523. created_by=current_user.id,
  1524. )
  1525. if document.doc_form == "qa_model":
  1526. segment_document.answer = segment_item["answer"]
  1527. segment_document.word_count += len(segment_item["answer"])
  1528. increment_word_count += segment_document.word_count
  1529. db.session.add(segment_document)
  1530. segment_data_list.append(segment_document)
  1531. position += 1
  1532. pre_segment_data_list.append(segment_document)
  1533. if "keywords" in segment_item:
  1534. keywords_list.append(segment_item["keywords"])
  1535. else:
  1536. keywords_list.append(None)
  1537. # update document word count
  1538. document.word_count += increment_word_count
  1539. db.session.add(document)
  1540. try:
  1541. # save vector index
  1542. VectorService.create_segments_vector(keywords_list, pre_segment_data_list, dataset, document.doc_form)
  1543. except Exception as e:
  1544. logging.exception("create segment index failed")
  1545. for segment_document in segment_data_list:
  1546. segment_document.enabled = False
  1547. segment_document.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1548. segment_document.status = "error"
  1549. segment_document.error = str(e)
  1550. db.session.commit()
  1551. return segment_data_list
  1552. @classmethod
  1553. def update_segment(cls, args: SegmentUpdateArgs, segment: DocumentSegment, document: Document, dataset: Dataset):
  1554. indexing_cache_key = "segment_{}_indexing".format(segment.id)
  1555. cache_result = redis_client.get(indexing_cache_key)
  1556. if cache_result is not None:
  1557. raise ValueError("Segment is indexing, please try again later")
  1558. if args.enabled is not None:
  1559. action = args.enabled
  1560. if segment.enabled != action:
  1561. if not action:
  1562. segment.enabled = action
  1563. segment.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1564. segment.disabled_by = current_user.id
  1565. db.session.add(segment)
  1566. db.session.commit()
  1567. # Set cache to prevent indexing the same segment multiple times
  1568. redis_client.setex(indexing_cache_key, 600, 1)
  1569. disable_segment_from_index_task.delay(segment.id)
  1570. return segment
  1571. if not segment.enabled:
  1572. if args.enabled is not None:
  1573. if not args.enabled:
  1574. raise ValueError("Can't update disabled segment")
  1575. else:
  1576. raise ValueError("Can't update disabled segment")
  1577. try:
  1578. word_count_change = segment.word_count
  1579. content = args.content or segment.content
  1580. if segment.content == content:
  1581. segment.word_count = len(content)
  1582. if document.doc_form == "qa_model":
  1583. segment.answer = args.answer
  1584. segment.word_count += len(args.answer) if args.answer else 0
  1585. word_count_change = segment.word_count - word_count_change
  1586. keyword_changed = False
  1587. if args.keywords:
  1588. if Counter(segment.keywords) != Counter(args.keywords):
  1589. segment.keywords = args.keywords
  1590. keyword_changed = True
  1591. segment.enabled = True
  1592. segment.disabled_at = None
  1593. segment.disabled_by = None
  1594. db.session.add(segment)
  1595. db.session.commit()
  1596. # update document word count
  1597. if word_count_change != 0:
  1598. document.word_count = max(0, document.word_count + word_count_change)
  1599. db.session.add(document)
  1600. # update segment index task
  1601. if document.doc_form == IndexType.PARENT_CHILD_INDEX and args.regenerate_child_chunks:
  1602. # regenerate child chunks
  1603. # get embedding model instance
  1604. if dataset.indexing_technique == "high_quality":
  1605. # check embedding model setting
  1606. model_manager = ModelManager()
  1607. if dataset.embedding_model_provider:
  1608. embedding_model_instance = model_manager.get_model_instance(
  1609. tenant_id=dataset.tenant_id,
  1610. provider=dataset.embedding_model_provider,
  1611. model_type=ModelType.TEXT_EMBEDDING,
  1612. model=dataset.embedding_model,
  1613. )
  1614. else:
  1615. embedding_model_instance = model_manager.get_default_model_instance(
  1616. tenant_id=dataset.tenant_id,
  1617. model_type=ModelType.TEXT_EMBEDDING,
  1618. )
  1619. else:
  1620. raise ValueError("The knowledge base index technique is not high quality!")
  1621. # get the process rule
  1622. processing_rule = (
  1623. db.session.query(DatasetProcessRule)
  1624. .filter(DatasetProcessRule.id == document.dataset_process_rule_id)
  1625. .first()
  1626. )
  1627. if not processing_rule:
  1628. raise ValueError("No processing rule found.")
  1629. VectorService.generate_child_chunks(
  1630. segment, document, dataset, embedding_model_instance, processing_rule, True
  1631. )
  1632. elif document.doc_form in (IndexType.PARAGRAPH_INDEX, IndexType.QA_INDEX):
  1633. if args.enabled or keyword_changed:
  1634. VectorService.create_segments_vector(
  1635. [args.keywords] if args.keywords else None,
  1636. [segment],
  1637. dataset,
  1638. document.doc_form,
  1639. )
  1640. else:
  1641. segment_hash = helper.generate_text_hash(content)
  1642. tokens = 0
  1643. if dataset.indexing_technique == "high_quality":
  1644. model_manager = ModelManager()
  1645. embedding_model = model_manager.get_model_instance(
  1646. tenant_id=current_user.current_tenant_id,
  1647. provider=dataset.embedding_model_provider,
  1648. model_type=ModelType.TEXT_EMBEDDING,
  1649. model=dataset.embedding_model,
  1650. )
  1651. # calc embedding use tokens
  1652. if document.doc_form == "qa_model":
  1653. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content + segment.answer])[0]
  1654. else:
  1655. tokens = embedding_model.get_text_embedding_num_tokens(texts=[content])[0]
  1656. segment.content = content
  1657. segment.index_node_hash = segment_hash
  1658. segment.word_count = len(content)
  1659. segment.tokens = tokens
  1660. segment.status = "completed"
  1661. segment.indexing_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1662. segment.completed_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1663. segment.updated_by = current_user.id
  1664. segment.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1665. segment.enabled = True
  1666. segment.disabled_at = None
  1667. segment.disabled_by = None
  1668. if document.doc_form == "qa_model":
  1669. segment.answer = args.answer
  1670. segment.word_count += len(args.answer) if args.answer else 0
  1671. word_count_change = segment.word_count - word_count_change
  1672. # update document word count
  1673. if word_count_change != 0:
  1674. document.word_count = max(0, document.word_count + word_count_change)
  1675. db.session.add(document)
  1676. db.session.add(segment)
  1677. db.session.commit()
  1678. if document.doc_form == IndexType.PARENT_CHILD_INDEX and args.regenerate_child_chunks:
  1679. # get embedding model instance
  1680. if dataset.indexing_technique == "high_quality":
  1681. # check embedding model setting
  1682. model_manager = ModelManager()
  1683. if dataset.embedding_model_provider:
  1684. embedding_model_instance = model_manager.get_model_instance(
  1685. tenant_id=dataset.tenant_id,
  1686. provider=dataset.embedding_model_provider,
  1687. model_type=ModelType.TEXT_EMBEDDING,
  1688. model=dataset.embedding_model,
  1689. )
  1690. else:
  1691. embedding_model_instance = model_manager.get_default_model_instance(
  1692. tenant_id=dataset.tenant_id,
  1693. model_type=ModelType.TEXT_EMBEDDING,
  1694. )
  1695. else:
  1696. raise ValueError("The knowledge base index technique is not high quality!")
  1697. # get the process rule
  1698. processing_rule = (
  1699. db.session.query(DatasetProcessRule)
  1700. .filter(DatasetProcessRule.id == document.dataset_process_rule_id)
  1701. .first()
  1702. )
  1703. if not processing_rule:
  1704. raise ValueError("No processing rule found.")
  1705. VectorService.generate_child_chunks(
  1706. segment, document, dataset, embedding_model_instance, processing_rule, True
  1707. )
  1708. elif document.doc_form in (IndexType.PARAGRAPH_INDEX, IndexType.QA_INDEX):
  1709. # update segment vector index
  1710. VectorService.update_segment_vector(args.keywords, segment, dataset)
  1711. except Exception as e:
  1712. logging.exception("update segment index failed")
  1713. segment.enabled = False
  1714. segment.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1715. segment.status = "error"
  1716. segment.error = str(e)
  1717. db.session.commit()
  1718. new_segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment.id).first()
  1719. return new_segment
  1720. @classmethod
  1721. def delete_segment(cls, segment: DocumentSegment, document: Document, dataset: Dataset):
  1722. indexing_cache_key = "segment_{}_delete_indexing".format(segment.id)
  1723. cache_result = redis_client.get(indexing_cache_key)
  1724. if cache_result is not None:
  1725. raise ValueError("Segment is deleting.")
  1726. # enabled segment need to delete index
  1727. if segment.enabled:
  1728. # send delete segment index task
  1729. redis_client.setex(indexing_cache_key, 600, 1)
  1730. delete_segment_from_index_task.delay([segment.index_node_id], dataset.id, document.id)
  1731. db.session.delete(segment)
  1732. # update document word count
  1733. document.word_count -= segment.word_count
  1734. db.session.add(document)
  1735. db.session.commit()
  1736. @classmethod
  1737. def delete_segments(cls, segment_ids: list, document: Document, dataset: Dataset):
  1738. index_node_ids = (
  1739. DocumentSegment.query.with_entities(DocumentSegment.index_node_id)
  1740. .filter(
  1741. DocumentSegment.id.in_(segment_ids),
  1742. DocumentSegment.dataset_id == dataset.id,
  1743. DocumentSegment.document_id == document.id,
  1744. DocumentSegment.tenant_id == current_user.current_tenant_id,
  1745. )
  1746. .all()
  1747. )
  1748. index_node_ids = [index_node_id[0] for index_node_id in index_node_ids]
  1749. delete_segment_from_index_task.delay(index_node_ids, dataset.id, document.id)
  1750. db.session.query(DocumentSegment).filter(DocumentSegment.id.in_(segment_ids)).delete()
  1751. db.session.commit()
  1752. @classmethod
  1753. def update_segments_status(cls, segment_ids: list, action: str, dataset: Dataset, document: Document):
  1754. if action == "enable":
  1755. segments = (
  1756. db.session.query(DocumentSegment)
  1757. .filter(
  1758. DocumentSegment.id.in_(segment_ids),
  1759. DocumentSegment.dataset_id == dataset.id,
  1760. DocumentSegment.document_id == document.id,
  1761. DocumentSegment.enabled == False,
  1762. )
  1763. .all()
  1764. )
  1765. if not segments:
  1766. return
  1767. real_deal_segmment_ids = []
  1768. for segment in segments:
  1769. indexing_cache_key = "segment_{}_indexing".format(segment.id)
  1770. cache_result = redis_client.get(indexing_cache_key)
  1771. if cache_result is not None:
  1772. continue
  1773. segment.enabled = True
  1774. segment.disabled_at = None
  1775. segment.disabled_by = None
  1776. db.session.add(segment)
  1777. real_deal_segmment_ids.append(segment.id)
  1778. db.session.commit()
  1779. enable_segments_to_index_task.delay(real_deal_segmment_ids, dataset.id, document.id)
  1780. elif action == "disable":
  1781. segments = (
  1782. db.session.query(DocumentSegment)
  1783. .filter(
  1784. DocumentSegment.id.in_(segment_ids),
  1785. DocumentSegment.dataset_id == dataset.id,
  1786. DocumentSegment.document_id == document.id,
  1787. DocumentSegment.enabled == True,
  1788. )
  1789. .all()
  1790. )
  1791. if not segments:
  1792. return
  1793. real_deal_segmment_ids = []
  1794. for segment in segments:
  1795. indexing_cache_key = "segment_{}_indexing".format(segment.id)
  1796. cache_result = redis_client.get(indexing_cache_key)
  1797. if cache_result is not None:
  1798. continue
  1799. segment.enabled = False
  1800. segment.disabled_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1801. segment.disabled_by = current_user.id
  1802. db.session.add(segment)
  1803. real_deal_segmment_ids.append(segment.id)
  1804. db.session.commit()
  1805. disable_segments_from_index_task.delay(real_deal_segmment_ids, dataset.id, document.id)
  1806. else:
  1807. raise InvalidActionError()
  1808. @classmethod
  1809. def create_child_chunk(
  1810. cls, content: str, segment: DocumentSegment, document: Document, dataset: Dataset
  1811. ) -> ChildChunk:
  1812. lock_name = "add_child_lock_{}".format(segment.id)
  1813. with redis_client.lock(lock_name, timeout=20):
  1814. index_node_id = str(uuid.uuid4())
  1815. index_node_hash = helper.generate_text_hash(content)
  1816. child_chunk_count = (
  1817. db.session.query(ChildChunk)
  1818. .filter(
  1819. ChildChunk.tenant_id == current_user.current_tenant_id,
  1820. ChildChunk.dataset_id == dataset.id,
  1821. ChildChunk.document_id == document.id,
  1822. ChildChunk.segment_id == segment.id,
  1823. )
  1824. .count()
  1825. )
  1826. max_position = (
  1827. db.session.query(func.max(ChildChunk.position))
  1828. .filter(
  1829. ChildChunk.tenant_id == current_user.current_tenant_id,
  1830. ChildChunk.dataset_id == dataset.id,
  1831. ChildChunk.document_id == document.id,
  1832. ChildChunk.segment_id == segment.id,
  1833. )
  1834. .scalar()
  1835. )
  1836. child_chunk = ChildChunk(
  1837. tenant_id=current_user.current_tenant_id,
  1838. dataset_id=dataset.id,
  1839. document_id=document.id,
  1840. segment_id=segment.id,
  1841. position=max_position + 1,
  1842. index_node_id=index_node_id,
  1843. index_node_hash=index_node_hash,
  1844. content=content,
  1845. word_count=len(content),
  1846. type="customized",
  1847. created_by=current_user.id,
  1848. )
  1849. db.session.add(child_chunk)
  1850. # save vector index
  1851. try:
  1852. VectorService.create_child_chunk_vector(child_chunk, dataset)
  1853. except Exception as e:
  1854. logging.exception("create child chunk index failed")
  1855. db.session.rollback()
  1856. raise ChildChunkIndexingError(str(e))
  1857. db.session.commit()
  1858. return child_chunk
  1859. @classmethod
  1860. def update_child_chunks(
  1861. cls,
  1862. child_chunks_update_args: list[ChildChunkUpdateArgs],
  1863. segment: DocumentSegment,
  1864. document: Document,
  1865. dataset: Dataset,
  1866. ) -> list[ChildChunk]:
  1867. child_chunks = (
  1868. db.session.query(ChildChunk)
  1869. .filter(
  1870. ChildChunk.dataset_id == dataset.id,
  1871. ChildChunk.document_id == document.id,
  1872. ChildChunk.segment_id == segment.id,
  1873. )
  1874. .all()
  1875. )
  1876. child_chunks_map = {chunk.id: chunk for chunk in child_chunks}
  1877. new_child_chunks, update_child_chunks, delete_child_chunks, new_child_chunks_args = [], [], [], []
  1878. for child_chunk_update_args in child_chunks_update_args:
  1879. if child_chunk_update_args.id:
  1880. child_chunk = child_chunks_map.pop(child_chunk_update_args.id, None)
  1881. if child_chunk:
  1882. if child_chunk.content != child_chunk_update_args.content:
  1883. child_chunk.content = child_chunk_update_args.content
  1884. child_chunk.word_count = len(child_chunk.content)
  1885. child_chunk.updated_by = current_user.id
  1886. child_chunk.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1887. child_chunk.type = "customized"
  1888. update_child_chunks.append(child_chunk)
  1889. else:
  1890. new_child_chunks_args.append(child_chunk_update_args)
  1891. if child_chunks_map:
  1892. delete_child_chunks = list(child_chunks_map.values())
  1893. try:
  1894. if update_child_chunks:
  1895. db.session.bulk_save_objects(update_child_chunks)
  1896. if delete_child_chunks:
  1897. for child_chunk in delete_child_chunks:
  1898. db.session.delete(child_chunk)
  1899. if new_child_chunks_args:
  1900. child_chunk_count = len(child_chunks)
  1901. for position, args in enumerate(new_child_chunks_args, start=child_chunk_count + 1):
  1902. index_node_id = str(uuid.uuid4())
  1903. index_node_hash = helper.generate_text_hash(args.content)
  1904. child_chunk = ChildChunk(
  1905. tenant_id=current_user.current_tenant_id,
  1906. dataset_id=dataset.id,
  1907. document_id=document.id,
  1908. segment_id=segment.id,
  1909. position=position,
  1910. index_node_id=index_node_id,
  1911. index_node_hash=index_node_hash,
  1912. content=args.content,
  1913. word_count=len(args.content),
  1914. type="customized",
  1915. created_by=current_user.id,
  1916. )
  1917. db.session.add(child_chunk)
  1918. db.session.flush()
  1919. new_child_chunks.append(child_chunk)
  1920. VectorService.update_child_chunk_vector(new_child_chunks, update_child_chunks, delete_child_chunks, dataset)
  1921. db.session.commit()
  1922. except Exception as e:
  1923. logging.exception("update child chunk index failed")
  1924. db.session.rollback()
  1925. raise ChildChunkIndexingError(str(e))
  1926. return sorted(new_child_chunks + update_child_chunks, key=lambda x: x.position)
  1927. @classmethod
  1928. def update_child_chunk(
  1929. cls,
  1930. content: str,
  1931. child_chunk: ChildChunk,
  1932. segment: DocumentSegment,
  1933. document: Document,
  1934. dataset: Dataset,
  1935. ) -> ChildChunk:
  1936. try:
  1937. child_chunk.content = content
  1938. child_chunk.word_count = len(content)
  1939. child_chunk.updated_by = current_user.id
  1940. child_chunk.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  1941. child_chunk.type = "customized"
  1942. db.session.add(child_chunk)
  1943. VectorService.update_child_chunk_vector([], [child_chunk], [], dataset)
  1944. db.session.commit()
  1945. except Exception as e:
  1946. logging.exception("update child chunk index failed")
  1947. db.session.rollback()
  1948. raise ChildChunkIndexingError(str(e))
  1949. return child_chunk
  1950. @classmethod
  1951. def delete_child_chunk(cls, child_chunk: ChildChunk, dataset: Dataset):
  1952. db.session.delete(child_chunk)
  1953. try:
  1954. VectorService.delete_child_chunk_vector(child_chunk, dataset)
  1955. except Exception as e:
  1956. logging.exception("delete child chunk index failed")
  1957. db.session.rollback()
  1958. raise ChildChunkDeleteIndexError(str(e))
  1959. db.session.commit()
  1960. @classmethod
  1961. def get_child_chunks(
  1962. cls, segment_id: str, document_id: str, dataset_id: str, page: int, limit: int, keyword: Optional[str] = None
  1963. ):
  1964. query = ChildChunk.query.filter_by(
  1965. tenant_id=current_user.current_tenant_id,
  1966. dataset_id=dataset_id,
  1967. document_id=document_id,
  1968. segment_id=segment_id,
  1969. ).order_by(ChildChunk.position.asc())
  1970. if keyword:
  1971. query = query.where(ChildChunk.content.ilike(f"%{keyword}%"))
  1972. return query.paginate(page=page, per_page=limit, max_per_page=100, error_out=False)
  1973. @classmethod
  1974. def get_child_chunk_by_id(cls, child_chunk_id: str, tenant_id: str) -> Optional[ChildChunk]:
  1975. """Get a child chunk by its ID."""
  1976. result = ChildChunk.query.filter(ChildChunk.id == child_chunk_id, ChildChunk.tenant_id == tenant_id).first()
  1977. return result if isinstance(result, ChildChunk) else None
  1978. @classmethod
  1979. def get_segments(
  1980. cls, document_id: str, tenant_id: str, status_list: list[str] | None = None, keyword: str | None = None
  1981. ):
  1982. """Get segments for a document with optional filtering."""
  1983. query = DocumentSegment.query.filter(
  1984. DocumentSegment.document_id == document_id, DocumentSegment.tenant_id == tenant_id
  1985. )
  1986. if status_list:
  1987. query = query.filter(DocumentSegment.status.in_(status_list))
  1988. if keyword:
  1989. query = query.filter(DocumentSegment.content.ilike(f"%{keyword}%"))
  1990. segments = query.order_by(DocumentSegment.position.asc()).all()
  1991. total = len(segments)
  1992. return segments, total
  1993. @classmethod
  1994. def update_segment_by_id(
  1995. cls, tenant_id: str, dataset_id: str, document_id: str, segment_id: str, segment_data: dict, user_id: str
  1996. ) -> tuple[DocumentSegment, Document]:
  1997. """Update a segment by its ID with validation and checks."""
  1998. # check dataset
  1999. dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  2000. if not dataset:
  2001. raise NotFound("Dataset not found.")
  2002. # check user's model setting
  2003. DatasetService.check_dataset_model_setting(dataset)
  2004. # check document
  2005. document = DocumentService.get_document(dataset_id, document_id)
  2006. if not document:
  2007. raise NotFound("Document not found.")
  2008. # check embedding model setting if high quality
  2009. if dataset.indexing_technique == "high_quality":
  2010. try:
  2011. model_manager = ModelManager()
  2012. model_manager.get_model_instance(
  2013. tenant_id=user_id,
  2014. provider=dataset.embedding_model_provider,
  2015. model_type=ModelType.TEXT_EMBEDDING,
  2016. model=dataset.embedding_model,
  2017. )
  2018. except LLMBadRequestError:
  2019. raise ValueError(
  2020. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  2021. )
  2022. except ProviderTokenNotInitError as ex:
  2023. raise ValueError(ex.description)
  2024. # check segment
  2025. segment = DocumentSegment.query.filter(
  2026. DocumentSegment.id == segment_id, DocumentSegment.tenant_id == user_id
  2027. ).first()
  2028. if not segment:
  2029. raise NotFound("Segment not found.")
  2030. # validate and update segment
  2031. cls.segment_create_args_validate(segment_data, document)
  2032. updated_segment = cls.update_segment(SegmentUpdateArgs(**segment_data), segment, document, dataset)
  2033. return updated_segment, document
  2034. @classmethod
  2035. def get_segment_by_id(cls, segment_id: str, tenant_id: str) -> Optional[DocumentSegment]:
  2036. """Get a segment by its ID."""
  2037. result = DocumentSegment.query.filter(
  2038. DocumentSegment.id == segment_id, DocumentSegment.tenant_id == tenant_id
  2039. ).first()
  2040. return result if isinstance(result, DocumentSegment) else None
  2041. class DatasetCollectionBindingService:
  2042. @classmethod
  2043. def get_dataset_collection_binding(
  2044. cls, provider_name: str, model_name: str, collection_type: str = "dataset"
  2045. ) -> DatasetCollectionBinding:
  2046. dataset_collection_binding = (
  2047. db.session.query(DatasetCollectionBinding)
  2048. .filter(
  2049. DatasetCollectionBinding.provider_name == provider_name,
  2050. DatasetCollectionBinding.model_name == model_name,
  2051. DatasetCollectionBinding.type == collection_type,
  2052. )
  2053. .order_by(DatasetCollectionBinding.created_at)
  2054. .first()
  2055. )
  2056. if not dataset_collection_binding:
  2057. dataset_collection_binding = DatasetCollectionBinding(
  2058. provider_name=provider_name,
  2059. model_name=model_name,
  2060. collection_name=Dataset.gen_collection_name_by_id(str(uuid.uuid4())),
  2061. type=collection_type,
  2062. )
  2063. db.session.add(dataset_collection_binding)
  2064. db.session.commit()
  2065. return dataset_collection_binding
  2066. @classmethod
  2067. def get_dataset_collection_binding_by_id_and_type(
  2068. cls, collection_binding_id: str, collection_type: str = "dataset"
  2069. ) -> DatasetCollectionBinding:
  2070. dataset_collection_binding = (
  2071. db.session.query(DatasetCollectionBinding)
  2072. .filter(
  2073. DatasetCollectionBinding.id == collection_binding_id, DatasetCollectionBinding.type == collection_type
  2074. )
  2075. .order_by(DatasetCollectionBinding.created_at)
  2076. .first()
  2077. )
  2078. if not dataset_collection_binding:
  2079. raise ValueError("Dataset collection binding not found")
  2080. return dataset_collection_binding
  2081. class DatasetPermissionService:
  2082. @classmethod
  2083. def get_dataset_partial_member_list(cls, dataset_id):
  2084. user_list_query = (
  2085. db.session.query(
  2086. DatasetPermission.account_id,
  2087. )
  2088. .filter(DatasetPermission.dataset_id == dataset_id)
  2089. .all()
  2090. )
  2091. user_list = []
  2092. for user in user_list_query:
  2093. user_list.append(user.account_id)
  2094. return user_list
  2095. @classmethod
  2096. def update_partial_member_list(cls, tenant_id, dataset_id, user_list):
  2097. try:
  2098. db.session.query(DatasetPermission).filter(DatasetPermission.dataset_id == dataset_id).delete()
  2099. permissions = []
  2100. for user in user_list:
  2101. permission = DatasetPermission(
  2102. tenant_id=tenant_id,
  2103. dataset_id=dataset_id,
  2104. account_id=user["user_id"],
  2105. )
  2106. permissions.append(permission)
  2107. db.session.add_all(permissions)
  2108. db.session.commit()
  2109. except Exception as e:
  2110. db.session.rollback()
  2111. raise e
  2112. @classmethod
  2113. def check_permission(cls, user, dataset, requested_permission, requested_partial_member_list):
  2114. if not user.is_dataset_editor:
  2115. raise NoPermissionError("User does not have permission to edit this dataset.")
  2116. if user.is_dataset_operator and dataset.permission != requested_permission:
  2117. raise NoPermissionError("Dataset operators cannot change the dataset permissions.")
  2118. if user.is_dataset_operator and requested_permission == "partial_members":
  2119. if not requested_partial_member_list:
  2120. raise ValueError("Partial member list is required when setting to partial members.")
  2121. local_member_list = cls.get_dataset_partial_member_list(dataset.id)
  2122. request_member_list = [user["user_id"] for user in requested_partial_member_list]
  2123. if set(local_member_list) != set(request_member_list):
  2124. raise ValueError("Dataset operators cannot change the dataset permissions.")
  2125. @classmethod
  2126. def clear_partial_member_list(cls, dataset_id):
  2127. try:
  2128. db.session.query(DatasetPermission).filter(DatasetPermission.dataset_id == dataset_id).delete()
  2129. db.session.commit()
  2130. except Exception as e:
  2131. db.session.rollback()
  2132. raise e