result_saver.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 traceback
  17. from .file_interface import write_json_file
  18. def try_except_decorator(func):
  19. """try-except"""
  20. def wrap(self, *args, **kwargs):
  21. try:
  22. result = func(self, *args, **kwargs)
  23. if result:
  24. save_result(True, self._mode, self._output, result_dict=result)
  25. except Exception:
  26. exc_type, exc_value, exc_tb = sys.exc_info()
  27. save_result(
  28. False,
  29. self._mode,
  30. self._output,
  31. err_type=str(exc_type),
  32. err_msg=str(exc_value),
  33. )
  34. traceback.print_exception(exc_type, exc_value, exc_tb)
  35. sys.exit(1)
  36. return wrap
  37. def save_result(run_pass, mode, output, result_dict=None, err_type=None, err_msg=None):
  38. """format, build and save result"""
  39. json_data = {"done_flag": run_pass}
  40. if not run_pass:
  41. assert result_dict is None and err_type is not None and err_msg is not None
  42. json_data.update({"err_type": err_type, "err_msg": err_msg})
  43. else:
  44. assert result_dict is not None and err_type is None and err_msg is None
  45. json_data.update(result_dict)
  46. if not os.path.exists(output):
  47. os.makedirs(output, exist_ok=True)
  48. write_json_file(json_data, os.path.join(output, f"{mode}_result.json"), indent=2)