Merge pull request #2898 from MycroftAI/bugfix/docstring-cleanup

Cleanup of documentation
pull/2913/head
Kris Gesling 2021-06-01 12:16:44 +09:30 committed by GitHub
commit 1cc25da144
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 474 additions and 446 deletions

View File

@ -1,4 +1,5 @@
.. Mycroft documentation master file .. Mycroft documentation master file
Mycroft-core technical documentation Mycroft-core technical documentation
==================================== ====================================

View File

@ -1,6 +1,8 @@
mycroft.audio package mycroft.audio
==================== ====================
wait_while_speaking .. automodule:: mycroft.audio
------------------- :members:
.. autofunction:: mycroft.audio.wait_while_speaking is_speaking,
stop_speaking,
wait_while_speaking

View File

@ -5,25 +5,25 @@ mycroft.skills
============== ==============
MycroftSkill class - Base class for all Mycroft skills MycroftSkill class - Base class for all Mycroft skills
------------------ ------------------------------------------------------
.. autoclass:: mycroft.MycroftSkill .. autoclass:: mycroft.MycroftSkill
:members: :members:
CommonIoTSkill class CommonIoTSkill class
------------------- --------------------
.. autoclass:: mycroft.skills.common_iot_skill.CommonIoTSkill .. autoclass:: mycroft.skills.common_iot_skill.CommonIoTSkill
:show-inheritance: :show-inheritance:
:members: :members:
CommonPlaySkill class CommonPlaySkill class
------------------- ---------------------
.. autoclass:: mycroft.skills.common_play_skill.CommonPlaySkill .. autoclass:: mycroft.skills.common_play_skill.CommonPlaySkill
:show-inheritance: :show-inheritance:
:members: :members:
CommonQuerySkill class CommonQuerySkill class
------------------- ----------------------
.. autoclass:: mycroft.skills.common_query_skill.CommonQuerySkill .. autoclass:: mycroft.skills.common_query_skill.CommonQuerySkill
:show-inheritance: :show-inheritance:
:members: :members:
@ -56,6 +56,12 @@ removes_context decorator
------------------------- -------------------------
.. autofunction:: mycroft.removes_context .. autofunction:: mycroft.removes_context
mycroft.audio
==================
.. toctree::
mycroft.audio
mycroft.filesystem mycroft.filesystem
================== ==================
@ -73,16 +79,15 @@ mycroft.util
.. toctree:: .. toctree::
mycroft.util.parse mycroft.util.parse
Parsing functions for extracting data from natural speech. Parsing functions for extracting data from natural speech.
.. toctree:: .. toctree::
mycroft.util.format mycroft.util.format
Formatting functions for producing natural speech from common datatypes such as numbers, dates and times. Formatting functions for producing natural speech from common datatypes such as numbers, dates and times.
.. toctree:: .. toctree::
mycroft.util.time mycroft.util.time
A collection of functions for handling local, system and global times.
----------------- A collection of functions for handling local, system and global times.
.. automodule::
mycroft.util.time

View File

@ -1,5 +1,5 @@
mycroft.util.format mycroft.util.format
================== ===================
.. automodule:: mycroft.util.format .. automodule:: mycroft.util.format
:members: :members:

View File

@ -25,22 +25,6 @@ play_ogg
--------- ---------
.. autofunction:: mycroft.util.play_ogg .. autofunction:: mycroft.util.play_ogg
extract_datetime
----------------
.. autofunction:: mycroft.util.extract_datetime
extract_number
-------------
.. autofunction:: mycroft.util.extract_number
normalize
---------
.. autofunction:: mycroft.util.normalize
nice_number
-----------
.. autofunction:: mycroft.util.nice_number
resolve_resource_file resolve_resource_file
--------------------- ---------------------
.. autofunction:: mycroft.util.resolve_resource_file .. autofunction:: mycroft.util.resolve_resource_file

View File

