result_saver.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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(True, self._mode, self._output, result_dict=result)
  27. except Exception as e:
  28. exc_type, exc_value, exc_tb = sys.exc_info()
  29. save_result(
  30. False,
  31. self._mode,
  32. self._output,
  33. err_type=str(exc_type),
  34. err_msg=str(exc_value),
  35. )
  36. traceback.print_exception(exc_type, exc_value, exc_tb)
  37. sys.exit(1)
  38. return wrap
  39. def save_result(run_pass, mode, output, result_dict=None, err_type=None, err_msg=None):
  40. """format, build and save result"""
  41. json_data = {"done_flag": run_pass}
  42. if not run_pass:
  43. assert result_dict is None and err_type is not None and err_msg is not None
  44. json_data.update({"err_type": err_type, "err_msg": err_msg})
  45. else:
  46. assert result_dict is not None and err_type is None and err_msg is None
  47. json_data.update(result_dict)
  48. if not os.path.exists(output):
  49. os.makedirs(output, exist_ok=True)
  50. write_json_file(json_data, os.path.join(output, f"{mode}_result.json"), indent=2)