disable_annotation_reply_task.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import logging
  2. import time
  3. import click
  4. from celery import shared_task
  5. from werkzeug.exceptions import NotFound
  6. from core.rag.datasource.vdb.vector_factory import Vector
  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. try:
  41. vector = Vector(dataset, attributes=['doc_id', 'annotation_id', 'app_id'])
  42. vector.delete_by_metadata_field('app_id', app_id)
  43. except Exception:
  44. logging.exception("Delete annotation index failed when annotation deleted.")
  45. redis_client.setex(disable_app_annotation_job_key, 600, 'completed')
  46. # delete annotation setting
  47. db.session.delete(app_annotation_setting)
  48. db.session.commit()
  49. end_at = time.perf_counter()
  50. logging.info(
  51. click.style('App annotations index deleted : {} latency: {}'.format(app_id, end_at - start_at),
  52. fg='green'))
  53. except Exception as e:
  54. logging.exception("Annotation batch deleted index failed:{}".format(str(e)))
  55. redis_client.setex(disable_app_annotation_job_key, 600, 'error')
  56. disable_app_annotation_error_key = 'disable_app_annotation_error_{}'.format(str(job_id))
  57. redis_client.setex(disable_app_annotation_error_key, 600, str(e))
  58. finally:
  59. redis_client.delete(disable_app_annotation_key)