Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
WLEDFlowHandler.async_step_zeroconf_confirm
( self, user_input: ConfigType = None )
Handle a flow initiated by zeroconf.
Handle a flow initiated by zeroconf.
async def async_step_zeroconf_confirm( self, user_input: ConfigType = None ) -> Dict[str, Any]: """Handle a flow initiated by zeroconf.""" return await self._handle_config_flow(user_input)
[ "async", "def", "async_step_zeroconf_confirm", "(", "self", ",", "user_input", ":", "ConfigType", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "await", "self", ".", "_handle_config_flow", "(", "user_input", ")" ]
[ 54, 4 ]
[ 58, 57 ]
python
en
['en', 'en', 'en']
True
WLEDFlowHandler._handle_config_flow
( self, user_input: Optional[ConfigType] = None, prepare: bool = False )
Config flow handler for WLED.
Config flow handler for WLED.
async def _handle_config_flow( self, user_input: Optional[ConfigType] = None, prepare: bool = False ) -> Dict[str, Any]: """Config flow handler for WLED.""" # pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167 source = self.context.get("source") # Request user input, unless we are preparing discovery flow if user_input is None and not prepare: if source == SOURCE_ZEROCONF: return self._show_confirm_dialog() return self._show_setup_form() if source == SOURCE_ZEROCONF: # pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167 user_input[CONF_HOST] = self.context.get(CONF_HOST) user_input[CONF_MAC] = self.context.get(CONF_MAC) if user_input.get(CONF_MAC) is None or not prepare: session = async_get_clientsession(self.hass) wled = WLED(user_input[CONF_HOST], session=session) try: device = await wled.update() except WLEDConnectionError: if source == SOURCE_ZEROCONF: return self.async_abort(reason="cannot_connect") return self._show_setup_form({"base": "cannot_connect"}) user_input[CONF_MAC] = device.info.mac_address # Check if already configured await self.async_set_unique_id(user_input[CONF_MAC]) self._abort_if_unique_id_configured(updates={CONF_HOST: user_input[CONF_HOST]}) title = user_input[CONF_HOST] if source == SOURCE_ZEROCONF: # pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167 title = self.context.get(CONF_NAME) if prepare: return await self.async_step_zeroconf_confirm() return self.async_create_entry( title=title, data={CONF_HOST: user_input[CONF_HOST], CONF_MAC: user_input[CONF_MAC]}, )
[ "async", "def", "_handle_config_flow", "(", "self", ",", "user_input", ":", "Optional", "[", "ConfigType", "]", "=", "None", ",", "prepare", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167", "source", "=", "self", ".", "context", ".", "get", "(", "\"source\"", ")", "# Request user input, unless we are preparing discovery flow", "if", "user_input", "is", "None", "and", "not", "prepare", ":", "if", "source", "==", "SOURCE_ZEROCONF", ":", "return", "self", ".", "_show_confirm_dialog", "(", ")", "return", "self", ".", "_show_setup_form", "(", ")", "if", "source", "==", "SOURCE_ZEROCONF", ":", "# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167", "user_input", "[", "CONF_HOST", "]", "=", "self", ".", "context", ".", "get", "(", "CONF_HOST", ")", "user_input", "[", "CONF_MAC", "]", "=", "self", ".", "context", ".", "get", "(", "CONF_MAC", ")", "if", "user_input", ".", "get", "(", "CONF_MAC", ")", "is", "None", "or", "not", "prepare", ":", "session", "=", "async_get_clientsession", "(", "self", ".", "hass", ")", "wled", "=", "WLED", "(", "user_input", "[", "CONF_HOST", "]", ",", "session", "=", "session", ")", "try", ":", "device", "=", "await", "wled", ".", "update", "(", ")", "except", "WLEDConnectionError", ":", "if", "source", "==", "SOURCE_ZEROCONF", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"cannot_connect\"", ")", "return", "self", ".", "_show_setup_form", "(", "{", "\"base\"", ":", "\"cannot_connect\"", "}", ")", "user_input", "[", "CONF_MAC", "]", "=", "device", ".", "info", ".", "mac_address", "# Check if already configured", "await", "self", ".", "async_set_unique_id", "(", "user_input", "[", "CONF_MAC", "]", ")", "self", ".", "_abort_if_unique_id_configured", "(", "updates", "=", "{", "CONF_HOST", ":", "user_input", "[", "CONF_HOST", "]", "}", ")", "title", "=", "user_input", "[", "CONF_HOST", "]", "if", "source", "==", "SOURCE_ZEROCONF", ":", "# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167", "title", "=", "self", ".", "context", ".", "get", "(", "CONF_NAME", ")", "if", "prepare", ":", "return", "await", "self", ".", "async_step_zeroconf_confirm", "(", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "title", ",", "data", "=", "{", "CONF_HOST", ":", "user_input", "[", "CONF_HOST", "]", ",", "CONF_MAC", ":", "user_input", "[", "CONF_MAC", "]", "}", ",", ")" ]
[ 60, 4 ]
[ 104, 9 ]
python
da
['da', 'da', 'en']
True
WLEDFlowHandler._show_setup_form
(self, errors: Optional[Dict] = None)
Show the setup form to the user.
Show the setup form to the user.
def _show_setup_form(self, errors: Optional[Dict] = None) -> Dict[str, Any]: """Show the setup form to the user.""" return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required(CONF_HOST): str}), errors=errors or {}, )
[ "def", "_show_setup_form", "(", "self", ",", "errors", ":", "Optional", "[", "Dict", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_HOST", ")", ":", "str", "}", ")", ",", "errors", "=", "errors", "or", "{", "}", ",", ")" ]
[ 106, 4 ]
[ 112, 9 ]
python
en
['en', 'en', 'en']
True
WLEDFlowHandler._show_confirm_dialog
(self, errors: Optional[Dict] = None)
Show the confirm dialog to the user.
Show the confirm dialog to the user.
def _show_confirm_dialog(self, errors: Optional[Dict] = None) -> Dict[str, Any]: """Show the confirm dialog to the user.""" # pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167 name = self.context.get(CONF_NAME) return self.async_show_form( step_id="zeroconf_confirm", description_placeholders={"name": name}, errors=errors or {}, )
[ "def", "_show_confirm_dialog", "(", "self", ",", "errors", ":", "Optional", "[", "Dict", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167", "name", "=", "self", ".", "context", ".", "get", "(", "CONF_NAME", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"zeroconf_confirm\"", ",", "description_placeholders", "=", "{", "\"name\"", ":", "name", "}", ",", "errors", "=", "errors", "or", "{", "}", ",", ")" ]
[ 114, 4 ]
[ 122, 9 ]
python
en
['en', 'en', 'en']
True
AutoModel.from_config
(cls, config)
r""" Instantiates one of the base model classes of the library from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModel.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModel >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModel.from_config(config)
r""" Instantiates one of the base model classes of the library from a configuration.
def from_config(cls, config): r""" Instantiates one of the base model classes of the library from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModel.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModel >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModel.from_config(config) """ if type(config) in MODEL_MAPPING.keys(): return MODEL_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_MAPPING.keys()) ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 751, 4 ]
[ 779, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModel.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModel >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModel.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModel.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModel.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r"""
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModel >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModel.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModel.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModel.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_MAPPING.keys(): return MODEL_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_MAPPING.keys()) ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 787, 4 ]
[ 821, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForPreTraining.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with the architecture used for pretraining this model---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForPreTraining.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForPreTraining >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForPreTraining.from_config(config)
r""" Instantiates one of the model classes of the library---with the architecture used for pretraining this model---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with the architecture used for pretraining this model---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForPreTraining.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForPreTraining >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForPreTraining.from_config(config) """ if type(config) in MODEL_FOR_PRETRAINING_MAPPING.keys(): return MODEL_FOR_PRETRAINING_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_PRETRAINING_MAPPING.keys()) ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_PRETRAINING_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_PRETRAINING_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_PRETRAINING_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 843, 4 ]
[ 873, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForPreTraining.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForPreTraining >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForPreTraining.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForPreTraining.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForPreTraining.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForPreTraining >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForPreTraining.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForPreTraining.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForPreTraining.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_PRETRAINING_MAPPING.keys(): return MODEL_FOR_PRETRAINING_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_PRETRAINING_MAPPING.keys()) ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_PRETRAINING_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_PRETRAINING_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_PRETRAINING_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 882, 4 ]
[ 915, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelWithLMHead.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a language modeling head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelWithLMHead.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelWithLMHead >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelWithLMHead.from_config(config)
r""" Instantiates one of the model classes of the library---with a language modeling head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a language modeling head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelWithLMHead.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelWithLMHead >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelWithLMHead.from_config(config) """ warnings.warn( "The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use " "`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and " "`AutoModelForSeq2SeqLM` for encoder-decoder models.", FutureWarning, ) if type(config) in MODEL_WITH_LM_HEAD_MAPPING.keys(): return MODEL_WITH_LM_HEAD_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_WITH_LM_HEAD_MAPPING.keys()) ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "warnings", ".", "warn", "(", "\"The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use \"", "\"`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and \"", "\"`AutoModelForSeq2SeqLM` for encoder-decoder models.\"", ",", "FutureWarning", ",", ")", "if", "type", "(", "config", ")", "in", "MODEL_WITH_LM_HEAD_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_WITH_LM_HEAD_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_WITH_LM_HEAD_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 943, 4 ]
[ 978, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelWithLMHead.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelWithLMHead >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelWithLMHead.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelWithLMHead.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelWithLMHead.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelWithLMHead >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelWithLMHead.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelWithLMHead.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelWithLMHead.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ warnings.warn( "The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use " "`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and " "`AutoModelForSeq2SeqLM` for encoder-decoder models.", FutureWarning, ) config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_WITH_LM_HEAD_MAPPING.keys(): return MODEL_WITH_LM_HEAD_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_WITH_LM_HEAD_MAPPING.keys()) ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use \"", "\"`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and \"", "\"`AutoModelForSeq2SeqLM` for encoder-decoder models.\"", ",", "FutureWarning", ",", ")", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_WITH_LM_HEAD_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_WITH_LM_HEAD_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_WITH_LM_HEAD_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 987, 4 ]
[ 1026, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForCausalLM.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a causal language modeling head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForCausalLM.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForCausalLM >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('gpt2') >>> model = AutoModelForCausalLM.from_config(config)
r""" Instantiates one of the model classes of the library---with a causal language modeling head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a causal language modeling head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForCausalLM.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForCausalLM >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('gpt2') >>> model = AutoModelForCausalLM.from_config(config) """ if type(config) in MODEL_FOR_CAUSAL_LM_MAPPING.keys(): return MODEL_FOR_CAUSAL_LM_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_CAUSAL_LM_MAPPING.keys()) ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_CAUSAL_LM_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_CAUSAL_LM_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_CAUSAL_LM_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 1047, 4 ]
[ 1077, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForCausalLM.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForCausalLM >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForCausalLM.from_pretrained('gpt2') >>> # Update configuration during loading >>> model = AutoModelForCausalLM.from_pretrained('gpt2', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/gpt2_tf_model_config.json') >>> model = AutoModelForCausalLM.from_pretrained('./tf_model/gpt2_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForCausalLM >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForCausalLM.from_pretrained('gpt2') >>> # Update configuration during loading >>> model = AutoModelForCausalLM.from_pretrained('gpt2', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/gpt2_tf_model_config.json') >>> model = AutoModelForCausalLM.from_pretrained('./tf_model/gpt2_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_CAUSAL_LM_MAPPING.keys(): return MODEL_FOR_CAUSAL_LM_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_CAUSAL_LM_MAPPING.keys()) ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_CAUSAL_LM_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_CAUSAL_LM_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_CAUSAL_LM_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 1086, 4 ]
[ 1119, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForMaskedLM.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a masked language modeling head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForMaskedLM.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForMaskedLM >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForMaskedLM.from_config(config)
r""" Instantiates one of the model classes of the library---with a masked language modeling head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a masked language modeling head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForMaskedLM.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForMaskedLM >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForMaskedLM.from_config(config) """ if type(config) in MODEL_FOR_MASKED_LM_MAPPING.keys(): return MODEL_FOR_MASKED_LM_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_MASKED_LM_MAPPING.keys()) ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_MASKED_LM_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_MASKED_LM_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_MASKED_LM_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 1140, 4 ]
[ 1170, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForMaskedLM.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForMaskedLM >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForMaskedLM.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForMaskedLM.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForMaskedLM.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForMaskedLM >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForMaskedLM.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForMaskedLM.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForMaskedLM.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_MASKED_LM_MAPPING.keys(): return MODEL_FOR_MASKED_LM_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_MASKED_LM_MAPPING.keys()) ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_MASKED_LM_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_MASKED_LM_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_MASKED_LM_MAPPING", ".", "keys", "(", ")", ")", ")", ")" ]
[ 1179, 4 ]
[ 1212, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForSeq2SeqLM.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a sequence-to-sequence language modeling head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForSeq2SeqLM.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForSeq2SeqLM >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('t5') >>> model = AutoModelForSeq2SeqLM.from_config(config)
r""" Instantiates one of the model classes of the library---with a sequence-to-sequence language modeling head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a sequence-to-sequence language modeling head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForSeq2SeqLM.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForSeq2SeqLM >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('t5') >>> model = AutoModelForSeq2SeqLM.from_config(config) """ if type(config) in MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.keys(): return MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.keys()), ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1234, 4 ]
[ 1266, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForSeq2SeqLM.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForSeq2SeqLM >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForSeq2SeqLM.from_pretrained('t5-base') >>> # Update configuration during loading >>> model = AutoModelForSeq2SeqLM.from_pretrained('t5-base', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/t5_tf_model_config.json') >>> model = AutoModelForSeq2SeqLM.from_pretrained('./tf_model/t5_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForSeq2SeqLM >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForSeq2SeqLM.from_pretrained('t5-base') >>> # Update configuration during loading >>> model = AutoModelForSeq2SeqLM.from_pretrained('t5-base', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/t5_tf_model_config.json') >>> model = AutoModelForSeq2SeqLM.from_pretrained('./tf_model/t5_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.keys(): return MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.keys()), ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1275, 4 ]
[ 1310, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForSequenceClassification.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a sequence classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForSequenceClassification.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForSequenceClassification >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForSequenceClassification.from_config(config)
r""" Instantiates one of the model classes of the library---with a sequence classification head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a sequence classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForSequenceClassification.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForSequenceClassification >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForSequenceClassification.from_config(config) """ if type(config) in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING.keys(): return MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING.keys()), ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1332, 4 ]
[ 1364, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForSequenceClassification.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForSequenceClassification >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForSequenceClassification.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForSequenceClassification >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForSequenceClassification.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING.keys(): return MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING.keys()), ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1373, 4 ]
[ 1408, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForQuestionAnswering.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a question answering head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForQuestionAnswering.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForQuestionAnswering >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForQuestionAnswering.from_config(config)
r""" Instantiates one of the model classes of the library---with a question answering head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a question answering head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForQuestionAnswering.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForQuestionAnswering >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForQuestionAnswering.from_config(config) """ if type(config) in MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys(): return MODEL_FOR_QUESTION_ANSWERING_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()), ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_QUESTION_ANSWERING_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_QUESTION_ANSWERING_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_QUESTION_ANSWERING_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1429, 4 ]
[ 1461, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForQuestionAnswering.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForQuestionAnswering >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForQuestionAnswering.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForQuestionAnswering.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForQuestionAnswering.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForQuestionAnswering >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForQuestionAnswering.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForQuestionAnswering.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForQuestionAnswering.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys(): return MODEL_FOR_QUESTION_ANSWERING_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()), ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_QUESTION_ANSWERING_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_QUESTION_ANSWERING_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_QUESTION_ANSWERING_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1470, 4 ]
[ 1506, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForTableQuestionAnswering.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a table question answering head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForTableQuestionAnswering.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForTableQuestionAnswering >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('google/tapas-base-finetuned-wtq') >>> model = AutoModelForTableQuestionAnswering.from_config(config)
r""" Instantiates one of the model classes of the library---with a table question answering head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a table question answering head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForTableQuestionAnswering.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForTableQuestionAnswering >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('google/tapas-base-finetuned-wtq') >>> model = AutoModelForTableQuestionAnswering.from_config(config) """ if type(config) in MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.keys(): return MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.keys()), ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1528, 4 ]
[ 1561, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForTableQuestionAnswering.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForTableQuestionAnswering >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForTableQuestionAnswering.from_pretrained('google/tapas-base-finetuned-wtq') >>> # Update configuration during loading >>> model = AutoModelForTableQuestionAnswering.from_pretrained('google/tapas-base-finetuned-wtq', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/tapas_tf_checkpoint.json') >>> model = AutoModelForQuestionAnswering.from_pretrained('./tf_model/tapas_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForTableQuestionAnswering >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForTableQuestionAnswering.from_pretrained('google/tapas-base-finetuned-wtq') >>> # Update configuration during loading >>> model = AutoModelForTableQuestionAnswering.from_pretrained('google/tapas-base-finetuned-wtq', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/tapas_tf_checkpoint.json') >>> model = AutoModelForQuestionAnswering.from_pretrained('./tf_model/tapas_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.keys(): return MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.keys()), ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1570, 4 ]
[ 1606, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForTokenClassification.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a token classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForTokenClassification.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForTokenClassification >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForTokenClassification.from_config(config)
r""" Instantiates one of the model classes of the library---with a token classification head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a token classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForTokenClassification.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForTokenClassification >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForTokenClassification.from_config(config) """ if type(config) in MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.keys(): return MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.keys()), ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1627, 4 ]
[ 1659, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForTokenClassification.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForTokenClassification >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForTokenClassification.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForTokenClassification.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForTokenClassification.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForTokenClassification >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForTokenClassification.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForTokenClassification.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForTokenClassification.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.keys(): return MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.keys()), ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1668, 4 ]
[ 1704, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForMultipleChoice.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a multiple choice classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForMultipleChoice.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForMultipleChoice >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForMultipleChoice.from_config(config)
r""" Instantiates one of the model classes of the library---with a multiple choice classification head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a multiple choice classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForMultipleChoice.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForMultipleChoice >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForMultipleChoice.from_config(config) """ if type(config) in MODEL_FOR_MULTIPLE_CHOICE_MAPPING.keys(): return MODEL_FOR_MULTIPLE_CHOICE_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_MULTIPLE_CHOICE_MAPPING.keys()), ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1726, 4 ]
[ 1759, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForMultipleChoice.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForMultipleChoice >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForMultipleChoice.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForMultipleChoice.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForMultipleChoice.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForMultipleChoice >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForMultipleChoice.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForMultipleChoice.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForMultipleChoice.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_MULTIPLE_CHOICE_MAPPING.keys(): return MODEL_FOR_MULTIPLE_CHOICE_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_MULTIPLE_CHOICE_MAPPING.keys()), ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1768, 4 ]
[ 1804, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForNextSentencePrediction.from_config
(cls, config)
r""" Instantiates one of the model classes of the library---with a multiple choice classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForNextSentencePrediction.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForNextSentencePrediction >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForNextSentencePrediction.from_config(config)
r""" Instantiates one of the model classes of the library---with a multiple choice classification head---from a configuration.
def from_config(cls, config): r""" Instantiates one of the model classes of the library---with a multiple choice classification head---from a configuration. Note: Loading a model from its configuration file does **not** load the model weights. It only affects the model's configuration. Use :meth:`~transformers.AutoModelForNextSentencePrediction.from_pretrained` to load the model weights. Args: config (:class:`~transformers.PretrainedConfig`): The model class to instantiate is selected based on the configuration class: List options Examples:: >>> from transformers import AutoConfig, AutoModelForNextSentencePrediction >>> # Download configuration from huggingface.co and cache. >>> config = AutoConfig.from_pretrained('bert-base-uncased') >>> model = AutoModelForNextSentencePrediction.from_config(config) """ if type(config) in MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING.keys(): return MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING[type(config)](config) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING.keys()), ) )
[ "def", "from_config", "(", "cls", ",", "config", ")", ":", "if", "type", "(", "config", ")", "in", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", "[", "type", "(", "config", ")", "]", "(", "config", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1826, 4 ]
[ 1859, 9 ]
python
cy
['en', 'cy', 'hi']
False
AutoModelForNextSentencePrediction.from_pretrained
(cls, pretrained_model_name_or_path, *model_args, **kwargs)
r""" Examples:: >>> from transformers import AutoConfig, AutoModelForNextSentencePrediction >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForNextSentencePrediction.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForNextSentencePrediction.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForNextSentencePrediction.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
r""" Examples::
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Examples:: >>> from transformers import AutoConfig, AutoModelForNextSentencePrediction >>> # Download model and configuration from huggingface.co and cache. >>> model = AutoModelForNextSentencePrediction.from_pretrained('bert-base-uncased') >>> # Update configuration during loading >>> model = AutoModelForNextSentencePrediction.from_pretrained('bert-base-uncased', output_attentions=True) >>> model.config.output_attentions True >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower) >>> config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json') >>> model = AutoModelForNextSentencePrediction.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config) """ config = kwargs.pop("config", None) if not isinstance(config, PretrainedConfig): config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) if type(config) in MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING.keys(): return MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING[type(config)].from_pretrained( pretrained_model_name_or_path, *model_args, config=config, **kwargs ) raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING.keys()), ) )
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "kwargs", ".", "pop", "(", "\"config\"", ",", "None", ")", "if", "not", "isinstance", "(", "config", ",", "PretrainedConfig", ")", ":", "config", ",", "kwargs", "=", "AutoConfig", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "return_unused_kwargs", "=", "True", ",", "*", "*", "kwargs", ")", "if", "type", "(", "config", ")", "in", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", ".", "keys", "(", ")", ":", "return", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", "[", "type", "(", "config", ")", "]", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "model_args", ",", "config", "=", "config", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"Unrecognized configuration class {} for this kind of AutoModel: {}.\\n\"", "\"Model type should be one of {}.\"", ".", "format", "(", "config", ".", "__class__", ",", "cls", ".", "__name__", ",", "\", \"", ".", "join", "(", "c", ".", "__name__", "for", "c", "in", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", ".", "keys", "(", ")", ")", ",", ")", ")" ]
[ 1868, 4 ]
[ 1904, 9 ]
python
cy
['en', 'cy', 'hi']
False
setup_androidtv
(hass, config)
Generate an ADB key (if needed) and load it.
Generate an ADB key (if needed) and load it.
def setup_androidtv(hass, config): """Generate an ADB key (if needed) and load it.""" adbkey = config.get(CONF_ADBKEY, hass.config.path(STORAGE_DIR, "androidtv_adbkey")) if CONF_ADB_SERVER_IP not in config: # Use "adb_shell" (Python ADB implementation) if not os.path.isfile(adbkey): # Generate ADB key files keygen(adbkey) # Load the ADB key signer = ADBPythonSync.load_adbkey(adbkey) adb_log = f"using Python ADB implementation with adbkey='{adbkey}'" else: # Use "pure-python-adb" (communicate with ADB server) signer = None adb_log = f"using ADB server at {config[CONF_ADB_SERVER_IP]}:{config[CONF_ADB_SERVER_PORT]}" return adbkey, signer, adb_log
[ "def", "setup_androidtv", "(", "hass", ",", "config", ")", ":", "adbkey", "=", "config", ".", "get", "(", "CONF_ADBKEY", ",", "hass", ".", "config", ".", "path", "(", "STORAGE_DIR", ",", "\"androidtv_adbkey\"", ")", ")", "if", "CONF_ADB_SERVER_IP", "not", "in", "config", ":", "# Use \"adb_shell\" (Python ADB implementation)", "if", "not", "os", ".", "path", ".", "isfile", "(", "adbkey", ")", ":", "# Generate ADB key files", "keygen", "(", "adbkey", ")", "# Load the ADB key", "signer", "=", "ADBPythonSync", ".", "load_adbkey", "(", "adbkey", ")", "adb_log", "=", "f\"using Python ADB implementation with adbkey='{adbkey}'\"", "else", ":", "# Use \"pure-python-adb\" (communicate with ADB server)", "signer", "=", "None", "adb_log", "=", "f\"using ADB server at {config[CONF_ADB_SERVER_IP]}:{config[CONF_ADB_SERVER_PORT]}\"", "return", "adbkey", ",", "signer", ",", "adb_log" ]
[ 168, 0 ]
[ 186, 34 ]
python
en
['en', 'en', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the Android TV / Fire TV platform.
Set up the Android TV / Fire TV platform.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Android TV / Fire TV platform.""" hass.data.setdefault(ANDROIDTV_DOMAIN, {}) address = f"{config[CONF_HOST]}:{config[CONF_PORT]}" if address in hass.data[ANDROIDTV_DOMAIN]: _LOGGER.warning("Platform already setup on %s, skipping", address) return adbkey, signer, adb_log = await hass.async_add_executor_job( setup_androidtv, hass, config ) aftv = await setup( config[CONF_HOST], config[CONF_PORT], adbkey, config.get(CONF_ADB_SERVER_IP, ""), config[CONF_ADB_SERVER_PORT], config[CONF_STATE_DETECTION_RULES], config[CONF_DEVICE_CLASS], 10.0, signer, ) if not aftv.available: # Determine the name that will be used for the device in the log if CONF_NAME in config: device_name = config[CONF_NAME] elif config[CONF_DEVICE_CLASS] == DEVICE_ANDROIDTV: device_name = "Android TV device" elif config[CONF_DEVICE_CLASS] == DEVICE_FIRETV: device_name = "Fire TV device" else: device_name = "Android TV / Fire TV device" _LOGGER.warning( "Could not connect to %s at %s %s", device_name, address, adb_log ) raise PlatformNotReady async def _async_close(event): """Close the ADB socket connection when HA stops.""" await aftv.adb_close() # Close the ADB connection when HA stops hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_close) device_args = [ aftv, config[CONF_NAME], config[CONF_APPS], config[CONF_GET_SOURCES], config.get(CONF_TURN_ON_COMMAND), config.get(CONF_TURN_OFF_COMMAND), config[CONF_EXCLUDE_UNNAMED_APPS], config[CONF_SCREENCAP], ] if aftv.DEVICE_CLASS == DEVICE_ANDROIDTV: device = AndroidTVDevice(*device_args) device_name = config.get(CONF_NAME, "Android TV") else: device = FireTVDevice(*device_args) device_name = config.get(CONF_NAME, "Fire TV") async_add_entities([device]) _LOGGER.debug("Setup %s at %s %s", device_name, address, adb_log) hass.data[ANDROIDTV_DOMAIN][address] = device if hass.services.has_service(ANDROIDTV_DOMAIN, SERVICE_ADB_COMMAND): return platform = entity_platform.current_platform.get() async def service_adb_command(service): """Dispatch service calls to target entities.""" cmd = service.data[ATTR_COMMAND] entity_id = service.data[ATTR_ENTITY_ID] target_devices = [ dev for dev in hass.data[ANDROIDTV_DOMAIN].values() if dev.entity_id in entity_id ] for target_device in target_devices: output = await target_device.adb_command(cmd) # log the output, if there is any if output: _LOGGER.info( "Output of command '%s' from '%s': %s", cmd, target_device.entity_id, output, ) hass.services.async_register( ANDROIDTV_DOMAIN, SERVICE_ADB_COMMAND, service_adb_command, schema=SERVICE_ADB_COMMAND_SCHEMA, ) platform.async_register_entity_service( SERVICE_LEARN_SENDEVENT, {}, "learn_sendevent" ) async def service_download(service): """Download a file from your Android TV / Fire TV device to your Home Assistant instance.""" local_path = service.data[ATTR_LOCAL_PATH] if not hass.config.is_allowed_path(local_path): _LOGGER.warning("'%s' is not secure to load data from!", local_path) return device_path = service.data[ATTR_DEVICE_PATH] entity_id = service.data[ATTR_ENTITY_ID] target_device = [ dev for dev in hass.data[ANDROIDTV_DOMAIN].values() if dev.entity_id in entity_id ][0] await target_device.adb_pull(local_path, device_path) hass.services.async_register( ANDROIDTV_DOMAIN, SERVICE_DOWNLOAD, service_download, schema=SERVICE_DOWNLOAD_SCHEMA, ) async def service_upload(service): """Upload a file from your Home Assistant instance to an Android TV / Fire TV device.""" local_path = service.data[ATTR_LOCAL_PATH] if not hass.config.is_allowed_path(local_path): _LOGGER.warning("'%s' is not secure to load data from!", local_path) return device_path = service.data[ATTR_DEVICE_PATH] entity_id = service.data[ATTR_ENTITY_ID] target_devices = [ dev for dev in hass.data[ANDROIDTV_DOMAIN].values() if dev.entity_id in entity_id ] for target_device in target_devices: await target_device.adb_push(local_path, device_path) hass.services.async_register( ANDROIDTV_DOMAIN, SERVICE_UPLOAD, service_upload, schema=SERVICE_UPLOAD_SCHEMA )
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "hass", ".", "data", ".", "setdefault", "(", "ANDROIDTV_DOMAIN", ",", "{", "}", ")", "address", "=", "f\"{config[CONF_HOST]}:{config[CONF_PORT]}\"", "if", "address", "in", "hass", ".", "data", "[", "ANDROIDTV_DOMAIN", "]", ":", "_LOGGER", ".", "warning", "(", "\"Platform already setup on %s, skipping\"", ",", "address", ")", "return", "adbkey", ",", "signer", ",", "adb_log", "=", "await", "hass", ".", "async_add_executor_job", "(", "setup_androidtv", ",", "hass", ",", "config", ")", "aftv", "=", "await", "setup", "(", "config", "[", "CONF_HOST", "]", ",", "config", "[", "CONF_PORT", "]", ",", "adbkey", ",", "config", ".", "get", "(", "CONF_ADB_SERVER_IP", ",", "\"\"", ")", ",", "config", "[", "CONF_ADB_SERVER_PORT", "]", ",", "config", "[", "CONF_STATE_DETECTION_RULES", "]", ",", "config", "[", "CONF_DEVICE_CLASS", "]", ",", "10.0", ",", "signer", ",", ")", "if", "not", "aftv", ".", "available", ":", "# Determine the name that will be used for the device in the log", "if", "CONF_NAME", "in", "config", ":", "device_name", "=", "config", "[", "CONF_NAME", "]", "elif", "config", "[", "CONF_DEVICE_CLASS", "]", "==", "DEVICE_ANDROIDTV", ":", "device_name", "=", "\"Android TV device\"", "elif", "config", "[", "CONF_DEVICE_CLASS", "]", "==", "DEVICE_FIRETV", ":", "device_name", "=", "\"Fire TV device\"", "else", ":", "device_name", "=", "\"Android TV / Fire TV device\"", "_LOGGER", ".", "warning", "(", "\"Could not connect to %s at %s %s\"", ",", "device_name", ",", "address", ",", "adb_log", ")", "raise", "PlatformNotReady", "async", "def", "_async_close", "(", "event", ")", ":", "\"\"\"Close the ADB socket connection when HA stops.\"\"\"", "await", "aftv", ".", "adb_close", "(", ")", "# Close the ADB connection when HA stops", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "_async_close", ")", "device_args", "=", "[", "aftv", ",", "config", "[", "CONF_NAME", "]", ",", "config", "[", "CONF_APPS", "]", ",", "config", "[", "CONF_GET_SOURCES", "]", ",", "config", ".", "get", "(", "CONF_TURN_ON_COMMAND", ")", ",", "config", ".", "get", "(", "CONF_TURN_OFF_COMMAND", ")", ",", "config", "[", "CONF_EXCLUDE_UNNAMED_APPS", "]", ",", "config", "[", "CONF_SCREENCAP", "]", ",", "]", "if", "aftv", ".", "DEVICE_CLASS", "==", "DEVICE_ANDROIDTV", ":", "device", "=", "AndroidTVDevice", "(", "*", "device_args", ")", "device_name", "=", "config", ".", "get", "(", "CONF_NAME", ",", "\"Android TV\"", ")", "else", ":", "device", "=", "FireTVDevice", "(", "*", "device_args", ")", "device_name", "=", "config", ".", "get", "(", "CONF_NAME", ",", "\"Fire TV\"", ")", "async_add_entities", "(", "[", "device", "]", ")", "_LOGGER", ".", "debug", "(", "\"Setup %s at %s %s\"", ",", "device_name", ",", "address", ",", "adb_log", ")", "hass", ".", "data", "[", "ANDROIDTV_DOMAIN", "]", "[", "address", "]", "=", "device", "if", "hass", ".", "services", ".", "has_service", "(", "ANDROIDTV_DOMAIN", ",", "SERVICE_ADB_COMMAND", ")", ":", "return", "platform", "=", "entity_platform", ".", "current_platform", ".", "get", "(", ")", "async", "def", "service_adb_command", "(", "service", ")", ":", "\"\"\"Dispatch service calls to target entities.\"\"\"", "cmd", "=", "service", ".", "data", "[", "ATTR_COMMAND", "]", "entity_id", "=", "service", ".", "data", "[", "ATTR_ENTITY_ID", "]", "target_devices", "=", "[", "dev", "for", "dev", "in", "hass", ".", "data", "[", "ANDROIDTV_DOMAIN", "]", ".", "values", "(", ")", "if", "dev", ".", "entity_id", "in", "entity_id", "]", "for", "target_device", "in", "target_devices", ":", "output", "=", "await", "target_device", ".", "adb_command", "(", "cmd", ")", "# log the output, if there is any", "if", "output", ":", "_LOGGER", ".", "info", "(", "\"Output of command '%s' from '%s': %s\"", ",", "cmd", ",", "target_device", ".", "entity_id", ",", "output", ",", ")", "hass", ".", "services", ".", "async_register", "(", "ANDROIDTV_DOMAIN", ",", "SERVICE_ADB_COMMAND", ",", "service_adb_command", ",", "schema", "=", "SERVICE_ADB_COMMAND_SCHEMA", ",", ")", "platform", ".", "async_register_entity_service", "(", "SERVICE_LEARN_SENDEVENT", ",", "{", "}", ",", "\"learn_sendevent\"", ")", "async", "def", "service_download", "(", "service", ")", ":", "\"\"\"Download a file from your Android TV / Fire TV device to your Home Assistant instance.\"\"\"", "local_path", "=", "service", ".", "data", "[", "ATTR_LOCAL_PATH", "]", "if", "not", "hass", ".", "config", ".", "is_allowed_path", "(", "local_path", ")", ":", "_LOGGER", ".", "warning", "(", "\"'%s' is not secure to load data from!\"", ",", "local_path", ")", "return", "device_path", "=", "service", ".", "data", "[", "ATTR_DEVICE_PATH", "]", "entity_id", "=", "service", ".", "data", "[", "ATTR_ENTITY_ID", "]", "target_device", "=", "[", "dev", "for", "dev", "in", "hass", ".", "data", "[", "ANDROIDTV_DOMAIN", "]", ".", "values", "(", ")", "if", "dev", ".", "entity_id", "in", "entity_id", "]", "[", "0", "]", "await", "target_device", ".", "adb_pull", "(", "local_path", ",", "device_path", ")", "hass", ".", "services", ".", "async_register", "(", "ANDROIDTV_DOMAIN", ",", "SERVICE_DOWNLOAD", ",", "service_download", ",", "schema", "=", "SERVICE_DOWNLOAD_SCHEMA", ",", ")", "async", "def", "service_upload", "(", "service", ")", ":", "\"\"\"Upload a file from your Home Assistant instance to an Android TV / Fire TV device.\"\"\"", "local_path", "=", "service", ".", "data", "[", "ATTR_LOCAL_PATH", "]", "if", "not", "hass", ".", "config", ".", "is_allowed_path", "(", "local_path", ")", ":", "_LOGGER", ".", "warning", "(", "\"'%s' is not secure to load data from!\"", ",", "local_path", ")", "return", "device_path", "=", "service", ".", "data", "[", "ATTR_DEVICE_PATH", "]", "entity_id", "=", "service", ".", "data", "[", "ATTR_ENTITY_ID", "]", "target_devices", "=", "[", "dev", "for", "dev", "in", "hass", ".", "data", "[", "ANDROIDTV_DOMAIN", "]", ".", "values", "(", ")", "if", "dev", ".", "entity_id", "in", "entity_id", "]", "for", "target_device", "in", "target_devices", ":", "await", "target_device", ".", "adb_push", "(", "local_path", ",", "device_path", ")", "hass", ".", "services", ".", "async_register", "(", "ANDROIDTV_DOMAIN", ",", "SERVICE_UPLOAD", ",", "service_upload", ",", "schema", "=", "SERVICE_UPLOAD_SCHEMA", ")" ]
[ 189, 0 ]
[ 342, 5 ]
python
en
['en', 'en', 'en']
True
adb_decorator
(override_available=False)
Wrap ADB methods and catch exceptions. Allows for overriding the available status of the ADB connection via the `override_available` parameter.
Wrap ADB methods and catch exceptions.
def adb_decorator(override_available=False): """Wrap ADB methods and catch exceptions. Allows for overriding the available status of the ADB connection via the `override_available` parameter. """ def _adb_decorator(func): """Wrap the provided ADB method and catch exceptions.""" @functools.wraps(func) async def _adb_exception_catcher(self, *args, **kwargs): """Call an ADB-related method and catch exceptions.""" if not self.available and not override_available: return None try: return await func(self, *args, **kwargs) except LockNotAcquiredException: # If the ADB lock could not be acquired, skip this command _LOGGER.info( "ADB command not executed because the connection is currently in use" ) return except self.exceptions as err: _LOGGER.error( "Failed to execute an ADB command. ADB connection re-" "establishing attempt in the next update. Error: %s", err, ) await self.aftv.adb_close() self._available = False return None except Exception: # An unforeseen exception occurred. Close the ADB connection so that # it doesn't happen over and over again, then raise the exception. await self.aftv.adb_close() self._available = False raise return _adb_exception_catcher return _adb_decorator
[ "def", "adb_decorator", "(", "override_available", "=", "False", ")", ":", "def", "_adb_decorator", "(", "func", ")", ":", "\"\"\"Wrap the provided ADB method and catch exceptions.\"\"\"", "@", "functools", ".", "wraps", "(", "func", ")", "async", "def", "_adb_exception_catcher", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Call an ADB-related method and catch exceptions.\"\"\"", "if", "not", "self", ".", "available", "and", "not", "override_available", ":", "return", "None", "try", ":", "return", "await", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "LockNotAcquiredException", ":", "# If the ADB lock could not be acquired, skip this command", "_LOGGER", ".", "info", "(", "\"ADB command not executed because the connection is currently in use\"", ")", "return", "except", "self", ".", "exceptions", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Failed to execute an ADB command. ADB connection re-\"", "\"establishing attempt in the next update. Error: %s\"", ",", "err", ",", ")", "await", "self", ".", "aftv", ".", "adb_close", "(", ")", "self", ".", "_available", "=", "False", "return", "None", "except", "Exception", ":", "# An unforeseen exception occurred. Close the ADB connection so that", "# it doesn't happen over and over again, then raise the exception.", "await", "self", ".", "aftv", ".", "adb_close", "(", ")", "self", ".", "_available", "=", "False", "raise", "return", "_adb_exception_catcher", "return", "_adb_decorator" ]
[ 345, 0 ]
[ 387, 25 ]
python
en
['en', 'en', 'en']
True
ADBDevice.__init__
( self, aftv, name, apps, get_sources, turn_on_command, turn_off_command, exclude_unnamed_apps, screencap, )
Initialize the Android TV / Fire TV device.
Initialize the Android TV / Fire TV device.
def __init__( self, aftv, name, apps, get_sources, turn_on_command, turn_off_command, exclude_unnamed_apps, screencap, ): """Initialize the Android TV / Fire TV device.""" self.aftv = aftv self._name = name self._app_id_to_name = APPS.copy() self._app_id_to_name.update(apps) self._app_name_to_id = { value: key for key, value in self._app_id_to_name.items() if value } # Make sure that apps overridden via the `apps` parameter are reflected # in `self._app_name_to_id` for key, value in apps.items(): self._app_name_to_id[value] = key self._get_sources = get_sources self._keys = KEYS self._device_properties = self.aftv.device_properties self._unique_id = self._device_properties.get("serialno") self.turn_on_command = turn_on_command self.turn_off_command = turn_off_command self._exclude_unnamed_apps = exclude_unnamed_apps self._screencap = screencap # ADB exceptions to catch if not self.aftv.adb_server_ip: # Using "adb_shell" (Python ADB implementation) self.exceptions = ( AdbTimeoutError, BrokenPipeError, ConnectionResetError, ValueError, InvalidChecksumError, InvalidCommandError, InvalidResponseError, TcpTimeoutException, ) else: # Using "pure-python-adb" (communicate with ADB server) self.exceptions = (ConnectionResetError, RuntimeError) # Property attributes self._adb_response = None self._available = True self._current_app = None self._sources = None self._state = None self._hdmi_input = None
[ "def", "__init__", "(", "self", ",", "aftv", ",", "name", ",", "apps", ",", "get_sources", ",", "turn_on_command", ",", "turn_off_command", ",", "exclude_unnamed_apps", ",", "screencap", ",", ")", ":", "self", ".", "aftv", "=", "aftv", "self", ".", "_name", "=", "name", "self", ".", "_app_id_to_name", "=", "APPS", ".", "copy", "(", ")", "self", ".", "_app_id_to_name", ".", "update", "(", "apps", ")", "self", ".", "_app_name_to_id", "=", "{", "value", ":", "key", "for", "key", ",", "value", "in", "self", ".", "_app_id_to_name", ".", "items", "(", ")", "if", "value", "}", "# Make sure that apps overridden via the `apps` parameter are reflected", "# in `self._app_name_to_id`", "for", "key", ",", "value", "in", "apps", ".", "items", "(", ")", ":", "self", ".", "_app_name_to_id", "[", "value", "]", "=", "key", "self", ".", "_get_sources", "=", "get_sources", "self", ".", "_keys", "=", "KEYS", "self", ".", "_device_properties", "=", "self", ".", "aftv", ".", "device_properties", "self", ".", "_unique_id", "=", "self", ".", "_device_properties", ".", "get", "(", "\"serialno\"", ")", "self", ".", "turn_on_command", "=", "turn_on_command", "self", ".", "turn_off_command", "=", "turn_off_command", "self", ".", "_exclude_unnamed_apps", "=", "exclude_unnamed_apps", "self", ".", "_screencap", "=", "screencap", "# ADB exceptions to catch", "if", "not", "self", ".", "aftv", ".", "adb_server_ip", ":", "# Using \"adb_shell\" (Python ADB implementation)", "self", ".", "exceptions", "=", "(", "AdbTimeoutError", ",", "BrokenPipeError", ",", "ConnectionResetError", ",", "ValueError", ",", "InvalidChecksumError", ",", "InvalidCommandError", ",", "InvalidResponseError", ",", "TcpTimeoutException", ",", ")", "else", ":", "# Using \"pure-python-adb\" (communicate with ADB server)", "self", ".", "exceptions", "=", "(", "ConnectionResetError", ",", "RuntimeError", ")", "# Property attributes", "self", ".", "_adb_response", "=", "None", "self", ".", "_available", "=", "True", "self", ".", "_current_app", "=", "None", "self", ".", "_sources", "=", "None", "self", ".", "_state", "=", "None", "self", ".", "_hdmi_input", "=", "None" ]
[ 393, 4 ]
[ 453, 31 ]
python
en
['en', 'en', 'en']
True
ADBDevice.app_id
(self)
Return the current app.
Return the current app.
def app_id(self): """Return the current app.""" return self._current_app
[ "def", "app_id", "(", "self", ")", ":", "return", "self", ".", "_current_app" ]
[ 456, 4 ]
[ 458, 32 ]
python
en
['en', 'la', 'en']
True
ADBDevice.app_name
(self)
Return the friendly name of the current app.
Return the friendly name of the current app.
def app_name(self): """Return the friendly name of the current app.""" return self._app_id_to_name.get(self._current_app, self._current_app)
[ "def", "app_name", "(", "self", ")", ":", "return", "self", ".", "_app_id_to_name", ".", "get", "(", "self", ".", "_current_app", ",", "self", ".", "_current_app", ")" ]
[ 461, 4 ]
[ 463, 77 ]
python
en
['en', 'en', 'en']
True
ADBDevice.available
(self)
Return whether or not the ADB connection is valid.
Return whether or not the ADB connection is valid.
def available(self): """Return whether or not the ADB connection is valid.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
[ 466, 4 ]
[ 468, 30 ]
python
en
['en', 'en', 'en']
True
ADBDevice.device_state_attributes
(self)
Provide the last ADB command's response and the device's HDMI input as attributes.
Provide the last ADB command's response and the device's HDMI input as attributes.
def device_state_attributes(self): """Provide the last ADB command's response and the device's HDMI input as attributes.""" return { "adb_response": self._adb_response, "hdmi_input": self._hdmi_input, }
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "\"adb_response\"", ":", "self", ".", "_adb_response", ",", "\"hdmi_input\"", ":", "self", ".", "_hdmi_input", ",", "}" ]
[ 471, 4 ]
[ 476, 9 ]
python
en
['en', 'en', 'en']
True
ADBDevice.media_image_hash
(self)
Hash value for media image.
Hash value for media image.
def media_image_hash(self): """Hash value for media image.""" return f"{datetime.now().timestamp()}" if self._screencap else None
[ "def", "media_image_hash", "(", "self", ")", ":", "return", "f\"{datetime.now().timestamp()}\"", "if", "self", ".", "_screencap", "else", "None" ]
[ 479, 4 ]
[ 481, 75 ]
python
en
['en', 'en', 'en']
True
ADBDevice.name
(self)
Return the device name.
Return the device name.
def name(self): """Return the device name.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 484, 4 ]
[ 486, 25 ]
python
en
['en', 'en', 'en']
True
ADBDevice.source
(self)
Return the current app.
Return the current app.
def source(self): """Return the current app.""" return self._app_id_to_name.get(self._current_app, self._current_app)
[ "def", "source", "(", "self", ")", ":", "return", "self", ".", "_app_id_to_name", ".", "get", "(", "self", ".", "_current_app", ",", "self", ".", "_current_app", ")" ]
[ 489, 4 ]
[ 491, 77 ]
python
en
['en', 'la', 'en']
True
ADBDevice.source_list
(self)
Return a list of running apps.
Return a list of running apps.
def source_list(self): """Return a list of running apps.""" return self._sources
[ "def", "source_list", "(", "self", ")", ":", "return", "self", ".", "_sources" ]
[ 494, 4 ]
[ 496, 28 ]
python
en
['en', 'lb', 'en']
True
ADBDevice.state
(self)
Return the state of the player.
Return the state of the player.
def state(self): """Return the state of the player.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 499, 4 ]
[ 501, 26 ]
python
en
['en', 'en', 'en']
True
ADBDevice.unique_id
(self)
Return the device unique id.
Return the device unique id.
def unique_id(self): """Return the device unique id.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_unique_id" ]
[ 504, 4 ]
[ 506, 30 ]
python
en
['en', 'it', 'en']
True
ADBDevice._adb_screencap
(self)
Take a screen capture from the device.
Take a screen capture from the device.
async def _adb_screencap(self): """Take a screen capture from the device.""" return await self.aftv.adb_screencap()
[ "async", "def", "_adb_screencap", "(", "self", ")", ":", "return", "await", "self", ".", "aftv", ".", "adb_screencap", "(", ")" ]
[ 509, 4 ]
[ 511, 46 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_get_media_image
(self)
Fetch current playing image.
Fetch current playing image.
async def async_get_media_image(self): """Fetch current playing image.""" if not self._screencap or self.state in [STATE_OFF, None] or not self.available: return None, None media_data = await self._adb_screencap() if media_data: return media_data, "image/png" # If an exception occurred and the device is no longer available, write the state if not self.available: self.async_write_ha_state() return None, None
[ "async", "def", "async_get_media_image", "(", "self", ")", ":", "if", "not", "self", ".", "_screencap", "or", "self", ".", "state", "in", "[", "STATE_OFF", ",", "None", "]", "or", "not", "self", ".", "available", ":", "return", "None", ",", "None", "media_data", "=", "await", "self", ".", "_adb_screencap", "(", ")", "if", "media_data", ":", "return", "media_data", ",", "\"image/png\"", "# If an exception occurred and the device is no longer available, write the state", "if", "not", "self", ".", "available", ":", "self", ".", "async_write_ha_state", "(", ")", "return", "None", ",", "None" ]
[ 513, 4 ]
[ 526, 25 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_media_play
(self)
Send play command.
Send play command.
async def async_media_play(self): """Send play command.""" await self.aftv.media_play()
[ "async", "def", "async_media_play", "(", "self", ")", ":", "await", "self", ".", "aftv", ".", "media_play", "(", ")" ]
[ 529, 4 ]
[ 531, 36 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_media_pause
(self)
Send pause command.
Send pause command.
async def async_media_pause(self): """Send pause command.""" await self.aftv.media_pause()
[ "async", "def", "async_media_pause", "(", "self", ")", ":", "await", "self", ".", "aftv", ".", "media_pause", "(", ")" ]
[ 534, 4 ]
[ 536, 37 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_media_play_pause
(self)
Send play/pause command.
Send play/pause command.
async def async_media_play_pause(self): """Send play/pause command.""" await self.aftv.media_play_pause()
[ "async", "def", "async_media_play_pause", "(", "self", ")", ":", "await", "self", ".", "aftv", ".", "media_play_pause", "(", ")" ]
[ 539, 4 ]
[ 541, 42 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_turn_on
(self)
Turn on the device.
Turn on the device.
async def async_turn_on(self): """Turn on the device.""" if self.turn_on_command: await self.aftv.adb_shell(self.turn_on_command) else: await self.aftv.turn_on()
[ "async", "def", "async_turn_on", "(", "self", ")", ":", "if", "self", ".", "turn_on_command", ":", "await", "self", ".", "aftv", ".", "adb_shell", "(", "self", ".", "turn_on_command", ")", "else", ":", "await", "self", ".", "aftv", ".", "turn_on", "(", ")" ]
[ 544, 4 ]
[ 549, 37 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_turn_off
(self)
Turn off the device.
Turn off the device.
async def async_turn_off(self): """Turn off the device.""" if self.turn_off_command: await self.aftv.adb_shell(self.turn_off_command) else: await self.aftv.turn_off()
[ "async", "def", "async_turn_off", "(", "self", ")", ":", "if", "self", ".", "turn_off_command", ":", "await", "self", ".", "aftv", ".", "adb_shell", "(", "self", ".", "turn_off_command", ")", "else", ":", "await", "self", ".", "aftv", ".", "turn_off", "(", ")" ]
[ 552, 4 ]
[ 557, 38 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_media_previous_track
(self)
Send previous track command (results in rewind).
Send previous track command (results in rewind).
async def async_media_previous_track(self): """Send previous track command (results in rewind).""" await self.aftv.media_previous_track()
[ "async", "def", "async_media_previous_track", "(", "self", ")", ":", "await", "self", ".", "aftv", ".", "media_previous_track", "(", ")" ]
[ 560, 4 ]
[ 562, 46 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_media_next_track
(self)
Send next track command (results in fast-forward).
Send next track command (results in fast-forward).
async def async_media_next_track(self): """Send next track command (results in fast-forward).""" await self.aftv.media_next_track()
[ "async", "def", "async_media_next_track", "(", "self", ")", ":", "await", "self", ".", "aftv", ".", "media_next_track", "(", ")" ]
[ 565, 4 ]
[ 567, 42 ]
python
en
['en', 'en', 'en']
True
ADBDevice.async_select_source
(self, source)
Select input source. If the source starts with a '!', then it will close the app instead of opening it.
Select input source.
async def async_select_source(self, source): """Select input source. If the source starts with a '!', then it will close the app instead of opening it. """ if isinstance(source, str): if not source.startswith("!"): await self.aftv.launch_app(self._app_name_to_id.get(source, source)) else: source_ = source[1:].lstrip() await self.aftv.stop_app(self._app_name_to_id.get(source_, source_))
[ "async", "def", "async_select_source", "(", "self", ",", "source", ")", ":", "if", "isinstance", "(", "source", ",", "str", ")", ":", "if", "not", "source", ".", "startswith", "(", "\"!\"", ")", ":", "await", "self", ".", "aftv", ".", "launch_app", "(", "self", ".", "_app_name_to_id", ".", "get", "(", "source", ",", "source", ")", ")", "else", ":", "source_", "=", "source", "[", "1", ":", "]", ".", "lstrip", "(", ")", "await", "self", ".", "aftv", ".", "stop_app", "(", "self", ".", "_app_name_to_id", ".", "get", "(", "source_", ",", "source_", ")", ")" ]
[ 570, 4 ]
[ 581, 84 ]
python
en
['fr', 'su', 'en']
False
ADBDevice.adb_command
(self, cmd)
Send an ADB command to an Android TV / Fire TV device.
Send an ADB command to an Android TV / Fire TV device.
async def adb_command(self, cmd): """Send an ADB command to an Android TV / Fire TV device.""" key = self._keys.get(cmd) if key: await self.aftv.adb_shell(f"input keyevent {key}") return if cmd == "GET_PROPERTIES": self._adb_response = str(await self.aftv.get_properties_dict()) self.async_write_ha_state() return self._adb_response try: response = await self.aftv.adb_shell(cmd) except UnicodeDecodeError: return if isinstance(response, str) and response.strip(): self._adb_response = response.strip() self.async_write_ha_state() return self._adb_response
[ "async", "def", "adb_command", "(", "self", ",", "cmd", ")", ":", "key", "=", "self", ".", "_keys", ".", "get", "(", "cmd", ")", "if", "key", ":", "await", "self", ".", "aftv", ".", "adb_shell", "(", "f\"input keyevent {key}\"", ")", "return", "if", "cmd", "==", "\"GET_PROPERTIES\"", ":", "self", ".", "_adb_response", "=", "str", "(", "await", "self", ".", "aftv", ".", "get_properties_dict", "(", ")", ")", "self", ".", "async_write_ha_state", "(", ")", "return", "self", ".", "_adb_response", "try", ":", "response", "=", "await", "self", ".", "aftv", ".", "adb_shell", "(", "cmd", ")", "except", "UnicodeDecodeError", ":", "return", "if", "isinstance", "(", "response", ",", "str", ")", "and", "response", ".", "strip", "(", ")", ":", "self", ".", "_adb_response", "=", "response", ".", "strip", "(", ")", "self", ".", "async_write_ha_state", "(", ")", "return", "self", ".", "_adb_response" ]
[ 584, 4 ]
[ 605, 33 ]
python
en
['en', 'en', 'en']
True
ADBDevice.learn_sendevent
(self)
Translate a key press on a remote to ADB 'sendevent' commands.
Translate a key press on a remote to ADB 'sendevent' commands.
async def learn_sendevent(self): """Translate a key press on a remote to ADB 'sendevent' commands.""" output = await self.aftv.learn_sendevent() if output: self._adb_response = output self.async_write_ha_state() msg = f"Output from service '{SERVICE_LEARN_SENDEVENT}' from {self.entity_id}: '{output}'" self.hass.components.persistent_notification.async_create( msg, title="Android TV", ) _LOGGER.info("%s", msg)
[ "async", "def", "learn_sendevent", "(", "self", ")", ":", "output", "=", "await", "self", ".", "aftv", ".", "learn_sendevent", "(", ")", "if", "output", ":", "self", ".", "_adb_response", "=", "output", "self", ".", "async_write_ha_state", "(", ")", "msg", "=", "f\"Output from service '{SERVICE_LEARN_SENDEVENT}' from {self.entity_id}: '{output}'\"", "self", ".", "hass", ".", "components", ".", "persistent_notification", ".", "async_create", "(", "msg", ",", "title", "=", "\"Android TV\"", ",", ")", "_LOGGER", ".", "info", "(", "\"%s\"", ",", "msg", ")" ]
[ 608, 4 ]
[ 620, 35 ]
python
en
['en', 'en', 'en']
True
ADBDevice.adb_pull
(self, local_path, device_path)
Download a file from your Android TV / Fire TV device to your Home Assistant instance.
Download a file from your Android TV / Fire TV device to your Home Assistant instance.
async def adb_pull(self, local_path, device_path): """Download a file from your Android TV / Fire TV device to your Home Assistant instance.""" await self.aftv.adb_pull(local_path, device_path)
[ "async", "def", "adb_pull", "(", "self", ",", "local_path", ",", "device_path", ")", ":", "await", "self", ".", "aftv", ".", "adb_pull", "(", "local_path", ",", "device_path", ")" ]
[ 623, 4 ]
[ 625, 57 ]
python
en
['en', 'en', 'en']
True
ADBDevice.adb_push
(self, local_path, device_path)
Upload a file from your Home Assistant instance to an Android TV / Fire TV device.
Upload a file from your Home Assistant instance to an Android TV / Fire TV device.
async def adb_push(self, local_path, device_path): """Upload a file from your Home Assistant instance to an Android TV / Fire TV device.""" await self.aftv.adb_push(local_path, device_path)
[ "async", "def", "adb_push", "(", "self", ",", "local_path", ",", "device_path", ")", ":", "await", "self", ".", "aftv", ".", "adb_push", "(", "local_path", ",", "device_path", ")" ]
[ 628, 4 ]
[ 630, 57 ]
python
en
['en', 'en', 'en']
True
AndroidTVDevice.__init__
( self, aftv, name, apps, get_sources, turn_on_command, turn_off_command, exclude_unnamed_apps, screencap, )
Initialize the Android TV device.
Initialize the Android TV device.
def __init__( self, aftv, name, apps, get_sources, turn_on_command, turn_off_command, exclude_unnamed_apps, screencap, ): """Initialize the Android TV device.""" super().__init__( aftv, name, apps, get_sources, turn_on_command, turn_off_command, exclude_unnamed_apps, screencap, ) self._is_volume_muted = None self._volume_level = None
[ "def", "__init__", "(", "self", ",", "aftv", ",", "name", ",", "apps", ",", "get_sources", ",", "turn_on_command", ",", "turn_off_command", ",", "exclude_unnamed_apps", ",", "screencap", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", "aftv", ",", "name", ",", "apps", ",", "get_sources", ",", "turn_on_command", ",", "turn_off_command", ",", "exclude_unnamed_apps", ",", "screencap", ",", ")", "self", ".", "_is_volume_muted", "=", "None", "self", ".", "_volume_level", "=", "None" ]
[ 636, 4 ]
[ 660, 33 ]
python
en
['en', 'en', 'en']
True
AndroidTVDevice.async_update
(self)
Update the device state and, if necessary, re-connect.
Update the device state and, if necessary, re-connect.
async def async_update(self): """Update the device state and, if necessary, re-connect.""" # Check if device is disconnected. if not self._available: # Try to connect self._available = await self.aftv.adb_connect(always_log_errors=False) # If the ADB connection is not intact, don't update. if not self._available: return # Get the updated state and attributes. ( state, self._current_app, running_apps, _, self._is_volume_muted, self._volume_level, self._hdmi_input, ) = await self.aftv.update(self._get_sources) self._state = ANDROIDTV_STATES.get(state) if self._state is None: self._available = False if running_apps: sources = [ self._app_id_to_name.get( app_id, app_id if not self._exclude_unnamed_apps else None ) for app_id in running_apps ] self._sources = [source for source in sources if source] else: self._sources = None
[ "async", "def", "async_update", "(", "self", ")", ":", "# Check if device is disconnected.", "if", "not", "self", ".", "_available", ":", "# Try to connect", "self", ".", "_available", "=", "await", "self", ".", "aftv", ".", "adb_connect", "(", "always_log_errors", "=", "False", ")", "# If the ADB connection is not intact, don't update.", "if", "not", "self", ".", "_available", ":", "return", "# Get the updated state and attributes.", "(", "state", ",", "self", ".", "_current_app", ",", "running_apps", ",", "_", ",", "self", ".", "_is_volume_muted", ",", "self", ".", "_volume_level", ",", "self", ".", "_hdmi_input", ",", ")", "=", "await", "self", ".", "aftv", ".", "update", "(", "self", ".", "_get_sources", ")", "self", ".", "_state", "=", "ANDROIDTV_STATES", ".", "get", "(", "state", ")", "if", "self", ".", "_state", "is", "None", ":", "self", ".", "_available", "=", "False", "if", "running_apps", ":", "sources", "=", "[", "self", ".", "_app_id_to_name", ".", "get", "(", "app_id", ",", "app_id", "if", "not", "self", ".", "_exclude_unnamed_apps", "else", "None", ")", "for", "app_id", "in", "running_apps", "]", "self", ".", "_sources", "=", "[", "source", "for", "source", "in", "sources", "if", "source", "]", "else", ":", "self", ".", "_sources", "=", "None" ]
[ 663, 4 ]
[ 698, 32 ]
python
en
['en', 'en', 'en']
True
AndroidTVDevice.is_volume_muted
(self)
Boolean if volume is currently muted.
Boolean if volume is currently muted.
def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._is_volume_muted
[ "def", "is_volume_muted", "(", "self", ")", ":", "return", "self", ".", "_is_volume_muted" ]
[ 701, 4 ]
[ 703, 36 ]
python
en
['en', 'en', 'en']
True
AndroidTVDevice.supported_features
(self)
Flag media player features that are supported.
Flag media player features that are supported.
def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_ANDROIDTV
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_ANDROIDTV" ]
[ 706, 4 ]
[ 708, 32 ]
python
en
['en', 'en', 'en']
True
AndroidTVDevice.volume_level
(self)
Return the volume level.
Return the volume level.
def volume_level(self): """Return the volume level.""" return self._volume_level
[ "def", "volume_level", "(", "self", ")", ":", "return", "self", ".", "_volume_level" ]
[ 711, 4 ]
[ 713, 33 ]
python
en
['en', 'no', 'en']
True
AndroidTVDevice.async_media_stop
(self)
Send stop command.
Send stop command.
async def async_media_stop(self): """Send stop command.""" await self.aftv.media_stop()
[ "async", "def", "async_media_stop", "(", "self", ")", ":", "await", "self", ".", "aftv", ".", "media_stop", "(", ")" ]
[ 716, 4 ]
[ 718, 36 ]
python
en
['en', 'en', 'en']
True
AndroidTVDevice.async_mute_volume
(self, mute)
Mute the volume.
Mute the volume.
async def async_mute_volume(self, mute): """Mute the volume.""" await self.aftv.mute_volume()
[ "async", "def", "async_mute_volume", "(", "self", ",", "mute", ")", ":", "await", "self", ".", "aftv", ".", "mute_volume", "(", ")" ]
[ 721, 4 ]
[ 723, 37 ]
python
en
['en', 'sn', 'en']
True
AndroidTVDevice.async_set_volume_level
(self, volume)
Set the volume level.
Set the volume level.
async def async_set_volume_level(self, volume): """Set the volume level.""" await self.aftv.set_volume_level(volume)
[ "async", "def", "async_set_volume_level", "(", "self", ",", "volume", ")", ":", "await", "self", ".", "aftv", ".", "set_volume_level", "(", "volume", ")" ]
[ 726, 4 ]
[ 728, 48 ]
python
en
['en', 'sr', 'en']
True
AndroidTVDevice.async_volume_down
(self)
Send volume down command.
Send volume down command.
async def async_volume_down(self): """Send volume down command.""" self._volume_level = await self.aftv.volume_down(self._volume_level)
[ "async", "def", "async_volume_down", "(", "self", ")", ":", "self", ".", "_volume_level", "=", "await", "self", ".", "aftv", ".", "volume_down", "(", "self", ".", "_volume_level", ")" ]
[ 731, 4 ]
[ 733, 76 ]
python
en
['en', 'it', 'en']
True
AndroidTVDevice.async_volume_up
(self)
Send volume up command.
Send volume up command.
async def async_volume_up(self): """Send volume up command.""" self._volume_level = await self.aftv.volume_up(self._volume_level)
[ "async", "def", "async_volume_up", "(", "self", ")", ":", "self", ".", "_volume_level", "=", "await", "self", ".", "aftv", ".", "volume_up", "(", "self", ".", "_volume_level", ")" ]
[ 736, 4 ]
[ 738, 74 ]
python
en
['en', 'en', 'en']
True
FireTVDevice.async_update
(self)
Update the device state and, if necessary, re-connect.
Update the device state and, if necessary, re-connect.
async def async_update(self): """Update the device state and, if necessary, re-connect.""" # Check if device is disconnected. if not self._available: # Try to connect self._available = await self.aftv.adb_connect(always_log_errors=False) # If the ADB connection is not intact, don't update. if not self._available: return # Get the `state`, `current_app`, `running_apps` and `hdmi_input`. ( state, self._current_app, running_apps, self._hdmi_input, ) = await self.aftv.update(self._get_sources) self._state = ANDROIDTV_STATES.get(state) if self._state is None: self._available = False if running_apps: sources = [ self._app_id_to_name.get( app_id, app_id if not self._exclude_unnamed_apps else None ) for app_id in running_apps ] self._sources = [source for source in sources if source] else: self._sources = None
[ "async", "def", "async_update", "(", "self", ")", ":", "# Check if device is disconnected.", "if", "not", "self", ".", "_available", ":", "# Try to connect", "self", ".", "_available", "=", "await", "self", ".", "aftv", ".", "adb_connect", "(", "always_log_errors", "=", "False", ")", "# If the ADB connection is not intact, don't update.", "if", "not", "self", ".", "_available", ":", "return", "# Get the `state`, `current_app`, `running_apps` and `hdmi_input`.", "(", "state", ",", "self", ".", "_current_app", ",", "running_apps", ",", "self", ".", "_hdmi_input", ",", ")", "=", "await", "self", ".", "aftv", ".", "update", "(", "self", ".", "_get_sources", ")", "self", ".", "_state", "=", "ANDROIDTV_STATES", ".", "get", "(", "state", ")", "if", "self", ".", "_state", "is", "None", ":", "self", ".", "_available", "=", "False", "if", "running_apps", ":", "sources", "=", "[", "self", ".", "_app_id_to_name", ".", "get", "(", "app_id", ",", "app_id", "if", "not", "self", ".", "_exclude_unnamed_apps", "else", "None", ")", "for", "app_id", "in", "running_apps", "]", "self", ".", "_sources", "=", "[", "source", "for", "source", "in", "sources", "if", "source", "]", "else", ":", "self", ".", "_sources", "=", "None" ]
[ 745, 4 ]
[ 777, 32 ]
python
en
['en', 'en', 'en']
True
FireTVDevice.supported_features
(self)
Flag media player features that are supported.
Flag media player features that are supported.
def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_FIRETV
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_FIRETV" ]
[ 780, 4 ]
[ 782, 29 ]
python
en
['en', 'en', 'en']
True
FireTVDevice.async_media_stop
(self)
Send stop (back) command.
Send stop (back) command.
async def async_media_stop(self): """Send stop (back) command.""" await self.aftv.back()
[ "async", "def", "async_media_stop", "(", "self", ")", ":", "await", "self", ".", "aftv", ".", "back", "(", ")" ]
[ 785, 4 ]
[ 787, 30 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Wink lights.
Set up the Wink lights.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Wink lights.""" for light in pywink.get_light_bulbs(): _id = light.object_id() + light.name() if _id not in hass.data[DOMAIN]["unique_ids"]: add_entities([WinkLight(light, hass)]) for light in pywink.get_light_groups(): _id = light.object_id() + light.name() if _id not in hass.data[DOMAIN]["unique_ids"]: add_entities([WinkLight(light, hass)])
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "for", "light", "in", "pywink", ".", "get_light_bulbs", "(", ")", ":", "_id", "=", "light", ".", "object_id", "(", ")", "+", "light", ".", "name", "(", ")", "if", "_id", "not", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"unique_ids\"", "]", ":", "add_entities", "(", "[", "WinkLight", "(", "light", ",", "hass", ")", "]", ")", "for", "light", "in", "pywink", ".", "get_light_groups", "(", ")", ":", "_id", "=", "light", ".", "object_id", "(", ")", "+", "light", ".", "name", "(", ")", "if", "_id", "not", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"unique_ids\"", "]", ":", "add_entities", "(", "[", "WinkLight", "(", "light", ",", "hass", ")", "]", ")" ]
[ 20, 0 ]
[ 30, 50 ]
python
en
['en', 'da', 'en']
True
WinkLight.async_added_to_hass
(self)
Call when entity is added to hass.
Call when entity is added to hass.
async def async_added_to_hass(self): """Call when entity is added to hass.""" self.hass.data[DOMAIN]["entities"]["light"].append(self)
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "self", ".", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"entities\"", "]", "[", "\"light\"", "]", ".", "append", "(", "self", ")" ]
[ 36, 4 ]
[ 38, 64 ]
python
en
['en', 'en', 'en']
True
WinkLight.is_on
(self)
Return true if light is on.
Return true if light is on.
def is_on(self): """Return true if light is on.""" return self.wink.state()
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "wink", ".", "state", "(", ")" ]
[ 41, 4 ]
[ 43, 32 ]
python
en
['en', 'et', 'en']
True
WinkLight.brightness
(self)
Return the brightness of the light.
Return the brightness of the light.
def brightness(self): """Return the brightness of the light.""" if self.wink.brightness() is not None: return int(self.wink.brightness() * 255) return None
[ "def", "brightness", "(", "self", ")", ":", "if", "self", ".", "wink", ".", "brightness", "(", ")", "is", "not", "None", ":", "return", "int", "(", "self", ".", "wink", ".", "brightness", "(", ")", "*", "255", ")", "return", "None" ]
[ 46, 4 ]
[ 50, 19 ]
python
en
['en', 'no', 'en']
True
WinkLight.hs_color
(self)
Define current bulb color.
Define current bulb color.
def hs_color(self): """Define current bulb color.""" if self.wink.supports_xy_color(): return color_util.color_xy_to_hs(*self.wink.color_xy()) if self.wink.supports_hue_saturation(): hue = self.wink.color_hue() saturation = self.wink.color_saturation() if hue is not None and saturation is not None: return hue * 360, saturation * 100 return None
[ "def", "hs_color", "(", "self", ")", ":", "if", "self", ".", "wink", ".", "supports_xy_color", "(", ")", ":", "return", "color_util", ".", "color_xy_to_hs", "(", "*", "self", ".", "wink", ".", "color_xy", "(", ")", ")", "if", "self", ".", "wink", ".", "supports_hue_saturation", "(", ")", ":", "hue", "=", "self", ".", "wink", ".", "color_hue", "(", ")", "saturation", "=", "self", ".", "wink", ".", "color_saturation", "(", ")", "if", "hue", "is", "not", "None", "and", "saturation", "is", "not", "None", ":", "return", "hue", "*", "360", ",", "saturation", "*", "100", "return", "None" ]
[ 53, 4 ]
[ 64, 19 ]
python
en
['ro', 'en', 'en']
True
WinkLight.color_temp
(self)
Define current bulb color in degrees Kelvin.
Define current bulb color in degrees Kelvin.
def color_temp(self): """Define current bulb color in degrees Kelvin.""" if not self.wink.supports_temperature(): return None return color_util.color_temperature_kelvin_to_mired( self.wink.color_temperature_kelvin() )
[ "def", "color_temp", "(", "self", ")", ":", "if", "not", "self", ".", "wink", ".", "supports_temperature", "(", ")", ":", "return", "None", "return", "color_util", ".", "color_temperature_kelvin_to_mired", "(", "self", ".", "wink", ".", "color_temperature_kelvin", "(", ")", ")" ]
[ 67, 4 ]
[ 73, 9 ]
python
en
['ro', 'en', 'en']
True
WinkLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" supports = SUPPORT_BRIGHTNESS if self.wink.supports_temperature(): supports = supports | SUPPORT_COLOR_TEMP if self.wink.supports_xy_color(): supports = supports | SUPPORT_COLOR elif self.wink.supports_hue_saturation(): supports = supports | SUPPORT_COLOR return supports
[ "def", "supported_features", "(", "self", ")", ":", "supports", "=", "SUPPORT_BRIGHTNESS", "if", "self", ".", "wink", ".", "supports_temperature", "(", ")", ":", "supports", "=", "supports", "|", "SUPPORT_COLOR_TEMP", "if", "self", ".", "wink", ".", "supports_xy_color", "(", ")", ":", "supports", "=", "supports", "|", "SUPPORT_COLOR", "elif", "self", ".", "wink", ".", "supports_hue_saturation", "(", ")", ":", "supports", "=", "supports", "|", "SUPPORT_COLOR", "return", "supports" ]
[ 76, 4 ]
[ 85, 23 ]
python
en
['da', 'en', 'en']
True
WinkLight.turn_on
(self, **kwargs)
Turn the switch on.
Turn the switch on.
def turn_on(self, **kwargs): """Turn the switch on.""" brightness = kwargs.get(ATTR_BRIGHTNESS) hs_color = kwargs.get(ATTR_HS_COLOR) color_temp_mired = kwargs.get(ATTR_COLOR_TEMP) state_kwargs = {} if hs_color: if self.wink.supports_xy_color(): xy_color = color_util.color_hs_to_xy(*hs_color) state_kwargs["color_xy"] = xy_color if self.wink.supports_hue_saturation(): hs_scaled = hs_color[0] / 360, hs_color[1] / 100 state_kwargs["color_hue_saturation"] = hs_scaled if color_temp_mired: state_kwargs["color_kelvin"] = mired_to_kelvin(color_temp_mired) if brightness: state_kwargs["brightness"] = brightness / 255.0 self.wink.set_state(True, **state_kwargs)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "brightness", "=", "kwargs", ".", "get", "(", "ATTR_BRIGHTNESS", ")", "hs_color", "=", "kwargs", ".", "get", "(", "ATTR_HS_COLOR", ")", "color_temp_mired", "=", "kwargs", ".", "get", "(", "ATTR_COLOR_TEMP", ")", "state_kwargs", "=", "{", "}", "if", "hs_color", ":", "if", "self", ".", "wink", ".", "supports_xy_color", "(", ")", ":", "xy_color", "=", "color_util", ".", "color_hs_to_xy", "(", "*", "hs_color", ")", "state_kwargs", "[", "\"color_xy\"", "]", "=", "xy_color", "if", "self", ".", "wink", ".", "supports_hue_saturation", "(", ")", ":", "hs_scaled", "=", "hs_color", "[", "0", "]", "/", "360", ",", "hs_color", "[", "1", "]", "/", "100", "state_kwargs", "[", "\"color_hue_saturation\"", "]", "=", "hs_scaled", "if", "color_temp_mired", ":", "state_kwargs", "[", "\"color_kelvin\"", "]", "=", "mired_to_kelvin", "(", "color_temp_mired", ")", "if", "brightness", ":", "state_kwargs", "[", "\"brightness\"", "]", "=", "brightness", "/", "255.0", "self", ".", "wink", ".", "set_state", "(", "True", ",", "*", "*", "state_kwargs", ")" ]
[ 87, 4 ]
[ 109, 49 ]
python
en
['en', 'en', 'en']
True
WinkLight.turn_off
(self, **kwargs)
Turn the switch off.
Turn the switch off.
def turn_off(self, **kwargs): """Turn the switch off.""" self.wink.set_state(False)
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "wink", ".", "set_state", "(", "False", ")" ]
[ 111, 4 ]
[ 113, 34 ]
python
en
['en', 'en', 'en']
True
hash_from_url
(url: str)
Hash url to create a unique ID.
Hash url to create a unique ID.
def hash_from_url(url: str): """Hash url to create a unique ID.""" return hashlib.sha256(url.encode("utf-8")).hexdigest()
[ "def", "hash_from_url", "(", "url", ":", "str", ")", ":", "return", "hashlib", ".", "sha256", "(", "url", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ")" ]
[ 4, 0 ]
[ 6, 58 ]
python
en
['es', 'it', 'en']
False
clust_name
(hostname,username,password)
Finding cluster name & feeding into the targets.json file for labels of prometheus. In case no cluster name is found populating 'Orphan VM' value. ReST endpoint used 'pools/default'. Parameters ---------- hostname : str The hostname of the Couchbase VM. username : str The username of that given Couchbase VM. password : str The password of that given Couchbase VM.
Finding cluster name & feeding into the targets.json file for labels of prometheus. In case no cluster name is found populating 'Orphan VM' value. ReST endpoint used 'pools/default'. Parameters ---------- hostname : str The hostname of the Couchbase VM. username : str The username of that given Couchbase VM. password : str The password of that given Couchbase VM.
def clust_name(hostname,username,password): '''Finding cluster name & feeding into the targets.json file for labels of prometheus. In case no cluster name is found populating 'Orphan VM' value. ReST endpoint used 'pools/default'. Parameters ---------- hostname : str The hostname of the Couchbase VM. username : str The username of that given Couchbase VM. password : str The password of that given Couchbase VM. ''' port='8091' URL='http://'+hostname+':'+port try: resp = requests.get(URL + '/pools/default', auth=HTTPBasicAuth(username, password)) if resp.status_code != 200: return 0 else: data=resp.json() cluster_name=data['clusterName'] if len(cluster_name.replace(" ","")) == 0: return "Orphan VM. No, Cluster Name." else: return cluster_name except requests.exceptions.RequestException as err: print (hostname + " - OOps: Something Else",err) except requests.exceptions.HTTPError as errh: print (hostname + " - Http Error:",errh) except requests.exceptions.ConnectionError as errc: print (hostname + " - Error Connecting:",errc) except requests.exceptions.Timeout as errt: print (hostname + " - Timeout Error:",errt)
[ "def", "clust_name", "(", "hostname", ",", "username", ",", "password", ")", ":", "port", "=", "'8091'", "URL", "=", "'http://'", "+", "hostname", "+", "':'", "+", "port", "try", ":", "resp", "=", "requests", ".", "get", "(", "URL", "+", "'/pools/default'", ",", "auth", "=", "HTTPBasicAuth", "(", "username", ",", "password", ")", ")", "if", "resp", ".", "status_code", "!=", "200", ":", "return", "0", "else", ":", "data", "=", "resp", ".", "json", "(", ")", "cluster_name", "=", "data", "[", "'clusterName'", "]", "if", "len", "(", "cluster_name", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ")", "==", "0", ":", "return", "\"Orphan VM. No, Cluster Name.\"", "else", ":", "return", "cluster_name", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "err", ":", "print", "(", "hostname", "+", "\" - OOps: Something Else\"", ",", "err", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "errh", ":", "print", "(", "hostname", "+", "\" - Http Error:\"", ",", "errh", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "errc", ":", "print", "(", "hostname", "+", "\" - Error Connecting:\"", ",", "errc", ")", "except", "requests", ".", "exceptions", ".", "Timeout", "as", "errt", ":", "print", "(", "hostname", "+", "\" - Timeout Error:\"", ",", "errt", ")" ]
[ 10, 0 ]
[ 46, 51 ]
python
en
['en', 'en', 'en']
True
get_empty_port
()
Finding and returning an empty port-number for starting couchbase-exporter process. Each VM for exporting stats by couchbase-exporter requires it's own specific port number. Returns ------- port_no : int The empty port number returned for CB-Exporter to spin its instance.
Finding and returning an empty port-number for starting couchbase-exporter process. Each VM for exporting stats by couchbase-exporter requires it's own specific port number.
def get_empty_port(): '''Finding and returning an empty port-number for starting couchbase-exporter process. Each VM for exporting stats by couchbase-exporter requires it's own specific port number. Returns ------- port_no : int The empty port number returned for CB-Exporter to spin its instance. ''' # Assumption empty is available in the given VM. port_no = -1 mssg_dgst = '-1 Imaginary Port' while( len(mssg_dgst) != 0 ): port_no = random.randint(16384,65535) eff_command = "netstat -anp | grep ':"+str(port_no)+"'" # giving shell=True is a bad code design, for insecure input: hazardous pointed by documentation p = subprocess.Popen(eff_command, stdout=subprocess.PIPE, shell=True) mssg_dgst = p.communicate()[0] return port_no
[ "def", "get_empty_port", "(", ")", ":", "# Assumption empty is available in the given VM.", "port_no", "=", "-", "1", "mssg_dgst", "=", "'-1 Imaginary Port'", "while", "(", "len", "(", "mssg_dgst", ")", "!=", "0", ")", ":", "port_no", "=", "random", ".", "randint", "(", "16384", ",", "65535", ")", "eff_command", "=", "\"netstat -anp | grep ':\"", "+", "str", "(", "port_no", ")", "+", "\"'\"", "# giving shell=True is a bad code design, for insecure input: hazardous pointed by documentation", "p", "=", "subprocess", ".", "Popen", "(", "eff_command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ")", "mssg_dgst", "=", "p", ".", "communicate", "(", ")", "[", "0", "]", "return", "port_no" ]
[ 49, 0 ]
[ 69, 18 ]
python
en
['en', 'en', 'en']
True
write_util
(hostname,username, password, port_no)
write VM related information into the reference file. Parameters ---------- hostname : str The hostname of the Couchbase VM. username : str The username of that given Couchbase VM. password : str The password of that given Couchbase VM. port_no : int The port-no on which CB-Exporter instance is running.
write VM related information into the reference file. Parameters ---------- hostname : str The hostname of the Couchbase VM. username : str The username of that given Couchbase VM. password : str The password of that given Couchbase VM. port_no : int The port-no on which CB-Exporter instance is running.
def write_util(hostname,username, password, port_no): '''write VM related information into the reference file. Parameters ---------- hostname : str The hostname of the Couchbase VM. username : str The username of that given Couchbase VM. password : str The password of that given Couchbase VM. port_no : int The port-no on which CB-Exporter instance is running. ''' with open("targets.json", "r") as read_file: data=json.load(read_file) str_val = username+","+password+","+str(port_no) data[hostname] = str_val print("Inserted Data: for key"+" hostname "+data[hostname]) with open("targets.json", "w+") as write_file: data=json.dump(data,write_file, indent=4, separators=(',', ': '))
[ "def", "write_util", "(", "hostname", ",", "username", ",", "password", ",", "port_no", ")", ":", "with", "open", "(", "\"targets.json\"", ",", "\"r\"", ")", "as", "read_file", ":", "data", "=", "json", ".", "load", "(", "read_file", ")", "str_val", "=", "username", "+", "\",\"", "+", "password", "+", "\",\"", "+", "str", "(", "port_no", ")", "data", "[", "hostname", "]", "=", "str_val", "print", "(", "\"Inserted Data: for key\"", "+", "\" hostname \"", "+", "data", "[", "hostname", "]", ")", "with", "open", "(", "\"targets.json\"", ",", "\"w+\"", ")", "as", "write_file", ":", "data", "=", "json", ".", "dump", "(", "data", ",", "write_file", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
[ 74, 0 ]
[ 94, 73 ]
python
en
['en', 'en', 'en']
True
get_util
(hostname)
return information related to particular hostname passed as string argument.
return information related to particular hostname passed as string argument.
def get_util(hostname): '''return information related to particular hostname passed as string argument.''' with open("targets.json", "r") as read_file: data=json.load(read_file) if hostname in data: return data[hostname] return "Key Not Present. Please Check."
[ "def", "get_util", "(", "hostname", ")", ":", "with", "open", "(", "\"targets.json\"", ",", "\"r\"", ")", "as", "read_file", ":", "data", "=", "json", ".", "load", "(", "read_file", ")", "if", "hostname", "in", "data", ":", "return", "data", "[", "hostname", "]", "return", "\"Key Not Present. Please Check.\"" ]
[ 97, 0 ]
[ 104, 43 ]
python
en
['en', 'en', 'en']
True
get_view
()
returns all information of reference targets.json file under consideration.
returns all information of reference targets.json file under consideration.
def get_view(): '''returns all information of reference targets.json file under consideration. ''' with open("targets.json", "r") as read_file: data=json.load(read_file) return data
[ "def", "get_view", "(", ")", ":", "with", "open", "(", "\"targets.json\"", ",", "\"r\"", ")", "as", "read_file", ":", "data", "=", "json", ".", "load", "(", "read_file", ")", "return", "data" ]
[ 107, 0 ]
[ 112, 15 ]
python
en
['en', 'en', 'en']
True
del_util
(hostname)
Delete given Key entry from reference targets.json file.
Delete given Key entry from reference targets.json file.
def del_util(hostname): '''Delete given Key entry from reference targets.json file.''' with open("targets.json", "r") as read_file: data=json.load(read_file) str_val = "" port_no = "-1" if hostname in data: str_val = data.pop(hostname) val_lst = str_val.split(',') port_no = val_lst[2] str_val = "Values Deleted: "+str_val+" for Key: "+hostname else: str_val = "Key Not Present. Please Check." with open("targets.json", "w+") as write_file: json.dump(data,write_file, indent=4, separators=(',', ': ')) return str_val, port_no
[ "def", "del_util", "(", "hostname", ")", ":", "with", "open", "(", "\"targets.json\"", ",", "\"r\"", ")", "as", "read_file", ":", "data", "=", "json", ".", "load", "(", "read_file", ")", "str_val", "=", "\"\"", "port_no", "=", "\"-1\"", "if", "hostname", "in", "data", ":", "str_val", "=", "data", ".", "pop", "(", "hostname", ")", "val_lst", "=", "str_val", ".", "split", "(", "','", ")", "port_no", "=", "val_lst", "[", "2", "]", "str_val", "=", "\"Values Deleted: \"", "+", "str_val", "+", "\" for Key: \"", "+", "hostname", "else", ":", "str_val", "=", "\"Key Not Present. Please Check.\"", "with", "open", "(", "\"targets.json\"", ",", "\"w+\"", ")", "as", "write_file", ":", "json", ".", "dump", "(", "data", ",", "write_file", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "return", "str_val", ",", "port_no" ]
[ 115, 0 ]
[ 131, 27 ]
python
en
['en', 'en', 'en']
True
cbexport_start
(hostname)
Start the couchbase exporter with executing the command.
Start the couchbase exporter with executing the command.
def cbexport_start(hostname): '''Start the couchbase exporter with executing the command.''' with open("targets.json", "r") as read_file: data=json.load(read_file) if hostname in data: str_vals=data[hostname] lst_vals=str_vals.split(",") eff_command="nohup ./../CBExporter/couchbase-exporter --couchbase.username "+lst_vals[0]+" --couchbase.password "+lst_vals[1]+" --web.listen-address="+ \ '":'+lst_vals[2]+'" --couchbase.url="http://'+hostname+':8091" &' else: eff_command="echo Malformed Command Exception: Key Not Found." p = subprocess.Popen(eff_command, stdout=subprocess.PIPE, shell=True) mssg_dgst = p.communicate()[0] return eff_command, mssg_dgst
[ "def", "cbexport_start", "(", "hostname", ")", ":", "with", "open", "(", "\"targets.json\"", ",", "\"r\"", ")", "as", "read_file", ":", "data", "=", "json", ".", "load", "(", "read_file", ")", "if", "hostname", "in", "data", ":", "str_vals", "=", "data", "[", "hostname", "]", "lst_vals", "=", "str_vals", ".", "split", "(", "\",\"", ")", "eff_command", "=", "\"nohup ./../CBExporter/couchbase-exporter --couchbase.username \"", "+", "lst_vals", "[", "0", "]", "+", "\" --couchbase.password \"", "+", "lst_vals", "[", "1", "]", "+", "\" --web.listen-address=\"", "+", "'\":'", "+", "lst_vals", "[", "2", "]", "+", "'\" --couchbase.url=\"http://'", "+", "hostname", "+", "':8091\" &'", "else", ":", "eff_command", "=", "\"echo Malformed Command Exception: Key Not Found.\"", "p", "=", "subprocess", ".", "Popen", "(", "eff_command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ")", "mssg_dgst", "=", "p", ".", "communicate", "(", ")", "[", "0", "]", "return", "eff_command", ",", "mssg_dgst" ]
[ 134, 0 ]
[ 148, 33 ]
python
en
['en', 'en', 'en']
True
cbexport_del
(port_no)
Delete or end the couchbase exporter process.
Delete or end the couchbase exporter process.
def cbexport_del(port_no): '''Delete or end the couchbase exporter process.''' # Need to be 'root' to know the process id information. port_command = 'netstat -nlp | grep ":'+str(port_no)+'"' p = subprocess.Popen(port_command, stdout=subprocess.PIPE, shell=True) mssg_dgst = p.communicate()[0] if len(mssg_dgst) != 0: mssg_lst = mssg_dgst.split(" ") mssg_lst[:] = [item for item in mssg_lst if item != ''] rgx = re.compile(r'[0-9]+\/\w+') pid_list = list(filter(rgx.match, mssg_lst)) pid_list = map(lambda x: x.split("/")[0], pid_list) if len(pid_list) != 0: for x in pid_list: kill_command = 'kill -SIGTERM '+str(x) p = subprocess.Popen(kill_command, stdout=subprocess.PIPE, shell=True) mssg_dgst = p.communicate()[0] print(mssg_dgst) else: print("Port number not in use.")
[ "def", "cbexport_del", "(", "port_no", ")", ":", "# Need to be 'root' to know the process id information.", "port_command", "=", "'netstat -nlp | grep \":'", "+", "str", "(", "port_no", ")", "+", "'\"'", "p", "=", "subprocess", ".", "Popen", "(", "port_command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ")", "mssg_dgst", "=", "p", ".", "communicate", "(", ")", "[", "0", "]", "if", "len", "(", "mssg_dgst", ")", "!=", "0", ":", "mssg_lst", "=", "mssg_dgst", ".", "split", "(", "\" \"", ")", "mssg_lst", "[", ":", "]", "=", "[", "item", "for", "item", "in", "mssg_lst", "if", "item", "!=", "''", "]", "rgx", "=", "re", ".", "compile", "(", "r'[0-9]+\\/\\w+'", ")", "pid_list", "=", "list", "(", "filter", "(", "rgx", ".", "match", ",", "mssg_lst", ")", ")", "pid_list", "=", "map", "(", "lambda", "x", ":", "x", ".", "split", "(", "\"/\"", ")", "[", "0", "]", ",", "pid_list", ")", "if", "len", "(", "pid_list", ")", "!=", "0", ":", "for", "x", "in", "pid_list", ":", "kill_command", "=", "'kill -SIGTERM '", "+", "str", "(", "x", ")", "p", "=", "subprocess", ".", "Popen", "(", "kill_command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ")", "mssg_dgst", "=", "p", ".", "communicate", "(", ")", "[", "0", "]", "print", "(", "mssg_dgst", ")", "else", ":", "print", "(", "\"Port number not in use.\"", ")" ]
[ 155, 0 ]
[ 175, 40 ]
python
en
['en', 'en', 'en']
True
write_targets
(port_no,hostname,username,password)
Write into json file of prometheus running server. For dynamic detection by Node Exporter.
Write into json file of prometheus running server. For dynamic detection by Node Exporter.
def write_targets(port_no,hostname,username,password): '''Write into json file of prometheus running server. For dynamic detection by Node Exporter.''' targ_str = "localhost:"+str(port_no) # These two entries can be fetched from global repository # get this data with another rest query to server clus_str = clust_name(hostname, username, password) # eff_net_str for inputting into targets.json eff_net_str = '{ "targets": [ "localhost:'+str(port_no)+'" ], "labels": { "cluster": "'+clus_str+'"} }' data_appnd = json.loads(eff_net_str) with open('../prometheus-2.9.2.linux-amd64/targets.json','r') as read_file: data = json.load(read_file) data.append(data_appnd) with open('../prometheus-2.9.2.linux-amd64/targets.json','w+') as write_file: data=json.dump(data,write_file, indent=4, separators=(',', ': '))
[ "def", "write_targets", "(", "port_no", ",", "hostname", ",", "username", ",", "password", ")", ":", "targ_str", "=", "\"localhost:\"", "+", "str", "(", "port_no", ")", "# These two entries can be fetched from global repository", "# get this data with another rest query to server", "clus_str", "=", "clust_name", "(", "hostname", ",", "username", ",", "password", ")", "# eff_net_str for inputting into targets.json", "eff_net_str", "=", "'{ \"targets\": [ \"localhost:'", "+", "str", "(", "port_no", ")", "+", "'\" ], \"labels\": { \"cluster\": \"'", "+", "clus_str", "+", "'\"} }'", "data_appnd", "=", "json", ".", "loads", "(", "eff_net_str", ")", "with", "open", "(", "'../prometheus-2.9.2.linux-amd64/targets.json'", ",", "'r'", ")", "as", "read_file", ":", "data", "=", "json", ".", "load", "(", "read_file", ")", "data", ".", "append", "(", "data_appnd", ")", "with", "open", "(", "'../prometheus-2.9.2.linux-amd64/targets.json'", ",", "'w+'", ")", "as", "write_file", ":", "data", "=", "json", ".", "dump", "(", "data", ",", "write_file", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
[ 178, 0 ]
[ 192, 73 ]
python
en
['en', 'en', 'en']
True
del_targets
(port_no)
Delete value from json file of prometheus running server. For dynamic detection by Node Exporter.
Delete value from json file of prometheus running server. For dynamic detection by Node Exporter.
def del_targets(port_no): '''Delete value from json file of prometheus running server. For dynamic detection by Node Exporter.''' with open('../prometheus-2.9.2.linux-amd64/targets.json','r') as read_file: data = json.load(read_file) i=0 for x in data: str_ports = ''.join(x['targets']) str_lst = re.findall(r'\d+', str_ports) str_ports = ''.join(str_lst) # print(str_ports) if str_ports == str(port_no): # print(re.findall(r'\d+', str(x['targets'][0]))) # print(str(port_no)) s=data.pop(i) # print(s) i=i+1 # print(data) with open('../prometheus-2.9.2.linux-amd64/targets.json','w+') as write_file: data=json.dump(data,write_file, indent=4, separators=(',', ': '))
[ "def", "del_targets", "(", "port_no", ")", ":", "with", "open", "(", "'../prometheus-2.9.2.linux-amd64/targets.json'", ",", "'r'", ")", "as", "read_file", ":", "data", "=", "json", ".", "load", "(", "read_file", ")", "i", "=", "0", "for", "x", "in", "data", ":", "str_ports", "=", "''", ".", "join", "(", "x", "[", "'targets'", "]", ")", "str_lst", "=", "re", ".", "findall", "(", "r'\\d+'", ",", "str_ports", ")", "str_ports", "=", "''", ".", "join", "(", "str_lst", ")", "# print(str_ports)", "if", "str_ports", "==", "str", "(", "port_no", ")", ":", "# print(re.findall(r'\\d+', str(x['targets'][0])))", "# print(str(port_no))", "s", "=", "data", ".", "pop", "(", "i", ")", "# print(s)", "i", "=", "i", "+", "1", "# print(data)", "with", "open", "(", "'../prometheus-2.9.2.linux-amd64/targets.json'", ",", "'w+'", ")", "as", "write_file", ":", "data", "=", "json", ".", "dump", "(", "data", ",", "write_file", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
[ 195, 0 ]
[ 214, 73 ]
python
en
['en', 'en', 'en']
True
async_set_lights_xy
(hass, lights, x_val, y_val, brightness, transition)
Set color of array of lights.
Set color of array of lights.
async def async_set_lights_xy(hass, lights, x_val, y_val, brightness, transition): """Set color of array of lights.""" for light in lights: if is_on(hass, light): service_data = {ATTR_ENTITY_ID: light} if x_val is not None and y_val is not None: service_data[ATTR_XY_COLOR] = [x_val, y_val] if brightness is not None: service_data[ATTR_BRIGHTNESS] = brightness service_data[ATTR_WHITE_VALUE] = brightness if transition is not None: service_data[ATTR_TRANSITION] = transition await hass.services.async_call(LIGHT_DOMAIN, SERVICE_TURN_ON, service_data)
[ "async", "def", "async_set_lights_xy", "(", "hass", ",", "lights", ",", "x_val", ",", "y_val", ",", "brightness", ",", "transition", ")", ":", "for", "light", "in", "lights", ":", "if", "is_on", "(", "hass", ",", "light", ")", ":", "service_data", "=", "{", "ATTR_ENTITY_ID", ":", "light", "}", "if", "x_val", "is", "not", "None", "and", "y_val", "is", "not", "None", ":", "service_data", "[", "ATTR_XY_COLOR", "]", "=", "[", "x_val", ",", "y_val", "]", "if", "brightness", "is", "not", "None", ":", "service_data", "[", "ATTR_BRIGHTNESS", "]", "=", "brightness", "service_data", "[", "ATTR_WHITE_VALUE", "]", "=", "brightness", "if", "transition", "is", "not", "None", ":", "service_data", "[", "ATTR_TRANSITION", "]", "=", "transition", "await", "hass", ".", "services", ".", "async_call", "(", "LIGHT_DOMAIN", ",", "SERVICE_TURN_ON", ",", "service_data", ")" ]
[ 89, 0 ]
[ 101, 87 ]
python
en
['en', 'da', 'en']
True
async_set_lights_temp
(hass, lights, mired, brightness, transition)
Set color of array of lights.
Set color of array of lights.
async def async_set_lights_temp(hass, lights, mired, brightness, transition): """Set color of array of lights.""" for light in lights: if is_on(hass, light): service_data = {ATTR_ENTITY_ID: light} if mired is not None: service_data[ATTR_COLOR_TEMP] = int(mired) if brightness is not None: service_data[ATTR_BRIGHTNESS] = brightness if transition is not None: service_data[ATTR_TRANSITION] = transition await hass.services.async_call(LIGHT_DOMAIN, SERVICE_TURN_ON, service_data)
[ "async", "def", "async_set_lights_temp", "(", "hass", ",", "lights", ",", "mired", ",", "brightness", ",", "transition", ")", ":", "for", "light", "in", "lights", ":", "if", "is_on", "(", "hass", ",", "light", ")", ":", "service_data", "=", "{", "ATTR_ENTITY_ID", ":", "light", "}", "if", "mired", "is", "not", "None", ":", "service_data", "[", "ATTR_COLOR_TEMP", "]", "=", "int", "(", "mired", ")", "if", "brightness", "is", "not", "None", ":", "service_data", "[", "ATTR_BRIGHTNESS", "]", "=", "brightness", "if", "transition", "is", "not", "None", ":", "service_data", "[", "ATTR_TRANSITION", "]", "=", "transition", "await", "hass", ".", "services", ".", "async_call", "(", "LIGHT_DOMAIN", ",", "SERVICE_TURN_ON", ",", "service_data", ")" ]
[ 104, 0 ]
[ 115, 87 ]
python
en
['en', 'da', 'en']
True
async_set_lights_rgb
(hass, lights, rgb, transition)
Set color of array of lights.
Set color of array of lights.
async def async_set_lights_rgb(hass, lights, rgb, transition): """Set color of array of lights.""" for light in lights: if is_on(hass, light): service_data = {ATTR_ENTITY_ID: light} if rgb is not None: service_data[ATTR_RGB_COLOR] = rgb if transition is not None: service_data[ATTR_TRANSITION] = transition await hass.services.async_call(LIGHT_DOMAIN, SERVICE_TURN_ON, service_data)
[ "async", "def", "async_set_lights_rgb", "(", "hass", ",", "lights", ",", "rgb", ",", "transition", ")", ":", "for", "light", "in", "lights", ":", "if", "is_on", "(", "hass", ",", "light", ")", ":", "service_data", "=", "{", "ATTR_ENTITY_ID", ":", "light", "}", "if", "rgb", "is", "not", "None", ":", "service_data", "[", "ATTR_RGB_COLOR", "]", "=", "rgb", "if", "transition", "is", "not", "None", ":", "service_data", "[", "ATTR_TRANSITION", "]", "=", "transition", "await", "hass", ".", "services", ".", "async_call", "(", "LIGHT_DOMAIN", ",", "SERVICE_TURN_ON", ",", "service_data", ")" ]
[ 118, 0 ]
[ 127, 87 ]
python
en
['en', 'da', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the Flux switches.
Set up the Flux switches.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Flux switches.""" name = config.get(CONF_NAME) lights = config.get(CONF_LIGHTS) start_time = config.get(CONF_START_TIME) stop_time = config.get(CONF_STOP_TIME) start_colortemp = config.get(CONF_START_CT) sunset_colortemp = config.get(CONF_SUNSET_CT) stop_colortemp = config.get(CONF_STOP_CT) brightness = config.get(CONF_BRIGHTNESS) disable_brightness_adjust = config.get(CONF_DISABLE_BRIGHTNESS_ADJUST) mode = config.get(CONF_MODE) interval = config.get(CONF_INTERVAL) transition = config.get(ATTR_TRANSITION) flux = FluxSwitch( name, hass, lights, start_time, stop_time, start_colortemp, sunset_colortemp, stop_colortemp, brightness, disable_brightness_adjust, mode, interval, transition, ) async_add_entities([flux]) async def async_update(call=None): """Update lights.""" await flux.async_flux_update() service_name = slugify(f"{name} update") hass.services.async_register(DOMAIN, service_name, async_update)
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "lights", "=", "config", ".", "get", "(", "CONF_LIGHTS", ")", "start_time", "=", "config", ".", "get", "(", "CONF_START_TIME", ")", "stop_time", "=", "config", ".", "get", "(", "CONF_STOP_TIME", ")", "start_colortemp", "=", "config", ".", "get", "(", "CONF_START_CT", ")", "sunset_colortemp", "=", "config", ".", "get", "(", "CONF_SUNSET_CT", ")", "stop_colortemp", "=", "config", ".", "get", "(", "CONF_STOP_CT", ")", "brightness", "=", "config", ".", "get", "(", "CONF_BRIGHTNESS", ")", "disable_brightness_adjust", "=", "config", ".", "get", "(", "CONF_DISABLE_BRIGHTNESS_ADJUST", ")", "mode", "=", "config", ".", "get", "(", "CONF_MODE", ")", "interval", "=", "config", ".", "get", "(", "CONF_INTERVAL", ")", "transition", "=", "config", ".", "get", "(", "ATTR_TRANSITION", ")", "flux", "=", "FluxSwitch", "(", "name", ",", "hass", ",", "lights", ",", "start_time", ",", "stop_time", ",", "start_colortemp", ",", "sunset_colortemp", ",", "stop_colortemp", ",", "brightness", ",", "disable_brightness_adjust", ",", "mode", ",", "interval", ",", "transition", ",", ")", "async_add_entities", "(", "[", "flux", "]", ")", "async", "def", "async_update", "(", "call", "=", "None", ")", ":", "\"\"\"Update lights.\"\"\"", "await", "flux", ".", "async_flux_update", "(", ")", "service_name", "=", "slugify", "(", "f\"{name} update\"", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "service_name", ",", "async_update", ")" ]
[ 130, 0 ]
[ 166, 68 ]
python
en
['en', 'en', 'en']
True
FluxSwitch.__init__
( self, name, hass, lights, start_time, stop_time, start_colortemp, sunset_colortemp, stop_colortemp, brightness, disable_brightness_adjust, mode, interval, transition, )
Initialize the Flux switch.
Initialize the Flux switch.
def __init__( self, name, hass, lights, start_time, stop_time, start_colortemp, sunset_colortemp, stop_colortemp, brightness, disable_brightness_adjust, mode, interval, transition, ): """Initialize the Flux switch.""" self._name = name self.hass = hass self._lights = lights self._start_time = start_time self._stop_time = stop_time self._start_colortemp = start_colortemp self._sunset_colortemp = sunset_colortemp self._stop_colortemp = stop_colortemp self._brightness = brightness self._disable_brightness_adjust = disable_brightness_adjust self._mode = mode self._interval = interval self._transition = transition self.unsub_tracker = None
[ "def", "__init__", "(", "self", ",", "name", ",", "hass", ",", "lights", ",", "start_time", ",", "stop_time", ",", "start_colortemp", ",", "sunset_colortemp", ",", "stop_colortemp", ",", "brightness", ",", "disable_brightness_adjust", ",", "mode", ",", "interval", ",", "transition", ",", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "hass", "=", "hass", "self", ".", "_lights", "=", "lights", "self", ".", "_start_time", "=", "start_time", "self", ".", "_stop_time", "=", "stop_time", "self", ".", "_start_colortemp", "=", "start_colortemp", "self", ".", "_sunset_colortemp", "=", "sunset_colortemp", "self", ".", "_stop_colortemp", "=", "stop_colortemp", "self", ".", "_brightness", "=", "brightness", "self", ".", "_disable_brightness_adjust", "=", "disable_brightness_adjust", "self", ".", "_mode", "=", "mode", "self", ".", "_interval", "=", "interval", "self", ".", "_transition", "=", "transition", "self", ".", "unsub_tracker", "=", "None" ]
[ 172, 4 ]
[ 202, 33 ]
python
en
['en', 'en', 'en']
True
FluxSwitch.name
(self)
Return the name of the device if any.
Return the name of the device if any.
def name(self): """Return the name of the device if any.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 205, 4 ]
[ 207, 25 ]
python
en
['en', 'en', 'en']
True
FluxSwitch.is_on
(self)
Return true if switch is on.
Return true if switch is on.
def is_on(self): """Return true if switch is on.""" return self.unsub_tracker is not None
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "unsub_tracker", "is", "not", "None" ]
[ 210, 4 ]
[ 212, 45 ]
python
en
['en', 'fy', 'en']
True
FluxSwitch.async_added_to_hass
(self)
Call when entity about to be added to hass.
Call when entity about to be added to hass.
async def async_added_to_hass(self): """Call when entity about to be added to hass.""" last_state = await self.async_get_last_state() if last_state and last_state.state == STATE_ON: await self.async_turn_on()
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "last_state", "=", "await", "self", ".", "async_get_last_state", "(", ")", "if", "last_state", "and", "last_state", ".", "state", "==", "STATE_ON", ":", "await", "self", ".", "async_turn_on", "(", ")" ]
[ 214, 4 ]
[ 218, 38 ]
python
en
['en', 'en', 'en']
True
FluxSwitch.async_turn_on
(self, **kwargs)
Turn on flux.
Turn on flux.
async def async_turn_on(self, **kwargs): """Turn on flux.""" if self.is_on: return self.unsub_tracker = event.async_track_time_interval( self.hass, self.async_flux_update, datetime.timedelta(seconds=self._interval), ) # Make initial update await self.async_flux_update() self.async_write_ha_state()
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "is_on", ":", "return", "self", ".", "unsub_tracker", "=", "event", ".", "async_track_time_interval", "(", "self", ".", "hass", ",", "self", ".", "async_flux_update", ",", "datetime", ".", "timedelta", "(", "seconds", "=", "self", ".", "_interval", ")", ",", ")", "# Make initial update", "await", "self", ".", "async_flux_update", "(", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 220, 4 ]
[ 234, 35 ]
python
en
['en', 'et', 'en']
True
FluxSwitch.async_turn_off
(self, **kwargs)
Turn off flux.
Turn off flux.
async def async_turn_off(self, **kwargs): """Turn off flux.""" if self.is_on: self.unsub_tracker() self.unsub_tracker = None self.async_write_ha_state()
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "is_on", ":", "self", ".", "unsub_tracker", "(", ")", "self", ".", "unsub_tracker", "=", "None", "self", ".", "async_write_ha_state", "(", ")" ]
[ 236, 4 ]
[ 242, 35 ]
python
en
['en', 'da', 'en']
True
FluxSwitch.async_flux_update
(self, utcnow=None)
Update all the lights using flux.
Update all the lights using flux.
async def async_flux_update(self, utcnow=None): """Update all the lights using flux.""" if utcnow is None: utcnow = dt_utcnow() now = as_local(utcnow) sunset = get_astral_event_date(self.hass, SUN_EVENT_SUNSET, now.date()) start_time = self.find_start_time(now) stop_time = self.find_stop_time(now) if stop_time <= start_time: # stop_time does not happen in the same day as start_time if start_time < now: # stop time is tomorrow stop_time += datetime.timedelta(days=1) elif now < start_time: # stop_time was yesterday since the new start_time is not reached stop_time -= datetime.timedelta(days=1) if start_time < now < sunset: # Daytime time_state = "day" temp_range = abs(self._start_colortemp - self._sunset_colortemp) day_length = int(sunset.timestamp() - start_time.timestamp()) seconds_from_start = int(now.timestamp() - start_time.timestamp()) percentage_complete = seconds_from_start / day_length temp_offset = temp_range * percentage_complete if self._start_colortemp > self._sunset_colortemp: temp = self._start_colortemp - temp_offset else: temp = self._start_colortemp + temp_offset else: # Night time time_state = "night" if now < stop_time: if stop_time < start_time and stop_time.day == sunset.day: # we need to use yesterday's sunset time sunset_time = sunset - datetime.timedelta(days=1) else: sunset_time = sunset night_length = int(stop_time.timestamp() - sunset_time.timestamp()) seconds_from_sunset = int(now.timestamp() - sunset_time.timestamp()) percentage_complete = seconds_from_sunset / night_length else: percentage_complete = 1 temp_range = abs(self._sunset_colortemp - self._stop_colortemp) temp_offset = temp_range * percentage_complete if self._sunset_colortemp > self._stop_colortemp: temp = self._sunset_colortemp - temp_offset else: temp = self._sunset_colortemp + temp_offset rgb = color_temperature_to_rgb(temp) x_val, y_val, b_val = color_RGB_to_xy_brightness(*rgb) brightness = self._brightness if self._brightness else b_val if self._disable_brightness_adjust: brightness = None if self._mode == MODE_XY: await async_set_lights_xy( self.hass, self._lights, x_val, y_val, brightness, self._transition ) _LOGGER.debug( "Lights updated to x:%s y:%s brightness:%s, %s%% " "of %s cycle complete at %s", x_val, y_val, brightness, round(percentage_complete * 100), time_state, now, ) elif self._mode == MODE_RGB: await async_set_lights_rgb(self.hass, self._lights, rgb, self._transition) _LOGGER.debug( "Lights updated to rgb:%s, %s%% of %s cycle complete at %s", rgb, round(percentage_complete * 100), time_state, now, ) else: # Convert to mired and clamp to allowed values mired = color_temperature_kelvin_to_mired(temp) await async_set_lights_temp( self.hass, self._lights, mired, brightness, self._transition ) _LOGGER.debug( "Lights updated to mired:%s brightness:%s, %s%% " "of %s cycle complete at %s", mired, brightness, round(percentage_complete * 100), time_state, now, )
[ "async", "def", "async_flux_update", "(", "self", ",", "utcnow", "=", "None", ")", ":", "if", "utcnow", "is", "None", ":", "utcnow", "=", "dt_utcnow", "(", ")", "now", "=", "as_local", "(", "utcnow", ")", "sunset", "=", "get_astral_event_date", "(", "self", ".", "hass", ",", "SUN_EVENT_SUNSET", ",", "now", ".", "date", "(", ")", ")", "start_time", "=", "self", ".", "find_start_time", "(", "now", ")", "stop_time", "=", "self", ".", "find_stop_time", "(", "now", ")", "if", "stop_time", "<=", "start_time", ":", "# stop_time does not happen in the same day as start_time", "if", "start_time", "<", "now", ":", "# stop time is tomorrow", "stop_time", "+=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "elif", "now", "<", "start_time", ":", "# stop_time was yesterday since the new start_time is not reached", "stop_time", "-=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "if", "start_time", "<", "now", "<", "sunset", ":", "# Daytime", "time_state", "=", "\"day\"", "temp_range", "=", "abs", "(", "self", ".", "_start_colortemp", "-", "self", ".", "_sunset_colortemp", ")", "day_length", "=", "int", "(", "sunset", ".", "timestamp", "(", ")", "-", "start_time", ".", "timestamp", "(", ")", ")", "seconds_from_start", "=", "int", "(", "now", ".", "timestamp", "(", ")", "-", "start_time", ".", "timestamp", "(", ")", ")", "percentage_complete", "=", "seconds_from_start", "/", "day_length", "temp_offset", "=", "temp_range", "*", "percentage_complete", "if", "self", ".", "_start_colortemp", ">", "self", ".", "_sunset_colortemp", ":", "temp", "=", "self", ".", "_start_colortemp", "-", "temp_offset", "else", ":", "temp", "=", "self", ".", "_start_colortemp", "+", "temp_offset", "else", ":", "# Night time", "time_state", "=", "\"night\"", "if", "now", "<", "stop_time", ":", "if", "stop_time", "<", "start_time", "and", "stop_time", ".", "day", "==", "sunset", ".", "day", ":", "# we need to use yesterday's sunset time", "sunset_time", "=", "sunset", "-", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "else", ":", "sunset_time", "=", "sunset", "night_length", "=", "int", "(", "stop_time", ".", "timestamp", "(", ")", "-", "sunset_time", ".", "timestamp", "(", ")", ")", "seconds_from_sunset", "=", "int", "(", "now", ".", "timestamp", "(", ")", "-", "sunset_time", ".", "timestamp", "(", ")", ")", "percentage_complete", "=", "seconds_from_sunset", "/", "night_length", "else", ":", "percentage_complete", "=", "1", "temp_range", "=", "abs", "(", "self", ".", "_sunset_colortemp", "-", "self", ".", "_stop_colortemp", ")", "temp_offset", "=", "temp_range", "*", "percentage_complete", "if", "self", ".", "_sunset_colortemp", ">", "self", ".", "_stop_colortemp", ":", "temp", "=", "self", ".", "_sunset_colortemp", "-", "temp_offset", "else", ":", "temp", "=", "self", ".", "_sunset_colortemp", "+", "temp_offset", "rgb", "=", "color_temperature_to_rgb", "(", "temp", ")", "x_val", ",", "y_val", ",", "b_val", "=", "color_RGB_to_xy_brightness", "(", "*", "rgb", ")", "brightness", "=", "self", ".", "_brightness", "if", "self", ".", "_brightness", "else", "b_val", "if", "self", ".", "_disable_brightness_adjust", ":", "brightness", "=", "None", "if", "self", ".", "_mode", "==", "MODE_XY", ":", "await", "async_set_lights_xy", "(", "self", ".", "hass", ",", "self", ".", "_lights", ",", "x_val", ",", "y_val", ",", "brightness", ",", "self", ".", "_transition", ")", "_LOGGER", ".", "debug", "(", "\"Lights updated to x:%s y:%s brightness:%s, %s%% \"", "\"of %s cycle complete at %s\"", ",", "x_val", ",", "y_val", ",", "brightness", ",", "round", "(", "percentage_complete", "*", "100", ")", ",", "time_state", ",", "now", ",", ")", "elif", "self", ".", "_mode", "==", "MODE_RGB", ":", "await", "async_set_lights_rgb", "(", "self", ".", "hass", ",", "self", ".", "_lights", ",", "rgb", ",", "self", ".", "_transition", ")", "_LOGGER", ".", "debug", "(", "\"Lights updated to rgb:%s, %s%% of %s cycle complete at %s\"", ",", "rgb", ",", "round", "(", "percentage_complete", "*", "100", ")", ",", "time_state", ",", "now", ",", ")", "else", ":", "# Convert to mired and clamp to allowed values", "mired", "=", "color_temperature_kelvin_to_mired", "(", "temp", ")", "await", "async_set_lights_temp", "(", "self", ".", "hass", ",", "self", ".", "_lights", ",", "mired", ",", "brightness", ",", "self", ".", "_transition", ")", "_LOGGER", ".", "debug", "(", "\"Lights updated to mired:%s brightness:%s, %s%% \"", "\"of %s cycle complete at %s\"", ",", "mired", ",", "brightness", ",", "round", "(", "percentage_complete", "*", "100", ")", ",", "time_state", ",", "now", ",", ")" ]
[ 244, 4 ]
[ 341, 13 ]
python
en
['en', 'en', 'en']
True