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
Unauthorized.__init__
( self, context: Optional["Context"] = None, user_id: Optional[str] = None, entity_id: Optional[str] = None, config_entry_id: Optional[str] = None, perm_category: Optional[str] = None, permission: Optional[str] = None, )
Unauthorized error.
Unauthorized error.
def __init__( self, context: Optional["Context"] = None, user_id: Optional[str] = None, entity_id: Optional[str] = None, config_entry_id: Optional[str] = None, perm_category: Optional[str] = None, permission: Optional[str] = None, ) -> None: """Unauthorized error.""" super().__init__(self.__class__.__name__) self.context = context if user_id is None and context is not None: user_id = context.user_id self.user_id = user_id self.entity_id = entity_id self.config_entry_id = config_entry_id # Not all actions have an ID (like adding config entry) # We then use this fallback to know what category was unauth self.perm_category = perm_category self.permission = permission
[ "def", "__init__", "(", "self", ",", "context", ":", "Optional", "[", "\"Context\"", "]", "=", "None", ",", "user_id", ":", "Optional", "[", "str", "]", "=", "None", ",", "entity_id", ":", "Optional", "[", "str", "]", "=", "None", ",", "config_entry_id", ":", "Optional", "[", "str", "]", "=", "None", ",", "perm_category", ":", "Optional", "[", "str", "]", "=", "None", ",", "permission", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "self", ".", "__class__", ".", "__name__", ")", "self", ".", "context", "=", "context", "if", "user_id", "is", "None", "and", "context", "is", "not", "None", ":", "user_id", "=", "context", ".", "user_id", "self", ".", "user_id", "=", "user_id", "self", ".", "entity_id", "=", "entity_id", "self", ".", "config_entry_id", "=", "config_entry_id", "# Not all actions have an ID (like adding config entry)", "# We then use this fallback to know what category was unauth", "self", ".", "perm_category", "=", "perm_category", "self", ".", "permission", "=", "permission" ]
[ 42, 4 ]
[ 64, 36 ]
python
de
['de', 'sr', 'it']
False
ServiceNotFound.__init__
(self, domain: str, service: str)
Initialize error.
Initialize error.
def __init__(self, domain: str, service: str) -> None: """Initialize error.""" super().__init__(self, f"Service {domain}.{service} not found") self.domain = domain self.service = service
[ "def", "__init__", "(", "self", ",", "domain", ":", "str", ",", "service", ":", "str", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "self", ",", "f\"Service {domain}.{service} not found\"", ")", "self", ".", "domain", "=", "domain", "self", ".", "service", "=", "service" ]
[ 74, 4 ]
[ 78, 30 ]
python
da
['da', 'la', 'it']
False
ServiceNotFound.__str__
(self)
Return string representation.
Return string representation.
def __str__(self) -> str: """Return string representation.""" return f"Unable to find service {self.domain}/{self.service}"
[ "def", "__str__", "(", "self", ")", "->", "str", ":", "return", "f\"Unable to find service {self.domain}/{self.service}\"" ]
[ 80, 4 ]
[ 82, 69 ]
python
en
['en', 'no', 'en']
True
run
(args)
Handle keyring script.
Handle keyring script.
def run(args): """Handle keyring script.""" parser = argparse.ArgumentParser( description=( "Modify Home Assistant secrets in the default keyring. " "Use the secrets in configuration files with: " "!secret <name>" ) ) parser.add_argument("--script", choices=["keyring"]) parser.add_argument( "action", choices=["get", "set", "del", "info"], help="Get, set or delete a secret", ) parser.add_argument("name", help="Name of the secret", nargs="?", default=None) import keyring # pylint: disable=import-outside-toplevel # pylint: disable=import-outside-toplevel from keyring.util import platform_ as platform args = parser.parse_args(args) if args.action == "info": keyr = keyring.get_keyring() print("Keyring version {}\n".format(REQUIREMENTS[0].split("==")[1])) print(f"Active keyring : {keyr.__module__}") config_name = os.path.join(platform.config_root(), "keyringrc.cfg") print(f"Config location : {config_name}") print(f"Data location : {platform.data_root()}\n") elif args.name is None: parser.print_help() return 1 if args.action == "set": entered_secret = getpass.getpass(f"Please enter the secret for {args.name}: ") keyring.set_password(_SECRET_NAMESPACE, args.name, entered_secret) print(f"Secret {args.name} set successfully") elif args.action == "get": the_secret = keyring.get_password(_SECRET_NAMESPACE, args.name) if the_secret is None: print(f"Secret {args.name} not found") else: print(f"Secret {args.name}={the_secret}") elif args.action == "del": try: keyring.delete_password(_SECRET_NAMESPACE, args.name) print(f"Deleted secret {args.name}") except keyring.errors.PasswordDeleteError: print(f"Secret {args.name} not found")
[ "def", "run", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "\"Modify Home Assistant secrets in the default keyring. \"", "\"Use the secrets in configuration files with: \"", "\"!secret <name>\"", ")", ")", "parser", ".", "add_argument", "(", "\"--script\"", ",", "choices", "=", "[", "\"keyring\"", "]", ")", "parser", ".", "add_argument", "(", "\"action\"", ",", "choices", "=", "[", "\"get\"", ",", "\"set\"", ",", "\"del\"", ",", "\"info\"", "]", ",", "help", "=", "\"Get, set or delete a secret\"", ",", ")", "parser", ".", "add_argument", "(", "\"name\"", ",", "help", "=", "\"Name of the secret\"", ",", "nargs", "=", "\"?\"", ",", "default", "=", "None", ")", "import", "keyring", "# pylint: disable=import-outside-toplevel", "# pylint: disable=import-outside-toplevel", "from", "keyring", ".", "util", "import", "platform_", "as", "platform", "args", "=", "parser", ".", "parse_args", "(", "args", ")", "if", "args", ".", "action", "==", "\"info\"", ":", "keyr", "=", "keyring", ".", "get_keyring", "(", ")", "print", "(", "\"Keyring version {}\\n\"", ".", "format", "(", "REQUIREMENTS", "[", "0", "]", ".", "split", "(", "\"==\"", ")", "[", "1", "]", ")", ")", "print", "(", "f\"Active keyring : {keyr.__module__}\"", ")", "config_name", "=", "os", ".", "path", ".", "join", "(", "platform", ".", "config_root", "(", ")", ",", "\"keyringrc.cfg\"", ")", "print", "(", "f\"Config location : {config_name}\"", ")", "print", "(", "f\"Data location : {platform.data_root()}\\n\"", ")", "elif", "args", ".", "name", "is", "None", ":", "parser", ".", "print_help", "(", ")", "return", "1", "if", "args", ".", "action", "==", "\"set\"", ":", "entered_secret", "=", "getpass", ".", "getpass", "(", "f\"Please enter the secret for {args.name}: \"", ")", "keyring", ".", "set_password", "(", "_SECRET_NAMESPACE", ",", "args", ".", "name", ",", "entered_secret", ")", "print", "(", "f\"Secret {args.name} set successfully\"", ")", "elif", "args", ".", "action", "==", "\"get\"", ":", "the_secret", "=", "keyring", ".", "get_password", "(", "_SECRET_NAMESPACE", ",", "args", ".", "name", ")", "if", "the_secret", "is", "None", ":", "print", "(", "f\"Secret {args.name} not found\"", ")", "else", ":", "print", "(", "f\"Secret {args.name}={the_secret}\"", ")", "elif", "args", ".", "action", "==", "\"del\"", ":", "try", ":", "keyring", ".", "delete_password", "(", "_SECRET_NAMESPACE", ",", "args", ".", "name", ")", "print", "(", "f\"Deleted secret {args.name}\"", ")", "except", "keyring", ".", "errors", ".", "PasswordDeleteError", ":", "print", "(", "f\"Secret {args.name} not found\"", ")" ]
[ 11, 0 ]
[ 61, 50 ]
python
en
['en', 'af', 'en']
True
websocket_client
(hass, hass_ws_client)
Create a websocket client.
Create a websocket client.
async def websocket_client(hass, hass_ws_client): """Create a websocket client.""" return await hass_ws_client(hass)
[ "async", "def", "websocket_client", "(", "hass", ",", "hass_ws_client", ")", ":", "return", "await", "hass_ws_client", "(", "hass", ")" ]
[ 9, 0 ]
[ 11, 37 ]
python
en
['en', 'lb', 'en']
True
no_auth_websocket_client
(hass, aiohttp_client)
Websocket connection that requires authentication.
Websocket connection that requires authentication.
async def no_auth_websocket_client(hass, aiohttp_client): """Websocket connection that requires authentication.""" assert await async_setup_component(hass, "websocket_api", {}) await hass.async_block_till_done() client = await aiohttp_client(hass.http.app) ws = await client.ws_connect(URL) auth_ok = await ws.receive_json() assert auth_ok["type"] == TYPE_AUTH_REQUIRED ws.client = client yield ws if not ws.closed: await ws.close()
[ "async", "def", "no_auth_websocket_client", "(", "hass", ",", "aiohttp_client", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"websocket_api\"", ",", "{", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "client", "=", "await", "aiohttp_client", "(", "hass", ".", "http", ".", "app", ")", "ws", "=", "await", "client", ".", "ws_connect", "(", "URL", ")", "auth_ok", "=", "await", "ws", ".", "receive_json", "(", ")", "assert", "auth_ok", "[", "\"type\"", "]", "==", "TYPE_AUTH_REQUIRED", "ws", ".", "client", "=", "client", "yield", "ws", "if", "not", "ws", ".", "closed", ":", "await", "ws", ".", "close", "(", ")" ]
[ 15, 0 ]
[ 30, 24 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Deutsche Bahn Sensor.
Set up the Deutsche Bahn Sensor.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Deutsche Bahn Sensor.""" start = config.get(CONF_START) destination = config[CONF_DESTINATION] offset = config[CONF_OFFSET] only_direct = config[CONF_ONLY_DIRECT] add_entities([DeutscheBahnSensor(start, destination, offset, only_direct)], True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "start", "=", "config", ".", "get", "(", "CONF_START", ")", "destination", "=", "config", "[", "CONF_DESTINATION", "]", "offset", "=", "config", "[", "CONF_OFFSET", "]", "only_direct", "=", "config", "[", "CONF_ONLY_DIRECT", "]", "add_entities", "(", "[", "DeutscheBahnSensor", "(", "start", ",", "destination", ",", "offset", ",", "only_direct", ")", "]", ",", "True", ")" ]
[ 32, 0 ]
[ 39, 85 ]
python
de
['de', 'nl', 'de']
True
DeutscheBahnSensor.__init__
(self, start, goal, offset, only_direct)
Initialize the sensor.
Initialize the sensor.
def __init__(self, start, goal, offset, only_direct): """Initialize the sensor.""" self._name = f"{start} to {goal}" self.data = SchieneData(start, goal, offset, only_direct) self._state = None
[ "def", "__init__", "(", "self", ",", "start", ",", "goal", ",", "offset", ",", "only_direct", ")", ":", "self", ".", "_name", "=", "f\"{start} to {goal}\"", "self", ".", "data", "=", "SchieneData", "(", "start", ",", "goal", ",", "offset", ",", "only_direct", ")", "self", ".", "_state", "=", "None" ]
[ 45, 4 ]
[ 49, 26 ]
python
en
['en', 'en', 'en']
True
DeutscheBahnSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 52, 4 ]
[ 54, 25 ]
python
en
['en', 'mi', 'en']
True
DeutscheBahnSensor.icon
(self)
Return the icon for the frontend.
Return the icon for the frontend.
def icon(self): """Return the icon for the frontend.""" return ICON
[ "def", "icon", "(", "self", ")", ":", "return", "ICON" ]
[ 57, 4 ]
[ 59, 19 ]
python
en
['en', 'en', 'en']
True
DeutscheBahnSensor.state
(self)
Return the departure time of the next train.
Return the departure time of the next train.
def state(self): """Return the departure time of the next train.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 62, 4 ]
[ 64, 26 ]
python
en
['en', 'en', 'en']
True
DeutscheBahnSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" connections = self.data.connections[0] if len(self.data.connections) > 1: connections["next"] = self.data.connections[1]["departure"] if len(self.data.connections) > 2: connections["next_on"] = self.data.connections[2]["departure"] return connections
[ "def", "device_state_attributes", "(", "self", ")", ":", "connections", "=", "self", ".", "data", ".", "connections", "[", "0", "]", "if", "len", "(", "self", ".", "data", ".", "connections", ")", ">", "1", ":", "connections", "[", "\"next\"", "]", "=", "self", ".", "data", ".", "connections", "[", "1", "]", "[", "\"departure\"", "]", "if", "len", "(", "self", ".", "data", ".", "connections", ")", ">", "2", ":", "connections", "[", "\"next_on\"", "]", "=", "self", ".", "data", ".", "connections", "[", "2", "]", "[", "\"departure\"", "]", "return", "connections" ]
[ 67, 4 ]
[ 74, 26 ]
python
en
['en', 'en', 'en']
True
DeutscheBahnSensor.update
(self)
Get the latest delay from bahn.de and updates the state.
Get the latest delay from bahn.de and updates the state.
def update(self): """Get the latest delay from bahn.de and updates the state.""" self.data.update() self._state = self.data.connections[0].get("departure", "Unknown") if self.data.connections[0].get("delay", 0) != 0: self._state += f" + {self.data.connections[0]['delay']}"
[ "def", "update", "(", "self", ")", ":", "self", ".", "data", ".", "update", "(", ")", "self", ".", "_state", "=", "self", ".", "data", ".", "connections", "[", "0", "]", ".", "get", "(", "\"departure\"", ",", "\"Unknown\"", ")", "if", "self", ".", "data", ".", "connections", "[", "0", "]", ".", "get", "(", "\"delay\"", ",", "0", ")", "!=", "0", ":", "self", ".", "_state", "+=", "f\" + {self.data.connections[0]['delay']}\"" ]
[ 76, 4 ]
[ 81, 68 ]
python
en
['en', 'en', 'en']
True
SchieneData.__init__
(self, start, goal, offset, only_direct)
Initialize the sensor.
Initialize the sensor.
def __init__(self, start, goal, offset, only_direct): """Initialize the sensor.""" self.start = start self.goal = goal self.offset = offset self.only_direct = only_direct self.schiene = schiene.Schiene() self.connections = [{}]
[ "def", "__init__", "(", "self", ",", "start", ",", "goal", ",", "offset", ",", "only_direct", ")", ":", "self", ".", "start", "=", "start", "self", ".", "goal", "=", "goal", "self", ".", "offset", "=", "offset", "self", ".", "only_direct", "=", "only_direct", "self", ".", "schiene", "=", "schiene", ".", "Schiene", "(", ")", "self", ".", "connections", "=", "[", "{", "}", "]" ]
[ 87, 4 ]
[ 95, 31 ]
python
en
['en', 'en', 'en']
True
SchieneData.update
(self)
Update the connection data.
Update the connection data.
def update(self): """Update the connection data.""" self.connections = self.schiene.connections( self.start, self.goal, dt_util.as_local(dt_util.utcnow() + self.offset), self.only_direct, ) if not self.connections: self.connections = [{}] for con in self.connections: # Detail info is not useful. Having a more consistent interface # simplifies usage of template sensors. if "details" in con: con.pop("details") delay = con.get("delay", {"delay_departure": 0, "delay_arrival": 0}) con["delay"] = delay["delay_departure"] con["delay_arrival"] = delay["delay_arrival"] con["ontime"] = con.get("ontime", False)
[ "def", "update", "(", "self", ")", ":", "self", ".", "connections", "=", "self", ".", "schiene", ".", "connections", "(", "self", ".", "start", ",", "self", ".", "goal", ",", "dt_util", ".", "as_local", "(", "dt_util", ".", "utcnow", "(", ")", "+", "self", ".", "offset", ")", ",", "self", ".", "only_direct", ",", ")", "if", "not", "self", ".", "connections", ":", "self", ".", "connections", "=", "[", "{", "}", "]", "for", "con", "in", "self", ".", "connections", ":", "# Detail info is not useful. Having a more consistent interface", "# simplifies usage of template sensors.", "if", "\"details\"", "in", "con", ":", "con", ".", "pop", "(", "\"details\"", ")", "delay", "=", "con", ".", "get", "(", "\"delay\"", ",", "{", "\"delay_departure\"", ":", "0", ",", "\"delay_arrival\"", ":", "0", "}", ")", "con", "[", "\"delay\"", "]", "=", "delay", "[", "\"delay_departure\"", "]", "con", "[", "\"delay_arrival\"", "]", "=", "delay", "[", "\"delay_arrival\"", "]", "con", "[", "\"ontime\"", "]", "=", "con", ".", "get", "(", "\"ontime\"", ",", "False", ")" ]
[ 97, 4 ]
[ 117, 56 ]
python
en
['en', 'en', 'en']
True
async_get_device_config
(hass, config_entry)
Initiate the connection and services.
Initiate the connection and services.
async def async_get_device_config(hass, config_entry): """Initiate the connection and services.""" # Make a copy of addresses due to edge case where the list of devices could change during status update # Cannot be done concurrently due to issues with the underlying protocol. for address in list(devices): try: await devices[address].async_status() except AttributeError: pass await devices.async_load(id_devices=1) for addr in devices: device = devices[addr] flags = True for name in device.operating_flags: if not device.operating_flags[name].is_loaded: flags = False break if flags: for name in device.properties: if not device.properties[name].is_loaded: flags = False break # Cannot be done concurrently due to issues with the underlying protocol. if not device.aldb.is_loaded or not flags: await device.async_read_config() await devices.async_save(workdir=hass.config.config_dir)
[ "async", "def", "async_get_device_config", "(", "hass", ",", "config_entry", ")", ":", "# Make a copy of addresses due to edge case where the list of devices could change during status update", "# Cannot be done concurrently due to issues with the underlying protocol.", "for", "address", "in", "list", "(", "devices", ")", ":", "try", ":", "await", "devices", "[", "address", "]", ".", "async_status", "(", ")", "except", "AttributeError", ":", "pass", "await", "devices", ".", "async_load", "(", "id_devices", "=", "1", ")", "for", "addr", "in", "devices", ":", "device", "=", "devices", "[", "addr", "]", "flags", "=", "True", "for", "name", "in", "device", ".", "operating_flags", ":", "if", "not", "device", ".", "operating_flags", "[", "name", "]", ".", "is_loaded", ":", "flags", "=", "False", "break", "if", "flags", ":", "for", "name", "in", "device", ".", "properties", ":", "if", "not", "device", ".", "properties", "[", "name", "]", ".", "is_loaded", ":", "flags", "=", "False", "break", "# Cannot be done concurrently due to issues with the underlying protocol.", "if", "not", "device", ".", "aldb", ".", "is_loaded", "or", "not", "flags", ":", "await", "device", ".", "async_read_config", "(", ")", "await", "devices", ".", "async_save", "(", "workdir", "=", "hass", ".", "config", ".", "config_dir", ")" ]
[ 34, 0 ]
[ 62, 60 ]
python
en
['en', 'en', 'en']
True
close_insteon_connection
(*args)
Close the Insteon connection.
Close the Insteon connection.
async def close_insteon_connection(*args): """Close the Insteon connection.""" await async_close()
[ "async", "def", "close_insteon_connection", "(", "*", "args", ")", ":", "await", "async_close", "(", ")" ]
[ 65, 0 ]
[ 67, 23 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the Insteon platform.
Set up the Insteon platform.
async def async_setup(hass, config): """Set up the Insteon platform.""" if DOMAIN not in config: return True conf = config[DOMAIN] data, options = convert_yaml_to_config_flow(conf) if options: hass.data[DOMAIN] = {} hass.data[DOMAIN][OPTIONS] = options # Create a config entry with the connection data hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=data ) ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "if", "DOMAIN", "not", "in", "config", ":", "return", "True", "conf", "=", "config", "[", "DOMAIN", "]", "data", ",", "options", "=", "convert_yaml_to_config_flow", "(", "conf", ")", "if", "options", ":", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "OPTIONS", "]", "=", "options", "# Create a config entry with the connection data", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_IMPORT", "}", ",", "data", "=", "data", ")", ")", "return", "True" ]
[ 70, 0 ]
[ 86, 15 ]
python
en
['en', 'da', 'en']
True
async_setup_entry
(hass, entry)
Set up an Insteon entry.
Set up an Insteon entry.
async def async_setup_entry(hass, entry): """Set up an Insteon entry.""" if not devices.modem: try: await async_connect(**entry.data) except ConnectionError as exception: _LOGGER.error("Could not connect to Insteon modem") raise ConfigEntryNotReady from exception hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, close_insteon_connection) await devices.async_load( workdir=hass.config.config_dir, id_devices=0, load_modem_aldb=0 ) # If options existed in YAML and have not already been saved to the config entry # add them now if ( not entry.options and entry.source == SOURCE_IMPORT and hass.data.get(DOMAIN) and hass.data[DOMAIN].get(OPTIONS) ): hass.config_entries.async_update_entry( entry=entry, options=hass.data[DOMAIN][OPTIONS], ) for device_override in entry.options.get(CONF_OVERRIDE, []): # Override the device default capabilities for a specific address address = device_override.get("address") if not devices.get(address): cat = device_override[CONF_CAT] subcat = device_override[CONF_SUBCAT] devices.set_id(address, cat, subcat, 0) for device in entry.options.get(CONF_X10, []): housecode = device.get(CONF_HOUSECODE) unitcode = device.get(CONF_UNITCODE) x10_type = "on_off" steps = device.get(CONF_DIM_STEPS, 22) if device.get(CONF_PLATFORM) == "light": x10_type = "dimmable" elif device.get(CONF_PLATFORM) == "binary_sensor": x10_type = "sensor" _LOGGER.debug( "Adding X10 device to Insteon: %s %d %s", housecode, unitcode, x10_type ) device = devices.add_x10_device(housecode, unitcode, x10_type, steps) for component in INSTEON_COMPONENTS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) for address in devices: device = devices[address] platforms = get_device_platforms(device) if ON_OFF_EVENTS in platforms: add_on_off_event_device(hass, device) _LOGGER.debug("Insteon device count: %s", len(devices)) register_new_device_callback(hass) async_register_services(hass) device_registry = await hass.helpers.device_registry.async_get_registry() device_registry.async_get_or_create( config_entry_id=entry.entry_id, identifiers={(DOMAIN, str(devices.modem.address))}, manufacturer="Smart Home", name=f"{devices.modem.description} {devices.modem.address}", model=f"{devices.modem.model} ({devices.modem.cat!r}, 0x{devices.modem.subcat:02x})", sw_version=f"{devices.modem.firmware:02x} Engine Version: {devices.modem.engine_version}", ) asyncio.create_task(async_get_device_config(hass, entry)) return True
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ")", ":", "if", "not", "devices", ".", "modem", ":", "try", ":", "await", "async_connect", "(", "*", "*", "entry", ".", "data", ")", "except", "ConnectionError", "as", "exception", ":", "_LOGGER", ".", "error", "(", "\"Could not connect to Insteon modem\"", ")", "raise", "ConfigEntryNotReady", "from", "exception", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "close_insteon_connection", ")", "await", "devices", ".", "async_load", "(", "workdir", "=", "hass", ".", "config", ".", "config_dir", ",", "id_devices", "=", "0", ",", "load_modem_aldb", "=", "0", ")", "# If options existed in YAML and have not already been saved to the config entry", "# add them now", "if", "(", "not", "entry", ".", "options", "and", "entry", ".", "source", "==", "SOURCE_IMPORT", "and", "hass", ".", "data", ".", "get", "(", "DOMAIN", ")", "and", "hass", ".", "data", "[", "DOMAIN", "]", ".", "get", "(", "OPTIONS", ")", ")", ":", "hass", ".", "config_entries", ".", "async_update_entry", "(", "entry", "=", "entry", ",", "options", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "OPTIONS", "]", ",", ")", "for", "device_override", "in", "entry", ".", "options", ".", "get", "(", "CONF_OVERRIDE", ",", "[", "]", ")", ":", "# Override the device default capabilities for a specific address", "address", "=", "device_override", ".", "get", "(", "\"address\"", ")", "if", "not", "devices", ".", "get", "(", "address", ")", ":", "cat", "=", "device_override", "[", "CONF_CAT", "]", "subcat", "=", "device_override", "[", "CONF_SUBCAT", "]", "devices", ".", "set_id", "(", "address", ",", "cat", ",", "subcat", ",", "0", ")", "for", "device", "in", "entry", ".", "options", ".", "get", "(", "CONF_X10", ",", "[", "]", ")", ":", "housecode", "=", "device", ".", "get", "(", "CONF_HOUSECODE", ")", "unitcode", "=", "device", ".", "get", "(", "CONF_UNITCODE", ")", "x10_type", "=", "\"on_off\"", "steps", "=", "device", ".", "get", "(", "CONF_DIM_STEPS", ",", "22", ")", "if", "device", ".", "get", "(", "CONF_PLATFORM", ")", "==", "\"light\"", ":", "x10_type", "=", "\"dimmable\"", "elif", "device", ".", "get", "(", "CONF_PLATFORM", ")", "==", "\"binary_sensor\"", ":", "x10_type", "=", "\"sensor\"", "_LOGGER", ".", "debug", "(", "\"Adding X10 device to Insteon: %s %d %s\"", ",", "housecode", ",", "unitcode", ",", "x10_type", ")", "device", "=", "devices", ".", "add_x10_device", "(", "housecode", ",", "unitcode", ",", "x10_type", ",", "steps", ")", "for", "component", "in", "INSTEON_COMPONENTS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "component", ")", ")", "for", "address", "in", "devices", ":", "device", "=", "devices", "[", "address", "]", "platforms", "=", "get_device_platforms", "(", "device", ")", "if", "ON_OFF_EVENTS", "in", "platforms", ":", "add_on_off_event_device", "(", "hass", ",", "device", ")", "_LOGGER", ".", "debug", "(", "\"Insteon device count: %s\"", ",", "len", "(", "devices", ")", ")", "register_new_device_callback", "(", "hass", ")", "async_register_services", "(", "hass", ")", "device_registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "device_registry", ".", "async_get_or_create", "(", "config_entry_id", "=", "entry", ".", "entry_id", ",", "identifiers", "=", "{", "(", "DOMAIN", ",", "str", "(", "devices", ".", "modem", ".", "address", ")", ")", "}", ",", "manufacturer", "=", "\"Smart Home\"", ",", "name", "=", "f\"{devices.modem.description} {devices.modem.address}\"", ",", "model", "=", "f\"{devices.modem.model} ({devices.modem.cat!r}, 0x{devices.modem.subcat:02x})\"", ",", "sw_version", "=", "f\"{devices.modem.firmware:02x} Engine Version: {devices.modem.engine_version}\"", ",", ")", "asyncio", ".", "create_task", "(", "async_get_device_config", "(", "hass", ",", "entry", ")", ")", "return", "True" ]
[ 89, 0 ]
[ 167, 15 ]
python
en
['en', 'en', 'en']
True
async_check_ha_config_file
(hass: HomeAssistant)
Load and check if Home Assistant configuration file is valid. This method is a coroutine.
Load and check if Home Assistant configuration file is valid.
async def async_check_ha_config_file(hass: HomeAssistant) -> HomeAssistantConfig: """Load and check if Home Assistant configuration file is valid. This method is a coroutine. """ result = HomeAssistantConfig() def _pack_error( package: str, component: str, config: ConfigType, message: str ) -> None: """Handle errors from packages: _log_pkg_error.""" message = f"Package {package} setup failed. Component {component} {message}" domain = f"homeassistant.packages.{package}.{component}" pack_config = core_config[CONF_PACKAGES].get(package, config) result.add_error(message, domain, pack_config) def _comp_error(ex: Exception, domain: str, config: ConfigType) -> None: """Handle errors from components: async_log_exception.""" result.add_error(_format_config_error(ex, domain, config), domain, config) # Load configuration.yaml config_path = hass.config.path(YAML_CONFIG_FILE) try: if not await hass.async_add_executor_job(os.path.isfile, config_path): return result.add_error("File configuration.yaml not found.") config = await hass.async_add_executor_job(load_yaml_config_file, config_path) except FileNotFoundError: return result.add_error(f"File not found: {config_path}") except HomeAssistantError as err: return result.add_error(f"Error loading {config_path}: {err}") finally: yaml_loader.clear_secret_cache() # Extract and validate core [homeassistant] config try: core_config = config.pop(CONF_CORE, {}) core_config = CORE_CONFIG_SCHEMA(core_config) result[CONF_CORE] = core_config except vol.Invalid as err: result.add_error(err, CONF_CORE, core_config) core_config = {} # Merge packages await merge_packages_config( hass, config, core_config.get(CONF_PACKAGES, {}), _pack_error ) core_config.pop(CONF_PACKAGES, None) # Filter out repeating config sections components = {key.split(" ")[0] for key in config.keys()} # Process and validate config for domain in components: try: integration = await async_get_integration_with_requirements(hass, domain) except (RequirementsNotFound, loader.IntegrationNotFound) as ex: result.add_error(f"Component error: {domain} - {ex}") continue try: component = integration.get_component() except ImportError as ex: result.add_error(f"Component error: {domain} - {ex}") continue # Check if the integration has a custom config validator config_validator = None try: config_validator = integration.get_platform("config") except ImportError as err: # Filter out import error of the config platform. # If the config platform contains bad imports, make sure # that still fails. if err.name != f"{integration.pkg_path}.config": result.add_error(f"Error importing config platform {domain}: {err}") continue if config_validator is not None and hasattr( config_validator, "async_validate_config" ): try: return await config_validator.async_validate_config( # type: ignore hass, config ) except (vol.Invalid, HomeAssistantError) as ex: _comp_error(ex, domain, config) continue except Exception: # pylint: disable=broad-except result.add_error("Unknown error calling %s config validator", domain) continue config_schema = getattr(component, "CONFIG_SCHEMA", None) if config_schema is not None: try: config = config_schema(config) result[domain] = config[domain] except vol.Invalid as ex: _comp_error(ex, domain, config) continue component_platform_schema = getattr( component, "PLATFORM_SCHEMA_BASE", getattr(component, "PLATFORM_SCHEMA", None), ) if component_platform_schema is None: continue platforms = [] for p_name, p_config in config_per_platform(config, domain): # Validate component specific platform schema try: p_validated = component_platform_schema(p_config) except vol.Invalid as ex: _comp_error(ex, domain, config) continue # Not all platform components follow same pattern for platforms # So if p_name is None we are not going to validate platform # (the automation component is one of them) if p_name is None: platforms.append(p_validated) continue try: p_integration = await async_get_integration_with_requirements( hass, p_name ) platform = p_integration.get_platform(domain) except ( loader.IntegrationNotFound, RequirementsNotFound, ImportError, ) as ex: result.add_error(f"Platform error {domain}.{p_name} - {ex}") continue # Validate platform specific schema platform_schema = getattr(platform, "PLATFORM_SCHEMA", None) if platform_schema is not None: try: p_validated = platform_schema(p_validated) except vol.Invalid as ex: _comp_error(ex, f"{domain}.{p_name}", p_validated) continue platforms.append(p_validated) # Remove config for current component and add validated config back in. for filter_comp in extract_domain_configs(config, domain): del config[filter_comp] result[domain] = platforms return result
[ "async", "def", "async_check_ha_config_file", "(", "hass", ":", "HomeAssistant", ")", "->", "HomeAssistantConfig", ":", "result", "=", "HomeAssistantConfig", "(", ")", "def", "_pack_error", "(", "package", ":", "str", ",", "component", ":", "str", ",", "config", ":", "ConfigType", ",", "message", ":", "str", ")", "->", "None", ":", "\"\"\"Handle errors from packages: _log_pkg_error.\"\"\"", "message", "=", "f\"Package {package} setup failed. Component {component} {message}\"", "domain", "=", "f\"homeassistant.packages.{package}.{component}\"", "pack_config", "=", "core_config", "[", "CONF_PACKAGES", "]", ".", "get", "(", "package", ",", "config", ")", "result", ".", "add_error", "(", "message", ",", "domain", ",", "pack_config", ")", "def", "_comp_error", "(", "ex", ":", "Exception", ",", "domain", ":", "str", ",", "config", ":", "ConfigType", ")", "->", "None", ":", "\"\"\"Handle errors from components: async_log_exception.\"\"\"", "result", ".", "add_error", "(", "_format_config_error", "(", "ex", ",", "domain", ",", "config", ")", ",", "domain", ",", "config", ")", "# Load configuration.yaml", "config_path", "=", "hass", ".", "config", ".", "path", "(", "YAML_CONFIG_FILE", ")", "try", ":", "if", "not", "await", "hass", ".", "async_add_executor_job", "(", "os", ".", "path", ".", "isfile", ",", "config_path", ")", ":", "return", "result", ".", "add_error", "(", "\"File configuration.yaml not found.\"", ")", "config", "=", "await", "hass", ".", "async_add_executor_job", "(", "load_yaml_config_file", ",", "config_path", ")", "except", "FileNotFoundError", ":", "return", "result", ".", "add_error", "(", "f\"File not found: {config_path}\"", ")", "except", "HomeAssistantError", "as", "err", ":", "return", "result", ".", "add_error", "(", "f\"Error loading {config_path}: {err}\"", ")", "finally", ":", "yaml_loader", ".", "clear_secret_cache", "(", ")", "# Extract and validate core [homeassistant] config", "try", ":", "core_config", "=", "config", ".", "pop", "(", "CONF_CORE", ",", "{", "}", ")", "core_config", "=", "CORE_CONFIG_SCHEMA", "(", "core_config", ")", "result", "[", "CONF_CORE", "]", "=", "core_config", "except", "vol", ".", "Invalid", "as", "err", ":", "result", ".", "add_error", "(", "err", ",", "CONF_CORE", ",", "core_config", ")", "core_config", "=", "{", "}", "# Merge packages", "await", "merge_packages_config", "(", "hass", ",", "config", ",", "core_config", ".", "get", "(", "CONF_PACKAGES", ",", "{", "}", ")", ",", "_pack_error", ")", "core_config", ".", "pop", "(", "CONF_PACKAGES", ",", "None", ")", "# Filter out repeating config sections", "components", "=", "{", "key", ".", "split", "(", "\" \"", ")", "[", "0", "]", "for", "key", "in", "config", ".", "keys", "(", ")", "}", "# Process and validate config", "for", "domain", "in", "components", ":", "try", ":", "integration", "=", "await", "async_get_integration_with_requirements", "(", "hass", ",", "domain", ")", "except", "(", "RequirementsNotFound", ",", "loader", ".", "IntegrationNotFound", ")", "as", "ex", ":", "result", ".", "add_error", "(", "f\"Component error: {domain} - {ex}\"", ")", "continue", "try", ":", "component", "=", "integration", ".", "get_component", "(", ")", "except", "ImportError", "as", "ex", ":", "result", ".", "add_error", "(", "f\"Component error: {domain} - {ex}\"", ")", "continue", "# Check if the integration has a custom config validator", "config_validator", "=", "None", "try", ":", "config_validator", "=", "integration", ".", "get_platform", "(", "\"config\"", ")", "except", "ImportError", "as", "err", ":", "# Filter out import error of the config platform.", "# If the config platform contains bad imports, make sure", "# that still fails.", "if", "err", ".", "name", "!=", "f\"{integration.pkg_path}.config\"", ":", "result", ".", "add_error", "(", "f\"Error importing config platform {domain}: {err}\"", ")", "continue", "if", "config_validator", "is", "not", "None", "and", "hasattr", "(", "config_validator", ",", "\"async_validate_config\"", ")", ":", "try", ":", "return", "await", "config_validator", ".", "async_validate_config", "(", "# type: ignore", "hass", ",", "config", ")", "except", "(", "vol", ".", "Invalid", ",", "HomeAssistantError", ")", "as", "ex", ":", "_comp_error", "(", "ex", ",", "domain", ",", "config", ")", "continue", "except", "Exception", ":", "# pylint: disable=broad-except", "result", ".", "add_error", "(", "\"Unknown error calling %s config validator\"", ",", "domain", ")", "continue", "config_schema", "=", "getattr", "(", "component", ",", "\"CONFIG_SCHEMA\"", ",", "None", ")", "if", "config_schema", "is", "not", "None", ":", "try", ":", "config", "=", "config_schema", "(", "config", ")", "result", "[", "domain", "]", "=", "config", "[", "domain", "]", "except", "vol", ".", "Invalid", "as", "ex", ":", "_comp_error", "(", "ex", ",", "domain", ",", "config", ")", "continue", "component_platform_schema", "=", "getattr", "(", "component", ",", "\"PLATFORM_SCHEMA_BASE\"", ",", "getattr", "(", "component", ",", "\"PLATFORM_SCHEMA\"", ",", "None", ")", ",", ")", "if", "component_platform_schema", "is", "None", ":", "continue", "platforms", "=", "[", "]", "for", "p_name", ",", "p_config", "in", "config_per_platform", "(", "config", ",", "domain", ")", ":", "# Validate component specific platform schema", "try", ":", "p_validated", "=", "component_platform_schema", "(", "p_config", ")", "except", "vol", ".", "Invalid", "as", "ex", ":", "_comp_error", "(", "ex", ",", "domain", ",", "config", ")", "continue", "# Not all platform components follow same pattern for platforms", "# So if p_name is None we are not going to validate platform", "# (the automation component is one of them)", "if", "p_name", "is", "None", ":", "platforms", ".", "append", "(", "p_validated", ")", "continue", "try", ":", "p_integration", "=", "await", "async_get_integration_with_requirements", "(", "hass", ",", "p_name", ")", "platform", "=", "p_integration", ".", "get_platform", "(", "domain", ")", "except", "(", "loader", ".", "IntegrationNotFound", ",", "RequirementsNotFound", ",", "ImportError", ",", ")", "as", "ex", ":", "result", ".", "add_error", "(", "f\"Platform error {domain}.{p_name} - {ex}\"", ")", "continue", "# Validate platform specific schema", "platform_schema", "=", "getattr", "(", "platform", ",", "\"PLATFORM_SCHEMA\"", ",", "None", ")", "if", "platform_schema", "is", "not", "None", ":", "try", ":", "p_validated", "=", "platform_schema", "(", "p_validated", ")", "except", "vol", ".", "Invalid", "as", "ex", ":", "_comp_error", "(", "ex", ",", "f\"{domain}.{p_name}\"", ",", "p_validated", ")", "continue", "platforms", ".", "append", "(", "p_validated", ")", "# Remove config for current component and add validated config back in.", "for", "filter_comp", "in", "extract_domain_configs", "(", "config", ",", "domain", ")", ":", "del", "config", "[", "filter_comp", "]", "result", "[", "domain", "]", "=", "platforms", "return", "result" ]
[ 60, 0 ]
[ 214, 17 ]
python
en
['en', 'en', 'en']
True
empty_value
(value: Any)
Test if the user has the default config value from adding "zone:".
Test if the user has the default config value from adding "zone:".
def empty_value(value: Any) -> Any: """Test if the user has the default config value from adding "zone:".""" if isinstance(value, dict) and len(value) == 0: return [] raise vol.Invalid("Not a default value")
[ "def", "empty_value", "(", "value", ":", "Any", ")", "->", "Any", ":", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "len", "(", "value", ")", "==", "0", ":", "return", "[", "]", "raise", "vol", ".", "Invalid", "(", "\"Not a default value\"", ")" ]
[ 67, 0 ]
[ 72, 44 ]
python
en
['en', 'en', 'en']
True
async_active_zone
( hass: HomeAssistant, latitude: float, longitude: float, radius: int = 0 )
Find the active zone for given latitude, longitude. This method must be run in the event loop.
Find the active zone for given latitude, longitude.
def async_active_zone( hass: HomeAssistant, latitude: float, longitude: float, radius: int = 0 ) -> Optional[State]: """Find the active zone for given latitude, longitude. This method must be run in the event loop. """ # Sort entity IDs so that we are deterministic if equal distance to 2 zones zones = ( cast(State, hass.states.get(entity_id)) for entity_id in sorted(hass.states.async_entity_ids(DOMAIN)) ) min_dist = None closest = None for zone in zones: if zone.state == STATE_UNAVAILABLE or zone.attributes.get(ATTR_PASSIVE): continue zone_dist = distance( latitude, longitude, zone.attributes[ATTR_LATITUDE], zone.attributes[ATTR_LONGITUDE], ) if zone_dist is None: continue within_zone = zone_dist - radius < zone.attributes[ATTR_RADIUS] closer_zone = closest is None or zone_dist < min_dist # type: ignore smaller_zone = ( zone_dist == min_dist and zone.attributes[ATTR_RADIUS] < cast(State, closest).attributes[ATTR_RADIUS] ) if within_zone and (closer_zone or smaller_zone): min_dist = zone_dist closest = zone return closest
[ "def", "async_active_zone", "(", "hass", ":", "HomeAssistant", ",", "latitude", ":", "float", ",", "longitude", ":", "float", ",", "radius", ":", "int", "=", "0", ")", "->", "Optional", "[", "State", "]", ":", "# Sort entity IDs so that we are deterministic if equal distance to 2 zones", "zones", "=", "(", "cast", "(", "State", ",", "hass", ".", "states", ".", "get", "(", "entity_id", ")", ")", "for", "entity_id", "in", "sorted", "(", "hass", ".", "states", ".", "async_entity_ids", "(", "DOMAIN", ")", ")", ")", "min_dist", "=", "None", "closest", "=", "None", "for", "zone", "in", "zones", ":", "if", "zone", ".", "state", "==", "STATE_UNAVAILABLE", "or", "zone", ".", "attributes", ".", "get", "(", "ATTR_PASSIVE", ")", ":", "continue", "zone_dist", "=", "distance", "(", "latitude", ",", "longitude", ",", "zone", ".", "attributes", "[", "ATTR_LATITUDE", "]", ",", "zone", ".", "attributes", "[", "ATTR_LONGITUDE", "]", ",", ")", "if", "zone_dist", "is", "None", ":", "continue", "within_zone", "=", "zone_dist", "-", "radius", "<", "zone", ".", "attributes", "[", "ATTR_RADIUS", "]", "closer_zone", "=", "closest", "is", "None", "or", "zone_dist", "<", "min_dist", "# type: ignore", "smaller_zone", "=", "(", "zone_dist", "==", "min_dist", "and", "zone", ".", "attributes", "[", "ATTR_RADIUS", "]", "<", "cast", "(", "State", ",", "closest", ")", ".", "attributes", "[", "ATTR_RADIUS", "]", ")", "if", "within_zone", "and", "(", "closer_zone", "or", "smaller_zone", ")", ":", "min_dist", "=", "zone_dist", "closest", "=", "zone", "return", "closest" ]
[ 91, 0 ]
[ 133, 18 ]
python
en
['en', 'en', 'en']
True
in_zone
(zone: State, latitude: float, longitude: float, radius: float = 0)
Test if given latitude, longitude is in given zone. Async friendly.
Test if given latitude, longitude is in given zone.
def in_zone(zone: State, latitude: float, longitude: float, radius: float = 0) -> bool: """Test if given latitude, longitude is in given zone. Async friendly. """ if zone.state == STATE_UNAVAILABLE: return False zone_dist = distance( latitude, longitude, zone.attributes[ATTR_LATITUDE], zone.attributes[ATTR_LONGITUDE], ) if zone_dist is None or zone.attributes[ATTR_RADIUS] is None: return False return zone_dist - radius < cast(float, zone.attributes[ATTR_RADIUS])
[ "def", "in_zone", "(", "zone", ":", "State", ",", "latitude", ":", "float", ",", "longitude", ":", "float", ",", "radius", ":", "float", "=", "0", ")", "->", "bool", ":", "if", "zone", ".", "state", "==", "STATE_UNAVAILABLE", ":", "return", "False", "zone_dist", "=", "distance", "(", "latitude", ",", "longitude", ",", "zone", ".", "attributes", "[", "ATTR_LATITUDE", "]", ",", "zone", ".", "attributes", "[", "ATTR_LONGITUDE", "]", ",", ")", "if", "zone_dist", "is", "None", "or", "zone", ".", "attributes", "[", "ATTR_RADIUS", "]", "is", "None", ":", "return", "False", "return", "zone_dist", "-", "radius", "<", "cast", "(", "float", ",", "zone", ".", "attributes", "[", "ATTR_RADIUS", "]", ")" ]
[ 136, 0 ]
[ 153, 73 ]
python
en
['nl', 'en', 'en']
True
async_setup
(hass: HomeAssistant, config: Dict)
Set up configured zones as well as Home Assistant zone if necessary.
Set up configured zones as well as Home Assistant zone if necessary.
async def async_setup(hass: HomeAssistant, config: Dict) -> bool: """Set up configured zones as well as Home Assistant zone if necessary.""" component = entity_component.EntityComponent(_LOGGER, DOMAIN, hass) id_manager = collection.IDManager() yaml_collection = collection.IDLessCollection( logging.getLogger(f"{__name__}.yaml_collection"), id_manager ) collection.attach_entity_component_collection( component, yaml_collection, lambda conf: Zone(conf, False) ) storage_collection = ZoneStorageCollection( storage.Store(hass, STORAGE_VERSION, STORAGE_KEY), logging.getLogger(f"{__name__}.storage_collection"), id_manager, ) collection.attach_entity_component_collection( component, storage_collection, lambda conf: Zone(conf, True) ) if config[DOMAIN]: await yaml_collection.async_load(config[DOMAIN]) await storage_collection.async_load() collection.StorageCollectionWebsocket( storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDS ).async_setup(hass) async def _collection_changed(change_type: str, item_id: str, config: Dict) -> None: """Handle a collection change: clean up entity registry on removals.""" if change_type != collection.CHANGE_REMOVED: return ent_reg = await entity_registry.async_get_registry(hass) ent_reg.async_remove( cast(str, ent_reg.async_get_entity_id(DOMAIN, DOMAIN, item_id)) ) storage_collection.async_add_listener(_collection_changed) async def reload_service_handler(service_call: ServiceCall) -> None: """Remove all zones and load new ones from config.""" conf = await component.async_prepare_reload(skip_reset=True) if conf is None: return await yaml_collection.async_load(conf[DOMAIN]) service.async_register_admin_service( hass, DOMAIN, SERVICE_RELOAD, reload_service_handler, schema=RELOAD_SERVICE_SCHEMA, ) if component.get_entity("zone.home"): return True home_zone = Zone( _home_conf(hass), True, ) home_zone.entity_id = ENTITY_ID_HOME await component.async_add_entities([home_zone]) async def core_config_updated(_: Event) -> None: """Handle core config updated.""" await home_zone.async_update_config(_home_conf(hass)) hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, core_config_updated) hass.data[DOMAIN] = storage_collection return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "Dict", ")", "->", "bool", ":", "component", "=", "entity_component", ".", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "id_manager", "=", "collection", ".", "IDManager", "(", ")", "yaml_collection", "=", "collection", ".", "IDLessCollection", "(", "logging", ".", "getLogger", "(", "f\"{__name__}.yaml_collection\"", ")", ",", "id_manager", ")", "collection", ".", "attach_entity_component_collection", "(", "component", ",", "yaml_collection", ",", "lambda", "conf", ":", "Zone", "(", "conf", ",", "False", ")", ")", "storage_collection", "=", "ZoneStorageCollection", "(", "storage", ".", "Store", "(", "hass", ",", "STORAGE_VERSION", ",", "STORAGE_KEY", ")", ",", "logging", ".", "getLogger", "(", "f\"{__name__}.storage_collection\"", ")", ",", "id_manager", ",", ")", "collection", ".", "attach_entity_component_collection", "(", "component", ",", "storage_collection", ",", "lambda", "conf", ":", "Zone", "(", "conf", ",", "True", ")", ")", "if", "config", "[", "DOMAIN", "]", ":", "await", "yaml_collection", ".", "async_load", "(", "config", "[", "DOMAIN", "]", ")", "await", "storage_collection", ".", "async_load", "(", ")", "collection", ".", "StorageCollectionWebsocket", "(", "storage_collection", ",", "DOMAIN", ",", "DOMAIN", ",", "CREATE_FIELDS", ",", "UPDATE_FIELDS", ")", ".", "async_setup", "(", "hass", ")", "async", "def", "_collection_changed", "(", "change_type", ":", "str", ",", "item_id", ":", "str", ",", "config", ":", "Dict", ")", "->", "None", ":", "\"\"\"Handle a collection change: clean up entity registry on removals.\"\"\"", "if", "change_type", "!=", "collection", ".", "CHANGE_REMOVED", ":", "return", "ent_reg", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "ent_reg", ".", "async_remove", "(", "cast", "(", "str", ",", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "item_id", ")", ")", ")", "storage_collection", ".", "async_add_listener", "(", "_collection_changed", ")", "async", "def", "reload_service_handler", "(", "service_call", ":", "ServiceCall", ")", "->", "None", ":", "\"\"\"Remove all zones and load new ones from config.\"\"\"", "conf", "=", "await", "component", ".", "async_prepare_reload", "(", "skip_reset", "=", "True", ")", "if", "conf", "is", "None", ":", "return", "await", "yaml_collection", ".", "async_load", "(", "conf", "[", "DOMAIN", "]", ")", "service", ".", "async_register_admin_service", "(", "hass", ",", "DOMAIN", ",", "SERVICE_RELOAD", ",", "reload_service_handler", ",", "schema", "=", "RELOAD_SERVICE_SCHEMA", ",", ")", "if", "component", ".", "get_entity", "(", "\"zone.home\"", ")", ":", "return", "True", "home_zone", "=", "Zone", "(", "_home_conf", "(", "hass", ")", ",", "True", ",", ")", "home_zone", ".", "entity_id", "=", "ENTITY_ID_HOME", "await", "component", ".", "async_add_entities", "(", "[", "home_zone", "]", ")", "async", "def", "core_config_updated", "(", "_", ":", "Event", ")", "->", "None", ":", "\"\"\"Handle core config updated.\"\"\"", "await", "home_zone", ".", "async_update_config", "(", "_home_conf", "(", "hass", ")", ")", "hass", ".", "bus", ".", "async_listen", "(", "EVENT_CORE_CONFIG_UPDATE", ",", "core_config_updated", ")", "hass", ".", "data", "[", "DOMAIN", "]", "=", "storage_collection", "return", "True" ]
[ 177, 0 ]
[ 252, 15 ]
python
en
['en', 'en', 'en']
True
_home_conf
(hass: HomeAssistant)
Return the home zone config.
Return the home zone config.
def _home_conf(hass: HomeAssistant) -> Dict: """Return the home zone config.""" return { CONF_NAME: hass.config.location_name, CONF_LATITUDE: hass.config.latitude, CONF_LONGITUDE: hass.config.longitude, CONF_RADIUS: DEFAULT_RADIUS, CONF_ICON: ICON_HOME, CONF_PASSIVE: False, }
[ "def", "_home_conf", "(", "hass", ":", "HomeAssistant", ")", "->", "Dict", ":", "return", "{", "CONF_NAME", ":", "hass", ".", "config", ".", "location_name", ",", "CONF_LATITUDE", ":", "hass", ".", "config", ".", "latitude", ",", "CONF_LONGITUDE", ":", "hass", ".", "config", ".", "longitude", ",", "CONF_RADIUS", ":", "DEFAULT_RADIUS", ",", "CONF_ICON", ":", "ICON_HOME", ",", "CONF_PASSIVE", ":", "False", ",", "}" ]
[ 256, 0 ]
[ 265, 5 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistant, config_entry: config_entries.ConfigEntry )
Set up zone as config entry.
Set up zone as config entry.
async def async_setup_entry( hass: HomeAssistant, config_entry: config_entries.ConfigEntry ) -> bool: """Set up zone as config entry.""" storage_collection = cast(ZoneStorageCollection, hass.data[DOMAIN]) data = dict(config_entry.data) data.setdefault(CONF_PASSIVE, DEFAULT_PASSIVE) data.setdefault(CONF_RADIUS, DEFAULT_RADIUS) await storage_collection.async_create_item(data) hass.async_create_task(hass.config_entries.async_remove(config_entry.entry_id)) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "config_entries", ".", "ConfigEntry", ")", "->", "bool", ":", "storage_collection", "=", "cast", "(", "ZoneStorageCollection", ",", "hass", ".", "data", "[", "DOMAIN", "]", ")", "data", "=", "dict", "(", "config_entry", ".", "data", ")", "data", ".", "setdefault", "(", "CONF_PASSIVE", ",", "DEFAULT_PASSIVE", ")", "data", ".", "setdefault", "(", "CONF_RADIUS", ",", "DEFAULT_RADIUS", ")", "await", "storage_collection", ".", "async_create_item", "(", "data", ")", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_remove", "(", "config_entry", ".", "entry_id", ")", ")", "return", "True" ]
[ 268, 0 ]
[ 282, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
( hass: HomeAssistant, config_entry: config_entries.ConfigEntry )
Will be called once we remove it.
Will be called once we remove it.
async def async_unload_entry( hass: HomeAssistant, config_entry: config_entries.ConfigEntry ) -> bool: """Will be called once we remove it.""" return True
[ "async", "def", "async_unload_entry", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "config_entries", ".", "ConfigEntry", ")", "->", "bool", ":", "return", "True" ]
[ 285, 0 ]
[ 289, 15 ]
python
en
['en', 'en', 'en']
True
ZoneStorageCollection._process_create_data
(self, data: Dict)
Validate the config is valid.
Validate the config is valid.
async def _process_create_data(self, data: Dict) -> Dict: """Validate the config is valid.""" return cast(Dict, self.CREATE_SCHEMA(data))
[ "async", "def", "_process_create_data", "(", "self", ",", "data", ":", "Dict", ")", "->", "Dict", ":", "return", "cast", "(", "Dict", ",", "self", ".", "CREATE_SCHEMA", "(", "data", ")", ")" ]
[ 162, 4 ]
[ 164, 51 ]
python
en
['en', 'en', 'en']
True
ZoneStorageCollection._get_suggested_id
(self, info: Dict)
Suggest an ID based on the config.
Suggest an ID based on the config.
def _get_suggested_id(self, info: Dict) -> str: """Suggest an ID based on the config.""" return cast(str, info[CONF_NAME])
[ "def", "_get_suggested_id", "(", "self", ",", "info", ":", "Dict", ")", "->", "str", ":", "return", "cast", "(", "str", ",", "info", "[", "CONF_NAME", "]", ")" ]
[ 167, 4 ]
[ 169, 41 ]
python
en
['en', 'en', 'en']
True
ZoneStorageCollection._update_data
(self, data: dict, update_data: Dict)
Return a new updated data object.
Return a new updated data object.
async def _update_data(self, data: dict, update_data: Dict) -> Dict: """Return a new updated data object.""" update_data = self.UPDATE_SCHEMA(update_data) return {**data, **update_data}
[ "async", "def", "_update_data", "(", "self", ",", "data", ":", "dict", ",", "update_data", ":", "Dict", ")", "->", "Dict", ":", "update_data", "=", "self", ".", "UPDATE_SCHEMA", "(", "update_data", ")", "return", "{", "*", "*", "data", ",", "*", "*", "update_data", "}" ]
[ 171, 4 ]
[ 174, 38 ]
python
en
['en', 'en', 'en']
True
Zone.__init__
(self, config: Dict, editable: bool)
Initialize the zone.
Initialize the zone.
def __init__(self, config: Dict, editable: bool): """Initialize the zone.""" self._config = config self._editable = editable self._attrs: Optional[Dict] = None self._generate_attrs()
[ "def", "__init__", "(", "self", ",", "config", ":", "Dict", ",", "editable", ":", "bool", ")", ":", "self", ".", "_config", "=", "config", "self", ".", "_editable", "=", "editable", "self", ".", "_attrs", ":", "Optional", "[", "Dict", "]", "=", "None", "self", ".", "_generate_attrs", "(", ")" ]
[ 295, 4 ]
[ 300, 30 ]
python
en
['en', 'en', 'en']
True
Zone.state
(self)
Return the state property really does nothing for a zone.
Return the state property really does nothing for a zone.
def state(self) -> str: """Return the state property really does nothing for a zone.""" return "zoning"
[ "def", "state", "(", "self", ")", "->", "str", ":", "return", "\"zoning\"" ]
[ 303, 4 ]
[ 305, 23 ]
python
en
['en', 'en', 'en']
True
Zone.name
(self)
Return name.
Return name.
def name(self) -> str: """Return name.""" return cast(str, self._config[CONF_NAME])
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "cast", "(", "str", ",", "self", ".", "_config", "[", "CONF_NAME", "]", ")" ]
[ 308, 4 ]
[ 310, 49 ]
python
en
['en', 'ig', 'en']
False
Zone.unique_id
(self)
Return unique ID.
Return unique ID.
def unique_id(self) -> Optional[str]: """Return unique ID.""" return self._config.get(CONF_ID)
[ "def", "unique_id", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_config", ".", "get", "(", "CONF_ID", ")" ]
[ 313, 4 ]
[ 315, 40 ]
python
en
['fr', 'la', 'en']
False
Zone.icon
(self)
Return the icon if any.
Return the icon if any.
def icon(self) -> Optional[str]: """Return the icon if any.""" return self._config.get(CONF_ICON)
[ "def", "icon", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_config", ".", "get", "(", "CONF_ICON", ")" ]
[ 318, 4 ]
[ 320, 42 ]
python
en
['en', 'en', 'en']
True
Zone.state_attributes
(self)
Return the state attributes of the zone.
Return the state attributes of the zone.
def state_attributes(self) -> Optional[Dict]: """Return the state attributes of the zone.""" return self._attrs
[ "def", "state_attributes", "(", "self", ")", "->", "Optional", "[", "Dict", "]", ":", "return", "self", ".", "_attrs" ]
[ 323, 4 ]
[ 325, 26 ]
python
en
['en', 'en', 'en']
True
Zone.should_poll
(self)
Zone does not poll.
Zone does not poll.
def should_poll(self) -> bool: """Zone does not poll.""" return False
[ "def", "should_poll", "(", "self", ")", "->", "bool", ":", "return", "False" ]
[ 328, 4 ]
[ 330, 20 ]
python
en
['it', 'en', 'en']
True
Zone.async_update_config
(self, config: Dict)
Handle when the config is updated.
Handle when the config is updated.
async def async_update_config(self, config: Dict) -> None: """Handle when the config is updated.""" if self._config == config: return self._config = config self._generate_attrs() self.async_write_ha_state()
[ "async", "def", "async_update_config", "(", "self", ",", "config", ":", "Dict", ")", "->", "None", ":", "if", "self", ".", "_config", "==", "config", ":", "return", "self", ".", "_config", "=", "config", "self", ".", "_generate_attrs", "(", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 332, 4 ]
[ 338, 35 ]
python
en
['en', 'en', 'en']
True
Zone._generate_attrs
(self)
Generate new attrs based on config.
Generate new attrs based on config.
def _generate_attrs(self) -> None: """Generate new attrs based on config.""" self._attrs = { ATTR_LATITUDE: self._config[CONF_LATITUDE], ATTR_LONGITUDE: self._config[CONF_LONGITUDE], ATTR_RADIUS: self._config[CONF_RADIUS], ATTR_PASSIVE: self._config[CONF_PASSIVE], ATTR_EDITABLE: self._editable, }
[ "def", "_generate_attrs", "(", "self", ")", "->", "None", ":", "self", ".", "_attrs", "=", "{", "ATTR_LATITUDE", ":", "self", ".", "_config", "[", "CONF_LATITUDE", "]", ",", "ATTR_LONGITUDE", ":", "self", ".", "_config", "[", "CONF_LONGITUDE", "]", ",", "ATTR_RADIUS", ":", "self", ".", "_config", "[", "CONF_RADIUS", "]", ",", "ATTR_PASSIVE", ":", "self", ".", "_config", "[", "CONF_PASSIVE", "]", ",", "ATTR_EDITABLE", ":", "self", ".", "_editable", ",", "}" ]
[ 341, 4 ]
[ 349, 9 ]
python
en
['en', 'en', 'en']
True
Compressor.__init__
(self, model, config_list, optimizer=None)
Record necessary info in class members Parameters ---------- model : pytorch model the model user wants to compress config_list : list the configurations that users specify for compression optimizer: pytorch optimizer optimizer used to train the model
Record necessary info in class members
def __init__(self, model, config_list, optimizer=None): """ Record necessary info in class members Parameters ---------- model : pytorch model the model user wants to compress config_list : list the configurations that users specify for compression optimizer: pytorch optimizer optimizer used to train the model """ assert isinstance(model, torch.nn.Module) self.validate_config(model, config_list) self.bound_model = model self.config_list = config_list self.optimizer = optimizer self.modules_to_compress = None self.modules_wrapper = [] self.is_wrapped = False self._fwd_hook_handles = {} self._fwd_hook_id = 0 self.reset() if not self.modules_wrapper: _logger.warning('Nothing is configured to compress, please check your model and config_list')
[ "def", "__init__", "(", "self", ",", "model", ",", "config_list", ",", "optimizer", "=", "None", ")", ":", "assert", "isinstance", "(", "model", ",", "torch", ".", "nn", ".", "Module", ")", "self", ".", "validate_config", "(", "model", ",", "config_list", ")", "self", ".", "bound_model", "=", "model", "self", ".", "config_list", "=", "config_list", "self", ".", "optimizer", "=", "optimizer", "self", ".", "modules_to_compress", "=", "None", "self", ".", "modules_wrapper", "=", "[", "]", "self", ".", "is_wrapped", "=", "False", "self", ".", "_fwd_hook_handles", "=", "{", "}", "self", ".", "_fwd_hook_id", "=", "0", "self", ".", "reset", "(", ")", "if", "not", "self", ".", "modules_wrapper", ":", "_logger", ".", "warning", "(", "'Nothing is configured to compress, please check your model and config_list'", ")" ]
[ 27, 4 ]
[ 57, 105 ]
python
en
['en', 'error', 'th']
False
Compressor.validate_config
(self, model, config_list)
subclass can optionally implement this method to check if config_list if valid
subclass can optionally implement this method to check if config_list if valid
def validate_config(self, model, config_list): """ subclass can optionally implement this method to check if config_list if valid """ pass
[ "def", "validate_config", "(", "self", ",", "model", ",", "config_list", ")", ":", "pass" ]
[ 59, 4 ]
[ 63, 12 ]
python
en
['en', 'error', 'th']
False
Compressor.reset
(self, checkpoint=None)
reset model state dict and model wrapper
reset model state dict and model wrapper
def reset(self, checkpoint=None): """ reset model state dict and model wrapper """ self._unwrap_model() if checkpoint is not None: self.bound_model.load_state_dict(checkpoint) self.modules_to_compress = None self.modules_wrapper = [] for layer, config in self._detect_modules_to_compress(): wrapper = self._wrap_modules(layer, config) self.modules_wrapper.append(wrapper) self._wrap_model()
[ "def", "reset", "(", "self", ",", "checkpoint", "=", "None", ")", ":", "self", ".", "_unwrap_model", "(", ")", "if", "checkpoint", "is", "not", "None", ":", "self", ".", "bound_model", ".", "load_state_dict", "(", "checkpoint", ")", "self", ".", "modules_to_compress", "=", "None", "self", ".", "modules_wrapper", "=", "[", "]", "for", "layer", ",", "config", "in", "self", ".", "_detect_modules_to_compress", "(", ")", ":", "wrapper", "=", "self", ".", "_wrap_modules", "(", "layer", ",", "config", ")", "self", ".", "modules_wrapper", ".", "append", "(", "wrapper", ")", "self", ".", "_wrap_model", "(", ")" ]
[ 65, 4 ]
[ 80, 26 ]
python
en
['en', 'error', 'th']
False
Compressor._detect_modules_to_compress
(self)
detect all modules should be compressed, and save the result in `self.modules_to_compress`. The model will be instrumented and user should never edit it after calling this method.
detect all modules should be compressed, and save the result in `self.modules_to_compress`. The model will be instrumented and user should never edit it after calling this method.
def _detect_modules_to_compress(self): """ detect all modules should be compressed, and save the result in `self.modules_to_compress`. The model will be instrumented and user should never edit it after calling this method. """ if self.modules_to_compress is None: self.modules_to_compress = [] for name, module in self.bound_model.named_modules(): if module == self.bound_model: continue layer = LayerInfo(name, module) config = self.select_config(layer) if config is not None: self.modules_to_compress.append((layer, config)) return self.modules_to_compress
[ "def", "_detect_modules_to_compress", "(", "self", ")", ":", "if", "self", ".", "modules_to_compress", "is", "None", ":", "self", ".", "modules_to_compress", "=", "[", "]", "for", "name", ",", "module", "in", "self", ".", "bound_model", ".", "named_modules", "(", ")", ":", "if", "module", "==", "self", ".", "bound_model", ":", "continue", "layer", "=", "LayerInfo", "(", "name", ",", "module", ")", "config", "=", "self", ".", "select_config", "(", "layer", ")", "if", "config", "is", "not", "None", ":", "self", ".", "modules_to_compress", ".", "append", "(", "(", "layer", ",", "config", ")", ")", "return", "self", ".", "modules_to_compress" ]
[ 82, 4 ]
[ 96, 39 ]
python
en
['en', 'error', 'th']
False
Compressor._wrap_model
(self)
wrap all modules that needed to be compressed
wrap all modules that needed to be compressed
def _wrap_model(self): """ wrap all modules that needed to be compressed """ for wrapper in reversed(self.get_modules_wrapper()): _setattr(self.bound_model, wrapper.name, wrapper) self.is_wrapped = True
[ "def", "_wrap_model", "(", "self", ")", ":", "for", "wrapper", "in", "reversed", "(", "self", ".", "get_modules_wrapper", "(", ")", ")", ":", "_setattr", "(", "self", ".", "bound_model", ",", "wrapper", ".", "name", ",", "wrapper", ")", "self", ".", "is_wrapped", "=", "True" ]
[ 98, 4 ]
[ 105, 30 ]
python
en
['en', 'error', 'th']
False
Compressor._unwrap_model
(self)
unwrap all modules that needed to be compressed
unwrap all modules that needed to be compressed
def _unwrap_model(self): """ unwrap all modules that needed to be compressed """ for wrapper in self.get_modules_wrapper(): _setattr(self.bound_model, wrapper.name, wrapper.module) self.is_wrapped = False
[ "def", "_unwrap_model", "(", "self", ")", ":", "for", "wrapper", "in", "self", ".", "get_modules_wrapper", "(", ")", ":", "_setattr", "(", "self", ".", "bound_model", ",", "wrapper", ".", "name", ",", "wrapper", ".", "module", ")", "self", ".", "is_wrapped", "=", "False" ]
[ 107, 4 ]
[ 114, 31 ]
python
en
['en', 'error', 'th']
False
Compressor.compress
(self)
Compress the model with algorithm implemented by subclass. The model will be instrumented and user should never edit it after calling this method. `self.modules_to_compress` records all the to-be-compressed layers Returns ------- torch.nn.Module model with specified modules compressed.
Compress the model with algorithm implemented by subclass.
def compress(self): """ Compress the model with algorithm implemented by subclass. The model will be instrumented and user should never edit it after calling this method. `self.modules_to_compress` records all the to-be-compressed layers Returns ------- torch.nn.Module model with specified modules compressed. """ return self.bound_model
[ "def", "compress", "(", "self", ")", ":", "return", "self", ".", "bound_model" ]
[ 116, 4 ]
[ 128, 31 ]
python
en
['en', 'error', 'th']
False
Compressor.set_wrappers_attribute
(self, name, value)
To register attributes used in wrapped module's forward method. If the type of the value is Torch.tensor, then this value is registered as a buffer in wrapper, which will be saved by model.state_dict. Otherwise, this value is just a regular variable in wrapper. Parameters ---------- name : str name of the variable value: any value of the variable
To register attributes used in wrapped module's forward method. If the type of the value is Torch.tensor, then this value is registered as a buffer in wrapper, which will be saved by model.state_dict. Otherwise, this value is just a regular variable in wrapper.
def set_wrappers_attribute(self, name, value): """ To register attributes used in wrapped module's forward method. If the type of the value is Torch.tensor, then this value is registered as a buffer in wrapper, which will be saved by model.state_dict. Otherwise, this value is just a regular variable in wrapper. Parameters ---------- name : str name of the variable value: any value of the variable """ for wrapper in self.get_modules_wrapper(): if isinstance(value, torch.Tensor): wrapper.register_buffer(name, value.clone()) else: setattr(wrapper, name, value)
[ "def", "set_wrappers_attribute", "(", "self", ",", "name", ",", "value", ")", ":", "for", "wrapper", "in", "self", ".", "get_modules_wrapper", "(", ")", ":", "if", "isinstance", "(", "value", ",", "torch", ".", "Tensor", ")", ":", "wrapper", ".", "register_buffer", "(", "name", ",", "value", ".", "clone", "(", ")", ")", "else", ":", "setattr", "(", "wrapper", ",", "name", ",", "value", ")" ]
[ 130, 4 ]
[ 147, 45 ]
python
en
['en', 'error', 'th']
False
Compressor.get_modules_to_compress
(self)
To obtain all the to-be-compressed modules. Returns ------- list a list of the layers, each of which is a tuple (`layer`, `config`), `layer` is `LayerInfo`, `config` is a `dict`
To obtain all the to-be-compressed modules.
def get_modules_to_compress(self): """ To obtain all the to-be-compressed modules. Returns ------- list a list of the layers, each of which is a tuple (`layer`, `config`), `layer` is `LayerInfo`, `config` is a `dict` """ return self.modules_to_compress
[ "def", "get_modules_to_compress", "(", "self", ")", ":", "return", "self", ".", "modules_to_compress" ]
[ 149, 4 ]
[ 159, 39 ]
python
en
['en', 'error', 'th']
False
Compressor.get_modules_wrapper
(self)
To obtain all the wrapped modules. Returns ------- list a list of the wrapped modules
To obtain all the wrapped modules.
def get_modules_wrapper(self): """ To obtain all the wrapped modules. Returns ------- list a list of the wrapped modules """ return self.modules_wrapper
[ "def", "get_modules_wrapper", "(", "self", ")", ":", "return", "self", ".", "modules_wrapper" ]
[ 161, 4 ]
[ 170, 35 ]
python
en
['en', 'error', 'th']
False
Compressor.select_config
(self, layer)
Find the configuration for `layer` by parsing `self.config_list` Parameters ---------- layer : LayerInfo one layer Returns ------- config or None the retrieved configuration for this layer, if None, this layer should not be compressed
Find the configuration for `layer` by parsing `self.config_list`
def select_config(self, layer): """ Find the configuration for `layer` by parsing `self.config_list` Parameters ---------- layer : LayerInfo one layer Returns ------- config or None the retrieved configuration for this layer, if None, this layer should not be compressed """ ret = None for config in self.config_list: config = config.copy() # expand config if key `default` is in config['op_types'] if 'op_types' in config and 'default' in config['op_types']: expanded_op_types = [] for op_type in config['op_types']: if op_type == 'default': expanded_op_types.extend(default_layers.weighted_modules) else: expanded_op_types.append(op_type) config['op_types'] = expanded_op_types # check if condition is satisified if 'op_types' in config and layer.type not in config['op_types']: continue if 'op_names' in config and layer.name not in config['op_names']: continue ret = config if ret is None or 'exclude' in ret: return None return ret
[ "def", "select_config", "(", "self", ",", "layer", ")", ":", "ret", "=", "None", "for", "config", "in", "self", ".", "config_list", ":", "config", "=", "config", ".", "copy", "(", ")", "# expand config if key `default` is in config['op_types']", "if", "'op_types'", "in", "config", "and", "'default'", "in", "config", "[", "'op_types'", "]", ":", "expanded_op_types", "=", "[", "]", "for", "op_type", "in", "config", "[", "'op_types'", "]", ":", "if", "op_type", "==", "'default'", ":", "expanded_op_types", ".", "extend", "(", "default_layers", ".", "weighted_modules", ")", "else", ":", "expanded_op_types", ".", "append", "(", "op_type", ")", "config", "[", "'op_types'", "]", "=", "expanded_op_types", "# check if condition is satisified", "if", "'op_types'", "in", "config", "and", "layer", ".", "type", "not", "in", "config", "[", "'op_types'", "]", ":", "continue", "if", "'op_names'", "in", "config", "and", "layer", ".", "name", "not", "in", "config", "[", "'op_names'", "]", ":", "continue", "ret", "=", "config", "if", "ret", "is", "None", "or", "'exclude'", "in", "ret", ":", "return", "None", "return", "ret" ]
[ 172, 4 ]
[ 209, 18 ]
python
en
['en', 'error', 'th']
False
Compressor.update_epoch
(self, epoch)
If user want to update model every epoch, user can override this method. This method should be called at the beginning of each epoch Parameters ---------- epoch : num the current epoch number
If user want to update model every epoch, user can override this method. This method should be called at the beginning of each epoch
def update_epoch(self, epoch): """ If user want to update model every epoch, user can override this method. This method should be called at the beginning of each epoch Parameters ---------- epoch : num the current epoch number """ pass
[ "def", "update_epoch", "(", "self", ",", "epoch", ")", ":", "pass" ]
[ 211, 4 ]
[ 221, 12 ]
python
en
['en', 'error', 'th']
False
Compressor._wrap_modules
(self, layer, config)
This method is implemented in the subclasses, i.e., `Pruner` and `Quantizer` Parameters ---------- layer : LayerInfo the layer to instrument the compression operation config : dict the configuration for compressing this layer
This method is implemented in the subclasses, i.e., `Pruner` and `Quantizer`
def _wrap_modules(self, layer, config): """ This method is implemented in the subclasses, i.e., `Pruner` and `Quantizer` Parameters ---------- layer : LayerInfo the layer to instrument the compression operation config : dict the configuration for compressing this layer """ raise NotImplementedError()
[ "def", "_wrap_modules", "(", "self", ",", "layer", ",", "config", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 223, 4 ]
[ 234, 35 ]
python
en
['en', 'error', 'th']
False
PrunerModuleWrapper.__init__
(self, module, module_name, module_type, config, pruner)
Wrap an module to enable data parallel, forward method customization and buffer registeration. Parameters ---------- module : pytorch module the module user wants to compress config : dict the configurations that users specify for compression module_name : str the name of the module to compress, wrapper module shares same name module_type : str the type of the module to compress pruner : Pruner the pruner used to calculate mask
Wrap an module to enable data parallel, forward method customization and buffer registeration.
def __init__(self, module, module_name, module_type, config, pruner): """ Wrap an module to enable data parallel, forward method customization and buffer registeration. Parameters ---------- module : pytorch module the module user wants to compress config : dict the configurations that users specify for compression module_name : str the name of the module to compress, wrapper module shares same name module_type : str the type of the module to compress pruner : Pruner the pruner used to calculate mask """ super().__init__() # origin layer information self.module = module self.name = module_name self.type = module_type # config and pruner self.config = config self.pruner = pruner # register buffer for mask self.register_buffer("weight_mask", torch.ones(self.module.weight.shape)) if hasattr(self.module, 'bias') and self.module.bias is not None: self.register_buffer("bias_mask", torch.ones(self.module.bias.shape)) else: self.register_buffer("bias_mask", None)
[ "def", "__init__", "(", "self", ",", "module", ",", "module_name", ",", "module_type", ",", "config", ",", "pruner", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "# origin layer information", "self", ".", "module", "=", "module", "self", ".", "name", "=", "module_name", "self", ".", "type", "=", "module_type", "# config and pruner", "self", ".", "config", "=", "config", "self", ".", "pruner", "=", "pruner", "# register buffer for mask", "self", ".", "register_buffer", "(", "\"weight_mask\"", ",", "torch", ".", "ones", "(", "self", ".", "module", ".", "weight", ".", "shape", ")", ")", "if", "hasattr", "(", "self", ".", "module", ",", "'bias'", ")", "and", "self", ".", "module", ".", "bias", "is", "not", "None", ":", "self", ".", "register_buffer", "(", "\"bias_mask\"", ",", "torch", ".", "ones", "(", "self", ".", "module", ".", "bias", ".", "shape", ")", ")", "else", ":", "self", ".", "register_buffer", "(", "\"bias_mask\"", ",", "None", ")" ]
[ 277, 4 ]
[ 308, 51 ]
python
en
['en', 'error', 'th']
False
Pruner.calc_mask
(self, wrapper, **kwargs)
Pruners should overload this method to provide mask for weight tensors. The mask must have the same shape and type comparing to the weight. It will be applied with `mul()` operation on the weight. This method is effectively hooked to `forward()` method of the model. Parameters ---------- wrapper : Module calculate mask for `wrapper.module`'s weight
Pruners should overload this method to provide mask for weight tensors. The mask must have the same shape and type comparing to the weight. It will be applied with `mul()` operation on the weight. This method is effectively hooked to `forward()` method of the model.
def calc_mask(self, wrapper, **kwargs): """ Pruners should overload this method to provide mask for weight tensors. The mask must have the same shape and type comparing to the weight. It will be applied with `mul()` operation on the weight. This method is effectively hooked to `forward()` method of the model. Parameters ---------- wrapper : Module calculate mask for `wrapper.module`'s weight """ raise NotImplementedError("Pruners must overload calc_mask()")
[ "def", "calc_mask", "(", "self", ",", "wrapper", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "\"Pruners must overload calc_mask()\"", ")" ]
[ 344, 4 ]
[ 356, 70 ]
python
en
['en', 'error', 'th']
False
Pruner._wrap_modules
(self, layer, config)
Create a wrapper module to replace the original one. Parameters ---------- layer : LayerInfo the layer to instrument the mask config : dict the configuration for generating the mask
Create a wrapper module to replace the original one.
def _wrap_modules(self, layer, config): """ Create a wrapper module to replace the original one. Parameters ---------- layer : LayerInfo the layer to instrument the mask config : dict the configuration for generating the mask """ _logger.debug("Module detected to compress : %s.", layer.name) wrapper = PrunerModuleWrapper(layer.module, layer.name, layer.type, config, self) assert hasattr(layer.module, 'weight'), "module %s does not have 'weight' attribute" % layer.name # move newly registered buffers to the same device of weight wrapper.to(layer.module.weight.device) return wrapper
[ "def", "_wrap_modules", "(", "self", ",", "layer", ",", "config", ")", ":", "_logger", ".", "debug", "(", "\"Module detected to compress : %s.\"", ",", "layer", ".", "name", ")", "wrapper", "=", "PrunerModuleWrapper", "(", "layer", ".", "module", ",", "layer", ".", "name", ",", "layer", ".", "type", ",", "config", ",", "self", ")", "assert", "hasattr", "(", "layer", ".", "module", ",", "'weight'", ")", ",", "\"module %s does not have 'weight' attribute\"", "%", "layer", ".", "name", "# move newly registered buffers to the same device of weight", "wrapper", ".", "to", "(", "layer", ".", "module", ".", "weight", ".", "device", ")", "return", "wrapper" ]
[ 358, 4 ]
[ 374, 22 ]
python
en
['en', 'error', 'th']
False
Pruner.export_model
(self, model_path, mask_path=None, onnx_path=None, input_shape=None, device=None)
Export pruned model weights, masks and onnx model(optional) Parameters ---------- model_path : str path to save pruned model state_dict mask_path : str (optional) path to save mask dict onnx_path : str (optional) path to save onnx model input_shape : list or tuple input shape to onnx model device : torch.device device of the model, used to place the dummy input tensor for exporting onnx file. the tensor is placed on cpu if ```device``` is None
Export pruned model weights, masks and onnx model(optional)
def export_model(self, model_path, mask_path=None, onnx_path=None, input_shape=None, device=None): """ Export pruned model weights, masks and onnx model(optional) Parameters ---------- model_path : str path to save pruned model state_dict mask_path : str (optional) path to save mask dict onnx_path : str (optional) path to save onnx model input_shape : list or tuple input shape to onnx model device : torch.device device of the model, used to place the dummy input tensor for exporting onnx file. the tensor is placed on cpu if ```device``` is None """ assert model_path is not None, 'model_path must be specified' mask_dict = {} self._unwrap_model() # used for generating correct state_dict name without wrapper state for wrapper in self.get_modules_wrapper(): weight_mask = wrapper.weight_mask bias_mask = wrapper.bias_mask if weight_mask is not None: mask_sum = weight_mask.sum().item() mask_num = weight_mask.numel() _logger.debug('Layer: %s Sparsity: %.4f', wrapper.name, 1 - mask_sum / mask_num) wrapper.module.weight.data = wrapper.module.weight.data.mul(weight_mask) if bias_mask is not None: wrapper.module.bias.data = wrapper.module.bias.data.mul(bias_mask) # save mask to dict mask_dict[wrapper.name] = {"weight": weight_mask, "bias": bias_mask} torch.save(self.bound_model.state_dict(), model_path) _logger.info('Model state_dict saved to %s', model_path) if mask_path is not None: torch.save(mask_dict, mask_path) _logger.info('Mask dict saved to %s', mask_path) if onnx_path is not None: assert input_shape is not None, 'input_shape must be specified to export onnx model' # input info needed if device is None: device = torch.device('cpu') input_data = torch.Tensor(*input_shape) torch.onnx.export(self.bound_model, input_data.to(device), onnx_path) _logger.info('Model in onnx with input shape %s saved to %s', input_data.shape, onnx_path) self._wrap_model()
[ "def", "export_model", "(", "self", ",", "model_path", ",", "mask_path", "=", "None", ",", "onnx_path", "=", "None", ",", "input_shape", "=", "None", ",", "device", "=", "None", ")", ":", "assert", "model_path", "is", "not", "None", ",", "'model_path must be specified'", "mask_dict", "=", "{", "}", "self", ".", "_unwrap_model", "(", ")", "# used for generating correct state_dict name without wrapper state", "for", "wrapper", "in", "self", ".", "get_modules_wrapper", "(", ")", ":", "weight_mask", "=", "wrapper", ".", "weight_mask", "bias_mask", "=", "wrapper", ".", "bias_mask", "if", "weight_mask", "is", "not", "None", ":", "mask_sum", "=", "weight_mask", ".", "sum", "(", ")", ".", "item", "(", ")", "mask_num", "=", "weight_mask", ".", "numel", "(", ")", "_logger", ".", "debug", "(", "'Layer: %s Sparsity: %.4f'", ",", "wrapper", ".", "name", ",", "1", "-", "mask_sum", "/", "mask_num", ")", "wrapper", ".", "module", ".", "weight", ".", "data", "=", "wrapper", ".", "module", ".", "weight", ".", "data", ".", "mul", "(", "weight_mask", ")", "if", "bias_mask", "is", "not", "None", ":", "wrapper", ".", "module", ".", "bias", ".", "data", "=", "wrapper", ".", "module", ".", "bias", ".", "data", ".", "mul", "(", "bias_mask", ")", "# save mask to dict", "mask_dict", "[", "wrapper", ".", "name", "]", "=", "{", "\"weight\"", ":", "weight_mask", ",", "\"bias\"", ":", "bias_mask", "}", "torch", ".", "save", "(", "self", ".", "bound_model", ".", "state_dict", "(", ")", ",", "model_path", ")", "_logger", ".", "info", "(", "'Model state_dict saved to %s'", ",", "model_path", ")", "if", "mask_path", "is", "not", "None", ":", "torch", ".", "save", "(", "mask_dict", ",", "mask_path", ")", "_logger", ".", "info", "(", "'Mask dict saved to %s'", ",", "mask_path", ")", "if", "onnx_path", "is", "not", "None", ":", "assert", "input_shape", "is", "not", "None", ",", "'input_shape must be specified to export onnx model'", "# input info needed", "if", "device", "is", "None", ":", "device", "=", "torch", ".", "device", "(", "'cpu'", ")", "input_data", "=", "torch", ".", "Tensor", "(", "*", "input_shape", ")", "torch", ".", "onnx", ".", "export", "(", "self", ".", "bound_model", ",", "input_data", ".", "to", "(", "device", ")", ",", "onnx_path", ")", "_logger", ".", "info", "(", "'Model in onnx with input shape %s saved to %s'", ",", "input_data", ".", "shape", ",", "onnx_path", ")", "self", ".", "_wrap_model", "(", ")" ]
[ 376, 4 ]
[ 425, 26 ]
python
en
['en', 'error', 'th']
False
Pruner.load_model_state_dict
(self, model_state)
Load the state dict saved from unwrapped model. Parameters ---------- model_state : dict state dict saved from unwrapped model
Load the state dict saved from unwrapped model.
def load_model_state_dict(self, model_state): """ Load the state dict saved from unwrapped model. Parameters ---------- model_state : dict state dict saved from unwrapped model """ if self.is_wrapped: self._unwrap_model() self.bound_model.load_state_dict(model_state) self._wrap_model() else: self.bound_model.load_state_dict(model_state)
[ "def", "load_model_state_dict", "(", "self", ",", "model_state", ")", ":", "if", "self", ".", "is_wrapped", ":", "self", ".", "_unwrap_model", "(", ")", "self", ".", "bound_model", ".", "load_state_dict", "(", "model_state", ")", "self", ".", "_wrap_model", "(", ")", "else", ":", "self", ".", "bound_model", ".", "load_state_dict", "(", "model_state", ")" ]
[ 427, 4 ]
[ 441, 57 ]
python
en
['en', 'error', 'th']
False
Pruner.get_pruned_weights
(self, dim=0)
Log the simulated prune sparsity. Parameters ---------- dim : int the pruned dim.
Log the simulated prune sparsity.
def get_pruned_weights(self, dim=0): """ Log the simulated prune sparsity. Parameters ---------- dim : int the pruned dim. """ for _, wrapper in enumerate(self.get_modules_wrapper()): weight_mask = wrapper.weight_mask mask_size = weight_mask.size() if len(mask_size) == 1: index = torch.nonzero(weight_mask.abs() != 0).tolist() else: sum_idx = list(range(len(mask_size))) sum_idx.remove(dim) index = torch.nonzero(weight_mask.abs().sum(sum_idx) != 0).tolist() _logger.info(f'simulated prune {wrapper.name} remain/total: {len(index)}/{weight_mask.size(dim)}')
[ "def", "get_pruned_weights", "(", "self", ",", "dim", "=", "0", ")", ":", "for", "_", ",", "wrapper", "in", "enumerate", "(", "self", ".", "get_modules_wrapper", "(", ")", ")", ":", "weight_mask", "=", "wrapper", ".", "weight_mask", "mask_size", "=", "weight_mask", ".", "size", "(", ")", "if", "len", "(", "mask_size", ")", "==", "1", ":", "index", "=", "torch", ".", "nonzero", "(", "weight_mask", ".", "abs", "(", ")", "!=", "0", ")", ".", "tolist", "(", ")", "else", ":", "sum_idx", "=", "list", "(", "range", "(", "len", "(", "mask_size", ")", ")", ")", "sum_idx", ".", "remove", "(", "dim", ")", "index", "=", "torch", ".", "nonzero", "(", "weight_mask", ".", "abs", "(", ")", ".", "sum", "(", "sum_idx", ")", "!=", "0", ")", ".", "tolist", "(", ")", "_logger", ".", "info", "(", "f'simulated prune {wrapper.name} remain/total: {len(index)}/{weight_mask.size(dim)}'", ")" ]
[ 443, 4 ]
[ 461, 110 ]
python
en
['en', 'error', 'th']
False
QuantizerModuleWrapper.__init__
(self, module, module_name, module_type, config, quantizer)
Wrap an module to enable data parallel, forward method customization and buffer registeration. Parameters ---------- module : pytorch module the module user wants to compress config : dict the configurations that users specify for compression module_name : str the name of the module to compress, wrapper module shares same name module_type : str the type of the module to compress quantizer :quantizer the quantizer used to calculate mask
Wrap an module to enable data parallel, forward method customization and buffer registeration.
def __init__(self, module, module_name, module_type, config, quantizer): """ Wrap an module to enable data parallel, forward method customization and buffer registeration. Parameters ---------- module : pytorch module the module user wants to compress config : dict the configurations that users specify for compression module_name : str the name of the module to compress, wrapper module shares same name module_type : str the type of the module to compress quantizer :quantizer the quantizer used to calculate mask """ super().__init__() # origin layer information self.module = module self.name = module_name self.type = module_type # config and pruner self.config = config self.quantizer = quantizer # register buffer and parameter # old_weight is used to store origin weight and weight is used to store quantized weight # the reason why weight is buffer instead of parameter is because in pytorch parameter is used as leaf # if weight is leaf , then old_weight can not be updated. if 'weight' in config['quant_types']: if not _check_weight(self.module): _logger.warning('Module %s does not have parameter "weight"', self.name) else: self.module.register_parameter('old_weight', torch.nn.Parameter(self.module.weight)) delattr(self.module, 'weight') self.module.register_buffer('weight', self.module.old_weight)
[ "def", "__init__", "(", "self", ",", "module", ",", "module_name", ",", "module_type", ",", "config", ",", "quantizer", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "# origin layer information", "self", ".", "module", "=", "module", "self", ".", "name", "=", "module_name", "self", ".", "type", "=", "module_type", "# config and pruner", "self", ".", "config", "=", "config", "self", ".", "quantizer", "=", "quantizer", "# register buffer and parameter", "# old_weight is used to store origin weight and weight is used to store quantized weight", "# the reason why weight is buffer instead of parameter is because in pytorch parameter is used as leaf", "# if weight is leaf , then old_weight can not be updated.", "if", "'weight'", "in", "config", "[", "'quant_types'", "]", ":", "if", "not", "_check_weight", "(", "self", ".", "module", ")", ":", "_logger", ".", "warning", "(", "'Module %s does not have parameter \"weight\"'", ",", "self", ".", "name", ")", "else", ":", "self", ".", "module", ".", "register_parameter", "(", "'old_weight'", ",", "torch", ".", "nn", ".", "Parameter", "(", "self", ".", "module", ".", "weight", ")", ")", "delattr", "(", "self", ".", "module", ",", "'weight'", ")", "self", ".", "module", ".", "register_buffer", "(", "'weight'", ",", "self", ".", "module", ".", "old_weight", ")" ]
[ 465, 4 ]
[ 501, 77 ]
python
en
['en', 'error', 'th']
False
Quantizer.quantize_weight
(self, wrapper, **kwargs)
quantize should overload this method to quantize weight. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- wrapper : QuantizerModuleWrapper the wrapper for origin module
quantize should overload this method to quantize weight. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- wrapper : QuantizerModuleWrapper the wrapper for origin module
def quantize_weight(self, wrapper, **kwargs): """ quantize should overload this method to quantize weight. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- wrapper : QuantizerModuleWrapper the wrapper for origin module """ raise NotImplementedError('Quantizer must overload quantize_weight()')
[ "def", "quantize_weight", "(", "self", ",", "wrapper", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "'Quantizer must overload quantize_weight()'", ")" ]
[ 543, 4 ]
[ 552, 78 ]
python
en
['en', 'error', 'th']
False
Quantizer.quantize_output
(self, output, wrapper, **kwargs)
quantize should overload this method to quantize output. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- output : Tensor output that needs to be quantized wrapper : QuantizerModuleWrapper the wrapper for origin module
quantize should overload this method to quantize output. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- output : Tensor output that needs to be quantized wrapper : QuantizerModuleWrapper the wrapper for origin module
def quantize_output(self, output, wrapper, **kwargs): """ quantize should overload this method to quantize output. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- output : Tensor output that needs to be quantized wrapper : QuantizerModuleWrapper the wrapper for origin module """ raise NotImplementedError('Quantizer must overload quantize_output()')
[ "def", "quantize_output", "(", "self", ",", "output", ",", "wrapper", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "'Quantizer must overload quantize_output()'", ")" ]
[ 554, 4 ]
[ 565, 78 ]
python
en
['en', 'error', 'th']
False
Quantizer.quantize_input
(self, *inputs, wrapper, **kwargs)
quantize should overload this method to quantize input. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- inputs : Tensor inputs that needs to be quantized wrapper : QuantizerModuleWrapper the wrapper for origin module
quantize should overload this method to quantize input. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- inputs : Tensor inputs that needs to be quantized wrapper : QuantizerModuleWrapper the wrapper for origin module
def quantize_input(self, *inputs, wrapper, **kwargs): """ quantize should overload this method to quantize input. This method is effectively hooked to :meth:`forward` of the model. Parameters ---------- inputs : Tensor inputs that needs to be quantized wrapper : QuantizerModuleWrapper the wrapper for origin module """ raise NotImplementedError('Quantizer must overload quantize_input()')
[ "def", "quantize_input", "(", "self", ",", "*", "inputs", ",", "wrapper", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "'Quantizer must overload quantize_input()'", ")" ]
[ 567, 4 ]
[ 578, 77 ]
python
en
['en', 'error', 'th']
False
Quantizer._wrap_modules
(self, layer, config)
Create a wrapper forward function to replace the original one. Parameters ---------- layer : LayerInfo the layer to instrument the mask config : dict the configuration for quantization
Create a wrapper forward function to replace the original one. Parameters ---------- layer : LayerInfo the layer to instrument the mask config : dict the configuration for quantization
def _wrap_modules(self, layer, config): """ Create a wrapper forward function to replace the original one. Parameters ---------- layer : LayerInfo the layer to instrument the mask config : dict the configuration for quantization """ assert 'quant_types' in config, 'must provide quant_types in config' assert isinstance(config['quant_types'], list), 'quant_types must be list type' assert 'quant_bits' in config, 'must provide quant_bits in config' assert isinstance(config['quant_bits'], int) or isinstance(config['quant_bits'], dict), 'quant_bits must be dict type or int type' if isinstance(config['quant_bits'], dict): for quant_type in config['quant_types']: assert quant_type in config['quant_bits'], 'bits length for %s must be specified in quant_bits dict' % quant_type return QuantizerModuleWrapper(layer.module, layer.name, layer.type, config, self)
[ "def", "_wrap_modules", "(", "self", ",", "layer", ",", "config", ")", ":", "assert", "'quant_types'", "in", "config", ",", "'must provide quant_types in config'", "assert", "isinstance", "(", "config", "[", "'quant_types'", "]", ",", "list", ")", ",", "'quant_types must be list type'", "assert", "'quant_bits'", "in", "config", ",", "'must provide quant_bits in config'", "assert", "isinstance", "(", "config", "[", "'quant_bits'", "]", ",", "int", ")", "or", "isinstance", "(", "config", "[", "'quant_bits'", "]", ",", "dict", ")", ",", "'quant_bits must be dict type or int type'", "if", "isinstance", "(", "config", "[", "'quant_bits'", "]", ",", "dict", ")", ":", "for", "quant_type", "in", "config", "[", "'quant_types'", "]", ":", "assert", "quant_type", "in", "config", "[", "'quant_bits'", "]", ",", "'bits length for %s must be specified in quant_bits dict'", "%", "quant_type", "return", "QuantizerModuleWrapper", "(", "layer", ".", "module", ",", "layer", ".", "name", ",", "layer", ".", "type", ",", "config", ",", "self", ")" ]
[ 580, 4 ]
[ 599, 89 ]
python
en
['en', 'error', 'th']
False
Quantizer.export_model_save
(self, model, model_path, calibration_config=None, calibration_path=None, onnx_path=None, input_shape=None, device=None)
This method helps save pytorch model, calibration config, onnx model in quantizer. Parameters ---------- model : pytorch model pytorch model to be saved model_path : str path to save pytorch calibration_config: dict (optional) config of calibration parameters calibration_path : str (optional) path to save quantize parameters after calibration onnx_path : str (optional) path to save onnx model input_shape : list or tuple input shape to onnx model device : torch.device device of the model, used to place the dummy input tensor for exporting onnx file. the tensor is placed on cpu if ```device``` is None
This method helps save pytorch model, calibration config, onnx model in quantizer.
def export_model_save(self, model, model_path, calibration_config=None, calibration_path=None, onnx_path=None, input_shape=None, device=None): """ This method helps save pytorch model, calibration config, onnx model in quantizer. Parameters ---------- model : pytorch model pytorch model to be saved model_path : str path to save pytorch calibration_config: dict (optional) config of calibration parameters calibration_path : str (optional) path to save quantize parameters after calibration onnx_path : str (optional) path to save onnx model input_shape : list or tuple input shape to onnx model device : torch.device device of the model, used to place the dummy input tensor for exporting onnx file. the tensor is placed on cpu if ```device``` is None """ torch.save(model.state_dict(), model_path) _logger.info('Model state_dict saved to %s', model_path) if calibration_path is not None: torch.save(calibration_config, calibration_path) _logger.info('Mask dict saved to %s', calibration_path) if onnx_path is not None: assert input_shape is not None, 'input_shape must be specified to export onnx model' # input info needed if device is None: device = torch.device('cpu') input_data = torch.Tensor(*input_shape) torch.onnx.export(self.bound_model, input_data.to(device), onnx_path) _logger.info('Model in onnx with input shape %s saved to %s', input_data.shape, onnx_path)
[ "def", "export_model_save", "(", "self", ",", "model", ",", "model_path", ",", "calibration_config", "=", "None", ",", "calibration_path", "=", "None", ",", "onnx_path", "=", "None", ",", "input_shape", "=", "None", ",", "device", "=", "None", ")", ":", "torch", ".", "save", "(", "model", ".", "state_dict", "(", ")", ",", "model_path", ")", "_logger", ".", "info", "(", "'Model state_dict saved to %s'", ",", "model_path", ")", "if", "calibration_path", "is", "not", "None", ":", "torch", ".", "save", "(", "calibration_config", ",", "calibration_path", ")", "_logger", ".", "info", "(", "'Mask dict saved to %s'", ",", "calibration_path", ")", "if", "onnx_path", "is", "not", "None", ":", "assert", "input_shape", "is", "not", "None", ",", "'input_shape must be specified to export onnx model'", "# input info needed", "if", "device", "is", "None", ":", "device", "=", "torch", ".", "device", "(", "'cpu'", ")", "input_data", "=", "torch", ".", "Tensor", "(", "*", "input_shape", ")", "torch", ".", "onnx", ".", "export", "(", "self", ".", "bound_model", ",", "input_data", ".", "to", "(", "device", ")", ",", "onnx_path", ")", "_logger", ".", "info", "(", "'Model in onnx with input shape %s saved to %s'", ",", "input_data", ".", "shape", ",", "onnx_path", ")" ]
[ 601, 4 ]
[ 636, 102 ]
python
en
['en', 'error', 'th']
False
Quantizer.export_model
(self, model_path, calibration_path=None, onnx_path=None, input_shape=None, device=None)
Export quantized model weights and calibration parameters Parameters ---------- model_path : str path to save quantized model weight calibration_path : str (optional) path to save quantize parameters after calibration onnx_path : str (optional) path to save onnx model input_shape : list or tuple input shape to onnx model device : torch.device device of the model, used to place the dummy input tensor for exporting onnx file. the tensor is placed on cpu if ```device``` is None Returns ------- Dict
Export quantized model weights and calibration parameters
def export_model(self, model_path, calibration_path=None, onnx_path=None, input_shape=None, device=None): """ Export quantized model weights and calibration parameters Parameters ---------- model_path : str path to save quantized model weight calibration_path : str (optional) path to save quantize parameters after calibration onnx_path : str (optional) path to save onnx model input_shape : list or tuple input shape to onnx model device : torch.device device of the model, used to place the dummy input tensor for exporting onnx file. the tensor is placed on cpu if ```device``` is None Returns ------- Dict """ raise NotImplementedError('Quantizer must overload export_model()')
[ "def", "export_model", "(", "self", ",", "model_path", ",", "calibration_path", "=", "None", ",", "onnx_path", "=", "None", ",", "input_shape", "=", "None", ",", "device", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'Quantizer must overload export_model()'", ")" ]
[ 638, 4 ]
[ 660, 75 ]
python
en
['en', 'error', 'th']
False
QuantGrad._quantize
(cls, x, scale, zero_point)
Reference function for quantizing x -- non-clamped. Parameters ---------- x : Tensor tensor to be quantized scale : Tensor scale for quantizing x zero_point : Tensor zero_point for quantizing x Returns ------- tensor quantized x without clamped
Reference function for quantizing x -- non-clamped. Parameters ---------- x : Tensor tensor to be quantized scale : Tensor scale for quantizing x zero_point : Tensor zero_point for quantizing x Returns ------- tensor quantized x without clamped
def _quantize(cls, x, scale, zero_point): """ Reference function for quantizing x -- non-clamped. Parameters ---------- x : Tensor tensor to be quantized scale : Tensor scale for quantizing x zero_point : Tensor zero_point for quantizing x Returns ------- tensor quantized x without clamped """ return ((x / scale) + zero_point).round()
[ "def", "_quantize", "(", "cls", ",", "x", ",", "scale", ",", "zero_point", ")", ":", "return", "(", "(", "x", "/", "scale", ")", "+", "zero_point", ")", ".", "round", "(", ")" ]
[ 684, 4 ]
[ 700, 49 ]
python
en
['en', 'error', 'th']
False
QuantGrad.get_bits_length
(cls, config, quant_type)
Get bit for quantize config Parameters ---------- config : Dict the configuration for quantization quant_type : str quant type Returns ------- int n-bits for quantization configuration
Get bit for quantize config Parameters ---------- config : Dict the configuration for quantization quant_type : str quant type Returns ------- int n-bits for quantization configuration
def get_bits_length(cls, config, quant_type): """ Get bit for quantize config Parameters ---------- config : Dict the configuration for quantization quant_type : str quant type Returns ------- int n-bits for quantization configuration """ if isinstance(config["quant_bits"], int): return config["quant_bits"] else: return config["quant_bits"].get(quant_type)
[ "def", "get_bits_length", "(", "cls", ",", "config", ",", "quant_type", ")", ":", "if", "isinstance", "(", "config", "[", "\"quant_bits\"", "]", ",", "int", ")", ":", "return", "config", "[", "\"quant_bits\"", "]", "else", ":", "return", "config", "[", "\"quant_bits\"", "]", ".", "get", "(", "quant_type", ")" ]
[ 703, 4 ]
[ 720, 55 ]
python
en
['en', 'error', 'th']
False
QuantGrad.quant_backward
(tensor, grad_output, quant_type, scale, zero_point, qmin, qmax)
This method should be overrided by subclass to provide customized backward function, default implementation is Straight-Through Estimator Parameters ---------- tensor : Tensor input of quantization operation grad_output : Tensor gradient of the output of quantization operation scale : Tensor the type of quantization, it can be `QuantType.QUANT_INPUT`, `QuantType.QUANT_WEIGHT`, `QuantType.QUANT_OUTPUT`, you can define different behavior for different types. zero_point : Tensor zero_point for quantizing tensor qmin : Tensor quant_min for quantizing tensor qmax : Tensor quant_max for quantizng tensor Returns ------- tensor gradient of the input of quantization operation
This method should be overrided by subclass to provide customized backward function, default implementation is Straight-Through Estimator Parameters ---------- tensor : Tensor input of quantization operation grad_output : Tensor gradient of the output of quantization operation scale : Tensor the type of quantization, it can be `QuantType.QUANT_INPUT`, `QuantType.QUANT_WEIGHT`, `QuantType.QUANT_OUTPUT`, you can define different behavior for different types. zero_point : Tensor zero_point for quantizing tensor qmin : Tensor quant_min for quantizing tensor qmax : Tensor quant_max for quantizng tensor Returns ------- tensor gradient of the input of quantization operation
def quant_backward(tensor, grad_output, quant_type, scale, zero_point, qmin, qmax): """ This method should be overrided by subclass to provide customized backward function, default implementation is Straight-Through Estimator Parameters ---------- tensor : Tensor input of quantization operation grad_output : Tensor gradient of the output of quantization operation scale : Tensor the type of quantization, it can be `QuantType.QUANT_INPUT`, `QuantType.QUANT_WEIGHT`, `QuantType.QUANT_OUTPUT`, you can define different behavior for different types. zero_point : Tensor zero_point for quantizing tensor qmin : Tensor quant_min for quantizing tensor qmax : Tensor quant_max for quantizng tensor Returns ------- tensor gradient of the input of quantization operation """ return grad_output
[ "def", "quant_backward", "(", "tensor", ",", "grad_output", ",", "quant_type", ",", "scale", ",", "zero_point", ",", "qmin", ",", "qmax", ")", ":", "return", "grad_output" ]
[ 723, 4 ]
[ 747, 26 ]
python
en
['en', 'error', 'th']
False
test_platform_manually_configured
(hass)
Test that nothing happens when platform is manually configured.
Test that nothing happens when platform is manually configured.
async def test_platform_manually_configured(hass): """Test that nothing happens when platform is manually configured.""" assert ( await async_setup_component( hass, CAMERA_DOMAIN, {CAMERA_DOMAIN: {"platform": AXIS_DOMAIN}} ) is True ) assert AXIS_DOMAIN not in hass.data
[ "async", "def", "test_platform_manually_configured", "(", "hass", ")", ":", "assert", "(", "await", "async_setup_component", "(", "hass", ",", "CAMERA_DOMAIN", ",", "{", "CAMERA_DOMAIN", ":", "{", "\"platform\"", ":", "AXIS_DOMAIN", "}", "}", ")", "is", "True", ")", "assert", "AXIS_DOMAIN", "not", "in", "hass", ".", "data" ]
[ 16, 0 ]
[ 25, 39 ]
python
en
['en', 'en', 'en']
True
test_camera
(hass)
Test that Axis camera platform is loaded properly.
Test that Axis camera platform is loaded properly.
async def test_camera(hass): """Test that Axis camera platform is loaded properly.""" await setup_axis_integration(hass) assert len(hass.states.async_entity_ids(CAMERA_DOMAIN)) == 1 entity_id = f"{CAMERA_DOMAIN}.{NAME}" cam = hass.states.get(entity_id) assert cam.state == STATE_IDLE assert cam.name == NAME camera_entity = camera._get_camera_from_entity_id(hass, entity_id) assert camera_entity.image_source == "http://1.2.3.4:80/axis-cgi/jpg/image.cgi" assert camera_entity.mjpeg_source == "http://1.2.3.4:80/axis-cgi/mjpg/video.cgi" assert ( await camera_entity.stream_source() == "rtsp://root:pass@1.2.3.4/axis-media/media.amp?videocodec=h264" )
[ "async", "def", "test_camera", "(", "hass", ")", ":", "await", "setup_axis_integration", "(", "hass", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", "CAMERA_DOMAIN", ")", ")", "==", "1", "entity_id", "=", "f\"{CAMERA_DOMAIN}.{NAME}\"", "cam", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "cam", ".", "state", "==", "STATE_IDLE", "assert", "cam", ".", "name", "==", "NAME", "camera_entity", "=", "camera", ".", "_get_camera_from_entity_id", "(", "hass", ",", "entity_id", ")", "assert", "camera_entity", ".", "image_source", "==", "\"http://1.2.3.4:80/axis-cgi/jpg/image.cgi\"", "assert", "camera_entity", ".", "mjpeg_source", "==", "\"http://1.2.3.4:80/axis-cgi/mjpg/video.cgi\"", "assert", "(", "await", "camera_entity", ".", "stream_source", "(", ")", "==", "\"rtsp://root:pass@1.2.3.4/axis-media/media.amp?videocodec=h264\"", ")" ]
[ 28, 0 ]
[ 46, 5 ]
python
en
['en', 'en', 'en']
True
test_camera_with_stream_profile
(hass)
Test that Axis camera entity is using the correct path with stream profike.
Test that Axis camera entity is using the correct path with stream profike.
async def test_camera_with_stream_profile(hass): """Test that Axis camera entity is using the correct path with stream profike.""" with patch.dict(ENTRY_OPTIONS, {CONF_STREAM_PROFILE: "profile_1"}): await setup_axis_integration(hass) assert len(hass.states.async_entity_ids(CAMERA_DOMAIN)) == 1 entity_id = f"{CAMERA_DOMAIN}.{NAME}" cam = hass.states.get(entity_id) assert cam.state == STATE_IDLE assert cam.name == NAME camera_entity = camera._get_camera_from_entity_id(hass, entity_id) assert camera_entity.image_source == "http://1.2.3.4:80/axis-cgi/jpg/image.cgi" assert ( camera_entity.mjpeg_source == "http://1.2.3.4:80/axis-cgi/mjpg/video.cgi?&streamprofile=profile_1" ) assert ( await camera_entity.stream_source() == "rtsp://root:pass@1.2.3.4/axis-media/media.amp?videocodec=h264&streamprofile=profile_1" )
[ "async", "def", "test_camera_with_stream_profile", "(", "hass", ")", ":", "with", "patch", ".", "dict", "(", "ENTRY_OPTIONS", ",", "{", "CONF_STREAM_PROFILE", ":", "\"profile_1\"", "}", ")", ":", "await", "setup_axis_integration", "(", "hass", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", "CAMERA_DOMAIN", ")", ")", "==", "1", "entity_id", "=", "f\"{CAMERA_DOMAIN}.{NAME}\"", "cam", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "cam", ".", "state", "==", "STATE_IDLE", "assert", "cam", ".", "name", "==", "NAME", "camera_entity", "=", "camera", ".", "_get_camera_from_entity_id", "(", "hass", ",", "entity_id", ")", "assert", "camera_entity", ".", "image_source", "==", "\"http://1.2.3.4:80/axis-cgi/jpg/image.cgi\"", "assert", "(", "camera_entity", ".", "mjpeg_source", "==", "\"http://1.2.3.4:80/axis-cgi/mjpg/video.cgi?&streamprofile=profile_1\"", ")", "assert", "(", "await", "camera_entity", ".", "stream_source", "(", ")", "==", "\"rtsp://root:pass@1.2.3.4/axis-media/media.amp?videocodec=h264&streamprofile=profile_1\"", ")" ]
[ 49, 0 ]
[ 71, 5 ]
python
en
['en', 'en', 'en']
True
test_camera_disabled
(hass)
Test that Axis camera platform is loaded properly but does not create camera entity.
Test that Axis camera platform is loaded properly but does not create camera entity.
async def test_camera_disabled(hass): """Test that Axis camera platform is loaded properly but does not create camera entity.""" with patch("axis.vapix.Params.image_format", new=None): await setup_axis_integration(hass) assert len(hass.states.async_entity_ids(CAMERA_DOMAIN)) == 0
[ "async", "def", "test_camera_disabled", "(", "hass", ")", ":", "with", "patch", "(", "\"axis.vapix.Params.image_format\"", ",", "new", "=", "None", ")", ":", "await", "setup_axis_integration", "(", "hass", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", "CAMERA_DOMAIN", ")", ")", "==", "0" ]
[ 74, 0 ]
[ 79, 64 ]
python
en
['en', 'en', 'en']
True
infer_framework_from_model
(model, model_classes: Optional[Dict[str, type]] = None, revision: Optional[str] = None)
Select framework (TensorFlow or PyTorch) to use from the :obj:`model` passed. Returns a tuple (framework, model). If :obj:`model` is instantiated, this function will just infer the framework from the model class. Otherwise :obj:`model` is actually a checkpoint name and this method will try to instantiate it using :obj:`model_classes`. Since we don't want to instantiate the model twice, this model is returned for use by the pipeline. If both frameworks are installed and available for :obj:`model`, PyTorch is selected. Args: model (:obj:`str`, :class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`): The model to infer the framework from. If :obj:`str`, a checkpoint name. The model to infer the framewrok from. model_classes (dictionary :obj:`str` to :obj:`type`, `optional`): A mapping framework to class. revision (:obj:`str`, `optional`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so ``revision`` can be any identifier allowed by git. Returns: :obj:`Tuple`: A tuple framework, model.
Select framework (TensorFlow or PyTorch) to use from the :obj:`model` passed. Returns a tuple (framework, model).
def infer_framework_from_model(model, model_classes: Optional[Dict[str, type]] = None, revision: Optional[str] = None): """ Select framework (TensorFlow or PyTorch) to use from the :obj:`model` passed. Returns a tuple (framework, model). If :obj:`model` is instantiated, this function will just infer the framework from the model class. Otherwise :obj:`model` is actually a checkpoint name and this method will try to instantiate it using :obj:`model_classes`. Since we don't want to instantiate the model twice, this model is returned for use by the pipeline. If both frameworks are installed and available for :obj:`model`, PyTorch is selected. Args: model (:obj:`str`, :class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`): The model to infer the framework from. If :obj:`str`, a checkpoint name. The model to infer the framewrok from. model_classes (dictionary :obj:`str` to :obj:`type`, `optional`): A mapping framework to class. revision (:obj:`str`, `optional`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so ``revision`` can be any identifier allowed by git. Returns: :obj:`Tuple`: A tuple framework, model. """ if not is_tf_available() and not is_torch_available(): raise RuntimeError( "At least one of TensorFlow 2.0 or PyTorch should be installed. " "To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ " "To install PyTorch, read the instructions at https://pytorch.org/." ) if isinstance(model, str): if is_torch_available() and not is_tf_available(): model_class = model_classes.get("pt", AutoModel) model = model_class.from_pretrained(model, revision=revision) elif is_tf_available() and not is_torch_available(): model_class = model_classes.get("tf", TFAutoModel) model = model_class.from_pretrained(model, revision=revision) else: try: model_class = model_classes.get("pt", AutoModel) model = model_class.from_pretrained(model, revision=revision) except OSError: model_class = model_classes.get("tf", TFAutoModel) model = model_class.from_pretrained(model, revision=revision) framework = "tf" if model.__class__.__name__.startswith("TF") else "pt" return framework, model
[ "def", "infer_framework_from_model", "(", "model", ",", "model_classes", ":", "Optional", "[", "Dict", "[", "str", ",", "type", "]", "]", "=", "None", ",", "revision", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "if", "not", "is_tf_available", "(", ")", "and", "not", "is_torch_available", "(", ")", ":", "raise", "RuntimeError", "(", "\"At least one of TensorFlow 2.0 or PyTorch should be installed. \"", "\"To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ \"", "\"To install PyTorch, read the instructions at https://pytorch.org/.\"", ")", "if", "isinstance", "(", "model", ",", "str", ")", ":", "if", "is_torch_available", "(", ")", "and", "not", "is_tf_available", "(", ")", ":", "model_class", "=", "model_classes", ".", "get", "(", "\"pt\"", ",", "AutoModel", ")", "model", "=", "model_class", ".", "from_pretrained", "(", "model", ",", "revision", "=", "revision", ")", "elif", "is_tf_available", "(", ")", "and", "not", "is_torch_available", "(", ")", ":", "model_class", "=", "model_classes", ".", "get", "(", "\"tf\"", ",", "TFAutoModel", ")", "model", "=", "model_class", ".", "from_pretrained", "(", "model", ",", "revision", "=", "revision", ")", "else", ":", "try", ":", "model_class", "=", "model_classes", ".", "get", "(", "\"pt\"", ",", "AutoModel", ")", "model", "=", "model_class", ".", "from_pretrained", "(", "model", ",", "revision", "=", "revision", ")", "except", "OSError", ":", "model_class", "=", "model_classes", ".", "get", "(", "\"tf\"", ",", "TFAutoModel", ")", "model", "=", "model_class", ".", "from_pretrained", "(", "model", ",", "revision", "=", "revision", ")", "framework", "=", "\"tf\"", "if", "model", ".", "__class__", ".", "__name__", ".", "startswith", "(", "\"TF\"", ")", "else", "\"pt\"", "return", "framework", ",", "model" ]
[ 49, 0 ]
[ 95, 27 ]
python
en
['en', 'error', 'th']
False
get_framework
(model, revision: Optional[str] = None)
Select framework (TensorFlow or PyTorch) to use. Args: model (:obj:`str`, :class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`): If both frameworks are installed, picks the one corresponding to the model passed (either a model class or the model name). If no specific model is provided, defaults to using PyTorch.
Select framework (TensorFlow or PyTorch) to use.
def get_framework(model, revision: Optional[str] = None): """ Select framework (TensorFlow or PyTorch) to use. Args: model (:obj:`str`, :class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`): If both frameworks are installed, picks the one corresponding to the model passed (either a model class or the model name). If no specific model is provided, defaults to using PyTorch. """ warnings.warn( "`get_framework` is deprecated and will be removed in v5, use `infer_framework_from_model` instead.", FutureWarning, ) if not is_tf_available() and not is_torch_available(): raise RuntimeError( "At least one of TensorFlow 2.0 or PyTorch should be installed. " "To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ " "To install PyTorch, read the instructions at https://pytorch.org/." ) if isinstance(model, str): if is_torch_available() and not is_tf_available(): model = AutoModel.from_pretrained(model, revision=revision) elif is_tf_available() and not is_torch_available(): model = TFAutoModel.from_pretrained(model, revision=revision) else: try: model = AutoModel.from_pretrained(model, revision=revision) except OSError: model = TFAutoModel.from_pretrained(model, revision=revision) framework = "tf" if model.__class__.__name__.startswith("TF") else "pt" return framework
[ "def", "get_framework", "(", "model", ",", "revision", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"`get_framework` is deprecated and will be removed in v5, use `infer_framework_from_model` instead.\"", ",", "FutureWarning", ",", ")", "if", "not", "is_tf_available", "(", ")", "and", "not", "is_torch_available", "(", ")", ":", "raise", "RuntimeError", "(", "\"At least one of TensorFlow 2.0 or PyTorch should be installed. \"", "\"To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ \"", "\"To install PyTorch, read the instructions at https://pytorch.org/.\"", ")", "if", "isinstance", "(", "model", ",", "str", ")", ":", "if", "is_torch_available", "(", ")", "and", "not", "is_tf_available", "(", ")", ":", "model", "=", "AutoModel", ".", "from_pretrained", "(", "model", ",", "revision", "=", "revision", ")", "elif", "is_tf_available", "(", ")", "and", "not", "is_torch_available", "(", ")", ":", "model", "=", "TFAutoModel", ".", "from_pretrained", "(", "model", ",", "revision", "=", "revision", ")", "else", ":", "try", ":", "model", "=", "AutoModel", ".", "from_pretrained", "(", "model", ",", "revision", "=", "revision", ")", "except", "OSError", ":", "model", "=", "TFAutoModel", ".", "from_pretrained", "(", "model", ",", "revision", "=", "revision", ")", "framework", "=", "\"tf\"", "if", "model", ".", "__class__", ".", "__name__", ".", "startswith", "(", "\"TF\"", ")", "else", "\"pt\"", "return", "framework" ]
[ 98, 0 ]
[ 129, 20 ]
python
en
['en', 'error', 'th']
False
get_default_model
(targeted_task: Dict, framework: Optional[str], task_options: Optional[Any])
Select a default model to use for a given task. Defaults to pytorch if ambiguous. Args: targeted_task (:obj:`Dict` ): Dictionary representing the given task, that should contain default models framework (:obj:`str`, None) "pt", "tf" or None, representing a specific framework if it was specified, or None if we don't know yet. task_options (:obj:`Any`, None) Any further value required by the task to get fully specified, for instance (SRC, TGT) languages for translation task. Returns :obj:`str` The model string representing the default model for this pipeline
Select a default model to use for a given task. Defaults to pytorch if ambiguous.
def get_default_model(targeted_task: Dict, framework: Optional[str], task_options: Optional[Any]) -> str: """ Select a default model to use for a given task. Defaults to pytorch if ambiguous. Args: targeted_task (:obj:`Dict` ): Dictionary representing the given task, that should contain default models framework (:obj:`str`, None) "pt", "tf" or None, representing a specific framework if it was specified, or None if we don't know yet. task_options (:obj:`Any`, None) Any further value required by the task to get fully specified, for instance (SRC, TGT) languages for translation task. Returns :obj:`str` The model string representing the default model for this pipeline """ if is_torch_available() and not is_tf_available(): framework = "pt" elif is_tf_available() and not is_torch_available(): framework = "tf" defaults = targeted_task["default"] if task_options: if task_options not in defaults: raise ValueError("The task does not provide any default models for options {}".format(task_options)) default_models = defaults[task_options]["model"] elif "model" in defaults: default_models = targeted_task["default"]["model"] else: # XXX This error message needs to be updated to be more generic if more tasks are going to become # parametrized raise ValueError('The task defaults can\'t be correctly selected. You probably meant "translation_XX_to_YY"') if framework is None: framework = "pt" return default_models[framework]
[ "def", "get_default_model", "(", "targeted_task", ":", "Dict", ",", "framework", ":", "Optional", "[", "str", "]", ",", "task_options", ":", "Optional", "[", "Any", "]", ")", "->", "str", ":", "if", "is_torch_available", "(", ")", "and", "not", "is_tf_available", "(", ")", ":", "framework", "=", "\"pt\"", "elif", "is_tf_available", "(", ")", "and", "not", "is_torch_available", "(", ")", ":", "framework", "=", "\"tf\"", "defaults", "=", "targeted_task", "[", "\"default\"", "]", "if", "task_options", ":", "if", "task_options", "not", "in", "defaults", ":", "raise", "ValueError", "(", "\"The task does not provide any default models for options {}\"", ".", "format", "(", "task_options", ")", ")", "default_models", "=", "defaults", "[", "task_options", "]", "[", "\"model\"", "]", "elif", "\"model\"", "in", "defaults", ":", "default_models", "=", "targeted_task", "[", "\"default\"", "]", "[", "\"model\"", "]", "else", ":", "# XXX This error message needs to be updated to be more generic if more tasks are going to become", "# parametrized", "raise", "ValueError", "(", "'The task defaults can\\'t be correctly selected. You probably meant \"translation_XX_to_YY\"'", ")", "if", "framework", "is", "None", ":", "framework", "=", "\"pt\"", "return", "default_models", "[", "framework", "]" ]
[ 132, 0 ]
[ 171, 36 ]
python
en
['en', 'error', 'th']
False
PipelineDataFormat.save
(self, data: Union[dict, List[dict]])
Save the provided data object with the representation for the current :class:`~transformers.pipelines.PipelineDataFormat`. Args: data (:obj:`dict` or list of :obj:`dict`): The data to store.
Save the provided data object with the representation for the current :class:`~transformers.pipelines.PipelineDataFormat`.
def save(self, data: Union[dict, List[dict]]): """ Save the provided data object with the representation for the current :class:`~transformers.pipelines.PipelineDataFormat`. Args: data (:obj:`dict` or list of :obj:`dict`): The data to store. """ raise NotImplementedError()
[ "def", "save", "(", "self", ",", "data", ":", "Union", "[", "dict", ",", "List", "[", "dict", "]", "]", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 251, 4 ]
[ 259, 35 ]
python
en
['en', 'error', 'th']
False
PipelineDataFormat.save_binary
(self, data: Union[dict, List[dict]])
Save the provided data object as a pickle-formatted binary data on the disk. Args: data (:obj:`dict` or list of :obj:`dict`): The data to store. Returns: :obj:`str`: Path where the data has been saved.
Save the provided data object as a pickle-formatted binary data on the disk.
def save_binary(self, data: Union[dict, List[dict]]) -> str: """ Save the provided data object as a pickle-formatted binary data on the disk. Args: data (:obj:`dict` or list of :obj:`dict`): The data to store. Returns: :obj:`str`: Path where the data has been saved. """ path, _ = os.path.splitext(self.output_path) binary_path = os.path.extsep.join((path, "pickle")) with open(binary_path, "wb+") as f_output: pickle.dump(data, f_output) return binary_path
[ "def", "save_binary", "(", "self", ",", "data", ":", "Union", "[", "dict", ",", "List", "[", "dict", "]", "]", ")", "->", "str", ":", "path", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "output_path", ")", "binary_path", "=", "os", ".", "path", ".", "extsep", ".", "join", "(", "(", "path", ",", "\"pickle\"", ")", ")", "with", "open", "(", "binary_path", ",", "\"wb+\"", ")", "as", "f_output", ":", "pickle", ".", "dump", "(", "data", ",", "f_output", ")", "return", "binary_path" ]
[ 261, 4 ]
[ 277, 26 ]
python
en
['en', 'error', 'th']
False
PipelineDataFormat.from_str
( format: str, output_path: Optional[str], input_path: Optional[str], column: Optional[str], overwrite=False, )
Creates an instance of the right subclass of :class:`~transformers.pipelines.PipelineDataFormat` depending on :obj:`format`. Args: format: (:obj:`str`): The format of the desired pipeline. Acceptable values are :obj:`"json"`, :obj:`"csv"` or :obj:`"pipe"`. output_path (:obj:`str`, `optional`): Where to save the outgoing data. input_path (:obj:`str`, `optional`): Where to look for the input data. column (:obj:`str`, `optional`): The column to read. overwrite (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not to overwrite the :obj:`output_path`. Returns: :class:`~transformers.pipelines.PipelineDataFormat`: The proper data format.
Creates an instance of the right subclass of :class:`~transformers.pipelines.PipelineDataFormat` depending on :obj:`format`.
def from_str( format: str, output_path: Optional[str], input_path: Optional[str], column: Optional[str], overwrite=False, ) -> "PipelineDataFormat": """ Creates an instance of the right subclass of :class:`~transformers.pipelines.PipelineDataFormat` depending on :obj:`format`. Args: format: (:obj:`str`): The format of the desired pipeline. Acceptable values are :obj:`"json"`, :obj:`"csv"` or :obj:`"pipe"`. output_path (:obj:`str`, `optional`): Where to save the outgoing data. input_path (:obj:`str`, `optional`): Where to look for the input data. column (:obj:`str`, `optional`): The column to read. overwrite (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not to overwrite the :obj:`output_path`. Returns: :class:`~transformers.pipelines.PipelineDataFormat`: The proper data format. """ if format == "json": return JsonPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) elif format == "csv": return CsvPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) elif format == "pipe": return PipedPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) else: raise KeyError("Unknown reader {} (Available reader are json/csv/pipe)".format(format))
[ "def", "from_str", "(", "format", ":", "str", ",", "output_path", ":", "Optional", "[", "str", "]", ",", "input_path", ":", "Optional", "[", "str", "]", ",", "column", ":", "Optional", "[", "str", "]", ",", "overwrite", "=", "False", ",", ")", "->", "\"PipelineDataFormat\"", ":", "if", "format", "==", "\"json\"", ":", "return", "JsonPipelineDataFormat", "(", "output_path", ",", "input_path", ",", "column", ",", "overwrite", "=", "overwrite", ")", "elif", "format", "==", "\"csv\"", ":", "return", "CsvPipelineDataFormat", "(", "output_path", ",", "input_path", ",", "column", ",", "overwrite", "=", "overwrite", ")", "elif", "format", "==", "\"pipe\"", ":", "return", "PipedPipelineDataFormat", "(", "output_path", ",", "input_path", ",", "column", ",", "overwrite", "=", "overwrite", ")", "else", ":", "raise", "KeyError", "(", "\"Unknown reader {} (Available reader are json/csv/pipe)\"", ".", "format", "(", "format", ")", ")" ]
[ 280, 4 ]
[ 313, 99 ]
python
en
['en', 'error', 'th']
False
CsvPipelineDataFormat.save
(self, data: List[dict])
Save the provided data object with the representation for the current :class:`~transformers.pipelines.PipelineDataFormat`. Args: data (:obj:`List[dict]`): The data to store.
Save the provided data object with the representation for the current :class:`~transformers.pipelines.PipelineDataFormat`.
def save(self, data: List[dict]): """ Save the provided data object with the representation for the current :class:`~transformers.pipelines.PipelineDataFormat`. Args: data (:obj:`List[dict]`): The data to store. """ with open(self.output_path, "w") as f: if len(data) > 0: writer = csv.DictWriter(f, list(data[0].keys())) writer.writeheader() writer.writerows(data)
[ "def", "save", "(", "self", ",", "data", ":", "List", "[", "dict", "]", ")", ":", "with", "open", "(", "self", ".", "output_path", ",", "\"w\"", ")", "as", "f", ":", "if", "len", "(", "data", ")", ">", "0", ":", "writer", "=", "csv", ".", "DictWriter", "(", "f", ",", "list", "(", "data", "[", "0", "]", ".", "keys", "(", ")", ")", ")", "writer", ".", "writeheader", "(", ")", "writer", ".", "writerows", "(", "data", ")" ]
[ 346, 4 ]
[ 358, 38 ]
python
en
['en', 'error', 'th']
False
JsonPipelineDataFormat.save
(self, data: dict)
Save the provided data object in a json file. Args: data (:obj:`dict`): The data to store.
Save the provided data object in a json file.
def save(self, data: dict): """ Save the provided data object in a json file. Args: data (:obj:`dict`): The data to store. """ with open(self.output_path, "w") as f: json.dump(data, f)
[ "def", "save", "(", "self", ",", "data", ":", "dict", ")", ":", "with", "open", "(", "self", ".", "output_path", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ")" ]
[ 392, 4 ]
[ 400, 30 ]
python
en
['en', 'error', 'th']
False
PipedPipelineDataFormat.save
(self, data: dict)
Print the data. Args: data (:obj:`dict`): The data to store.
Print the data.
def save(self, data: dict): """ Print the data. Args: data (:obj:`dict`): The data to store. """ print(data)
[ "def", "save", "(", "self", ",", "data", ":", "dict", ")", ":", "print", "(", "data", ")" ]
[ 433, 4 ]
[ 440, 19 ]
python
en
['en', 'error', 'th']
False
async_setup
(hass)
Set up the Automation config API.
Set up the Automation config API.
async def async_setup(hass): """Set up the Automation config API.""" async def hook(action, config_key): """post_write_hook for Config View that reloads automations.""" await hass.services.async_call(DOMAIN, SERVICE_RELOAD) if action != ACTION_DELETE: return ent_reg = await entity_registry.async_get_registry(hass) entity_id = ent_reg.async_get_entity_id(DOMAIN, DOMAIN, config_key) if entity_id is None: return ent_reg.async_remove(entity_id) hass.http.register_view( EditAutomationConfigView( DOMAIN, "config", AUTOMATION_CONFIG_PATH, cv.string, PLATFORM_SCHEMA, post_write_hook=hook, data_validator=async_validate_config_item, ) ) return True
[ "async", "def", "async_setup", "(", "hass", ")", ":", "async", "def", "hook", "(", "action", ",", "config_key", ")", ":", "\"\"\"post_write_hook for Config View that reloads automations.\"\"\"", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_RELOAD", ")", "if", "action", "!=", "ACTION_DELETE", ":", "return", "ent_reg", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "entity_id", "=", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "config_key", ")", "if", "entity_id", "is", "None", ":", "return", "ent_reg", ".", "async_remove", "(", "entity_id", ")", "hass", ".", "http", ".", "register_view", "(", "EditAutomationConfigView", "(", "DOMAIN", ",", "\"config\"", ",", "AUTOMATION_CONFIG_PATH", ",", "cv", ".", "string", ",", "PLATFORM_SCHEMA", ",", "post_write_hook", "=", "hook", ",", "data_validator", "=", "async_validate_config_item", ",", ")", ")", "return", "True" ]
[ 16, 0 ]
[ 46, 15 ]
python
en
['en', 'en', 'en']
True
async_describe_on_off_states
( hass: HomeAssistantType, registry: GroupIntegrationRegistry )
Describe group on off states.
Describe group on off states.
def async_describe_on_off_states( hass: HomeAssistantType, registry: GroupIntegrationRegistry ) -> None: """Describe group on off states.""" registry.on_off_states( {STATE_CLEANING, STATE_ON, STATE_RETURNING, STATE_ERROR}, STATE_OFF )
[ "def", "async_describe_on_off_states", "(", "hass", ":", "HomeAssistantType", ",", "registry", ":", "GroupIntegrationRegistry", ")", "->", "None", ":", "registry", ".", "on_off_states", "(", "{", "STATE_CLEANING", ",", "STATE_ON", ",", "STATE_RETURNING", ",", "STATE_ERROR", "}", ",", "STATE_OFF", ")" ]
[ 12, 0 ]
[ 18, 5 ]
python
en
['en', 'en', 'en']
True
RoonServer.__init__
(self, hass, config_entry)
Initialize the system.
Initialize the system.
def __init__(self, hass, config_entry): """Initialize the system.""" self.config_entry = config_entry self.hass = hass self.roonapi = None self.all_player_ids = set() self.all_playlists = [] self.offline_devices = set() self._exit = False self._roon_name_by_id = {}
[ "def", "__init__", "(", "self", ",", "hass", ",", "config_entry", ")", ":", "self", ".", "config_entry", "=", "config_entry", "self", ".", "hass", "=", "hass", "self", ".", "roonapi", "=", "None", "self", ".", "all_player_ids", "=", "set", "(", ")", "self", ".", "all_playlists", "=", "[", "]", "self", ".", "offline_devices", "=", "set", "(", ")", "self", ".", "_exit", "=", "False", "self", ".", "_roon_name_by_id", "=", "{", "}" ]
[ 19, 4 ]
[ 28, 34 ]
python
en
['en', 'en', 'en']
True
RoonServer.host
(self)
Return the host of this server.
Return the host of this server.
def host(self): """Return the host of this server.""" return self.config_entry.data[CONF_HOST]
[ "def", "host", "(", "self", ")", ":", "return", "self", ".", "config_entry", ".", "data", "[", "CONF_HOST", "]" ]
[ 31, 4 ]
[ 33, 48 ]
python
en
['en', 'en', 'en']
True
RoonServer.async_setup
(self, tries=0)
Set up a roon server based on host parameter.
Set up a roon server based on host parameter.
async def async_setup(self, tries=0): """Set up a roon server based on host parameter.""" host = self.host hass = self.hass token = self.config_entry.data[CONF_API_KEY] _LOGGER.debug("async_setup: %s %s", token, host) self.roonapi = RoonApi(ROON_APPINFO, token, host, blocking_init=False) self.roonapi.register_state_callback( self.roonapi_state_callback, event_filter=["zones_changed"] ) # initialize media_player platform hass.async_create_task( hass.config_entries.async_forward_entry_setup( self.config_entry, "media_player" ) ) # Initialize Roon background polling asyncio.create_task(self.async_do_loop()) return True
[ "async", "def", "async_setup", "(", "self", ",", "tries", "=", "0", ")", ":", "host", "=", "self", ".", "host", "hass", "=", "self", ".", "hass", "token", "=", "self", ".", "config_entry", ".", "data", "[", "CONF_API_KEY", "]", "_LOGGER", ".", "debug", "(", "\"async_setup: %s %s\"", ",", "token", ",", "host", ")", "self", ".", "roonapi", "=", "RoonApi", "(", "ROON_APPINFO", ",", "token", ",", "host", ",", "blocking_init", "=", "False", ")", "self", ".", "roonapi", ".", "register_state_callback", "(", "self", ".", "roonapi_state_callback", ",", "event_filter", "=", "[", "\"zones_changed\"", "]", ")", "# initialize media_player platform", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "self", ".", "config_entry", ",", "\"media_player\"", ")", ")", "# Initialize Roon background polling", "asyncio", ".", "create_task", "(", "self", ".", "async_do_loop", "(", ")", ")", "return", "True" ]
[ 35, 4 ]
[ 56, 19 ]
python
en
['en', 'da', 'en']
True
RoonServer.async_reset
(self)
Reset this connection to default state. Will cancel any scheduled setup retry and will unload the config entry.
Reset this connection to default state.
async def async_reset(self): """Reset this connection to default state. Will cancel any scheduled setup retry and will unload the config entry. """ self.stop_roon() return True
[ "async", "def", "async_reset", "(", "self", ")", ":", "self", ".", "stop_roon", "(", ")", "return", "True" ]
[ 58, 4 ]
[ 65, 19 ]
python
en
['en', 'en', 'en']
True
RoonServer.zones
(self)
Return list of zones.
Return list of zones.
def zones(self): """Return list of zones.""" return self.roonapi.zones
[ "def", "zones", "(", "self", ")", ":", "return", "self", ".", "roonapi", ".", "zones" ]
[ 68, 4 ]
[ 70, 33 ]
python
en
['en', 'nl', 'en']
True
RoonServer.add_player_id
(self, entity_id, roon_name)
Register a roon player.
Register a roon player.
def add_player_id(self, entity_id, roon_name): """Register a roon player.""" self._roon_name_by_id[entity_id] = roon_name
[ "def", "add_player_id", "(", "self", ",", "entity_id", ",", "roon_name", ")", ":", "self", ".", "_roon_name_by_id", "[", "entity_id", "]", "=", "roon_name" ]
[ 72, 4 ]
[ 74, 52 ]
python
en
['en', 'en', 'en']
True
RoonServer.roon_name
(self, entity_id)
Get the name of the roon player from entity_id.
Get the name of the roon player from entity_id.
def roon_name(self, entity_id): """Get the name of the roon player from entity_id.""" return self._roon_name_by_id.get(entity_id)
[ "def", "roon_name", "(", "self", ",", "entity_id", ")", ":", "return", "self", ".", "_roon_name_by_id", ".", "get", "(", "entity_id", ")" ]
[ 76, 4 ]
[ 78, 51 ]
python
en
['en', 'en', 'en']
True
RoonServer.stop_roon
(self)
Stop background worker.
Stop background worker.
def stop_roon(self): """Stop background worker.""" self.roonapi.stop() self._exit = True
[ "def", "stop_roon", "(", "self", ")", ":", "self", ".", "roonapi", ".", "stop", "(", ")", "self", ".", "_exit", "=", "True" ]
[ 80, 4 ]
[ 83, 25 ]
python
en
['en', 'en', 'en']
True
RoonServer.roonapi_state_callback
(self, event, changed_zones)
Callbacks from the roon api websockets.
Callbacks from the roon api websockets.
def roonapi_state_callback(self, event, changed_zones): """Callbacks from the roon api websockets.""" self.hass.add_job(self.async_update_changed_players(changed_zones))
[ "def", "roonapi_state_callback", "(", "self", ",", "event", ",", "changed_zones", ")", ":", "self", ".", "hass", ".", "add_job", "(", "self", ".", "async_update_changed_players", "(", "changed_zones", ")", ")" ]
[ 85, 4 ]
[ 87, 75 ]
python
en
['en', 'mg', 'en']
True
RoonServer.async_do_loop
(self)
Background work loop.
Background work loop.
async def async_do_loop(self): """Background work loop.""" self._exit = False while not self._exit: await self.async_update_players() # await self.async_update_playlists() await asyncio.sleep(FULL_SYNC_INTERVAL)
[ "async", "def", "async_do_loop", "(", "self", ")", ":", "self", ".", "_exit", "=", "False", "while", "not", "self", ".", "_exit", ":", "await", "self", ".", "async_update_players", "(", ")", "# await self.async_update_playlists()", "await", "asyncio", ".", "sleep", "(", "FULL_SYNC_INTERVAL", ")" ]
[ 89, 4 ]
[ 95, 51 ]
python
en
['en', 'af', 'en']
True
RoonServer.async_update_changed_players
(self, changed_zones_ids)
Update the players which were reported as changed by the Roon API.
Update the players which were reported as changed by the Roon API.
async def async_update_changed_players(self, changed_zones_ids): """Update the players which were reported as changed by the Roon API.""" for zone_id in changed_zones_ids: if zone_id not in self.roonapi.zones: # device was removed ? continue zone = self.roonapi.zones[zone_id] for device in zone["outputs"]: dev_name = device["display_name"] if dev_name == "Unnamed" or not dev_name: # ignore unnamed devices continue player_data = await self.async_create_player_data(zone, device) dev_id = player_data["dev_id"] player_data["is_available"] = True if dev_id in self.offline_devices: # player back online self.offline_devices.remove(dev_id) async_dispatcher_send(self.hass, "roon_media_player", player_data) self.all_player_ids.add(dev_id)
[ "async", "def", "async_update_changed_players", "(", "self", ",", "changed_zones_ids", ")", ":", "for", "zone_id", "in", "changed_zones_ids", ":", "if", "zone_id", "not", "in", "self", ".", "roonapi", ".", "zones", ":", "# device was removed ?", "continue", "zone", "=", "self", ".", "roonapi", ".", "zones", "[", "zone_id", "]", "for", "device", "in", "zone", "[", "\"outputs\"", "]", ":", "dev_name", "=", "device", "[", "\"display_name\"", "]", "if", "dev_name", "==", "\"Unnamed\"", "or", "not", "dev_name", ":", "# ignore unnamed devices", "continue", "player_data", "=", "await", "self", ".", "async_create_player_data", "(", "zone", ",", "device", ")", "dev_id", "=", "player_data", "[", "\"dev_id\"", "]", "player_data", "[", "\"is_available\"", "]", "=", "True", "if", "dev_id", "in", "self", ".", "offline_devices", ":", "# player back online", "self", ".", "offline_devices", ".", "remove", "(", "dev_id", ")", "async_dispatcher_send", "(", "self", ".", "hass", ",", "\"roon_media_player\"", ",", "player_data", ")", "self", ".", "all_player_ids", ".", "add", "(", "dev_id", ")" ]
[ 97, 4 ]
[ 116, 47 ]
python
en
['en', 'en', 'en']
True
RoonServer.async_update_players
(self)
Periodic full scan of all devices.
Periodic full scan of all devices.
async def async_update_players(self): """Periodic full scan of all devices.""" zone_ids = self.roonapi.zones.keys() await self.async_update_changed_players(zone_ids) # check for any removed devices all_devs = {} for zone in self.roonapi.zones.values(): for device in zone["outputs"]: player_data = await self.async_create_player_data(zone, device) dev_id = player_data["dev_id"] all_devs[dev_id] = player_data for dev_id in self.all_player_ids: if dev_id in all_devs: continue # player was removed! player_data = {"dev_id": dev_id} player_data["is_available"] = False async_dispatcher_send(self.hass, "roon_media_player", player_data) self.offline_devices.add(dev_id)
[ "async", "def", "async_update_players", "(", "self", ")", ":", "zone_ids", "=", "self", ".", "roonapi", ".", "zones", ".", "keys", "(", ")", "await", "self", ".", "async_update_changed_players", "(", "zone_ids", ")", "# check for any removed devices", "all_devs", "=", "{", "}", "for", "zone", "in", "self", ".", "roonapi", ".", "zones", ".", "values", "(", ")", ":", "for", "device", "in", "zone", "[", "\"outputs\"", "]", ":", "player_data", "=", "await", "self", ".", "async_create_player_data", "(", "zone", ",", "device", ")", "dev_id", "=", "player_data", "[", "\"dev_id\"", "]", "all_devs", "[", "dev_id", "]", "=", "player_data", "for", "dev_id", "in", "self", ".", "all_player_ids", ":", "if", "dev_id", "in", "all_devs", ":", "continue", "# player was removed!", "player_data", "=", "{", "\"dev_id\"", ":", "dev_id", "}", "player_data", "[", "\"is_available\"", "]", "=", "False", "async_dispatcher_send", "(", "self", ".", "hass", ",", "\"roon_media_player\"", ",", "player_data", ")", "self", ".", "offline_devices", ".", "add", "(", "dev_id", ")" ]
[ 118, 4 ]
[ 136, 44 ]
python
en
['en', 'en', 'en']
True
RoonServer.async_update_playlists
(self)
Store lists in memory with all playlists - could be used by a custom lovelace card.
Store lists in memory with all playlists - could be used by a custom lovelace card.
async def async_update_playlists(self): """Store lists in memory with all playlists - could be used by a custom lovelace card.""" all_playlists = [] roon_playlists = self.roonapi.playlists() if roon_playlists and "items" in roon_playlists: all_playlists += [item["title"] for item in roon_playlists["items"]] roon_playlists = self.roonapi.internet_radio() if roon_playlists and "items" in roon_playlists: all_playlists += [item["title"] for item in roon_playlists["items"]] self.all_playlists = all_playlists
[ "async", "def", "async_update_playlists", "(", "self", ")", ":", "all_playlists", "=", "[", "]", "roon_playlists", "=", "self", ".", "roonapi", ".", "playlists", "(", ")", "if", "roon_playlists", "and", "\"items\"", "in", "roon_playlists", ":", "all_playlists", "+=", "[", "item", "[", "\"title\"", "]", "for", "item", "in", "roon_playlists", "[", "\"items\"", "]", "]", "roon_playlists", "=", "self", ".", "roonapi", ".", "internet_radio", "(", ")", "if", "roon_playlists", "and", "\"items\"", "in", "roon_playlists", ":", "all_playlists", "+=", "[", "item", "[", "\"title\"", "]", "for", "item", "in", "roon_playlists", "[", "\"items\"", "]", "]", "self", ".", "all_playlists", "=", "all_playlists" ]
[ 138, 4 ]
[ 147, 42 ]
python
en
['en', 'en', 'en']
True
RoonServer.async_create_player_data
(self, zone, output)
Create player object dict by combining zone with output.
Create player object dict by combining zone with output.
async def async_create_player_data(self, zone, output): """Create player object dict by combining zone with output.""" new_dict = zone.copy() new_dict.update(output) new_dict.pop("outputs") new_dict["host"] = self.host new_dict["is_synced"] = len(zone["outputs"]) > 1 new_dict["zone_name"] = zone["display_name"] new_dict["display_name"] = output["display_name"] new_dict["last_changed"] = utcnow() # we don't use the zone_id or output_id for now as unique id as I've seen cases were it changes for some reason new_dict["dev_id"] = f"roon_{self.host}_{output['display_name']}" return new_dict
[ "async", "def", "async_create_player_data", "(", "self", ",", "zone", ",", "output", ")", ":", "new_dict", "=", "zone", ".", "copy", "(", ")", "new_dict", ".", "update", "(", "output", ")", "new_dict", ".", "pop", "(", "\"outputs\"", ")", "new_dict", "[", "\"host\"", "]", "=", "self", ".", "host", "new_dict", "[", "\"is_synced\"", "]", "=", "len", "(", "zone", "[", "\"outputs\"", "]", ")", ">", "1", "new_dict", "[", "\"zone_name\"", "]", "=", "zone", "[", "\"display_name\"", "]", "new_dict", "[", "\"display_name\"", "]", "=", "output", "[", "\"display_name\"", "]", "new_dict", "[", "\"last_changed\"", "]", "=", "utcnow", "(", ")", "# we don't use the zone_id or output_id for now as unique id as I've seen cases were it changes for some reason", "new_dict", "[", "\"dev_id\"", "]", "=", "f\"roon_{self.host}_{output['display_name']}\"", "return", "new_dict" ]
[ 149, 4 ]
[ 161, 23 ]
python
en
['en', 'en', 'en']
True
_generate_mock_feed_entry
( external_id, title, alert_level, distance_to_home, coordinates, attribution=None, activity=None, hazards=None, )
Construct a mock feed entry for testing purposes.
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id, title, alert_level, distance_to_home, coordinates, attribution=None, activity=None, hazards=None, ): """Construct a mock feed entry for testing purposes.""" feed_entry = MagicMock() feed_entry.external_id = external_id feed_entry.title = title feed_entry.alert_level = alert_level feed_entry.distance_to_home = distance_to_home feed_entry.coordinates = coordinates feed_entry.attribution = attribution feed_entry.activity = activity feed_entry.hazards = hazards return feed_entry
[ "def", "_generate_mock_feed_entry", "(", "external_id", ",", "title", ",", "alert_level", ",", "distance_to_home", ",", "coordinates", ",", "attribution", "=", "None", ",", "activity", "=", "None", ",", "hazards", "=", "None", ",", ")", ":", "feed_entry", "=", "MagicMock", "(", ")", "feed_entry", ".", "external_id", "=", "external_id", "feed_entry", ".", "title", "=", "title", "feed_entry", ".", "alert_level", "=", "alert_level", "feed_entry", ".", "distance_to_home", "=", "distance_to_home", "feed_entry", ".", "coordinates", "=", "coordinates", "feed_entry", ".", "attribution", "=", "attribution", "feed_entry", ".", "activity", "=", "activity", "feed_entry", ".", "hazards", "=", "hazards", "return", "feed_entry" ]
[ 4, 0 ]
[ 24, 21 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the ProgettiHWSW Automation component.
Set up the ProgettiHWSW Automation component.
async def async_setup(hass, config): """Set up the ProgettiHWSW Automation component.""" hass.data[DOMAIN] = {} return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "}", "return", "True" ]
[ 15, 0 ]
[ 19, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass: HomeAssistant, entry: ConfigEntry)
Set up ProgettiHWSW Automation from a config entry.
Set up ProgettiHWSW Automation from a config entry.
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up ProgettiHWSW Automation from a config entry.""" hass.data[DOMAIN][entry.entry_id] = ProgettiHWSWAPI( f'{entry.data["host"]}:{entry.data["port"]}' ) # Check board validation again to load new values to API. await hass.data[DOMAIN][entry.entry_id].check_board() for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "=", "ProgettiHWSWAPI", "(", "f'{entry.data[\"host\"]}:{entry.data[\"port\"]}'", ")", "# Check board validation again to load new values to API.", "await", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", ".", "check_board", "(", ")", "for", "component", "in", "PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "component", ")", ")", "return", "True" ]
[ 22, 0 ]
[ 37, 15 ]
python
en
['en', 'en', 'en']
True