result_saver.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # !/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. ################################################################################
  4. #
  5. # Copyright (c) 2024 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ################################################################################
  8. """
  9. Author: PaddlePaddle Authors
  10. """
  11. import os
  12. import sys
  13. import json
  14. import traceback
  15. from .flags import DEBUG
  16. from .file_interface import custom_open
  17. def try_except_decorator(func):
  18. """ try-except """
  19. def wrap(self, *args, **kwargs):
  20. try:
  21. result = func(self, *args, **kwargs)
  22. if result:
  23. save_result(
  24. True, self.mode, self.output_dir, result_dict=result)
  25. except Exception as e:
  26. exc_type, exc_value, exc_tb = sys.exc_info()
  27. save_result(
  28. False,
  29. self.mode,
  30. self.output_dir,
  31. err_type=str(exc_type),
  32. err_msg=str(exc_value))
  33. traceback.print_exception(exc_type, exc_value, exc_tb)
  34. return wrap
  35. def save_result(run_pass,
  36. mode,
  37. output_dir,
  38. result_dict=None,
  39. err_type=None,
  40. err_msg=None):
  41. """ format, build and save result """
  42. json_data = {
  43. # "model_name": self.args.model_name,
  44. "done_flag": run_pass
  45. }
  46. if not run_pass:
  47. assert result_dict is None and err_type is not None and err_msg is not None
  48. json_data.update({"err_type": err_type, "err_msg": err_msg})
  49. else:
  50. assert result_dict is not None and err_type is None and err_msg is None
  51. json_data.update(result_dict)
  52. if not os.path.exists(output_dir):
  53. os.makedirs(output_dir, exist_ok=True)
  54. with custom_open(os.path.join(output_dir, f"{mode}_result.json"), "w") as f:
  55. json.dump(json_data, f, indent=2)