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-core technical documentation
====================================

View File

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

View File

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

View File

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

View File

@ -25,22 +25,6 @@ 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
---------------------
.. 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
if nothing has changed on the remote.
Arguments:
Args:
params (dict): request parameters
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.
Arguments:
Args:
response (requests Response object): Response to parse
no_refresh (bool): Disable refreshing of the token
Returns:
data fetched from server
"""
@ -373,7 +374,7 @@ class DeviceApi(Api):
def upload_skill_metadata(self, settings_meta):
"""Upload skill metadata.
Arguments:
Args:
settings_meta (dict): skill info and settings in JSON format
"""
return self.request({
@ -386,7 +387,7 @@ class DeviceApi(Api):
""" Upload skills.json file. This file contains a manifest of installed
and failed installations for use with the Marketplace.
Arguments:
Args:
data: dictionary with skills data from msm
"""
if not isinstance(data, dict):
@ -512,7 +513,7 @@ def is_paired(ignore_errors=True):
def check_remote_pairing(ignore_errors):
"""Check that a basic backend endpoint accepts our pairing.
Arguments:
Args:
ignore_errors (bool): True if errors should be ignored when
Returns:

View File

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

View File

@ -23,7 +23,7 @@ from abc import ABCMeta, abstractmethod
class AudioBackend(metaclass=ABCMeta):
"""Base class for all audio backend implementations.
Arguments:
Args:
config (dict): configuration dict for the instance
bus (MessageBusClient): Mycroft messagebus emitter
"""
@ -50,7 +50,7 @@ class AudioBackend(metaclass=ABCMeta):
def add_list(self, tracks):
"""Add tracks to backend's playlist.
Arguments:
Args:
tracks (list): list of tracks.
"""
@ -61,7 +61,7 @@ class AudioBackend(metaclass=ABCMeta):
Starts playing the first track in the playlist and will contiune
until all tracks have been played.
Arguments:
Args:
repeat (bool): Repeat playlist, defaults to False
"""
@ -119,14 +119,14 @@ class AudioBackend(metaclass=ABCMeta):
def seek_forward(self, seconds=1):
"""Skip X seconds.
Arguments:
Args:
seconds (int): number of seconds to seek, if negative rewind
"""
def seek_backward(self, seconds=1):
"""Rewind X seconds.
Arguments:
Args:
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):
"""Mute mic and start speaking the utterance using selected tts backend.
Arguments:
Args:
utterance: The sentence to be spoken
ident: Ident tying the utterance to the source query
"""
@ -152,7 +152,7 @@ def _get_mimic_fallback():
def mimic_fallback_tts(utterance, ident, listen):
"""Speak utterance using fallback TTS if connection is lost.
Arguments:
Args:
utterance (str): sentence to speak
ident (str): interaction id for metrics
listen (bool): True if interaction should end with mycroft listening
@ -177,7 +177,7 @@ def handle_stop(event):
def init(messagebus):
"""Start speech related handlers.
Arguments:
Args:
messagebus: Connection to the Mycroft messagebus
"""

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -49,7 +49,7 @@ class MustacheDialogRenderer:
def load_template_file(self, template_name, filename):
"""Load a template by file name into the templates cache.
Arguments:
Args:
template_name (str): a unique identifier for a group of templates
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.
Arguments:
Args:
template_name (str): the name of a template group.
context (dict): dictionary representing values to be rendered
index (int): optional, the specific index in the collection of
@ -123,7 +123,7 @@ class MustacheDialogRenderer:
def load_dialogs(dialog_dir, renderer=None):
"""Load all dialog files within the specified directory.
Arguments:
Args:
dialog_dir (str): directory that contains dialog files
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
will use the default language for translations.
Arguments:
Args:
phrase (str): resource phrase to retrieve/translate
lang (str): the language to use
context (dict): values to be inserted into the string

View File

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

View File

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

View File

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

View File

@ -71,7 +71,7 @@ def report_metric(name, data):
def report_timing(ident, system, timing, additional_data=None):
"""Create standardized message for reporting timing.
Arguments:
Args:
ident (str): identifier of user interaction
system (str): system the that's generated the report
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):
"""Container handling the device preparation.
Arguments:
Args:
message_bus_client: Bus client used to interact with the system
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):
"""Start up the all intent services and connect them as needed.
Arguments:
Args:
bus: messagebus client to register the services on
"""
service = IntentService(bus)

View File

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

View File

@ -20,7 +20,7 @@ from mycroft.messagebus.message import Message
def ensure_uri(s):
"""Interprete paths as file:// uri's.
Arguments:
Args:
s: string to be checked
Returns:
@ -43,7 +43,7 @@ def ensure_uri(s):
class AudioService:
"""AudioService class for interacting with the audio subsystem
Arguments:
Args:
bus: Mycroft messagebus connection
"""
@ -53,7 +53,7 @@ class AudioService:
def queue(self, tracks=None):
"""Queue up a track to playing playlist.
Arguments:
Args:
tracks: track uri or list of track uri's
Each track can be added as a tuple with (uri, mime)
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):
"""Start playback.
Arguments:
Args:
tracks: track uri or list of track uri's
Each track can be added as a tuple with (uri, mime)
to give a hint of the mime type to the system
@ -114,7 +114,7 @@ class AudioService:
def seek(self, seconds=1):
"""Seek X seconds.
Arguments:
Args:
seconds (int): number of seconds to seek, if negative rewind
"""
if seconds < 0:
@ -125,7 +125,7 @@ class AudioService:
def seek_forward(self, seconds=1):
"""Skip ahead X seconds.
Arguments:
Args:
seconds (int): number of seconds to skip
"""
self.bus.emit(Message('mycroft.audio.service.seek_forward',
@ -134,7 +134,7 @@ class AudioService:
def seek_backward(self, seconds=1):
"""Rewind X seconds
Arguments:
Args:
seconds (int): number of seconds to rewind
"""
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
documentation for that class). This method should return
True if and only if this skill can take the appropriate
'action' when considering _all other properties
of the request_. In other words, a partial match, one in which
'action' when considering all other properties
of the request. In other words, a partial match, one in which
any piece of the IoTRequest is not known to this skill,
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
Arguments:
Args:
match (str): Matching string
phrase (str): original input phrase
level (CPSMatchLevel): match level
@ -203,7 +203,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
def CPS_match_query_phrase(self, phrase):
"""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"
Returns:
@ -233,7 +233,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
def CPS_start(self, phrase, data):
"""Begin playing whatever is specified in 'phrase'
Arguments:
Args:
phrase (str): User phrase uttered after "Play", e.g. "some music"
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
for an answer from this skill.
Arguments:
Args:
timeout (int): Number of seconds
"""
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
data.
Arguments:
Args:
artist (str): Current track artist
track (str): Track name
album (str): Album title
@ -297,7 +297,7 @@ class CommonPlaySkill(MycroftSkill, ABC):
Provides track data for playlist
Arguments:
Args:
tracklist (list/dict): Tracklist data
"""
tracklist = tracklist or []

View File

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

View File

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

View File

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

View File

@ -116,7 +116,7 @@ class FallbackSkill(MycroftSkill):
Lower priority gets run first
0 for high priority 100 for low priority
Arguments:
Args:
handler (callable): original handler, used as a reference when
removing
wrapper (callable): wrapped version of handler
@ -146,7 +146,7 @@ class FallbackSkill(MycroftSkill):
def _remove_registered_handler(cls, wrapper_to_del):
"""Remove a registered wrapper.
Arguments:
Args:
wrapper_to_del (callable): wrapped handler to be removed
Returns:
@ -166,7 +166,7 @@ class FallbackSkill(MycroftSkill):
def remove_fallback(cls, handler_to_del):
"""Remove a fallback handler.
Arguments:
Args:
handler_to_del: reference to handler
Returns:
(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):
"""Get the language from the message or the default language.
Arguments:
Args:
message: message to check for language code.
Returns:
@ -47,7 +47,7 @@ def _normalize_all_utterances(utterances):
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.
Arguments:
Args:
utterances (list): list of utterances to normalize
Returns:
@ -159,7 +159,7 @@ class IntentService:
def do_converse(self, utterances, skill_id, lang, message):
"""Call skill and ask if they want to process the utterance.
Arguments:
Args:
utterances (list of tuples): utterances paired with normalized
versions.
skill_id: skill to query.
@ -182,7 +182,7 @@ class IntentService:
def handle_converse_error(self, message):
"""Handle error in converse system.
Arguments:
Args:
message (Message): info about the error.
"""
skill_id = message.data["skill_id"]
@ -194,7 +194,7 @@ class IntentService:
def remove_active_skill(self, skill_id):
"""Remove a skill from being targetable by converse.
Arguments:
Args:
skill_id (str): skill to remove
"""
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
list it's removed so there is only a single entry of it.
Arguments:
Args:
skill_id (str): identifier of skill to be added.
"""
# 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.
Arguments:
Args:
intent (IntentMatch or None): intet match info
context (dict): context info about the interaction
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
and a generic info of the failure will be spoken.
Arguments:
Args:
message (Message): The messagebus data
"""
try:
@ -318,7 +318,7 @@ class IntentService:
def _converse(self, utterances, lang, message):
"""Give active skills a chance at the utterance
Arguments:
Args:
utterances (list): list of utterances
lang (string): 4 letter ISO language code
message (Message): message to use to generate reply
@ -343,7 +343,7 @@ class IntentService:
def send_complete_intent_failure(self, message):
"""Send a message that no skill could handle the utterance.
Arguments:
Args:
message (Message): original message to forward from
"""
self.bus.emit(message.forward('complete_intent_failure'))
@ -351,7 +351,7 @@ class IntentService:
def handle_register_vocab(self, message):
"""Register adapt vocabulary.
Arguments:
Args:
message (Message): message containing vocab info
"""
start_concept = message.data.get('start')
@ -365,7 +365,7 @@ class IntentService:
def handle_register_intent(self, message):
"""Register adapt intent.
Arguments:
Args:
message (Message): message containing intent info
"""
intent = open_intent_envelope(message)
@ -374,7 +374,7 @@ class IntentService:
def handle_detach_intent(self, message):
"""Remover adapt intent.
Arguments:
Args:
message (Message): message containing intent info
"""
intent_name = message.data.get('intent_name')
@ -383,7 +383,7 @@ class IntentService:
def handle_detach_skill(self, message):
"""Remove all intents registered for a specific skill.
Arguments:
Args:
message (Message): message containing intent info
"""
skill_id = message.data.get('skill_id')
@ -427,7 +427,7 @@ class IntentService:
def handle_get_intent(self, message):
"""Get intent from either adapt or padatious.
Arguments:
Args:
message (Message): message containing utterance
"""
utterance = message.data["utterance"]
@ -486,7 +486,7 @@ class IntentService:
def handle_get_adapt(self, message):
"""handler getting the adapt response for an utterance.
Arguments:
Args:
message (Message): message containing utterance
"""
utterance = message.data["utterance"]
@ -518,7 +518,7 @@ class IntentService:
def handle_get_padatious(self, message):
"""messagebus handler for perfoming padatious parsing.
Arguments:
Args:
message (Message): message triggering the method
"""
utterance = message.data["utterance"]
@ -534,7 +534,7 @@ class IntentService:
def handle_padatious_manifest(self, message):
"""Messagebus handler returning the registered padatious intents.
Arguments:
Args:
message (Message): message triggering the method
"""
self.bus.emit(message.reply(
@ -544,7 +544,7 @@ class IntentService:
def handle_entity_manifest(self, message):
"""Messagebus handler returning the registered padatious entities.
Arguments:
Args:
message (Message): message triggering the method
"""
self.bus.emit(message.reply(

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -32,7 +32,7 @@ def read_vocab_file(path):
parentheses. It returns each line as a list of all expanded
alternatives.
Arguments:
Args:
path (str): path to vocab file.
Returns:
@ -74,7 +74,7 @@ def load_regex_from_file(path, skill_id):
def load_vocabulary(basedir, skill_id):
"""Load vocabulary from all files in the specified directory.
Arguments:
Args:
basedir (str): path of directory to load from (will recurse)
skill_id: skill the data belongs to
Returns:
@ -189,7 +189,7 @@ def read_value_file(filename, delim):
The value file is a simple csv structure with a key and value.
Arguments:
Args:
filename (str): file to read
delim (str): csv delimiter
@ -215,7 +215,7 @@ def read_value_file(filename, delim):
def read_translated_file(filename, data):
"""Read a file inserting data.
Arguments:
Args:
filename (str): file to read
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
sure skills are completely reloaded these references are deleted.
Arguments:
Args:
module_name: name of skill module.
"""
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
as makes sure the module is inserted into the sys.modules dict.
Arguments:
Args:
path: Path to the skill main file (__init__.py)
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):
"""Return all entries with modification time in the future.
Arguments:
Args:
mod_times (dict): dict mapping file paths to modification times.
Returns:
@ -92,7 +92,7 @@ def _get_last_modified_time(path):
Exclude compiled python files, hidden directories and the settings.json
file.
Arguments:
Args:
path: skill directory to check
Returns:

View File

@ -92,7 +92,7 @@ def _shutdown_skill(instance):
Call the default_shutdown method of the skill, will produce a warning if
the shutdown process takes longer than 1 second.
Arguments:
Args:
instance (MycroftSkill): Skill instance to shutdown
"""
try:
@ -115,7 +115,7 @@ class SkillManager(Thread):
def __init__(self, bus, watchdog=None):
"""Constructor
Arguments:
Args:
bus (event emitter): Mycroft messagebus connection
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
expected to return a text string.
Arguments:
Args:
audio (AudioData): audio recorded by mycroft.
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
STT engine.
Arguments:
Args:
queue (Queue): Input Queue
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
it's collected by Mycroft.
Arguments:
Args:
language (str): optional language code for the new stream.
"""
self.stream_stop()
@ -404,7 +404,7 @@ class StreamingSTT(STT, metaclass=ABCMeta):
def stream_data(self, data):
"""Receiver of audio data.
Arguments:
Args:
data (bytes): raw audio data.
"""
self.queue.put(data)
@ -607,7 +607,7 @@ class GoVivaceSTT(TokenSTT):
def load_stt_plugin(module_name):
"""Wrapper function for loading stt plugin.
Arguments:
Args:
module_name (str): Mycroft stt module name from config
Returns:
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]:
"""Use the Mimic2 API to retrieve the audio for a sentence.
Arguments:
Args:
sentence: The sentence to be cached
"""
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):
"""Convert the sentence into a hash value used for the file name
Arguments:
Args:
sentence: The sentence to be cached
"""
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.
Arguments:
Args:
path: path to get hash from
Returns:
@ -93,7 +93,7 @@ class AudioFile:
def save(self, audio: bytes):
"""Write a TTS cache file containing the audio to be spoken.
Arguments:
Args:
audio: TTS inference of a sentence
"""
try:
@ -123,7 +123,7 @@ class PhonemeFile:
def save(self, phonemes):
"""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
"""
try:
@ -228,7 +228,7 @@ class TextToSpeechCache:
punctuation
example : <<< LOADING <<<
Arguments:
Args:
dialogs: a list of the records in the dialog resource files
"""
sentences = set()

