result_saver.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import sys
  16. import json
  17. import traceback
  18. from .flags import DEBUG
  19. from .file_interface import custom_open, write_json_file
  20. def try_except_decorator(func):
  21. """ try-except """
  22. def wrap(self, *args, **kwargs):
  23. try:
  24. result = func(self, *args, **kwargs)
  25. if result:
  26. save_result(
  27. True, self.mode, self.output_dir, result_dict=result)
  28. except Exception as e:
  29. exc_type, exc_value, exc_tb = sys.exc_info()
  30. save_result(
  31. False,
  32. self.mode,
  33. self.output_dir,
  34. err_type=str(exc_type),
  35. err_msg=str(exc_value))
  36. traceback.print_exception(exc_type, exc_value, exc_tb)
  37. return wrap
  38. def save_result(run_pass,
  39. mode,
  40. output_dir,
  41. result_dict=None,
  42. err_type=None,
  43. err_msg=None):
  44. """ format, build and save result """
  45. json_data = {
  46. # "model_name": self.args.model_name,
  47. "done_flag": run_pass
  48. }
  49. if not run_pass:
  50. assert result_dict is None and err_type is not None and err_msg is not None
  51. json_data.update({"err_type": err_type, "err_msg": err_msg})
  52. else:
  53. assert result_dict is not None and err_type is None and err_msg is None
  54. json_data.update(result_dict)
  55. if not os.path.exists(output_dir):
  56. os.makedirs(output_dir, exist_ok=True)
  57. write_json_file(
  58. json_data, os.path.join(output_dir, f"{mode}_result.json"), indent=2)