dataset_service.py 47 KB

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