dataset_service.py 47 KB

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