@ -113,7 +113,7 @@ class Api:
The method handles Etags and will return a cached response value The method handles Etags and will return a cached response value
if nothing has changed on the remote. if nothing has changed on the remote.
Arguments: Args:
params (dict): request parameters params (dict): request parameters
no_refresh (bool): optional parameter to disable refreshs of token no_refresh (bool): optional parameter to disable refreshs of token
@ -156,9 +156,10 @@ class Api:
Will try to refresh the access token if it's expired. Will try to refresh the access token if it's expired.
Arguments: Args:
response (requests Response object): Response to parse response (requests Response object): Response to parse
no_refresh (bool): Disable refreshing of the token no_refresh (bool): Disable refreshing of the token
Returns: Returns:
data fetched from server data fetched from server
""" """
@ -373,7 +374,7 @@ class DeviceApi(Api):
def upload_skill_metadata(self, settings_meta): def upload_skill_metadata(self, settings_meta):
"""Upload skill metadata. """Upload skill metadata.
Arguments: Args:
settings_meta (dict): skill info and settings in JSON format settings_meta (dict): skill info and settings in JSON format
""" """
return self.request({ return self.request({
@ -386,7 +387,7 @@ class DeviceApi(Api):
""" Upload skills.json file. This file contains a manifest of installed """ Upload skills.json file. This file contains a manifest of installed
and failed installations for use with the Marketplace. and failed installations for use with the Marketplace.
Arguments: Args:
data: dictionary with skills data from msm data: dictionary with skills data from msm
""" """
if not isinstance(data, dict): if not isinstance(data, dict):
@ -512,7 +513,7 @@ def is_paired(ignore_errors=True):
def check_remote_pairing(ignore_errors): def check_remote_pairing(ignore_errors):
"""Check that a basic backend endpoint accepts our pairing. """Check that a basic backend endpoint accepts our pairing.
Arguments: Args:
ignore_errors (bool): True if errors should be ignored when ignore_errors (bool): True if errors should be ignored when
Returns: Returns:

View File

@ -91,10 +91,11 @@ def get_services(services_folder):
def setup_service(service_module, config, bus): def setup_service(service_module, config, bus):
"""Run the appropriate setup function and return created service objects. """Run the appropriate setup function and return created service objects.
Arguments: Args:
service_module: Python module to run service_module: Python module to run
config (dict): Mycroft configuration dict config (dict): Mycroft configuration dict
bus (MessageBusClient): Messagebus interface bus (MessageBusClient): Messagebus interface
Returns: Returns:
(list) List of created services. (list) List of created services.
""" """
@ -116,11 +117,12 @@ def setup_service(service_module, config, bus):
def load_internal_services(config, bus, path=None): def load_internal_services(config, bus, path=None):
"""Load audio services included in Mycroft-core. """Load audio services included in Mycroft-core.
Arguments: Args:
config: configuration dict for the audio backends. config: configuration dict for the audio backends.
bus: Mycroft messagebus bus: Mycroft messagebus
path: (default None) optional path for builtin audio service path: (default None) optional path for builtin audio service
implementations implementations
Returns: Returns:
List of started services List of started services
""" """
@ -150,7 +152,7 @@ def load_internal_services(config, bus, path=None):
def load_plugins(config, bus): def load_plugins(config, bus):
"""Load installed audioservice plugins. """Load installed audioservice plugins.
Arguments: Args:
config: configuration dict for the audio backends. config: configuration dict for the audio backends.
bus: Mycroft messagebus bus: Mycroft messagebus
@ -173,7 +175,7 @@ def load_services(config, bus, path=None):
parameter) for services and plugins registered with the parameter) for services and plugins registered with the
"mycroft.plugin.audioservice" entrypoint group. "mycroft.plugin.audioservice" entrypoint group.
Arguments: Args:
config: configuration dict for the audio backends. config: configuration dict for the audio backends.
bus: Mycroft messagebus bus: Mycroft messagebus
path: (default None) optional path for builtin audio service path: (default None) optional path for builtin audio service
@ -261,7 +263,7 @@ class AudioService:
def wait_for_load(self, timeout=3 * MINUTES): def wait_for_load(self, timeout=3 * MINUTES):
"""Wait for services to be loaded. """Wait for services to be loaded.
Arguments: Args:
timeout (float): Seconds to wait (default 3 minutes) timeout (float): Seconds to wait (default 3 minutes)
Returns: Returns:
(bool) True if loading completed within timeout, else False. (bool) True if loading completed within timeout, else False.

View File

@ -23,7 +23,7 @@ from abc import ABCMeta, abstractmethod
class AudioBackend(metaclass=ABCMeta): class AudioBackend(metaclass=ABCMeta):
"""Base class for all audio backend implementations. """Base class for all audio backend implementations.
Arguments: Args:
config (dict): configuration dict for the instance config (dict): configuration dict for the instance
bus (MessageBusClient): Mycroft messagebus emitter bus (MessageBusClient): Mycroft messagebus emitter
""" """
@ -50,7 +50,7 @@ class AudioBackend(metaclass=ABCMeta):
def add_list(self, tracks): def add_list(self, tracks):
"""Add tracks to backend's playlist. """Add tracks to backend's playlist.
Arguments: Args:
tracks (list): list of tracks. tracks (list): list of tracks.
""" """
@ -61,7 +61,7 @@ class AudioBackend(metaclass=ABCMeta):
Starts playing the first track in the playlist and will contiune Starts playing the first track in the playlist and will contiune
until all tracks have been played. until all tracks have been played.
Arguments: Args:
repeat (bool): Repeat playlist, defaults to False repeat (bool): Repeat playlist, defaults to False
""" """
@ -119,14 +119,14 @@ class AudioBackend(metaclass=ABCMeta):
def seek_forward(self, seconds=1): def seek_forward(self, seconds=1):
"""Skip X seconds. """Skip X seconds.
Arguments: Args:
seconds (int): number of seconds to seek, if negative rewind seconds (int): number of seconds to seek, if negative rewind
""" """
def seek_backward(self, seconds=1): def seek_backward(self, seconds=1):
"""Rewind X seconds. """Rewind X seconds.
Arguments: Args:
seconds (int): number of seconds to seek, if negative jump forward. seconds (int): number of seconds to seek, if negative jump forward.
""" """

View File

@ -108,7 +108,7 @@ def handle_speak(event):
def mute_and_speak(utterance, ident, listen=False): def mute_and_speak(utterance, ident, listen=False):
"""Mute mic and start speaking the utterance using selected tts backend. """Mute mic and start speaking the utterance using selected tts backend.
Arguments: Args:
utterance: The sentence to be spoken utterance: The sentence to be spoken
ident: Ident tying the utterance to the source query ident: Ident tying the utterance to the source query
""" """
@ -152,7 +152,7 @@ def _get_mimic_fallback():
def mimic_fallback_tts(utterance, ident, listen): def mimic_fallback_tts(utterance, ident, listen):
"""Speak utterance using fallback TTS if connection is lost. """Speak utterance using fallback TTS if connection is lost.
Arguments: Args:
utterance (str): sentence to speak utterance (str): sentence to speak
ident (str): interaction id for metrics ident (str): interaction id for metrics
listen (bool): True if interaction should end with mycroft listening listen (bool): True if interaction should end with mycroft listening
@ -177,7 +177,7 @@ def handle_stop(event):
def init(messagebus): def init(messagebus):
"""Start speech related handlers. """Start speech related handlers.
Arguments: Args:
messagebus: Connection to the Mycroft messagebus messagebus: Connection to the Mycroft messagebus
""" """

View File

@ -37,7 +37,7 @@ def on_error(e='Unknown'):
def create_enclosure(platform): def create_enclosure(platform):
"""Create an enclosure based on the provided platform string. """Create an enclosure based on the provided platform string.
Arguments: Args:
platform (str): platform name string platform (str): platform name string
Returns: Returns:

View File

@ -93,7 +93,7 @@ class EnclosureMouth:
def __display(self, code, clear_previous, x_offset, y_offset): def __display(self, code, clear_previous, x_offset, y_offset):
""" Write the encoded image to enclosure screen. """ Write the encoded image to enclosure screen.
Arguments: Args:
code (str): encoded image to display code (str): encoded image to display
clean_previous (str): if "True" will clear the screen before clean_previous (str): if "True" will clear the screen before
drawing. drawing.
@ -119,7 +119,7 @@ class EnclosureMouth:
def display(self, event=None): def display(self, event=None):
""" Display a Mark-1 specific code. """ Display a Mark-1 specific code.
Arguments: Args:
event (Message): messagebus message with data to display event (Message): messagebus message with data to display
""" """
code = "" code = ""
@ -139,7 +139,7 @@ class EnclosureMouth:
The method uses PIL to convert the image supplied into a code The method uses PIL to convert the image supplied into a code
suitable for the Mark-1 display. suitable for the Mark-1 display.
Arguments: Args:
event (Message): messagebus message with data to display event (Message): messagebus message with data to display
""" """
if not event: if not event:

View File

@ -21,7 +21,7 @@ class RollingMean:
The optimization is made for cases where value retrieval is made at a The optimization is made for cases where value retrieval is made at a
comparative rate to the sample additions. comparative rate to the sample additions.
Arguments: Args:
mean_samples: Number of samples to use for mean value mean_samples: Number of samples to use for mean value
""" """
def __init__(self, mean_samples): def __init__(self, mean_samples):
@ -66,7 +66,7 @@ class CyclicAudioBuffer:
TODO: The class is still unoptimized and performance can probably be TODO: The class is still unoptimized and performance can probably be
enhanced. enhanced.
Arguments: Args:
size (int): size in bytes size (int): size in bytes
initial_data (bytes): initial buffer data initial_data (bytes): initial buffer data
""" """
@ -78,7 +78,7 @@ class CyclicAudioBuffer:
def append(self, data): def append(self, data):
"""Add new data to the buffer, and slide out data if the buffer is full """Add new data to the buffer, and slide out data if the buffer is full
Arguments: Args:
data (bytes): binary data to append to the buffer. If buffer size data (bytes): binary data to append to the buffer. If buffer size
is exceeded the oldest data will be dropped. is exceeded the oldest data will be dropped.
""" """

View File

@ -50,7 +50,7 @@ class NoModelAvailable(Exception):
def msec_to_sec(msecs): def msec_to_sec(msecs):
"""Convert milliseconds to seconds. """Convert milliseconds to seconds.
Arguments: Args:
msecs: milliseconds msecs: milliseconds
Returns: Returns:
@ -62,7 +62,7 @@ def msec_to_sec(msecs):
class HotWordEngine: class HotWordEngine:
"""Hotword/Wakeword base class to be implemented by all wake word plugins. """Hotword/Wakeword base class to be implemented by all wake word plugins.
Arguments: Args:
key_phrase (str): string representation of the wake word key_phrase (str): string representation of the wake word
config (dict): Configuration block for the specific wake word config (dict): Configuration block for the specific wake word
lang (str): language code (BCP-47) lang (str): language code (BCP-47)
@ -89,7 +89,7 @@ class HotWordEngine:
Checks if the wake word has been found. Should reset any internal Checks if the wake word has been found. Should reset any internal
tracking of the wake word state. tracking of the wake word state.
Arguments: Args:
frame_data (binary data): Deprecated. Audio data for large chunk frame_data (binary data): Deprecated. Audio data for large chunk
of audio to be processed. This should not of audio to be processed. This should not
be used to detect audio data instead be used to detect audio data instead
@ -104,7 +104,7 @@ class HotWordEngine:
The engine should process the data and update internal trigger state. The engine should process the data and update internal trigger state.
Arguments: Args:
chunk (bytes): Chunk of audio data to process chunk (bytes): Chunk of audio data to process
""" """
@ -403,7 +403,7 @@ class PorcupineHotWord(HotWordEngine):
def update(self, chunk): def update(self, chunk):
"""Update detection state from a chunk of audio data. """Update detection state from a chunk of audio data.
Arguments: Args:
chunk (bytes): Audio data to parse chunk (bytes): Audio data to parse
""" """
pcm = struct.unpack_from("h" * (len(chunk)//2), chunk) pcm = struct.unpack_from("h" * (len(chunk)//2), chunk)
@ -443,7 +443,7 @@ class PorcupineHotWord(HotWordEngine):
def load_wake_word_plugin(module_name): def load_wake_word_plugin(module_name):
"""Wrapper function for loading wake word plugin. """Wrapper function for loading wake word plugin.
Arguments: Args:
(str) Mycroft wake word module name from config (str) Mycroft wake word module name from config
""" """
return load_plugin('mycroft.plugin.wake_word', module_name) return load_plugin('mycroft.plugin.wake_word', module_name)

View File

@ -276,7 +276,7 @@ class RecognizerLoop(EventEmitter):
Local wake word recognizer and remote general speech recognition. Local wake word recognizer and remote general speech recognition.
Arguments: Args:
watchdog: (callable) function to call periodically indicating watchdog: (callable) function to call periodically indicating
operational status. operational status.
""" """

View File

@ -79,7 +79,7 @@ class MutableStream:
def read(self, size, of_exc=False): def read(self, size, of_exc=False):
"""Read data from stream. """Read data from stream.
Arguments: Args:
size (int): Number of bytes to read size (int): Number of bytes to read
of_exc (bool): flag determining if the audio producer thread of_exc (bool): flag determining if the audio producer thread
should throw IOError at overflows. should throw IOError at overflows.
@ -189,7 +189,7 @@ class MutableMicrophone(Microphone):
def duration_to_bytes(self, sec): def duration_to_bytes(self, sec):
"""Converts a duration in seconds to number of recorded bytes. """Converts a duration in seconds to number of recorded bytes.
Arguments: Args:
sec: number of seconds sec: number of seconds
Returns: Returns:
@ -209,7 +209,7 @@ class NoiseTracker:
in one continous sequence) followed by a short period of continous quiet in one continous sequence) followed by a short period of continous quiet
audio data to be considered complete. audio data to be considered complete.
Arguments: Args:
minimum (int): lower noise level will be threshold for "quiet" level minimum (int): lower noise level will be threshold for "quiet" level
maximum (int): ceiling of noise level maximum (int): ceiling of noise level
sec_per_buffer (float): the length of each buffer used when updating sec_per_buffer (float): the length of each buffer used when updating
@ -262,7 +262,7 @@ class NoiseTracker:
def update(self, is_loud): def update(self, is_loud):
"""Update the tracking. with either a loud chunk or a quiet chunk. """Update the tracking. with either a loud chunk or a quiet chunk.
Arguments: Args:
is_loud: True if a loud chunk should be registered is_loud: True if a loud chunk should be registered
False if a quiet chunk should be registered False if a quiet chunk should be registered
""" """
@ -543,7 +543,7 @@ class ResponsiveRecognizer(speech_recognition.Recognizer):
def _send_wakeword_info(self, emitter): def _send_wakeword_info(self, emitter):
"""Send messagebus message indicating that a wakeword was received. """Send messagebus message indicating that a wakeword was received.
Arguments: Args:
emitter: bus emitter to send information on. emitter: bus emitter to send information on.
""" """
SessionManager.touch() SessionManager.touch()
@ -554,7 +554,7 @@ class ResponsiveRecognizer(speech_recognition.Recognizer):
def _write_wakeword_to_disk(self, audio, metadata): def _write_wakeword_to_disk(self, audio, metadata):
"""Write wakeword to disk. """Write wakeword to disk.
Arguments: Args:
audio: Audio data to write audio: Audio data to write
metadata: List of metadata about the captured wakeword metadata: List of metadata about the captured wakeword
""" """
@ -586,7 +586,7 @@ class ResponsiveRecognizer(speech_recognition.Recognizer):
def _wait_until_wake_word(self, source, sec_per_buffer): def _wait_until_wake_word(self, source, sec_per_buffer):
"""Listen continuously on source until a wake word is spoken """Listen continuously on source until a wake word is spoken
Arguments: Args:
source (AudioSource): Source producing the audio chunks source (AudioSource): Source producing the audio chunks
sec_per_buffer (float): Fractional number of seconds in each chunk sec_per_buffer (float): Fractional number of seconds in each chunk
""" """

View File

@ -82,8 +82,8 @@ SCR_SKILLS = 2
screen_mode = SCR_MAIN screen_mode = SCR_MAIN
subscreen = 0 # for help pages, etc. subscreen = 0 # for help pages, etc.
FULL_REDRAW_FREQUENCY = 10 # seconds between full redraws REDRAW_FREQUENCY = 10 # seconds between full redraws
last_full_redraw = time.time()-(FULL_REDRAW_FREQUENCY-1) # seed for 1s redraw last_redraw = time.time() - (REDRAW_FREQUENCY - 1) # seed for 1s redraw
screen_lock = Lock() screen_lock = Lock()
is_screen_dirty = True is_screen_dirty = True
@ -437,7 +437,7 @@ def handle_utterance(event):
def connect(bus): def connect(bus):
""" Run the mycroft messagebus referenced by bus. """ Run the mycroft messagebus referenced by bus.
Arguments: Args:
bus: Mycroft messagebus instance bus: Mycroft messagebus instance
""" """
bus.run_forever() bus.run_forever()
@ -470,19 +470,19 @@ def draw(x, y, msg, pad=None, pad_chr=None, clr=None):
return return
if x + len(msg) > curses.COLS: if x + len(msg) > curses.COLS:
s = msg[:curses.COLS-x] s = msg[:curses.COLS - x]
else: else:
s = msg s = msg
if pad: if pad:
ch = pad_chr or " " ch = pad_chr or " "
if pad is True: if pad is True:
pad = curses.COLS # pad to edge of screen pad = curses.COLS # pad to edge of screen
s += ch * (pad-x-len(msg)) s += ch * (pad - x - len(msg))
else: else:
# pad to given length (or screen width) # pad to given length (or screen width)
if x+pad > curses.COLS: if x + pad > curses.COLS:
pad = curses.COLS-x pad = curses.COLS - x
s += ch * (pad-len(msg)) s += ch * (pad - len(msg))
if not clr: if not clr:
clr = CLR_LOG1 clr = CLR_LOG1
@ -622,18 +622,27 @@ def _do_gui(gui_width):
clr = curses.color_pair(2) # dark red clr = curses.color_pair(2) # dark red
x = curses.COLS - gui_width x = curses.COLS - gui_width
y = 3 y = 3
draw(x, y, " "+make_titlebar("= GUI", gui_width-1)+" ", clr=CLR_HEADING) draw(
cnt = len(gui_text)+1 x,
if cnt > curses.LINES-15: y,
cnt = curses.LINES-15 " " +
make_titlebar(
"= GUI",
gui_width -
1) +
" ",
clr=CLR_HEADING)
cnt = len(gui_text) + 1
if cnt > curses.LINES - 15:
cnt = curses.LINES - 15
for i in range(0, cnt): for i in range(0, cnt):
draw(x, y+1+i, " !", clr=CLR_HEADING) draw(x, y + 1 + i, " !", clr=CLR_HEADING)
if i < len(gui_text): if i < len(gui_text):
draw(x+2, y+1+i, gui_text[i], pad=gui_width-3) draw(x + 2, y + 1 + i, gui_text[i], pad=gui_width - 3)
else: else:
draw(x+2, y+1+i, "*"*(gui_width-3)) draw(x + 2, y + 1 + i, "*" * (gui_width - 3))
draw(x+(gui_width-1), y+1+i, "!", clr=CLR_HEADING) draw(x + (gui_width - 1), y + 1 + i, "!", clr=CLR_HEADING)
draw(x, y+cnt, " "+"-"*(gui_width-2)+" ", clr=CLR_HEADING) draw(x, y + cnt, " " + "-" * (gui_width - 2) + " ", clr=CLR_HEADING)
def set_screen_dirty(): def set_screen_dirty():
@ -647,16 +656,16 @@ def set_screen_dirty():
def do_draw_main(scr): def do_draw_main(scr):
global log_line_offset global log_line_offset
global longest_visible_line global longest_visible_line
global last_full_redraw global last_redraw
global auto_scroll global auto_scroll
global size_log_area global size_log_area
if time.time() - last_full_redraw > FULL_REDRAW_FREQUENCY: if time.time() - last_redraw > REDRAW_FREQUENCY:
# Do a full-screen redraw periodically to clear and # Do a full-screen redraw periodically to clear and
# noise from non-curses text that get output to the # noise from non-curses text that get output to the
# screen (e.g. modules that do a 'print') # screen (e.g. modules that do a 'print')
scr.clear() scr.clear()
last_full_redraw = time.time() last_redraw = time.time()
else: else:
scr.erase() scr.erase()
@ -689,8 +698,8 @@ def do_draw_main(scr):
str(start) + "-" + str(end) + " of " + str(cLogs), str(start) + "-" + str(end) + " of " + str(cLogs),
CLR_HEADING) CLR_HEADING)
ver = " mycroft-core " + mycroft.version.CORE_VERSION_STR + " ===" ver = " mycroft-core " + mycroft.version.CORE_VERSION_STR + " ==="
scr.addstr(1, 0, "=" * (curses.COLS-1-len(ver)), CLR_HEADING) scr.addstr(1, 0, "=" * (curses.COLS - 1 - len(ver)), CLR_HEADING)
scr.addstr(1, curses.COLS-1-len(ver), ver, CLR_HEADING) scr.addstr(1, curses.COLS - 1 - len(ver), ver, CLR_HEADING)
y = 2 y = 2
for i in range(start, end): for i in range(start, end):
@ -747,10 +756,10 @@ def do_draw_main(scr):
if len(log_files) > 0: if len(log_files) > 0:
scr.addstr(y_log_legend + 2, curses.COLS // 2 + 2, scr.addstr(y_log_legend + 2, curses.COLS // 2 + 2,
os.path.basename(log_files[0]) + ", other", os.path.basename(log_files[0]) + ", other",
CLR_LOG1) CLR_LOG2)
if len(log_files) > 1: if len(log_files) > 1:
scr.addstr(y_log_legend + 3, curses.COLS // 2 + 2, scr.addstr(y_log_legend + 3, curses.COLS // 2 + 2,
os.path.basename(log_files[1]), CLR_LOG2) os.path.basename(log_files[1]), CLR_LOG1)
# Meter # Meter
y_meter = y_log_legend y_meter = y_log_legend
@ -794,7 +803,7 @@ def do_draw_main(scr):
y += 1 y += 1
if show_gui and curses.COLS > 20 and curses.LINES > 20: if show_gui and curses.COLS > 20 and curses.LINES > 20:
_do_gui(curses.COLS-20) _do_gui(curses.COLS - 20)
# Command line at the bottom # Command line at the bottom
ln = line ln = line
@ -806,7 +815,7 @@ def do_draw_main(scr):
else: else:
prompt = "Input (':' for command, Ctrl+C to quit)" prompt = "Input (':' for command, Ctrl+C to quit)"
if show_last_key: if show_last_key:
prompt += " === keycode: "+last_key prompt += " === keycode: " + last_key
scr.addstr(curses.LINES - 2, 0, scr.addstr(curses.LINES - 2, 0,
make_titlebar(prompt, make_titlebar(prompt,
curses.COLS - 1), curses.COLS - 1),
@ -827,59 +836,59 @@ def make_titlebar(title, bar_length):
# Help system # Help system
help_struct = [ help_struct = [('Log Scrolling shortcuts',
( [("Up / Down / PgUp / PgDn",
'Log Scrolling shortcuts', "scroll thru history"),
[ ("Ctrl+T / Ctrl+PgUp",
("Up / Down / PgUp / PgDn", "scroll thru history"), "scroll to top of logs (jump to oldest)"),
("Ctrl+T / Ctrl+PgUp", "scroll to top of logs (jump to oldest)"), ("Ctrl+B / Ctrl+PgDn",
("Ctrl+B / Ctrl+PgDn", "scroll to bottom of logs" + "scroll to bottom of logs" + "(jump to newest)"),
"(jump to newest)"), ("Left / Right",
("Left / Right", "scroll long lines left/right"), "scroll long lines left/right"),
("Home / End", "scroll to start/end of long lines") ("Home / End",
] "scroll to start/end of long lines")]),
), ("Query History shortcuts",
( [("Ctrl+N / Ctrl+Left",
"Query History shortcuts", "previous query"),
[ ("Ctrl+P / Ctrl+Right",
("Ctrl+N / Ctrl+Right", "previous query"), "next query")]),
("Ctrl+P / Ctrl+Left", "next query") ("General Commands (type ':' to enter command mode)",
] [(":quit or :exit",
), "exit the program"),
( (":meter (show|hide)",
"General Commands (type ':' to enter command mode)", "display the microphone level"),
[ (":keycode (show|hide)",
(":quit or :exit", "exit the program"), "display typed key codes (mainly debugging)"),
(":meter (show|hide)", "display the microphone level"), (":history (# lines)",
(":keycode (show|hide)", "display typed key codes (mainly debugging)"), "set size of visible history buffer"),
(":history (# lines)", "set size of visible history buffer"), (":clear",
(":clear", "flush the logs") "flush the logs")]),
] ("Log Manipulation Commands",
), [(":filter 'STR'",
( "adds a log filter (optional quotes)"),
"Log Manipulation Commands", (":filter remove 'STR'",
[ "removes a log filter"),
(":filter 'STR'", "adds a log filter (optional quotes)"), (":filter (clear|reset)",
(":filter remove 'STR'", "removes a log filter"), "reset filters"),
(":filter (clear|reset)", "reset filters"), (":filter (show|list)",
(":filter (show|list)", "display current filters"), "display current filters"),
(":find 'STR'", "show logs containing 'str'"), (":find 'STR'",
(":log level (DEBUG|INFO|ERROR)", "set logging level"), "show logs containing 'str'"),
(":log bus (on|off)", "control logging of messagebus messages") (":log level (DEBUG|INFO|ERROR)",
] "set logging level"),
), (":log bus (on|off)",
( "control logging of messagebus messages")]),
"Skill Debugging Commands", ("Skill Debugging Commands",
[ [(":skills",
(":skills", "list installed skills"), "list installed Skills"),
(":api SKILL", "show skill's public API"), (":api SKILL",
(":activate SKILL", "activate skill, e.g. 'activate skill-wiki'"), "show Skill's public API"),
(":deactivate SKILL", "deactivate skill"), (":activate SKILL",
(":keep SKILL", "deactivate all skills except " + "activate Skill, e.g. 'activate skill-wiki'"),
"the indicated skill") (":deactivate SKILL",
] "deactivate Skill"),
) (":keep SKILL",
] "deactivate all Skills except the indicated Skill")])]
help_longest = 0 help_longest = 0
for s in help_struct: for s in help_struct:
for ent in s[1]: for ent in s[1]:
@ -934,7 +943,7 @@ def do_draw_help(scr):
ln = line[0].ljust(help_longest + 1) ln = line[0].ljust(help_longest + 1)
for w in words: for w in words:
if len(ln) + 1 + len(w) < curses.COLS: if len(ln) + 1 + len(w) < curses.COLS:
ln += " "+w ln += " " + w
else: else:
y = render_help(ln, y, i, first, last, CLR_CMDLINE) y = render_help(ln, y, i, first, last, CLR_CMDLINE)
ln = " ".ljust(help_longest + 2) + w ln = " ".ljust(help_longest + 2) + w
@ -978,9 +987,7 @@ def show_next_help():
# Skill debugging # Skill debugging
def show_skills(skills): def show_skills(skills):
""" """Show list of loaded Skills in as many column as necessary."""
Show list of loaded skills in as many column as necessary
"""
global scr global scr
global screen_mode global screen_mode
@ -997,7 +1004,7 @@ def show_skills(skills):
nonlocal row nonlocal row
nonlocal column nonlocal column
scr.erase() scr.erase()
scr.addstr(0, 0, center(25) + "Loaded skills", CLR_CMDLINE) scr.addstr(0, 0, center(25) + "Loaded Skills", CLR_CMDLINE)
scr.addstr(1, 1, "=" * (curses.COLS - 2), CLR_CMDLINE) scr.addstr(1, 1, "=" * (curses.COLS - 2), CLR_CMDLINE)
row = 2 row = 2
column = 0 column = 0
@ -1037,7 +1044,7 @@ def show_skills(skills):
def show_skill_api(skill, data): def show_skill_api(skill, data):
"""Show available help on skill's API.""" """Show available help on Skill's API."""
global scr global scr
global screen_mode global screen_mode
@ -1335,13 +1342,13 @@ def gui_main(stdscr):
start = time.time() start = time.time()
while c1 == -1: while c1 == -1:
c1 = scr.getch() c1 = scr.getch()
if time.time()-start > 1: if time.time() - start > 1:
break # 1 second timeout waiting for ESC code break # 1 second timeout waiting for ESC code
c2 = -1 c2 = -1
while c2 == -1: while c2 == -1:
c2 = scr.getch() c2 = scr.getch()
if time.time()-start > 1: # 1 second timeout if time.time() - start > 1: # 1 second timeout
break # 1 second timeout waiting for ESC code break # 1 second timeout waiting for ESC code
if c1 == 79 and c2 == 120: if c1 == 79 and c2 == 120:

View File

@ -41,7 +41,7 @@ def is_remote_list(values):
def translate_remote(config, setting): def translate_remote(config, setting):
"""Translate config names from server to equivalents for mycroft-core. """Translate config names from server to equivalents for mycroft-core.
Arguments: Args:
config: base config to populate config: base config to populate
settings: remote settings to be translated settings: remote settings to be translated
""" """
@ -69,7 +69,7 @@ def translate_remote(config, setting):
def translate_list(config, values): def translate_list(config, values):
"""Translate list formated by mycroft server. """Translate list formated by mycroft server.
Arguments: Args:
config (dict): target config config (dict): target config
values (list): list from mycroft server config values (list): list from mycroft server config
""" """
@ -92,7 +92,7 @@ class LocalConf(dict):
def load_local(self, path): def load_local(self, path):
"""Load local json file into self. """Load local json file into self.
Arguments: Args:
path (str): file to load path (str): file to load
""" """
if exists(path) and isfile(path): if exists(path) and isfile(path):
@ -180,7 +180,7 @@ class Configuration:
Returns cached instance if available otherwise builds a new Returns cached instance if available otherwise builds a new
configuration dict. configuration dict.
Arguments: Args:
configs (list): List of configuration dicts configs (list): List of configuration dicts
cache (boolean): True if the result should be cached cache (boolean): True if the result should be cached
@ -196,7 +196,7 @@ class Configuration:
def load_config_stack(configs=None, cache=False): def load_config_stack(configs=None, cache=False):
"""Load a stack of config dicts into a single dict """Load a stack of config dicts into a single dict
Arguments: Args:
configs (list): list of dicts to load configs (list): list of dicts to load
cache (boolean): True if result should be cached cache (boolean): True if result should be cached
@ -231,7 +231,7 @@ class Configuration:
def set_config_update_handlers(bus): def set_config_update_handlers(bus):
"""Setup websocket handlers to update config. """Setup websocket handlers to update config.
Arguments: Args:
bus: Message bus client instance bus: Message bus client instance
""" """
bus.on("configuration.updated", Configuration.updated) bus.on("configuration.updated", Configuration.updated)
@ -250,7 +250,7 @@ class Configuration:
def patch(message): def patch(message):
"""Patch the volatile dict usable by skills """Patch the volatile dict usable by skills
Arguments: Args:
message: Messagebus message should contain a config message: Messagebus message should contain a config
in the data payload. in the data payload.
""" """
@ -262,7 +262,7 @@ class Configuration:
def patch_clear(message): def patch_clear(message):
"""Clear the config patch space. """Clear the config patch space.
Arguments: Args:
message: Messagebus message should contain a config message: Messagebus message should contain a config
in the data payload. in the data payload.
""" """

View File

@ -26,7 +26,7 @@ WEB_CONFIG_CACHE = os.environ.get('MYCROFT_WEB_CACHE',
def __ensure_folder_exists(path): def __ensure_folder_exists(path):
""" Make sure the directory for the specified path exists. """ Make sure the directory for the specified path exists.
Arguments: Args:
path (str): path to config file path (str): path to config file
""" """
directory = dirname(path) directory = dirname(path)

View File

@ -49,7 +49,7 @@ class MustacheDialogRenderer:
def load_template_file(self, template_name, filename): def load_template_file(self, template_name, filename):
"""Load a template by file name into the templates cache. """Load a template by file name into the templates cache.
Arguments: Args:
template_name (str): a unique identifier for a group of templates template_name (str): a unique identifier for a group of templates
filename (str): a fully qualified filename of a mustache template. filename (str): a fully qualified filename of a mustache template.
""" """
@ -78,7 +78,7 @@ class MustacheDialogRenderer:
Tries not to let Mycroft say exactly the same thing twice in a row. Tries not to let Mycroft say exactly the same thing twice in a row.
Arguments: Args:
template_name (str): the name of a template group. template_name (str): the name of a template group.
context (dict): dictionary representing values to be rendered context (dict): dictionary representing values to be rendered
index (int): optional, the specific index in the collection of index (int): optional, the specific index in the collection of
@ -123,7 +123,7 @@ class MustacheDialogRenderer:
def load_dialogs(dialog_dir, renderer=None): def load_dialogs(dialog_dir, renderer=None):
"""Load all dialog files within the specified directory. """Load all dialog files within the specified directory.
Arguments: Args:
dialog_dir (str): directory that contains dialog files dialog_dir (str): directory that contains dialog files
Returns: Returns:
@ -151,7 +151,7 @@ def get(phrase, lang=None, context=None):
If no file is found, the requested phrase is returned as the string. This If no file is found, the requested phrase is returned as the string. This
will use the default language for translations. will use the default language for translations.
Arguments: Args:
phrase (str): resource phrase to retrieve/translate phrase (str): resource phrase to retrieve/translate
lang (str): the language to use lang (str): the language to use
context (dict): values to be inserted into the string context (dict): values to be inserted into the string

View File

@ -224,7 +224,7 @@ class EnclosureAPI:
def mouth_viseme(self, start, viseme_pairs): def mouth_viseme(self, start, viseme_pairs):
""" Send mouth visemes as a list in a single message. """ Send mouth visemes as a list in a single message.
Arguments: Args:
start (int): Timestamp for start of speech start (int): Timestamp for start of speech
viseme_pairs: Pairs of viseme id and cumulative end times viseme_pairs: Pairs of viseme id and cumulative end times
(code, end time) (code, end time)

View File

@ -69,7 +69,7 @@ class SkillGUI:
When using the triggerEvent method from Qt When using the triggerEvent method from Qt
triggerEvent("event", {"data": "cool"}) triggerEvent("event", {"data": "cool"})
Arguments: Args:
event (str): event to catch event (str): event to catch
handler: function to handle the event handler: function to handle the event
""" """
@ -80,7 +80,7 @@ class SkillGUI:
"""Registers a callback function to run when a value is """Registers a callback function to run when a value is
changed from the GUI. changed from the GUI.
Arguments: Args:
callback: Function to call when a value is changed callback: Function to call when a value is changed
""" """
self.on_gui_changed_callback = callback self.on_gui_changed_callback = callback
@ -88,7 +88,7 @@ class SkillGUI:
def gui_set(self, message): def gui_set(self, message):
"""Handler catching variable changes from the GUI. """Handler catching variable changes from the GUI.
Arguments: Args:
message: Messagebus message message: Messagebus message
""" """
for key in message.data: for key in message.data:
@ -132,7 +132,7 @@ class SkillGUI:
def send_event(self, event_name, params=None): def send_event(self, event_name, params=None):
"""Trigger a gui event. """Trigger a gui event.
Arguments: Args:
event_name (str): name of event to be triggered event_name (str): name of event to be triggered
params: json serializable object containing any parameters that params: json serializable object containing any parameters that
should be sent along with the request. should be sent along with the request.
@ -147,7 +147,7 @@ class SkillGUI:
override_animations=False): override_animations=False):
"""Begin showing the page in the GUI """Begin showing the page in the GUI
Arguments: Args:
name (str): Name of page (e.g "mypage.qml") to display name (str): Name of page (e.g "mypage.qml") to display
override_idle (boolean, int): override_idle (boolean, int):
True: Takes over the resting page indefinitely True: Takes over the resting page indefinitely
@ -163,7 +163,7 @@ class SkillGUI:
override_animations=False): override_animations=False):
"""Begin showing the list of pages in the GUI. """Begin showing the list of pages in the GUI.
Arguments: Args:
page_names (list): List of page names (str) to display, such as page_names (list): List of page names (str) to display, such as
["Weather.qml", "Forecast.qml", "Details.qml"] ["Weather.qml", "Forecast.qml", "Details.qml"]
index (int): Page number (0-based) to show initially. For the index (int): Page number (0-based) to show initially. For the
@ -214,7 +214,7 @@ class SkillGUI:
def remove_page(self, page): def remove_page(self, page):
"""Remove a single page from the GUI. """Remove a single page from the GUI.
Arguments: Args:
page (str): Page to remove from the GUI page (str): Page to remove from the GUI
""" """
return self.remove_pages([page]) return self.remove_pages([page])
@ -222,7 +222,7 @@ class SkillGUI:
def remove_pages(self, page_names): def remove_pages(self, page_names):
"""Remove a list of pages in the GUI. """Remove a list of pages in the GUI.
Arguments: Args:
page_names (list): List of page names (str) to display, such as page_names (list): List of page names (str) to display, such as
["Weather.qml", "Forecast.qml", "Other.qml"] ["Weather.qml", "Forecast.qml", "Other.qml"]
""" """
@ -252,7 +252,7 @@ class SkillGUI:
override_animations=False): override_animations=False):
"""Display a GUI page for viewing simple text. """Display a GUI page for viewing simple text.
Arguments: Args:
text (str): Main text content. It will auto-paginate text (str): Main text content. It will auto-paginate
title (str): A title to display above the text content. title (str): A title to display above the text content.
override_idle (boolean, int): override_idle (boolean, int):
@ -273,7 +273,7 @@ class SkillGUI:
override_idle=None, override_animations=False): override_idle=None, override_animations=False):
"""Display a GUI page for viewing an image. """Display a GUI page for viewing an image.
Arguments: Args:
url (str): Pointer to the image url (str): Pointer to the image
caption (str): A caption to show under the image caption (str): A caption to show under the image
title (str): A title to display above the image content title (str): A title to display above the image content
@ -299,7 +299,7 @@ class SkillGUI:
override_idle=None, override_animations=False): override_idle=None, override_animations=False):
"""Display a GUI page for viewing an image. """Display a GUI page for viewing an image.
Arguments: Args:
url (str): Pointer to the .gif image url (str): Pointer to the .gif image
caption (str): A caption to show under the image caption (str): A caption to show under the image
title (str): A title to display above the image content title (str): A title to display above the image content
@ -324,7 +324,7 @@ class SkillGUI:
override_animations=False): override_animations=False):
"""Display an HTML page in the GUI. """Display an HTML page in the GUI.
Arguments: Args:
html (str): HTML text to display html (str): HTML text to display
resource_url (str): Pointer to HTML resources resource_url (str): Pointer to HTML resources
override_idle (boolean, int): override_idle (boolean, int):
@ -344,7 +344,7 @@ class SkillGUI:
override_animations=False): override_animations=False):
"""Display an HTML page in the GUI. """Display an HTML page in the GUI.
Arguments: Args:
url (str): URL to render url (str): URL to render
override_idle (boolean, int): override_idle (boolean, int):
True: Takes over the resting page indefinitely True: Takes over the resting page indefinitely

