errors.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import sys
  2. import textwrap
  3. import traceback
  4. exception_records = []
  5. def record_exception():
  6. _, e, tb = sys.exc_info()
  7. if e is None:
  8. return
  9. if exception_records and exception_records[-1] == e:
  10. return
  11. exception_records.append((e, tb))
  12. if len(exception_records) > 5:
  13. exception_records.pop(0)
  14. def report(message: str, *, exc_info: bool = False) -> None:
  15. """
  16. Print an error message to stderr, with optional traceback.
  17. """
  18. record_exception()
  19. for line in message.splitlines():
  20. print("***", line, file=sys.stderr)
  21. if exc_info:
  22. print(textwrap.indent(traceback.format_exc(), " "), file=sys.stderr)
  23. print("---", file=sys.stderr)
  24. def print_error_explanation(message):
  25. record_exception()
  26. lines = message.strip().split("\n")
  27. max_len = max([len(x) for x in lines])
  28. print('=' * max_len, file=sys.stderr)
  29. for line in lines:
  30. print(line, file=sys.stderr)
  31. print('=' * max_len, file=sys.stderr)
  32. def display(e: Exception, task, *, full_traceback=False):
  33. record_exception()
  34. print(f"{task or 'error'}: {type(e).__name__}", file=sys.stderr)
  35. te = traceback.TracebackException.from_exception(e)
  36. if full_traceback:
  37. # include frames leading up to the try-catch block
  38. te.stack = traceback.StackSummary(traceback.extract_stack()[:-2] + te.stack)
  39. print(*te.format(), sep="", file=sys.stderr)
  40. message = str(e)
  41. if "copying a param with shape torch.Size([640, 1024]) from checkpoint, the shape in current model is torch.Size([640, 768])" in message:
  42. print_error_explanation("""
  43. The most likely cause of this is you are trying to load Stable Diffusion 2.0 model without specifying its config file.
  44. See https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#stable-diffusion-20 for how to solve this.
  45. """)
  46. already_displayed = {}
  47. def display_once(e: Exception, task):
  48. record_exception()
  49. if task in already_displayed:
  50. return
  51. display(e, task)
  52. already_displayed[task] = 1
  53. def run(code, task):
  54. try:
  55. code()
  56. except Exception as e:
  57. display(task, e)