View File

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

View File

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

View File

@ -38,7 +38,7 @@ _max_sentence_size = 170
def _break_chunks(l, n):
"""Yield successive n-sized chunks
Arguments:
Args:
l (list): text (str) to split
chunk_size (int): chunk size
"""
@ -49,7 +49,7 @@ def _break_chunks(l, n):
def _split_by_chunk_size(text, chunk_size):
"""Split text into word chunks by chunk_size size
Arguments:
Args:
text (str): text to split
chunk_size (int): chunk size
@ -87,7 +87,7 @@ def _split_by_punctuation(chunks, puncs):
"""Splits text by various punctionations
e.g. hello, world => [hello, world]
Arguments:
Args:
chunks (list or str): text (str) to split
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.
This stage can be removed once Mimic2 can generate longer sentences.
Arguments:
Args:
text (str): text to split
chunk_size (int): size of each chunk
split_by_punc (bool, optional): Defaults to True.
@ -176,7 +176,7 @@ class Mimic2(TTS):
def _requests(self, sentence):
"""Create asynchronous request list
Arguments:
Args:
chunks (list): list of text to synthesize
Returns:
@ -189,7 +189,7 @@ class Mimic2(TTS):
def viseme(self, phonemes):
"""Maps phonemes to appropriate viseme encoding
Arguments:
Args:
phonemes (list): list of tuples (phoneme, time_start)
Returns:
@ -216,7 +216,7 @@ class Mimic2(TTS):
def get_tts(self, sentence, wav_file):
"""Generate (remotely) and play mimic2 WAV audio
Arguments:
Args:
sentence (str): Phrase to synthesize to audio with mimic2
wav_file (str): Location to write audio output
"""
@ -240,7 +240,7 @@ class Mimic2(TTS):
def save_phonemes(self, key, phonemes):
"""Cache phonemes
Arguments:
Args:
key: Hash key for the sentence
phonemes: phoneme string to save
"""
@ -255,7 +255,7 @@ class Mimic2(TTS):
def load_phonemes(self, key):
"""Load phonemes from cache file.
Arguments:
Args:
Key: Key identifying phoneme cache
"""
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):
"""Generate WAV and phonemes.
Arguments:
Args:
sentence (str): sentence to generate audio for
wav_file (str): output file
@ -196,7 +196,7 @@ class Mimic(TTS):
def viseme(self, phoneme_pairs):
"""Convert phoneme string to visemes.
Arguments:
Args:
phoneme_pairs (list): Phoneme output from mimic
Returns:

