indexing_runner.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. import datetime
  2. import json
  3. import re
  4. import tempfile
  5. import time
  6. from pathlib import Path
  7. from typing import Optional, List
  8. from flask_login import current_user
  9. from langchain.text_splitter import RecursiveCharacterTextSplitter
  10. from llama_index import SimpleDirectoryReader
  11. from llama_index.data_structs import Node
  12. from llama_index.data_structs.node_v2 import DocumentRelationship
  13. from llama_index.node_parser import SimpleNodeParser, NodeParser
  14. from llama_index.readers.file.base import DEFAULT_FILE_EXTRACTOR
  15. from llama_index.readers.file.markdown_parser import MarkdownParser
  16. from core.data_source.notion import NotionPageReader
  17. from core.index.readers.xlsx_parser import XLSXParser
  18. from core.docstore.dataset_docstore import DatesetDocumentStore
  19. from core.index.keyword_table_index import KeywordTableIndex
  20. from core.index.readers.html_parser import HTMLParser
  21. from core.index.readers.markdown_parser import MarkdownParser
  22. from core.index.readers.pdf_parser import PDFParser
  23. from core.index.spiltter.fixed_text_splitter import FixedRecursiveCharacterTextSplitter
  24. from core.index.vector_index import VectorIndex
  25. from core.llm.token_calculator import TokenCalculator
  26. from extensions.ext_database import db
  27. from extensions.ext_redis import redis_client
  28. from extensions.ext_storage import storage
  29. from models.dataset import Document, Dataset, DocumentSegment, DatasetProcessRule
  30. from models.model import UploadFile
  31. from models.source import DataSourceBinding
  32. class IndexingRunner:
  33. def __init__(self, embedding_model_name: str = "text-embedding-ada-002"):
  34. self.storage = storage
  35. self.embedding_model_name = embedding_model_name
  36. def run(self, documents: List[Document]):
  37. """Run the indexing process."""
  38. for document in documents:
  39. # get dataset
  40. dataset = Dataset.query.filter_by(
  41. id=document.dataset_id
  42. ).first()
  43. if not dataset:
  44. raise ValueError("no dataset found")
  45. # load file
  46. text_docs = self._load_data(document)
  47. # get the process rule
  48. processing_rule = db.session.query(DatasetProcessRule). \
  49. filter(DatasetProcessRule.id == document.dataset_process_rule_id). \
  50. first()
  51. # get node parser for splitting
  52. node_parser = self._get_node_parser(processing_rule)
  53. # split to nodes
  54. nodes = self._step_split(
  55. text_docs=text_docs,
  56. node_parser=node_parser,
  57. dataset=dataset,
  58. document=document,
  59. processing_rule=processing_rule
  60. )
  61. # build index
  62. self._build_index(
  63. dataset=dataset,
  64. document=document,
  65. nodes=nodes
  66. )
  67. def run_in_splitting_status(self, document: Document):
  68. """Run the indexing process when the index_status is splitting."""
  69. # get dataset
  70. dataset = Dataset.query.filter_by(
  71. id=document.dataset_id
  72. ).first()
  73. if not dataset:
  74. raise ValueError("no dataset found")
  75. # get exist document_segment list and delete
  76. document_segments = DocumentSegment.query.filter_by(
  77. dataset_id=dataset.id,
  78. document_id=document.id
  79. ).all()
  80. db.session.delete(document_segments)
  81. db.session.commit()
  82. # load file
  83. text_docs = self._load_data(document)
  84. # get the process rule
  85. processing_rule = db.session.query(DatasetProcessRule). \
  86. filter(DatasetProcessRule.id == document.dataset_process_rule_id). \
  87. first()
  88. # get node parser for splitting
  89. node_parser = self._get_node_parser(processing_rule)
  90. # split to nodes
  91. nodes = self._step_split(
  92. text_docs=text_docs,
  93. node_parser=node_parser,
  94. dataset=dataset,
  95. document=document,
  96. processing_rule=processing_rule
  97. )
  98. # build index
  99. self._build_index(
  100. dataset=dataset,
  101. document=document,
  102. nodes=nodes
  103. )
  104. def run_in_indexing_status(self, document: Document):
  105. """Run the indexing process when the index_status is indexing."""
  106. # get dataset
  107. dataset = Dataset.query.filter_by(
  108. id=document.dataset_id
  109. ).first()
  110. if not dataset:
  111. raise ValueError("no dataset found")
  112. # get exist document_segment list and delete
  113. document_segments = DocumentSegment.query.filter_by(
  114. dataset_id=dataset.id,
  115. document_id=document.id
  116. ).all()
  117. nodes = []
  118. if document_segments:
  119. for document_segment in document_segments:
  120. # transform segment to node
  121. if document_segment.status != "completed":
  122. relationships = {
  123. DocumentRelationship.SOURCE: document_segment.document_id,
  124. }
  125. previous_segment = document_segment.previous_segment
  126. if previous_segment:
  127. relationships[DocumentRelationship.PREVIOUS] = previous_segment.index_node_id
  128. next_segment = document_segment.next_segment
  129. if next_segment:
  130. relationships[DocumentRelationship.NEXT] = next_segment.index_node_id
  131. node = Node(
  132. doc_id=document_segment.index_node_id,
  133. doc_hash=document_segment.index_node_hash,
  134. text=document_segment.content,
  135. extra_info=None,
  136. node_info=None,
  137. relationships=relationships
  138. )
  139. nodes.append(node)
  140. # build index
  141. self._build_index(
  142. dataset=dataset,
  143. document=document,
  144. nodes=nodes
  145. )
  146. def file_indexing_estimate(self, file_details: List[UploadFile], tmp_processing_rule: dict) -> dict:
  147. """
  148. Estimate the indexing for the document.
  149. """
  150. tokens = 0
  151. preview_texts = []
  152. total_segments = 0
  153. for file_detail in file_details:
  154. # load data from file
  155. text_docs = self._load_data_from_file(file_detail)
  156. processing_rule = DatasetProcessRule(
  157. mode=tmp_processing_rule["mode"],
  158. rules=json.dumps(tmp_processing_rule["rules"])
  159. )
  160. # get node parser for splitting
  161. node_parser = self._get_node_parser(processing_rule)
  162. # split to nodes
  163. nodes = self._split_to_nodes(
  164. text_docs=text_docs,
  165. node_parser=node_parser,
  166. processing_rule=processing_rule
  167. )
  168. total_segments += len(nodes)
  169. for node in nodes:
  170. if len(preview_texts) < 5:
  171. preview_texts.append(node.get_text())
  172. tokens += TokenCalculator.get_num_tokens(self.embedding_model_name, node.get_text())
  173. return {
  174. "total_segments": total_segments,
  175. "tokens": tokens,
  176. "total_price": '{:f}'.format(TokenCalculator.get_token_price(self.embedding_model_name, tokens)),
  177. "currency": TokenCalculator.get_currency(self.embedding_model_name),
  178. "preview": preview_texts
  179. }
  180. def notion_indexing_estimate(self, notion_info_list: list, tmp_processing_rule: dict) -> dict:
  181. """
  182. Estimate the indexing for the document.
  183. """
  184. # load data from notion
  185. tokens = 0
  186. preview_texts = []
  187. total_segments = 0
  188. for notion_info in notion_info_list:
  189. workspace_id = notion_info['workspace_id']
  190. data_source_binding = DataSourceBinding.query.filter(
  191. db.and_(
  192. DataSourceBinding.tenant_id == current_user.current_tenant_id,
  193. DataSourceBinding.provider == 'notion',
  194. DataSourceBinding.disabled == False,
  195. DataSourceBinding.source_info['workspace_id'] == f'"{workspace_id}"'
  196. )
  197. ).first()
  198. if not data_source_binding:
  199. raise ValueError('Data source binding not found.')
  200. reader = NotionPageReader(integration_token=data_source_binding.access_token)
  201. for page in notion_info['pages']:
  202. if page['type'] == 'page':
  203. page_ids = [page['page_id']]
  204. documents = reader.load_data_as_documents(page_ids=page_ids)
  205. elif page['type'] == 'database':
  206. documents = reader.load_data_as_documents(database_id=page['page_id'])
  207. else:
  208. documents = []
  209. processing_rule = DatasetProcessRule(
  210. mode=tmp_processing_rule["mode"],
  211. rules=json.dumps(tmp_processing_rule["rules"])
  212. )
  213. # get node parser for splitting
  214. node_parser = self._get_node_parser(processing_rule)
  215. # split to nodes
  216. nodes = self._split_to_nodes(
  217. text_docs=documents,
  218. node_parser=node_parser,
  219. processing_rule=processing_rule
  220. )
  221. total_segments += len(nodes)
  222. for node in nodes:
  223. if len(preview_texts) < 5:
  224. preview_texts.append(node.get_text())
  225. tokens += TokenCalculator.get_num_tokens(self.embedding_model_name, node.get_text())
  226. return {
  227. "total_segments": total_segments,
  228. "tokens": tokens,
  229. "total_price": '{:f}'.format(TokenCalculator.get_token_price(self.embedding_model_name, tokens)),
  230. "currency": TokenCalculator.get_currency(self.embedding_model_name),
  231. "preview": preview_texts
  232. }
  233. def _load_data(self, document: Document) -> List[Document]:
  234. # load file
  235. if document.data_source_type not in ["upload_file", "notion_import"]:
  236. return []
  237. data_source_info = document.data_source_info_dict
  238. text_docs = []
  239. if document.data_source_type == 'upload_file':
  240. if not data_source_info or 'upload_file_id' not in data_source_info:
  241. raise ValueError("no upload file found")
  242. file_detail = db.session.query(UploadFile). \
  243. filter(UploadFile.id == data_source_info['upload_file_id']). \
  244. one_or_none()
  245. text_docs = self._load_data_from_file(file_detail)
  246. elif document.data_source_type == 'notion_import':
  247. if not data_source_info or 'notion_page_id' not in data_source_info \
  248. or 'notion_workspace_id' not in data_source_info:
  249. raise ValueError("no notion page found")
  250. workspace_id = data_source_info['notion_workspace_id']
  251. page_id = data_source_info['notion_page_id']
  252. page_type = data_source_info['type']
  253. data_source_binding = DataSourceBinding.query.filter(
  254. db.and_(
  255. DataSourceBinding.tenant_id == document.tenant_id,
  256. DataSourceBinding.provider == 'notion',
  257. DataSourceBinding.disabled == False,
  258. DataSourceBinding.source_info['workspace_id'] == f'"{workspace_id}"'
  259. )
  260. ).first()
  261. if not data_source_binding:
  262. raise ValueError('Data source binding not found.')
  263. if page_type == 'page':
  264. # add page last_edited_time to data_source_info
  265. self._get_notion_page_last_edited_time(page_id, data_source_binding.access_token, document)
  266. text_docs = self._load_page_data_from_notion(page_id, data_source_binding.access_token)
  267. elif page_type == 'database':
  268. # add page last_edited_time to data_source_info
  269. self._get_notion_database_last_edited_time(page_id, data_source_binding.access_token, document)
  270. text_docs = self._load_database_data_from_notion(page_id, data_source_binding.access_token)
  271. # update document status to splitting
  272. self._update_document_index_status(
  273. document_id=document.id,
  274. after_indexing_status="splitting",
  275. extra_update_params={
  276. Document.word_count: sum([len(text_doc.text) for text_doc in text_docs]),
  277. Document.parsing_completed_at: datetime.datetime.utcnow()
  278. }
  279. )
  280. # replace doc id to document model id
  281. for text_doc in text_docs:
  282. # remove invalid symbol
  283. text_doc.text = self.filter_string(text_doc.get_text())
  284. text_doc.doc_id = document.id
  285. return text_docs
  286. def filter_string(self, text):
  287. pattern = re.compile('[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x80-\xFF]')
  288. return pattern.sub('', text)
  289. def _load_data_from_file(self, upload_file: UploadFile) -> List[Document]:
  290. with tempfile.TemporaryDirectory() as temp_dir:
  291. suffix = Path(upload_file.key).suffix
  292. filepath = f"{temp_dir}/{next(tempfile._get_candidate_names())}{suffix}"
  293. self.storage.download(upload_file.key, filepath)
  294. file_extractor = DEFAULT_FILE_EXTRACTOR.copy()
  295. file_extractor[".markdown"] = MarkdownParser()
  296. file_extractor[".md"] = MarkdownParser()
  297. file_extractor[".html"] = HTMLParser()
  298. file_extractor[".htm"] = HTMLParser()
  299. file_extractor[".pdf"] = PDFParser({'upload_file': upload_file})
  300. file_extractor[".xlsx"] = XLSXParser()
  301. loader = SimpleDirectoryReader(input_files=[filepath], file_extractor=file_extractor)
  302. text_docs = loader.load_data()
  303. return text_docs
  304. def _load_page_data_from_notion(self, page_id: str, access_token: str) -> List[Document]:
  305. page_ids = [page_id]
  306. reader = NotionPageReader(integration_token=access_token)
  307. text_docs = reader.load_data_as_documents(page_ids=page_ids)
  308. return text_docs
  309. def _load_database_data_from_notion(self, database_id: str, access_token: str) -> List[Document]:
  310. reader = NotionPageReader(integration_token=access_token)
  311. text_docs = reader.load_data_as_documents(database_id=database_id)
  312. return text_docs
  313. def _get_notion_page_last_edited_time(self, page_id: str, access_token: str, document: Document):
  314. reader = NotionPageReader(integration_token=access_token)
  315. last_edited_time = reader.get_page_last_edited_time(page_id)
  316. data_source_info = document.data_source_info_dict
  317. data_source_info['last_edited_time'] = last_edited_time
  318. update_params = {
  319. Document.data_source_info: json.dumps(data_source_info)
  320. }
  321. Document.query.filter_by(id=document.id).update(update_params)
  322. db.session.commit()
  323. def _get_notion_database_last_edited_time(self, page_id: str, access_token: str, document: Document):
  324. reader = NotionPageReader(integration_token=access_token)
  325. last_edited_time = reader.get_database_last_edited_time(page_id)
  326. data_source_info = document.data_source_info_dict
  327. data_source_info['last_edited_time'] = last_edited_time
  328. update_params = {
  329. Document.data_source_info: json.dumps(data_source_info)
  330. }
  331. Document.query.filter_by(id=document.id).update(update_params)
  332. db.session.commit()
  333. def _get_node_parser(self, processing_rule: DatasetProcessRule) -> NodeParser:
  334. """
  335. Get the NodeParser object according to the processing rule.
  336. """
  337. if processing_rule.mode == "custom":
  338. # The user-defined segmentation rule
  339. rules = json.loads(processing_rule.rules)
  340. segmentation = rules["segmentation"]
  341. if segmentation["max_tokens"] < 50 or segmentation["max_tokens"] > 1000:
  342. raise ValueError("Custom segment length should be between 50 and 1000.")
  343. separator = segmentation["separator"]
  344. if separator:
  345. separator = separator.replace('\\n', '\n')
  346. character_splitter = FixedRecursiveCharacterTextSplitter.from_tiktoken_encoder(
  347. chunk_size=segmentation["max_tokens"],
  348. chunk_overlap=0,
  349. fixed_separator=separator,
  350. separators=["\n\n", "。", ".", " ", ""]
  351. )
  352. else:
  353. # Automatic segmentation
  354. character_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
  355. chunk_size=DatasetProcessRule.AUTOMATIC_RULES['segmentation']['max_tokens'],
  356. chunk_overlap=0,
  357. separators=["\n\n", "。", ".", " ", ""]
  358. )
  359. return SimpleNodeParser(text_splitter=character_splitter, include_extra_info=True)
  360. def _step_split(self, text_docs: List[Document], node_parser: NodeParser,
  361. dataset: Dataset, document: Document, processing_rule: DatasetProcessRule) -> List[Node]:
  362. """
  363. Split the text documents into nodes and save them to the document segment.
  364. """
  365. nodes = self._split_to_nodes(
  366. text_docs=text_docs,
  367. node_parser=node_parser,
  368. processing_rule=processing_rule
  369. )
  370. # save node to document segment
  371. doc_store = DatesetDocumentStore(
  372. dataset=dataset,
  373. user_id=document.created_by,
  374. embedding_model_name=self.embedding_model_name,
  375. document_id=document.id
  376. )
  377. # add document segments
  378. doc_store.add_documents(nodes)
  379. # update document status to indexing
  380. cur_time = datetime.datetime.utcnow()
  381. self._update_document_index_status(
  382. document_id=document.id,
  383. after_indexing_status="indexing",
  384. extra_update_params={
  385. Document.cleaning_completed_at: cur_time,
  386. Document.splitting_completed_at: cur_time,
  387. }
  388. )
  389. # update segment status to indexing
  390. self._update_segments_by_document(
  391. document_id=document.id,
  392. update_params={
  393. DocumentSegment.status: "indexing",
  394. DocumentSegment.indexing_at: datetime.datetime.utcnow()
  395. }
  396. )
  397. return nodes
  398. def _split_to_nodes(self, text_docs: List[Document], node_parser: NodeParser,
  399. processing_rule: DatasetProcessRule) -> List[Node]:
  400. """
  401. Split the text documents into nodes.
  402. """
  403. all_nodes = []
  404. for text_doc in text_docs:
  405. # document clean
  406. document_text = self._document_clean(text_doc.get_text(), processing_rule)
  407. text_doc.text = document_text
  408. # parse document to nodes
  409. nodes = node_parser.get_nodes_from_documents([text_doc])
  410. nodes = [node for node in nodes if node.text is not None and node.text.strip()]
  411. all_nodes.extend(nodes)
  412. return all_nodes
  413. def _document_clean(self, text: str, processing_rule: DatasetProcessRule) -> str:
  414. """
  415. Clean the document text according to the processing rules.
  416. """
  417. if processing_rule.mode == "automatic":
  418. rules = DatasetProcessRule.AUTOMATIC_RULES
  419. else:
  420. rules = json.loads(processing_rule.rules) if processing_rule.rules else {}
  421. if 'pre_processing_rules' in rules:
  422. pre_processing_rules = rules["pre_processing_rules"]
  423. for pre_processing_rule in pre_processing_rules:
  424. if pre_processing_rule["id"] == "remove_extra_spaces" and pre_processing_rule["enabled"] is True:
  425. # Remove extra spaces
  426. pattern = r'\n{3,}'
  427. text = re.sub(pattern, '\n\n', text)
  428. pattern = r'[\t\f\r\x20\u00a0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]{2,}'
  429. text = re.sub(pattern, ' ', text)
  430. elif pre_processing_rule["id"] == "remove_urls_emails" and pre_processing_rule["enabled"] is True:
  431. # Remove email
  432. pattern = r'([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)'
  433. text = re.sub(pattern, '', text)
  434. # Remove URL
  435. pattern = r'https?://[^\s]+'
  436. text = re.sub(pattern, '', text)
  437. return text
  438. def _build_index(self, dataset: Dataset, document: Document, nodes: List[Node]) -> None:
  439. """
  440. Build the index for the document.
  441. """
  442. vector_index = VectorIndex(dataset=dataset)
  443. keyword_table_index = KeywordTableIndex(dataset=dataset)
  444. # chunk nodes by chunk size
  445. indexing_start_at = time.perf_counter()
  446. tokens = 0
  447. chunk_size = 100
  448. for i in range(0, len(nodes), chunk_size):
  449. # check document is paused
  450. self._check_document_paused_status(document.id)
  451. chunk_nodes = nodes[i:i + chunk_size]
  452. tokens += sum(
  453. TokenCalculator.get_num_tokens(self.embedding_model_name, node.get_text()) for node in chunk_nodes
  454. )
  455. # save vector index
  456. if dataset.indexing_technique == "high_quality":
  457. vector_index.add_nodes(chunk_nodes)
  458. # save keyword index
  459. keyword_table_index.add_nodes(chunk_nodes)
  460. node_ids = [node.doc_id for node in chunk_nodes]
  461. db.session.query(DocumentSegment).filter(
  462. DocumentSegment.document_id == document.id,
  463. DocumentSegment.index_node_id.in_(node_ids),
  464. DocumentSegment.status == "indexing"
  465. ).update({
  466. DocumentSegment.status: "completed",
  467. DocumentSegment.completed_at: datetime.datetime.utcnow()
  468. })
  469. db.session.commit()
  470. indexing_end_at = time.perf_counter()
  471. # update document status to completed
  472. self._update_document_index_status(
  473. document_id=document.id,
  474. after_indexing_status="completed",
  475. extra_update_params={
  476. Document.tokens: tokens,
  477. Document.completed_at: datetime.datetime.utcnow(),
  478. Document.indexing_latency: indexing_end_at - indexing_start_at,
  479. }
  480. )
  481. def _check_document_paused_status(self, document_id: str):
  482. indexing_cache_key = 'document_{}_is_paused'.format(document_id)
  483. result = redis_client.get(indexing_cache_key)
  484. if result:
  485. raise DocumentIsPausedException()
  486. def _update_document_index_status(self, document_id: str, after_indexing_status: str,
  487. extra_update_params: Optional[dict] = None) -> None:
  488. """
  489. Update the document indexing status.
  490. """
  491. count = Document.query.filter_by(id=document_id, is_paused=True).count()
  492. if count > 0:
  493. raise DocumentIsPausedException()
  494. update_params = {
  495. Document.indexing_status: after_indexing_status
  496. }
  497. if extra_update_params:
  498. update_params.update(extra_update_params)
  499. Document.query.filter_by(id=document_id).update(update_params)
  500. db.session.commit()
  501. def _update_segments_by_document(self, document_id: str, update_params: dict) -> None:
  502. """
  503. Update the document segment by document id.
  504. """
  505. DocumentSegment.query.filter_by(document_id=document_id).update(update_params)
  506. db.session.commit()
  507. class DocumentIsPausedException(Exception):
  508. pass