dataset_service.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. import json
  2. import logging
  3. import datetime
  4. import time
  5. import random
  6. import uuid
  7. from typing import Optional, List
  8. from flask import current_app
  9. from sqlalchemy import func
  10. from core.index.index import IndexBuilder
  11. from core.model_providers.error import LLMBadRequestError, ProviderTokenNotInitError
  12. from core.model_providers.model_factory import ModelFactory
  13. from extensions.ext_redis import redis_client
  14. from flask_login import current_user
  15. from events.dataset_event import dataset_was_deleted
  16. from events.document_event import document_was_deleted
  17. from extensions.ext_database import db
  18. from libs import helper
  19. from models.account import Account
  20. from models.dataset import Dataset, Document, DatasetQuery, DatasetProcessRule, AppDatasetJoin, DocumentSegment, \
  21. DatasetCollectionBinding
  22. from models.model import UploadFile
  23. from models.source import DataSourceBinding
  24. from services.errors.account import NoPermissionError
  25. from services.errors.dataset import DatasetNameDuplicateError
  26. from services.errors.document import DocumentIndexingError
  27. from services.errors.file import FileNotExistsError
  28. from services.vector_service import VectorService
  29. from tasks.clean_notion_document_task import clean_notion_document_task
  30. from tasks.deal_dataset_vector_index_task import deal_dataset_vector_index_task
  31. from tasks.document_indexing_task import document_indexing_task
  32. from tasks.document_indexing_update_task import document_indexing_update_task
  33. from tasks.create_segment_to_index_task import create_segment_to_index_task
  34. from tasks.update_segment_index_task import update_segment_index_task
  35. from tasks.recover_document_indexing_task import recover_document_indexing_task
  36. from tasks.update_segment_keyword_index_task import update_segment_keyword_index_task
  37. from tasks.delete_segment_from_index_task import delete_segment_from_index_task
  38. class DatasetService:
  39. @staticmethod
  40. def get_datasets(page, per_page, provider="vendor", tenant_id=None, user=None):
  41. if user:
  42. permission_filter = db.or_(Dataset.created_by == user.id,
  43. Dataset.permission == 'all_team_members')
  44. else:
  45. permission_filter = Dataset.permission == 'all_team_members'
  46. datasets = Dataset.query.filter(
  47. db.and_(Dataset.provider == provider, Dataset.tenant_id == tenant_id, permission_filter)) \
  48. .order_by(Dataset.created_at.desc()) \
  49. .paginate(
  50. page=page,
  51. per_page=per_page,
  52. max_per_page=100,
  53. error_out=False
  54. )
  55. return datasets.items, datasets.total
  56. @staticmethod
  57. def get_process_rules(dataset_id):
  58. # get the latest process rule
  59. dataset_process_rule = db.session.query(DatasetProcessRule). \
  60. filter(DatasetProcessRule.dataset_id == dataset_id). \
  61. order_by(DatasetProcessRule.created_at.desc()). \
  62. limit(1). \
  63. one_or_none()
  64. if dataset_process_rule:
  65. mode = dataset_process_rule.mode
  66. rules = dataset_process_rule.rules_dict
  67. else:
  68. mode = DocumentService.DEFAULT_RULES['mode']
  69. rules = DocumentService.DEFAULT_RULES['rules']
  70. return {
  71. 'mode': mode,
  72. 'rules': rules
  73. }
  74. @staticmethod
  75. def get_datasets_by_ids(ids, tenant_id):
  76. datasets = Dataset.query.filter(Dataset.id.in_(ids),
  77. Dataset.tenant_id == tenant_id).paginate(
  78. page=1, per_page=len(ids), max_per_page=len(ids), error_out=False)
  79. return datasets.items, datasets.total
  80. @staticmethod
  81. def create_empty_dataset(tenant_id: str, name: str, indexing_technique: Optional[str], account: Account):
  82. # check if dataset name already exists
  83. if Dataset.query.filter_by(name=name, tenant_id=tenant_id).first():
  84. raise DatasetNameDuplicateError(
  85. f'Dataset with name {name} already exists.')
  86. embedding_model = None
  87. if indexing_technique == 'high_quality':
  88. embedding_model = ModelFactory.get_embedding_model(
  89. tenant_id=current_user.current_tenant_id
  90. )
  91. dataset = Dataset(name=name, indexing_technique=indexing_technique)
  92. # dataset = Dataset(name=name, provider=provider, config=config)
  93. dataset.created_by = account.id
  94. dataset.updated_by = account.id
  95. dataset.tenant_id = tenant_id
  96. dataset.embedding_model_provider = embedding_model.model_provider.provider_name if embedding_model else None
  97. dataset.embedding_model = embedding_model.name if embedding_model else None
  98. db.session.add(dataset)
  99. db.session.commit()
  100. return dataset
  101. @staticmethod
  102. def get_dataset(dataset_id):
  103. dataset = Dataset.query.filter_by(
  104. id=dataset_id
  105. ).first()
  106. if dataset is None:
  107. return None
  108. else:
  109. return dataset
  110. @staticmethod
  111. def check_dataset_model_setting(dataset):
  112. if dataset.indexing_technique == 'high_quality':
  113. try:
  114. ModelFactory.get_embedding_model(
  115. tenant_id=dataset.tenant_id,
  116. model_provider_name=dataset.embedding_model_provider,
  117. model_name=dataset.embedding_model
  118. )
  119. except LLMBadRequestError:
  120. raise ValueError(
  121. f"No Embedding Model available. Please configure a valid provider "
  122. f"in the Settings -> Model Provider.")
  123. except ProviderTokenNotInitError as ex:
  124. raise ValueError(f"The dataset in unavailable, due to: "
  125. f"{ex.description}")
  126. @staticmethod
  127. def update_dataset(dataset_id, data, user):
  128. filtered_data = {k: v for k, v in data.items() if v is not None or k == 'description'}
  129. dataset = DatasetService.get_dataset(dataset_id)
  130. DatasetService.check_dataset_permission(dataset, user)
  131. action = None
  132. if dataset.indexing_technique != data['indexing_technique']:
  133. # if update indexing_technique
  134. if data['indexing_technique'] == 'economy':
  135. action = 'remove'
  136. filtered_data['embedding_model'] = None
  137. filtered_data['embedding_model_provider'] = None
  138. filtered_data['collection_binding_id'] = None
  139. elif data['indexing_technique'] == 'high_quality':
  140. action = 'add'
  141. # get embedding model setting
  142. try:
  143. embedding_model = ModelFactory.get_embedding_model(
  144. tenant_id=current_user.current_tenant_id
  145. )
  146. filtered_data['embedding_model'] = embedding_model.name
  147. filtered_data['embedding_model_provider'] = embedding_model.model_provider.provider_name
  148. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  149. embedding_model.model_provider.provider_name,
  150. embedding_model.name
  151. )
  152. filtered_data['collection_binding_id'] = dataset_collection_binding.id
  153. except LLMBadRequestError:
  154. raise ValueError(
  155. f"No Embedding Model available. Please configure a valid provider "
  156. f"in the Settings -> Model Provider.")
  157. except ProviderTokenNotInitError as ex:
  158. raise ValueError(ex.description)
  159. filtered_data['updated_by'] = user.id
  160. filtered_data['updated_at'] = datetime.datetime.now()
  161. dataset.query.filter_by(id=dataset_id).update(filtered_data)
  162. db.session.commit()
  163. if action:
  164. deal_dataset_vector_index_task.delay(dataset_id, action)
  165. return dataset
  166. @staticmethod
  167. def delete_dataset(dataset_id, user):
  168. # todo: cannot delete dataset if it is being processed
  169. dataset = DatasetService.get_dataset(dataset_id)
  170. if dataset is None:
  171. return False
  172. DatasetService.check_dataset_permission(dataset, user)
  173. dataset_was_deleted.send(dataset)
  174. db.session.delete(dataset)
  175. db.session.commit()
  176. return True
  177. @staticmethod
  178. def check_dataset_permission(dataset, user):
  179. if dataset.tenant_id != user.current_tenant_id:
  180. logging.debug(
  181. f'User {user.id} does not have permission to access dataset {dataset.id}')
  182. raise NoPermissionError(
  183. 'You do not have permission to access this dataset.')
  184. if dataset.permission == 'only_me' and dataset.created_by != user.id:
  185. logging.debug(
  186. f'User {user.id} does not have permission to access dataset {dataset.id}')
  187. raise NoPermissionError(
  188. 'You do not have permission to access this dataset.')
  189. @staticmethod
  190. def get_dataset_queries(dataset_id: str, page: int, per_page: int):
  191. dataset_queries = DatasetQuery.query.filter_by(dataset_id=dataset_id) \
  192. .order_by(db.desc(DatasetQuery.created_at)) \
  193. .paginate(
  194. page=page, per_page=per_page, max_per_page=100, error_out=False
  195. )
  196. return dataset_queries.items, dataset_queries.total
  197. @staticmethod
  198. def get_related_apps(dataset_id: str):
  199. return AppDatasetJoin.query.filter(AppDatasetJoin.dataset_id == dataset_id) \
  200. .order_by(db.desc(AppDatasetJoin.created_at)).all()
  201. class DocumentService:
  202. DEFAULT_RULES = {
  203. 'mode': 'custom',
  204. 'rules': {
  205. 'pre_processing_rules': [
  206. {'id': 'remove_extra_spaces', 'enabled': True},
  207. {'id': 'remove_urls_emails', 'enabled': False}
  208. ],
  209. 'segmentation': {
  210. 'delimiter': '\n',
  211. 'max_tokens': 500
  212. }
  213. }
  214. }
  215. DOCUMENT_METADATA_SCHEMA = {
  216. "book": {
  217. "title": str,
  218. "language": str,
  219. "author": str,
  220. "publisher": str,
  221. "publication_date": str,
  222. "isbn": str,
  223. "category": str,
  224. },
  225. "web_page": {
  226. "title": str,
  227. "url": str,
  228. "language": str,
  229. "publish_date": str,
  230. "author/publisher": str,
  231. "topic/keywords": str,
  232. "description": str,
  233. },
  234. "paper": {
  235. "title": str,
  236. "language": str,
  237. "author": str,
  238. "publish_date": str,
  239. "journal/conference_name": str,
  240. "volume/issue/page_numbers": str,
  241. "doi": str,
  242. "topic/keywords": str,
  243. "abstract": str,
  244. },
  245. "social_media_post": {
  246. "platform": str,
  247. "author/username": str,
  248. "publish_date": str,
  249. "post_url": str,
  250. "topic/tags": str,
  251. },
  252. "wikipedia_entry": {
  253. "title": str,
  254. "language": str,
  255. "web_page_url": str,
  256. "last_edit_date": str,
  257. "editor/contributor": str,
  258. "summary/introduction": str,
  259. },
  260. "personal_document": {
  261. "title": str,
  262. "author": str,
  263. "creation_date": str,
  264. "last_modified_date": str,
  265. "document_type": str,
  266. "tags/category": str,
  267. },
  268. "business_document": {
  269. "title": str,
  270. "author": str,
  271. "creation_date": str,
  272. "last_modified_date": str,
  273. "document_type": str,
  274. "department/team": str,
  275. },
  276. "im_chat_log": {
  277. "chat_platform": str,
  278. "chat_participants/group_name": str,
  279. "start_date": str,
  280. "end_date": str,
  281. "summary": str,
  282. },
  283. "synced_from_notion": {
  284. "title": str,
  285. "language": str,
  286. "author/creator": str,
  287. "creation_date": str,
  288. "last_modified_date": str,
  289. "notion_page_link": str,
  290. "category/tags": str,
  291. "description": str,
  292. },
  293. "synced_from_github": {
  294. "repository_name": str,
  295. "repository_description": str,
  296. "repository_owner/organization": str,
  297. "code_filename": str,
  298. "code_file_path": str,
  299. "programming_language": str,
  300. "github_link": str,
  301. "open_source_license": str,
  302. "commit_date": str,
  303. "commit_author": str,
  304. },
  305. "others": dict
  306. }
  307. @staticmethod
  308. def get_document(dataset_id: str, document_id: str) -> Optional[Document]:
  309. document = db.session.query(Document).filter(
  310. Document.id == document_id,
  311. Document.dataset_id == dataset_id
  312. ).first()
  313. return document
  314. @staticmethod
  315. def get_document_by_id(document_id: str) -> Optional[Document]:
  316. document = db.session.query(Document).filter(
  317. Document.id == document_id
  318. ).first()
  319. return document
  320. @staticmethod
  321. def get_document_by_dataset_id(dataset_id: str) -> List[Document]:
  322. documents = db.session.query(Document).filter(
  323. Document.dataset_id == dataset_id,
  324. Document.enabled == True
  325. ).all()
  326. return documents
  327. @staticmethod
  328. def get_batch_documents(dataset_id: str, batch: str) -> List[Document]:
  329. documents = db.session.query(Document).filter(
  330. Document.batch == batch,
  331. Document.dataset_id == dataset_id,
  332. Document.tenant_id == current_user.current_tenant_id
  333. ).all()
  334. return documents
  335. @staticmethod
  336. def get_document_file_detail(file_id: str):
  337. file_detail = db.session.query(UploadFile). \
  338. filter(UploadFile.id == file_id). \
  339. one_or_none()
  340. return file_detail
  341. @staticmethod
  342. def check_archived(document):
  343. if document.archived:
  344. return True
  345. else:
  346. return False
  347. @staticmethod
  348. def delete_document(document):
  349. if document.indexing_status in ["parsing", "cleaning", "splitting", "indexing"]:
  350. raise DocumentIndexingError()
  351. # trigger document_was_deleted signal
  352. document_was_deleted.send(document.id, dataset_id=document.dataset_id)
  353. db.session.delete(document)
  354. db.session.commit()
  355. @staticmethod
  356. def pause_document(document):
  357. if document.indexing_status not in ["waiting", "parsing", "cleaning", "splitting", "indexing"]:
  358. raise DocumentIndexingError()
  359. # update document to be paused
  360. document.is_paused = True
  361. document.paused_by = current_user.id
  362. document.paused_at = datetime.datetime.utcnow()
  363. db.session.add(document)
  364. db.session.commit()
  365. # set document paused flag
  366. indexing_cache_key = 'document_{}_is_paused'.format(document.id)
  367. redis_client.setnx(indexing_cache_key, "True")
  368. @staticmethod
  369. def recover_document(document):
  370. if not document.is_paused:
  371. raise DocumentIndexingError()
  372. # update document to be recover
  373. document.is_paused = False
  374. document.paused_by = None
  375. document.paused_at = None
  376. db.session.add(document)
  377. db.session.commit()
  378. # delete paused flag
  379. indexing_cache_key = 'document_{}_is_paused'.format(document.id)
  380. redis_client.delete(indexing_cache_key)
  381. # trigger async task
  382. recover_document_indexing_task.delay(document.dataset_id, document.id)
  383. @staticmethod
  384. def get_documents_position(dataset_id):
  385. document = Document.query.filter_by(dataset_id=dataset_id).order_by(Document.position.desc()).first()
  386. if document:
  387. return document.position + 1
  388. else:
  389. return 1
  390. @staticmethod
  391. def save_document_with_dataset_id(dataset: Dataset, document_data: dict,
  392. account: Account, dataset_process_rule: Optional[DatasetProcessRule] = None,
  393. created_from: str = 'web'):
  394. # check document limit
  395. if current_app.config['EDITION'] == 'CLOUD':
  396. if 'original_document_id' not in document_data or not document_data['original_document_id']:
  397. count = 0
  398. if document_data["data_source"]["type"] == "upload_file":
  399. upload_file_list = document_data["data_source"]["info_list"]['file_info_list']['file_ids']
  400. count = len(upload_file_list)
  401. elif document_data["data_source"]["type"] == "notion_import":
  402. notion_info_list = document_data["data_source"]['info_list']['notion_info_list']
  403. for notion_info in notion_info_list:
  404. count = count + len(notion_info['pages'])
  405. documents_count = DocumentService.get_tenant_documents_count()
  406. total_count = documents_count + count
  407. tenant_document_count = int(current_app.config['TENANT_DOCUMENT_COUNT'])
  408. if total_count > tenant_document_count:
  409. raise ValueError(f"over document limit {tenant_document_count}.")
  410. # if dataset is empty, update dataset data_source_type
  411. if not dataset.data_source_type:
  412. dataset.data_source_type = document_data["data_source"]["type"]
  413. if not dataset.indexing_technique:
  414. if 'indexing_technique' not in document_data \
  415. or document_data['indexing_technique'] not in Dataset.INDEXING_TECHNIQUE_LIST:
  416. raise ValueError("Indexing technique is required")
  417. dataset.indexing_technique = document_data["indexing_technique"]
  418. if document_data["indexing_technique"] == 'high_quality':
  419. embedding_model = ModelFactory.get_embedding_model(
  420. tenant_id=dataset.tenant_id
  421. )
  422. dataset.embedding_model = embedding_model.name
  423. dataset.embedding_model_provider = embedding_model.model_provider.provider_name
  424. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  425. embedding_model.model_provider.provider_name,
  426. embedding_model.name
  427. )
  428. dataset.collection_binding_id = dataset_collection_binding.id
  429. documents = []
  430. batch = time.strftime('%Y%m%d%H%M%S') + str(random.randint(100000, 999999))
  431. if 'original_document_id' in document_data and document_data["original_document_id"]:
  432. document = DocumentService.update_document_with_dataset_id(dataset, document_data, account)
  433. documents.append(document)
  434. else:
  435. # save process rule
  436. if not dataset_process_rule:
  437. process_rule = document_data["process_rule"]
  438. if process_rule["mode"] == "custom":
  439. dataset_process_rule = DatasetProcessRule(
  440. dataset_id=dataset.id,
  441. mode=process_rule["mode"],
  442. rules=json.dumps(process_rule["rules"]),
  443. created_by=account.id
  444. )
  445. elif process_rule["mode"] == "automatic":
  446. dataset_process_rule = DatasetProcessRule(
  447. dataset_id=dataset.id,
  448. mode=process_rule["mode"],
  449. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  450. created_by=account.id
  451. )
  452. db.session.add(dataset_process_rule)
  453. db.session.commit()
  454. position = DocumentService.get_documents_position(dataset.id)
  455. document_ids = []
  456. if document_data["data_source"]["type"] == "upload_file":
  457. upload_file_list = document_data["data_source"]["info_list"]['file_info_list']['file_ids']
  458. for file_id in upload_file_list:
  459. file = db.session.query(UploadFile).filter(
  460. UploadFile.tenant_id == dataset.tenant_id,
  461. UploadFile.id == file_id
  462. ).first()
  463. # raise error if file not found
  464. if not file:
  465. raise FileNotExistsError()
  466. file_name = file.name
  467. data_source_info = {
  468. "upload_file_id": file_id,
  469. }
  470. document = DocumentService.build_document(dataset, dataset_process_rule.id,
  471. document_data["data_source"]["type"],
  472. document_data["doc_form"],
  473. document_data["doc_language"],
  474. data_source_info, created_from, position,
  475. account, file_name, batch)
  476. db.session.add(document)
  477. db.session.flush()
  478. document_ids.append(document.id)
  479. documents.append(document)
  480. position += 1
  481. elif document_data["data_source"]["type"] == "notion_import":
  482. notion_info_list = document_data["data_source"]['info_list']['notion_info_list']
  483. exist_page_ids = []
  484. exist_document = dict()
  485. documents = Document.query.filter_by(
  486. dataset_id=dataset.id,
  487. tenant_id=current_user.current_tenant_id,
  488. data_source_type='notion_import',
  489. enabled=True
  490. ).all()
  491. if documents:
  492. for document in documents:
  493. data_source_info = json.loads(document.data_source_info)
  494. exist_page_ids.append(data_source_info['notion_page_id'])
  495. exist_document[data_source_info['notion_page_id']] = document.id
  496. for notion_info in notion_info_list:
  497. workspace_id = notion_info['workspace_id']
  498. data_source_binding = DataSourceBinding.query.filter(
  499. db.and_(
  500. DataSourceBinding.tenant_id == current_user.current_tenant_id,
  501. DataSourceBinding.provider == 'notion',
  502. DataSourceBinding.disabled == False,
  503. DataSourceBinding.source_info['workspace_id'] == f'"{workspace_id}"'
  504. )
  505. ).first()
  506. if not data_source_binding:
  507. raise ValueError('Data source binding not found.')
  508. for page in notion_info['pages']:
  509. if page['page_id'] not in exist_page_ids:
  510. data_source_info = {
  511. "notion_workspace_id": workspace_id,
  512. "notion_page_id": page['page_id'],
  513. "notion_page_icon": page['page_icon'],
  514. "type": page['type']
  515. }
  516. document = DocumentService.build_document(dataset, dataset_process_rule.id,
  517. document_data["data_source"]["type"],
  518. document_data["doc_form"],
  519. document_data["doc_language"],
  520. data_source_info, created_from, position,
  521. account, page['page_name'], batch)
  522. db.session.add(document)
  523. db.session.flush()
  524. document_ids.append(document.id)
  525. documents.append(document)
  526. position += 1
  527. else:
  528. exist_document.pop(page['page_id'])
  529. # delete not selected documents
  530. if len(exist_document) > 0:
  531. clean_notion_document_task.delay(list(exist_document.values()), dataset.id)
  532. db.session.commit()
  533. # trigger async task
  534. document_indexing_task.delay(dataset.id, document_ids)
  535. return documents, batch
  536. @staticmethod
  537. def build_document(dataset: Dataset, process_rule_id: str, data_source_type: str, document_form: str,
  538. document_language: str, data_source_info: dict, created_from: str, position: int,
  539. account: Account,
  540. name: str, batch: str):
  541. document = Document(
  542. tenant_id=dataset.tenant_id,
  543. dataset_id=dataset.id,
  544. position=position,
  545. data_source_type=data_source_type,
  546. data_source_info=json.dumps(data_source_info),
  547. dataset_process_rule_id=process_rule_id,
  548. batch=batch,
  549. name=name,
  550. created_from=created_from,
  551. created_by=account.id,
  552. doc_form=document_form,
  553. doc_language=document_language
  554. )
  555. return document
  556. @staticmethod
  557. def get_tenant_documents_count():
  558. documents_count = Document.query.filter(Document.completed_at.isnot(None),
  559. Document.enabled == True,
  560. Document.archived == False,
  561. Document.tenant_id == current_user.current_tenant_id).count()
  562. return documents_count
  563. @staticmethod
  564. def update_document_with_dataset_id(dataset: Dataset, document_data: dict,
  565. account: Account, dataset_process_rule: Optional[DatasetProcessRule] = None,
  566. created_from: str = 'web'):
  567. DatasetService.check_dataset_model_setting(dataset)
  568. document = DocumentService.get_document(dataset.id, document_data["original_document_id"])
  569. if document.display_status != 'available':
  570. raise ValueError("Document is not available")
  571. # save process rule
  572. if 'process_rule' in document_data and document_data['process_rule']:
  573. process_rule = document_data["process_rule"]
  574. if process_rule["mode"] == "custom":
  575. dataset_process_rule = DatasetProcessRule(
  576. dataset_id=dataset.id,
  577. mode=process_rule["mode"],
  578. rules=json.dumps(process_rule["rules"]),
  579. created_by=account.id
  580. )
  581. elif process_rule["mode"] == "automatic":
  582. dataset_process_rule = DatasetProcessRule(
  583. dataset_id=dataset.id,
  584. mode=process_rule["mode"],
  585. rules=json.dumps(DatasetProcessRule.AUTOMATIC_RULES),
  586. created_by=account.id
  587. )
  588. db.session.add(dataset_process_rule)
  589. db.session.commit()
  590. document.dataset_process_rule_id = dataset_process_rule.id
  591. # update document data source
  592. if 'data_source' in document_data and document_data['data_source']:
  593. file_name = ''
  594. data_source_info = {}
  595. if document_data["data_source"]["type"] == "upload_file":
  596. upload_file_list = document_data["data_source"]["info_list"]['file_info_list']['file_ids']
  597. for file_id in upload_file_list:
  598. file = db.session.query(UploadFile).filter(
  599. UploadFile.tenant_id == dataset.tenant_id,
  600. UploadFile.id == file_id
  601. ).first()
  602. # raise error if file not found
  603. if not file:
  604. raise FileNotExistsError()
  605. file_name = file.name
  606. data_source_info = {
  607. "upload_file_id": file_id,
  608. }
  609. elif document_data["data_source"]["type"] == "notion_import":
  610. notion_info_list = document_data["data_source"]['info_list']['notion_info_list']
  611. for notion_info in notion_info_list:
  612. workspace_id = notion_info['workspace_id']
  613. data_source_binding = DataSourceBinding.query.filter(
  614. db.and_(
  615. DataSourceBinding.tenant_id == current_user.current_tenant_id,
  616. DataSourceBinding.provider == 'notion',
  617. DataSourceBinding.disabled == False,
  618. DataSourceBinding.source_info['workspace_id'] == f'"{workspace_id}"'
  619. )
  620. ).first()
  621. if not data_source_binding:
  622. raise ValueError('Data source binding not found.')
  623. for page in notion_info['pages']:
  624. data_source_info = {
  625. "notion_workspace_id": workspace_id,
  626. "notion_page_id": page['page_id'],
  627. "notion_page_icon": page['page_icon'],
  628. "type": page['type']
  629. }
  630. document.data_source_type = document_data["data_source"]["type"]
  631. document.data_source_info = json.dumps(data_source_info)
  632. document.name = file_name
  633. # update document to be waiting
  634. document.indexing_status = 'waiting'
  635. document.completed_at = None
  636. document.processing_started_at = None
  637. document.parsing_completed_at = None
  638. document.cleaning_completed_at = None
  639. document.splitting_completed_at = None
  640. document.updated_at = datetime.datetime.utcnow()
  641. document.created_from = created_from
  642. document.doc_form = document_data['doc_form']
  643. db.session.add(document)
  644. db.session.commit()
  645. # update document segment
  646. update_params = {
  647. DocumentSegment.status: 're_segment'
  648. }
  649. DocumentSegment.query.filter_by(document_id=document.id).update(update_params)
  650. db.session.commit()
  651. # trigger async task
  652. document_indexing_update_task.delay(document.dataset_id, document.id)
  653. return document
  654. @staticmethod
  655. def save_document_without_dataset_id(tenant_id: str, document_data: dict, account: Account):
  656. count = 0
  657. if document_data["data_source"]["type"] == "upload_file":
  658. upload_file_list = document_data["data_source"]["info_list"]['file_info_list']['file_ids']
  659. count = len(upload_file_list)
  660. elif document_data["data_source"]["type"] == "notion_import":
  661. notion_info_list = document_data["data_source"]['info_list']['notion_info_list']
  662. for notion_info in notion_info_list:
  663. count = count + len(notion_info['pages'])
  664. # check document limit
  665. if current_app.config['EDITION'] == 'CLOUD':
  666. documents_count = DocumentService.get_tenant_documents_count()
  667. total_count = documents_count + count
  668. tenant_document_count = int(current_app.config['TENANT_DOCUMENT_COUNT'])
  669. if total_count > tenant_document_count:
  670. raise ValueError(f"All your documents have overed limit {tenant_document_count}.")
  671. embedding_model = None
  672. dataset_collection_binding_id = None
  673. if document_data['indexing_technique'] == 'high_quality':
  674. embedding_model = ModelFactory.get_embedding_model(
  675. tenant_id=tenant_id
  676. )
  677. dataset_collection_binding = DatasetCollectionBindingService.get_dataset_collection_binding(
  678. embedding_model.model_provider.provider_name,
  679. embedding_model.name
  680. )
  681. dataset_collection_binding_id = dataset_collection_binding.id
  682. # save dataset
  683. dataset = Dataset(
  684. tenant_id=tenant_id,
  685. name='',
  686. data_source_type=document_data["data_source"]["type"],
  687. indexing_technique=document_data["indexing_technique"],
  688. created_by=account.id,
  689. embedding_model=embedding_model.name if embedding_model else None,
  690. embedding_model_provider=embedding_model.model_provider.provider_name if embedding_model else None,
  691. collection_binding_id=dataset_collection_binding_id
  692. )
  693. db.session.add(dataset)
  694. db.session.flush()
  695. documents, batch = DocumentService.save_document_with_dataset_id(dataset, document_data, account)
  696. cut_length = 18
  697. cut_name = documents[0].name[:cut_length]
  698. dataset.name = cut_name + '...'
  699. dataset.description = 'useful for when you want to answer queries about the ' + documents[0].name
  700. db.session.commit()
  701. return dataset, documents, batch
  702. @classmethod
  703. def document_create_args_validate(cls, args: dict):
  704. if 'original_document_id' not in args or not args['original_document_id']:
  705. DocumentService.data_source_args_validate(args)
  706. DocumentService.process_rule_args_validate(args)
  707. else:
  708. if ('data_source' not in args and not args['data_source']) \
  709. and ('process_rule' not in args and not args['process_rule']):
  710. raise ValueError("Data source or Process rule is required")
  711. else:
  712. if 'data_source' in args and args['data_source']:
  713. DocumentService.data_source_args_validate(args)
  714. if 'process_rule' in args and args['process_rule']:
  715. DocumentService.process_rule_args_validate(args)
  716. @classmethod
  717. def data_source_args_validate(cls, args: dict):
  718. if 'data_source' not in args or not args['data_source']:
  719. raise ValueError("Data source is required")
  720. if not isinstance(args['data_source'], dict):
  721. raise ValueError("Data source is invalid")
  722. if 'type' not in args['data_source'] or not args['data_source']['type']:
  723. raise ValueError("Data source type is required")
  724. if args['data_source']['type'] not in Document.DATA_SOURCES:
  725. raise ValueError("Data source type is invalid")
  726. if 'info_list' not in args['data_source'] or not args['data_source']['info_list']:
  727. raise ValueError("Data source info is required")
  728. if args['data_source']['type'] == 'upload_file':
  729. if 'file_info_list' not in args['data_source']['info_list'] or not args['data_source']['info_list'][
  730. 'file_info_list']:
  731. raise ValueError("File source info is required")
  732. if args['data_source']['type'] == 'notion_import':
  733. if 'notion_info_list' not in args['data_source']['info_list'] or not args['data_source']['info_list'][
  734. 'notion_info_list']:
  735. raise ValueError("Notion source info is required")
  736. @classmethod
  737. def process_rule_args_validate(cls, args: dict):
  738. if 'process_rule' not in args or not args['process_rule']:
  739. raise ValueError("Process rule is required")
  740. if not isinstance(args['process_rule'], dict):
  741. raise ValueError("Process rule is invalid")
  742. if 'mode' not in args['process_rule'] or not args['process_rule']['mode']:
  743. raise ValueError("Process rule mode is required")
  744. if args['process_rule']['mode'] not in DatasetProcessRule.MODES:
  745. raise ValueError("Process rule mode is invalid")
  746. if args['process_rule']['mode'] == 'automatic':
  747. args['process_rule']['rules'] = {}
  748. else:
  749. if 'rules' not in args['process_rule'] or not args['process_rule']['rules']:
  750. raise ValueError("Process rule rules is required")
  751. if not isinstance(args['process_rule']['rules'], dict):
  752. raise ValueError("Process rule rules is invalid")
  753. if 'pre_processing_rules' not in args['process_rule']['rules'] \
  754. or args['process_rule']['rules']['pre_processing_rules'] is None:
  755. raise ValueError("Process rule pre_processing_rules is required")
  756. if not isinstance(args['process_rule']['rules']['pre_processing_rules'], list):
  757. raise ValueError("Process rule pre_processing_rules is invalid")
  758. unique_pre_processing_rule_dicts = {}
  759. for pre_processing_rule in args['process_rule']['rules']['pre_processing_rules']:
  760. if 'id' not in pre_processing_rule or not pre_processing_rule['id']:
  761. raise ValueError("Process rule pre_processing_rules id is required")
  762. if pre_processing_rule['id'] not in DatasetProcessRule.PRE_PROCESSING_RULES:
  763. raise ValueError("Process rule pre_processing_rules id is invalid")
  764. if 'enabled' not in pre_processing_rule or pre_processing_rule['enabled'] is None:
  765. raise ValueError("Process rule pre_processing_rules enabled is required")
  766. if not isinstance(pre_processing_rule['enabled'], bool):
  767. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  768. unique_pre_processing_rule_dicts[pre_processing_rule['id']] = pre_processing_rule
  769. args['process_rule']['rules']['pre_processing_rules'] = list(unique_pre_processing_rule_dicts.values())
  770. if 'segmentation' not in args['process_rule']['rules'] \
  771. or args['process_rule']['rules']['segmentation'] is None:
  772. raise ValueError("Process rule segmentation is required")
  773. if not isinstance(args['process_rule']['rules']['segmentation'], dict):
  774. raise ValueError("Process rule segmentation is invalid")
  775. if 'separator' not in args['process_rule']['rules']['segmentation'] \
  776. or not args['process_rule']['rules']['segmentation']['separator']:
  777. raise ValueError("Process rule segmentation separator is required")
  778. if not isinstance(args['process_rule']['rules']['segmentation']['separator'], str):
  779. raise ValueError("Process rule segmentation separator is invalid")
  780. if 'max_tokens' not in args['process_rule']['rules']['segmentation'] \
  781. or not args['process_rule']['rules']['segmentation']['max_tokens']:
  782. raise ValueError("Process rule segmentation max_tokens is required")
  783. if not isinstance(args['process_rule']['rules']['segmentation']['max_tokens'], int):
  784. raise ValueError("Process rule segmentation max_tokens is invalid")
  785. @classmethod
  786. def estimate_args_validate(cls, args: dict):
  787. if 'info_list' not in args or not args['info_list']:
  788. raise ValueError("Data source info is required")
  789. if not isinstance(args['info_list'], dict):
  790. raise ValueError("Data info is invalid")
  791. if 'process_rule' not in args or not args['process_rule']:
  792. raise ValueError("Process rule is required")
  793. if not isinstance(args['process_rule'], dict):
  794. raise ValueError("Process rule is invalid")
  795. if 'mode' not in args['process_rule'] or not args['process_rule']['mode']:
  796. raise ValueError("Process rule mode is required")
  797. if args['process_rule']['mode'] not in DatasetProcessRule.MODES:
  798. raise ValueError("Process rule mode is invalid")
  799. if args['process_rule']['mode'] == 'automatic':
  800. args['process_rule']['rules'] = {}
  801. else:
  802. if 'rules' not in args['process_rule'] or not args['process_rule']['rules']:
  803. raise ValueError("Process rule rules is required")
  804. if not isinstance(args['process_rule']['rules'], dict):
  805. raise ValueError("Process rule rules is invalid")
  806. if 'pre_processing_rules' not in args['process_rule']['rules'] \
  807. or args['process_rule']['rules']['pre_processing_rules'] is None:
  808. raise ValueError("Process rule pre_processing_rules is required")
  809. if not isinstance(args['process_rule']['rules']['pre_processing_rules'], list):
  810. raise ValueError("Process rule pre_processing_rules is invalid")
  811. unique_pre_processing_rule_dicts = {}
  812. for pre_processing_rule in args['process_rule']['rules']['pre_processing_rules']:
  813. if 'id' not in pre_processing_rule or not pre_processing_rule['id']:
  814. raise ValueError("Process rule pre_processing_rules id is required")
  815. if pre_processing_rule['id'] not in DatasetProcessRule.PRE_PROCESSING_RULES:
  816. raise ValueError("Process rule pre_processing_rules id is invalid")
  817. if 'enabled' not in pre_processing_rule or pre_processing_rule['enabled'] is None:
  818. raise ValueError("Process rule pre_processing_rules enabled is required")
  819. if not isinstance(pre_processing_rule['enabled'], bool):
  820. raise ValueError("Process rule pre_processing_rules enabled is invalid")
  821. unique_pre_processing_rule_dicts[pre_processing_rule['id']] = pre_processing_rule
  822. args['process_rule']['rules']['pre_processing_rules'] = list(unique_pre_processing_rule_dicts.values())
  823. if 'segmentation' not in args['process_rule']['rules'] \
  824. or args['process_rule']['rules']['segmentation'] is None:
  825. raise ValueError("Process rule segmentation is required")
  826. if not isinstance(args['process_rule']['rules']['segmentation'], dict):
  827. raise ValueError("Process rule segmentation is invalid")
  828. if 'separator' not in args['process_rule']['rules']['segmentation'] \
  829. or not args['process_rule']['rules']['segmentation']['separator']:
  830. raise ValueError("Process rule segmentation separator is required")
  831. if not isinstance(args['process_rule']['rules']['segmentation']['separator'], str):
  832. raise ValueError("Process rule segmentation separator is invalid")
  833. if 'max_tokens' not in args['process_rule']['rules']['segmentation'] \
  834. or not args['process_rule']['rules']['segmentation']['max_tokens']:
  835. raise ValueError("Process rule segmentation max_tokens is required")
  836. if not isinstance(args['process_rule']['rules']['segmentation']['max_tokens'], int):
  837. raise ValueError("Process rule segmentation max_tokens is invalid")
  838. class SegmentService:
  839. @classmethod
  840. def segment_create_args_validate(cls, args: dict, document: Document):
  841. if document.doc_form == 'qa_model':
  842. if 'answer' not in args or not args['answer']:
  843. raise ValueError("Answer is required")
  844. if not args['answer'].strip():
  845. raise ValueError("Answer is empty")
  846. if 'content' not in args or not args['content'] or not args['content'].strip():
  847. raise ValueError("Content is empty")
  848. @classmethod
  849. def create_segment(cls, args: dict, document: Document, dataset: Dataset):
  850. content = args['content']
  851. doc_id = str(uuid.uuid4())
  852. segment_hash = helper.generate_text_hash(content)
  853. tokens = 0
  854. if dataset.indexing_technique == 'high_quality':
  855. embedding_model = ModelFactory.get_embedding_model(
  856. tenant_id=dataset.tenant_id,
  857. model_provider_name=dataset.embedding_model_provider,
  858. model_name=dataset.embedding_model
  859. )
  860. # calc embedding use tokens
  861. tokens = embedding_model.get_num_tokens(content)
  862. max_position = db.session.query(func.max(DocumentSegment.position)).filter(
  863. DocumentSegment.document_id == document.id
  864. ).scalar()
  865. segment_document = DocumentSegment(
  866. tenant_id=current_user.current_tenant_id,
  867. dataset_id=document.dataset_id,
  868. document_id=document.id,
  869. index_node_id=doc_id,
  870. index_node_hash=segment_hash,
  871. position=max_position + 1 if max_position else 1,
  872. content=content,
  873. word_count=len(content),
  874. tokens=tokens,
  875. status='completed',
  876. indexing_at=datetime.datetime.utcnow(),
  877. completed_at=datetime.datetime.utcnow(),
  878. created_by=current_user.id
  879. )
  880. if document.doc_form == 'qa_model':
  881. segment_document.answer = args['answer']
  882. db.session.add(segment_document)
  883. db.session.commit()
  884. # save vector index
  885. try:
  886. VectorService.create_segment_vector(args['keywords'], segment_document, dataset)
  887. except Exception as e:
  888. logging.exception("create segment index failed")
  889. segment_document.enabled = False
  890. segment_document.disabled_at = datetime.datetime.utcnow()
  891. segment_document.status = 'error'
  892. segment_document.error = str(e)
  893. db.session.commit()
  894. segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment_document.id).first()
  895. return segment
  896. @classmethod
  897. def update_segment(cls, args: dict, segment: DocumentSegment, document: Document, dataset: Dataset):
  898. indexing_cache_key = 'segment_{}_indexing'.format(segment.id)
  899. cache_result = redis_client.get(indexing_cache_key)
  900. if cache_result is not None:
  901. raise ValueError("Segment is indexing, please try again later")
  902. try:
  903. content = args['content']
  904. if segment.content == content:
  905. if document.doc_form == 'qa_model':
  906. segment.answer = args['answer']
  907. if args['keywords']:
  908. segment.keywords = args['keywords']
  909. db.session.add(segment)
  910. db.session.commit()
  911. # update segment index task
  912. if args['keywords']:
  913. kw_index = IndexBuilder.get_index(dataset, 'economy')
  914. # delete from keyword index
  915. kw_index.delete_by_ids([segment.index_node_id])
  916. # save keyword index
  917. kw_index.update_segment_keywords_index(segment.index_node_id, segment.keywords)
  918. else:
  919. segment_hash = helper.generate_text_hash(content)
  920. tokens = 0
  921. if dataset.indexing_technique == 'high_quality':
  922. embedding_model = ModelFactory.get_embedding_model(
  923. tenant_id=dataset.tenant_id,
  924. model_provider_name=dataset.embedding_model_provider,
  925. model_name=dataset.embedding_model
  926. )
  927. # calc embedding use tokens
  928. tokens = embedding_model.get_num_tokens(content)
  929. segment.content = content
  930. segment.index_node_hash = segment_hash
  931. segment.word_count = len(content)
  932. segment.tokens = tokens
  933. segment.status = 'completed'
  934. segment.indexing_at = datetime.datetime.utcnow()
  935. segment.completed_at = datetime.datetime.utcnow()
  936. segment.updated_by = current_user.id
  937. segment.updated_at = datetime.datetime.utcnow()
  938. if document.doc_form == 'qa_model':
  939. segment.answer = args['answer']
  940. db.session.add(segment)
  941. db.session.commit()
  942. # update segment vector index
  943. VectorService.update_segment_vector(args['keywords'], segment, dataset)
  944. except Exception as e:
  945. logging.exception("update segment index failed")
  946. segment.enabled = False
  947. segment.disabled_at = datetime.datetime.utcnow()
  948. segment.status = 'error'
  949. segment.error = str(e)
  950. db.session.commit()
  951. segment = db.session.query(DocumentSegment).filter(DocumentSegment.id == segment.id).first()
  952. return segment
  953. @classmethod
  954. def delete_segment(cls, segment: DocumentSegment, document: Document, dataset: Dataset):
  955. indexing_cache_key = 'segment_{}_delete_indexing'.format(segment.id)
  956. cache_result = redis_client.get(indexing_cache_key)
  957. if cache_result is not None:
  958. raise ValueError("Segment is deleting.")
  959. # enabled segment need to delete index
  960. if segment.enabled:
  961. # send delete segment index task
  962. redis_client.setex(indexing_cache_key, 600, 1)
  963. delete_segment_from_index_task.delay(segment.id, segment.index_node_id, dataset.id, document.id)
  964. db.session.delete(segment)
  965. db.session.commit()
  966. class DatasetCollectionBindingService:
  967. @classmethod
  968. def get_dataset_collection_binding(cls, provider_name: str, model_name: str) -> DatasetCollectionBinding:
  969. dataset_collection_binding = db.session.query(DatasetCollectionBinding). \
  970. filter(DatasetCollectionBinding.provider_name == provider_name,
  971. DatasetCollectionBinding.model_name == model_name). \
  972. order_by(DatasetCollectionBinding.created_at). \
  973. first()
  974. if not dataset_collection_binding:
  975. dataset_collection_binding = DatasetCollectionBinding(
  976. provider_name=provider_name,
  977. model_name=model_name,
  978. collection_name="Vector_index_" + str(uuid.uuid4()).replace("-", "_") + '_Node'
  979. )
  980. db.session.add(dataset_collection_binding)
  981. db.session.flush()
  982. return dataset_collection_binding