We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Not able to import flash as transformer.__spec__ is returning None
## 🐛 Bug

<!-- A clear and concise description of what the bug is. -->
I am trying to complete a summarization project and decided to use flash for it but am getting import error as `transformers.__spec__`  is returning None. I have opened huggingface/transformers#12904  issue on transformers page meanwhile, would like to know if there's a possible workaround to it.

#### Code sample
<!-- Ideally attach a minimal code sample to reproduce the decried issue.
Minimal means having the shortest code but still preserving the bug. -->

```
import transformers
print(transformers.__version__)
print(transformers.__spec__)

import flash
```

**OUTPUT**:
```
4.8.2
None
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-d02f1c770adc> in <module>
      3 print(transformers.__spec__)
      4 
----> 5 import flash

/opt/conda/lib/python3.7/site-packages/flash/__init__.py in <module>
     16 
     17 from flash.__about__ import *  # noqa: F401 F403
---> 18 from flash.core.utilities.imports import _TORCH_AVAILABLE
     19 
     20 if _TORCH_AVAILABLE:

/opt/conda/lib/python3.7/site-packages/flash/core/utilities/imports.py in <module>
     75 _PYTORCHVIDEO_AVAILABLE = _module_available("pytorchvideo")
     76 _MATPLOTLIB_AVAILABLE = _module_available("matplotlib")
---> 77 _TRANSFORMERS_AVAILABLE = _module_available("transformers")
     78 _PYSTICHE_AVAILABLE = _module_available("pystiche")
     79 _FIFTYONE_AVAILABLE = _module_available("fiftyone")

/opt/conda/lib/python3.7/site-packages/flash/core/utilities/imports.py in _module_available(module_path)
     36     """
     37     try:
---> 38         return find_spec(module_path) is not None
     39     except AttributeError:
     40         # Python 3.6

/opt/conda/lib/python3.7/importlib/util.py in find_spec(name, package)
    112         else:
    113             if spec is None:
--> 114                 raise ValueError('{}.__spec__ is None'.format(name))
    115             return spec
    116 

ValueError: transformers.__spec__ is None
```

### Expected behavior

<!-- A clear and concise description of what you expected to happen. -->
Able to import flash

### Environment

 - PyTorch Version (e.g., 1.0):  3.7.0/3.8.1
 - OS (e.g., Linux):
 - Platform: Colab/Kaggle
 - How you installed PyTorch (`conda`, `pip`, source): 
 - Build command you used (if compiling from source):
 - Python version:
 - CUDA/cuDNN version:
 - GPU models and configuration:
 - Any other relevant information:

### Additional context

<!-- Add any other context about the problem here. -->


--- 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 
21 from pkg_resources import DistributionNotFound
22 
23 try:
24     from packaging.version import Version
25 except (ModuleNotFoundError, DistributionNotFound):
26     Version = None
27 
28 
29 def _module_available(module_path: str) -> bool:
30     """
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 
47 
48 def _compare_version(package: str, op, version) -> bool:
49     """
50     Compare package version with some requirements
51 
52     >>> _compare_version("torch", operator.ge, "0.1")
53     True
54     """
55     try:
56         pkg = importlib.import_module(package)
57     except (ModuleNotFoundError, DistributionNotFound, ValueError):
58         return False
59     try:
60         pkg_version = Version(pkg.__version__)
61     except TypeError:
62         # this is mock by sphinx, so it shall return True ro generate all summaries
63         return True
64     return op(pkg_version, Version(version))
65 
66 
67 _TORCH_AVAILABLE = _module_available("torch")
68 _BOLTS_AVAILABLE = _module_available("pl_bolts") and _compare_version("torch", operator.lt, "1.9.0")
69 _PANDAS_AVAILABLE = _module_available("pandas")
70 _SKLEARN_AVAILABLE = _module_available("sklearn")
71 _TABNET_AVAILABLE = _module_available("pytorch_tabnet")
72 _KORNIA_AVAILABLE = _module_available("kornia")
73 _COCO_AVAILABLE = _module_available("pycocotools")
74 _TIMM_AVAILABLE = _module_available("timm")
75 _TORCHVISION_AVAILABLE = _module_available("torchvision")
76 _PYTORCHVIDEO_AVAILABLE = _module_available("pytorchvideo")
77 _MATPLOTLIB_AVAILABLE = _module_available("matplotlib")
78 _TRANSFORMERS_AVAILABLE = _module_available("transformers")
79 _PYSTICHE_AVAILABLE = _module_available("pystiche")
80 _FIFTYONE_AVAILABLE = _module_available("fiftyone")
81 _FASTAPI_AVAILABLE = _module_available("fastapi")
82 _PYDANTIC_AVAILABLE = _module_available("pydantic")
83 _GRAPHVIZ_AVAILABLE = _module_available("graphviz")
84 _CYTOOLZ_AVAILABLE = _module_available("cytoolz")
85 _UVICORN_AVAILABLE = _module_available("uvicorn")
86 _PIL_AVAILABLE = _module_available("PIL")
87 _OPEN3D_AVAILABLE = _module_available("open3d")
88 _ASTEROID_AVAILABLE = _module_available("asteroid")
89 _SEGMENTATION_MODELS_AVAILABLE = _module_available("segmentation_models_pytorch")
90 _SOUNDFILE_AVAILABLE = _module_available("soundfile")
91 _TORCH_SCATTER_AVAILABLE = _module_available("torch_scatter")
92 _TORCH_SPARSE_AVAILABLE = _module_available("torch_sparse")
93 _TORCH_GEOMETRIC_AVAILABLE = _module_available("torch_geometric")
94 _TORCHAUDIO_AVAILABLE = _module_available("torchaudio")
95 _ROUGE_SCORE_AVAILABLE = _module_available("rouge_score")
96 _SENTENCEPIECE_AVAILABLE = _module_available("sentencepiece")
97 _DATASETS_AVAILABLE = _module_available("datasets")
98 
99 if Version:
100     _TORCHVISION_GREATER_EQUAL_0_9 = _compare_version("torchvision", operator.ge, "0.9.0")
101 
102 _TEXT_AVAILABLE = all([
103     _TRANSFORMERS_AVAILABLE,
104     _ROUGE_SCORE_AVAILABLE,
105     _SENTENCEPIECE_AVAILABLE,
106     _DATASETS_AVAILABLE,
107 ])
108 _TABULAR_AVAILABLE = _TABNET_AVAILABLE and _PANDAS_AVAILABLE
109 _VIDEO_AVAILABLE = _PYTORCHVIDEO_AVAILABLE
110 _IMAGE_AVAILABLE = all([
111     _TORCHVISION_AVAILABLE,
112     _TIMM_AVAILABLE,
113     _PIL_AVAILABLE,
114     _KORNIA_AVAILABLE,
115     _PYSTICHE_AVAILABLE,
116     _SEGMENTATION_MODELS_AVAILABLE,
117 ])
118 _SERVE_AVAILABLE = _FASTAPI_AVAILABLE and _PYDANTIC_AVAILABLE and _CYTOOLZ_AVAILABLE and _UVICORN_AVAILABLE
119 _POINTCLOUD_AVAILABLE = _OPEN3D_AVAILABLE and _TORCHVISION_AVAILABLE
120 _AUDIO_AVAILABLE = all([_ASTEROID_AVAILABLE, _TORCHAUDIO_AVAILABLE, _SOUNDFILE_AVAILABLE, _TRANSFORMERS_AVAILABLE])
121 _GRAPH_AVAILABLE = _TORCH_SCATTER_AVAILABLE and _TORCH_SPARSE_AVAILABLE and _TORCH_GEOMETRIC_AVAILABLE
122 
123 _EXTRAS_AVAILABLE = {
124     'image': _IMAGE_AVAILABLE,
125     'tabular': _TABULAR_AVAILABLE,
126     'text': _TEXT_AVAILABLE,
127     'video': _VIDEO_AVAILABLE,
128     'pointcloud': _POINTCLOUD_AVAILABLE,
129     'serve': _SERVE_AVAILABLE,
130     'audio': _AUDIO_AVAILABLE,
131     'graph': _GRAPH_AVAILABLE,
132 }
133 
134 
135 def _requires(
136     module_paths: Union[str, List],
137     module_available: Callable[[str], bool],
138     formatter: Callable[[List[str]], str],
139 ):
140 
141     if not isinstance(module_paths, list):
142         module_paths = [module_paths]
143 
144     def decorator(func):
145         if not all(module_available(module_path) for module_path in module_paths):
146 
147             @functools.wraps(func)
148             def wrapper(*args, **kwargs):
149                 raise ModuleNotFoundError(
150                     f"Required dependencies not available. Please run: pip install {formatter(module_paths)}"
151                 )
152 
153             return wrapper
154         else:
155             return func
156 
157     return decorator
158 
159 
160 def requires(module_paths: Union[str, List]):
161     return _requires(module_paths, _module_available, lambda module_paths: " ".join(module_paths))
162 
163 
164 def requires_extras(extras: Union[str, List]):
165     return _requires(
166         extras, lambda extras: _EXTRAS_AVAILABLE[extras], lambda extras: f"'lightning-flash[{','.join(extras)}]'"
167     )
168 
169 
170 def lazy_import(module_name, callback=None):
171     """Returns a proxy module object that will lazily import the given module
172     the first time it is used.
173 
174     Example usage::
175 
176         # Lazy version of `import tensorflow as tf`
177         tf = lazy_import("tensorflow")
178 
179         # Other commands
180 
181         # Now the module is loaded
182         tf.__version__
183 
184     Args:
185         module_name: the fully-qualified module name to import
186         callback (None): a callback function to call before importing the
187             module
188 
189     Returns:
190         a proxy module object that will be lazily imported when first used
191     """
192     return LazyModule(module_name, callback=callback)
193 
194 
195 class LazyModule(types.ModuleType):
196     """Proxy module that lazily imports the underlying module the first time it
197     is actually used.
198 
199     Args:
200         module_name: the fully-qualified module name to import
201         callback (None): a callback function to call before importing the
202             module
203     """
204 
205     def __init__(self, module_name, callback=None):
206         super().__init__(module_name)
207         self._module = None
208         self._callback = callback
209 
210     def __getattr__(self, item):
211         if self._module is None:
212             self._import_module()
213 
214         return getattr(self._module, item)
215 
216     def __dir__(self):
217         if self._module is None:
218             self._import_module()
219 
220         return dir(self._module)
221 
222     def _import_module(self):
223         # Execute callback, if any
224         if self._callback is not None:
225             self._callback()
226 
227         # Actually import the module
228         module = importlib.import_module(self.__name__)
229         self._module = module
230 
231         # Update this object's dict so that attribute references are efficient
232         # (__getattr__ is only called on lookups that fail)
233         self.__dict__.update(module.__dict__)
234
```
--- 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
@@ -43,6 +43,9 @@
     except ModuleNotFoundError:
         # Python 3.7+
         return False
+    except ValueError:
+        # Sometimes __spec__ can be None and gives a ValueError
+        return True
 
 
 def _compare_version(package: str, op, version) -> bool:
@@ -59,7 +62,7 @@
     try:
         pkg_version = Version(pkg.__version__)
     except TypeError:
-        # this is mock by sphinx, so it shall return True ro generate all summaries
+        # this is mock by sphinx, so it shall return True to generate all summaries
         return True
     return op(pkg_version, Version(version))

{"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@@ -43,6 +43,9 @@\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 \n def _compare_version(package: str, op, version) -> bool:\n@@ -59,7 +62,7 @@\n     try:\n         pkg_version = Version(pkg.__version__)\n     except TypeError:\n-        # this is mock by sphinx, so it shall return True ro generate all summaries\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", "issue": "Not able to import flash as transformer.__spec__ is returning None\n## \ud83d\udc1b Bug\r\n\r\n<!-- A clear and concise description of what the bug is. -->\r\nI am trying to complete a summarization project and decided to use flash for it but am getting import error as `transformers.__spec__`  is returning None. I have opened huggingface/transformers#12904  issue on transformers page meanwhile, would like to know if there's a possible workaround to it.\r\n\r\n#### Code sample\r\n<!-- Ideally attach a minimal code sample to reproduce the decried issue.\r\nMinimal means having the shortest code but still preserving the bug. -->\r\n\r\n```\r\nimport transformers\r\nprint(transformers.__version__)\r\nprint(transformers.__spec__)\r\n\r\nimport flash\r\n```\r\n\r\n**OUTPUT**:\r\n```\r\n4.8.2\r\nNone\r\n---------------------------------------------------------------------------\r\nValueError                                Traceback (most recent call last)\r\n<ipython-input-1-d02f1c770adc> in <module>\r\n      3 print(transformers.__spec__)\r\n      4 \r\n----> 5 import flash\r\n\r\n/opt/conda/lib/python3.7/site-packages/flash/__init__.py in <module>\r\n     16 \r\n     17 from flash.__about__ import *  # noqa: F401 F403\r\n---> 18 from flash.core.utilities.imports import _TORCH_AVAILABLE\r\n     19 \r\n     20 if _TORCH_AVAILABLE:\r\n\r\n/opt/conda/lib/python3.7/site-packages/flash/core/utilities/imports.py in <module>\r\n     75 _PYTORCHVIDEO_AVAILABLE = _module_available(\"pytorchvideo\")\r\n     76 _MATPLOTLIB_AVAILABLE = _module_available(\"matplotlib\")\r\n---> 77 _TRANSFORMERS_AVAILABLE = _module_available(\"transformers\")\r\n     78 _PYSTICHE_AVAILABLE = _module_available(\"pystiche\")\r\n     79 _FIFTYONE_AVAILABLE = _module_available(\"fiftyone\")\r\n\r\n/opt/conda/lib/python3.7/site-packages/flash/core/utilities/imports.py in _module_available(module_path)\r\n     36     \"\"\"\r\n     37     try:\r\n---> 38         return find_spec(module_path) is not None\r\n     39     except AttributeError:\r\n     40         # Python 3.6\r\n\r\n/opt/conda/lib/python3.7/importlib/util.py in find_spec(name, package)\r\n    112         else:\r\n    113             if spec is None:\r\n--> 114                 raise ValueError('{}.__spec__ is None'.format(name))\r\n    115             return spec\r\n    116 \r\n\r\nValueError: transformers.__spec__ is None\r\n```\r\n\r\n### Expected behavior\r\n\r\n<!-- A clear and concise description of what you expected to happen. -->\r\nAble to import flash\r\n\r\n### Environment\r\n\r\n - PyTorch Version (e.g., 1.0):  3.7.0/3.8.1\r\n - OS (e.g., Linux):\r\n - Platform: Colab/Kaggle\r\n - How you installed PyTorch (`conda`, `pip`, source): \r\n - Build command you used (if compiling from source):\r\n - Python version:\r\n - CUDA/cuDNN version:\r\n - GPU models and configuration:\r\n - Any other relevant information:\r\n\r\n### Additional context\r\n\r\n<!-- Add any other context about the problem here. -->\r\n\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\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    \"\"\"\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\n\ndef _compare_version(package: str, op, version) -> bool:\n    \"\"\"\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 ro 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_ASTEROID_AVAILABLE = _module_available(\"asteroid\")\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\nif Version:\n    _TORCHVISION_GREATER_EQUAL_0_9 = _compare_version(\"torchvision\", operator.ge, \"0.9.0\")\n\n_TEXT_AVAILABLE = all([\n    _TRANSFORMERS_AVAILABLE,\n    _ROUGE_SCORE_AVAILABLE,\n    _SENTENCEPIECE_AVAILABLE,\n    _DATASETS_AVAILABLE,\n])\n_TABULAR_AVAILABLE = _TABNET_AVAILABLE and _PANDAS_AVAILABLE\n_VIDEO_AVAILABLE = _PYTORCHVIDEO_AVAILABLE\n_IMAGE_AVAILABLE = all([\n    _TORCHVISION_AVAILABLE,\n    _TIMM_AVAILABLE,\n    _PIL_AVAILABLE,\n    _KORNIA_AVAILABLE,\n    _PYSTICHE_AVAILABLE,\n    _SEGMENTATION_MODELS_AVAILABLE,\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([_ASTEROID_AVAILABLE, _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 lazy_import(module_name, callback=None):\n    \"\"\"Returns a proxy module object that will lazily import the given module\n    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\n    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\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    \"\"\"\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    \"\"\"\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_ASTEROID_AVAILABLE = _module_available(\"asteroid\")\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\nif Version:\n    _TORCHVISION_GREATER_EQUAL_0_9 = _compare_version(\"torchvision\", operator.ge, \"0.9.0\")\n\n_TEXT_AVAILABLE = all([\n    _TRANSFORMERS_AVAILABLE,\n    _ROUGE_SCORE_AVAILABLE,\n    _SENTENCEPIECE_AVAILABLE,\n    _DATASETS_AVAILABLE,\n])\n_TABULAR_AVAILABLE = _TABNET_AVAILABLE and _PANDAS_AVAILABLE\n_VIDEO_AVAILABLE = _PYTORCHVIDEO_AVAILABLE\n_IMAGE_AVAILABLE = all([\n    _TORCHVISION_AVAILABLE,\n    _TIMM_AVAILABLE,\n    _PIL_AVAILABLE,\n    _KORNIA_AVAILABLE,\n    _PYSTICHE_AVAILABLE,\n    _SEGMENTATION_MODELS_AVAILABLE,\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([_ASTEROID_AVAILABLE, _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 lazy_import(module_name, callback=None):\n    \"\"\"Returns a proxy module object that will lazily import the given module\n    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\n    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"}]}