dataset_service.py 71 KB

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