annotation.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. from flask import request
  2. from flask_login import current_user
  3. from flask_restful import Resource, marshal, marshal_with, reqparse
  4. from werkzeug.exceptions import Forbidden
  5. from controllers.console import api
  6. from controllers.console.app.error import NoFileUploadedError
  7. from controllers.console.datasets.error import TooManyFilesError
  8. from controllers.console.setup import setup_required
  9. from controllers.console.wraps import account_initialization_required, cloud_edition_billing_resource_check
  10. from extensions.ext_redis import redis_client
  11. from fields.annotation_fields import (
  12. annotation_fields,
  13. annotation_hit_history_fields,
  14. )
  15. from libs.login import login_required
  16. from services.annotation_service import AppAnnotationService
  17. class AnnotationReplyActionApi(Resource):
  18. @setup_required
  19. @login_required
  20. @account_initialization_required
  21. @cloud_edition_billing_resource_check('annotation')
  22. def post(self, app_id, action):
  23. # The role of the current user in the ta table must be admin or owner
  24. if not current_user.is_admin_or_owner:
  25. raise Forbidden()
  26. app_id = str(app_id)
  27. parser = reqparse.RequestParser()
  28. parser.add_argument('score_threshold', required=True, type=float, location='json')
  29. parser.add_argument('embedding_provider_name', required=True, type=str, location='json')
  30. parser.add_argument('embedding_model_name', required=True, type=str, location='json')
  31. args = parser.parse_args()
  32. if action == 'enable':
  33. result = AppAnnotationService.enable_app_annotation(args, app_id)
  34. elif action == 'disable':
  35. result = AppAnnotationService.disable_app_annotation(app_id)
  36. else:
  37. raise ValueError('Unsupported annotation reply action')
  38. return result, 200
  39. class AppAnnotationSettingDetailApi(Resource):
  40. @setup_required
  41. @login_required
  42. @account_initialization_required
  43. def get(self, app_id):
  44. # The role of the current user in the ta table must be admin or owner
  45. if not current_user.is_admin_or_owner:
  46. raise Forbidden()
  47. app_id = str(app_id)
  48. result = AppAnnotationService.get_app_annotation_setting_by_app_id(app_id)
  49. return result, 200
  50. class AppAnnotationSettingUpdateApi(Resource):
  51. @setup_required
  52. @login_required
  53. @account_initialization_required
  54. def post(self, app_id, annotation_setting_id):
  55. # The role of the current user in the ta table must be admin or owner
  56. if not current_user.is_admin_or_owner:
  57. raise Forbidden()
  58. app_id = str(app_id)
  59. annotation_setting_id = str(annotation_setting_id)
  60. parser = reqparse.RequestParser()
  61. parser.add_argument('score_threshold', required=True, type=float, location='json')
  62. args = parser.parse_args()
  63. result = AppAnnotationService.update_app_annotation_setting(app_id, annotation_setting_id, args)
  64. return result, 200
  65. class AnnotationReplyActionStatusApi(Resource):
  66. @setup_required
  67. @login_required
  68. @account_initialization_required
  69. @cloud_edition_billing_resource_check('annotation')
  70. def get(self, app_id, job_id, action):
  71. # The role of the current user in the ta table must be admin or owner
  72. if not current_user.is_admin_or_owner:
  73. raise Forbidden()
  74. job_id = str(job_id)
  75. app_annotation_job_key = '{}_app_annotation_job_{}'.format(action, str(job_id))
  76. cache_result = redis_client.get(app_annotation_job_key)
  77. if cache_result is None:
  78. raise ValueError("The job is not exist.")
  79. job_status = cache_result.decode()
  80. error_msg = ''
  81. if job_status == 'error':
  82. app_annotation_error_key = '{}_app_annotation_error_{}'.format(action, str(job_id))
  83. error_msg = redis_client.get(app_annotation_error_key).decode()
  84. return {
  85. 'job_id': job_id,
  86. 'job_status': job_status,
  87. 'error_msg': error_msg
  88. }, 200
  89. class AnnotationListApi(Resource):
  90. @setup_required
  91. @login_required
  92. @account_initialization_required
  93. def get(self, app_id):
  94. # The role of the current user in the ta table must be admin or owner
  95. if not current_user.is_admin_or_owner:
  96. raise Forbidden()
  97. page = request.args.get('page', default=1, type=int)
  98. limit = request.args.get('limit', default=20, type=int)
  99. keyword = request.args.get('keyword', default=None, type=str)
  100. app_id = str(app_id)
  101. annotation_list, total = AppAnnotationService.get_annotation_list_by_app_id(app_id, page, limit, keyword)
  102. response = {
  103. 'data': marshal(annotation_list, annotation_fields),
  104. 'has_more': len(annotation_list) == limit,
  105. 'limit': limit,
  106. 'total': total,
  107. 'page': page
  108. }
  109. return response, 200
  110. class AnnotationExportApi(Resource):
  111. @setup_required
  112. @login_required
  113. @account_initialization_required
  114. def get(self, app_id):
  115. # The role of the current user in the ta table must be admin or owner
  116. if not current_user.is_admin_or_owner:
  117. raise Forbidden()
  118. app_id = str(app_id)
  119. annotation_list = AppAnnotationService.export_annotation_list_by_app_id(app_id)
  120. response = {
  121. 'data': marshal(annotation_list, annotation_fields)
  122. }
  123. return response, 200
  124. class AnnotationCreateApi(Resource):
  125. @setup_required
  126. @login_required
  127. @account_initialization_required
  128. @cloud_edition_billing_resource_check('annotation')
  129. @marshal_with(annotation_fields)
  130. def post(self, app_id):
  131. # The role of the current user in the ta table must be admin or owner
  132. if not current_user.is_admin_or_owner:
  133. raise Forbidden()
  134. app_id = str(app_id)
  135. parser = reqparse.RequestParser()
  136. parser.add_argument('question', required=True, type=str, location='json')
  137. parser.add_argument('answer', required=True, type=str, location='json')
  138. args = parser.parse_args()
  139. annotation = AppAnnotationService.insert_app_annotation_directly(args, app_id)
  140. return annotation
  141. class AnnotationUpdateDeleteApi(Resource):
  142. @setup_required
  143. @login_required
  144. @account_initialization_required
  145. @cloud_edition_billing_resource_check('annotation')
  146. @marshal_with(annotation_fields)
  147. def post(self, app_id, annotation_id):
  148. # The role of the current user in the ta table must be admin or owner
  149. if not current_user.is_admin_or_owner:
  150. raise Forbidden()
  151. app_id = str(app_id)
  152. annotation_id = str(annotation_id)
  153. parser = reqparse.RequestParser()
  154. parser.add_argument('question', required=True, type=str, location='json')
  155. parser.add_argument('answer', required=True, type=str, location='json')
  156. args = parser.parse_args()
  157. annotation = AppAnnotationService.update_app_annotation_directly(args, app_id, annotation_id)
  158. return annotation
  159. @setup_required
  160. @login_required
  161. @account_initialization_required
  162. def delete(self, app_id, annotation_id):
  163. # The role of the current user in the ta table must be admin or owner
  164. if not current_user.is_admin_or_owner:
  165. raise Forbidden()
  166. app_id = str(app_id)
  167. annotation_id = str(annotation_id)
  168. AppAnnotationService.delete_app_annotation(app_id, annotation_id)
  169. return {'result': 'success'}, 200
  170. class AnnotationBatchImportApi(Resource):
  171. @setup_required
  172. @login_required
  173. @account_initialization_required
  174. @cloud_edition_billing_resource_check('annotation')
  175. def post(self, app_id):
  176. # The role of the current user in the ta table must be admin or owner
  177. if not current_user.is_admin_or_owner:
  178. raise Forbidden()
  179. app_id = str(app_id)
  180. # get file from request
  181. file = request.files['file']
  182. # check file
  183. if 'file' not in request.files:
  184. raise NoFileUploadedError()
  185. if len(request.files) > 1:
  186. raise TooManyFilesError()
  187. # check file type
  188. if not file.filename.endswith('.csv'):
  189. raise ValueError("Invalid file type. Only CSV files are allowed")
  190. return AppAnnotationService.batch_import_app_annotations(app_id, file)
  191. class AnnotationBatchImportStatusApi(Resource):
  192. @setup_required
  193. @login_required
  194. @account_initialization_required
  195. @cloud_edition_billing_resource_check('annotation')
  196. def get(self, app_id, job_id):
  197. # The role of the current user in the ta table must be admin or owner
  198. if not current_user.is_admin_or_owner:
  199. raise Forbidden()
  200. job_id = str(job_id)
  201. indexing_cache_key = 'app_annotation_batch_import_{}'.format(str(job_id))
  202. cache_result = redis_client.get(indexing_cache_key)
  203. if cache_result is None:
  204. raise ValueError("The job is not exist.")
  205. job_status = cache_result.decode()
  206. error_msg = ''
  207. if job_status == 'error':
  208. indexing_error_msg_key = 'app_annotation_batch_import_error_msg_{}'.format(str(job_id))
  209. error_msg = redis_client.get(indexing_error_msg_key).decode()
  210. return {
  211. 'job_id': job_id,
  212. 'job_status': job_status,
  213. 'error_msg': error_msg
  214. }, 200
  215. class AnnotationHitHistoryListApi(Resource):
  216. @setup_required
  217. @login_required
  218. @account_initialization_required
  219. def get(self, app_id, annotation_id):
  220. # The role of the current user in the table must be admin or owner
  221. if not current_user.is_admin_or_owner:
  222. raise Forbidden()
  223. page = request.args.get('page', default=1, type=int)
  224. limit = request.args.get('limit', default=20, type=int)
  225. app_id = str(app_id)
  226. annotation_id = str(annotation_id)
  227. annotation_hit_history_list, total = AppAnnotationService.get_annotation_hit_histories(app_id, annotation_id,
  228. page, limit)
  229. response = {
  230. 'data': marshal(annotation_hit_history_list, annotation_hit_history_fields),
  231. 'has_more': len(annotation_hit_history_list) == limit,
  232. 'limit': limit,
  233. 'total': total,
  234. 'page': page
  235. }
  236. return response
  237. api.add_resource(AnnotationReplyActionApi, '/apps/<uuid:app_id>/annotation-reply/<string:action>')
  238. api.add_resource(AnnotationReplyActionStatusApi,
  239. '/apps/<uuid:app_id>/annotation-reply/<string:action>/status/<uuid:job_id>')
  240. api.add_resource(AnnotationListApi, '/apps/<uuid:app_id>/annotations')
  241. api.add_resource(AnnotationExportApi, '/apps/<uuid:app_id>/annotations/export')
  242. api.add_resource(AnnotationUpdateDeleteApi, '/apps/<uuid:app_id>/annotations/<uuid:annotation_id>')
  243. api.add_resource(AnnotationBatchImportApi, '/apps/<uuid:app_id>/annotations/batch-import')
  244. api.add_resource(AnnotationBatchImportStatusApi, '/apps/<uuid:app_id>/annotations/batch-import-status/<uuid:job_id>')
  245. api.add_resource(AnnotationHitHistoryListApi, '/apps/<uuid:app_id>/annotations/<uuid:annotation_id>/hit-histories')
  246. api.add_resource(AppAnnotationSettingDetailApi, '/apps/<uuid:app_id>/annotation-setting')
  247. api.add_resource(AppAnnotationSettingUpdateApi, '/apps/<uuid:app_id>/annotation-settings/<uuid:annotation_setting_id>')