View File

@ -128,7 +128,7 @@ class PlaybackThread(Thread):
def show_visemes(self, pairs):
"""Send viseme data to enclosure
Arguments:
Args:
pairs (list): Visime and timing pair
Returns:
@ -158,7 +158,7 @@ class TTS(metaclass=ABCMeta):
It aggregates the minimum required parameters and exposes
``execute(sentence)`` and ``validate_ssml(sentence)`` functions.
Arguments:
Args:
lang (str):
config (dict): Configuration for this specific tts engine
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
cleaning to free up disk space.
Arguments:
Args:
listen (bool): indication if listening trigger should be sent.
"""
@ -234,7 +234,7 @@ class TTS(metaclass=ABCMeta):
def init(self, bus):
"""Performs intial setup of TTS object.
Arguments:
Args:
bus: Mycroft messagebus connection
"""
self.bus = bus
@ -247,7 +247,7 @@ class TTS(metaclass=ABCMeta):
Should get data from tts.
Arguments:
Args:
sentence(str): Sentence to synthesize
wav_file(str): output file
@ -259,7 +259,7 @@ class TTS(metaclass=ABCMeta):
def modify_tag(self, tag):
"""Override to modify each supported ssml tag.
Arguments:
Args:
tag (str): SSML tag to check and possibly transform.
"""
return tag
@ -268,7 +268,7 @@ class TTS(metaclass=ABCMeta):
def remove_ssml(text):
"""Removes SSML tags from a string.
Arguments:
Args:
text (str): input string
Returns:
@ -281,7 +281,7 @@ class TTS(metaclass=ABCMeta):
Remove unsupported / invalid tags
Arguments:
Args:
utterance (str): Sentence to validate
Returns:
@ -310,7 +310,7 @@ class TTS(metaclass=ABCMeta):
This method can be overridden to create chunks suitable to the
TTS engine in question.
Arguments:
Args:
sentence (str): sentence to preprocess
Returns:
@ -324,7 +324,7 @@ class TTS(metaclass=ABCMeta):
The method caches results if possible using the hash of the
sentence.
Arguments:
Args:
sentence: (str) Sentence to be spoken
ident: (str) Id reference to current interaction
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
visuals.
Arguments:
Args:
phonemes (str): String with phoneme data
Returns:
@ -427,7 +427,7 @@ class TTS(metaclass=ABCMeta):
def save_phonemes(self, key, phonemes):
"""Cache phonemes
Arguments:
Args:
key (str): Hash key for the sentence
phonemes (str): phoneme string to save
"""
@ -445,7 +445,7 @@ class TTS(metaclass=ABCMeta):
def load_phonemes(self, key):
"""Load phonemes from cache file.
Arguments:
Args:
key (str): Key identifying phoneme cache
"""
# TODO: remove in 21.08
@ -522,7 +522,7 @@ class TTSValidator(metaclass=ABCMeta):
def load_tts_plugin(module_name):
"""Wrapper function for loading tts plugin.
Arguments:
Args:
(str) Mycroft tts module name from config
Returns:
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
in the background.
Arguments:
Args:
uri: uri to play
environment (dict): optional environment for the subprocess call
@ -75,7 +75,7 @@ def _get_pulse_environment(config):
def _play_cmd(cmd, uri, config, environment):
"""Generic function for starting playback from a commandline and uri.
Arguments:
Args:
cmd (str): commandline to execute %1 in the command line will be
replaced with the provided uri.
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 file in the background.
Arguments:
Args:
uri: uri to play
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 file in the background.
Arguments:
Args:
uri: uri to play
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 file in the background.
Arguments:
Args:
uri: uri to play
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
application.
Arguments:
Args:
file_path: where to store the recorded data
duration: how long to record
rate: sample rate
@ -188,7 +188,7 @@ def record(file_path, duration, rate, channels):
def find_input_device(device_name):
"""Find audio input device by name.
Arguments:
Args:
device_name: device name or regex pattern to match
Returns: device_index (int) or None if device wasn't found