View File

@ -58,7 +58,7 @@ class FileSystemAccess:
def exists(self, filename): def exists(self, filename):
"""Check if file exists in the namespace. """Check if file exists in the namespace.
Arguments: Args:
filename (str): a path relative to the namespace. filename (str): a path relative to the namespace.
subdirs not currently supported. subdirs not currently supported.
Returns: Returns:

View File

@ -71,7 +71,7 @@ def report_metric(name, data):
def report_timing(ident, system, timing, additional_data=None): def report_timing(ident, system, timing, additional_data=None):
"""Create standardized message for reporting timing. """Create standardized message for reporting timing.
Arguments: Args:
ident (str): identifier of user interaction ident (str): identifier of user interaction
system (str): system the that's generated the report system (str): system the that's generated the report
timing (stopwatch): Stopwatch object with recorded timing timing (stopwatch): Stopwatch object with recorded timing

View File

@ -52,7 +52,7 @@ RASPBERRY_PI_PLATFORMS = ('mycroft_mark_1', 'picroft', 'mycroft_mark_2pi')
class DevicePrimer(object): class DevicePrimer(object):
"""Container handling the device preparation. """Container handling the device preparation.
Arguments: Args:
message_bus_client: Bus client used to interact with the system message_bus_client: Bus client used to interact with the system
config (dict): Mycroft configuration config (dict): Mycroft configuration
""" """
@ -241,7 +241,7 @@ def main(alive_hook=on_alive, started_hook=on_started, ready_hook=on_ready,
def _register_intent_services(bus): def _register_intent_services(bus):
"""Start up the all intent services and connect them as needed. """Start up the all intent services and connect them as needed.
Arguments: Args:
bus: messagebus client to register the services on bus: messagebus client to register the services on
""" """
service = IntentService(bus) service = IntentService(bus)

View File

@ -53,7 +53,7 @@ class SkillApi():
@staticmethod @staticmethod
def get(skill): def get(skill):
"""Generate api object from skill id. """Generate api object from skill id.
Arguments: Args:
skill (str): skill id for target skill skill (str): skill id for target skill
Returns: Returns:

View File

@ -20,7 +20,7 @@ from mycroft.messagebus.message import Message
def ensure_uri(s): def ensure_uri(s):
"""Interprete paths as file:// uri's. """Interprete paths as file:// uri's.
Arguments: Args:
s: string to be checked s: string to be checked
Returns: Returns:
@ -43,7 +43,7 @@ def ensure_uri(s):
class AudioService: class AudioService:
"""AudioService class for interacting with the audio subsystem """AudioService class for interacting with the audio subsystem
Arguments: Args:
bus: Mycroft messagebus connection bus: Mycroft messagebus connection
""" """
@ -53,7 +53,7 @@ class AudioService:
def queue(self, tracks=None): def queue(self, tracks=None):
"""Queue up a track to playing playlist. """Queue up a track to playing playlist.
Arguments: Args:
tracks: track uri or list of track uri's tracks: track uri or list of track uri's
Each track can be added as a tuple with (uri, mime) Each track can be added as a tuple with (uri, mime)
to give a hint of the mime type to the system to give a hint of the mime type to the system
@ -70,7 +70,7 @@ class AudioService:
def play(self, tracks=None, utterance=None, repeat=None): def play(self, tracks=None, utterance=None, repeat=None):
"""Start playback. """Start playback.
Arguments: Args:
tracks: track uri or list of track uri's tracks: track uri or list of track uri's
Each track can be added as a tuple with (uri, mime) Each track can be added as a tuple with (uri, mime)
to give a hint of the mime type to the system to give a hint of the mime type to the system
@ -114,7 +114,7 @@ class AudioService:
def seek(self, seconds=1): def seek(self, seconds=1):
"""Seek X seconds. """Seek X seconds.
Arguments: Args:
seconds (int): number of seconds to seek, if negative rewind seconds (int): number of seconds to seek, if negative rewind
""" """
if seconds < 0: if seconds < 0:
@ -125,7 +125,7 @@ class AudioService:
def seek_forward(self, seconds=1): def seek_forward(self, seconds=1):
"""Skip ahead X seconds. """Skip ahead X seconds.
Arguments: Args:
seconds (int): number of seconds to skip seconds (int): number of seconds to skip
""" """
self.bus.emit(Message('mycroft.audio.service.seek_forward', self.bus.emit(Message('mycroft.audio.service.seek_forward',
@ -134,7 +134,7 @@ class AudioService:
def seek_backward(self, seconds=1): def seek_backward(self, seconds=1):
"""Rewind X seconds """Rewind X seconds
Arguments: Args:
seconds (int): number of seconds to rewind seconds (int): number of seconds to rewind
""" """
self.bus.emit(Message('mycroft.audio.service.seek_backward', self.bus.emit(Message('mycroft.audio.service.seek_backward',

View File

@ -528,8 +528,8 @@ class CommonIoTSkill(MycroftSkill, ABC):
An IoTRequest contains several properties (see the An IoTRequest contains several properties (see the
documentation for that class). This method should return documentation for that class). This method should return
True if and only if this skill can take the appropriate True if and only if this skill can take the appropriate
'action' when considering _all other properties 'action' when considering all other properties
of the request_. In other words, a partial match, one in which of the request. In other words, a partial match, one in which
any piece of the IoTRequest is not known to this skill, any piece of the IoTRequest is not known to this skill,
and is not None, this should return (False, None). and is not None, this should return (False, None).

View File

@ -120,7 +120,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
Assume the more of the words that get consumed, the better the match Assume the more of the words that get consumed, the better the match
Arguments: Args:
match (str): Matching string match (str): Matching string
phrase (str): original input phrase phrase (str): original input phrase
level (CPSMatchLevel): match level level (CPSMatchLevel): match level
@ -203,7 +203,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
def CPS_match_query_phrase(self, phrase): def CPS_match_query_phrase(self, phrase):
"""Analyze phrase to see if it is a play-able phrase with this skill. """Analyze phrase to see if it is a play-able phrase with this skill.
Arguments: Args:
phrase (str): User phrase uttered after "Play", e.g. "some music" phrase (str): User phrase uttered after "Play", e.g. "some music"
Returns: Returns:
@ -233,7 +233,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
def CPS_start(self, phrase, data): def CPS_start(self, phrase, data):
"""Begin playing whatever is specified in 'phrase' """Begin playing whatever is specified in 'phrase'
Arguments: Args:
phrase (str): User phrase uttered after "Play", e.g. "some music" phrase (str): User phrase uttered after "Play", e.g. "some music"
data (dict): Callback data specified in match_query_phrase() data (dict): Callback data specified in match_query_phrase()
""" """
@ -245,7 +245,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
"""Request Common Play Framework to wait another {timeout} seconds """Request Common Play Framework to wait another {timeout} seconds
for an answer from this skill. for an answer from this skill.
Arguments: Args:
timeout (int): Number of seconds timeout (int): Number of seconds
""" """
self.bus.emit(Message('play:query.response', self.bus.emit(Message('play:query.response',
@ -268,7 +268,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
non-standard parameters are added, they too will be sent in the message non-standard parameters are added, they too will be sent in the message
data. data.
Arguments: Args:
artist (str): Current track artist artist (str): Current track artist
track (str): Track name track (str): Track name
album (str): Album title album (str): Album title
@ -297,7 +297,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
Provides track data for playlist Provides track data for playlist
Arguments: Args:
tracklist (list/dict): Tracklist data tracklist (list/dict): Tracklist data
""" """
tracklist = tracklist or [] tracklist = tracklist or []

View File

@ -134,7 +134,7 @@ class CommonQuerySkill(MycroftSkill, ABC):
Needs to be implemented by the skill. Needs to be implemented by the skill.
Arguments: Args:
phrase (str): User phrase, "What is an aardwark" phrase (str): User phrase, "What is an aardwark"
Returns: Returns:

View File

@ -22,7 +22,7 @@ Helper decorators for handling context from skills.
def adds_context(context, words=''): def adds_context(context, words=''):
"""Decorator adding context to the Adapt context manager. """Decorator adding context to the Adapt context manager.
Arguments: Args:
context (str): context Keyword to insert context (str): context Keyword to insert
words (str): optional string content of Keyword words (str): optional string content of Keyword
""" """
@ -39,7 +39,7 @@ def adds_context(context, words=''):
def removes_context(context): def removes_context(context):
"""Decorator removing context from the Adapt context manager. """Decorator removing context from the Adapt context manager.
Arguments: Args:
context (str): Context keyword to remove context (str): Context keyword to remove
""" """
def context_removes_decorator(func): def context_removes_decorator(func):

View File

@ -48,7 +48,7 @@ class EventScheduler(Thread):
"""Create an event scheduler thread. Will send messages at a """Create an event scheduler thread. Will send messages at a
predetermined time to the registered targets. predetermined time to the registered targets.
Arguments: Args:
bus: Mycroft messagebus (mycroft.messagebus) bus: Mycroft messagebus (mycroft.messagebus)
schedule_file: File to store pending events to on shutdown schedule_file: File to store pending events to on shutdown
""" """
@ -132,7 +132,7 @@ class EventScheduler(Thread):
data=None, context=None): data=None, context=None):
"""Add event to pending event schedule. """Add event to pending event schedule.
Arguments: Args:
event (str): Handler for the event event (str): Handler for the event
sched_time ([type]): [description] sched_time ([type]): [description]
repeat ([type], optional): Defaults to None. [description] repeat ([type], optional): Defaults to None. [description]
@ -180,7 +180,7 @@ class EventScheduler(Thread):
def remove_event(self, event): def remove_event(self, event):
"""Remove an event from the list of scheduled events. """Remove an event from the list of scheduled events.
Arguments: Args:
event (str): event identifier event (str): event identifier
""" """
with self.event_lock: with self.event_lock:
@ -198,7 +198,7 @@ class EventScheduler(Thread):
This will only update the first call if multiple calls are registered This will only update the first call if multiple calls are registered
to the same event identifier. to the same event identifier.
Arguments: Args:
event (str): event identifier event (str): event identifier
data (dict): new data data (dict): new data
""" """
@ -282,7 +282,7 @@ class EventSchedulerInterface:
"""Return a name unique to this skill using the format """Return a name unique to this skill using the format
[skill_id]:[name]. [skill_id]:[name].
Arguments: Args:
name: Name to use internally name: Name to use internally
Returns: Returns:
@ -296,7 +296,7 @@ class EventSchedulerInterface:
Takes scheduling information and sends it off on the message bus. Takes scheduling information and sends it off on the message bus.
Arguments: Args:
handler: method to be called handler: method to be called
when (datetime): time (in system timezone) for first when (datetime): time (in system timezone) for first
calling the handler, or None to calling the handler, or None to
@ -335,7 +335,7 @@ class EventSchedulerInterface:
context=None): context=None):
"""Schedule a single-shot event. """Schedule a single-shot event.
Arguments: Args:
handler: method to be called handler: method to be called
when (datetime/int/float): datetime (in system timezone) or when (datetime/int/float): datetime (in system timezone) or
number of seconds in the future when the number of seconds in the future when the
@ -354,7 +354,7 @@ class EventSchedulerInterface:
data=None, name=None, context=None): data=None, name=None, context=None):
"""Schedule a repeating event. """Schedule a repeating event.
Arguments: Args:
handler: method to be called handler: method to be called
when (datetime): time (in system timezone) for first when (datetime): time (in system timezone) for first
calling the handler, or None to calling the handler, or None to
@ -381,7 +381,7 @@ class EventSchedulerInterface:
def update_scheduled_event(self, name, data=None): def update_scheduled_event(self, name, data=None):
"""Change data of event. """Change data of event.
Arguments: Args:
name (str): reference name of event (from original scheduling) name (str): reference name of event (from original scheduling)
""" """
data = data or {} data = data or {}
@ -396,7 +396,7 @@ class EventSchedulerInterface:
"""Cancel a pending event. The event will no longer be scheduled """Cancel a pending event. The event will no longer be scheduled
to be executed to be executed
Arguments: Args:
name (str): reference name of event (from original scheduling) name (str): reference name of event (from original scheduling)
""" """
unique_name = self._create_unique_name(name) unique_name = self._create_unique_name(name)
@ -410,7 +410,7 @@ class EventSchedulerInterface:
def get_scheduled_event_status(self, name): def get_scheduled_event_status(self, name):
"""Get scheduled event data and return the amount of time left """Get scheduled event data and return the amount of time left
Arguments: Args:
name (str): reference name of event (from original scheduling) name (str): reference name of event (from original scheduling)
Returns: Returns:

View File

@ -116,7 +116,7 @@ class FallbackSkill(MycroftSkill):
Lower priority gets run first Lower priority gets run first
0 for high priority 100 for low priority 0 for high priority 100 for low priority
Arguments: Args:
handler (callable): original handler, used as a reference when handler (callable): original handler, used as a reference when
removing removing
wrapper (callable): wrapped version of handler wrapper (callable): wrapped version of handler
@ -146,7 +146,7 @@ class FallbackSkill(MycroftSkill):
def _remove_registered_handler(cls, wrapper_to_del): def _remove_registered_handler(cls, wrapper_to_del):
"""Remove a registered wrapper. """Remove a registered wrapper.
Arguments: Args:
wrapper_to_del (callable): wrapped handler to be removed wrapper_to_del (callable): wrapped handler to be removed
Returns: Returns:
@ -166,7 +166,7 @@ class FallbackSkill(MycroftSkill):
def remove_fallback(cls, handler_to_del): def remove_fallback(cls, handler_to_del):
"""Remove a fallback handler. """Remove a fallback handler.
Arguments: Args:
handler_to_del: reference to handler handler_to_del: reference to handler
Returns: Returns:
(bool) True if at least one handler was removed, otherwise False (bool) True if at least one handler was removed, otherwise False

View File

@ -29,7 +29,7 @@ from .intent_service_interface import open_intent_envelope
def _get_message_lang(message): def _get_message_lang(message):
"""Get the language from the message or the default language. """Get the language from the message or the default language.
Arguments: Args:
message: message to check for language code. message: message to check for language code.
Returns: Returns:
@ -47,7 +47,7 @@ def _normalize_all_utterances(utterances):
will be set as the second item in the tuple, if normalization doesn't will be set as the second item in the tuple, if normalization doesn't
change anything the tuple will only have the "raw" original utterance. change anything the tuple will only have the "raw" original utterance.
Arguments: Args:
utterances (list): list of utterances to normalize utterances (list): list of utterances to normalize
Returns: Returns:
@ -159,7 +159,7 @@ class IntentService:
def do_converse(self, utterances, skill_id, lang, message): def do_converse(self, utterances, skill_id, lang, message):
"""Call skill and ask if they want to process the utterance. """Call skill and ask if they want to process the utterance.
Arguments: Args:
utterances (list of tuples): utterances paired with normalized utterances (list of tuples): utterances paired with normalized
versions. versions.
skill_id: skill to query. skill_id: skill to query.
@ -182,7 +182,7 @@ class IntentService:
def handle_converse_error(self, message): def handle_converse_error(self, message):
"""Handle error in converse system. """Handle error in converse system.
Arguments: Args:
message (Message): info about the error. message (Message): info about the error.
""" """
skill_id = message.data["skill_id"] skill_id = message.data["skill_id"]
@ -194,7 +194,7 @@ class IntentService:
def remove_active_skill(self, skill_id): def remove_active_skill(self, skill_id):
"""Remove a skill from being targetable by converse. """Remove a skill from being targetable by converse.
Arguments: Args:
skill_id (str): skill to remove skill_id (str): skill to remove
""" """
for skill in self.active_skills: for skill in self.active_skills:
@ -207,7 +207,7 @@ class IntentService:
The skill is added to the front of the list, if it's already in the The skill is added to the front of the list, if it's already in the
list it's removed so there is only a single entry of it. list it's removed so there is only a single entry of it.
Arguments: Args:
skill_id (str): identifier of skill to be added. skill_id (str): identifier of skill to be added.
""" """
# search the list for an existing entry that already contains it # search the list for an existing entry that already contains it
@ -225,7 +225,7 @@ class IntentService:
NOTE: This only applies to those with Opt In. NOTE: This only applies to those with Opt In.
Arguments: Args:
intent (IntentMatch or None): intet match info intent (IntentMatch or None): intet match info
context (dict): context info about the interaction context (dict): context info about the interaction
stopwatch (StopWatch): Timing info about the skill parsing. stopwatch (StopWatch): Timing info about the skill parsing.
@ -268,7 +268,7 @@ class IntentService:
If all these fail the complete_intent_failure message will be sent If all these fail the complete_intent_failure message will be sent
and a generic info of the failure will be spoken. and a generic info of the failure will be spoken.
Arguments: Args:
message (Message): The messagebus data message (Message): The messagebus data
""" """
try: try:
@ -318,7 +318,7 @@ class IntentService:
def _converse(self, utterances, lang, message): def _converse(self, utterances, lang, message):
"""Give active skills a chance at the utterance """Give active skills a chance at the utterance
Arguments: Args:
utterances (list): list of utterances utterances (list): list of utterances
lang (string): 4 letter ISO language code lang (string): 4 letter ISO language code
message (Message): message to use to generate reply message (Message): message to use to generate reply
@ -343,7 +343,7 @@ class IntentService:
def send_complete_intent_failure(self, message): def send_complete_intent_failure(self, message):
"""Send a message that no skill could handle the utterance. """Send a message that no skill could handle the utterance.
Arguments: Args:
message (Message): original message to forward from message (Message): original message to forward from
""" """
self.bus.emit(message.forward('complete_intent_failure')) self.bus.emit(message.forward('complete_intent_failure'))
@ -351,7 +351,7 @@ class IntentService:
def handle_register_vocab(self, message): def handle_register_vocab(self, message):
"""Register adapt vocabulary. """Register adapt vocabulary.
Arguments: Args:
message (Message): message containing vocab info message (Message): message containing vocab info
""" """
start_concept = message.data.get('start') start_concept = message.data.get('start')
@ -365,7 +365,7 @@ class IntentService:
def handle_register_intent(self, message): def handle_register_intent(self, message):
"""Register adapt intent. """Register adapt intent.
Arguments: Args:
message (Message): message containing intent info message (Message): message containing intent info
""" """
intent = open_intent_envelope(message) intent = open_intent_envelope(message)
@ -374,7 +374,7 @@ class IntentService:
def handle_detach_intent(self, message): def handle_detach_intent(self, message):
"""Remover adapt intent. """Remover adapt intent.
Arguments: Args:
message (Message): message containing intent info message (Message): message containing intent info
""" """
intent_name = message.data.get('intent_name') intent_name = message.data.get('intent_name')
@ -383,7 +383,7 @@ class IntentService:
def handle_detach_skill(self, message): def handle_detach_skill(self, message):
"""Remove all intents registered for a specific skill. """Remove all intents registered for a specific skill.
Arguments: Args:
message (Message): message containing intent info message (Message): message containing intent info
""" """
skill_id = message.data.get('skill_id') skill_id = message.data.get('skill_id')
@ -427,7 +427,7 @@ class IntentService:
def handle_get_intent(self, message): def handle_get_intent(self, message):
"""Get intent from either adapt or padatious. """Get intent from either adapt or padatious.
Arguments: Args:
message (Message): message containing utterance message (Message): message containing utterance
""" """
utterance = message.data["utterance"] utterance = message.data["utterance"]
@ -486,7 +486,7 @@ class IntentService:
def handle_get_adapt(self, message): def handle_get_adapt(self, message):
"""handler getting the adapt response for an utterance. """handler getting the adapt response for an utterance.
Arguments: Args:
message (Message): message containing utterance message (Message): message containing utterance
""" """
utterance = message.data["utterance"] utterance = message.data["utterance"]
@ -518,7 +518,7 @@ class IntentService:
def handle_get_padatious(self, message): def handle_get_padatious(self, message):
"""messagebus handler for perfoming padatious parsing. """messagebus handler for perfoming padatious parsing.
Arguments: Args:
message (Message): message triggering the method message (Message): message triggering the method
""" """
utterance = message.data["utterance"] utterance = message.data["utterance"]
@ -534,7 +534,7 @@ class IntentService:
def handle_padatious_manifest(self, message): def handle_padatious_manifest(self, message):
"""Messagebus handler returning the registered padatious intents. """Messagebus handler returning the registered padatious intents.
Arguments: Args:
message (Message): message triggering the method message (Message): message triggering the method
""" """
self.bus.emit(message.reply( self.bus.emit(message.reply(
@ -544,7 +544,7 @@ class IntentService:
def handle_entity_manifest(self, message): def handle_entity_manifest(self, message):
"""Messagebus handler returning the registered padatious entities. """Messagebus handler returning the registered padatious entities.
Arguments: Args:
message (Message): message triggering the method message (Message): message triggering the method
""" """
self.bus.emit(message.reply( self.bus.emit(message.reply(

View File

@ -57,7 +57,7 @@ class IntentServiceInterface:
def register_adapt_regex(self, regex): def register_adapt_regex(self, regex):
"""Register a regex with the intent service. """Register a regex with the intent service.
Arguments: Args:
regex (str): Regex to be registered, (Adapt extracts keyword regex (str): Regex to be registered, (Adapt extracts keyword
reference from named match group. reference from named match group.
""" """
@ -75,7 +75,7 @@ class IntentServiceInterface:
def detach_intent(self, intent_name): def detach_intent(self, intent_name):
"""Remove an intent from the intent service. """Remove an intent from the intent service.
Arguments: Args:
intent_name(str): Intent reference intent_name(str): Intent reference
""" """
self.bus.emit(Message("detach_intent", {"intent_name": intent_name})) self.bus.emit(Message("detach_intent", {"intent_name": intent_name}))
@ -83,7 +83,7 @@ class IntentServiceInterface:
def set_adapt_context(self, context, word, origin): def set_adapt_context(self, context, word, origin):
"""Set an Adapt context. """Set an Adapt context.
Arguments: Args:
context (str): context keyword name context (str): context keyword name
word (str): word to register word (str): word to register
origin (str): original origin of the context (for cross context) origin (str): original origin of the context (for cross context)
@ -95,7 +95,7 @@ class IntentServiceInterface:
def remove_adapt_context(self, context): def remove_adapt_context(self, context):
"""Remove an active Adapt context. """Remove an active Adapt context.
Arguments: Args:
context(str): name of context to remove context(str): name of context to remove
""" """
self.bus.emit(Message('remove_context', {'context': context})) self.bus.emit(Message('remove_context', {'context': context}))
@ -103,7 +103,7 @@ class IntentServiceInterface:
def register_padatious_intent(self, intent_name, filename): def register_padatious_intent(self, intent_name, filename):
"""Register a padatious intent file with Padatious. """Register a padatious intent file with Padatious.
Arguments: Args:
intent_name(str): intent identifier intent_name(str): intent identifier
filename(str): complete file path for entity file filename(str): complete file path for entity file
""" """
@ -120,7 +120,7 @@ class IntentServiceInterface:
def register_padatious_entity(self, entity_name, filename): def register_padatious_entity(self, entity_name, filename):
"""Register a padatious entity file with Padatious. """Register a padatious entity file with Padatious.
Arguments: Args:
entity_name(str): entity name entity_name(str): entity name
filename(str): complete file path for entity file filename(str): complete file path for entity file
""" """
@ -149,7 +149,7 @@ class IntentServiceInterface:
def get_intent(self, intent_name): def get_intent(self, intent_name):
"""Get intent from intent_name. """Get intent from intent_name.
Arguments: Args:
intent_name (str): name to find. intent_name (str): name to find.
Returns: Returns:

View File

@ -42,7 +42,7 @@ def _entity_skill_id(skill_id):
class AdaptIntent(IntentBuilder): class AdaptIntent(IntentBuilder):
"""Wrapper for IntentBuilder setting a blank name. """Wrapper for IntentBuilder setting a blank name.
Arguments: Args:
name (str): Optional name of intent name (str): Optional name of intent
""" """
def __init__(self, name=''): def __init__(self, name=''):
@ -82,7 +82,7 @@ class ContextManager:
def remove_context(self, context_id): def remove_context(self, context_id):
"""Remove a specific context entry. """Remove a specific context entry.
Arguments: Args:
context_id (str): context entry to remove context_id (str): context entry to remove
""" """
self.frame_stack = [(f, t) for (f, t) in self.frame_stack self.frame_stack = [(f, t) for (f, t) in self.frame_stack
@ -201,7 +201,7 @@ class AdaptService:
def match_intent(self, utterances, _=None, __=None): def match_intent(self, utterances, _=None, __=None):
"""Run the Adapt engine to search for an matching intent. """Run the Adapt engine to search for an matching intent.
Arguments: Args:
utterances (iterable): iterable of utterances, expected order utterances (iterable): iterable of utterances, expected order
[raw, normalized, other] [raw, normalized, other]
@ -254,7 +254,7 @@ class AdaptService:
def register_intent(self, intent): def register_intent(self, intent):
"""Register new intent with adapt engine. """Register new intent with adapt engine.
Arguments: Args:
intent (IntentParser): IntentParser to register intent (IntentParser): IntentParser to register
""" """
with self.lock: with self.lock:
@ -263,7 +263,7 @@ class AdaptService:
def detach_skill(self, skill_id): def detach_skill(self, skill_id):
"""Remove all intents for skill. """Remove all intents for skill.
Arguments: Args:
skill_id (str): skill to process skill_id (str): skill to process
""" """
with self.lock: with self.lock:
@ -305,7 +305,7 @@ class AdaptService:
def detach_intent(self, intent_name): def detach_intent(self, intent_name):
"""Detatch a single intent """Detatch a single intent
Arguments: Args:
intent_name (str): Identifier for intent to remove. intent_name (str): Identifier for intent to remove.
""" """
new_parsers = [ new_parsers = [

View File

@ -27,7 +27,7 @@ class FallbackService:
def _fallback_range(self, utterances, lang, message, fb_range): def _fallback_range(self, utterances, lang, message, fb_range):
"""Send fallback request for a specified priority range. """Send fallback request for a specified priority range.
Arguments: Args:
utterances (list): List of tuples, utterances (list): List of tuples,
utterances and normalized version utterances and normalized version
lang (str): Langauge code lang (str): Langauge code

View File

@ -65,7 +65,7 @@ class PadatiousService:
def train(self, message=None): def train(self, message=None):
"""Perform padatious training. """Perform padatious training.
Arguments: Args:
message (Message): optional triggering message message (Message): optional triggering message
""" """
padatious_single_thread = Configuration.get()[ padatious_single_thread = Configuration.get()[
@ -102,7 +102,7 @@ class PadatiousService:
def __detach_intent(self, intent_name): def __detach_intent(self, intent_name):
""" Remove an intent if it has been registered. """ Remove an intent if it has been registered.
Arguments: Args:
intent_name (str): intent identifier intent_name (str): intent identifier
""" """
if intent_name in self.registered_intents: if intent_name in self.registered_intents:
@ -112,7 +112,7 @@ class PadatiousService:
def handle_detach_intent(self, message): def handle_detach_intent(self, message):
"""Messagebus handler for detaching padatious intent. """Messagebus handler for detaching padatious intent.
Arguments: Args:
message (Message): message triggering action message (Message): message triggering action
""" """
self.__detach_intent(message.data.get('intent_name')) self.__detach_intent(message.data.get('intent_name'))
@ -120,7 +120,7 @@ class PadatiousService:
def handle_detach_skill(self, message): def handle_detach_skill(self, message):
"""Messagebus handler for detaching all intents for skill. """Messagebus handler for detaching all intents for skill.
Arguments: Args:
message (Message): message triggering action message (Message): message triggering action
""" """
skill_id = message.data['skill_id'] skill_id = message.data['skill_id']
@ -131,7 +131,7 @@ class PadatiousService:
def _register_object(self, message, object_name, register_func): def _register_object(self, message, object_name, register_func):
"""Generic method for registering a padatious object. """Generic method for registering a padatious object.
Arguments: Args:
message (Message): trigger for action message (Message): trigger for action
object_name (str): type of entry to register object_name (str): type of entry to register
register_func (callable): function to call for registration register_func (callable): function to call for registration
@ -152,7 +152,7 @@ class PadatiousService:
def register_intent(self, message): def register_intent(self, message):
"""Messagebus handler for registering intents. """Messagebus handler for registering intents.
Arguments: Args:
message (Message): message triggering action message (Message): message triggering action
""" """
self.registered_intents.append(message.data['name']) self.registered_intents.append(message.data['name'])
@ -161,7 +161,7 @@ class PadatiousService:
def register_entity(self, message): def register_entity(self, message):
"""Messagebus handler for registering entities. """Messagebus handler for registering entities.
Arguments: Args:
message (Message): message triggering action message (Message): message triggering action
""" """
self.registered_entities.append(message.data) self.registered_entities.append(message.data)
@ -170,7 +170,7 @@ class PadatiousService:
def _match_level(self, utterances, limit): def _match_level(self, utterances, limit):
"""Match intent and make sure a certain level of confidence is reached. """Match intent and make sure a certain level of confidence is reached.
Arguments: Args:
utterances (list of tuples): Utterances to parse, originals paired utterances (list of tuples): Utterances to parse, originals paired
with optional normalized version. with optional normalized version.
limit (float): required confidence level. limit (float): required confidence level.
@ -199,7 +199,7 @@ class PadatiousService:
def match_high(self, utterances, _=None, __=None): def match_high(self, utterances, _=None, __=None):
"""Intent matcher for high confidence. """Intent matcher for high confidence.
Arguments: Args:
utterances (list of tuples): Utterances to parse, originals paired utterances (list of tuples): Utterances to parse, originals paired
with optional normalized version. with optional normalized version.
""" """
@ -208,7 +208,7 @@ class PadatiousService:
def match_medium(self, utterances, _=None, __=None): def match_medium(self, utterances, _=None, __=None):
"""Intent matcher for medium confidence. """Intent matcher for medium confidence.
Arguments: Args:
utterances (list of tuples): Utterances to parse, originals paired utterances (list of tuples): Utterances to parse, originals paired
with optional normalized version. with optional normalized version.
""" """
@ -217,7 +217,7 @@ class PadatiousService:
def match_low(self, utterances, _=None, __=None): def match_low(self, utterances, _=None, __=None):
"""Intent matcher for low confidence. """Intent matcher for low confidence.
Arguments: Args:
utterances (list of tuples): Utterances to parse, originals paired utterances (list of tuples): Utterances to parse, originals paired
with optional normalized version. with optional normalized version.
""" """
@ -234,7 +234,7 @@ class PadatiousService:
(PadatiousService), but we can live with that since it is used as a (PadatiousService), but we can live with that since it is used as a
singleton. singleton.
Arguments: Args:
utt (str): utterance to calculate best intent for utt (str): utterance to calculate best intent for
""" """
return self.container.calc_intent(utt) return self.container.calc_intent(utt)

View File

@ -9,7 +9,7 @@ from ..skill_data import to_alnum
def unmunge_message(message, skill_id): def unmunge_message(message, skill_id):
"""Restore message keywords by removing the Letterified skill ID. """Restore message keywords by removing the Letterified skill ID.
Arguments: Args:
message (Message): Intent result message message (Message): Intent result message
skill_id (str): skill identifier skill_id (str): skill identifier
Returns: Returns:
@ -29,7 +29,7 @@ def unmunge_message(message, skill_id):
def get_handler_name(handler): def get_handler_name(handler):
"""Name (including class if available) of handler function. """Name (including class if available) of handler function.
Arguments: Args:
handler (function): Function to be named handler (function): Function to be named
Returns: Returns:
@ -94,7 +94,7 @@ def create_basic_wrapper(handler, on_error=None):
This wrapper handles things like metrics, reporting handler start/stop This wrapper handles things like metrics, reporting handler start/stop
and errors. and errors.
Arguments: Args:
handler (callable): method/function to call handler (callable): method/function to call
on_error (function): function to call to report error. on_error (function): function to call to report error.
@ -130,7 +130,7 @@ class EventContainer:
def add(self, name, handler, once=False): def add(self, name, handler, once=False):
"""Create event handler for executing intent or other event. """Create event handler for executing intent or other event.
Arguments: Args:
name (string): IntentParser name name (string): IntentParser name
handler (func): Method to call handler (func): Method to call
once (bool, optional): Event handler will be removed after it has once (bool, optional): Event handler will be removed after it has

View File

@ -66,7 +66,7 @@ from ..skill_data import (
def simple_trace(stack_trace): def simple_trace(stack_trace):
"""Generate a simplified traceback. """Generate a simplified traceback.
Arguments: Args:
stack_trace: Stack trace to simplify stack_trace: Stack trace to simplify
Returns: (str) Simplified stack trace. Returns: (str) Simplified stack trace.
@ -84,8 +84,8 @@ def get_non_properties(obj):
Will return members of object class along with bases down to MycroftSkill. Will return members of object class along with bases down to MycroftSkill.
Arguments: Args:
obj: object to scan obj: object to scan
Returns: Returns:
Set of attributes that are not a property. Set of attributes that are not a property.
@ -111,7 +111,7 @@ class MycroftSkill:
For information on how to get started with creating mycroft skills see For information on how to get started with creating mycroft skills see
https://mycroft.ai/documentation/skills/introduction-developing-skills/ https://mycroft.ai/documentation/skills/introduction-developing-skills/
Arguments: Args:
name (str): skill name name (str): skill name
bus (MycroftWebsocketClient): Optional bus connection bus (MycroftWebsocketClient): Optional bus connection
use_settings (bool): Set to false to not use skill settings at all use_settings (bool): Set to false to not use skill settings at all
@ -247,7 +247,7 @@ class MycroftSkill:
def bind(self, bus): def bind(self, bus):
"""Register messagebus emitter with skill. """Register messagebus emitter with skill.
Arguments: Args:
bus: Mycroft messagebus connection bus: Mycroft messagebus connection
""" """
if bus: if bus:
@ -401,7 +401,7 @@ class MycroftSkill:
utterances and lang are depreciated utterances and lang are depreciated
Arguments: Args:
message: a message object containing a message type with an message: a message object containing a message type with an
optional JSON data packet optional JSON data packet
@ -442,19 +442,25 @@ class MycroftSkill:
The response can optionally be validated before returning. The response can optionally be validated before returning.
Example: Example::
color = self.get_response('ask.favorite.color') color = self.get_response('ask.favorite.color')
Arguments: Args:
dialog (str): Optional dialog to speak to the user dialog (str): Optional dialog to speak to the user
data (dict): Data used to render the dialog data (dict): Data used to render the dialog
validator (any): Function with following signature validator (any): Function with following signature::
def validator(utterance): def validator(utterance):
return utterance != "red" return utterance != "red"
on_fail (any): Dialog or function returning literal string
to speak on invalid input. For example: on_fail (any):
def on_fail(utterance): Dialog or function returning literal string to speak on
return "nobody likes the color red, pick another" invalid input. For example::
def on_fail(utterance):
return "nobody likes the color red, pick another"
num_retries (int): Times to ask user for input, -1 for infinite num_retries (int): Times to ask user for input, -1 for infinite
NOTE: User can not respond and timeout or say "cancel" to stop NOTE: User can not respond and timeout or say "cancel" to stop
@ -494,7 +500,7 @@ class MycroftSkill:
"""Loop until a valid response is received from the user or the retry """Loop until a valid response is received from the user or the retry
limit is reached. limit is reached.
Arguments: Args:
is_cancel (callable): function checking cancel criteria is_cancel (callable): function checking cancel criteria
validator (callbale): function checking for a valid response validator (callbale): function checking for a valid response
on_fail (callable): function handling retries on_fail (callable): function handling retries
@ -555,12 +561,13 @@ class MycroftSkill:
This automatically deals with fuzzy matching and selection by number This automatically deals with fuzzy matching and selection by number
e.g. e.g.
"first option"
"last option"
"second option"
"option number four"
Arguments: * "first option"
* "last option"
* "second option"
* "option number four"
Args:
options (list): list of options to present user options (list): list of options to present user
dialog (str): a dialog id or string to read AFTER all options dialog (str): a dialog id or string to read AFTER all options
data (dict): Data used to render the dialog data (dict): Data used to render the dialog
@ -616,7 +623,7 @@ class MycroftSkill:
in the "res/text" folder of mycroft-core. The result is cached to in the "res/text" folder of mycroft-core. The result is cached to
avoid hitting the disk each time the method is called. avoid hitting the disk each time the method is called.
Arguments: Args:
utt (str): Utterance to be tested utt (str): Utterance to be tested
voc_filename (str): Name of vocabulary file (e.g. 'yes' for voc_filename (str): Name of vocabulary file (e.g. 'yes' for
'res/text/en-us/yes.voc') 'res/text/en-us/yes.voc')
@ -656,7 +663,7 @@ class MycroftSkill:
def report_metric(self, name, data): def report_metric(self, name, data):
"""Report a skill metric to the Mycroft servers. """Report a skill metric to the Mycroft servers.
Arguments: Args:
name (str): Name of metric. Must use only letters and hyphens name (str): Name of metric. Must use only letters and hyphens
data (dict): JSON dictionary to report. Must be valid JSON data (dict): JSON dictionary to report. Must be valid JSON
""" """
@ -665,7 +672,7 @@ class MycroftSkill:
def send_email(self, title, body): def send_email(self, title, body):
"""Send an email to the registered user's email. """Send an email to the registered user's email.
Arguments: Args:
title (str): Title of email title (str): Title of email
body (str): HTML body of email. This supports body (str): HTML body of email. This supports
simple HTML like bold and italics simple HTML like bold and italics
@ -740,11 +747,12 @@ class MycroftSkill:
"""Load a translatable single string resource """Load a translatable single string resource
The string is loaded from a file in the skill's dialog subdirectory The string is loaded from a file in the skill's dialog subdirectory
'dialog/<lang>/<text>.dialog' 'dialog/<lang>/<text>.dialog'
The string is randomly chosen from the file and rendered, replacing The string is randomly chosen from the file and rendered, replacing
mustache placeholders with values found in the data dictionary. mustache placeholders with values found in the data dictionary.
Arguments: Args:
text (str): The base filename (no extension needed) text (str): The base filename (no extension needed)
data (dict, optional): a JSON dictionary data (dict, optional): a JSON dictionary
@ -754,18 +762,25 @@ class MycroftSkill:
return self.dialog_renderer.render(text, data or {}) return self.dialog_renderer.render(text, data or {})
def find_resource(self, res_name, res_dirname=None): def find_resource(self, res_name, res_dirname=None):
"""Find a resource file """Find a resource file.
Searches for the given filename using this scheme: Searches for the given filename using this scheme:
1) Search the resource lang directory:
<skill>/<res_dirname>/<lang>/<res_name>
2) Search the resource directory:
<skill>/<res_dirname>/<res_name>
3) Search the locale lang directory or other subdirectory:
<skill>/locale/<lang>/<res_name> or
<skill>/locale/<lang>/.../<res_name>
Arguments: 1. Search the resource lang directory:
<skill>/<res_dirname>/<lang>/<res_name>
2. Search the resource directory:
<skill>/<res_dirname>/<res_name>
3. Search the locale lang directory or other subdirectory:
<skill>/locale/<lang>/<res_name> or
<skill>/locale/<lang>/.../<res_name>
Args:
res_name (string): The resource name to be found res_name (string): The resource name to be found
res_dirname (string, optional): A skill resource directory, such res_dirname (string, optional): A skill resource directory, such
'dialog', 'vocab', 'regex' or 'ui'. 'dialog', 'vocab', 'regex' or 'ui'.
@ -814,7 +829,7 @@ class MycroftSkill:
The name is the first list item, the value is the The name is the first list item, the value is the
second. Lines prefixed with # or // get ignored second. Lines prefixed with # or // get ignored
Arguments: Args:
name (str): name of the .value file, no extension needed name (str): name of the .value file, no extension needed
delim (char): delimiter character used, default is ',' delim (char): delimiter character used, default is ','
@ -837,11 +852,12 @@ class MycroftSkill:
The strings are loaded from a template file in the skill's dialog The strings are loaded from a template file in the skill's dialog
subdirectory. subdirectory.
'dialog/<lang>/<template_name>.template' 'dialog/<lang>/<template_name>.template'
The strings are loaded and rendered, replacing mustache placeholders The strings are loaded and rendered, replacing mustache placeholders
with values found in the data dictionary. with values found in the data dictionary.
Arguments: Args:
template_name (str): The base filename (no extension needed) template_name (str): The base filename (no extension needed)
data (dict, optional): a JSON dictionary data (dict, optional): a JSON dictionary
@ -855,11 +871,12 @@ class MycroftSkill:
The strings are loaded from a list file in the skill's dialog The strings are loaded from a list file in the skill's dialog
subdirectory. subdirectory.
'dialog/<lang>/<list_name>.list' 'dialog/<lang>/<list_name>.list'
The strings are loaded and rendered, replacing mustache placeholders The strings are loaded and rendered, replacing mustache placeholders
with values found in the data dictionary. with values found in the data dictionary.
Arguments: Args:
list_name (str): The base filename (no extension needed) list_name (str): The base filename (no extension needed)
data (dict, optional): a JSON dictionary data (dict, optional): a JSON dictionary
@ -877,7 +894,7 @@ class MycroftSkill:
def add_event(self, name, handler, handler_info=None, once=False): def add_event(self, name, handler, handler_info=None, once=False):
"""Create event handler for executing intent or other event. """Create event handler for executing intent or other event.
Arguments: Args:
name (string): IntentParser name name (string): IntentParser name
handler (func): Method to call handler (func): Method to call
handler_info (string): Base message when reporting skill event handler_info (string): Base message when reporting skill event
@ -932,7 +949,7 @@ class MycroftSkill:
def _register_adapt_intent(self, intent_parser, handler): def _register_adapt_intent(self, intent_parser, handler):
"""Register an adapt intent. """Register an adapt intent.
Arguments: Args:
intent_parser: Intent object to parse utterance for the handler. intent_parser: Intent object to parse utterance for the handler.
handler (func): function to register with intent handler (func): function to register with intent
""" """
@ -947,7 +964,7 @@ class MycroftSkill:
def register_intent(self, intent_parser, handler): def register_intent(self, intent_parser, handler):
"""Register an Intent with the intent service. """Register an Intent with the intent service.
Arguments: Args:
intent_parser: Intent, IntentBuilder object or padatious intent intent_parser: Intent, IntentBuilder object or padatious intent
file to parse utterance for the handler. file to parse utterance for the handler.
handler (func): function to register with intent handler (func): function to register with intent
@ -983,7 +1000,7 @@ class MycroftSkill:
(Order | Grab) some {food} (from {place} | ). (Order | Grab) some {food} (from {place} | ).
I'm hungry. I'm hungry.
Arguments: Args:
intent_file: name of file that contains example queries intent_file: name of file that contains example queries
that should activate the intent. Must end with that should activate the intent. Must end with
'.intent' '.intent'
@ -1042,7 +1059,7 @@ class MycroftSkill:
def disable_intent(self, intent_name): def disable_intent(self, intent_name):
"""Disable a registered intent if it belongs to this skill. """Disable a registered intent if it belongs to this skill.
Arguments: Args:
intent_name (string): name of the intent to be disabled intent_name (string): name of the intent to be disabled
Returns: Returns:
@ -1061,7 +1078,7 @@ class MycroftSkill:
def enable_intent(self, intent_name): def enable_intent(self, intent_name):
"""(Re)Enable a registered intent if it belongs to this skill. """(Re)Enable a registered intent if it belongs to this skill.
Arguments: Args:
intent_name: name of the intent to be enabled intent_name: name of the intent to be enabled
Returns: Returns:
@ -1084,7 +1101,7 @@ class MycroftSkill:
def set_context(self, context, word='', origin=''): def set_context(self, context, word='', origin=''):
"""Add context to intent service """Add context to intent service
Arguments: Args:
context: Keyword context: Keyword
word: word connected to keyword word: word connected to keyword
origin: origin of context origin: origin of context
@ -1113,7 +1130,7 @@ class MycroftSkill:
def set_cross_skill_context(self, context, word=''): def set_cross_skill_context(self, context, word=''):
"""Tell all skills to add a context to intent service """Tell all skills to add a context to intent service
Arguments: Args:
context: Keyword context: Keyword
word: word connected to keyword word: word connected to keyword
""" """
@ -1138,7 +1155,7 @@ class MycroftSkill:
def register_vocabulary(self, entity, entity_type): def register_vocabulary(self, entity, entity_type):
""" Register a word to a keyword """ Register a word to a keyword
Arguments: Args:
entity: word to register entity: word to register
entity_type: Intent handler entity to tie the word to entity_type: Intent handler entity to tie the word to
""" """
@ -1148,7 +1165,7 @@ class MycroftSkill:
def register_regex(self, regex_str): def register_regex(self, regex_str):
"""Register a new regex. """Register a new regex.
Arguments: Args:
regex_str: Regex string regex_str: Regex string
""" """
self.log.debug('registering regex string: ' + regex_str) self.log.debug('registering regex string: ' + regex_str)
@ -1159,7 +1176,7 @@ class MycroftSkill:
def speak(self, utterance, expect_response=False, wait=False, meta=None): def speak(self, utterance, expect_response=False, wait=False, meta=None):
"""Speak a sentence. """Speak a sentence.
Arguments: Args:
utterance (str): sentence mycroft should speak utterance (str): sentence mycroft should speak
expect_response (bool): set to True if Mycroft should listen expect_response (bool): set to True if Mycroft should listen
for a response immediately after for a response immediately after
@ -1186,7 +1203,7 @@ class MycroftSkill:
def speak_dialog(self, key, data=None, expect_response=False, wait=False): def speak_dialog(self, key, data=None, expect_response=False, wait=False):
""" Speak a random sentence from a dialog file. """ Speak a random sentence from a dialog file.
Arguments: Args:
key (str): dialog file key (e.g. "hello" to speak from the file key (str): dialog file key (e.g. "hello" to speak from the file
"locale/en-us/hello.dialog") "locale/en-us/hello.dialog")
data (dict): information used to populate sentence data (dict): information used to populate sentence
@ -1241,7 +1258,7 @@ class MycroftSkill:
def load_data_files(self, root_directory=None): def load_data_files(self, root_directory=None):
"""Called by the skill loader to load intents, dialogs, etc. """Called by the skill loader to load intents, dialogs, etc.
Arguments: Args:
root_directory (str): root folder to use when loading files. root_directory (str): root folder to use when loading files.
""" """
root_directory = root_directory or self.root_dir root_directory = root_directory or self.root_dir
@ -1252,7 +1269,7 @@ class MycroftSkill:
def load_vocab_files(self, root_directory): def load_vocab_files(self, root_directory):
""" Load vocab files found under root_directory. """ Load vocab files found under root_directory.
Arguments: Args:
root_directory (str): root folder to use when loading files root_directory (str): root folder to use when loading files
""" """
keywords = [] keywords = []
@ -1277,7 +1294,7 @@ class MycroftSkill:
def load_regex_files(self, root_directory): def load_regex_files(self, root_directory):
""" Load regex files found under the skill directory. """ Load regex files found under the skill directory.
Arguments: Args:
root_directory (str): root folder to use when loading files root_directory (str): root folder to use when loading files
""" """
regexes = [] regexes = []
@ -1364,7 +1381,7 @@ class MycroftSkill:
context=None): context=None):
"""Schedule a single-shot event. """Schedule a single-shot event.
Arguments: Args:
handler: method to be called handler: method to be called
when (datetime/int/float): datetime (in system timezone) or when (datetime/int/float): datetime (in system timezone) or
number of seconds in the future when the number of seconds in the future when the
@ -1387,7 +1404,7 @@ class MycroftSkill:
data=None, name=None, context=None): data=None, name=None, context=None):
"""Schedule a repeating event. """Schedule a repeating event.
Arguments: Args:
handler: method to be called handler: method to be called
when (datetime): time (in system timezone) for first when (datetime): time (in system timezone) for first
calling the handler, or None to calling the handler, or None to
@ -1414,7 +1431,7 @@ class MycroftSkill:
def update_scheduled_event(self, name, data=None): def update_scheduled_event(self, name, data=None):
"""Change data of event. """Change data of event.
Arguments: Args:
name (str): reference name of event (from original scheduling) name (str): reference name of event (from original scheduling)
data (dict): event data data (dict): event data
""" """
@ -1424,7 +1441,7 @@ class MycroftSkill:
"""Cancel a pending event. The event will no longer be scheduled """Cancel a pending event. The event will no longer be scheduled
to be executed to be executed
Arguments: Args:
name (str): reference name of event (from original scheduling) name (str): reference name of event (from original scheduling)
""" """
return self.event_scheduler.cancel_scheduled_event(name) return self.event_scheduler.cancel_scheduled_event(name)
@ -1432,7 +1449,7 @@ class MycroftSkill:
def get_scheduled_event_status(self, name): def get_scheduled_event_status(self, name):
"""Get scheduled event data and return the amount of time left """Get scheduled event data and return the amount of time left
Arguments: Args:
name (str): reference name of event (from original scheduling) name (str): reference name of event (from original scheduling)
Returns: Returns:

View File

@ -335,7 +335,7 @@ def load_remote_settings_cache():
def save_remote_settings_cache(remote_settings): def save_remote_settings_cache(remote_settings):
"""Save updated remote settings to cache file. """Save updated remote settings to cache file.
Arguments: Args:
remote_settings (dict): downloaded remote settings. remote_settings (dict): downloaded remote settings.
""" """
try: try:

View File

@ -32,7 +32,7 @@ def read_vocab_file(path):
parentheses. It returns each line as a list of all expanded parentheses. It returns each line as a list of all expanded
alternatives. alternatives.
Arguments: Args:
path (str): path to vocab file. path (str): path to vocab file.
Returns: Returns:
@ -74,7 +74,7 @@ def load_regex_from_file(path, skill_id):
def load_vocabulary(basedir, skill_id): def load_vocabulary(basedir, skill_id):
"""Load vocabulary from all files in the specified directory. """Load vocabulary from all files in the specified directory.
Arguments: Args:
basedir (str): path of directory to load from (will recurse) basedir (str): path of directory to load from (will recurse)
skill_id: skill the data belongs to skill_id: skill the data belongs to
Returns: Returns:
@ -189,7 +189,7 @@ def read_value_file(filename, delim):
The value file is a simple csv structure with a key and value. The value file is a simple csv structure with a key and value.
Arguments: Args:
filename (str): file to read filename (str): file to read
delim (str): csv delimiter delim (str): csv delimiter
@ -215,7 +215,7 @@ def read_value_file(filename, delim):
def read_translated_file(filename, data): def read_translated_file(filename, data):
"""Read a file inserting data. """Read a file inserting data.
Arguments: Args:
filename (str): file to read filename (str): file to read
data (dict): dictionary with data to insert into file data (dict): dictionary with data to insert into file

View File

@ -37,7 +37,7 @@ def remove_submodule_refs(module_name):
dictionary to bypass loading if a module is already in memory. To make dictionary to bypass loading if a module is already in memory. To make
sure skills are completely reloaded these references are deleted. sure skills are completely reloaded these references are deleted.
Arguments: Args:
module_name: name of skill module. module_name: name of skill module.
""" """
submodules = [] submodules = []
@ -58,7 +58,7 @@ def load_skill_module(path, skill_id):
This function handles the differences between python 3.4 and 3.5+ as well This function handles the differences between python 3.4 and 3.5+ as well
as makes sure the module is inserted into the sys.modules dict. as makes sure the module is inserted into the sys.modules dict.
Arguments: Args:
path: Path to the skill main file (__init__.py) path: Path to the skill main file (__init__.py)
skill_id: skill_id used as skill identifier in the module list skill_id: skill_id used as skill identifier in the module list
""" """
@ -76,7 +76,7 @@ def load_skill_module(path, skill_id):
def _bad_mod_times(mod_times): def _bad_mod_times(mod_times):
"""Return all entries with modification time in the future. """Return all entries with modification time in the future.
Arguments: Args:
mod_times (dict): dict mapping file paths to modification times. mod_times (dict): dict mapping file paths to modification times.
Returns: Returns:
@ -92,7 +92,7 @@ def _get_last_modified_time(path):
Exclude compiled python files, hidden directories and the settings.json Exclude compiled python files, hidden directories and the settings.json
file. file.
Arguments: Args:
path: skill directory to check path: skill directory to check
Returns: Returns:

View File

@ -92,7 +92,7 @@ def _shutdown_skill(instance):
Call the default_shutdown method of the skill, will produce a warning if Call the default_shutdown method of the skill, will produce a warning if
the shutdown process takes longer than 1 second. the shutdown process takes longer than 1 second.
Arguments: Args:
instance (MycroftSkill): Skill instance to shutdown instance (MycroftSkill): Skill instance to shutdown
""" """
try: try:
@ -115,7 +115,7 @@ class SkillManager(Thread):
def __init__(self, bus, watchdog=None): def __init__(self, bus, watchdog=None):
"""Constructor """Constructor
Arguments: Args:
bus (event emitter): Mycroft messagebus connection bus (event emitter): Mycroft messagebus connection
watchdog (callable): optional watchdog function watchdog (callable): optional watchdog function
""" """

View File

@ -56,7 +56,7 @@ class STT(metaclass=ABCMeta):
The method gets passed audio and optionally a language code and is The method gets passed audio and optionally a language code and is
expected to return a text string. expected to return a text string.
Arguments: Args:
audio (AudioData): audio recorded by mycroft. audio (AudioData): audio recorded by mycroft.
language (str): optional language code language (str): optional language code
@ -342,7 +342,7 @@ class StreamThread(Thread, metaclass=ABCMeta):
This class reads audio chunks from a queue and sends it to a parsing This class reads audio chunks from a queue and sends it to a parsing
STT engine. STT engine.
Arguments: Args:
queue (Queue): Input Queue queue (Queue): Input Queue
language (str): language code for the current language. language (str): language code for the current language.
""" """
@ -392,7 +392,7 @@ class StreamingSTT(STT, metaclass=ABCMeta):
This creates a new thread for handling the incomming audio stream as This creates a new thread for handling the incomming audio stream as
it's collected by Mycroft. it's collected by Mycroft.
Arguments: Args:
language (str): optional language code for the new stream. language (str): optional language code for the new stream.
""" """
self.stream_stop() self.stream_stop()
@ -404,7 +404,7 @@ class StreamingSTT(STT, metaclass=ABCMeta):
def stream_data(self, data): def stream_data(self, data):
"""Receiver of audio data. """Receiver of audio data.
Arguments: Args:
data (bytes): raw audio data. data (bytes): raw audio data.
""" """
self.queue.put(data) self.queue.put(data)
@ -607,7 +607,7 @@ class GoVivaceSTT(TokenSTT):
def load_stt_plugin(module_name): def load_stt_plugin(module_name):
"""Wrapper function for loading stt plugin. """Wrapper function for loading stt plugin.
Arguments: Args:
module_name (str): Mycroft stt module name from config module_name (str): Mycroft stt module name from config
Returns: Returns:
class: STT plugin class class: STT plugin class

View File

@ -46,7 +46,7 @@ from mycroft.util.log import LOG
def _get_mimic2_audio(sentence: str, url: str) -> Tuple[bytes, str]: def _get_mimic2_audio(sentence: str, url: str) -> Tuple[bytes, str]:
"""Use the Mimic2 API to retrieve the audio for a sentence. """Use the Mimic2 API to retrieve the audio for a sentence.
Arguments: Args:
sentence: The sentence to be cached sentence: The sentence to be cached
""" """
LOG.debug("Retrieving Mimic2 audio for sentence \"{}\'".format(sentence)) LOG.debug("Retrieving Mimic2 audio for sentence \"{}\'".format(sentence))
@ -62,7 +62,7 @@ def _get_mimic2_audio(sentence: str, url: str) -> Tuple[bytes, str]:
def hash_sentence(sentence: str): def hash_sentence(sentence: str):
"""Convert the sentence into a hash value used for the file name """Convert the sentence into a hash value used for the file name
Arguments: Args:
sentence: The sentence to be cached sentence: The sentence to be cached
""" """
encoded_sentence = sentence.encode("utf-8", "ignore") encoded_sentence = sentence.encode("utf-8", "ignore")
@ -76,7 +76,7 @@ def hash_from_path(path: Path) -> str:
Simply removes extension and folder structure leaving the hash. Simply removes extension and folder structure leaving the hash.
Arguments: Args:
path: path to get hash from path: path to get hash from
Returns: Returns:
@ -93,7 +93,7 @@ class AudioFile:
def save(self, audio: bytes): def save(self, audio: bytes):
"""Write a TTS cache file containing the audio to be spoken. """Write a TTS cache file containing the audio to be spoken.
Arguments: Args:
audio: TTS inference of a sentence audio: TTS inference of a sentence
""" """
try: try:
@ -123,7 +123,7 @@ class PhonemeFile:
def save(self, phonemes): def save(self, phonemes):
"""Write a TTS cache file containing the phoneme to be displayed. """Write a TTS cache file containing the phoneme to be displayed.
Arguments: Args:
phonemes: instructions for how to make the mouth on a device move phonemes: instructions for how to make the mouth on a device move
""" """
try: try:
@ -228,7 +228,7 @@ class TextToSpeechCache:
punctuation punctuation
example : <<< LOADING <<< example : <<< LOADING <<<
Arguments: Args:
dialogs: a list of the records in the dialog resource files dialogs: a list of the records in the dialog resource files
""" """
sentences = set() sentences = set()

View File

@ -25,7 +25,7 @@ class ESpeak(TTS):
def get_tts(self, sentence, wav_file): def get_tts(self, sentence, wav_file):
"""Generate WAV from sentence, phonemes aren't supported. """Generate WAV from sentence, phonemes aren't supported.
Arguments: Args:
sentence (str): sentence to generate audio for sentence (str): sentence to generate audio for
wav_file (str): output file wav_file (str): output file

View File

@ -85,7 +85,7 @@ class GoogleTTS(TTS):
def get_tts(self, sentence, wav_file): def get_tts(self, sentence, wav_file):
"""Fetch tts audio using gTTS. """Fetch tts audio using gTTS.
Arguments: Args:
sentence (str): Sentence to generate audio for sentence (str): Sentence to generate audio for
wav_file (str): output file path wav_file (str): output file path
Returns: Returns:

View File

@ -38,7 +38,7 @@ _max_sentence_size = 170
def _break_chunks(l, n): def _break_chunks(l, n):
"""Yield successive n-sized chunks """Yield successive n-sized chunks
Arguments: Args:
l (list): text (str) to split l (list): text (str) to split
chunk_size (int): chunk size chunk_size (int): chunk size
""" """
@ -49,7 +49,7 @@ def _break_chunks(l, n):
def _split_by_chunk_size(text, chunk_size): def _split_by_chunk_size(text, chunk_size):
"""Split text into word chunks by chunk_size size """Split text into word chunks by chunk_size size
Arguments: Args:
text (str): text to split text (str): text to split
chunk_size (int): chunk size chunk_size (int): chunk size
@ -87,7 +87,7 @@ def _split_by_punctuation(chunks, puncs):
"""Splits text by various punctionations """Splits text by various punctionations
e.g. hello, world => [hello, world] e.g. hello, world => [hello, world]
Arguments: Args:
chunks (list or str): text (str) to split chunks (list or str): text (str) to split
puncs (list): list of punctuations used to split text puncs (list): list of punctuations used to split text
@ -128,7 +128,7 @@ def _sentence_chunker(text):
NOTE: The smaller chunks are needed due to current Mimic2 TTS limitations. NOTE: The smaller chunks are needed due to current Mimic2 TTS limitations.
This stage can be removed once Mimic2 can generate longer sentences. This stage can be removed once Mimic2 can generate longer sentences.
Arguments: Args:
text (str): text to split text (str): text to split
chunk_size (int): size of each chunk chunk_size (int): size of each chunk
split_by_punc (bool, optional): Defaults to True. split_by_punc (bool, optional): Defaults to True.
@ -176,7 +176,7 @@ class Mimic2(TTS):
def _requests(self, sentence): def _requests(self, sentence):
"""Create asynchronous request list """Create asynchronous request list
Arguments: Args:
chunks (list): list of text to synthesize chunks (list): list of text to synthesize
Returns: Returns:
@ -189,7 +189,7 @@ class Mimic2(TTS):
def viseme(self, phonemes): def viseme(self, phonemes):
"""Maps phonemes to appropriate viseme encoding """Maps phonemes to appropriate viseme encoding
Arguments: Args:
phonemes (list): list of tuples (phoneme, time_start) phonemes (list): list of tuples (phoneme, time_start)
Returns: Returns:
@ -216,7 +216,7 @@ class Mimic2(TTS):
def get_tts(self, sentence, wav_file): def get_tts(self, sentence, wav_file):
"""Generate (remotely) and play mimic2 WAV audio """Generate (remotely) and play mimic2 WAV audio
Arguments: Args:
sentence (str): Phrase to synthesize to audio with mimic2 sentence (str): Phrase to synthesize to audio with mimic2
wav_file (str): Location to write audio output wav_file (str): Location to write audio output
""" """
@ -240,7 +240,7 @@ class Mimic2(TTS):
def save_phonemes(self, key, phonemes): def save_phonemes(self, key, phonemes):
"""Cache phonemes """Cache phonemes
Arguments: Args:
key: Hash key for the sentence key: Hash key for the sentence
phonemes: phoneme string to save phonemes: phoneme string to save
""" """
@ -255,7 +255,7 @@ class Mimic2(TTS):
def load_phonemes(self, key): def load_phonemes(self, key):
"""Load phonemes from cache file. """Load phonemes from cache file.
Arguments: Args:
Key: Key identifying phoneme cache Key: Key identifying phoneme cache
""" """
pho_file = os.path.join(get_cache_directory("tts/" + self.tts_name), pho_file = os.path.join(get_cache_directory("tts/" + self.tts_name),

View File

@ -182,7 +182,7 @@ class Mimic(TTS):
def get_tts(self, sentence, wav_file): def get_tts(self, sentence, wav_file):
"""Generate WAV and phonemes. """Generate WAV and phonemes.
Arguments: Args:
sentence (str): sentence to generate audio for sentence (str): sentence to generate audio for
wav_file (str): output file wav_file (str): output file
@ -196,7 +196,7 @@ class Mimic(TTS):
def viseme(self, phoneme_pairs): def viseme(self, phoneme_pairs):
"""Convert phoneme string to visemes. """Convert phoneme string to visemes.
Arguments: Args:
phoneme_pairs (list): Phoneme output from mimic phoneme_pairs (list): Phoneme output from mimic
Returns: Returns:

View File

@ -128,7 +128,7 @@ class PlaybackThread(Thread):
def show_visemes(self, pairs): def show_visemes(self, pairs):
"""Send viseme data to enclosure """Send viseme data to enclosure
Arguments: Args:
pairs (list): Visime and timing pair pairs (list): Visime and timing pair
Returns: Returns:
@ -158,7 +158,7 @@ class TTS(metaclass=ABCMeta):
It aggregates the minimum required parameters and exposes It aggregates the minimum required parameters and exposes
``execute(sentence)`` and ``validate_ssml(sentence)`` functions. ``execute(sentence)`` and ``validate_ssml(sentence)`` functions.
Arguments: Args:
lang (str): lang (str):
config (dict): Configuration for this specific tts engine config (dict): Configuration for this specific tts engine
validator (TTSValidator): Used to verify proper installation validator (TTSValidator): Used to verify proper installation
@ -219,7 +219,7 @@ class TTS(metaclass=ABCMeta):
if it has been requested. It also checks if cache directory needs if it has been requested. It also checks if cache directory needs
cleaning to free up disk space. cleaning to free up disk space.
Arguments: Args:
listen (bool): indication if listening trigger should be sent. listen (bool): indication if listening trigger should be sent.
""" """
@ -234,7 +234,7 @@ class TTS(metaclass=ABCMeta):
def init(self, bus): def init(self, bus):
"""Performs intial setup of TTS object. """Performs intial setup of TTS object.
Arguments: Args:
bus: Mycroft messagebus connection bus: Mycroft messagebus connection
""" """
self.bus = bus self.bus = bus
@ -247,7 +247,7 @@ class TTS(metaclass=ABCMeta):
Should get data from tts. Should get data from tts.
Arguments: Args:
sentence(str): Sentence to synthesize sentence(str): Sentence to synthesize
wav_file(str): output file wav_file(str): output file
@ -259,7 +259,7 @@ class TTS(metaclass=ABCMeta):
def modify_tag(self, tag): def modify_tag(self, tag):
"""Override to modify each supported ssml tag. """Override to modify each supported ssml tag.
Arguments: Args:
tag (str): SSML tag to check and possibly transform. tag (str): SSML tag to check and possibly transform.
""" """
return tag return tag
@ -268,7 +268,7 @@ class TTS(metaclass=ABCMeta):
def remove_ssml(text): def remove_ssml(text):
"""Removes SSML tags from a string. """Removes SSML tags from a string.
Arguments: Args:
text (str): input string text (str): input string
Returns: Returns:
@ -281,7 +281,7 @@ class TTS(metaclass=ABCMeta):
Remove unsupported / invalid tags Remove unsupported / invalid tags
Arguments: Args:
utterance (str): Sentence to validate utterance (str): Sentence to validate
Returns: Returns:
@ -310,7 +310,7 @@ class TTS(metaclass=ABCMeta):
This method can be overridden to create chunks suitable to the This method can be overridden to create chunks suitable to the
TTS engine in question. TTS engine in question.
Arguments: Args:
sentence (str): sentence to preprocess sentence (str): sentence to preprocess
Returns: Returns:
@ -324,7 +324,7 @@ class TTS(metaclass=ABCMeta):
The method caches results if possible using the hash of the The method caches results if possible using the hash of the
sentence. sentence.
Arguments: Args:
sentence: (str) Sentence to be spoken sentence: (str) Sentence to be spoken
ident: (str) Id reference to current interaction ident: (str) Id reference to current interaction
listen: (bool) True if listen should be triggered at the end listen: (bool) True if listen should be triggered at the end
@ -399,7 +399,7 @@ class TTS(metaclass=ABCMeta):
May be implemented to convert TTS phonemes into Mycroft mouth May be implemented to convert TTS phonemes into Mycroft mouth
visuals. visuals.
Arguments: Args:
phonemes (str): String with phoneme data phonemes (str): String with phoneme data
Returns: Returns:
@ -427,7 +427,7 @@ class TTS(metaclass=ABCMeta):
def save_phonemes(self, key, phonemes): def save_phonemes(self, key, phonemes):
"""Cache phonemes """Cache phonemes
Arguments: Args:
key (str): Hash key for the sentence key (str): Hash key for the sentence
phonemes (str): phoneme string to save phonemes (str): phoneme string to save
""" """
@ -445,7 +445,7 @@ class TTS(metaclass=ABCMeta):
def load_phonemes(self, key): def load_phonemes(self, key):
"""Load phonemes from cache file. """Load phonemes from cache file.
Arguments: Args:
key (str): Key identifying phoneme cache key (str): Key identifying phoneme cache
""" """
# TODO: remove in 21.08 # TODO: remove in 21.08
@ -522,7 +522,7 @@ class TTSValidator(metaclass=ABCMeta):
def load_tts_plugin(module_name): def load_tts_plugin(module_name):
"""Wrapper function for loading tts plugin. """Wrapper function for loading tts plugin.
Arguments: Args:
(str) Mycroft tts module name from config (str) Mycroft tts module name from config
Returns: Returns:
class: found tts plugin class class: found tts plugin class

View File

@ -32,7 +32,7 @@ def play_audio_file(uri: str, environment=None):
the file extension. The function will return directly and play the file the file extension. The function will return directly and play the file
in the background. in the background.
Arguments: Args:
uri: uri to play uri: uri to play
environment (dict): optional environment for the subprocess call environment (dict): optional environment for the subprocess call
@ -75,7 +75,7 @@ def _get_pulse_environment(config):
def _play_cmd(cmd, uri, config, environment): def _play_cmd(cmd, uri, config, environment):
"""Generic function for starting playback from a commandline and uri. """Generic function for starting playback from a commandline and uri.
Arguments: Args:
cmd (str): commandline to execute %1 in the command line will be cmd (str): commandline to execute %1 in the command line will be
replaced with the provided uri. replaced with the provided uri.
uri (str): uri to play uri (str): uri to play
@ -96,7 +96,7 @@ def play_wav(uri, environment=None):
and play the uri passed as argument. The function will return directly and play the uri passed as argument. The function will return directly
and play the file in the background. and play the file in the background.
Arguments: Args:
uri: uri to play uri: uri to play
environment (dict): optional environment for the subprocess call environment (dict): optional environment for the subprocess call
@ -121,7 +121,7 @@ def play_mp3(uri, environment=None):
and play the uri passed as argument. The function will return directly and play the uri passed as argument. The function will return directly
and play the file in the background. and play the file in the background.
Arguments: Args:
uri: uri to play uri: uri to play
environment (dict): optional environment for the subprocess call environment (dict): optional environment for the subprocess call
@ -146,7 +146,7 @@ def play_ogg(uri, environment=None):
and play the uri passed as argument. The function will return directly and play the uri passed as argument. The function will return directly
and play the file in the background. and play the file in the background.
Arguments: Args:
uri: uri to play uri: uri to play
environment (dict): optional environment for the subprocess call environment (dict): optional environment for the subprocess call
@ -170,7 +170,7 @@ def record(file_path, duration, rate, channels):
The recording is done in the background by the arecord commandline The recording is done in the background by the arecord commandline
application. application.
Arguments: Args:
file_path: where to store the recorded data file_path: where to store the recorded data
duration: how long to record duration: how long to record
rate: sample rate rate: sample rate
@ -188,7 +188,7 @@ def record(file_path, duration, rate, channels):
def find_input_device(device_name): def find_input_device(device_name):
"""Find audio input device by name. """Find audio input device by name.
Arguments: Args:
device_name: device name or regex pattern to match device_name: device name or regex pattern to match
Returns: device_index (int) or None if device wasn't found Returns: device_index (int) or None if device wasn't found

View File

@ -21,7 +21,7 @@ from os import chmod
class ComboLock: class ComboLock:
""" A combined process and thread lock. """ A combined process and thread lock.
Arguments: Args:
path (str): path to the lockfile for the lock path (str): path to the lockfile for the lock
""" """
def __init__(self, path): def __init__(self, path):
@ -37,7 +37,7 @@ class ComboLock:
def acquire(self, blocking=True): def acquire(self, blocking=True):
""" Acquire lock, locks thread and process lock. """ Acquire lock, locks thread and process lock.
Arguments: Args:
blocking(bool): Set's blocking mode of acquire operation. blocking(bool): Set's blocking mode of acquire operation.
Default True. Default True.

View File

@ -31,7 +31,7 @@ _running_downloads = {} # Cache of running downloads
def _get_download_tmp(dest): def _get_download_tmp(dest):
"""Get temporary file for download. """Get temporary file for download.
Arguments: Args:
dest (str): path to download location dest (str): path to download location
Returns: Returns:
@ -55,7 +55,7 @@ class Downloader(Thread):
be set to true and the `.status` will indicate the HTTP status code. be set to true and the `.status` will indicate the HTTP status code.
200 = Success. 200 = Success.
Arguments: Args:
url (str): Url to download url (str): Url to download
dest (str): Path to save data to dest (str): Path to save data to
complete_action (callable): Function to run when download is complete complete_action (callable): Function to run when download is complete
@ -83,7 +83,7 @@ class Downloader(Thread):
def perform_download(self, dest): def perform_download(self, dest):
"""Handle the download through wget. """Handle the download through wget.
Arguments: Args:
dest (str): Save location dest (str): Save location
""" """
cmd = ['wget', '-c', self.url, '-O', dest, cmd = ['wget', '-c', self.url, '-O', dest,
@ -113,7 +113,7 @@ class Downloader(Thread):
Move the .part file to the final destination and perform any Move the .part file to the final destination and perform any
actions that should be performed at completion. actions that should be performed at completion.
Arguments: Args:
tmp(str): temporary file path tmp(str): temporary file path
""" """
os.rename(tmp, self.dest) os.rename(tmp, self.dest)
@ -135,7 +135,7 @@ class Downloader(Thread):
def download(url, dest, complete_action=None, header=None): def download(url, dest, complete_action=None, header=None):
"""Start a download or fetch an already running. """Start a download or fetch an already running.
Arguments: Args:
url (str): url to download url (str): url to download
dest (str): path to save download to dest (str): path to save download to
complete_action (callable): Optional function to call on completion complete_action (callable): Optional function to call on completion

View File

@ -39,15 +39,18 @@ def resolve_resource_file(res_name):
folder of the source code package. folder of the source code package.
Example: Example:
With mycroft running as the user 'bob', if you called With mycroft running as the user 'bob', if you called
resolve_resource_file('snd/beep.wav') ``resolve_resource_file('snd/beep.wav')``
it would return either '/home/bob/.mycroft/snd/beep.wav' or it would return either:
'/opt/mycroft/snd/beep.wav' or '.../mycroft/res/snd/beep.wav', '/home/bob/.mycroft/snd/beep.wav' or
where the '...' is replaced by the path where the package has '/opt/mycroft/snd/beep.wav' or
been installed. '.../mycroft/res/snd/beep.wav'
where the '...' is replaced by the path
where the package has been installed.
Arguments: Args:
res_name (str): a resource path/name res_name (str): a resource path/name
Returns: Returns:
(str) path to resource or None if no resource found (str) path to resource or None if no resource found
""" """
@ -80,7 +83,7 @@ def resolve_resource_file(res_name):
def read_stripped_lines(filename): def read_stripped_lines(filename):
"""Read a file and return a list of stripped lines. """Read a file and return a list of stripped lines.
Arguments: Args:
filename (str): path to file to read. filename (str): path to file to read.
Returns: Returns:
@ -106,7 +109,7 @@ def read_dict(filename, div='='):
'baz': 'bog' 'baz': 'bog'
} }
Arguments: Args:
filename (str): path to file filename (str): path to file
div (str): deviders between dict keys and values div (str): deviders between dict keys and values
@ -124,7 +127,7 @@ def read_dict(filename, div='='):
def mb_to_bytes(size): def mb_to_bytes(size):
"""Takes a size in MB and returns the number of bytes. """Takes a size in MB and returns the number of bytes.
Arguments: Args:
size(int/float): size in Mega Bytes size(int/float): size in Mega Bytes
Returns: Returns:
@ -136,7 +139,7 @@ def mb_to_bytes(size):
def _get_cache_entries(directory): def _get_cache_entries(directory):
"""Get information tuple for all regular files in directory. """Get information tuple for all regular files in directory.
Arguments: Args:
directory (str): path to directory to check directory (str): path to directory to check
Returns: Returns:
@ -153,7 +156,7 @@ def _get_cache_entries(directory):
def _delete_oldest(entries, bytes_needed): def _delete_oldest(entries, bytes_needed):
"""Delete files with oldest modification date until space is freed. """Delete files with oldest modification date until space is freed.
Arguments: Args:
entries (tuple): file + file stats tuple entries (tuple): file + file stats tuple
bytes_needed (int): disk space that needs to be freed bytes_needed (int): disk space that needs to be freed
@ -183,7 +186,7 @@ def curate_cache(directory, min_free_percent=5.0, min_free_disk=50):
is below the limit. This assumes all the files in the directory can be is below the limit. This assumes all the files in the directory can be
deleted as freely. deleted as freely.
Arguments: Args:
directory (str): directory path that holds cached files directory (str): directory path that holds cached files
min_free_percent (float): percentage (0.0-100.0) of drive to keep free, min_free_percent (float): percentage (0.0-100.0) of drive to keep free,
default is 5% if not specified. default is 5% if not specified.
@ -221,7 +224,7 @@ def get_cache_directory(domain=None):
uses these cached files must be able to fallback and regenerate uses these cached files must be able to fallback and regenerate
the file. the file.
Arguments: Args:
domain (str): The cache domain. Basically just a subdirectory. domain (str): The cache domain. Basically just a subdirectory.
Returns: Returns:
@ -238,7 +241,7 @@ def get_cache_directory(domain=None):
def ensure_directory_exists(directory, domain=None, permissions=0o777): def ensure_directory_exists(directory, domain=None, permissions=0o777):
"""Create a directory and give access rights to all """Create a directory and give access rights to all
Arguments: Args:
directory (str): Root directory directory (str): Root directory
domain (str): Domain. Basically a subdirectory to prevent things like domain (str): Domain. Basically a subdirectory to prevent things like
overlapping signal filenames. overlapping signal filenames.
@ -269,7 +272,7 @@ def ensure_directory_exists(directory, domain=None, permissions=0o777):
def create_file(filename): def create_file(filename):
"""Create the file filename and create any directories needed """Create the file filename and create any directories needed
Arguments: Args:
filename: Path to the file to be created filename: Path to the file to be created
""" """
ensure_directory_exists(os.path.dirname(filename), permissions=0o775) ensure_directory_exists(os.path.dirname(filename), permissions=0o775)

View File

@ -61,8 +61,9 @@ class TimeResolution(Enum):
def _duration_handler(time1, lang=None, speech=True, *, time2=None, def _duration_handler(time1, lang=None, speech=True, *, time2=None,
use_years=True, clock=False, use_years=True, clock=False,
resolution=TimeResolution.SECONDS): resolution=TimeResolution.SECONDS):
""" Convert duration in seconds to a nice spoken timespan """Convert duration in seconds to a nice spoken timespan.
Used as a handler by nice_duration and nice_duration_dt
Used as a handler by nice_duration and nice_duration_dt.
Accepts: Accepts:
datetime.timedelta, or datetime.timedelta, or
@ -323,6 +324,7 @@ def nice_duration(duration, lang=None, speech=True, use_years=True,
TimeResolution.MINUTES TimeResolution.MINUTES
TimeResolution.SECONDS TimeResolution.SECONDS
TimeResolution.MILLISECONDS TimeResolution.MILLISECONDS
NOTE: nice_duration will not produce milliseconds NOTE: nice_duration will not produce milliseconds
unless that resolution is passed. unless that resolution is passed.

View File

@ -37,7 +37,7 @@ class MonotonicEvent(Event):
Repeatingly wait as long the event hasn't been set and the Repeatingly wait as long the event hasn't been set and the
monotonic time doesn't indicate a timeout. monotonic time doesn't indicate a timeout.
Arguments: Args:
timeout: timeout of wait in seconds timeout: timeout of wait in seconds
Returns: Returns:

View File

@ -49,7 +49,7 @@ def _log_unsupported_language(language, supported_languages):
""" """
Log a warning when a language is unsupported Log a warning when a language is unsupported
Arguments: Args:
language: str language: str
The language that was supplied. The language that was supplied.
supported_languages: [str] supported_languages: [str]
@ -70,10 +70,13 @@ def extract_datetime(text, anchorDate="DEFAULT", lang=None,
"Tuesday". "Tuesday".
Vague terminology are given arbitrary values, like: Vague terminology are given arbitrary values, like:
- morning = 8 AM
- afternoon = 3 PM * morning = 8 AM
- evening = 7 PM * afternoon = 3 PM
* evening = 7 PM
If a time isn't supplied or implied, the function defaults to 12 AM If a time isn't supplied or implied, the function defaults to 12 AM
Args: Args:
text (str): the text to be interpreted text (str): the text to be interpreted
anchorDate (:obj:`datetime`, optional): the date to be used for anchorDate (:obj:`datetime`, optional): the date to be used for
@ -82,6 +85,7 @@ def extract_datetime(text, anchorDate="DEFAULT", lang=None,
lang (str): the BCP-47 code for the language to use, None uses default lang (str): the BCP-47 code for the language to use, None uses default
default_time (datetime.time): time to use if none was found in default_time (datetime.time): time to use if none was found in
the input string. the input string.
Returns: Returns:
[:obj:`datetime`, :obj:`str`]: 'datetime' is the extracted date [:obj:`datetime`, :obj:`str`]: 'datetime' is the extracted date
as a datetime object in the user's local timezone. as a datetime object in the user's local timezone.

View File

@ -22,7 +22,7 @@ from .log import LOG
def find_plugins(plug_type): def find_plugins(plug_type):
"""Finds all plugins matching specific entrypoint type. """Finds all plugins matching specific entrypoint type.
Arguments: Args:
plug_type (str): plugin entrypoint string to retrieve plug_type (str): plugin entrypoint string to retrieve
Returns: Returns:
@ -38,7 +38,7 @@ def find_plugins(plug_type):
def load_plugin(plug_type, plug_name): def load_plugin(plug_type, plug_name):
"""Load a specific plugin from a specific plugin type. """Load a specific plugin from a specific plugin type.
Arguments: Args:
plug_type: (str) plugin type name. Ex. "mycroft.plugin.tts". plug_type: (str) plugin type name. Ex. "mycroft.plugin.tts".
plug_name: (str) specific plugin name plug_name: (str) specific plugin name

View File

@ -47,7 +47,7 @@ def bus_logging_status():
def _update_log_level(msg, name): def _update_log_level(msg, name):
"""Update log level for process. """Update log level for process.
Arguments: Args:
msg (Message): Message sent to trigger the log level change msg (Message): Message sent to trigger the log level change
name (str): Name of the current process name (str): Name of the current process
""" """
@ -80,7 +80,7 @@ def create_echo_function(name, whitelist=None):
messagebus-based processes. messagebus-based processes.
TODO 20.08: extract log level setting thing completely from this function TODO 20.08: extract log level setting thing completely from this function
Arguments: Args:
name (str): Reference name of the process name (str): Reference name of the process
whitelist (list, optional): List of "type" strings. If defined, only whitelist (list, optional): List of "type" strings. If defined, only
messages in this list will be logged. messages in this list will be logged.
@ -129,7 +129,7 @@ def create_echo_function(name, whitelist=None):
def start_message_bus_client(service, bus=None, whitelist=None): def start_message_bus_client(service, bus=None, whitelist=None):
"""Start the bus client daemon and wait for connection. """Start the bus client daemon and wait for connection.
Arguments: Args:
service (str): name of the service starting the connection service (str): name of the service starting the connection
bus (MessageBusClient): an instance of the Mycroft MessageBusClient bus (MessageBusClient): an instance of the Mycroft MessageBusClient
whitelist (list, optional): List of "type" strings. If defined, only whitelist (list, optional): List of "type" strings. If defined, only
@ -201,7 +201,7 @@ class ProcessStatus:
state changes as well as replies to messagebus queries of the state changes as well as replies to messagebus queries of the
process status. process status.
Arguments: Args:
name (str): process name, will be used to create the messagebus name (str): process name, will be used to create the messagebus
messagetype "mycroft.{name}...". messagetype "mycroft.{name}...".
bus (MessageBusClient): Connection to the Mycroft messagebus. bus (MessageBusClient): Connection to the Mycroft messagebus.
@ -233,7 +233,7 @@ class ProcessStatus:
def check_alive(self, message=None): def check_alive(self, message=None):
"""Respond to is_alive status request. """Respond to is_alive status request.
Arguments: Args:
message: Optional message to respond to, if omitted no message message: Optional message to respond to, if omitted no message
is sent. is sent.
@ -251,7 +251,7 @@ class ProcessStatus:
def check_ready(self, message=None): def check_ready(self, message=None):
"""Respond to all_loaded status request. """Respond to all_loaded status request.
Arguments: Args:
message: Optional message to respond to, if omitted no message message: Optional message to respond to, if omitted no message
is sent. is sent.

View File

@ -57,7 +57,7 @@ def now_utc():
def now_local(tz=None): def now_local(tz=None):
"""Retrieve the current time """Retrieve the current time
Arguments: Args:
tz (datetime.tzinfo, optional): Timezone, default to user's settings tz (datetime.tzinfo, optional): Timezone, default to user's settings
Returns: Returns:
@ -71,7 +71,7 @@ def now_local(tz=None):
def to_utc(dt): def to_utc(dt):
"""Convert a datetime with timezone info to a UTC datetime """Convert a datetime with timezone info to a UTC datetime
Arguments: Args:
dt (datetime): A datetime (presumably in some local zone) dt (datetime): A datetime (presumably in some local zone)
Returns: Returns:
(datetime): time converted to UTC (datetime): time converted to UTC
@ -86,7 +86,7 @@ def to_utc(dt):
def to_local(dt): def to_local(dt):
"""Convert a datetime to the user's local timezone """Convert a datetime to the user's local timezone
Arguments: Args:
dt (datetime): A datetime (if no timezone, defaults to UTC) dt (datetime): A datetime (if no timezone, defaults to UTC)
Returns: Returns:
(datetime): time converted to the local timezone (datetime): time converted to the local timezone
@ -101,7 +101,7 @@ def to_local(dt):
def to_system(dt): def to_system(dt):
"""Convert a datetime to the system's local timezone """Convert a datetime to the system's local timezone
Arguments: Args:
dt (datetime): A datetime (if no timezone, assumed to be UTC) dt (datetime): A datetime (if no timezone, assumed to be UTC)
Returns: Returns:
(datetime): time converted to the operation system's timezone (datetime): time converted to the operation system's timezone

View File

@ -50,7 +50,7 @@ sys.argv = sys.argv[:1]
def load_test_environment(skill): def load_test_environment(skill):
"""Load skill's test environment if present """Load skill's test environment if present
Arguments: Args:
skill (str): path to skill root folder skill (str): path to skill root folder
Returns: Returns:

View File

@ -387,7 +387,7 @@ class SkillTest(object):
def execute_test(self, s): def execute_test(self, s):
""" Execute test case. """ Execute test case.
Arguments: Args:
s (MycroftSkill): mycroft skill to test s (MycroftSkill): mycroft skill to test
Returns: Returns:

View File

@ -29,7 +29,7 @@ def wait_for_config_change(context, key, expected_value):
Waits until the specified key has changed into the expected value, if Waits until the specified key has changed into the expected value, if
the change delays for too long a TimeoutError will be raised. the change delays for too long a TimeoutError will be raised.
Arguments: Args:
context (Context): Behave context of current scenario context (Context): Behave context of current scenario
key (str): key to verify key (str): key to verify
expected_value (Object): The expected value indicating that the change expected_value (Object): The expected value indicating that the change
@ -45,7 +45,7 @@ def wait_for_config_change(context, key, expected_value):
def reset_config(context): def reset_config(context):
"""Cleanup callback to reset patched configuration """Cleanup callback to reset patched configuration
Arguments: Args:
context (Context): Behave context of current scenario context (Context): Behave context of current scenario
""" """
context.log.info('Resetting patched configuration...') context.log.info('Resetting patched configuration...')
@ -57,7 +57,7 @@ def reset_config(context):
def patch_config(context, patch): def patch_config(context, patch):
"""Apply patch to config and wait for it to take effect. """Apply patch to config and wait for it to take effect.
Arguments: Args:
context: Behave context for test context: Behave context for test
patch: patch to apply patch: patch to apply
""" """
@ -86,7 +86,7 @@ def patch_config(context, patch):
def get_config_file_definition(configs_path, config, value): def get_config_file_definition(configs_path, config, value):
"""Read config definition file and return the matching patch dict. """Read config definition file and return the matching patch dict.
Arguments: Args:
configs_path: path to the configuration patch json file configs_path: path to the configuration patch json file
config: config value to fetch from the file config: config value to fetch from the file
value: predefined value to fetch value: predefined value to fetch
@ -102,7 +102,7 @@ def get_config_file_definition(configs_path, config, value):
def get_global_config_definition(context, config, value): def get_global_config_definition(context, config, value):
"""Get config definitions included with Mycroft. """Get config definitions included with Mycroft.
Arguments: Args:
context: behave test context context: behave test context
config: config value to fetch from the file config: config value to fetch from the file
value: predefined value to fetch value: predefined value to fetch
@ -118,7 +118,7 @@ def get_global_config_definition(context, config, value):
def get_feature_config_definition(context, config, value): def get_feature_config_definition(context, config, value):
"""Get config feature specific config defintion """Get config feature specific config defintion
Arguments: Args:
context: behave test context context: behave test context
config: config value to fetch from the file config: config value to fetch from the file
value: predefined value to fetch value: predefined value to fetch

View File

@ -56,7 +56,7 @@ def load_dialog_file(dialog_path):
def load_dialog_list(skill_path, dialog): def load_dialog_list(skill_path, dialog):
"""Load dialog from files into a single list. """Load dialog from files into a single list.
Arguments: Args:
skill (MycroftSkill): skill to load dialog from skill (MycroftSkill): skill to load dialog from
dialog (list): Dialog names (str) to load dialog (list): Dialog names (str) to load
@ -72,7 +72,7 @@ def load_dialog_list(skill_path, dialog):
def dialog_from_sentence(sentence, skill_path, lang): def dialog_from_sentence(sentence, skill_path, lang):
"""Find dialog file from example sentence. """Find dialog file from example sentence.
Arguments: Args:
sentence (str): Text to match sentence (str): Text to match
skill_path (str): path to skill directory skill_path (str): path to skill directory
lang (str): language code to use lang (str): language code to use

View File

@ -120,7 +120,7 @@ def get_random_skills(msm, num_random_skills):
def install_or_upgrade_skills(msm, skills): def install_or_upgrade_skills(msm, skills):
"""Install needed skills if uninstalled, otherwise try to update. """Install needed skills if uninstalled, otherwise try to update.
Arguments: Args:
msm: msm instance to use for the operations msm: msm instance to use for the operations
skills: list of skills skills: list of skills
""" """
@ -139,7 +139,7 @@ def install_or_upgrade_skills(msm, skills):
def collect_test_cases(msm, skills): def collect_test_cases(msm, skills):
"""Collect feature files and step files for each skill. """Collect feature files and step files for each skill.
Arguments: Args:
msm: msm instance to use for the operations msm: msm instance to use for the operations
skills: list of skills skills: list of skills
""" """
@ -180,7 +180,7 @@ def get_arguments(cmdline_args):
Parses the commandline and if specified applies configuration file. Parses the commandline and if specified applies configuration file.
Arguments: Args:
cmdline_args (list): argv like list of arguments cmdline_args (list): argv like list of arguments
Returns: Returns:
@ -194,7 +194,7 @@ def get_arguments(cmdline_args):
def create_skills_manager(platform, skills_dir, url, branch): def create_skills_manager(platform, skills_dir, url, branch):
"""Create mycroft skills manager for the given url / branch. """Create mycroft skills manager for the given url / branch.
Arguments: Args:
platform (str): platform to use platform (str): platform to use
skills_dir (str): skill directory to use skills_dir (str): skill directory to use
url (str): skills repo url url (str): skills repo url

View File

@ -26,7 +26,7 @@ TIMEOUT = 10
def then_wait(msg_type, criteria_func, context, timeout=None): def then_wait(msg_type, criteria_func, context, timeout=None):
"""Wait for a specified time for criteria to be fulfilled. """Wait for a specified time for criteria to be fulfilled.
Arguments: Args:
msg_type: message type to watch msg_type: message type to watch
criteria_func: Function to determine if a message fulfilling the criteria_func: Function to determine if a message fulfilling the
test case has been found. test case has been found.
@ -56,7 +56,7 @@ def then_wait(msg_type, criteria_func, context, timeout=None):
def then_wait_fail(msg_type, criteria_func, context, timeout=None): def then_wait_fail(msg_type, criteria_func, context, timeout=None):
"""Wait for a specified time, failing if criteria is fulfilled. """Wait for a specified time, failing if criteria is fulfilled.
Arguments: Args:
msg_type: message type to watch msg_type: message type to watch
criteria_func: Function to determine if a message fulfilling the criteria_func: Function to determine if a message fulfilling the
test case has been found. test case has been found.
@ -73,7 +73,7 @@ def then_wait_fail(msg_type, criteria_func, context, timeout=None):
def mycroft_responses(context): def mycroft_responses(context):
"""Collect and format mycroft responses from context. """Collect and format mycroft responses from context.
Arguments: Args:
context: behave context to extract messages from. context: behave context to extract messages from.
Returns: (str) Mycroft responses including skill and dialog file Returns: (str) Mycroft responses including skill and dialog file
@ -98,7 +98,7 @@ def print_mycroft_responses(context):
def emit_utterance(bus, utt): def emit_utterance(bus, utt):
"""Emit an utterance on the bus. """Emit an utterance on the bus.
Arguments: Args:
bus (InterceptAllBusClient): Bus instance to listen on bus (InterceptAllBusClient): Bus instance to listen on
dialogs (list): list of acceptable dialogs dialogs (list): list of acceptable dialogs
""" """
@ -113,7 +113,7 @@ def emit_utterance(bus, utt):
def wait_for_dialog(bus, dialogs, context=None, timeout=None): def wait_for_dialog(bus, dialogs, context=None, timeout=None):
"""Wait for one of the dialogs given as argument. """Wait for one of the dialogs given as argument.
Arguments: Args:
bus (InterceptAllBusClient): Bus instance to listen on bus (InterceptAllBusClient): Bus instance to listen on
dialogs (list): list of acceptable dialogs dialogs (list): list of acceptable dialogs
context (behave Context): optional context providing scenario timeout context (behave Context): optional context providing scenario timeout
@ -140,7 +140,7 @@ def wait_for_audio_service(context, message_type):
May be play, stop, or pause messages May be play, stop, or pause messages
Arguments: Args:
context (behave Context): optional context providing scenario timeout context (behave Context): optional context providing scenario timeout
message_type (string): final component of bus message in form message_type (string): final component of bus message in form
`mycroft.audio.service.{type} `mycroft.audio.service.{type}

View File

@ -22,7 +22,7 @@ def create_converse_responder(response, skill):
The function waits for the converse method to be replaced by the The function waits for the converse method to be replaced by the
_wait_response logic and afterwards injects the provided response. _wait_response logic and afterwards injects the provided response.
Arguments: Args:
response (str): Sentence to inject. response (str): Sentence to inject.
skill (MycroftSkill): skill to monitor. skill (MycroftSkill): skill to monitor.
""" """

View File

@ -46,7 +46,7 @@ def load_test_skill():
def create_skill_api_from_skill(skill): def create_skill_api_from_skill(skill):
"""Helper creating an api from a skill. """Helper creating an api from a skill.
Arguments: Args:
skill (MycroftSkill): Skill to create api from. skill (MycroftSkill): Skill to create api from.
Returns: Returns: