document_indexing_sync_task.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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.data_loader.loader.notion import NotionLoader
  8. from core.index.index import IndexBuilder
  9. from core.indexing_runner import IndexingRunner, DocumentIsPausedException
  10. from extensions.ext_database import db
  11. from models.dataset import Document, Dataset, 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 = NotionLoader(
  49. notion_access_token=data_source_binding.access_token,
  50. notion_workspace_id=workspace_id,
  51. notion_obj_id=page_id,
  52. notion_page_type=page_type
  53. )
  54. last_edited_time = loader.get_notion_last_edited_time()
  55. # check the page is updated
  56. if last_edited_time != page_edited_time:
  57. document.indexing_status = 'parsing'
  58. document.processing_started_at = datetime.datetime.utcnow()
  59. db.session.commit()
  60. # delete all document segment and index
  61. try:
  62. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  63. if not dataset:
  64. raise Exception('Dataset not found')
  65. vector_index = IndexBuilder.get_index(dataset, 'high_quality')
  66. kw_index = IndexBuilder.get_index(dataset, 'economy')
  67. segments = db.session.query(DocumentSegment).filter(DocumentSegment.document_id == document_id).all()
  68. index_node_ids = [segment.index_node_id for segment in segments]
  69. # delete from vector index
  70. if vector_index:
  71. vector_index.delete_by_document_id(document_id)
  72. # delete from keyword index
  73. if index_node_ids:
  74. kw_index.delete_by_ids(index_node_ids)
  75. for segment in segments:
  76. db.session.delete(segment)
  77. end_at = time.perf_counter()
  78. logging.info(
  79. click.style('Cleaned document when document update data source or process rule: {} latency: {}'.format(document_id, end_at - start_at), fg='green'))
  80. except Exception:
  81. logging.exception("Cleaned document when document update data source or process rule failed")
  82. try:
  83. indexing_runner = IndexingRunner()
  84. indexing_runner.run([document])
  85. end_at = time.perf_counter()
  86. logging.info(click.style('update document: {} latency: {}'.format(document.id, end_at - start_at), fg='green'))
  87. except DocumentIsPausedException as ex:
  88. logging.info(click.style(str(ex), fg='yellow'))
  89. except Exception:
  90. pass