dataset_service.py 72 KB

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