dataset_service.py 73 KB

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