Download vb/audio2tool.py from LeyanW/VoiceAuthWorld-Ebase: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/datasets/LeyanW/VoiceAuthWorld-Ebase/resolve/main/vb/audio2tool.py
- Command line
-
hf download hf://datasets/LeyanW/VoiceAuthWorld-Ebase/vb/audio2tool.py
-
curl -L -o audio2tool.py https://huggingface.co/datasets/LeyanW/VoiceAuthWorld-Ebase/resolve/main/vb/audio2tool.py
12.8 kB
| """Executable, offline household for a subset of the Audio2Tool smart_home catalog.""" | |
| import csv | |
| from copy import deepcopy | |
| from pathlib import Path | |
| import re | |
| from .fixtures import call, device | |
| from .tools import ToolError, ToolSpec, array, integer, string, validate | |
| from .world import World, state_diff | |
| ROOMS = {"living": "living room", "master": "main bedroom", "guest": "guest room", "entry": "entry", "dining": "dining room"} | |
| def initial(): | |
| devices = {} | |
| for room, label in ROOMS.items(): | |
| devices[room + "_light"] = device("light", room, label + " ceiling light", 24, power=room in ("living", "dining"), | |
| brightness=70, color_temperature=4000, adaptive=False) | |
| for room in ("living", "master"): | |
| label = ROOMS[room] | |
| devices[room + "_hvac"] = device("hvac", room, label + " thermostat", 900, mode="Cool", temperature=26, ambient=27, offset=0) | |
| devices[room + "_sensor"] = device("sensor", room, label + " air sensor", 1, pm25=65 if room == "living" else 18, | |
| aqi=90 if room == "living" else 32, co2=650, voc=120, humidity=55) | |
| devices.update({ | |
| "dining_plug": device("plug", "dining", "dining room kettle outlet", 800, power=True), | |
| "guest_plug": device("plug", "guest", "guest room desk outlet", 65, power=False), | |
| "entry_lock": device("lock", "entry", "entry door lock", 0, locked=True, door_closed=True), | |
| "living_tv": device("media", "living", "living room TV", 120, power=False, volume=35, input="TV", playback="Stop", track="", source="Local", muted=False), | |
| "living_speaker": device("media", "living", "living room speaker", 15, power=True, volume=25, playback="Pause", track="Quiet morning", source="Local", muted=False), | |
| "living_robot": device("cleaner", "living", "robot vacuum", 35, status="docked", battery=80, target_rooms=[]), | |
| "living_purifier": device("purifier", "living", "living room air purifier", 40, power=False, mode="Auto", speed=3, filter_life=72), | |
| "master_humidifier": device("humidifier", "master", "main bedroom humidifier", 20, power=False, target_humidity=50), | |
| "dining_valve": device("valve", "dining", "dining room water valve", 0, position="Closed"), | |
| }) | |
| return devices | |
| def scene_actions(): | |
| def light(did, level): | |
| return call("setBrightness", deviceId=did, level=level) | |
| def switch(did, state): | |
| return call("setLightState", deviceId=did, state=state) | |
| return { | |
| "Good_Morning": [switch("master_light", "On"), light("master_light", 70)], | |
| "Good_Night": [switch("living_light", "Off"), call("setLockState_home", deviceId="entry_lock", state="Locked")], | |
| "Movie_Time": [light("living_light", 30), call("setPowerState", deviceId="living_tv", state="On"), call("setVolume", deviceId="living_tv", level=20)], | |
| "Party": [switch("dining_light", "On"), light("dining_light", 90), call("setVolume", deviceId="living_speaker", level=40)], | |
| "Away": [switch("living_light", "Off"), call("setThermostatMode", deviceId="living_hvac", mode="Off"), call("setLockState_home", deviceId="entry_lock", state="Locked")], | |
| } | |
| # Each row binds an upstream signature to compatible devices, arguments and state fields. | |
| # None for read fields means every public attribute of that device. | |
| READS = { | |
| "getLightState": ("light", None), "getThermostatState": ("hvac", None), | |
| "getLockState": ("lock", None), "getSensorState": ("sensor", None), | |
| "getAirQuality": ("sensor", ("pm25", "aqi", "co2")), | |
| "getAirQuality_diag": ("sensor", ("voc", "co2", "humidity")), | |
| "getFilterLife": ("purifier", ("filter_life",)), "getBatteryLevel": ("cleaner", ("battery",)), | |
| "getApplianceState": ("plug media purifier humidifier cleaner", None), | |
| "getApplianceStatus": ("cleaner", ("status",)), "getEnergyUsage": ("*", None), "getDeviceList": ("", ()), | |
| } | |
| ONOFF = string(["On", "Off"]) | |
| WRITES = { | |
| "setLightState": ("light", {"state": ONOFF}, {"power": "state"}), | |
| "setBrightness": ("light", {"level": integer(0, 100)}, {"brightness": "level"}), | |
| "setColorTemperature": ("light", {"kelvin": integer(2000, 6500)}, {"color_temperature": "kelvin"}), | |
| "setAdaptiveLighting": ("light", {"enabled": {"type": "boolean"}}, {"adaptive": "enabled"}), | |
| "setThermostatMode": ("hvac", {"mode": string(["Heat", "Cool", "Auto", "Off", "Fan_Only", "Eco"])}, {"mode": "mode"}), | |
| "setTargetTemperature": ("hvac", {"temperature": dict(type="number", minimum=10, maximum=32)}, {"temperature": "temperature"}), | |
| "calibrateThermostat": ("hvac", {"offset": dict(type="number", minimum=-5, maximum=5)}, {"offset": "offset"}), | |
| "setFanMode": ("purifier", {"mode": string(["Auto", "On", "Off"]), "speed": integer(1,10)}, {"mode": "mode", "speed": "speed"}), | |
| "setHumidifierState": ("humidifier", {"targetHumidity": integer(30,80)}, {"target_humidity": "targetHumidity"}), | |
| "setLockState_home": ("lock", {"state": string(["Locked","Unlocked"])}, {"locked": "state"}), | |
| "setVolume": ("media", {"level": integer(0,100)}, {"volume":"level"}), | |
| "setInputSource": ("media", {"input": string(["HDMI_1","HDMI_2","HDMI_3","HDMI_ARC","TV","AV"])}, {"input":"input"}), | |
| "setPowerState": ("plug media purifier humidifier", {"state": ONOFF}, {"power":"state"}), | |
| "startCleaning": ("cleaner", {"zones":array(string(["Living_Room","Kitchen","Bedroom","Hallway"]))}, {}), | |
| "setDockState": ("cleaner", {}, {}), "resetFilterStatus": ("purifier", {}, {}), | |
| "setWaterValve": ("valve", {"state":string(["Open","Closed"])}, {"position":"state"}), | |
| "activateScene": ("", {"sceneId":string(scene_actions())}, {}), | |
| "playMedia": ("media", {"query": string(), "source": string(["Spotify","AppleMusic","YouTube","AmazonMusic","Local"])}, {}), | |
| "controlPlayback_home": ("media", {"action":string(["Play","Pause","Stop","Next","Previous","Mute","Unmute"])}, {}), | |
| } | |
| class Registry: | |
| def __init__(self, devices): | |
| self.specs = {} | |
| with Path(__file__).with_name("audio2tool_registry.csv").open() as f: | |
| for row in csv.DictReader(f): | |
| name = row["tool_name"] | |
| if name in READS: | |
| kinds, _ = READS[name] | |
| args = {} | |
| else: | |
| kinds, args, _ = WRITES[name] | |
| props = {} | |
| if kinds: | |
| ids = [k for k, d in devices.items() if kinds == "*" or d["kind"] in kinds.split()] | |
| if name == "setInputSource": | |
| ids = ["living_tv"] | |
| props["deviceId"] = string(ids) | |
| props.update(args) | |
| signature = re.findall(r"(\w+): ([\w<>]+)(\??)", row["signature"]) | |
| if [arg for arg, _, _ in signature] != list(props): | |
| raise ValueError(f"{name}: local binding differs from upstream signature") | |
| params = dict(type="object", properties=props, | |
| required=[arg for arg, _, optional in signature if not optional], | |
| additionalProperties=False) | |
| self.specs[name] = ToolSpec(name, row["description"], params, "read" if name in READS else "write") | |
| if self.specs.keys() != READS.keys() | WRITES.keys(): | |
| raise ValueError("Audio2Tool catalog and executable bindings disagree") | |
| def check(self, name, args, devices): | |
| if name not in self.specs: | |
| raise ToolError(f"unknown tool: {name}") | |
| spec = self.specs[name] | |
| validate(args, spec.parameters) | |
| return spec | |
| def public(self): | |
| return [s.public() for s in self.specs.values()] | |
| def footprint(self, name, args, devices, scenes): | |
| self.check(name, args, devices) | |
| if name in READS: | |
| if name == "getDeviceList": | |
| return set() | |
| did = args["deviceId"] | |
| fields = READS[name][1] or devices[did]["state"].keys() | |
| return {f"{did}.{field}" for field in fields} | |
| return self.attempted_writes(name, args, devices, scenes) | |
| def attempted_writes(self, name, args, devices, scenes): | |
| if name not in WRITES or not isinstance(args, dict): | |
| return set() | |
| if name == "activateScene": | |
| scene = args.get("sceneId") | |
| if not isinstance(scene, str): | |
| return set() | |
| return set().union(*(self.attempted_writes(c["name"], c["arguments"], devices, scenes) for c in scenes.get(scene, {}).get("actions", []))) | |
| did = args.get("deviceId") | |
| if not isinstance(did, str) or did not in devices: | |
| return set() | |
| fields = [key for key, param in WRITES[name][2].items() if param in args] | |
| if name in ("startCleaning","setDockState"): | |
| fields = ["status","target_rooms"] | |
| elif name == "resetFilterStatus": | |
| fields = ["filter_life"] | |
| elif name == "playMedia": | |
| fields = ["track","source","playback"] | |
| elif name == "controlPlayback_home": | |
| act = args.get("action") | |
| fields = ["muted"] if act in ("Mute","Unmute") else ["track"] if act in ("Next","Previous") else ["playback"] | |
| return {f"{did}.{k}" for k in fields} | |
| class Home(World): | |
| version = "audio2tool-home/1" | |
| def __init__(self, patch=None): | |
| self._initial = initial() | |
| for path, val in (patch or {}).items(): | |
| did, field = path.split(".") | |
| self._initial[did]["state"][field] = val | |
| self.registry = Registry(self._initial) | |
| self.scenes = {k: {"actions": v} for k, v in scene_actions().items()} | |
| self.reset() | |
| def _apply(self, name, args, devices): | |
| self.registry.check(name, args, devices) | |
| if name == "getDeviceList": | |
| return self.catalogue(), [] | |
| if name == "activateScene": | |
| children = [] | |
| for child in self.scenes[args["sceneId"]]["actions"]: | |
| before = deepcopy(devices) | |
| paths = self.registry.footprint(child["name"], child["arguments"], devices, self.scenes) | |
| data, _ = self._apply(child["name"], child["arguments"], devices) | |
| children.append(dict(call=child, data=data, effects=state_diff(before, devices), write_paths=sorted(paths))) | |
| return {"sceneId": args["sceneId"]}, children | |
| did = args["deviceId"] | |
| device_info = devices[did] | |
| state = device_info["state"] | |
| if name == "getEnergyUsage": | |
| watts = self._watts(device_info) | |
| if device_info["kind"] == "hvac": | |
| watts = device_info["rated_watts"] if state["mode"] != "Off" else 0 | |
| return {"simulated_watts": watts}, [] | |
| if name in READS: | |
| fields = READS[name][1] or state.keys() | |
| return {k:deepcopy(state[k]) for k in fields}, [] | |
| if name in ("startCleaning", "setDockState"): | |
| if name == "startCleaning": | |
| if state["status"] == "cleaning" or state["battery"] < 20: | |
| raise ToolError("vacuum is busy or has insufficient charge") | |
| state.update(status="cleaning", target_rooms=args.get("zones", ["Living_Room", "Kitchen", "Bedroom", "Hallway"])) | |
| else: | |
| state.update(status="docked", target_rooms=[]) | |
| elif name == "resetFilterStatus": | |
| state["filter_life"] = 100 | |
| elif name in ("playMedia", "controlPlayback_home"): | |
| if not state["power"]: | |
| raise ToolError("switch on this media device first") | |
| if name == "playMedia": | |
| state.update(track=args["query"], source=args.get("source","Local"), playback="Play") | |
| else: | |
| act = args["action"] | |
| if act in ("Mute","Unmute"): | |
| state["muted"] = act == "Mute" | |
| elif act in ("Next","Previous"): | |
| tracks = ["Quiet morning", "Blue sky", "Evening walk"] | |
| pos = tracks.index(state["track"]) if state["track"] in tracks else 0 | |
| state["track"] = tracks[(pos + (1 if act == "Next" else -1)) % len(tracks)] | |
| else: | |
| state["playback"] = act | |
| else: | |
| for key, param in WRITES[name][2].items(): | |
| if param not in args: | |
| continue | |
| val = args[param] | |
| if key == "power": | |
| val = val == "On" | |
| if key == "locked": | |
| val = val == "Locked" | |
| if val and not state["door_closed"]: | |
| raise ToolError("cannot lock an open door") | |
| state[key] = val | |
| return {"deviceId": did, "state": deepcopy(state)}, [] | |