2024-02-06 03:56:32 +00:00
|
|
|
import warnings
|
2024-06-06 14:28:00 +00:00
|
|
|
from contextlib import ContextDecorator
|
2024-02-06 03:56:32 +00:00
|
|
|
|
2024-06-06 14:28:00 +00:00
|
|
|
from diffusers.utils import logging as diffusers_logging
|
2024-02-06 03:56:32 +00:00
|
|
|
from transformers import logging as transformers_logging
|
|
|
|
|
|
|
|
|
2024-06-06 14:28:00 +00:00
|
|
|
# Inherit from ContextDecorator to allow using SilenceWarnings as both a context manager and a decorator.
|
|
|
|
class SilenceWarnings(ContextDecorator):
|
|
|
|
"""A context manager that disables warnings from transformers & diffusers modules while active.
|
2024-02-06 03:56:32 +00:00
|
|
|
|
2024-06-06 14:28:00 +00:00
|
|
|
As context manager:
|
|
|
|
```
|
2024-02-06 03:56:32 +00:00
|
|
|
with SilenceWarnings():
|
|
|
|
# do something
|
2024-06-06 14:28:00 +00:00
|
|
|
```
|
2024-02-06 03:56:32 +00:00
|
|
|
|
2024-06-06 14:28:00 +00:00
|
|
|
As decorator:
|
|
|
|
```
|
|
|
|
@SilenceWarnings()
|
|
|
|
def some_function():
|
|
|
|
# do something
|
|
|
|
```
|
|
|
|
"""
|
2024-02-06 03:56:32 +00:00
|
|
|
|
|
|
|
def __enter__(self) -> None:
|
2024-06-06 14:28:00 +00:00
|
|
|
self._transformers_verbosity = transformers_logging.get_verbosity()
|
|
|
|
self._diffusers_verbosity = diffusers_logging.get_verbosity()
|
2024-02-06 03:56:32 +00:00
|
|
|
transformers_logging.set_verbosity_error()
|
|
|
|
diffusers_logging.set_verbosity_error()
|
|
|
|
warnings.simplefilter("ignore")
|
|
|
|
|
2024-06-06 14:28:00 +00:00
|
|
|
def __exit__(self, *args) -> None:
|
|
|
|
transformers_logging.set_verbosity(self._transformers_verbosity)
|
|
|
|
diffusers_logging.set_verbosity(self._diffusers_verbosity)
|
2024-02-06 03:56:32 +00:00
|
|
|
warnings.simplefilter("default")
|