In the 1970s computer users had to understand the arcane syntax of the machines they used. They programed their computers using the machine's native language and hardly gave it a thought.
The 1980s birthed a new form of interaction between computers and users. For the first time computers became capable of understanding the most basic form of human communication - pointing and grunting. The mouse and the GUI revolutionized computing and made computers accessible to the masses. We have now entered a third era. We are rapidly approaching a time when computer systems will understand human language and respond using the most natural form of human communication – speech. This is an important development. Some might even call it revolutionary. Despite its importance, however, the technologies that will underpin this new method of interaction are the property of major tech firms who don't necessarily have the public's best interests at heart. Not anymore. Meet Mycroft – the worlds first open source natural language platform. Mycroft understands human language and responds with speech. It is being designed to run on anything from a phone to an automobile and will change the way we interact with open source technologies in profound ways. Our goal here at Mycroft is to improve this technology to the point that when you interact with the software it is impossible to tell if you are talking to a human or a machine. This initial release of the Mycroft software represents a significant effort by the Mycroft community to give the open source world access to this important technology. We are all hoping that the software will be useful to the public and will help to usher in a new era of human machine interaction. Our community welcomes everyone to use Mycroft, improve the software and contribute back to the project. With your help and support we can truly make Mycroft an AI for everyone. Joshua W Montgomery – May 17, 2016pull/13/head
parent
8e470ce7c1
commit
6e42bb1736
|
@ -0,0 +1,61 @@
|
|||
# How to contribute
|
||||
|
||||
So you want to contribute to Mycroft?
|
||||
This should be as easy as possible for you but there are a few things to consider when contributing.
|
||||
The following guidelines for contribution should be followed if you want to submit a pull request.
|
||||
|
||||
## How to prepare
|
||||
|
||||
* You need a [GitHub account](https://github.com/signup/free)
|
||||
* Submit an [issue ticket](https://github.com/MycroftAI/mycroft/issues) for your issue if there is no one yet.
|
||||
* Describe the issue and include steps to reproduce if it's a bug.
|
||||
* Ensure to mention the earliest version that you know is affected.
|
||||
* If you are able and want to fix this, fork the repository on GitHub
|
||||
|
||||
|
||||
## Make Changes
|
||||
|
||||
1. [Fork the Project](https://help.github.com/articles/fork-a-repo/)
|
||||
2. [Create a new Issue](https://help.github.com/articles/creating-an-issue/)
|
||||
3. Create a **feature** or **bugfix** branch based on **master** with your issue identifier. For example, if your issue identifier is: **issues-123** then you will create either: **feature/issues-123** or **bugfix/issues-123**. Use **feature** prefix for issues related to new functionalities or enhancements and **bugfix** in case of bugs found on the **master** branch
|
||||
4. Make sure you stick to the coding style and OO patterns that is used already.
|
||||
5. Make use of the `.editorconfig`-file if provided with the repository.
|
||||
6. Make commits of logical units and describe them properly. Use your issue identifier at the very begin of each commit. For instance:
|
||||
`git commit -m "Issues-123 - Fixing 'A' sound on Spelling Skill"`
|
||||
7. Check for unnecessary whitespace with `git diff --check` before committing and make sure you format code and organize your imports.
|
||||
8. Once you have committed everything and are done with your branch, you have to rebase your code with master. Do the following steps:
|
||||
1. Make sure you do not have any changes left on your branch
|
||||
2. Checkout on master branch and make sure it is up-to-date
|
||||
3. Checkout your branch and rebase it with master
|
||||
4. Resolve any conflicts you have
|
||||
5. You will have to force your push since the historical base has changed
|
||||
6. Suggested steps are:
|
||||
```
|
||||
git checkout master
|
||||
git fetch
|
||||
git reset --hard origin/master
|
||||
git checkout <your_branch_name>
|
||||
git rebase master
|
||||
git push -f
|
||||
```
|
||||
9. If possible, create unit tests for your changes
|
||||
* [Unit Tests for most contributions](https://github.com/MycroftAI/mycroft/tree/master/test)
|
||||
* [Intent Tests for new skills](https://github.com/MycroftAI/mycroft/tree/master/mycroft/skills/weather)
|
||||
* We utilize TRAVIS-CI, which will test each pull request. To test locally you can run: `./start.sh unittest`
|
||||
10. Once everything is OK, you can finally create a Pull Request (PR) on Github in order to be reviewed and merged (to provide GH wiki page link)
|
||||
|
||||
**Note**: Even if you have write access to the master branch, do not work directly on master!
|
||||
|
||||
## Submit Changes
|
||||
|
||||
* Push your changes to a topic branch in your fork of the repository.
|
||||
* Open a pull request to the original repository and choose the right original branch you want to patch.
|
||||
_Advanced users may install the `hub` gem and use the [`hub pull-request` command](https://github.com/defunkt/hub#git-pull-request)._
|
||||
* If not done in commit messages (which you really should do) please reference and update your issue with the code changes. But _please do not close the issue yourself_.
|
||||
* Even if you have write access to the repository, do not directly push or merge pull-requests. Let another team member review your pull request and approve.
|
||||
|
||||
# Additional Resources
|
||||
|
||||
* [General GitHub documentation](http://help.github.com/)
|
||||
* [GitHub pull request documentation](http://help.github.com/send-pull-requests/)
|
||||
* [Read the Issue Guidelines by @necolas](https://github.com/necolas/issue-guidelines/blob/master/CONTRIBUTING.md) for more details
|
1
LICENSE
1
LICENSE
|
@ -672,3 +672,4 @@ may consider it more useful to permit linking proprietary applications with
|
|||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
|
||||
|
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
55
README.md
55
README.md
|
@ -1,2 +1,53 @@
|
|||
# mycroft-core
|
||||
Mycroft A.I. Core Source
|
||||
Mycroft
|
||||
==========
|
||||
|
||||
Full docs at: https://docs.mycroft.ai
|
||||
|
||||
Pair Mycroft instance with Cerberus Account Management Service: https://cerberus.mycroft.ai
|
||||
|
||||
# Getting Started in Ubuntu - Development Environment
|
||||
- Install ` virtualenv` >= 13.1.2 and `virtualenvwrapper` (Restart session)
|
||||
- Install the following native packages
|
||||
- `libtool`
|
||||
- `autoconf`
|
||||
- `bison`
|
||||
- `swig`
|
||||
- `libglib2.0-dev`
|
||||
- `portaudio19-dev`
|
||||
- `python-dev`
|
||||
- `curl`
|
||||
- `mpg123`
|
||||
- `espeak`
|
||||
- run `dev_setup.sh` (feel free to read it, as well)
|
||||
- Restart session (reboot computer, or logging out and back in might work).
|
||||
|
||||
## Cerberus Device and Account Manager
|
||||
Mycroft AI, Inc. - the company behind Mycroft maintains the Cerberus device and account management system. Developers can sign up at https://cerberus.mycroft.ai
|
||||
|
||||
Once signed up you can pair a device and use our API keys for services, such as the STT (Speech-to-Text) API. It also uses allows you to use our API keys for weather, Wolfram-Alpha, and various other skills.
|
||||
|
||||
If you do not wish to use our service, you may insert your own API keys into the configuration file.
|
||||
|
||||
## Configuration
|
||||
Mycroft configuration consists of 3 possible config files.
|
||||
- `defaults.ini`, which lives inside the mycroft codebase/distribution
|
||||
- `/etc/mycroft/mycroft.ini`
|
||||
- `$HOME/.mycroft/mycroft.ini`
|
||||
|
||||
When the configuration loader starts, it looks in those locations in that order, and loads ALL configuration. Keys that exist in multiple config files will be overridden by the last file to contain that config value. This results in a minimal amount of config being written for a specific device/user, without modifying the distribution files.
|
||||
|
||||
## Starting the Virtualenv
|
||||
To ensure that you are in the Mycroft virtualenv before trying to start the services, as everything is installed there, Run:
|
||||
```
|
||||
workon mycroft
|
||||
```
|
||||
|
||||
### Running the initial stack
|
||||
- run `PYTHONPATH=. python client/speech/main.py` # the main speech detection loop, which prints events to stdout and broadcasts them to a message bus
|
||||
- run `PYTHONPATH=. python client/messagebus/service/main.py` # the main message bus, implemented via web sockets
|
||||
- run `PYTHONPATH=. python client/skills/main.py` # main skills executable, loads all skills under skills dir
|
||||
|
||||
### Running stack via the script
|
||||
- run `./start.sh service`
|
||||
- run `./start.sh skills`
|
||||
- run `./start.sh voice`
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
sudo apt-get install -y \
|
||||
git \
|
||||
python \
|
||||
python-dev \
|
||||
python-virtualenv \
|
||||
python-gobject-dev \
|
||||
virtualenvwrapper \
|
||||
libtool \
|
||||
libffi-dev \
|
||||
autoconf \
|
||||
bison \
|
||||
swig \
|
||||
libglib2.0-dev \
|
||||
s3cmd \
|
||||
portaudio19-dev \
|
||||
mpg123
|
||||
|
||||
# upgrade virtualenv to latest from pypi
|
||||
sudo easy_install --upgrade virtualenv
|
|
@ -0,0 +1,42 @@
|
|||
#!/usr/bin/env bash
|
||||
# exit on any error
|
||||
set -Ee
|
||||
|
||||
TOP=$(cd $(dirname $0) && pwd -L)
|
||||
VIRTUALENV_ROOT=${VIRTUALENV_ROOT:-"${HOME}/.virtualenvs/mycroft"}
|
||||
|
||||
# create virtualenv, consistent with virtualenv-wrapper conventions
|
||||
if [ ! -d ${VIRTUALENV_ROOT} ]; then
|
||||
mkdir -p $(dirname ${VIRTUALENV_ROOT})
|
||||
virtualenv ${VIRTUALENV_ROOT}
|
||||
fi
|
||||
source ${VIRTUALENV_ROOT}/bin/activate
|
||||
cd ${TOP}
|
||||
easy_install pip==7.1.2 # force version of pip
|
||||
|
||||
# install requirements (except pocketsphinx)
|
||||
pip install -r requirements.txt --trusted-host pypi.mycroft.team
|
||||
|
||||
# clone pocketsphinx-python at HEAD (fix to a constant version later)
|
||||
if [ ! -d ${TOP}/pocketsphinx-python ]; then
|
||||
# build sphinxbase and pocketsphinx if we haven't already
|
||||
git clone --recursive https://github.com/cmusphinx/pocketsphinx-python
|
||||
cd ${TOP}/pocketsphinx-python/sphinxbase
|
||||
./autogen.sh
|
||||
./configure
|
||||
make
|
||||
cd ${TOP}/pocketsphinx-python/pocketsphinx
|
||||
./autogen.sh
|
||||
./configure
|
||||
make
|
||||
fi
|
||||
|
||||
# build and install pocketsphinx python bindings
|
||||
cd ${TOP}/pocketsphinx-python
|
||||
python setup.py install
|
||||
|
||||
#build and install mimic
|
||||
#./install-mimic.sh
|
||||
|
||||
# install pygtk for desktop_launcher skill
|
||||
${TOP}/install-pygtk.sh
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1,53 @@
|
|||
import os
|
||||
import pdoc
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
DOCS_NAME = "mycroft-skills-sdk"
|
||||
|
||||
DOC_OUTPUT_DIR = "build/doc/%s/html" % DOCS_NAME
|
||||
|
||||
documented_sdk_modules = [
|
||||
"mycroft.configuration",
|
||||
"mycroft.configuration.config",
|
||||
"mycroft.dialog",
|
||||
"mycroft.filesystem",
|
||||
"mycroft.session",
|
||||
"mycroft.util",
|
||||
"mycroft.util.log"
|
||||
]
|
||||
|
||||
|
||||
def module_to_docpath(module_name):
|
||||
module_source_dir = module_name.replace(".", "/")
|
||||
module_doc_dir = os.path.join(DOC_OUTPUT_DIR, module_source_dir)
|
||||
base_module_name = os.path.basename(module_doc_dir)
|
||||
if not os.path.isdir(module_source_dir):
|
||||
d = os.path.dirname(module_doc_dir)
|
||||
try:
|
||||
os.makedirs(d)
|
||||
except OSError:
|
||||
pass
|
||||
return os.path.join(d, base_module_name + '.m.html')
|
||||
else:
|
||||
try:
|
||||
os.makedirs(module_doc_dir)
|
||||
except OSError:
|
||||
pass
|
||||
return os.path.join(module_doc_dir, 'index.html')
|
||||
|
||||
|
||||
def main():
|
||||
for m in documented_sdk_modules:
|
||||
html = pdoc.html(m, allsubmodules=True)
|
||||
with open(module_to_docpath(m), 'w') as f:
|
||||
f.write(html)
|
||||
import mycroft
|
||||
mycroft.__all__ = [m[8:] for m in documented_sdk_modules]
|
||||
root_module = pdoc.Module(mycroft)
|
||||
html = root_module.html(external_links=False, link_prefix='', source=True)
|
||||
with open(module_to_docpath("mycroft"), 'w') as f:
|
||||
f.write(html)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env bash
|
||||
# exit on any error
|
||||
set -Ee
|
||||
|
||||
MIMIC_DIR=mimic
|
||||
|
||||
# download and install mimic
|
||||
if [ ! -d ${MIMIC_DIR} ]; then
|
||||
git clone https://github.com/MycroftAI/mimic.git
|
||||
cd ${MIMIC_DIR}
|
||||
./configure --with-audio=alsa
|
||||
make
|
||||
else
|
||||
# ensure mimic is up to date
|
||||
cd ${MIMIC_DIR}
|
||||
git pull
|
||||
make clean
|
||||
./configure --with-audio=alsa
|
||||
make
|
||||
fi
|
|
@ -0,0 +1,76 @@
|
|||
# Ensure we're in a virtualenv.
|
||||
if [ "$VIRTUAL_ENV" == "" ]
|
||||
then
|
||||
echo "ERROR: not in a virtual environment."
|
||||
exit -1
|
||||
fi
|
||||
|
||||
# Setup variables.
|
||||
CACHE="/tmp/install-pygtk-$$"
|
||||
|
||||
# Make temp directory.
|
||||
mkdir -p $CACHE
|
||||
|
||||
# Test for py2cairo.
|
||||
echo -e "\E[1m * Checking for cairo...\E[0m"
|
||||
python -c "
|
||||
try: import cairo; raise SystemExit(0)
|
||||
except ImportError: raise SystemExit(-1)"
|
||||
|
||||
if [ $? == 255 ]
|
||||
then
|
||||
echo -e "\E[1m * Installing cairo...\E[0m"
|
||||
# Fetch, build, and install py2cairo.
|
||||
( cd $CACHE
|
||||
curl 'http://cairographics.org/releases/py2cairo-1.10.0.tar.bz2' > "py2cairo.tar.bz2"
|
||||
tar -xvf py2cairo.tar.bz2
|
||||
( cd py2cairo*
|
||||
autoreconf -ivf
|
||||
./configure --prefix=$VIRTUAL_ENV --disable-dependency-tracking
|
||||
make
|
||||
make install
|
||||
)
|
||||
)
|
||||
fi
|
||||
|
||||
# Test for gobject.
|
||||
echo -e "\E[1m * Checking for gobject...\E[0m"
|
||||
python -c "
|
||||
try: import gobject; raise SystemExit(0)
|
||||
except ImportError: raise SystemExit(-1)"
|
||||
|
||||
if [ $? == 255 ]
|
||||
then
|
||||
echo -e "\E[1m * Installing gobject...\E[0m"
|
||||
# Fetch, build, and install gobject.
|
||||
( cd $CACHE
|
||||
curl 'http://ftp.gnome.org/pub/GNOME/sources/pygobject/2.28/pygobject-2.28.6.tar.bz2' > 'pygobject.tar.bz2'
|
||||
tar -xvf pygobject.tar.bz2
|
||||
( cd pygobject*
|
||||
./configure --prefix=$VIRTUAL_ENV --disable-introspection
|
||||
make
|
||||
make install
|
||||
)
|
||||
)
|
||||
fi
|
||||
|
||||
# Test for gtk.
|
||||
echo -e "\E[1m * Checking for gtk...\E[0m"
|
||||
python -c "
|
||||
try: import gtk; raise SystemExit(0)
|
||||
except ImportError: raise SystemExit(-1)" 2&> /dev/null
|
||||
|
||||
if [ $? == 255 ]
|
||||
then
|
||||
echo -e "\E[1m * Installing gtk...\E[0m"
|
||||
# Fetch, build, and install gtk.
|
||||
( cd $CACHE
|
||||
curl 'https://pypi.python.org/packages/source/P/PyGTK/pygtk-2.24.0.tar.bz2' > 'pygtk.tar.bz2'
|
||||
tar -xvf pygtk.tar.bz2
|
||||
( cd pygtk*
|
||||
./configure --prefix=$VIRTUAL_ENV PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:$VIRTUAL_ENV/lib/pkgconfig
|
||||
make
|
||||
make install
|
||||
)
|
||||
)
|
||||
fi
|
|
@ -0,0 +1,6 @@
|
|||
recursive-include mycroft/client/speech/model *
|
||||
include requirements.txt
|
||||
include mycroft/configuration/defaults/*.ini
|
||||
recursive-include mycroft/skills/*/dialog *
|
||||
recursive-include mycroft/skills/*/vocab *
|
||||
include mycroft/skills/alarm/alarm.wav
|
|
@ -0,0 +1,26 @@
|
|||
from setuptools import setup
|
||||
|
||||
from mycroft.util.setup_base import find_all_packages, required, get_version, place_manifest
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
place_manifest('mycroft-base-MANIFEST.in')
|
||||
|
||||
setup(
|
||||
name="Mycroft",
|
||||
version=get_version(),
|
||||
install_requires=required('requirements.txt'),
|
||||
packages=find_all_packages("mycroft"),
|
||||
include_package_data=True,
|
||||
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'mycroft-speech-client=mycroft.client.speech.main:main',
|
||||
'mycroft-messagebus=mycroft.messagebus.service.main:main',
|
||||
'mycroft-skills=mycroft.skills.main:main',
|
||||
'mycroft-echo-observer=mycroft.messagebus.client.ws:echo',
|
||||
'mycroft-audio-test=mycroft.util.audio_test:main',
|
||||
'mycroft-enclosure-client=mycroft.client.enclosure.enclosure:main'
|
||||
]
|
||||
}
|
||||
)
|
|
@ -0,0 +1,5 @@
|
|||
from os.path import abspath, dirname, join
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
MYCROFT_ROOT_PATH = abspath(join(dirname(__file__), '..'))
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1,65 @@
|
|||
from mycroft.messagebus.message import Message
|
||||
from mycroft.util.log import getLogger
|
||||
|
||||
__author__ = 'jdorleans'
|
||||
|
||||
LOGGER = getLogger(__name__)
|
||||
|
||||
|
||||
class EnclosureAPI:
|
||||
"""
|
||||
This API is intended to be used to control Mycroft hardware capabilities.
|
||||
|
||||
It exposes all possible enclosure commands to be performed by a Mycroft unit.
|
||||
"""
|
||||
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
def system_mute(self):
|
||||
self.client.emit(Message("enclosure.system.mute"))
|
||||
|
||||
def system_unmute(self):
|
||||
self.client.emit(Message("enclosure.system.unmute"))
|
||||
|
||||
def system_blink(self, times):
|
||||
self.client.emit(Message("enclosure.system.blink", metadata={'times': times}))
|
||||
|
||||
def eyes_on(self):
|
||||
self.client.emit(Message("enclosure.eyes.on"))
|
||||
|
||||
def eyes_off(self):
|
||||
self.client.emit(Message("enclosure.eyes.off"))
|
||||
|
||||
def eyes_blink(self, side):
|
||||
self.client.emit(Message("enclosure.eyes.blink", metadata={'side': side}))
|
||||
|
||||
def eyes_narrow(self):
|
||||
self.client.emit(Message("enclosure.eyes.narrow"))
|
||||
|
||||
def eyes_look(self, side):
|
||||
self.client.emit(Message("enclosure.eyes.look", metadata={'side': side}))
|
||||
|
||||
def eyes_color(self, r=255, g=255, b=255):
|
||||
self.client.emit(Message("enclosure.eyes.color", metadata={'r': r, 'g': g, 'b': b}))
|
||||
|
||||
def eyes_brightness(self, level=30):
|
||||
self.client.emit(Message("enclosure.eyes.level", metadata={'level': level}))
|
||||
|
||||
def mouth_reset(self):
|
||||
self.client.emit(Message("enclosure.mouth.reset"))
|
||||
|
||||
def mouth_talk(self):
|
||||
self.client.emit(Message("enclosure.mouth.talk"))
|
||||
|
||||
def mouth_think(self):
|
||||
self.client.emit(Message("enclosure.mouth.think"))
|
||||
|
||||
def mouth_listen(self):
|
||||
self.client.emit(Message("enclosure.mouth.listen"))
|
||||
|
||||
def mouth_smile(self):
|
||||
self.client.emit(Message("enclosure.mouth.smile"))
|
||||
|
||||
def mouth_text(self, text=""):
|
||||
self.client.emit(Message("enclosure.mouth.text", metadata={'text': text}))
|
|
@ -0,0 +1,35 @@
|
|||
from mycroft.util.log import getLogger
|
||||
|
||||
__author__ = 'jdorleans'
|
||||
|
||||
LOGGER = getLogger(__name__)
|
||||
|
||||
|
||||
class EnclosureArduino:
|
||||
"""
|
||||
Listens to enclosure commands for Mycroft's Arduino.
|
||||
|
||||
Performs the associated command on Arduino by writing on the Serial port.
|
||||
"""
|
||||
|
||||
def __init__(self, client, writer):
|
||||
self.client = client
|
||||
self.writer = writer
|
||||
self.__init_events()
|
||||
|
||||
def __init_events(self):
|
||||
self.client.on('enclosure.system.mute', self.mute)
|
||||
self.client.on('enclosure.system.unmute', self.unmute)
|
||||
self.client.on('enclosure.system.blink', self.blink)
|
||||
|
||||
def mute(self, event=None):
|
||||
self.writer.write("system.mute")
|
||||
|
||||
def unmute(self, event=None):
|
||||
self.writer.write("system.unmute")
|
||||
|
||||
def blink(self, event=None):
|
||||
times = 1
|
||||
if event and event.metadata:
|
||||
times = event.metadata.get("times", times)
|
||||
self.writer.write("system.blink=" + str(times))
|
|
@ -0,0 +1,166 @@
|
|||
import serial
|
||||
import sys
|
||||
from Queue import Queue
|
||||
from threading import Thread
|
||||
|
||||
from mycroft.client.enclosure.arduino import EnclosureArduino
|
||||
from mycroft.client.enclosure.eyes import EnclosureEyes
|
||||
from mycroft.client.enclosure.mouth import EnclosureMouth
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
from mycroft.messagebus.client.ws import WebsocketClient
|
||||
from mycroft.messagebus.message import Message
|
||||
from mycroft.util import kill
|
||||
from mycroft.util.log import getLogger
|
||||
|
||||
__author__ = 'aatchison + jdorleans'
|
||||
|
||||
LOGGER = getLogger("EnclosureClient")
|
||||
|
||||
|
||||
class EnclosureReader(Thread):
|
||||
"""
|
||||
Reads data from Serial port.
|
||||
|
||||
Listens to all commands sent by Arduino that must be be performed on Mycroft Core.
|
||||
|
||||
E.g. Mycroft Stop Feature
|
||||
#. Arduino sends a Stop command after a button press on a Mycroft unit
|
||||
#. ``EnclosureReader`` captures the Stop command
|
||||
#. Notify all Mycroft Core processes (e.g. skills) to be stopped
|
||||
|
||||
Note: A command is identified by a line break
|
||||
"""
|
||||
|
||||
def __init__(self, serial, client):
|
||||
super(EnclosureReader, self).__init__(target=self.read)
|
||||
self.alive = True
|
||||
self.daemon = True
|
||||
self.serial = serial
|
||||
self.client = client
|
||||
self.start()
|
||||
|
||||
def read(self):
|
||||
while self.alive:
|
||||
try:
|
||||
data = self.serial.readline()[:-2]
|
||||
if data:
|
||||
self.process(data)
|
||||
LOGGER.info("Reading: " + data)
|
||||
except Exception as e:
|
||||
LOGGER.error("Reading error: {0}".format(e))
|
||||
|
||||
def process(self, data):
|
||||
if "mycroft.stop" in data:
|
||||
self.client.emit(Message("mycroft.stop"))
|
||||
kill(['mimic']) # TODO - Refactoring in favor of Mycroft Stop
|
||||
|
||||
def stop(self):
|
||||
self.alive = False
|
||||
self.join()
|
||||
|
||||
|
||||
class EnclosureWriter(Thread):
|
||||
"""
|
||||
Writes data to Serial port.
|
||||
#. Enqueues all commands received from Mycroft enclosures implementation
|
||||
#. Process them on the received order by writing on the Serial port
|
||||
|
||||
E.g. Displaying a text on Mycroft's Mouth
|
||||
#. ``EnclosureMouth`` sends a text command
|
||||
#. ``EnclosureWriter`` captures and enqueue the command
|
||||
#. ``EnclosureWriter`` removes the next command from the queue
|
||||
#. ``EnclosureWriter`` writes the command to Serial port
|
||||
|
||||
Note: A command has to end with a line break
|
||||
"""
|
||||
|
||||
def __init__(self, serial, client, size=16):
|
||||
super(EnclosureWriter, self).__init__(target=self.flush)
|
||||
self.alive = True
|
||||
self.daemon = True
|
||||
self.serial = serial
|
||||
self.client = client
|
||||
self.commands = Queue(size)
|
||||
self.start()
|
||||
|
||||
def flush(self):
|
||||
while self.alive:
|
||||
try:
|
||||
cmd = self.commands.get()
|
||||
self.serial.write(cmd + '\n')
|
||||
LOGGER.info("Writing: " + cmd)
|
||||
self.commands.task_done()
|
||||
except Exception as e:
|
||||
LOGGER.error("Writing error: {0}".format(e))
|
||||
|
||||
def write(self, command):
|
||||
self.commands.put(str(command))
|
||||
|
||||
def stop(self):
|
||||
self.alive = False
|
||||
self.join()
|
||||
|
||||
|
||||
class Enclosure:
|
||||
"""
|
||||
Serves as a communication interface between Arduino and Mycroft Core.
|
||||
|
||||
``Enclosure`` initializes and aggregates all enclosures implementation.
|
||||
|
||||
E.g. ``EnclosureEyes``, ``EnclosureMouth`` and ``EnclosureArduino``
|
||||
|
||||
It also listens to the basis events in order to perform those core actions on the unit.
|
||||
|
||||
E.g. Start and Stop talk animation
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.__init_serial()
|
||||
self.client = WebsocketClient()
|
||||
self.reader = EnclosureReader(self.serial, self.client)
|
||||
self.writer = EnclosureWriter(self.serial, self.client)
|
||||
self.eyes = EnclosureEyes(self.client, self.writer)
|
||||
self.mouth = EnclosureMouth(self.client, self.writer)
|
||||
self.system = EnclosureArduino(self.client, self.writer)
|
||||
self.__init_events()
|
||||
|
||||
def __init_serial(self):
|
||||
try:
|
||||
self.config = ConfigurationManager.get_config().get("enclosure")
|
||||
self.port = self.config.get("port")
|
||||
self.rate = int(self.config.get("rate"))
|
||||
self.timeout = int(self.config.get("timeout"))
|
||||
self.serial = serial.serial_for_url(url=self.port, baudrate=self.rate, timeout=self.timeout)
|
||||
LOGGER.info("Connected to: " + self.port + " rate: " + str(self.rate) + " timeout: " + str(self.timeout))
|
||||
except:
|
||||
LOGGER.error("It is not possible to connect to serial port: " + self.port)
|
||||
raise
|
||||
|
||||
def __init_events(self):
|
||||
self.client.on('recognizer_loop:listening', self.mouth.listen)
|
||||
self.client.on('recognizer_loop:audio_output_start', self.mouth.talk)
|
||||
self.client.on('recognizer_loop:audio_output_end', self.mouth.reset)
|
||||
self.client.on('recognizer_loop:wakeword', self.eyes.blink)
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
self.client.run_forever()
|
||||
except Exception as e:
|
||||
LOGGER.error("Client error: {0}".format(e))
|
||||
self.stop()
|
||||
|
||||
def stop(self):
|
||||
self.writer.stop()
|
||||
self.reader.stop()
|
||||
self.serial.close()
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
Enclosure().run()
|
||||
finally:
|
||||
sys.exit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
|
@ -0,0 +1,62 @@
|
|||
from mycroft.util.log import getLogger
|
||||
|
||||
__author__ = 'jdorleans'
|
||||
|
||||
LOGGER = getLogger(__name__)
|
||||
|
||||
|
||||
class EnclosureEyes:
|
||||
"""
|
||||
Listens to enclosure commands for Mycroft's Eyes.
|
||||
|
||||
Performs the associated command on Arduino by writing on the Serial port.
|
||||
"""
|
||||
|
||||
def __init__(self, client, writer):
|
||||
self.client = client
|
||||
self.writer = writer
|
||||
self.__init_events()
|
||||
|
||||
def __init_events(self):
|
||||
self.client.on('enclosure.eyes.on', self.on)
|
||||
self.client.on('enclosure.eyes.off', self.off)
|
||||
self.client.on('enclosure.eyes.blink', self.blink)
|
||||
self.client.on('enclosure.eyes.narrow', self.narrow)
|
||||
self.client.on('enclosure.eyes.look', self.look)
|
||||
self.client.on('enclosure.eyes.color', self.color)
|
||||
self.client.on('enclosure.eyes.level', self.brightness)
|
||||
|
||||
def on(self, event=None):
|
||||
self.writer.write("eyes.on")
|
||||
|
||||
def off(self, event=None):
|
||||
self.writer.write("eyes.off")
|
||||
|
||||
def blink(self, event=None):
|
||||
side = "b"
|
||||
if event and event.metadata:
|
||||
side = event.metadata.get("side", side)
|
||||
self.writer.write("eyes.blink=" + side)
|
||||
|
||||
def narrow(self, event=None):
|
||||
self.writer.write("eyes.narrow")
|
||||
|
||||
def look(self, event=None):
|
||||
if event and event.metadata:
|
||||
side = event.metadata.get("side", "")
|
||||
self.writer.write("eyes.look=" + side)
|
||||
|
||||
def color(self, event=None):
|
||||
r, g, b = 255, 255, 255
|
||||
if event and event.metadata:
|
||||
r = int(event.metadata.get("r"), r)
|
||||
g = int(event.metadata.get("g"), g)
|
||||
b = int(event.metadata.get("b"), b)
|
||||
color = (r * 65536) + (g * 256) + b
|
||||
self.writer.write("eyes.color=" + str(color))
|
||||
|
||||
def brightness(self, event=None):
|
||||
level = 30
|
||||
if event and event.metadata:
|
||||
level = event.metadata.get("level", level)
|
||||
self.writer.write("eyes.level=" + str(level))
|
|
@ -0,0 +1,47 @@
|
|||
from mycroft.util.log import getLogger
|
||||
|
||||
__author__ = 'jdorleans'
|
||||
|
||||
LOGGER = getLogger(__name__)
|
||||
|
||||
|
||||
class EnclosureMouth:
|
||||
"""
|
||||
Listens to enclosure commands for Mycroft's Mouth.
|
||||
|
||||
Performs the associated command on Arduino by writing on the Serial port.
|
||||
"""
|
||||
|
||||
def __init__(self, client, writer):
|
||||
self.client = client
|
||||
self.writer = writer
|
||||
self.__init_events()
|
||||
|
||||
def __init_events(self):
|
||||
self.client.on('enclosure.mouth.reset', self.reset)
|
||||
self.client.on('enclosure.mouth.talk', self.talk)
|
||||
self.client.on('enclosure.mouth.think', self.think)
|
||||
self.client.on('enclosure.mouth.listen', self.listen)
|
||||
self.client.on('enclosure.mouth.smile', self.smile)
|
||||
self.client.on('enclosure.mouth.text', self.text)
|
||||
|
||||
def reset(self, event=None):
|
||||
self.writer.write("mouth.reset")
|
||||
|
||||
def talk(self, event=None):
|
||||
self.writer.write("mouth.talk")
|
||||
|
||||
def think(self, event=None):
|
||||
self.writer.write("mouth.think")
|
||||
|
||||
def listen(self, event=None):
|
||||
self.writer.write("mouth.listen")
|
||||
|
||||
def smile(self, event=None):
|
||||
self.writer.write("mouth.smile")
|
||||
|
||||
def text(self, event=None):
|
||||
text = ""
|
||||
if event and event.metadata:
|
||||
text = event.metadata.get("text", text)
|
||||
self.writer.write("mouth.text=" + text)
|
|
@ -0,0 +1 @@
|
|||
0.1.2
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1,351 @@
|
|||
import threading
|
||||
import time
|
||||
from Queue import Queue
|
||||
|
||||
import os
|
||||
import pyee
|
||||
import speech_recognition as sr
|
||||
from speech_recognition import AudioData
|
||||
|
||||
from mycroft.client.speech import wakeword_recognizer
|
||||
from mycroft.client.speech.mic import MutableMicrophone, Recognizer
|
||||
from mycroft.client.speech.recognizer_wrapper import RemoteRecognizerWrapperFactory
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
from mycroft.messagebus.message import Message
|
||||
from mycroft.metrics import MetricsAggregator, Stopwatch
|
||||
from mycroft.session import SessionManager
|
||||
from mycroft.util import read_stripped_lines, CerberusAccessDenied
|
||||
from mycroft.util.log import getLogger
|
||||
|
||||
logger = getLogger(__name__)
|
||||
|
||||
core_config = ConfigurationManager.get_config().get('core')
|
||||
speech_config = ConfigurationManager.get_config().get('speech_client')
|
||||
|
||||
|
||||
class AudioProducer(threading.Thread):
|
||||
"""
|
||||
AudioProducer
|
||||
given a mic and a recognizer implementation, continuously listens to the mic for
|
||||
potential speech chunks and pushes them onto the queue.
|
||||
"""
|
||||
def __init__(self, state, queue, mic, recognizer, emitter):
|
||||
threading.Thread.__init__(self)
|
||||
self.daemon = True
|
||||
self.state = state
|
||||
self.queue = queue
|
||||
self.mic = mic
|
||||
self.recognizer = recognizer
|
||||
self.emitter = emitter
|
||||
|
||||
def run(self):
|
||||
with self.mic as source:
|
||||
self.recognizer.adjust_for_ambient_noise(source)
|
||||
while self.state.running:
|
||||
try:
|
||||
self.emitter.emit("recognizer_loop:listening")
|
||||
audio = self.recognizer.listen(source)
|
||||
self.queue.put(audio)
|
||||
except IOError, ex:
|
||||
# NOTE: Audio stack on raspi is slightly different, throws IOError every other listen,
|
||||
# almost like it can't handle buffering audio between listen loops.
|
||||
# The internet was not helpful.
|
||||
# http://stackoverflow.com/questions/10733903/pyaudio-input-overflowed
|
||||
self.emitter.emit("recognizer_loop:ioerror", ex)
|
||||
|
||||
|
||||
class WakewordExtractor:
|
||||
|
||||
MAX_ERROR_SECONDS = 0.02
|
||||
TRIM_SECONDS = 0.1
|
||||
PUSH_BACK_SECONDS = 0.2 # The seconds the safe end position is pushed back to ensure pocketsphinx is consistent
|
||||
SILENCE_SECONDS = 0.2 # The seconds of silence padded where the wakeword was removed
|
||||
|
||||
def __init__(self, audio_data, recognizer, metrics):
|
||||
self.audio_data = audio_data
|
||||
self.recognizer = recognizer
|
||||
self.silence_data = self.__generate_silence(self.SILENCE_SECONDS, self.audio_data.sample_rate, self.audio_data.sample_width)
|
||||
self.wav_data = self.audio_data.get_wav_data()
|
||||
self.AUDIO_SIZE = float(len(self.wav_data))
|
||||
self.range = self.Range(0, self.AUDIO_SIZE / 2)
|
||||
self.metrics = metrics
|
||||
|
||||
class Range:
|
||||
def __init__(self, begin, end):
|
||||
self.begin = begin
|
||||
self.end = end
|
||||
|
||||
def get_marker(self, get_begin):
|
||||
if get_begin:
|
||||
return self.begin
|
||||
else:
|
||||
return self.end
|
||||
|
||||
def add_to_marker(self, add_begin, value):
|
||||
if add_begin:
|
||||
self.begin += value
|
||||
else:
|
||||
self.end += value
|
||||
|
||||
def narrow(self, value):
|
||||
self.begin += value
|
||||
self.end -= value
|
||||
|
||||
@staticmethod
|
||||
def __found_in_segment(name, byte_data, recognizer, metrics):
|
||||
|
||||
hypothesis = recognizer.transcribe(byte_data, metrics=metrics)
|
||||
if hypothesis and hypothesis.hypstr.lower().find(name):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def audio_pos(self, raw_pos):
|
||||
return int(self.audio_data.sample_width * round(float(raw_pos)/self.audio_data.sample_width))
|
||||
|
||||
def get_audio_segment(self, begin, end):
|
||||
return self.wav_data[self.audio_pos(begin) : self.audio_pos(end)]
|
||||
|
||||
def __calculate_marker(self, use_begin, sign_if_found, range, delta):
|
||||
while 2 * delta >= self.MAX_ERROR_SECONDS * self.audio_data.sample_rate * self.audio_data.sample_width:
|
||||
byte_data = self.get_audio_segment(range.begin, range.end)
|
||||
found = self.__found_in_segment("mycroft", byte_data, self.recognizer, self.metrics)
|
||||
sign = sign_if_found if found else -sign_if_found
|
||||
range.add_to_marker(use_begin, delta * sign)
|
||||
delta /= 2
|
||||
return range.get_marker(use_begin)
|
||||
|
||||
def calculate_range(self):
|
||||
delta = self.AUDIO_SIZE / 4
|
||||
self.range.end = self.__calculate_marker(False, -1, self.Range(0, self.AUDIO_SIZE / 2), delta)
|
||||
|
||||
# Ensures the end position is well past the wakeword part of the audio
|
||||
pos_end_safe = min(self.AUDIO_SIZE, self.range.end + self.PUSH_BACK_SECONDS * self.audio_data.sample_rate * self.audio_data.sample_width)
|
||||
delta = pos_end_safe / 4
|
||||
begin = pos_end_safe / 2
|
||||
self.range.begin = self.__calculate_marker(True, 1, self.Range(begin, pos_end_safe), delta)
|
||||
self.range.narrow(self.TRIM_SECONDS * self.audio_data.sample_rate * self.audio_data.sample_width)
|
||||
|
||||
@staticmethod
|
||||
def __generate_silence(seconds, sample_rate, sample_width):
|
||||
return '\0'*int(seconds * sample_rate * sample_width)
|
||||
|
||||
def get_audio_data_before(self):
|
||||
byte_data = self.get_audio_segment(0, self.range.begin) + self.silence_data
|
||||
return AudioData(byte_data, self.audio_data.sample_rate,self.audio_data.sample_width)
|
||||
|
||||
def get_audio_data_after(self):
|
||||
byte_data = self.silence_data + self.get_audio_segment(self.range.end, self.AUDIO_SIZE)
|
||||
return AudioData(byte_data, self.audio_data.sample_rate,self.audio_data.sample_width)
|
||||
|
||||
|
||||
class AudioConsumer(threading.Thread):
|
||||
"""
|
||||
AudioConsumer
|
||||
Consumes AudioData chunks off the queue
|
||||
"""
|
||||
|
||||
MIN_AUDIO_SIZE = 1.0 # In seconds, the minimum audio size to be sent to remote STT
|
||||
|
||||
def __init__(self, state, queue, emitter, wakeup_recognizer, wakeword_recognizer,
|
||||
wrapped_remote_recognizer, wakeup_prefixes, wakeup_words):
|
||||
threading.Thread.__init__(self)
|
||||
self.daemon = True
|
||||
self.queue = queue
|
||||
self.state = state
|
||||
self.emitter = emitter
|
||||
self.wakeup_recognizer = wakeup_recognizer
|
||||
self.ww_recognizer = wakeword_recognizer
|
||||
self.wrapped_remote_recognizer = wrapped_remote_recognizer
|
||||
self.wakeup_prefixes = wakeup_prefixes
|
||||
self.wakeup_words = wakeup_words
|
||||
self.metrics = MetricsAggregator()
|
||||
|
||||
def run(self):
|
||||
while self.state.running:
|
||||
self.try_consume_audio()
|
||||
|
||||
@staticmethod
|
||||
def _audio_length(audio):
|
||||
return float(len(audio.frame_data))/(audio.sample_rate*audio.sample_width)
|
||||
|
||||
def try_consume_audio(self):
|
||||
timer = Stopwatch()
|
||||
hyp = None
|
||||
audio = self.queue.get()
|
||||
self.metrics.timer("mycroft.recognizer.audio.length_s", self._audio_length(audio))
|
||||
self.queue.task_done()
|
||||
timer.start()
|
||||
if self.state.sleeping:
|
||||
hyp = self.wakeup_recognizer.transcribe(audio.get_wav_data(), metrics=self.metrics)
|
||||
if hyp and hyp.hypstr:
|
||||
logger.debug("sleeping recognition: " + hyp.hypstr)
|
||||
if hyp and hyp.hypstr.lower().find("wake up") >= 0:
|
||||
SessionManager.touch()
|
||||
self.state.sleeping = False
|
||||
self.__speak("I'm awake.") # TODO: Localization
|
||||
self.metrics.increment("mycroft.wakeup")
|
||||
else:
|
||||
if not self.state.skip_wakeword:
|
||||
hyp = self.ww_recognizer.transcribe(audio.get_wav_data(), metrics=self.metrics)
|
||||
|
||||
if hyp and hyp.hypstr.lower().find("mycroft") >= 0:
|
||||
extractor = WakewordExtractor(audio, self.ww_recognizer, self.metrics)
|
||||
timer.lap()
|
||||
extractor.calculate_range()
|
||||
self.metrics.timer("mycroft.recognizer.extractor.time_s", timer.lap())
|
||||
audio_before = extractor.get_audio_data_before()
|
||||
self.metrics.timer("mycroft.recognizer.audio_extracted.length_s", self._audio_length(audio_before))
|
||||
audio_after = extractor.get_audio_data_after()
|
||||
self.metrics.timer("mycroft.recognizer.audio_extracted.length_s", self._audio_length(audio_after))
|
||||
|
||||
SessionManager.touch()
|
||||
payload = {
|
||||
'utterance': hyp.hypstr,
|
||||
'session': SessionManager.get().session_id,
|
||||
'pos_begin': int(extractor.range.begin),
|
||||
'pos_end': int(extractor.range.end)
|
||||
}
|
||||
self.emitter.emit("recognizer_loop:wakeword", payload)
|
||||
|
||||
try:
|
||||
self.transcribe([audio_before, audio_after])
|
||||
except sr.UnknownValueError:
|
||||
self.__speak("Go ahead")
|
||||
self.state.skip_wakeword = True
|
||||
self.metrics.increment("mycroft.wakeword")
|
||||
|
||||
elif self.state.skip_wakeword:
|
||||
SessionManager.touch()
|
||||
try:
|
||||
self.transcribe([audio])
|
||||
except sr.UnknownValueError:
|
||||
logger.warn("Speech Recognition could not understand audio")
|
||||
self.__speak("Sorry, I didn't catch that.")
|
||||
self.metrics.increment("mycroft.recognizer.error")
|
||||
self.state.skip_wakeword = False
|
||||
else:
|
||||
self.metrics.clear()
|
||||
self.metrics.flush()
|
||||
|
||||
def __speak(self, utterance):
|
||||
"""
|
||||
Speak commands should be asynchronous to avoid filling up the portaudio buffer.
|
||||
:param utterance:
|
||||
:return:
|
||||
"""
|
||||
def target():
|
||||
self.emitter.emit("speak", Message("speak", metadata={'utterance': utterance,
|
||||
'session': SessionManager.get().session_id}))
|
||||
|
||||
threading.Thread(target=target).start()
|
||||
|
||||
def _create_remote_stt_runnable(self, audio, utterances):
|
||||
def runnable():
|
||||
try:
|
||||
text = self.wrapped_remote_recognizer.transcribe(audio, metrics=self.metrics).lower()
|
||||
except sr.UnknownValueError:
|
||||
pass
|
||||
except sr.RequestError as e:
|
||||
logger.error("Could not request results from Speech Recognition service; {0}".format(e))
|
||||
except CerberusAccessDenied as e:
|
||||
logger.error("AccessDenied from Cerberus proxy.")
|
||||
self.__speak("Your device is not registered yet. To start pairing, login at cerberus.mycroft.ai")
|
||||
utterances.append("pair my device")
|
||||
else:
|
||||
logger.debug("STT: " + text)
|
||||
if text.strip() != '':
|
||||
utterances.append(text)
|
||||
return runnable
|
||||
|
||||
def transcribe(self, audio_segments):
|
||||
utterances = []
|
||||
threads = []
|
||||
for audio in audio_segments:
|
||||
if self._audio_length(audio) < self.MIN_AUDIO_SIZE:
|
||||
logger.debug("Audio too short to send to STT")
|
||||
continue
|
||||
|
||||
target = self._create_remote_stt_runnable(audio, utterances)
|
||||
t = threading.Thread(target=target)
|
||||
t.start()
|
||||
threads.append(t)
|
||||
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
if len(utterances) > 0:
|
||||
payload = {
|
||||
'utterances': utterances,
|
||||
'session': SessionManager.get().session_id
|
||||
}
|
||||
self.emitter.emit("recognizer_loop:utterance", payload)
|
||||
self.metrics.attr('utterances', utterances)
|
||||
else:
|
||||
raise sr.UnknownValueError
|
||||
|
||||
|
||||
class RecognizerLoopState(object):
|
||||
def __init__(self):
|
||||
self.running = False
|
||||
self.sleeping = False
|
||||
self.skip_wakeword = False
|
||||
|
||||
|
||||
class RecognizerLoop(pyee.EventEmitter):
|
||||
def __init__(self, channels=int(speech_config.get('channels')),
|
||||
sample_rate=int(speech_config.get('sample_rate')),
|
||||
device_index=None,
|
||||
lang=core_config.get('lang')):
|
||||
pyee.EventEmitter.__init__(self)
|
||||
self.microphone = MutableMicrophone(sample_rate=sample_rate, device_index=device_index)
|
||||
self.microphone.CHANNELS = channels
|
||||
self.ww_recognizer = wakeword_recognizer.create_recognizer(samprate=sample_rate, lang=lang)
|
||||
self.wakeup_recognizer = wakeword_recognizer.create_recognizer(samprate=sample_rate, lang=lang,
|
||||
keyphrase="wake up mycroft") # TODO - localization
|
||||
self.remote_recognizer = Recognizer()
|
||||
basedir = os.path.dirname(__file__)
|
||||
self.wakeup_words = read_stripped_lines(os.path.join(basedir, 'model', lang, 'WakeUpWord.voc'))
|
||||
self.wakeup_prefixes = read_stripped_lines(os.path.join(basedir, 'model', lang, 'PrefixWakeUp.voc'))
|
||||
self.state = RecognizerLoopState()
|
||||
|
||||
def start_async(self):
|
||||
self.state.running = True
|
||||
queue = Queue()
|
||||
AudioProducer(self.state,
|
||||
queue,
|
||||
self.microphone,
|
||||
self.remote_recognizer,
|
||||
self).start()
|
||||
AudioConsumer(self.state,
|
||||
queue,
|
||||
self,
|
||||
self.wakeup_recognizer,
|
||||
self.ww_recognizer,
|
||||
RemoteRecognizerWrapperFactory.wrap_recognizer(self.remote_recognizer),
|
||||
self.wakeup_prefixes,
|
||||
self.wakeup_words).start()
|
||||
|
||||
def stop(self):
|
||||
self.state.running = False
|
||||
|
||||
def mute(self):
|
||||
if self.microphone:
|
||||
self.microphone.mute()
|
||||
|
||||
def unmute(self):
|
||||
if self.microphone:
|
||||
self.microphone.unmute()
|
||||
|
||||
def sleep(self):
|
||||
self.state.sleeping = True
|
||||
|
||||
def awaken(self):
|
||||
self.state.sleeping = False
|
||||
|
||||
def run(self):
|
||||
self.start_async()
|
||||
while self.state.running:
|
||||
try:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt as e:
|
||||
self.stop()
|
|
@ -0,0 +1,96 @@
|
|||
import sys
|
||||
from threading import Thread, Lock
|
||||
|
||||
from mycroft.client.speech.listener import RecognizerLoop
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
from mycroft.messagebus.client.ws import WebsocketClient
|
||||
from mycroft.messagebus.message import Message
|
||||
from mycroft.tts import tts_factory
|
||||
from mycroft.util.log import getLogger
|
||||
|
||||
logger = getLogger("SpeechClient")
|
||||
client = None
|
||||
tts = tts_factory.create()
|
||||
mutex = Lock()
|
||||
loop = None
|
||||
|
||||
config = ConfigurationManager.get_config()
|
||||
|
||||
def handle_listening():
|
||||
logger.info("Listening...")
|
||||
client.emit(Message('recognizer_loop:listening'))
|
||||
|
||||
|
||||
def handle_wakeword(event):
|
||||
logger.info("Wakeword Detected: " + event['utterance'])
|
||||
client.emit(Message('recognizer_loop:wakeword', event))
|
||||
|
||||
|
||||
def handle_utterance(event):
|
||||
logger.info("Utterance: " + str(event['utterances']))
|
||||
client.emit(Message('recognizer_loop:utterance', event))
|
||||
|
||||
|
||||
def mute_and_speak(utterance):
|
||||
mutex.acquire()
|
||||
client.emit(Message("recognizer_loop:audio_output_start"))
|
||||
try:
|
||||
logger.info("Speak: " + utterance)
|
||||
loop.mute()
|
||||
tts.execute(utterance)
|
||||
finally:
|
||||
loop.unmute()
|
||||
mutex.release()
|
||||
client.emit(Message("recognizer_loop:audio_output_end"))
|
||||
|
||||
|
||||
def handle_multi_utterance_intent_failure(event):
|
||||
logger.info("Failed to find intent on multiple intents.")
|
||||
# TODO: Localize
|
||||
mute_and_speak("Sorry, I didn't catch that. Please rephrase your request.")
|
||||
|
||||
|
||||
def handle_speak(event):
|
||||
mute_and_speak(event.metadata['utterance'])
|
||||
|
||||
|
||||
def handle_sleep(event):
|
||||
loop.sleep()
|
||||
|
||||
|
||||
def handle_wake_up(event):
|
||||
loop.awaken()
|
||||
|
||||
|
||||
def connect():
|
||||
client.run_forever()
|
||||
|
||||
|
||||
def main():
|
||||
global client
|
||||
global loop
|
||||
client = WebsocketClient()
|
||||
device_index = config.get('speech_client').get('device_index')
|
||||
if device_index:
|
||||
device_index = int(device_index)
|
||||
loop = RecognizerLoop(device_index=device_index)
|
||||
loop.on('recognizer_loop:listening', handle_listening)
|
||||
loop.on('recognizer_loop:wakeword', handle_wakeword)
|
||||
loop.on('recognizer_loop:utterance', handle_utterance)
|
||||
loop.on('speak', handle_speak)
|
||||
client.on('speak', handle_speak)
|
||||
client.on('multi_utterance_intent_failure', handle_multi_utterance_intent_failure)
|
||||
client.on('recognizer_loop:sleep', handle_sleep)
|
||||
client.on('recognizer_loop:wake_up', handle_wake_up)
|
||||
event_thread = Thread(target=connect)
|
||||
event_thread.setDaemon(True)
|
||||
event_thread.start()
|
||||
try:
|
||||
loop.run()
|
||||
except KeyboardInterrupt, e:
|
||||
event_thread.exit()
|
||||
sys.exit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
|
@ -0,0 +1,177 @@
|
|||
import collections
|
||||
import math
|
||||
import audioop
|
||||
from time import sleep
|
||||
|
||||
import pyaudio
|
||||
from speech_recognition import Microphone, AudioSource, WaitTimeoutError, AudioData
|
||||
import speech_recognition
|
||||
from mycroft.util.log import getLogger
|
||||
logger = getLogger(__name__)
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
|
||||
class MutableStream(object):
|
||||
def __init__(self, wrapped_stream, format, muted=False):
|
||||
assert wrapped_stream != None
|
||||
self.wrapped_stream = wrapped_stream
|
||||
self.muted = muted
|
||||
self.SAMPLE_WIDTH = pyaudio.get_sample_size(format)
|
||||
self.muted_buffer = b''.join([b'\x00' * self.SAMPLE_WIDTH])
|
||||
|
||||
def mute(self):
|
||||
self.muted = True
|
||||
|
||||
def unmute(self):
|
||||
self.muted = False
|
||||
|
||||
def read(self, size):
|
||||
frames = collections.deque()
|
||||
remaining = size
|
||||
while remaining > 0:
|
||||
to_read = min(self.wrapped_stream.get_read_available(), remaining)
|
||||
if to_read == 0:
|
||||
sleep(.01)
|
||||
continue
|
||||
result = self.wrapped_stream.read(to_read)
|
||||
frames.append(result)
|
||||
remaining -= to_read
|
||||
|
||||
if self.muted:
|
||||
return self.muted_buffer
|
||||
input_latency = self.wrapped_stream.get_input_latency()
|
||||
if input_latency > 0.2:
|
||||
logger.warn("High input latency: %f" % input_latency)
|
||||
audio = b"".join(list(frames))
|
||||
return audio
|
||||
|
||||
def close(self):
|
||||
self.wrapped_stream.close()
|
||||
self.wrapped_stream = None
|
||||
|
||||
def is_stopped(self):
|
||||
return self.wrapped_stream.is_stopped()
|
||||
|
||||
def stop_stream(self):
|
||||
return self.wrapped_stream.stop_stream()
|
||||
|
||||
|
||||
class MutableMicrophone(Microphone):
|
||||
def __init__(self, device_index = None, sample_rate = 16000, chunk_size = 1024):
|
||||
Microphone.__init__(self, device_index=device_index, sample_rate=sample_rate, chunk_size=chunk_size)
|
||||
self.muted = False
|
||||
|
||||
def __enter__(self):
|
||||
assert self.stream is None, "This audio source is already inside a context manager"
|
||||
self.audio = pyaudio.PyAudio()
|
||||
self.stream = MutableStream(self.audio.open(
|
||||
input_device_index = self.device_index, channels = 1,
|
||||
format = self.format, rate = self.SAMPLE_RATE, frames_per_buffer = self.CHUNK,
|
||||
input = True, # stream is an input stream
|
||||
), self.format, self.muted)
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
if not self.stream.is_stopped():
|
||||
self.stream.stop_stream()
|
||||
self.stream.close()
|
||||
self.stream = None
|
||||
self.audio.terminate()
|
||||
|
||||
def mute(self):
|
||||
self.muted = True
|
||||
if self.stream:
|
||||
self.stream.mute()
|
||||
|
||||
def unmute(self):
|
||||
self.muted = False
|
||||
if self.stream:
|
||||
self.stream.unmute()
|
||||
|
||||
|
||||
class Recognizer(speech_recognition.Recognizer):
|
||||
def __init__(self):
|
||||
speech_recognition.Recognizer.__init__(self)
|
||||
self.max_audio_length_sec = 30
|
||||
|
||||
def listen(self, source, timeout = None):
|
||||
"""
|
||||
Records a single phrase from ``source`` (an ``AudioSource`` instance) into an ``AudioData`` instance, which it returns.
|
||||
|
||||
This is done by waiting until the audio has an energy above ``recognizer_instance.energy_threshold`` (the user has started speaking), and then recording until it encounters ``recognizer_instance.pause_threshold`` seconds of non-speaking or there is no more audio input. The ending silence is not included.
|
||||
|
||||
The ``timeout`` parameter is the maximum number of seconds that it will wait for a phrase to start before giving up and throwing an ``speech_recognition.WaitTimeoutError`` exception. If ``timeout`` is ``None``, it will wait indefinitely.
|
||||
"""
|
||||
assert isinstance(source, AudioSource), "Source must be an audio source"
|
||||
assert self.pause_threshold >= self.non_speaking_duration >= 0
|
||||
|
||||
seconds_per_buffer = (source.CHUNK + 0.0) / source.SAMPLE_RATE
|
||||
pause_buffer_count = int(math.ceil(self.pause_threshold / seconds_per_buffer)) # number of buffers of non-speaking audio before the phrase is complete
|
||||
phrase_buffer_count = int(math.ceil(self.phrase_threshold / seconds_per_buffer)) # minimum number of buffers of speaking audio before we consider the speaking audio a phrase
|
||||
non_speaking_buffer_count = int(math.ceil(self.non_speaking_duration / seconds_per_buffer)) # maximum number of buffers of non-speaking audio to retain before and after
|
||||
|
||||
# read audio input for phrases until there is a phrase that is long enough
|
||||
elapsed_time = 0 # number of seconds of audio read
|
||||
while True:
|
||||
frames = collections.deque()
|
||||
|
||||
# store audio input until the phrase starts
|
||||
while True:
|
||||
elapsed_time += seconds_per_buffer
|
||||
if timeout and elapsed_time > timeout: # handle timeout if specified
|
||||
raise WaitTimeoutError("listening timed out")
|
||||
|
||||
buffer = source.stream.read(source.CHUNK)
|
||||
if len(buffer) == 0: break # reached end of the stream
|
||||
frames.append(buffer)
|
||||
if len(frames) > non_speaking_buffer_count: # ensure we only keep the needed amount of non-speaking buffers
|
||||
frames.popleft()
|
||||
|
||||
# detect whether speaking has started on audio input
|
||||
energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # energy of the audio signal
|
||||
if energy > self.energy_threshold: break
|
||||
|
||||
# dynamically adjust the energy threshold using assymmetric weighted average
|
||||
# do not adjust dynamic energy level for this sample if it is muted audio (energy == 0)
|
||||
self.adjust_energy_threshold(energy, seconds_per_buffer)
|
||||
# read audio input until the phrase ends
|
||||
pause_count, phrase_count = 0, 0
|
||||
while True:
|
||||
elapsed_time += seconds_per_buffer
|
||||
|
||||
buffer = source.stream.read(source.CHUNK)
|
||||
if len(buffer) == 0: break # reached end of the stream
|
||||
frames.append(buffer)
|
||||
phrase_count += 1
|
||||
|
||||
# check if speaking has stopped for longer than the pause threshold on the audio input
|
||||
energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # energy of the audio signal
|
||||
if energy > self.energy_threshold:
|
||||
pause_count = 0
|
||||
else:
|
||||
pause_count += 1
|
||||
if pause_count > pause_buffer_count: # end of the phrase
|
||||
break
|
||||
|
||||
if len(frames) * seconds_per_buffer >= self.max_audio_length_sec:
|
||||
# if we hit the end of the audio length, readjust energy_threshold
|
||||
for frame in frames:
|
||||
energy = audioop.rms(frame, source.SAMPLE_WIDTH)
|
||||
self.adjust_energy_threshold(energy, seconds_per_buffer)
|
||||
break
|
||||
|
||||
# check how long the detected phrase is, and retry listening if the phrase is too short
|
||||
phrase_count -= pause_count
|
||||
if phrase_count >= phrase_buffer_count: break # phrase is long enough, stop listening
|
||||
|
||||
# obtain frame data
|
||||
for i in range(pause_count - non_speaking_buffer_count): frames.pop() # remove extra non-speaking frames at the end
|
||||
frame_data = b"".join(list(frames))
|
||||
|
||||
return AudioData(frame_data, source.SAMPLE_RATE, source.SAMPLE_WIDTH)
|
||||
|
||||
def adjust_energy_threshold(self, energy, seconds_per_buffer):
|
||||
if self.dynamic_energy_threshold and energy > 0:
|
||||
damping = self.dynamic_energy_adjustment_damping ** seconds_per_buffer # account for different chunk sizes and rates
|
||||
target_energy = energy * self.dynamic_energy_ratio
|
||||
self.energy_threshold = self.energy_threshold * damping + target_energy * (1 - damping)
|
|
@ -0,0 +1,4 @@
|
|||
hey
|
||||
hay
|
||||
okay
|
||||
ok
|
|
@ -0,0 +1,7 @@
|
|||
minecraft
|
||||
microsoft
|
||||
mycroft
|
||||
micro
|
||||
my friend
|
||||
my brother
|
||||
mike ross
|
|
@ -0,0 +1,38 @@
|
|||
/* ====================================================================
|
||||
* Copyright (c) 2013 Alpha Cephei Inc. All rights
|
||||
* reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in
|
||||
* the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
*
|
||||
* This work was supported in part by funding from the Defense Advanced
|
||||
* Research Projects Agency and the National Science Foundation of the
|
||||
* United States of America, and the CMU Sphinx Speech Consortium.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY ALPHA CEPHEI INC. ``AS IS'' AND
|
||||
* ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ALPHA CEPHEI INC.
|
||||
* NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* ====================================================================
|
||||
*
|
||||
*/
|
||||
|
||||
This directory contains generic US english acoustic model
|
||||
trained with latest sphinxtrain.
|
|
@ -0,0 +1,11 @@
|
|||
-nfilt 25
|
||||
-lowerf 130
|
||||
-upperf 6800
|
||||
-feat 1s_c_d_dd
|
||||
-svspec 0-12/13-25/26-38
|
||||
-agc none
|
||||
-cmn current
|
||||
-varnorm no
|
||||
-transform dct
|
||||
-lifter 22
|
||||
-cmninit 40
|
Binary file not shown.
After Width: | Height: | Size: 3.4 MiB |
Binary file not shown.
|
@ -0,0 +1,9 @@
|
|||
<s> SIL
|
||||
</s> SIL
|
||||
<sil> SIL
|
||||
[BREATH] +BREATH+
|
||||
[COUGH] +COUGH+
|
||||
[NOISE] +NOISE+
|
||||
[SMACK] +SMACK+
|
||||
[UH] +UH+
|
||||
[UM] +UM+
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,4 @@
|
|||
hey HH EY
|
||||
mycroft M AY K R AO F T
|
||||
up AH P
|
||||
wake W EY K
|
|
@ -0,0 +1,116 @@
|
|||
import json
|
||||
|
||||
import requests
|
||||
from speech_recognition import UnknownValueError
|
||||
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
from mycroft.identity import IdentityManager
|
||||
from mycroft.metrics import Stopwatch
|
||||
from mycroft.util import CerberusAccessDenied
|
||||
from mycroft.util.log import getLogger
|
||||
from mycroft.util.setup_base import get_version
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
log = getLogger("RecognizerWrapper")
|
||||
|
||||
config = ConfigurationManager.get_config().get('speech_client')
|
||||
|
||||
|
||||
class GoogleRecognizerWrapper(object):
|
||||
def __init__(self, recognizer):
|
||||
self.recognizer = recognizer
|
||||
|
||||
def transcribe(self, audio, language="en-US", show_all=False, metrics=None):
|
||||
key = config.get('goog_api_key')
|
||||
return self.recognizer.recognize_google(audio, key=key, language=language, show_all=show_all)
|
||||
|
||||
|
||||
class WitRecognizerWrapper(object):
|
||||
def __init__(self, recognizer):
|
||||
self.recognizer = recognizer
|
||||
|
||||
def transcribe(self, audio, language="en-US", show_all=False, metrics=None):
|
||||
assert language == "en-US", "language must be default, language parameter not supported."
|
||||
key = config.get('wit_api_key')
|
||||
return self.recognizer.recognize_wit(audio, key, show_all=show_all)
|
||||
|
||||
|
||||
class IBMRecognizerWrapper(object):
|
||||
def __init__(self, recognizer):
|
||||
self.recognizer = recognizer
|
||||
|
||||
def transcribe(self, audio, language="en-US", show_all=False, metrics=None):
|
||||
username = config.get('ibm_username')
|
||||
password = config.get('ibm_password')
|
||||
return self.recognizer.recognize_ibm(audio, username, password, language=language, show_all=show_all)
|
||||
|
||||
|
||||
class CerberusGoogleProxy(object):
|
||||
def __init__(self, _):
|
||||
self.version = get_version()
|
||||
|
||||
def transcribe(self, audio, language="en-US", show_all=False, metrics=None):
|
||||
timer = Stopwatch()
|
||||
timer.start()
|
||||
identity = IdentityManager().get()
|
||||
headers = {}
|
||||
if identity.token:
|
||||
headers['Authorization'] = 'Bearer %s:%s' % (identity.device_id, identity.token)
|
||||
|
||||
response = requests.post(config.get("proxy_host") +
|
||||
"/stt/google_v2?language=%s&version=%s"
|
||||
% (language, self.version),
|
||||
audio.get_flac_data(),
|
||||
headers=headers)
|
||||
|
||||
if metrics:
|
||||
t = timer.stop()
|
||||
metrics.timer("mycroft.cerberus.proxy.client.time_s", t)
|
||||
metrics.timer("mycroft.stt.remote.time_s", t)
|
||||
|
||||
if response.status_code == 401:
|
||||
raise CerberusAccessDenied()
|
||||
|
||||
try:
|
||||
actual_result = response.json()
|
||||
except:
|
||||
raise UnknownValueError()
|
||||
|
||||
log.info("STT JSON: " + json.dumps(actual_result))
|
||||
if show_all: return actual_result
|
||||
|
||||
# return the best guess
|
||||
if "alternative" not in actual_result: raise UnknownValueError()
|
||||
alternatives = actual_result["alternative"]
|
||||
if len([alt for alt in alternatives if alt.get('confidence')]) > 0:
|
||||
# if there is at least one element with confidence, force it to the front
|
||||
alternatives.sort(key=lambda e: e.get('confidence', 0.0), reverse=True)
|
||||
|
||||
for entry in alternatives:
|
||||
if "transcript" in entry:
|
||||
return entry["transcript"]
|
||||
|
||||
if len(alternatives) > 0:
|
||||
log.error("Found %d entries, but none with a transcript." % len(alternatives))
|
||||
|
||||
# no transcriptions available
|
||||
raise UnknownValueError()
|
||||
|
||||
|
||||
RECOGNIZER_IMPLS = {
|
||||
'google': GoogleRecognizerWrapper,
|
||||
'google_proxy': CerberusGoogleProxy,
|
||||
'wit': WitRecognizerWrapper,
|
||||
'ibm': IBMRecognizerWrapper
|
||||
}
|
||||
|
||||
|
||||
class RemoteRecognizerWrapperFactory(object):
|
||||
@staticmethod
|
||||
def wrap_recognizer(recognizer, impl=config.get('recognizer_impl')):
|
||||
if impl not in RECOGNIZER_IMPLS.keys():
|
||||
raise NotImplementedError("%s recognizer not implemented." % impl)
|
||||
|
||||
impl_class = RECOGNIZER_IMPLS.get(impl)
|
||||
return impl_class(recognizer)
|
|
@ -0,0 +1,58 @@
|
|||
from mycroft.metrics import Stopwatch
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
import os
|
||||
import sys
|
||||
|
||||
from pocketsphinx import *
|
||||
|
||||
|
||||
BASEDIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
from cmath import exp, pi
|
||||
|
||||
def fft(x):
|
||||
"""
|
||||
fft function to clean data, but most be converted to array of IEEE floats first
|
||||
:param x:
|
||||
:return:
|
||||
"""
|
||||
N = len(x)
|
||||
if N <= 1: return x
|
||||
even = fft(x[0::2])
|
||||
odd = fft(x[1::2])
|
||||
T= [exp(-2j*pi*k/N)*odd[k] for k in xrange(N/2)]
|
||||
return [even[k] + T[k] for k in xrange(N/2)] + \
|
||||
[even[k] - T[k] for k in xrange(N/2)]
|
||||
|
||||
|
||||
class Recognizer(object):
|
||||
def __init__(self, local_recognizer):
|
||||
self.local_recognizer = local_recognizer
|
||||
|
||||
def transcribe(self, wav_data, metrics=None):
|
||||
timer = Stopwatch()
|
||||
timer.start()
|
||||
self.local_recognizer.start_utt()
|
||||
self.local_recognizer.process_raw(wav_data, False, False)
|
||||
self.local_recognizer.end_utt()
|
||||
if metrics:
|
||||
metrics.timer("mycroft.stt.local.time_s", timer.stop())
|
||||
return self.local_recognizer.hyp()
|
||||
|
||||
|
||||
def create_recognizer(samprate=16000, lang="en-us", keyphrase="hey mycroft"):
|
||||
sphinx_config = Decoder.default_config()
|
||||
|
||||
sphinx_config.set_string('-hmm', os.path.join(BASEDIR, 'model', lang, 'hmm'))
|
||||
sphinx_config.set_string('-dict', os.path.join(BASEDIR, 'model', lang, 'mycroft-en-us.dict'))
|
||||
sphinx_config.set_string('-keyphrase', keyphrase)
|
||||
sphinx_config.set_float('-kws_threshold', float('1e-45'))
|
||||
sphinx_config.set_float('-samprate', samprate)
|
||||
sphinx_config.set_int('-nfft', 2048)
|
||||
sphinx_config.set_string('-logfn', '/dev/null')
|
||||
|
||||
decoder = Decoder(sphinx_config)
|
||||
|
||||
return Recognizer(decoder)
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1,50 @@
|
|||
import sys
|
||||
from threading import Thread, Lock
|
||||
|
||||
from mycroft.messagebus.client.ws import WebsocketClient
|
||||
from mycroft.messagebus.message import Message
|
||||
from mycroft.tts import tts_factory
|
||||
from mycroft.util.log import getLogger
|
||||
|
||||
tts = tts_factory.create()
|
||||
client = None
|
||||
mutex = Lock()
|
||||
logger = getLogger("CLIClient")
|
||||
|
||||
|
||||
def handle_speak(event):
|
||||
mutex.acquire()
|
||||
client.emit(Message("recognizer_loop:audio_output_start"))
|
||||
try:
|
||||
utterance = event.metadata.get('utterance')
|
||||
logger.info("Speak: " + utterance)
|
||||
tts.execute(utterance)
|
||||
finally:
|
||||
mutex.release()
|
||||
client.emit(Message("recognizer_loop:audio_output_end"))
|
||||
|
||||
|
||||
def connect():
|
||||
client.run_forever()
|
||||
|
||||
|
||||
def main():
|
||||
global client
|
||||
client = WebsocketClient()
|
||||
if not '--quiet' in sys.argv:
|
||||
client.on('speak', handle_speak)
|
||||
event_thread = Thread(target=connect)
|
||||
event_thread.setDaemon(True)
|
||||
event_thread.start()
|
||||
try:
|
||||
while True:
|
||||
print("Input:")
|
||||
line = sys.stdin.readline()
|
||||
client.emit(Message("recognizer_loop:utterance", metadata={'utterances': [line.strip()]}))
|
||||
except KeyboardInterrupt, e:
|
||||
event_thread.exit()
|
||||
sys.exit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1,121 @@
|
|||
import os
|
||||
import requests
|
||||
from configobj import ConfigObj
|
||||
import collections
|
||||
|
||||
from mycroft.identity import IdentityManager
|
||||
from mycroft.util import str2bool
|
||||
from mycroft.util.log import getLogger
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
logger = getLogger(__name__)
|
||||
DEFAULTS_FILE = os.path.join(os.path.dirname(__file__), 'defaults', 'defaults.ini')
|
||||
ETC_CONFIG_FILE = '/etc/mycroft/mycroft.ini'
|
||||
USER_CONFIG_FILE = os.path.join(os.path.expanduser('~'), '.mycroft/mycroft.ini')
|
||||
DEFAULT_LOCATIONS = [DEFAULTS_FILE, ETC_CONFIG_FILE, USER_CONFIG_FILE]
|
||||
|
||||
|
||||
class ConfigurationLoader(object):
|
||||
"""
|
||||
A utility for loading mycroft configuration files.
|
||||
"""
|
||||
def __init__(self, config_locations):
|
||||
self.config_locations = config_locations
|
||||
|
||||
@staticmethod
|
||||
def _overwrite_merge(d, u):
|
||||
for k, v in u.iteritems():
|
||||
if isinstance(v, collections.Mapping):
|
||||
r = ConfigurationLoader._overwrite_merge(d.get(k, {}), v)
|
||||
d[k] = r
|
||||
else:
|
||||
d[k] = u[k]
|
||||
return d
|
||||
|
||||
def load(self):
|
||||
"""
|
||||
Loads configuration files from disk, in the locations defined by DEFAULT_LOCATIONS
|
||||
"""
|
||||
config = {}
|
||||
for config_file in self.config_locations:
|
||||
if os.path.exists(config_file) and os.path.isfile(config_file):
|
||||
logger.debug("Loading config file [%s]" % config_file)
|
||||
try:
|
||||
cobj = ConfigObj(config_file)
|
||||
config = ConfigurationLoader._overwrite_merge(config, cobj)
|
||||
except Exception, e:
|
||||
logger.error("Error loading config file [%s]" % config_file)
|
||||
logger.error(repr(e))
|
||||
else:
|
||||
logger.debug("Could not find config file at [%s]" % config_file)
|
||||
return config
|
||||
|
||||
|
||||
class RemoteConfiguration(object):
|
||||
"""
|
||||
map remote configuration properties to
|
||||
config in the [core] config section
|
||||
"""
|
||||
remote_config_mapping = {
|
||||
"default_location": "location",
|
||||
"default_language": "lang",
|
||||
"timezone": "timezone"
|
||||
}
|
||||
|
||||
def __init__(self, identity=None):
|
||||
self.identity = identity or IdentityManager().get()
|
||||
self.config_manager = ConfigurationManager()
|
||||
|
||||
def update(self):
|
||||
config = self.config_manager.get_config()
|
||||
remote_config_url = config.get("remote_configuration").get("url")
|
||||
enabled = str2bool(config.get("remote_configuration").get("enabled", "False"))
|
||||
if enabled and self.identity.token:
|
||||
auth_header = "Bearer %s:%s" % (self.identity.device_id, self.identity.token)
|
||||
try:
|
||||
response = requests.get(remote_config_url, headers={"Authorization": auth_header})
|
||||
user = response.json()
|
||||
for attribute in user["attributes"]:
|
||||
attribute_name = attribute.get("attribute_name")
|
||||
core_config_name = self.remote_config_mapping.get(attribute_name)
|
||||
if core_config_name:
|
||||
config["core"][core_config_name] = str(attribute.get("attribute_value"))
|
||||
logger.info("Accepting remote configuration: core[%s] == %s" % (core_config_name, attribute["attribute_value"]))
|
||||
except Exception as e:
|
||||
logger.error("Failed to fetch remote configuration: %s" % repr(e))
|
||||
|
||||
else:
|
||||
logger.debug("Device not paired, cannot retrieve remote configuration.")
|
||||
|
||||
|
||||
class ConfigurationManager(object):
|
||||
"""
|
||||
Static management utility for calling up cached configuration.
|
||||
"""
|
||||
_config = None
|
||||
|
||||
@staticmethod
|
||||
def load(*config_files):
|
||||
"""
|
||||
Load default config files as well as any additionally specified files.
|
||||
Now also loads configuration from Cerberus (if device is paired)
|
||||
|
||||
:param config_files: An array of config file paths in addition to DEFAULT_LOCATIONS
|
||||
|
||||
:return: None
|
||||
"""
|
||||
loader = ConfigurationLoader(DEFAULT_LOCATIONS + list(config_files))
|
||||
ConfigurationManager._config = loader.load()
|
||||
RemoteConfiguration().update()
|
||||
|
||||
@staticmethod
|
||||
def get_config():
|
||||
"""
|
||||
Get or create and get statically cached configuration.
|
||||
|
||||
:return: A dictionary representing config files.
|
||||
"""
|
||||
if not ConfigurationManager._config:
|
||||
ConfigurationManager.load()
|
||||
return ConfigurationManager._config
|
|
@ -0,0 +1,94 @@
|
|||
# TODO - User Configuration
|
||||
[core]
|
||||
lang = "en-us"
|
||||
location = "Lawrence, Kansas"
|
||||
time.format = "%A, %B %d, %Y at %H:%M"
|
||||
stop_threshold = 2 # in seconds
|
||||
|
||||
[messagebus_service]
|
||||
host = ""
|
||||
port = 8000
|
||||
route = "/events/ws"
|
||||
|
||||
[messagebus_client]
|
||||
host = "localhost"
|
||||
port = 8000
|
||||
route = "/events/ws"
|
||||
ssl = False
|
||||
|
||||
[metrics_client]
|
||||
url = "https://cerberus.mycroft.ai/metrics"
|
||||
enabled = False
|
||||
|
||||
[pairing_client]
|
||||
host = "cerberus.mycroft.ai"
|
||||
port = 443
|
||||
route = "/pairing"
|
||||
ssl = True
|
||||
|
||||
[remote_configuration]
|
||||
url = "https://cerberus.mycroft.ai/user"
|
||||
enabled = True
|
||||
|
||||
[speech_client]
|
||||
sample_rate = 16000
|
||||
channels = 1
|
||||
proxy_host = "https://cerberus.mycroft.ai"
|
||||
recognizer_impl = 'google_proxy'
|
||||
goog_api_key = ""
|
||||
wit_api_key = ""
|
||||
ibm_username = ""
|
||||
ibm_password = ""
|
||||
|
||||
[enclosure]
|
||||
port = "/dev/ttyAMA0"
|
||||
rate = 9600
|
||||
timeout = 5 # in seconds
|
||||
|
||||
[session_management]
|
||||
session_ttl_seconds = 180
|
||||
|
||||
[tts]
|
||||
module = "espeak"
|
||||
mimic.voice = "rms"
|
||||
espeak.lang = "english-us"
|
||||
espeak.voice = "m1"
|
||||
|
||||
[WikipediaSkill]
|
||||
max_results = 5
|
||||
max_phrases = 2
|
||||
|
||||
[WolframAlphaSkill]
|
||||
api_key = ""
|
||||
|
||||
[WeatherSkill]
|
||||
api_key = ""
|
||||
temperature = fahrenheit # Options are celsius and fahrenheit
|
||||
|
||||
[NPRNewsSkill]
|
||||
url_rss = "http://www.npr.org/rss/podcast.php?id=500005"
|
||||
|
||||
[TimeSkill]
|
||||
time_format = 12h # Options are 12h and 24h
|
||||
|
||||
[AlarmSkill]
|
||||
filename = alarm.wav
|
||||
max_delay = 600 # in seconds
|
||||
repeat_time = 20 # in seconds
|
||||
extended_delay = 60 # in seconds
|
||||
|
||||
[ReminderSkill]
|
||||
max_delay = 600 # in seconds
|
||||
repeat_time = 60 # in seconds
|
||||
extended_delay = 60 # in seconds
|
||||
|
||||
[VolumeSkill]
|
||||
default_volume = 70 # 0-100
|
||||
|
||||
[AudioRecordSkill]
|
||||
filename = /tmp/mycroft-recording.wav
|
||||
free_disk = 100 # in Mb
|
||||
max_time = 600 # in seconds
|
||||
notify_delay = 5 # in seconds
|
||||
rate = 16000
|
||||
channels = 1
|
|
@ -0,0 +1,88 @@
|
|||
import mustache
|
||||
import os
|
||||
import random
|
||||
from mycroft.util import log
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
logger = log.getLogger(__name__)
|
||||
|
||||
__doc__ = """
|
||||
|
||||
"""
|
||||
|
||||
|
||||
class MustacheDialogRenderer(object):
|
||||
"""
|
||||
A dialog template renderer based on the mustache templating language.
|
||||
"""
|
||||
def __init__(self):
|
||||
self.templates = {}
|
||||
|
||||
def load_template_file(self, template_name, filename):
|
||||
"""
|
||||
Load a template by file name into the templates cache.
|
||||
|
||||
:param template_name: a unique identifier for a group of templates.
|
||||
|
||||
:param filename: a fully qualified filename of a mustache template.
|
||||
|
||||
:return:
|
||||
"""
|
||||
with open(filename, 'r') as f:
|
||||
for line in f:
|
||||
template_text = line.strip()
|
||||
if template_name not in self.templates:
|
||||
self.templates[template_name] = []
|
||||
|
||||
self.templates[template_name].append(template_text)
|
||||
|
||||
def render(self, template_name, context={}, index=None):
|
||||
"""
|
||||
Given a template name, pick a template and render it with the provided context.
|
||||
|
||||
:param template_name: the name of a template group.
|
||||
|
||||
:param context: dictionary representing values to be rendered
|
||||
|
||||
:param index: optional, the specific index in the collection of templates
|
||||
|
||||
:raises NotImplementedError: if no template can be found identified by template_name
|
||||
|
||||
:return:
|
||||
"""
|
||||
if template_name not in self.templates:
|
||||
raise NotImplementedError("Template not found: %s" % template_name)
|
||||
template_functions = self.templates.get(template_name)
|
||||
if index == None:
|
||||
index = random.randrange(len(template_functions))
|
||||
else:
|
||||
index %= len(template_functions)
|
||||
return mustache.render(template_functions[index], context)
|
||||
|
||||
|
||||
class DialogLoader(object):
|
||||
"""
|
||||
Loads a collection of dialog files into a renderer implementation.
|
||||
"""
|
||||
def __init__(self, renderer_factory=MustacheDialogRenderer):
|
||||
self.__renderer = renderer_factory()
|
||||
|
||||
def load(self, dialog_dir):
|
||||
"""
|
||||
Load all dialog files within the specified directory.
|
||||
|
||||
:param dialog_dir: directory that contains dialog files
|
||||
|
||||
:return: a loaded instance of a dialog renderer
|
||||
"""
|
||||
if not os.path.exists(dialog_dir) or not os.path.isdir(dialog_dir):
|
||||
logger.warn("No dialog found: " + dialog_dir)
|
||||
return self.__renderer
|
||||
|
||||
for f in sorted(filter(lambda x: os.path.isfile(os.path.join(dialog_dir, x)), os.listdir(dialog_dir))):
|
||||
dialog_entry_name = os.path.splitext(f)[0]
|
||||
self.__renderer.load_template_file(dialog_entry_name, os.path.join(dialog_dir, f))
|
||||
|
||||
return self.__renderer
|
||||
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import os
|
||||
from os.path import join, expanduser, isdir
|
||||
|
||||
__author__ = 'jdorleans'
|
||||
|
||||
|
||||
class FileSystemAccess(object):
|
||||
"""
|
||||
A class for providing access to the mycroft FS sandbox. Intended to be attached to skills
|
||||
at initialization time to provide a skill-specific namespace.
|
||||
"""
|
||||
def __init__(self, path):
|
||||
self.path = self.__init_path(path)
|
||||
|
||||
@staticmethod
|
||||
def __init_path(path):
|
||||
if not isinstance(path, str) or len(path) == 0:
|
||||
raise ValueError("path must be initialized as a non empty string")
|
||||
path = join(expanduser('~'), '.mycroft', path)
|
||||
|
||||
if not isdir(path):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
def open(self, filename, mode):
|
||||
"""
|
||||
Get a handle to a file (with the provided mode) within the skill-specific namespace.
|
||||
|
||||
:param filename: a str representing a path relative to the namespace. subdirs not currently supported.
|
||||
|
||||
:param mode: a file handle mode
|
||||
|
||||
:return: an open file handle.
|
||||
"""
|
||||
file_path = join(self.path, filename)
|
||||
return open(file_path, mode)
|
||||
|
||||
def exists(self, filename):
|
||||
return os.path.exists(join(self.path, filename))
|
|
@ -0,0 +1,43 @@
|
|||
from uuid import uuid4
|
||||
import json
|
||||
from mycroft.filesystem import FileSystemAccess
|
||||
|
||||
|
||||
class DeviceIdentity(object):
|
||||
def __init__(self, **kwargs):
|
||||
self.device_id = kwargs.get('device_id')
|
||||
self.owner = kwargs.get('owner')
|
||||
self.token = kwargs.get('token')
|
||||
|
||||
@staticmethod
|
||||
def load(identity_file_handle):
|
||||
json_blob = json.load(identity_file_handle)
|
||||
return DeviceIdentity(**json_blob)
|
||||
|
||||
def save(self, identity_file_handle):
|
||||
json.dump(self.__dict__, identity_file_handle)
|
||||
|
||||
|
||||
class IdentityManager(object):
|
||||
def __init__(self):
|
||||
self.filesystem = FileSystemAccess('identity')
|
||||
self.identity = None
|
||||
self.initialize()
|
||||
|
||||
def initialize(self):
|
||||
if self.filesystem.exists('identity.json'):
|
||||
self.identity = DeviceIdentity.load(self.filesystem.open('identity.json', 'r'))
|
||||
else:
|
||||
identity = DeviceIdentity(device_id=str(uuid4()))
|
||||
self.update(identity)
|
||||
|
||||
def update(self, identity):
|
||||
self.identity = identity
|
||||
with self.filesystem.open('identity.json', 'w') as f:
|
||||
self.identity.save(f)
|
||||
|
||||
def is_paired(self):
|
||||
return self.identity is not None and self.identity.owner is not None
|
||||
|
||||
def get(self):
|
||||
return self.identity
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1,100 @@
|
|||
import json
|
||||
from multiprocessing.pool import ThreadPool
|
||||
import time
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
from mycroft.messagebus.message import Message
|
||||
import mycroft.util.log
|
||||
from pyee import EventEmitter
|
||||
from websocket import WebSocketApp
|
||||
|
||||
from mycroft.util import str2bool
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
logger = mycroft.util.log.getLogger(__name__)
|
||||
|
||||
config = ConfigurationManager.get_config()
|
||||
client_config = config.get("messagebus_client")
|
||||
|
||||
|
||||
class WebsocketClient(object):
|
||||
def __init__(self, host=client_config.get("host"),
|
||||
port=client_config.get("port"),
|
||||
path=client_config.get("route"),
|
||||
ssl=str2bool(client_config.get("ssl"))):
|
||||
self.emitter = EventEmitter()
|
||||
self.scheme = "wss" if ssl else "ws"
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.path = path
|
||||
self.exp_backoff_counter = 1
|
||||
self.client = self._create_new_connection()
|
||||
self.pool = ThreadPool(10)
|
||||
|
||||
def _create_new_connection(self):
|
||||
return WebSocketApp(self.scheme + "://" + self.host + ":" + str(self.port) + self.path,
|
||||
on_open=self.on_open,
|
||||
on_close=self.on_close,
|
||||
on_error=self.on_error,
|
||||
on_message=self.on_message)
|
||||
|
||||
def on_open(self, ws):
|
||||
logger.info("Connected")
|
||||
self.emitter.emit("open")
|
||||
|
||||
def on_close(self, ws):
|
||||
self.emitter.emit("close")
|
||||
|
||||
def on_error(self, ws, error):
|
||||
try:
|
||||
self.emitter.emit('error', error)
|
||||
self.client.close()
|
||||
except Exception, e:
|
||||
logger.error(repr(e))
|
||||
sleep_time = self.exp_backoff_counter
|
||||
logger.warn("Disconnecting on error, reconnecting in %d seconds." % sleep_time)
|
||||
self.exp_backoff_counter = min(self.exp_backoff_counter * 2, 60)
|
||||
time.sleep(sleep_time)
|
||||
self.client = self._create_new_connection()
|
||||
self.run_forever()
|
||||
|
||||
def on_message(self, ws, message):
|
||||
self.emitter.emit('message', message)
|
||||
parsed_message = Message.deserialize(message)
|
||||
self.pool.apply_async(self.emitter.emit, (parsed_message.message_type, parsed_message))
|
||||
|
||||
def emit(self, message):
|
||||
if not self.client or not self.client.sock or not self.client.sock.connected:
|
||||
return
|
||||
if hasattr(message, 'serialize'):
|
||||
self.client.send(message.serialize())
|
||||
else:
|
||||
self.client.send(json.dumps(message.__dict__))
|
||||
|
||||
def on(self, event_name, func):
|
||||
self.emitter.on(event_name, func)
|
||||
|
||||
def once(self, event_name, func):
|
||||
self.emitter.once(event_name, func)
|
||||
|
||||
def run_forever(self):
|
||||
self.client.run_forever()
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
|
||||
|
||||
def echo():
|
||||
client = WebsocketClient()
|
||||
def echo(message):
|
||||
logger.info(message)
|
||||
|
||||
def repeat_utterance(message):
|
||||
message.message_type = 'speak'
|
||||
client.emit(message)
|
||||
client.on('message', echo)
|
||||
client.on('recognizer_loop:utterance', repeat_utterance)
|
||||
client.run_forever()
|
||||
|
||||
if __name__ == "__main__":
|
||||
echo()
|
|
@ -0,0 +1,47 @@
|
|||
__author__ = 'seanfitz'
|
||||
import json
|
||||
|
||||
|
||||
class Message(object):
|
||||
def __init__(self, message_type, metadata={}, context=None):
|
||||
self.message_type = message_type
|
||||
self.metadata = metadata
|
||||
self.context = context
|
||||
|
||||
def serialize(self):
|
||||
return json.dumps({
|
||||
'message_type': self.message_type,
|
||||
'metadata': self.metadata,
|
||||
'context': self.context
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
def deserialize(json_str):
|
||||
json_message = json.loads(json_str)
|
||||
return Message(json_message.get('message_type'),
|
||||
metadata=json_message.get('metadata'),
|
||||
context=json_message.get('context'))
|
||||
|
||||
def reply(self, message_type, metadata, context={}):
|
||||
if not context:
|
||||
context = {}
|
||||
new_context = self.context if self.context else {}
|
||||
for key in context:
|
||||
new_context[key] = context[key]
|
||||
if 'target' in metadata:
|
||||
new_context['target'] = metadata['target']
|
||||
elif 'client_name' in context:
|
||||
context['target'] = context['client_name']
|
||||
return Message(message_type, metadata, context=new_context)
|
||||
|
||||
def publish(self, message_type, metadata, context={}):
|
||||
if not context:
|
||||
context = {}
|
||||
new_context = self.context.copy() if self.context else {}
|
||||
for key in context:
|
||||
new_context[key] = context[key]
|
||||
|
||||
if 'target' in new_context:
|
||||
del new_context['target']
|
||||
|
||||
return Message(message_type, metadata, context=new_context)
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1,35 @@
|
|||
import tornado.ioloop
|
||||
import tornado.web
|
||||
|
||||
from mycroft.messagebus.service.ws import WebsocketEventHandler
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
settings = {
|
||||
'debug': True
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
import tornado.options
|
||||
tornado.options.parse_command_line()
|
||||
ConfigurationManager.load()
|
||||
config = ConfigurationManager.get_config()
|
||||
service_config = config.get("messagebus_service")
|
||||
|
||||
routes = [
|
||||
(service_config.get('route'), WebsocketEventHandler)
|
||||
]
|
||||
|
||||
application = tornado.web.Application(routes, **settings)
|
||||
|
||||
application.listen(service_config.get("port"), service_config.get("host"))
|
||||
ioloop = tornado.ioloop.IOLoop.instance()
|
||||
ioloop.start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
|
@ -0,0 +1,54 @@
|
|||
import traceback
|
||||
import sys
|
||||
import json
|
||||
|
||||
from pyee import EventEmitter
|
||||
import tornado.websocket
|
||||
|
||||
from mycroft.messagebus.message import Message
|
||||
import mycroft.util.log
|
||||
|
||||
logger = mycroft.util.log.getLogger(__name__)
|
||||
__author__ = 'seanfitz'
|
||||
|
||||
EventBusEmitter = EventEmitter()
|
||||
|
||||
client_connections = []
|
||||
|
||||
|
||||
class WebsocketEventHandler(tornado.websocket.WebSocketHandler):
|
||||
def __init__(self, application, request, **kwargs):
|
||||
tornado.websocket.WebSocketHandler.__init__(self, application, request, **kwargs)
|
||||
self.emitter = EventBusEmitter
|
||||
|
||||
def on(self, event_name, handler):
|
||||
self.emitter.on(event_name, handler)
|
||||
|
||||
def on_message(self, message):
|
||||
logger.debug(message)
|
||||
try:
|
||||
deserialized_message = Message.deserialize(message)
|
||||
except:
|
||||
return
|
||||
|
||||
try:
|
||||
self.emitter.emit(deserialized_message.message_type, deserialized_message)
|
||||
except Exception, e:
|
||||
traceback.print_exc(file=sys.stdout)
|
||||
pass
|
||||
|
||||
for client in client_connections:
|
||||
client.write_message(message)
|
||||
|
||||
def open(self):
|
||||
self.write_message(Message("connected").serialize())
|
||||
client_connections.append(self)
|
||||
|
||||
def on_close(self):
|
||||
client_connections.remove(self)
|
||||
|
||||
def emit(self, channel_message):
|
||||
if hasattr(channel_message, 'serialize') and callable(getattr(channel_message, 'serialize')):
|
||||
self.write_message(channel_message.serialize())
|
||||
else:
|
||||
self.write_message(json.dumps(channel_message))
|
|
@ -0,0 +1,100 @@
|
|||
import json
|
||||
import threading
|
||||
import time
|
||||
import requests
|
||||
|
||||
from mycroft.util import str2bool
|
||||
from mycroft.util.log import getLogger
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
from mycroft.session import SessionManager
|
||||
from mycroft.util.setup_base import get_version
|
||||
|
||||
config = ConfigurationManager.get_config().get('metrics_client')
|
||||
metrics_log = getLogger("METRICS")
|
||||
|
||||
class Stopwatch(object):
|
||||
def __init__(self):
|
||||
self.timestamp = None
|
||||
|
||||
def start(self):
|
||||
self.timestamp = time.time()
|
||||
|
||||
def lap(self):
|
||||
cur_time = time.time()
|
||||
start_time = self.timestamp
|
||||
self.timestamp = cur_time
|
||||
return cur_time - start_time
|
||||
|
||||
def stop(self):
|
||||
cur_time = time.time()
|
||||
start_time = self.timestamp
|
||||
self.timestamp = None
|
||||
return cur_time - start_time
|
||||
|
||||
|
||||
class MetricsAggregator(object):
|
||||
"""
|
||||
MetricsAggregator is not threadsafe, and multiple clients writing the
|
||||
same metric "concurrently" may result in data loss.
|
||||
"""
|
||||
def __init__(self):
|
||||
self._counters = {}
|
||||
self._timers = {}
|
||||
self._levels = {}
|
||||
self._attributes = {}
|
||||
self.attr("version", get_version())
|
||||
|
||||
def increment(self, name, value=1):
|
||||
cur = self._counters.get(name, 0)
|
||||
self._counters[name] = cur + value
|
||||
|
||||
def timer(self, name, value):
|
||||
cur = self._timers.get(name)
|
||||
if not cur:
|
||||
self._timers[name] = []
|
||||
cur = self._timers[name] = []
|
||||
cur.append(value)
|
||||
|
||||
def level(self, name, value):
|
||||
self._levels[name] = value
|
||||
|
||||
def clear(self):
|
||||
self._counters = {}
|
||||
self._timers = {}
|
||||
self._levels = {}
|
||||
self._attributes = {}
|
||||
self.attr("version", get_version())
|
||||
|
||||
def attr(self, name, value):
|
||||
self._attributes[name] = value
|
||||
|
||||
def flush(self):
|
||||
publisher = MetricsPublisher()
|
||||
payload = {
|
||||
'counters': self._counters,
|
||||
'timers': self._timers,
|
||||
'levels': self._levels,
|
||||
'attributes': self._attributes
|
||||
}
|
||||
self.clear()
|
||||
count = len(payload['counters']) + len(payload['timers']) + len(payload['levels'])
|
||||
if count > 0:
|
||||
metrics_log.debug(json.dumps(payload))
|
||||
def publish():
|
||||
publisher.publish(payload)
|
||||
threading.Thread(target=publish).start()
|
||||
|
||||
|
||||
class MetricsPublisher(object):
|
||||
def __init__(self,
|
||||
url=config.get("url"),
|
||||
enabled=str2bool(config.get("enabled"))):
|
||||
self.url = url
|
||||
self.enabled = enabled
|
||||
|
||||
def publish(self, events):
|
||||
if 'session_id' not in events:
|
||||
session_id = SessionManager.get().session_id
|
||||
events['session_id'] = session_id
|
||||
if self.enabled:
|
||||
requests.post(self.url, headers={'Content-Type': 'application/json'}, data=json.dumps(events), verify=False)
|
|
@ -0,0 +1,65 @@
|
|||
import json
|
||||
|
||||
import shortuuid
|
||||
import sys
|
||||
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
from mycroft.identity import IdentityManager
|
||||
from mycroft.messagebus.client.ws import WebsocketClient
|
||||
from mycroft.messagebus.message import Message
|
||||
from mycroft.util import str2bool
|
||||
|
||||
_config = ConfigurationManager().get_config().get("pairing_client")
|
||||
|
||||
|
||||
def generate_pairing_code():
|
||||
shortuuid.set_alphabet("0123456789ABCDEF")
|
||||
return shortuuid.random(length=6)
|
||||
|
||||
|
||||
class DevicePairingClient(object):
|
||||
def __init__(self, config=_config, pairing_code=None):
|
||||
self.config = config
|
||||
self.ws_client = WebsocketClient(host=config.get("host"),
|
||||
port=config.get("port"),
|
||||
path=config.get("route"),
|
||||
ssl=str2bool(config.get("ssl")))
|
||||
self.identity_manager = IdentityManager()
|
||||
self.identity = self.identity_manager.identity
|
||||
self.pairing_code = pairing_code if pairing_code else generate_pairing_code()
|
||||
|
||||
def on_registration(self, message):
|
||||
# TODO: actually accept the configuration message and store it in identity
|
||||
identity = self.identity_manager.get()
|
||||
register_payload = message.metadata
|
||||
if register_payload.get("device_id") == identity.device_id:
|
||||
identity.token = register_payload.get('token')
|
||||
identity.owner = register_payload.get('user')
|
||||
self.identity_manager.update(identity)
|
||||
self.ws_client.close()
|
||||
|
||||
def send_device_info(self):
|
||||
msg = Message("device_info",
|
||||
metadata={
|
||||
"pairing_code": self.pairing_code,
|
||||
"device_id": self.identity.device_id
|
||||
})
|
||||
|
||||
self.ws_client.emit(msg)
|
||||
|
||||
def print_error(self, message):
|
||||
print(repr(message))
|
||||
|
||||
def run(self):
|
||||
self.ws_client.on('registration', self.on_registration)
|
||||
self.ws_client.on('open', self.send_device_info)
|
||||
self.ws_client.on('error', self.print_error)
|
||||
self.ws_client.run_forever()
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
DevicePairingClient().run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
|
@ -0,0 +1,71 @@
|
|||
import time
|
||||
from uuid import uuid4
|
||||
from threading import Lock
|
||||
from mycroft.util import log
|
||||
from mycroft.configuration.config import ConfigurationManager
|
||||
|
||||
__author__ = 'seanfitz'
|
||||
logger = log.getLogger(__name__)
|
||||
config = ConfigurationManager.get_config().get('session_management', {})
|
||||
|
||||
|
||||
class Session(object):
|
||||
"""
|
||||
An object representing a Mycroft Session Identifier
|
||||
"""
|
||||
def __init__(self, session_id, expiration_seconds=180):
|
||||
self.session_id = session_id
|
||||
self.touch_time = int(time.time())
|
||||
self.expiration_seconds = expiration_seconds
|
||||
|
||||
def touch(self):
|
||||
"""
|
||||
update the touch_time on the session
|
||||
|
||||
:return:
|
||||
"""
|
||||
self.touch_time = int(time.time())
|
||||
|
||||
def expired(self):
|
||||
"""
|
||||
determine if the session has expired
|
||||
|
||||
:return:
|
||||
"""
|
||||
return int(time.time()) - self.touch_time > self.expiration_seconds
|
||||
|
||||
def __str__(self):
|
||||
return "{%s,%d}" % (str(self.session_id), self.touch_time)
|
||||
|
||||
|
||||
class SessionManager(object):
|
||||
"""
|
||||
Keeps track of the current active session
|
||||
"""
|
||||
__current_session = None
|
||||
__lock = Lock()
|
||||
|
||||
@staticmethod
|
||||
def get():
|
||||
"""
|
||||
get the active session.
|
||||
|
||||
:return: An active session
|
||||
"""
|
||||
with SessionManager.__lock:
|
||||
if not SessionManager.__current_session or SessionManager.__current_session.expired():
|
||||
SessionManager.__current_session = Session(str(uuid4()),
|
||||
expiration_seconds=config.get('session_ttl_seconds', 180))
|
||||
logger.info("New Session Start: " + SessionManager.__current_session.session_id)
|
||||
return SessionManager.__current_session
|
||||
|
||||
@staticmethod
|
||||
def touch():
|
||||
"""
|
||||
Update the last_touch timestamp on the current session
|
||||
|
||||
:return: None
|
||||
"""
|
||||
SessionManager.get().touch()
|
||||
|
||||
|
|
@ -0,0 +1 @@
|
|||
__author__ = 'seanfitz'
|
|
@ -0,0 +1,91 @@
|
|||
import time
|
||||
import yaml
|
||||
from alsaaudio import Mixer
|
||||
from datetime import datetime, timedelta
|
||||
from os.path import dirname, join
|
||||
|
||||
from adapt.intent import IntentBuilder
|
||||
from mycroft.skills.scheduled_skills import ScheduledCRUDSkill
|
||||
from mycroft.util import play_wav
|
||||
|
||||
__author__ = 'jdorleans'
|
||||
|
||||
|
||||
# TODO - Localization
|
||||
class AlarmSkill(ScheduledCRUDSkill):
|
||||
def __init__(self):
|
||||
super(AlarmSkill, self).__init__("AlarmSkill", None, dirname(__file__))
|
||||
self.alarm_on = False
|
||||
self.max_delay = int(self.config.get('max_delay'))
|
||||
self.repeat_time = int(self.config.get('repeat_time'))
|
||||
self.extended_delay = int(self.config.get('extended_delay'))
|
||||
self.file_path = join(self.basedir, self.config.get('filename'))
|
||||
|
||||
def initialize(self):
|
||||
super(AlarmSkill, self).initialize()
|
||||
intent = IntentBuilder('AlarmSkillStopIntent').require('AlarmSkillStopVerb') \
|
||||
.require('AlarmSkillKeyword').build()
|
||||
self.register_intent(intent, self.__handle_stop)
|
||||
|
||||
def load_data(self):
|
||||
try:
|
||||
with self.file_system.open(self.PENDING_TASK, 'r') as f:
|
||||
self.data = yaml.safe_load(f)
|
||||
assert self.data
|
||||
except:
|
||||
self.data = {}
|
||||
|
||||
def load_repeat_data(self):
|
||||
try:
|
||||
with self.file_system.open(self.REPEAT_TASK, 'r') as f:
|
||||
self.repeat_data = yaml.safe_load(f)
|
||||
assert self.repeat_data
|
||||
except:
|
||||
self.repeat_data = {}
|
||||
|
||||
def __handle_stop(self, message):
|
||||
if self.alarm_on:
|
||||
self.speak_dialog('alarm.off')
|
||||
self.alarm_on = False
|
||||
|
||||
def notify(self, timestamp):
|
||||
with self.LOCK:
|
||||
if self.data.__contains__(timestamp):
|
||||
volume = None
|
||||
self.alarm_on = True
|
||||
delay = self.__calculate_delay(self.max_delay)
|
||||
|
||||
while self.alarm_on and datetime.now() < delay:
|
||||
play_wav(self.file_path)
|
||||
time.sleep(1)
|
||||
self.speak_dialog('alarm.stop')
|
||||
time.sleep(self.repeat_time + 2)
|
||||
if not volume and datetime.now() >= delay:
|
||||
mixer = Mixer()
|
||||
volume = mixer.getvolume()[0]
|
||||
mixer.setvolume(100)
|
||||
delay = self.__calculate_delay(self.extended_delay)
|
||||
if volume:
|
||||
Mixer().setvolume(volume)
|
||||
self.remove(timestamp)
|
||||
self.alarm_on = False
|
||||
self.save()
|
||||
|
||||
@staticmethod
|
||||
def __calculate_delay(seconds):
|
||||
return datetime.now() + timedelta(seconds=seconds)
|
||||
|
||||
def save(self):
|
||||
with self.file_system.open(self.PENDING_TASK, 'w') as f:
|
||||
yaml.safe_dump(self.data, f)
|
||||
with self.file_system.open(self.REPEAT_TASK, 'w') as f:
|
||||
yaml.safe_dump(self.repeat_data, f)
|
||||
if not self.alarm_on:
|
||||
self.schedule()
|
||||
|
||||
def stop(self):
|
||||
self.__handle_stop(None)
|
||||
|
||||
|
||||
def create_skill():
|
||||
return AlarmSkill()
|
Binary file not shown.
|
@ -0,0 +1,3 @@
|
|||
the alarm has been turned off
|
||||
the alarm has been shut off
|
||||
the alarm has been stopped
|
|
@ -0,0 +1,3 @@
|
|||
Stop this alarm by saying, stop alarm
|
||||
Say, set alarm off to end this alarm
|
||||
Tell me to end alarm to stop the current alarm
|
|
@ -0,0 +1,3 @@
|
|||
Alarm set for {{datetime}}
|
||||
You have a new alarm on {{datetime}}
|
||||
A new alarm for {{datetime}} was added
|
|
@ -0,0 +1,2 @@
|
|||
Sorry, I didn't find a valid date and time to alarm you.
|
||||
It was not possible to set an alarm for the informed date and time.
|
|
@ -0,0 +1,2 @@
|
|||
There is no alarm to be removed
|
||||
You don't have any alarm to be deleted
|
|
@ -0,0 +1,3 @@
|
|||
{{amount}} alarms removed
|
||||
{{amount}} alarms were cancelled
|
||||
You have deleted {{amount}} alarms
|
|
@ -0,0 +1,3 @@
|
|||
One alarm removed
|
||||
An alarm was cancelled
|
||||
You have deleted one alarm
|
|
@ -0,0 +1,2 @@
|
|||
You have an alarm on {{datetime}}
|
||||
There is an alarm set for {{datetime}}
|
|
@ -0,0 +1,2 @@
|
|||
There is no alarm to be listed
|
||||
You don't have any alarm to be listed
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"utterance": "alarm in 2 months",
|
||||
"intent_type": "AlarmSkillCreateIntent",
|
||||
"intent": {
|
||||
"AlarmSkillCreateVerb": "alarm"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"utterance": "alarm on july 4th 2016 at 3pm",
|
||||
"intent_type": "AlarmSkillCreateIntent",
|
||||
"intent": {
|
||||
"AlarmSkillCreateVerb": "alarm"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"utterance": "set a timer for tomorrow evening",
|
||||
"intent_type": "AlarmSkillCreateIntent",
|
||||
"intent": {
|
||||
"AlarmSkillCreateVerb": "timer"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"utterance": "set an alarm to next saturday",
|
||||
"intent_type": "AlarmSkillCreateIntent",
|
||||
"intent": {
|
||||
"AlarmSkillCreateVerb": "alarm"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"utterance": "list two alarms",
|
||||
"intent_type": "AlarmSkillListIntent",
|
||||
"intent": {
|
||||
"AlarmSkillListVerb": "list",
|
||||
"AlarmSkillAmount": "2",
|
||||
"AlarmSkillKeyword": "alarms"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"utterance": "show all my timers",
|
||||
"intent_type": "AlarmSkillListIntent",
|
||||
"intent": {
|
||||
"AlarmSkillListVerb": "show",
|
||||
"AlarmSkillAmount": "all",
|
||||
"AlarmSkillKeyword": "timers"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"utterance": "cancel one alarm",
|
||||
"intent_type": "AlarmSkillDeleteIntent",
|
||||
"intent": {
|
||||
"AlarmSkillDeleteVerb": "cancel",
|
||||
"AlarmSkillAmount": "1",
|
||||
"AlarmSkillKeyword": "alarm"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"utterance": "erase the next alarm",
|
||||
"intent_type": "AlarmSkillDeleteIntent",
|
||||
"intent": {
|
||||
"AlarmSkillDeleteVerb": "erase",
|
||||
"AlarmSkillAmount": "the next",
|
||||
"AlarmSkillKeyword": "alarm"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
all|all my
|
||||
1|one
|
||||
2|two
|
||||
the next
|
||||
the following
|
|
@ -0,0 +1,4 @@
|
|||
timer
|
||||
timers
|
||||
alarm
|
||||
alarms
|
|
@ -0,0 +1,4 @@
|
|||
erase
|
||||
cancel
|
||||
delete
|
||||
remove
|
|
@ -0,0 +1,4 @@
|
|||
timer
|
||||
timers
|
||||
alarm
|
||||
alarms
|
|
@ -0,0 +1,2 @@
|
|||
show
|
||||
list
|
|
@ -0,0 +1,3 @@
|
|||
off
|
||||
end
|
||||
stop
|
|
@ -0,0 +1,128 @@
|
|||
import math
|
||||
import time
|
||||
from os.path import dirname
|
||||
|
||||
import psutil as psutil
|
||||
|
||||
from adapt.intent import IntentBuilder
|
||||
from mycroft.skills.scheduled_skills import ScheduledSkill
|
||||
from mycroft.util import record, play_wav
|
||||
from mycroft.util.log import getLogger
|
||||
|
||||
__author__ = 'jdorleans'
|
||||
|
||||
LOGGER = getLogger(__name__)
|
||||
|
||||
|
||||
class AudioRecordSkill(ScheduledSkill):
|
||||
def __init__(self):
|
||||
super(AudioRecordSkill, self).__init__("AudioRecordSkill")
|
||||
self.free_disk = int(self.config.get('free_disk'))
|
||||
self.max_time = int(self.config.get('max_time'))
|
||||
self.notify_delay = int(self.config.get('notify_delay'))
|
||||
self.rate = int(self.config.get('rate'))
|
||||
self.channels = int(self.config.get('channels'))
|
||||
self.file_path = self.config.get('filename')
|
||||
self.duration = 0
|
||||
self.notify_time = None
|
||||
self.play_process = None
|
||||
self.record_process = None
|
||||
|
||||
def initialize(self):
|
||||
self.load_data_files(dirname(__file__))
|
||||
|
||||
intent = IntentBuilder("AudioRecordSkillIntent").require("AudioRecordSkillKeyword").build()
|
||||
self.register_intent(intent, self.handle_record)
|
||||
|
||||
intent = IntentBuilder('AudioRecordSkillStopIntent').require('AudioRecordSkillStopVerb') \
|
||||
.require('AudioRecordSkillKeyword').build()
|
||||
self.register_intent(intent, self.handle_stop)
|
||||
|
||||
intent = IntentBuilder('AudioRecordSkillPlayIntent').require('AudioRecordSkillPlayVerb') \
|
||||
.require('AudioRecordSkillKeyword').build()
|
||||
self.register_intent(intent, self.handle_play)
|
||||
|
||||
intent = IntentBuilder('AudioRecordSkillStopPlayIntent').require('AudioRecordSkillStopVerb') \
|
||||
.require('AudioRecordSkillPlayVerb').require('AudioRecordSkillKeyword').build()
|
||||
self.register_intent(intent, self.handle_stop_play)
|
||||
|
||||
def handle_record(self, message):
|
||||
utterance = message.metadata.get('utterance')
|
||||
date = self.get_utc_time(utterance)
|
||||
now = self.get_utc_time()
|
||||
self.duration = self.get_duration(date, now)
|
||||
if self.is_free_disk_space():
|
||||
self.notify_time = now
|
||||
self.feedback_start()
|
||||
time.sleep(3)
|
||||
self.record_process = record(self.file_path, self.duration, self.rate, self.channels)
|
||||
self.schedule()
|
||||
else:
|
||||
self.speak_dialog("audio.record.disk.full")
|
||||
|
||||
def get_duration(self, date, now):
|
||||
duration = math.ceil(date - now)
|
||||
if duration <= 0:
|
||||
duration = self.max_time
|
||||
return int(duration)
|
||||
|
||||
def is_free_disk_space(self):
|
||||
space = self.duration * self.channels * self.rate / 1024 / 1024
|
||||
free_mb = psutil.disk_usage('/')[2] / 1024 / 1024
|
||||
if free_mb - space > self.free_disk:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def feedback_start(self):
|
||||
if self.duration > 0:
|
||||
self.speak_dialog('audio.record.start.duration', {'duration': self.duration})
|
||||
else:
|
||||
self.speak_dialog('audio.record.start')
|
||||
|
||||
def handle_stop(self, message):
|
||||
self.speak_dialog('audio.record.stop')
|
||||
if self.record_process:
|
||||
self.stop_process(self.record_process)
|
||||
self.record_process = None
|
||||
self.cancel()
|
||||
|
||||
@staticmethod
|
||||
def stop_process(process):
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait()
|
||||
|
||||
def get_times(self):
|
||||
return [self.notify_time]
|
||||
|
||||
def notify(self, timestamp):
|
||||
if self.record_process and self.record_process.poll() is None:
|
||||
if self.is_free_disk_space():
|
||||
LOGGER.info("Recording...")
|
||||
self.notify_time = self.get_utc_time() + self.notify_delay
|
||||
self.schedule()
|
||||
else:
|
||||
self.handle_stop(None)
|
||||
self.speak_dialog("audio.record.disk.full")
|
||||
else:
|
||||
self.handle_stop(None)
|
||||
|
||||
def handle_play(self, message):
|
||||
self.play_process = play_wav(self.file_path)
|
||||
|
||||
def handle_stop_play(self, message):
|
||||
self.speak_dialog('audio.record.stop.play')
|
||||
if self.play_process:
|
||||
self.stop(self.play_process)
|
||||
self.play_process = None
|
||||
|
||||
def stop(self):
|
||||
if self.play_process:
|
||||
self.stop_process(self.play_process)
|
||||
if self.record_process:
|
||||
self.stop_process(self.record_process)
|
||||
|
||||
|
||||
def create_skill():
|
||||
return AudioRecordSkill()
|
|
@ -0,0 +1,3 @@
|
|||
There is not enough free disk space to record an audio
|
||||
Audio recording is not possible. You have to free some disk usage
|
||||
You have reached the maximum disk usage. Free some disk space to record an audio
|
|
@ -0,0 +1,3 @@
|
|||
Recording audio
|
||||
Starting audio recording
|
||||
Audio recording initialized
|
|
@ -0,0 +1,3 @@
|
|||
Recording audio for {{duration}} seconds
|
||||
Starting audio recording for {{duration}} seconds
|
||||
Audio recording for {{duration}} seconds initialized
|
|
@ -0,0 +1,3 @@
|
|||
Audio recording ended
|
||||
Stopping audio recording
|
||||
Audio recording was stopped
|
|
@ -0,0 +1,3 @@
|
|||
Audio reproducing ended
|
||||
Stopping audio playing
|
||||
Audio playing was stopped
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"utterance": "record",
|
||||
"intent_type": "AudioRecordSkillIntent",
|
||||
"intent": {
|
||||
"AudioRecordSkillKeyword": "record"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"utterance": "start recording",
|
||||
"intent_type": "AudioRecordSkillIntent",
|
||||
"intent": {
|
||||
"AudioRecordSkillKeyword": "recording"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"utterance": "record audio for 10 minutes",
|
||||
"intent_type": "AudioRecordSkillIntent",
|
||||
"intent": {
|
||||
"AudioRecordSkillKeyword": "record"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"utterance": "stop recording",
|
||||
"intent_type": "AudioRecordSkillStopIntent",
|
||||
"intent": {
|
||||
"AudioRecordSkillStopVerb": "stop",
|
||||
"AudioRecordSkillKeyword": "recording"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"utterance": "end record",
|
||||
"intent_type": "AudioRecordSkillStopIntent",
|
||||
"intent": {
|
||||
"AudioRecordSkillStopVerb": "end",
|
||||
"AudioRecordSkillKeyword": "record"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"utterance": "cancel recording",
|
||||
"intent_type": "AudioRecordSkillStopIntent",
|
||||
"intent": {
|
||||
"AudioRecordSkillStopVerb": "cancel",
|
||||
"AudioRecordSkillKeyword": "recording"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"utterance": "play record",
|
||||
"intent_type": "AudioRecordSkillPlayIntent",
|
||||
"intent": {
|
||||
"AudioRecordSkillPlayVerb": "play",
|
||||
"AudioRecordSkillKeyword": "record"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"utterance": "stop playing record",
|
||||
"intent_type": "AudioRecordSkillStopPlayIntent",
|
||||
"intent": {
|
||||
"AudioRecordSkillStopVerb": "stop",
|
||||
"AudioRecordSkillPlayVerb": "playing",
|
||||
"AudioRecordSkillKeyword": "record"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
record
|
||||
recording
|
|
@ -0,0 +1,9 @@
|
|||
run
|
||||
play
|
||||
replay
|
||||
playback
|
||||
reproduce
|
||||
running
|
||||
playing
|
||||
replaying
|
||||
reproducing
|
|
@ -0,0 +1,3 @@
|
|||
end
|
||||
stop
|
||||
cancel
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue