dataset_service.py 76 KB

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