disable_annotation_reply_task.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import logging
  2. import time
  3. import click
  4. from celery import shared_task
  5. from werkzeug.exceptions import NotFound
  6. from core.index.index import IndexBuilder
  7. from extensions.ext_database import db
  8. from extensions.ext_redis import redis_client
  9. from models.dataset import Dataset
  10. from models.model import App, AppAnnotationSetting
  11. @shared_task(queue='dataset')
  12. def disable_annotation_reply_task(job_id: str, app_id: str, tenant_id: str):
  13. """
  14. Async enable annotation reply task
  15. """
  16. logging.info(click.style('Start delete app annotations index: {}'.format(app_id), fg='green'))
  17. start_at = time.perf_counter()
  18. # get app info
  19. app = db.session.query(App).filter(
  20. App.id == app_id,
  21. App.tenant_id == tenant_id,
  22. App.status == 'normal'
  23. ).first()
  24. if not app:
  25. raise NotFound("App not found")
  26. app_annotation_setting = db.session.query(AppAnnotationSetting).filter(
  27. AppAnnotationSetting.app_id == app_id
  28. ).first()
  29. if not app_annotation_setting:
  30. raise NotFound("App annotation setting not found")
  31. disable_app_annotation_key = 'disable_app_annotation_{}'.format(str(app_id))
  32. disable_app_annotation_job_key = 'disable_app_annotation_job_{}'.format(str(job_id))
  33. try:
  34. dataset = Dataset(
  35. id=app_id,
  36. tenant_id=tenant_id,
  37. indexing_technique='high_quality',
  38. collection_binding_id=app_annotation_setting.collection_binding_id
  39. )
  40. vector_index = IndexBuilder.get_default_high_quality_index(dataset)
  41. if vector_index:
  42. try:
  43. vector_index.delete_by_metadata_field('app_id', app_id)
  44. except Exception:
  45. logging.exception("Delete doc index failed when dataset deleted.")
  46. redis_client.setex(disable_app_annotation_job_key, 600, 'completed')
  47. # delete annotation setting
  48. db.session.delete(app_annotation_setting)
  49. db.session.commit()
  50. end_at = time.perf_counter()
  51. logging.info(
  52. click.style('App annotations index deleted : {} latency: {}'.format(app_id, end_at - start_at),
  53. fg='green'))
  54. except Exception as e:
  55. logging.exception("Annotation batch deleted index failed:{}".format(str(e)))
  56. redis_client.setex(disable_app_annotation_job_key, 600, 'error')
  57. disable_app_annotation_error_key = 'disable_app_annotation_error_{}'.format(str(job_id))
  58. redis_client.setex(disable_app_annotation_error_key, 600, str(e))
  59. finally:
  60. redis_client.delete(disable_app_annotation_key)