Skip to content

Commit

Permalink
Remove plot mic from process map when user stops
Browse files Browse the repository at this point in the history
Create a mapping for keywords in lights_squire.py
Improve accuracy in getting light location
Upgrade dependent modules
  • Loading branch information
dormant-user committed Oct 2, 2023
1 parent 7a3f32c commit a70c434
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 30 deletions.
19 changes: 11 additions & 8 deletions jarvis/executors/lights.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,11 @@ def lights(phrase: str) -> None:
input_=util.matrix_to_flat_list(input_=[v for k, v in lights_map.items()])
)
else:
light_location = util.get_closest_match(text=phrase, match_list=list(lights_map.keys()))
remove = util.matrix_to_flat_list(input_=squire.word_map.values()) + ['lights', 'light']
phrase_location = phrase
for word in remove:
phrase_location = phrase_location.replace(word, '')
light_location = util.get_closest_match(text=phrase_location.strip(), match_list=list(lights_map.keys()))
logger.info("Lights location: %s", light_location)
host_names: List[str] = lights_map[light_location]
host_names = util.remove_none(input_=host_names)
Expand Down Expand Up @@ -151,7 +155,7 @@ def lights(phrase: str) -> None:
executor = ThreadExecutor(host_ip=host_ip, mapping=lights_map)

plural = 'lights' if len(host_ip) > 1 else 'light'
if 'turn on' in phrase or 'cool' in phrase or 'white' in phrase:
if word_match.word_match(phrase, squire.word_map['turn_on']):
tone = 'white' if 'white' in phrase else 'cool'
if 'turn on' in phrase:
speaker.speak(text=f'{random.choice(conversation.acknowledgement)}! Turning on {len(host_ip)} {plural}')
Expand All @@ -160,21 +164,21 @@ def lights(phrase: str) -> None:
text=f'{random.choice(conversation.acknowledgement)}! Setting {len(host_ip)} {plural} to {tone}!'
)
executor.avail_check(function_to_call=squire.cool)
elif 'turn off' in phrase:
elif word_match.word_match(phrase, squire.word_map['turn_off']):
speaker.speak(text=f'{random.choice(conversation.acknowledgement)}! Turning off {len(host_ip)} {plural}')
if state := squire.check_status():
support.stop_process(pid=int(state[0]))
if 'just' in phrase or 'simply' in phrase:
if word_match.word_match(phrase, squire.word_map['simple']):
executor.avail_check(function_to_call=squire.turn_off)
else:
Thread(target=executor.thread_worker, args=[squire.cool]).run()
executor.avail_check(function_to_call=squire.turn_off)
elif 'party mode' in phrase:
elif word_match.word_match(phrase, squire.word_map['party_mode']):
if squire.party_mode(host=host_ip, phrase=phrase):
Thread(target=executor.thread_worker, args=[squire.cool]).run()
time.sleep(1)
Thread(target=executor.thread_worker, args=[squire.turn_off]).start()
elif 'warm' in phrase or 'yellow' in phrase:
elif word_match.word_match(phrase, squire.word_map['warm']):
if 'yellow' in phrase:
speaker.speak(text=f'{random.choice(conversation.acknowledgement)}! '
f'Setting {len(host_ip)} {plural} to yellow!')
Expand All @@ -188,8 +192,7 @@ def lights(phrase: str) -> None:
squire.preset(host=light_ip, speed=50,
color=[preset_values.PRESET_VALUES[_type] for _type in
list(preset_values.PRESET_VALUES.keys()) if _type in phrase][0])
elif 'set' in phrase or 'percentage' in phrase or '%' in phrase or 'dim' in phrase \
or 'bright' in phrase:
elif word_match.word_match(phrase, squire.word_map['set']):
if 'bright' in phrase:
level = 100
elif 'dim' in phrase:
Expand Down
8 changes: 8 additions & 0 deletions jarvis/executors/lights_squire.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@
from jarvis.modules.utils import support

db = database.Database(database=models.fileio.base_db)
word_map = {
'turn_on': ['turn on', 'cool', 'white'],
'turn_off': ['turn off'],
'party_mode': ['party mode'],
'simple': ['just', 'simply'],
'warm': ['warm', 'yellow'],
'set': ['set', 'percentage', 'percent', '%', 'dim', 'bright']
}


def turn_off(host: IPv4Address) -> None:
Expand Down
26 changes: 13 additions & 13 deletions jarvis/lib/version_locked_requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,43 @@ wave==0.0.2
wikipedia==1.4.0
newsapi-python==0.2.7
pyrh==2.0 # Do not upgrade, as the new version doesn't have the option for QR
pytz==2023.3
pytz==2023.3.post1
timezonefinder==6.2.0
pyicloud==1.0.0
geopy==2.3.0
geopy==2.4.0
PyYAML==6.0.1
axju-jokes==1.0.3
inflect==7.0.0
pywebostv==0.8.9
speedtest-cli==2.1.3
holidays==0.30
holidays==0.33
randfacts==0.20.2
openai==0.27.8
fastapi==0.103.1
openai==0.28.1
fastapi==0.103.2
uvicorn==0.23.2
aiofiles==23.2.1
python-multipart==0.0.6
pydantic==2.3.0
pydantic==2.4.2
pydantic-settings==2.0.3
icalendar==5.0.7
icalendar==5.0.10
Jinja2==3.1.2
certifi==2023.7.22
googlehomepush==0.1.0
PyChromecast==2.3.0 # Do not upgrade, as googlehomepush module relies on this version
psutil==5.9.5
pytest==7.4.0
pytest==7.4.2
bs4==0.0.1
Pillow==10.0.0
packaging==23.1
numpy==1.25.2
Pillow==10.0.1
packaging==23.2
numpy==1.26.0
SoundFile==0.12.1
deepdiff==6.3.1
deepdiff==6.5.0
pymyq==3.1.6
docker==6.1.3
websockets==11.0.3
PyJWT==2.8.0
webull==0.6.1
matplotlib==3.7.2
matplotlib==3.8.0
lxml==4.9.3
aiohttp==3.8.5
python-dateutil==2.8.2
Expand Down
20 changes: 11 additions & 9 deletions jarvis/modules/microphone/graph_mic.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
from struct import Struct
from typing import List, Optional, Tuple, Union, cast

import matplotlib.pyplot
import numpy
import matplotlib.pyplot as plt
import numpy as np
import sounddevice
import yaml
from matplotlib.animation import FuncAnimation
Expand Down Expand Up @@ -47,7 +47,7 @@ class Settings:
# System config
mapping: Optional[List[int]]
lines: Optional[List[Line2D]]
plot_data: Optional[numpy.ndarray]
plot_data: Optional[np.ndarray]


settings = Settings()
Expand All @@ -59,7 +59,7 @@ def list_devices() -> sounddevice.DeviceList:


# noinspection PyUnusedLocal
def audio_callback(indata: numpy.ndarray, frames: int, time: Struct, status: sounddevice.CallbackFlags) -> None:
def audio_callback(indata: np.ndarray, frames: int, time: Struct, status: sounddevice.CallbackFlags) -> None:
"""This is called (from a separate thread) for each audio block."""
if status:
logger.info(status)
Expand All @@ -81,7 +81,7 @@ def update_plot(frame: int) -> List[Line2D]:
except queue.Empty:
break
shift = len(data)
settings.plot_data = numpy.roll(settings.plot_data, -shift, axis=0)
settings.plot_data = np.roll(settings.plot_data, -shift, axis=0)
settings.plot_data[-shift:, :] = data
for column, line in enumerate(settings.lines):
line.set_ydata(settings.plot_data[:, column])
Expand Down Expand Up @@ -157,10 +157,10 @@ def _kick_off() -> None:
settings.samplerate = device_info['default_samplerate']

length = int(settings.window * settings.samplerate / (settings.rate * settings.down_sample))
settings.plot_data = numpy.zeros((length, len(settings.channels)))
settings.plot_data = np.zeros((length, len(settings.channels)))

# Add type hint when unpacking a tuple (lazy way to avoid variables)
fig, ax = cast(Tuple[Figure, Subplot], matplotlib.pyplot.subplots())
fig, ax = cast(Tuple[Figure, Subplot], plt.subplots())
fig.set_size_inches(settings.window_size)
settings.lines = ax.plot(settings.plot_data)
if len(settings.channels) > 1:
Expand All @@ -175,7 +175,7 @@ def _kick_off() -> None:
# ax.set_xlabel('Time')
# ax.set_ylabel('Frequency')
fig.tight_layout(pad=0) # no padding
matplotlib.pyplot.legend(["Microphone Amplitude"])
plt.legend(["Microphone Amplitude"])
fig.canvas.manager.set_window_title("Realtime Spectrum Display")
if settings.dark_mode:
ax.set_facecolor('xkcd:almost black') # https://xkcd.com/color/rgb/
Expand All @@ -188,7 +188,8 @@ def _kick_off() -> None:
)
ani = FuncAnimation(fig=fig, func=update_plot, interval=settings.interval, blit=True, cache_frame_data=False) # noqa
with stream:
matplotlib.pyplot.show()
plt.show()
process_map.remove(plot_mic.__name__)


if __name__ == '__main__':
Expand All @@ -198,6 +199,7 @@ def _kick_off() -> None:
from multiprocessing import current_process

current_process().name = "PlotMic"
from jarvis.executors import process_map
from jarvis.modules.database import database
from jarvis.modules.logger import logger, multiprocessing_logger
from jarvis.modules.models import models
Expand Down

0 comments on commit a70c434

Please sign in to comment.