View File

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

View File

@ -31,7 +31,7 @@ _running_downloads = {} # Cache of running downloads
def _get_download_tmp(dest):
"""Get temporary file for download.
Arguments:
Args:
dest (str): path to download location
Returns:
@ -55,7 +55,7 @@ class Downloader(Thread):
be set to true and the `.status` will indicate the HTTP status code.
200 = Success.
Arguments:
Args:
url (str): Url to download
dest (str): Path to save data to
complete_action (callable): Function to run when download is complete
@ -83,7 +83,7 @@ class Downloader(Thread):
def perform_download(self, dest):
"""Handle the download through wget.
Arguments:
Args:
dest (str): Save location
"""
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
actions that should be performed at completion.
Arguments:
Args:
tmp(str): temporary file path
"""
os.rename(tmp, self.dest)
@ -135,7 +135,7 @@ class Downloader(Thread):
def download(url, dest, complete_action=None, header=None):
"""Start a download or fetch an already running.
Arguments:
Args:
url (str): url to download
dest (str): path to save download to
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.
Example:
With mycroft running as the user 'bob', if you called
resolve_resource_file('snd/beep.wav')
it would return either '/home/bob/.mycroft/snd/beep.wav' or
'/opt/mycroft/snd/beep.wav' or '.../mycroft/res/snd/beep.wav',
where the '...' is replaced by the path where the package has
been installed.
With mycroft running as the user 'bob', if you called
``resolve_resource_file('snd/beep.wav')``
it would return either:
'/home/bob/.mycroft/snd/beep.wav' or
'/opt/mycroft/snd/beep.wav' or
'.../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
Returns:
(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):
"""Read a file and return a list of stripped lines.
Arguments:
Args:
filename (str): path to file to read.
Returns:
@ -106,7 +109,7 @@ def read_dict(filename, div='='):
'baz': 'bog'
}
Arguments:
Args:
filename (str): path to file
div (str): deviders between dict keys and values
@ -124,7 +127,7 @@ def read_dict(filename, div='='):
def mb_to_bytes(size):
"""Takes a size in MB and returns the number of bytes.
Arguments:
Args:
size(int/float): size in Mega Bytes
Returns:
@ -136,7 +139,7 @@ def mb_to_bytes(size):
def _get_cache_entries(directory):
"""Get information tuple for all regular files in directory.
Arguments:
Args:
directory (str): path to directory to check
Returns:
@ -153,7 +156,7 @@ def _get_cache_entries(directory):
def _delete_oldest(entries, bytes_needed):
"""Delete files with oldest modification date until space is freed.
Arguments:
Args:
entries (tuple): file + file stats tuple
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
deleted as freely.
Arguments:
Args:
directory (str): directory path that holds cached files
min_free_percent (float): percentage (0.0-100.0) of drive to keep free,
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
the file.
Arguments:
Args:
domain (str): The cache domain. Basically just a subdirectory.
Returns:
@ -238,7 +241,7 @@ def get_cache_directory(domain=None):
def ensure_directory_exists(directory, domain=None, permissions=0o777):
"""Create a directory and give access rights to all
Arguments:
Args:
directory (str): Root directory
domain (str): Domain. Basically a subdirectory to prevent things like
overlapping signal filenames.
@ -269,7 +272,7 @@ def ensure_directory_exists(directory, domain=None, permissions=0o777):
def create_file(filename):
"""Create the file filename and create any directories needed
Arguments:
Args:
filename: Path to the file to be created
"""
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,
use_years=True, clock=False,
resolution=TimeResolution.SECONDS):
""" Convert duration in seconds to a nice spoken timespan
Used as a handler by nice_duration and nice_duration_dt
"""Convert duration in seconds to a nice spoken timespan.
Used as a handler by nice_duration and nice_duration_dt.
Accepts:
datetime.timedelta, or
@ -323,6 +324,7 @@ def nice_duration(duration, lang=None, speech=True, use_years=True,
TimeResolution.MINUTES
TimeResolution.SECONDS
TimeResolution.MILLISECONDS
NOTE: nice_duration will not produce milliseconds
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
monotonic time doesn't indicate a timeout.
Arguments:
Args:
timeout: timeout of wait in seconds
Returns:

View File

@ -49,7 +49,7 @@ def _log_unsupported_language(language, supported_languages):
"""
Log a warning when a language is unsupported
Arguments:
Args:
language: str
The language that was supplied.
supported_languages: [str]
@ -70,10 +70,13 @@ def extract_datetime(text, anchorDate="DEFAULT", lang=None,
"Tuesday".
Vague terminology are given arbitrary values, like:
- morning = 8 AM
- afternoon = 3 PM
- evening = 7 PM
* morning = 8 AM
* afternoon = 3 PM
* evening = 7 PM
If a time isn't supplied or implied, the function defaults to 12 AM
Args:
text (str): the text to be interpreted
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
default_time (datetime.time): time to use if none was found in
the input string.
Returns:
[:obj:`datetime`, :obj:`str`]: 'datetime' is the extracted date
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):
"""Finds all plugins matching specific entrypoint type.
Arguments:
Args:
plug_type (str): plugin entrypoint string to retrieve
Returns:
@ -38,7 +38,7 @@ def find_plugins(plug_type):
def load_plugin(plug_type, plug_name):
"""Load a specific plugin from a specific plugin type.
Arguments:
Args:
plug_type: (str) plugin type name. Ex. "mycroft.plugin.tts".
plug_name: (str) specific plugin name

View File

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

View File

@ -57,7 +57,7 @@ def now_utc():
def now_local(tz=None):
"""Retrieve the current time
Arguments:
Args:
tz (datetime.tzinfo, optional): Timezone, default to user's settings
Returns:
@ -71,7 +71,7 @@ def now_local(tz=None):
def to_utc(dt):
"""Convert a datetime with timezone info to a UTC datetime
Arguments:
Args:
dt (datetime): A datetime (presumably in some local zone)
Returns:
(datetime): time converted to UTC
@ -86,7 +86,7 @@ def to_utc(dt):
def to_local(dt):
"""Convert a datetime to the user's local timezone
Arguments:
Args:
dt (datetime): A datetime (if no timezone, defaults to UTC)
Returns:
(datetime): time converted to the local timezone
@ -101,7 +101,7 @@ def to_local(dt):
def to_system(dt):
"""Convert a datetime to the system's local timezone
Arguments:
Args:
dt (datetime): A datetime (if no timezone, assumed to be UTC)
Returns:
(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):
"""Load skill's test environment if present
Arguments:
Args:
skill (str): path to skill root folder
Returns:

View File

@ -387,7 +387,7 @@ class SkillTest(object):
def execute_test(self, s):
""" Execute test case.
Arguments:
Args:
s (MycroftSkill): mycroft skill to test
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
the change delays for too long a TimeoutError will be raised.
Arguments:
Args:
context (Context): Behave context of current scenario
key (str): key to verify
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):
"""Cleanup callback to reset patched configuration
Arguments:
Args:
context (Context): Behave context of current scenario
"""
context.log.info('Resetting patched configuration...')
@ -57,7 +57,7 @@ def reset_config(context):
def patch_config(context, patch):
"""Apply patch to config and wait for it to take effect.
Arguments:
Args:
context: Behave context for test
patch: patch to apply
"""
@ -86,7 +86,7 @@ def patch_config(context, patch):
def get_config_file_definition(configs_path, config, value):
"""Read config definition file and return the matching patch dict.
Arguments:
Args:
configs_path: path to the configuration patch json file
config: config value to fetch from the file
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):
"""Get config definitions included with Mycroft.
Arguments:
Args:
context: behave test context
config: config value to fetch from the file
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):
"""Get config feature specific config defintion
Arguments:
Args:
context: behave test context
config: config value to fetch from the file
value: predefined value to fetch

