errors.py 2.3 KB

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