@inject
def import_from_tfhub(identifier: t.Union[(str, 'HubModule', 'KerasLayer')], name: t.Optional[str]=None, labels: t.Optional[t.Dict[(str, str)]]=None, custom_objects: t.Optional[t.Dict[(str, t.Any)]]=None, metadata: t.Optional[t.Dict[(str, t.Any)]]=None, model_store: 'ModelStore'=Provide[BentoMLContainer.model_store]) -> Tag:
    '\n    Import a model from `Tensorflow Hub <https://tfhub.dev/>`_ to BentoML modelstore.\n\n    Args:\n        identifier (:code:`Union[str, tensorflow_hub.Module, tensorflow_hub.KerasLayer]`): Identifier accepts\n            two type of inputs:\n                - if `type` of :code:`identifier` either of type :code:`tensorflow_hub.Module` (**legacy** `tensorflow_hub`) or :code:`tensorflow_hub.KerasLayer` (`tensorflow_hub`), then we will save the given model to a :code:`SavedModel` format.\n                - if `type` of :code:`identifier` is a :obj:`str`, we assume that this is the URI retrieved from Tensorflow Hub. We then clean the given URI, and get a local copy of a given model to BentoML modelstore. name (:code:`str`, `optional`, defaults to `None`): An optional name for the model. If :code:`identifier` is a :obj:`str`, then name can be autogenerated from the given URI.\n        name (:code:`str`, `optional`, default to `None`):\n            Optional name for the saved model. If None, then name will be generated from :code:`identifier`.\n        labels (:code:`Dict[str, str]`, `optional`, default to :code:`None`):\n            user-defined labels for managing models, e.g. team=nlp, stage=dev\n        custom_objects (:code:`Dict[str, Any]]`, `optional`, default to :code:`None`):\n            user-defined additional python objects to be saved alongside the model,\n            e.g. a tokenizer instance, preprocessor function, model configuration json\n        metadata (:code:`Dict[str, Any]`, `optional`,  default to :code:`None`):\n            Custom metadata for given model.\n        model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n            BentoML modelstore, provided by DI Container.\n\n    Returns:\n        :obj:`~bentoml.Tag`: A :obj:`~bentoml.Tag` object that can be used to retrieve the model with :func:`bentoml.tensorflow.load`:\n\n    Example for importing a model from Tensorflow Hub:\n\n    .. code-block:: python\n\n        import tensorflow_text as text # noqa # pylint: disable\n        import bentoml\n\n        tag = bentoml.tensorflow.import_from_tfhub("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3")\n\n        # load model back with `load`:\n        model = bentoml.tensorflow.load(tag, load_as_hub_module=True)\n\n\n    Example for importing a custom Tensorflow Hub model:\n\n    .. code-block:: python\n\n        import tensorflow as tf\n        import tensorflow_hub as hub\n        import bentoml\n\n        def _plus_one_model_tf2():\n            obj = tf.train.Checkpoint()\n\n            @tf.function(input_signature=[tf.TensorSpec(None, dtype=tf.float32)])\n            def plus_one(x):\n                return x + 1\n\n            obj.__call__ = plus_one\n            return obj\n\n        # then save the given model to BentoML modelstore:\n        model = _plus_one_model_tf2()\n        tag = bentoml.tensorflow.import_from_tfhub(model)\n    '
    if (hub is None):
        raise MissingDependencyException('        `tensorflow_hub` does not exists.\n        Make sure to `pip install --upgrade tensorflow_hub` before using.\n        ')
    context: t.Dict[(str, t.Any)] = {'framework_name': 'tensorflow', 'pip_dependencies': [f'tensorflow=={get_tf_version()}', f"tensorflow_hub=={importlib_metadata.version('tensorflow_hub')}"], 'import_from_tfhub': True}
    if (name is None):
        if isinstance(identifier, str):
            name = _clean_name(identifier)
        else:
            name = f'{identifier.__class__.__name__}_{uuid.uuid4().hex[:5].upper()}'
    with bentoml.models.create(name, module=MODULE_NAME, options=None, context=context, metadata=metadata, labels=labels, custom_objects=custom_objects) as _model:
        if isinstance(identifier, str):
            current_cache_dir = os.environ.get('TFHUB_CACHE_DIR')
            os.environ['TFHUB_CACHE_DIR'] = _model.path
            fpath: str = resolve(identifier)
            folder = fpath.split('/')[(- 1)]
            _model.info.options = {'model': identifier, 'local_path': folder}
            if (current_cache_dir is not None):
                os.environ['TFHUB_CACHE_DIR'] = current_cache_dir
        else:
            if hasattr(identifier, 'export'):
                with tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph()) as sess:
                    sess.run(tf.compat.v1.global_variables_initializer())
                    identifier.export(_model.path, sess)
            else:
                tf.saved_model.save(identifier, _model.path)
            _model.info.options = {'model': identifier.__class__.__name__, 'local_path': '.'}
        return _model.tag
Import a model from `Tensorflow Hub <https://tfhub.dev/>`_ to BentoML modelstore.

Args:
    identifier (:code:`Union[str, tensorflow_hub.Module, tensorflow_hub.KerasLayer]`): Identifier accepts
        two type of inputs:
            - if `type` of :code:`identifier` either of type :code:`tensorflow_hub.Module` (**legacy** `tensorflow_hub`) or :code:`tensorflow_hub.KerasLayer` (`tensorflow_hub`), then we will save the given model to a :code:`SavedModel` format.
            - if `type` of :code:`identifier` is a :obj:`str`, we assume that this is the URI retrieved from Tensorflow Hub. We then clean the given URI, and get a local copy of a given model to BentoML modelstore. name (:code:`str`, `optional`, defaults to `None`): An optional name for the model. If :code:`identifier` is a :obj:`str`, then name can be autogenerated from the given URI.
    name (:code:`str`, `optional`, default to `None`):
        Optional name for the saved model. If None, then name will be generated from :code:`identifier`.
    labels (:code:`Dict[str, str]`, `optional`, default to :code:`None`):
        user-defined labels for managing models, e.g. team=nlp, stage=dev
    custom_objects (:code:`Dict[str, Any]]`, `optional`, default to :code:`None`):
        user-defined additional python objects to be saved alongside the model,
        e.g. a tokenizer instance, preprocessor function, model configuration json
    metadata (:code:`Dict[str, Any]`, `optional`,  default to :code:`None`):
        Custom metadata for given model.
    model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):
        BentoML modelstore, provided by DI Container.

Returns:
    :obj:`~bentoml.Tag`: A :obj:`~bentoml.Tag` object that can be used to retrieve the model with :func:`bentoml.tensorflow.load`:

Example for importing a model from Tensorflow Hub:

.. code-block:: python

    import tensorflow_text as text # noqa # pylint: disable
    import bentoml

    tag = bentoml.tensorflow.import_from_tfhub("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3")

    # load model back with `load`:
    model = bentoml.tensorflow.load(tag, load_as_hub_module=True)


Example for importing a custom Tensorflow Hub model:

.. code-block:: python

    import tensorflow as tf
    import tensorflow_hub as hub
    import bentoml

    def _plus_one_model_tf2():
        obj = tf.train.Checkpoint()

        @tf.function(input_signature=[tf.TensorSpec(None, dtype=tf.float32)])
        def plus_one(x):
            return x + 1

        obj.__call__ = plus_one
        return obj

    # then save the given model to BentoML modelstore:
    model = _plus_one_model_tf2()
    tag = bentoml.tensorflow.import_from_tfhub(model)
@inject
def import_from_tfhub(identifier: t.Union[(str, 'HubModule', 'KerasLayer')], name: t.Optional[str]=None, labels: t.Optional[t.Dict[(str, str)]]=None, custom_objects: t.Optional[t.Dict[(str, t.Any)]]=None, metadata: t.Optional[t.Dict[(str, t.Any)]]=None, model_store: 'ModelStore'=Provide[BentoMLContainer.model_store]) -> Tag:
    '\n    Import a model from `Tensorflow Hub <https://tfhub.dev/>`_ to BentoML modelstore.\n\n    Args:\n        identifier (:code:`Union[str, tensorflow_hub.Module, tensorflow_hub.KerasLayer]`): Identifier accepts\n            two type of inputs:\n                - if `type` of :code:`identifier` either of type :code:`tensorflow_hub.Module` (**legacy** `tensorflow_hub`) or :code:`tensorflow_hub.KerasLayer` (`tensorflow_hub`), then we will save the given model to a :code:`SavedModel` format.\n                - if `type` of :code:`identifier` is a :obj:`str`, we assume that this is the URI retrieved from Tensorflow Hub. We then clean the given URI, and get a local copy of a given model to BentoML modelstore. name (:code:`str`, `optional`, defaults to `None`): An optional name for the model. If :code:`identifier` is a :obj:`str`, then name can be autogenerated from the given URI.\n        name (:code:`str`, `optional`, default to `None`):\n            Optional name for the saved model. If None, then name will be generated from :code:`identifier`.\n        labels (:code:`Dict[str, str]`, `optional`, default to :code:`None`):\n            user-defined labels for managing models, e.g. team=nlp, stage=dev\n        custom_objects (:code:`Dict[str, Any]]`, `optional`, default to :code:`None`):\n            user-defined additional python objects to be saved alongside the model,\n            e.g. a tokenizer instance, preprocessor function, model configuration json\n        metadata (:code:`Dict[str, Any]`, `optional`,  default to :code:`None`):\n            Custom metadata for given model.\n        model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n            BentoML modelstore, provided by DI Container.\n\n    Returns:\n        :obj:`~bentoml.Tag`: A :obj:`~bentoml.Tag` object that can be used to retrieve the model with :func:`bentoml.tensorflow.load`:\n\n    Example for importing a model from Tensorflow Hub:\n\n    .. code-block:: python\n\n        import tensorflow_text as text # noqa # pylint: disable\n        import bentoml\n\n        tag = bentoml.tensorflow.import_from_tfhub("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3")\n\n        # load model back with `load`:\n        model = bentoml.tensorflow.load(tag, load_as_hub_module=True)\n\n\n    Example for importing a custom Tensorflow Hub model:\n\n    .. code-block:: python\n\n        import tensorflow as tf\n        import tensorflow_hub as hub\n        import bentoml\n\n        def _plus_one_model_tf2():\n            obj = tf.train.Checkpoint()\n\n            @tf.function(input_signature=[tf.TensorSpec(None, dtype=tf.float32)])\n            def plus_one(x):\n                return x + 1\n\n            obj.__call__ = plus_one\n            return obj\n\n        # then save the given model to BentoML modelstore:\n        model = _plus_one_model_tf2()\n        tag = bentoml.tensorflow.import_from_tfhub(model)\n    '
    if (hub is None):
        raise MissingDependencyException('        `tensorflow_hub` does not exists.\n        Make sure to `pip install --upgrade tensorflow_hub` before using.\n        ')
    context: t.Dict[(str, t.Any)] = {'framework_name': 'tensorflow', 'pip_dependencies': [f'tensorflow=={get_tf_version()}', f"tensorflow_hub=={importlib_metadata.version('tensorflow_hub')}"], 'import_from_tfhub': True}
    if (name is None):
        if isinstance(identifier, str):
            name = _clean_name(identifier)
        else:
            name = f'{identifier.__class__.__name__}_{uuid.uuid4().hex[:5].upper()}'
    with bentoml.models.create(name, module=MODULE_NAME, options=None, context=context, metadata=metadata, labels=labels, custom_objects=custom_objects) as _model:
        if isinstance(identifier, str):
            current_cache_dir = os.environ.get('TFHUB_CACHE_DIR')
            os.environ['TFHUB_CACHE_DIR'] = _model.path
            fpath: str = resolve(identifier)
            folder = fpath.split('/')[(- 1)]
            _model.info.options = {'model': identifier, 'local_path': folder}
            if (current_cache_dir is not None):
                os.environ['TFHUB_CACHE_DIR'] = current_cache_dir
        else:
            if hasattr(identifier, 'export'):
                with tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph()) as sess:
                    sess.run(tf.compat.v1.global_variables_initializer())
                    identifier.export(_model.path, sess)
            else:
                tf.saved_model.save(identifier, _model.path)
            _model.info.options = {'model': identifier.__class__.__name__, 'local_path': '.'}
        return _model.tag