View File

@ -56,7 +56,7 @@ def load_dialog_file(dialog_path):
def load_dialog_list(skill_path, dialog):
"""Load dialog from files into a single list.
Arguments:
Args:
skill (MycroftSkill): skill to load dialog from
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):
"""Find dialog file from example sentence.
Arguments:
Args:
sentence (str): Text to match
skill_path (str): path to skill directory
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):
"""Install needed skills if uninstalled, otherwise try to update.
Arguments:
Args:
msm: msm instance to use for the operations
skills: list of skills
"""
@ -139,7 +139,7 @@ def install_or_upgrade_skills(msm, skills):
def collect_test_cases(msm, skills):
"""Collect feature files and step files for each skill.
Arguments:
Args:
msm: msm instance to use for the operations
skills: list of skills
"""
@ -180,7 +180,7 @@ def get_arguments(cmdline_args):
Parses the commandline and if specified applies configuration file.
Arguments:
Args:
cmdline_args (list): argv like list of arguments
Returns:
@ -194,7 +194,7 @@ def get_arguments(cmdline_args):
def create_skills_manager(platform, skills_dir, url, branch):
"""Create mycroft skills manager for the given url / branch.
Arguments:
Args:
platform (str): platform to use
skills_dir (str): skill directory to use
url (str): skills repo url

View File

@ -26,7 +26,7 @@ TIMEOUT = 10
def then_wait(msg_type, criteria_func, context, timeout=None):
"""Wait for a specified time for criteria to be fulfilled.
Arguments:
Args:
msg_type: message type to watch
criteria_func: Function to determine if a message fulfilling the
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):
"""Wait for a specified time, failing if criteria is fulfilled.
Arguments:
Args:
msg_type: message type to watch
criteria_func: Function to determine if a message fulfilling the
test case has been found.
@ -73,7 +73,7 @@ def then_wait_fail(msg_type, criteria_func, context, timeout=None):
def mycroft_responses(context):
"""Collect and format mycroft responses from context.
Arguments:
Args:
context: behave context to extract messages from.
Returns: (str) Mycroft responses including skill and dialog file
@ -98,7 +98,7 @@ def print_mycroft_responses(context):
def emit_utterance(bus, utt):
"""Emit an utterance on the bus.
Arguments:
Args:
bus (InterceptAllBusClient): Bus instance to listen on
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):
"""Wait for one of the dialogs given as argument.
Arguments:
Args:
bus (InterceptAllBusClient): Bus instance to listen on
dialogs (list): list of acceptable dialogs
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
Arguments:
Args:
context (behave Context): optional context providing scenario timeout
message_type (string): final component of bus message in form
`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
_wait_response logic and afterwards injects the provided response.
Arguments:
Args:
response (str): Sentence to inject.
skill (MycroftSkill): skill to monitor.
"""

View File

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