We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
NameError: name 'K' is not defined
## 🐛 Bug

<!-- A clear and concise description of what the bug is. -->
````sh
Uncaught exception
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    datamodule = VideoClassificationData.from_folders(
  File "/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/core/data/data_module.py", line 540, in from_folders
    return cls.from_data_source(
  File "/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/core/data/data_module.py", line 448, in from_data_source
    preprocess = preprocess or cls.preprocess_cls(
  File "/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/video/classification/data.py", line 241, in __init__
    super().__init__(
  File "/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/core/data/process.py", line 196, in __init__
    train_transform = train_transform or self._resolve_transforms(RunningStage.TRAINING)
  File "/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/core/data/process.py", line 247, in _resolve_transforms
    transforms: Optional[Dict[str, Callable]] = resolved_function()
  File "/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/video/classification/data.py", line 307, in default_transforms
    transform=K.VideoSequential(
NameError: name 'K' is not defined
````


### To Reproduce

Steps to reproduce the behavior:

````python
import os
from torch.utils.data.sampler import RandomSampler
import flash
from flash.core.data.utils import download_data
from flash.video import VideoClassificationData, VideoClassifier

# 1. Download a video clip dataset. Find more datasets at https://pytorchvideo.readthedocs.io/en/latest/data.html
download_data("https://pl-flash-data.s3.amazonaws.com/kinetics.zip")

# 2. Load the Data
datamodule = VideoClassificationData.from_folders(
    train_folder=os.path.join(flash.PROJECT_ROOT, "data/kinetics/train"),
    val_folder=os.path.join(flash.PROJECT_ROOT, "data/kinetics/val"),
    predict_folder=os.path.join(flash.PROJECT_ROOT, "data/kinetics/predict"),
    batch_size=8,
    clip_sampler="uniform",
    clip_duration=1,
    video_sampler=RandomSampler,
    decode_audio=False,
    num_workers=8,
)

# 3. Build the model
model = VideoClassifier(backbone="x3d_xs", num_classes=datamodule.num_classes, pretrained=False)

# 4. Create the trainer
trainer = flash.Trainer(max_epochs=3)

# 5. Finetune the model
trainer.finetune(model, datamodule=datamodule)

# 6. Save it!
trainer.save_checkpoint("video_classification.pt")
````

<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->

### Environment

 - PyTorch Version (e.g., 1.0): 1.9.0
 - OS (e.g., Linux):  Linux (Ubuntu 18.04)
 - How you installed PyTorch: pip
 - Python version: 3.8
 - CUDA/cuDNN version: 11.3
 - GPU models and configuration: GTX 1650 

### Additional Note

<!-- Add any other context about the problem here. -->
Please update the package, `lightning-flash==0.4.0` is not compatible with `pytorchvideo==0.1.2`

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `flash/core/utilities/imports.py`
Content:
```
1 # Copyright The PyTorch Lightning team.
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 functools
15 import importlib
16 import operator
17 import types
18 from importlib.util import find_spec
19 from typing import Callable, List, Union
20 from warnings import warn
21 
22 from pkg_resources import DistributionNotFound
23 
24 try:
25     from packaging.version import Version
26 except (ModuleNotFoundError, DistributionNotFound):
27     Version = None
28 
29 
30 def _module_available(module_path: str) -> bool:
31     """Check if a path is available in your environment.
32 
33     >>> _module_available('os')
34     True
35     >>> _module_available('bla.bla')
36     False
37     """
38     try:
39         return find_spec(module_path) is not None
40     except AttributeError:
41         # Python 3.6
42         return False
43     except ModuleNotFoundError:
44         # Python 3.7+
45         return False
46     except ValueError:
47         # Sometimes __spec__ can be None and gives a ValueError
48         return True
49 
50 
51 def _compare_version(package: str, op, version) -> bool:
52     """Compare package version with some requirements.
53 
54     >>> _compare_version("torch", operator.ge, "0.1")
55     True
56     """
57     try:
58         pkg = importlib.import_module(package)
59     except (ModuleNotFoundError, DistributionNotFound, ValueError):
60         return False
61     try:
62         pkg_version = Version(pkg.__version__)
63     except TypeError:
64         # this is mock by sphinx, so it shall return True to generate all summaries
65         return True
66     return op(pkg_version, Version(version))
67 
68 
69 _TORCH_AVAILABLE = _module_available("torch")
70 _BOLTS_AVAILABLE = _module_available("pl_bolts") and _compare_version("torch", operator.lt, "1.9.0")
71 _PANDAS_AVAILABLE = _module_available("pandas")
72 _SKLEARN_AVAILABLE = _module_available("sklearn")
73 _TABNET_AVAILABLE = _module_available("pytorch_tabnet")
74 _KORNIA_AVAILABLE = _module_available("kornia")
75 _COCO_AVAILABLE = _module_available("pycocotools")
76 _TIMM_AVAILABLE = _module_available("timm")
77 _TORCHVISION_AVAILABLE = _module_available("torchvision")
78 _PYTORCHVIDEO_AVAILABLE = _module_available("pytorchvideo")
79 _MATPLOTLIB_AVAILABLE = _module_available("matplotlib")
80 _TRANSFORMERS_AVAILABLE = _module_available("transformers")
81 _PYSTICHE_AVAILABLE = _module_available("pystiche")
82 _FIFTYONE_AVAILABLE = _module_available("fiftyone")
83 _FASTAPI_AVAILABLE = _module_available("fastapi")
84 _PYDANTIC_AVAILABLE = _module_available("pydantic")
85 _GRAPHVIZ_AVAILABLE = _module_available("graphviz")
86 _CYTOOLZ_AVAILABLE = _module_available("cytoolz")
87 _UVICORN_AVAILABLE = _module_available("uvicorn")
88 _PIL_AVAILABLE = _module_available("PIL")
89 _OPEN3D_AVAILABLE = _module_available("open3d")
90 _SEGMENTATION_MODELS_AVAILABLE = _module_available("segmentation_models_pytorch")
91 _SOUNDFILE_AVAILABLE = _module_available("soundfile")
92 _TORCH_SCATTER_AVAILABLE = _module_available("torch_scatter")
93 _TORCH_SPARSE_AVAILABLE = _module_available("torch_sparse")
94 _TORCH_GEOMETRIC_AVAILABLE = _module_available("torch_geometric")
95 _TORCHAUDIO_AVAILABLE = _module_available("torchaudio")
96 _ROUGE_SCORE_AVAILABLE = _module_available("rouge_score")
97 _SENTENCEPIECE_AVAILABLE = _module_available("sentencepiece")
98 _DATASETS_AVAILABLE = _module_available("datasets")
99 _ICEVISION_AVAILABLE = _module_available("icevision")
100 _ICEDATA_AVAILABLE = _module_available("icedata")
101 _TORCH_ORT_AVAILABLE = _module_available("torch_ort")
102 _VISSL_AVAILABLE = _module_available("vissl") and _module_available("classy_vision")
103 
104 if _PIL_AVAILABLE:
105     from PIL import Image
106 else:
107 
108     class MetaImage(type):
109         def __init__(cls, name, bases, dct):
110             super().__init__(name, bases, dct)
111 
112             cls._Image = None
113 
114         @property
115         def Image(cls):
116             warn("Mock object called due to missing PIL library. Please use \"pip install 'lightning-flash[image]'\".")
117             return cls._Image
118 
119     class Image(metaclass=MetaImage):
120         pass
121 
122 
123 if Version:
124     _TORCHVISION_GREATER_EQUAL_0_9 = _compare_version("torchvision", operator.ge, "0.9.0")
125     _PL_GREATER_EQUAL_1_4_3 = _compare_version("pytorch_lightning", operator.ge, "1.4.3")
126 
127 _TEXT_AVAILABLE = all(
128     [
129         _TRANSFORMERS_AVAILABLE,
130         _ROUGE_SCORE_AVAILABLE,
131         _SENTENCEPIECE_AVAILABLE,
132         _DATASETS_AVAILABLE,
133     ]
134 )
135 _TABULAR_AVAILABLE = _TABNET_AVAILABLE and _PANDAS_AVAILABLE
136 _VIDEO_AVAILABLE = _PYTORCHVIDEO_AVAILABLE
137 _IMAGE_AVAILABLE = all(
138     [
139         _TORCHVISION_AVAILABLE,
140         _TIMM_AVAILABLE,
141         _PIL_AVAILABLE,
142         _KORNIA_AVAILABLE,
143         _PYSTICHE_AVAILABLE,
144         _SEGMENTATION_MODELS_AVAILABLE,
145         _ICEVISION_AVAILABLE,
146         _ICEDATA_AVAILABLE,
147     ]
148 )
149 _SERVE_AVAILABLE = _FASTAPI_AVAILABLE and _PYDANTIC_AVAILABLE and _CYTOOLZ_AVAILABLE and _UVICORN_AVAILABLE
150 _POINTCLOUD_AVAILABLE = _OPEN3D_AVAILABLE and _TORCHVISION_AVAILABLE
151 _AUDIO_AVAILABLE = all([_TORCHAUDIO_AVAILABLE, _SOUNDFILE_AVAILABLE, _TRANSFORMERS_AVAILABLE])
152 _GRAPH_AVAILABLE = _TORCH_SCATTER_AVAILABLE and _TORCH_SPARSE_AVAILABLE and _TORCH_GEOMETRIC_AVAILABLE
153 
154 _EXTRAS_AVAILABLE = {
155     "image": _IMAGE_AVAILABLE,
156     "tabular": _TABULAR_AVAILABLE,
157     "text": _TEXT_AVAILABLE,
158     "video": _VIDEO_AVAILABLE,
159     "pointcloud": _POINTCLOUD_AVAILABLE,
160     "serve": _SERVE_AVAILABLE,
161     "audio": _AUDIO_AVAILABLE,
162     "graph": _GRAPH_AVAILABLE,
163 }
164 
165 
166 def _requires(
167     module_paths: Union[str, List],
168     module_available: Callable[[str], bool],
169     formatter: Callable[[List[str]], str],
170 ):
171 
172     if not isinstance(module_paths, list):
173         module_paths = [module_paths]
174 
175     def decorator(func):
176         if not all(module_available(module_path) for module_path in module_paths):
177 
178             @functools.wraps(func)
179             def wrapper(*args, **kwargs):
180                 raise ModuleNotFoundError(
181                     f"Required dependencies not available. Please run: pip install {formatter(module_paths)}"
182                 )
183 
184             return wrapper
185         else:
186             return func
187 
188     return decorator
189 
190 
191 def requires(module_paths: Union[str, List]):
192     return _requires(module_paths, _module_available, lambda module_paths: " ".join(module_paths))
193 
194 
195 def requires_extras(extras: Union[str, List]):
196     return _requires(
197         extras, lambda extras: _EXTRAS_AVAILABLE[extras], lambda extras: f"'lightning-flash[{','.join(extras)}]'"
198     )
199 
200 
201 def example_requires(extras: Union[str, List[str]]):
202     return requires_extras(extras)(lambda: None)()
203 
204 
205 def lazy_import(module_name, callback=None):
206     """Returns a proxy module object that will lazily import the given module the first time it is used.
207 
208     Example usage::
209 
210         # Lazy version of `import tensorflow as tf`
211         tf = lazy_import("tensorflow")
212 
213         # Other commands
214 
215         # Now the module is loaded
216         tf.__version__
217 
218     Args:
219         module_name: the fully-qualified module name to import
220         callback (None): a callback function to call before importing the
221             module
222 
223     Returns:
224         a proxy module object that will be lazily imported when first used
225     """
226     return LazyModule(module_name, callback=callback)
227 
228 
229 class LazyModule(types.ModuleType):
230     """Proxy module that lazily imports the underlying module the first time it is actually used.
231 
232     Args:
233         module_name: the fully-qualified module name to import
234         callback (None): a callback function to call before importing the
235             module
236     """
237 
238     def __init__(self, module_name, callback=None):
239         super().__init__(module_name)
240         self._module = None
241         self._callback = callback
242 
243     def __getattr__(self, item):
244         if self._module is None:
245             self._import_module()
246 
247         return getattr(self._module, item)
248 
249     def __dir__(self):
250         if self._module is None:
251             self._import_module()
252 
253         return dir(self._module)
254 
255     def _import_module(self):
256         # Execute callback, if any
257         if self._callback is not None:
258             self._callback()
259 
260         # Actually import the module
261         module = importlib.import_module(self.__name__)
262         self._module = module
263 
264         # Update this object's dict so that attribute references are efficient
265         # (__getattr__ is only called on lookups that fail)
266         self.__dict__.update(module.__dict__)
267
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/flash/core/utilities/imports.py b/flash/core/utilities/imports.py
--- a/flash/core/utilities/imports.py
+++ b/flash/core/utilities/imports.py
@@ -133,7 +133,7 @@
     ]
 )
 _TABULAR_AVAILABLE = _TABNET_AVAILABLE and _PANDAS_AVAILABLE
-_VIDEO_AVAILABLE = _PYTORCHVIDEO_AVAILABLE
+_VIDEO_AVAILABLE = _TORCHVISION_AVAILABLE and _PIL_AVAILABLE and _PYTORCHVIDEO_AVAILABLE and _KORNIA_AVAILABLE
 _IMAGE_AVAILABLE = all(
     [
         _TORCHVISION_AVAILABLE,

{"golden_diff": "diff --git a/flash/core/utilities/imports.py b/flash/core/utilities/imports.py\n--- a/flash/core/utilities/imports.py\n+++ b/flash/core/utilities/imports.py\n@@ -133,7 +133,7 @@\n     ]\n )\n _TABULAR_AVAILABLE = _TABNET_AVAILABLE and _PANDAS_AVAILABLE\n-_VIDEO_AVAILABLE = _PYTORCHVIDEO_AVAILABLE\n+_VIDEO_AVAILABLE = _TORCHVISION_AVAILABLE and _PIL_AVAILABLE and _PYTORCHVIDEO_AVAILABLE and _KORNIA_AVAILABLE\n _IMAGE_AVAILABLE = all(\n     [\n         _TORCHVISION_AVAILABLE,\n", "issue": "NameError: name 'K' is not defined\n## \ud83d\udc1b Bug\r\n\r\n<!-- A clear and concise description of what the bug is. -->\r\n````sh\r\nUncaught exception\r\nTraceback (most recent call last):\r\n  File \"main.py\", line 11, in <module>\r\n    datamodule = VideoClassificationData.from_folders(\r\n  File \"/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/core/data/data_module.py\", line 540, in from_folders\r\n    return cls.from_data_source(\r\n  File \"/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/core/data/data_module.py\", line 448, in from_data_source\r\n    preprocess = preprocess or cls.preprocess_cls(\r\n  File \"/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/video/classification/data.py\", line 241, in __init__\r\n    super().__init__(\r\n  File \"/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/core/data/process.py\", line 196, in __init__\r\n    train_transform = train_transform or self._resolve_transforms(RunningStage.TRAINING)\r\n  File \"/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/core/data/process.py\", line 247, in _resolve_transforms\r\n    transforms: Optional[Dict[str, Callable]] = resolved_function()\r\n  File \"/home/nitin/github/video_classification/venv/lib/python3.8/site-packages/flash/video/classification/data.py\", line 307, in default_transforms\r\n    transform=K.VideoSequential(\r\nNameError: name 'K' is not defined\r\n````\r\n\r\n\r\n### To Reproduce\r\n\r\nSteps to reproduce the behavior:\r\n\r\n````python\r\nimport os\r\nfrom torch.utils.data.sampler import RandomSampler\r\nimport flash\r\nfrom flash.core.data.utils import download_data\r\nfrom flash.video import VideoClassificationData, VideoClassifier\r\n\r\n# 1. Download a video clip dataset. Find more datasets at https://pytorchvideo.readthedocs.io/en/latest/data.html\r\ndownload_data(\"https://pl-flash-data.s3.amazonaws.com/kinetics.zip\")\r\n\r\n# 2. Load the Data\r\ndatamodule = VideoClassificationData.from_folders(\r\n    train_folder=os.path.join(flash.PROJECT_ROOT, \"data/kinetics/train\"),\r\n    val_folder=os.path.join(flash.PROJECT_ROOT, \"data/kinetics/val\"),\r\n    predict_folder=os.path.join(flash.PROJECT_ROOT, \"data/kinetics/predict\"),\r\n    batch_size=8,\r\n    clip_sampler=\"uniform\",\r\n    clip_duration=1,\r\n    video_sampler=RandomSampler,\r\n    decode_audio=False,\r\n    num_workers=8,\r\n)\r\n\r\n# 3. Build the model\r\nmodel = VideoClassifier(backbone=\"x3d_xs\", num_classes=datamodule.num_classes, pretrained=False)\r\n\r\n# 4. Create the trainer\r\ntrainer = flash.Trainer(max_epochs=3)\r\n\r\n# 5. Finetune the model\r\ntrainer.finetune(model, datamodule=datamodule)\r\n\r\n# 6. Save it!\r\ntrainer.save_checkpoint(\"video_classification.pt\")\r\n````\r\n\r\n<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->\r\n\r\n### Environment\r\n\r\n - PyTorch Version (e.g., 1.0): 1.9.0\r\n - OS (e.g., Linux):  Linux (Ubuntu 18.04)\r\n - How you installed PyTorch: pip\r\n - Python version: 3.8\r\n - CUDA/cuDNN version: 11.3\r\n - GPU models and configuration: GTX 1650 \r\n\r\n### Additional Note\r\n\r\n<!-- Add any other context about the problem here. -->\r\nPlease update the package, `lightning-flash==0.4.0` is not compatible with `pytorchvideo==0.1.2`\n", "before_files": [{"content": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport functools\nimport importlib\nimport operator\nimport types\nfrom importlib.util import find_spec\nfrom typing import Callable, List, Union\nfrom warnings import warn\n\nfrom pkg_resources import DistributionNotFound\n\ntry:\n    from packaging.version import Version\nexcept (ModuleNotFoundError, DistributionNotFound):\n    Version = None\n\n\ndef _module_available(module_path: str) -> bool:\n    \"\"\"Check if a path is available in your environment.\n\n    >>> _module_available('os')\n    True\n    >>> _module_available('bla.bla')\n    False\n    \"\"\"\n    try:\n        return find_spec(module_path) is not None\n    except AttributeError:\n        # Python 3.6\n        return False\n    except ModuleNotFoundError:\n        # Python 3.7+\n        return False\n    except ValueError:\n        # Sometimes __spec__ can be None and gives a ValueError\n        return True\n\n\ndef _compare_version(package: str, op, version) -> bool:\n    \"\"\"Compare package version with some requirements.\n\n    >>> _compare_version(\"torch\", operator.ge, \"0.1\")\n    True\n    \"\"\"\n    try:\n        pkg = importlib.import_module(package)\n    except (ModuleNotFoundError, DistributionNotFound, ValueError):\n        return False\n    try:\n        pkg_version = Version(pkg.__version__)\n    except TypeError:\n        # this is mock by sphinx, so it shall return True to generate all summaries\n        return True\n    return op(pkg_version, Version(version))\n\n\n_TORCH_AVAILABLE = _module_available(\"torch\")\n_BOLTS_AVAILABLE = _module_available(\"pl_bolts\") and _compare_version(\"torch\", operator.lt, \"1.9.0\")\n_PANDAS_AVAILABLE = _module_available(\"pandas\")\n_SKLEARN_AVAILABLE = _module_available(\"sklearn\")\n_TABNET_AVAILABLE = _module_available(\"pytorch_tabnet\")\n_KORNIA_AVAILABLE = _module_available(\"kornia\")\n_COCO_AVAILABLE = _module_available(\"pycocotools\")\n_TIMM_AVAILABLE = _module_available(\"timm\")\n_TORCHVISION_AVAILABLE = _module_available(\"torchvision\")\n_PYTORCHVIDEO_AVAILABLE = _module_available(\"pytorchvideo\")\n_MATPLOTLIB_AVAILABLE = _module_available(\"matplotlib\")\n_TRANSFORMERS_AVAILABLE = _module_available(\"transformers\")\n_PYSTICHE_AVAILABLE = _module_available(\"pystiche\")\n_FIFTYONE_AVAILABLE = _module_available(\"fiftyone\")\n_FASTAPI_AVAILABLE = _module_available(\"fastapi\")\n_PYDANTIC_AVAILABLE = _module_available(\"pydantic\")\n_GRAPHVIZ_AVAILABLE = _module_available(\"graphviz\")\n_CYTOOLZ_AVAILABLE = _module_available(\"cytoolz\")\n_UVICORN_AVAILABLE = _module_available(\"uvicorn\")\n_PIL_AVAILABLE = _module_available(\"PIL\")\n_OPEN3D_AVAILABLE = _module_available(\"open3d\")\n_SEGMENTATION_MODELS_AVAILABLE = _module_available(\"segmentation_models_pytorch\")\n_SOUNDFILE_AVAILABLE = _module_available(\"soundfile\")\n_TORCH_SCATTER_AVAILABLE = _module_available(\"torch_scatter\")\n_TORCH_SPARSE_AVAILABLE = _module_available(\"torch_sparse\")\n_TORCH_GEOMETRIC_AVAILABLE = _module_available(\"torch_geometric\")\n_TORCHAUDIO_AVAILABLE = _module_available(\"torchaudio\")\n_ROUGE_SCORE_AVAILABLE = _module_available(\"rouge_score\")\n_SENTENCEPIECE_AVAILABLE = _module_available(\"sentencepiece\")\n_DATASETS_AVAILABLE = _module_available(\"datasets\")\n_ICEVISION_AVAILABLE = _module_available(\"icevision\")\n_ICEDATA_AVAILABLE = _module_available(\"icedata\")\n_TORCH_ORT_AVAILABLE = _module_available(\"torch_ort\")\n_VISSL_AVAILABLE = _module_available(\"vissl\") and _module_available(\"classy_vision\")\n\nif _PIL_AVAILABLE:\n    from PIL import Image\nelse:\n\n    class MetaImage(type):\n        def __init__(cls, name, bases, dct):\n            super().__init__(name, bases, dct)\n\n            cls._Image = None\n\n        @property\n        def Image(cls):\n            warn(\"Mock object called due to missing PIL library. Please use \\\"pip install 'lightning-flash[image]'\\\".\")\n            return cls._Image\n\n    class Image(metaclass=MetaImage):\n        pass\n\n\nif Version:\n    _TORCHVISION_GREATER_EQUAL_0_9 = _compare_version(\"torchvision\", operator.ge, \"0.9.0\")\n    _PL_GREATER_EQUAL_1_4_3 = _compare_version(\"pytorch_lightning\", operator.ge, \"1.4.3\")\n\n_TEXT_AVAILABLE = all(\n    [\n        _TRANSFORMERS_AVAILABLE,\n        _ROUGE_SCORE_AVAILABLE,\n        _SENTENCEPIECE_AVAILABLE,\n        _DATASETS_AVAILABLE,\n    ]\n)\n_TABULAR_AVAILABLE = _TABNET_AVAILABLE and _PANDAS_AVAILABLE\n_VIDEO_AVAILABLE = _PYTORCHVIDEO_AVAILABLE\n_IMAGE_AVAILABLE = all(\n    [\n        _TORCHVISION_AVAILABLE,\n        _TIMM_AVAILABLE,\n        _PIL_AVAILABLE,\n        _KORNIA_AVAILABLE,\n        _PYSTICHE_AVAILABLE,\n        _SEGMENTATION_MODELS_AVAILABLE,\n        _ICEVISION_AVAILABLE,\n        _ICEDATA_AVAILABLE,\n    ]\n)\n_SERVE_AVAILABLE = _FASTAPI_AVAILABLE and _PYDANTIC_AVAILABLE and _CYTOOLZ_AVAILABLE and _UVICORN_AVAILABLE\n_POINTCLOUD_AVAILABLE = _OPEN3D_AVAILABLE and _TORCHVISION_AVAILABLE\n_AUDIO_AVAILABLE = all([_TORCHAUDIO_AVAILABLE, _SOUNDFILE_AVAILABLE, _TRANSFORMERS_AVAILABLE])\n_GRAPH_AVAILABLE = _TORCH_SCATTER_AVAILABLE and _TORCH_SPARSE_AVAILABLE and _TORCH_GEOMETRIC_AVAILABLE\n\n_EXTRAS_AVAILABLE = {\n    \"image\": _IMAGE_AVAILABLE,\n    \"tabular\": _TABULAR_AVAILABLE,\n    \"text\": _TEXT_AVAILABLE,\n    \"video\": _VIDEO_AVAILABLE,\n    \"pointcloud\": _POINTCLOUD_AVAILABLE,\n    \"serve\": _SERVE_AVAILABLE,\n    \"audio\": _AUDIO_AVAILABLE,\n    \"graph\": _GRAPH_AVAILABLE,\n}\n\n\ndef _requires(\n    module_paths: Union[str, List],\n    module_available: Callable[[str], bool],\n    formatter: Callable[[List[str]], str],\n):\n\n    if not isinstance(module_paths, list):\n        module_paths = [module_paths]\n\n    def decorator(func):\n        if not all(module_available(module_path) for module_path in module_paths):\n\n            @functools.wraps(func)\n            def wrapper(*args, **kwargs):\n                raise ModuleNotFoundError(\n                    f\"Required dependencies not available. Please run: pip install {formatter(module_paths)}\"\n                )\n\n            return wrapper\n        else:\n            return func\n\n    return decorator\n\n\ndef requires(module_paths: Union[str, List]):\n    return _requires(module_paths, _module_available, lambda module_paths: \" \".join(module_paths))\n\n\ndef requires_extras(extras: Union[str, List]):\n    return _requires(\n        extras, lambda extras: _EXTRAS_AVAILABLE[extras], lambda extras: f\"'lightning-flash[{','.join(extras)}]'\"\n    )\n\n\ndef example_requires(extras: Union[str, List[str]]):\n    return requires_extras(extras)(lambda: None)()\n\n\ndef lazy_import(module_name, callback=None):\n    \"\"\"Returns a proxy module object that will lazily import the given module the first time it is used.\n\n    Example usage::\n\n        # Lazy version of `import tensorflow as tf`\n        tf = lazy_import(\"tensorflow\")\n\n        # Other commands\n\n        # Now the module is loaded\n        tf.__version__\n\n    Args:\n        module_name: the fully-qualified module name to import\n        callback (None): a callback function to call before importing the\n            module\n\n    Returns:\n        a proxy module object that will be lazily imported when first used\n    \"\"\"\n    return LazyModule(module_name, callback=callback)\n\n\nclass LazyModule(types.ModuleType):\n    \"\"\"Proxy module that lazily imports the underlying module the first time it is actually used.\n\n    Args:\n        module_name: the fully-qualified module name to import\n        callback (None): a callback function to call before importing the\n            module\n    \"\"\"\n\n    def __init__(self, module_name, callback=None):\n        super().__init__(module_name)\n        self._module = None\n        self._callback = callback\n\n    def __getattr__(self, item):\n        if self._module is None:\n            self._import_module()\n\n        return getattr(self._module, item)\n\n    def __dir__(self):\n        if self._module is None:\n            self._import_module()\n\n        return dir(self._module)\n\n    def _import_module(self):\n        # Execute callback, if any\n        if self._callback is not None:\n            self._callback()\n\n        # Actually import the module\n        module = importlib.import_module(self.__name__)\n        self._module = module\n\n        # Update this object's dict so that attribute references are efficient\n        # (__getattr__ is only called on lookups that fail)\n        self.__dict__.update(module.__dict__)\n", "path": "flash/core/utilities/imports.py"}], "after_files": [{"content": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport functools\nimport importlib\nimport operator\nimport types\nfrom importlib.util import find_spec\nfrom typing import Callable, List, Union\nfrom warnings import warn\n\nfrom pkg_resources import DistributionNotFound\n\ntry:\n    from packaging.version import Version\nexcept (ModuleNotFoundError, DistributionNotFound):\n    Version = None\n\n\ndef _module_available(module_path: str) -> bool:\n    \"\"\"Check if a path is available in your environment.\n\n    >>> _module_available('os')\n    True\n    >>> _module_available('bla.bla')\n    False\n    \"\"\"\n    try:\n        return find_spec(module_path) is not None\n    except AttributeError:\n        # Python 3.6\n        return False\n    except ModuleNotFoundError:\n        # Python 3.7+\n        return False\n    except ValueError:\n        # Sometimes __spec__ can be None and gives a ValueError\n        return True\n\n\ndef _compare_version(package: str, op, version) -> bool:\n    \"\"\"Compare package version with some requirements.\n\n    >>> _compare_version(\"torch\", operator.ge, \"0.1\")\n    True\n    \"\"\"\n    try:\n        pkg = importlib.import_module(package)\n    except (ModuleNotFoundError, DistributionNotFound, ValueError):\n        return False\n    try:\n        pkg_version = Version(pkg.__version__)\n    except TypeError:\n        # this is mock by sphinx, so it shall return True to generate all summaries\n        return True\n    return op(pkg_version, Version(version))\n\n\n_TORCH_AVAILABLE = _module_available(\"torch\")\n_BOLTS_AVAILABLE = _module_available(\"pl_bolts\") and _compare_version(\"torch\", operator.lt, \"1.9.0\")\n_PANDAS_AVAILABLE = _module_available(\"pandas\")\n_SKLEARN_AVAILABLE = _module_available(\"sklearn\")\n_TABNET_AVAILABLE = _module_available(\"pytorch_tabnet\")\n_KORNIA_AVAILABLE = _module_available(\"kornia\")\n_COCO_AVAILABLE = _module_available(\"pycocotools\")\n_TIMM_AVAILABLE = _module_available(\"timm\")\n_TORCHVISION_AVAILABLE = _module_available(\"torchvision\")\n_PYTORCHVIDEO_AVAILABLE = _module_available(\"pytorchvideo\")\n_MATPLOTLIB_AVAILABLE = _module_available(\"matplotlib\")\n_TRANSFORMERS_AVAILABLE = _module_available(\"transformers\")\n_PYSTICHE_AVAILABLE = _module_available(\"pystiche\")\n_FIFTYONE_AVAILABLE = _module_available(\"fiftyone\")\n_FASTAPI_AVAILABLE = _module_available(\"fastapi\")\n_PYDANTIC_AVAILABLE = _module_available(\"pydantic\")\n_GRAPHVIZ_AVAILABLE = _module_available(\"graphviz\")\n_CYTOOLZ_AVAILABLE = _module_available(\"cytoolz\")\n_UVICORN_AVAILABLE = _module_available(\"uvicorn\")\n_PIL_AVAILABLE = _module_available(\"PIL\")\n_OPEN3D_AVAILABLE = _module_available(\"open3d\")\n_SEGMENTATION_MODELS_AVAILABLE = _module_available(\"segmentation_models_pytorch\")\n_SOUNDFILE_AVAILABLE = _module_available(\"soundfile\")\n_TORCH_SCATTER_AVAILABLE = _module_available(\"torch_scatter\")\n_TORCH_SPARSE_AVAILABLE = _module_available(\"torch_sparse\")\n_TORCH_GEOMETRIC_AVAILABLE = _module_available(\"torch_geometric\")\n_TORCHAUDIO_AVAILABLE = _module_available(\"torchaudio\")\n_ROUGE_SCORE_AVAILABLE = _module_available(\"rouge_score\")\n_SENTENCEPIECE_AVAILABLE = _module_available(\"sentencepiece\")\n_DATASETS_AVAILABLE = _module_available(\"datasets\")\n_ICEVISION_AVAILABLE = _module_available(\"icevision\")\n_ICEDATA_AVAILABLE = _module_available(\"icedata\")\n_TORCH_ORT_AVAILABLE = _module_available(\"torch_ort\")\n_VISSL_AVAILABLE = _module_available(\"vissl\") and _module_available(\"classy_vision\")\n\nif _PIL_AVAILABLE:\n    from PIL import Image\nelse:\n\n    class MetaImage(type):\n        def __init__(cls, name, bases, dct):\n            super().__init__(name, bases, dct)\n\n            cls._Image = None\n\n        @property\n        def Image(cls):\n            warn(\"Mock object called due to missing PIL library. Please use \\\"pip install 'lightning-flash[image]'\\\".\")\n            return cls._Image\n\n    class Image(metaclass=MetaImage):\n        pass\n\n\nif Version:\n    _TORCHVISION_GREATER_EQUAL_0_9 = _compare_version(\"torchvision\", operator.ge, \"0.9.0\")\n    _PL_GREATER_EQUAL_1_4_3 = _compare_version(\"pytorch_lightning\", operator.ge, \"1.4.3\")\n\n_TEXT_AVAILABLE = all(\n    [\n        _TRANSFORMERS_AVAILABLE,\n        _ROUGE_SCORE_AVAILABLE,\n        _SENTENCEPIECE_AVAILABLE,\n        _DATASETS_AVAILABLE,\n    ]\n)\n_TABULAR_AVAILABLE = _TABNET_AVAILABLE and _PANDAS_AVAILABLE\n_VIDEO_AVAILABLE = _TORCHVISION_AVAILABLE and _PIL_AVAILABLE and _PYTORCHVIDEO_AVAILABLE and _KORNIA_AVAILABLE\n_IMAGE_AVAILABLE = all(\n    [\n        _TORCHVISION_AVAILABLE,\n        _TIMM_AVAILABLE,\n        _PIL_AVAILABLE,\n        _KORNIA_AVAILABLE,\n        _PYSTICHE_AVAILABLE,\n        _SEGMENTATION_MODELS_AVAILABLE,\n        _ICEVISION_AVAILABLE,\n        _ICEDATA_AVAILABLE,\n    ]\n)\n_SERVE_AVAILABLE = _FASTAPI_AVAILABLE and _PYDANTIC_AVAILABLE and _CYTOOLZ_AVAILABLE and _UVICORN_AVAILABLE\n_POINTCLOUD_AVAILABLE = _OPEN3D_AVAILABLE and _TORCHVISION_AVAILABLE\n_AUDIO_AVAILABLE = all([_TORCHAUDIO_AVAILABLE, _SOUNDFILE_AVAILABLE, _TRANSFORMERS_AVAILABLE])\n_GRAPH_AVAILABLE = _TORCH_SCATTER_AVAILABLE and _TORCH_SPARSE_AVAILABLE and _TORCH_GEOMETRIC_AVAILABLE\n\n_EXTRAS_AVAILABLE = {\n    \"image\": _IMAGE_AVAILABLE,\n    \"tabular\": _TABULAR_AVAILABLE,\n    \"text\": _TEXT_AVAILABLE,\n    \"video\": _VIDEO_AVAILABLE,\n    \"pointcloud\": _POINTCLOUD_AVAILABLE,\n    \"serve\": _SERVE_AVAILABLE,\n    \"audio\": _AUDIO_AVAILABLE,\n    \"graph\": _GRAPH_AVAILABLE,\n}\n\n\ndef _requires(\n    module_paths: Union[str, List],\n    module_available: Callable[[str], bool],\n    formatter: Callable[[List[str]], str],\n):\n\n    if not isinstance(module_paths, list):\n        module_paths = [module_paths]\n\n    def decorator(func):\n        if not all(module_available(module_path) for module_path in module_paths):\n\n            @functools.wraps(func)\n            def wrapper(*args, **kwargs):\n                raise ModuleNotFoundError(\n                    f\"Required dependencies not available. Please run: pip install {formatter(module_paths)}\"\n                )\n\n            return wrapper\n        else:\n            return func\n\n    return decorator\n\n\ndef requires(module_paths: Union[str, List]):\n    return _requires(module_paths, _module_available, lambda module_paths: \" \".join(module_paths))\n\n\ndef requires_extras(extras: Union[str, List]):\n    return _requires(\n        extras, lambda extras: _EXTRAS_AVAILABLE[extras], lambda extras: f\"'lightning-flash[{','.join(extras)}]'\"\n    )\n\n\ndef example_requires(extras: Union[str, List[str]]):\n    return requires_extras(extras)(lambda: None)()\n\n\ndef lazy_import(module_name, callback=None):\n    \"\"\"Returns a proxy module object that will lazily import the given module the first time it is used.\n\n    Example usage::\n\n        # Lazy version of `import tensorflow as tf`\n        tf = lazy_import(\"tensorflow\")\n\n        # Other commands\n\n        # Now the module is loaded\n        tf.__version__\n\n    Args:\n        module_name: the fully-qualified module name to import\n        callback (None): a callback function to call before importing the\n            module\n\n    Returns:\n        a proxy module object that will be lazily imported when first used\n    \"\"\"\n    return LazyModule(module_name, callback=callback)\n\n\nclass LazyModule(types.ModuleType):\n    \"\"\"Proxy module that lazily imports the underlying module the first time it is actually used.\n\n    Args:\n        module_name: the fully-qualified module name to import\n        callback (None): a callback function to call before importing the\n            module\n    \"\"\"\n\n    def __init__(self, module_name, callback=None):\n        super().__init__(module_name)\n        self._module = None\n        self._callback = callback\n\n    def __getattr__(self, item):\n        if self._module is None:\n            self._import_module()\n\n        return getattr(self._module, item)\n\n    def __dir__(self):\n        if self._module is None:\n            self._import_module()\n\n        return dir(self._module)\n\n    def _import_module(self):\n        # Execute callback, if any\n        if self._callback is not None:\n            self._callback()\n\n        # Actually import the module\n        module = importlib.import_module(self.__name__)\n        self._module = module\n\n        # Update this object's dict so that attribute references are efficient\n        # (__getattr__ is only called on lookups that fail)\n        self.__dict__.update(module.__dict__)\n", "path": "flash/core/utilities/imports.py"}]}