Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

dataset_service.py 134KB

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