document_indexing_sync_task.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import datetime
  2. import logging
  3. import time
  4. import click
  5. from celery import shared_task
  6. from werkzeug.exceptions import NotFound
  7. from core.indexing_runner import DocumentIsPausedException, IndexingRunner
  8. from core.rag.extractor.notion_extractor import NotionExtractor
  9. from core.rag.index_processor.index_processor_factory import IndexProcessorFactory
  10. from extensions.ext_database import db
  11. from models.dataset import Dataset, Document, DocumentSegment
  12. from models.source import DataSourceBinding
  13. @shared_task(queue='dataset')
  14. def document_indexing_sync_task(dataset_id: str, document_id: str):
  15. """
  16. Async update document
  17. :param dataset_id:
  18. :param document_id:
  19. Usage: document_indexing_sync_task.delay(dataset_id, document_id)
  20. """
  21. logging.info(click.style('Start sync document: {}'.format(document_id), fg='green'))
  22. start_at = time.perf_counter()
  23. document = db.session.query(Document).filter(
  24. Document.id == document_id,
  25. Document.dataset_id == dataset_id
  26. ).first()
  27. if not document:
  28. raise NotFound('Document not found')
  29. data_source_info = document.data_source_info_dict
  30. if document.data_source_type == 'notion_import':
  31. if not data_source_info or 'notion_page_id' not in data_source_info \
  32. or 'notion_workspace_id' not in data_source_info:
  33. raise ValueError("no notion page found")
  34. workspace_id = data_source_info['notion_workspace_id']
  35. page_id = data_source_info['notion_page_id']
  36. page_type = data_source_info['type']
  37. page_edited_time = data_source_info['last_edited_time']
  38. data_source_binding = DataSourceBinding.query.filter(
  39. db.and_(
  40. DataSourceBinding.tenant_id == document.tenant_id,
  41. DataSourceBinding.provider == 'notion',
  42. DataSourceBinding.disabled == False,
  43. DataSourceBinding.source_info['workspace_id'] == f'"{workspace_id}"'
  44. )
  45. ).first()
  46. if not data_source_binding:
  47. raise ValueError('Data source binding not found.')
  48. loader = NotionExtractor(
  49. notion_workspace_id=workspace_id,
  50. notion_obj_id=page_id,
  51. notion_page_type=page_type,
  52. notion_access_token=data_source_binding.access_token,
  53. tenant_id=document.tenant_id
  54. )
  55. last_edited_time = loader.get_notion_last_edited_time()
  56. # check the page is updated
  57. if last_edited_time != page_edited_time:
  58. document.indexing_status = 'parsing'
  59. document.processing_started_at = datetime.datetime.utcnow()
  60. db.session.commit()
  61. # delete all document segment and index
  62. try:
  63. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  64. if not dataset:
  65. raise Exception('Dataset not found')
  66. index_type = document.doc_form
  67. index_processor = IndexProcessorFactory(index_type).init_index_processor()
  68. segments = db.session.query(DocumentSegment).filter(DocumentSegment.document_id == document_id).all()
  69. index_node_ids = [segment.index_node_id for segment in segments]
  70. # delete from vector index
  71. index_processor.clean(dataset, index_node_ids)
  72. for segment in segments:
  73. db.session.delete(segment)
  74. end_at = time.perf_counter()
  75. logging.info(
  76. click.style('Cleaned document when document update data source or process rule: {} latency: {}'.format(document_id, end_at - start_at), fg='green'))
  77. except Exception:
  78. logging.exception("Cleaned document when document update data source or process rule failed")
  79. try:
  80. indexing_runner = IndexingRunner()
  81. indexing_runner.run([document])
  82. end_at = time.perf_counter()
  83. logging.info(click.style('update document: {} latency: {}'.format(document.id, end_at - start_at), fg='green'))
  84. except DocumentIsPausedException as ex:
  85. logging.info(click.style(str(ex), fg='yellow'))
  86. except Exception:
  87. pass