Repository: wzpan/wukong-robot Branch: master Commit: 3fd73e075bc3 Files: 209 Total size: 2.6 MB Directory structure: gitextract__p4m59za/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── ----.md │ │ └── bug---.md │ ├── stale.yml │ └── workflows/ │ └── dockerimage.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── VERSION ├── docker/ │ ├── Dockerfile │ └── DockerfileArm ├── docs/ │ ├── .buildinfo │ ├── .nojekyll │ ├── AI.html │ ├── ASR.html │ ├── Brain.html │ ├── ConfigMonitor.html │ ├── Conversation.html │ ├── Player.html │ ├── TTS.html │ ├── Updater.html │ ├── _modules/ │ │ ├── index.html │ │ ├── logging.html │ │ ├── plugins/ │ │ │ ├── Camera.html │ │ │ ├── CleanCache.html │ │ │ ├── Echo.html │ │ │ ├── Email.html │ │ │ ├── Geek.html │ │ │ ├── LocalPlayer.html │ │ │ └── Poem.html │ │ ├── robot/ │ │ │ ├── AI.html │ │ │ ├── ASR.html │ │ │ ├── Brain.html │ │ │ ├── ConfigMonitor.html │ │ │ ├── Conversation.html │ │ │ ├── NLU.html │ │ │ ├── Player.html │ │ │ ├── TTS.html │ │ │ ├── Updater.html │ │ │ ├── config.html │ │ │ ├── constants.html │ │ │ ├── drivers/ │ │ │ │ ├── apa102.html │ │ │ │ └── pixels.html │ │ │ ├── logging.html │ │ │ ├── plugin_loader.html │ │ │ ├── sdk/ │ │ │ │ ├── AbstractPlugin.html │ │ │ │ ├── AliSpeech.html │ │ │ │ ├── RASRsdk.html │ │ │ │ ├── TencentSpeech.html │ │ │ │ ├── XunfeiSpeech.html │ │ │ │ └── unit.html │ │ │ ├── statistic.html │ │ │ └── utils.html │ │ ├── snowboy/ │ │ │ ├── snowboydecoder.html │ │ │ └── snowboydetect.html │ │ └── wukong.html │ ├── _sources/ │ │ ├── AI.rst.txt │ │ ├── ASR.rst.txt │ │ ├── Brain.rst.txt │ │ ├── ConfigMonitor.rst.txt │ │ ├── Conversation.rst.txt │ │ ├── Player.rst.txt │ │ ├── TTS.rst.txt │ │ ├── Updater.rst.txt │ │ ├── config.rst.txt │ │ ├── constants.rst.txt │ │ ├── drivers.rst.txt │ │ ├── index.rst.txt │ │ ├── logging.rst.txt │ │ ├── modules.rst.txt │ │ ├── plugin_loader.rst.txt │ │ ├── plugins.rst.txt │ │ ├── robot.drivers.rst.txt │ │ ├── robot.rst.txt │ │ ├── robot.sdk.rst.txt │ │ ├── snowboy.rst.txt │ │ ├── statistic.rst.txt │ │ ├── utils.rst.txt │ │ └── wukong.rst.txt │ ├── _static/ │ │ ├── alabaster.css │ │ ├── basic.css │ │ ├── css/ │ │ │ ├── badge_only.css │ │ │ └── theme.css │ │ ├── custom.css │ │ ├── doctools.js │ │ ├── documentation_options.js │ │ ├── jquery-3.2.1.js │ │ ├── jquery.js │ │ ├── js/ │ │ │ └── theme.js │ │ ├── language_data.js │ │ ├── pygments.css │ │ ├── searchtools.js │ │ ├── translations.js │ │ ├── underscore-1.3.1.js │ │ ├── underscore.js │ │ └── websupport.js │ ├── config.html │ ├── constants.html │ ├── drivers.html │ ├── genindex.html │ ├── index.html │ ├── logging.html │ ├── modules.html │ ├── objects.inv │ ├── plugin_loader.html │ ├── plugins.html │ ├── py-modindex.html │ ├── robot.drivers.html │ ├── robot.html │ ├── robot.sdk.html │ ├── search.html │ ├── searchindex.js │ ├── snowboy.html │ ├── statistic.html │ ├── utils.html │ └── wukong.html ├── plugins/ │ ├── Camera.py │ ├── CleanCache.py │ ├── Echo.py │ ├── Email.py │ ├── Geek.py │ ├── Gossip.py │ ├── LocalPlayer.py │ ├── Poem.py │ ├── Reminder.py │ ├── Volume.py │ └── __init__.py ├── requirements.txt ├── robot/ │ ├── AI.py │ ├── ASR.py │ ├── BCI.py │ ├── Brain.py │ ├── ConfigMonitor.py │ ├── Conversation.py │ ├── LifeCycleHandler.py │ ├── NLU.py │ ├── Player.py │ ├── Scheduler.py │ ├── TTS.py │ ├── Updater.py │ ├── __init__.py │ ├── config.py │ ├── constants.py │ ├── detector.py │ ├── drivers/ │ │ ├── AIY.py │ │ ├── __init__.py │ │ ├── apa102.py │ │ └── pixels.py │ ├── logging.py │ ├── plugin_loader.py │ ├── sdk/ │ │ ├── AbstractPlugin.py │ │ ├── AliSpeech.py │ │ ├── BaiduSpeech.py │ │ ├── FunASREngine.py │ │ ├── History.py │ │ ├── LED.py │ │ ├── RASRsdk.py │ │ ├── TencentSpeech.py │ │ ├── Unihiker.py │ │ ├── VITSClient.py │ │ ├── VolcengineSpeech.py │ │ ├── XunfeiSpeech.py │ │ ├── __init__.py │ │ ├── atc.py │ │ └── unit.py │ ├── statistic.py │ └── utils.py ├── server/ │ ├── server.py │ ├── static/ │ │ ├── api.css │ │ ├── bootbox.js │ │ ├── bubble.css │ │ ├── config.js │ │ ├── index.js │ │ ├── jquery.fancybox.css │ │ ├── jquery.fancybox.js │ │ ├── log.js │ │ ├── main.js │ │ ├── modernizr.touch.js │ │ ├── monokai-sublime.css │ │ ├── qa.js │ │ ├── signin.css │ │ ├── spin.css │ │ ├── starter-template.css │ │ └── static.js │ └── templates/ │ ├── api.html │ ├── api.md │ ├── config.html │ ├── donate.html │ ├── index.html │ ├── layout.html │ ├── log.html │ ├── login.html │ └── qa.html ├── snowboy/ │ ├── __init__.py │ ├── resources/ │ │ └── common.res │ ├── snowboydecoder.py │ └── snowboydetect.py ├── static/ │ ├── default.yml │ ├── qa.csv │ ├── snowboy.umdl │ ├── wukong.pmdl │ ├── wukong_pi.pmdl │ └── zhimakaimen.pmdl ├── tools/ │ ├── changelog.sh │ ├── make_json.py │ ├── solr_api.py │ └── solr_tools.py └── wukong.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: #'wzpan' patreon: # Replace with a single Patreon username open_collective: wukong-robot ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: ['https://wukong.hahack.com/#/donate'] ================================================ FILE: .github/ISSUE_TEMPLATE/----.md ================================================ --- name: 使用求助 about: 使用遇到问题,请求帮助 title: '' labels: operation problem assignees: wzpan --- **确认已寻找过答案** 我已确认在 [Github issue](https://github.com/wzpan/wukong-robot/issues) 页、[常见问题](https://github.com/wzpan/wukong-robot/wiki/troubleshooting)页、[文档](http://wukong.hahack.com) 中都查找过,没有找到类似问题和资料。我也没有 google / bing/ 百度 / duckduckgo 到相关解答。 **安装方式** 手动安装/docker安装 **操作系统** (例如 Raspbian Stretch、Ubuntu 16.04) **离线唤醒相关** 如果是离线唤醒相关的问题,是否已确保 `arecord temp.wav`、`aplay temp.wav` (Linux) 或 `rec temp.wav`、`play temp.wav` (Mac)已正常工作?(注意要求不能带任何其他参数)如果不能,请先配置好麦克风和音响再尝试。 —— 我已确保录音、播放都正常工作才尝试 wukong-robot 。 **问题描述** 具体说明下问题 ================================================ FILE: .github/ISSUE_TEMPLATE/bug---.md ================================================ --- name: Bug 反馈 about: 反馈一个bug,帮助改进 wukong-robot title: '' labels: bug assignees: wzpan --- **确认已寻找过答案** 我已确认在 [Github issue](https://github.com/wzpan/wukong-robot/issues) 页、[常见问题](https://github.com/wzpan/wukong-robot/wiki/troubleshooting)页、[文档](http://wukong.hahack.com) 中都查找过,没有找到类似问题和资料。我也没有 google / bing/ 百度 / duckduckgo 到相关解答。 **安装方式** 手动安装/docker安装 **操作系统** (例如 Raspbian Stretch、Ubuntu 16.04) **离线唤醒相关** 如果是离线唤醒相关的问题,是否已确保 `arecord temp.wav`、`aplay temp.wav` (Linux) 或 `rec temp.wav`、`play temp.wav` (Mac)已正常工作?(注意要求不能带任何其他参数)如果不能,请先配置好麦克风和音响再尝试。 —— 我已确保录音、播放都正常工作才尝试 wukong-robot 。 **问题描述** 具体说明下问题 **复现步骤** 具体描述下复现步骤 ================================================ FILE: .github/stale.yml ================================================ # Number of days of inactivity before an issue becomes stale daysUntilStale: 7 # Number of days of inactivity before a stale issue is closed daysUntilClose: 3 # Issues with these labels will never be considered stale exemptLabels: - pinned - security - bug # Label to use when marking an issue as stale staleLabel: wontfix # Comment to post when marking an issue as stale. Set to `false` to disable markComment: > 由于久无进展,这个 issue 已被标为过期。如果还没有后续进展,这个 issue 将被关闭。谢谢你的反馈! # Comment to post when closing a stale issue. Set to `false` to disable closeComment: false ================================================ FILE: .github/workflows/dockerimage.yml ================================================ name: Docker Image CI on: push: branches: - master jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Publish to Docker Hub Registry uses: elgohr/Publish-Docker-Github-Action@master with: name: wzpan/wukong-robot username: ${{ secrets.DOCKER_GITHUB_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} dockerfile: docker/Dockerfile - name: Publish to Github Package Registry uses: elgohr/Publish-Docker-Github-Action@master with: name: docker.pkg.github.com/wzpan/wukong-robot/wukong username: ${{ secrets.DOCKER_GITHUB_USERNAME }} password: ${{ secrets.DOCKER_GITHUB_PASSWORD }} registry: docker.pkg.github.com dockerfile: docker/Dockerfile ================================================ FILE: .gitignore ================================================ # Generic files to ignore *~ *.lock *.DS_Store *.swp *.out # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .cache nosetests.xml coverage.xml # Translations *.mo *.pot # Django stuff/Logfiles *.log # Sphinx documentation docs/_build/ # PyBuilder target/ # Coverage reports for a specific version .coverage # SublimeLinter config file .sublimelinterrc # temp folder temp/* # temp file #*.*# #*# \#*# *~ .#*.* # NetEase music account info userInfo # wget log wget-log* # some thirdparty libs client/mic_array login/wxqr.png .idea/ sftp-config.json __pycache__ ================================================ FILE: .travis.yml ================================================ env: - ARCH=x86 language: python sudo: false python: - "3.5" cache: directories: - "$HOME/.pip-cache/" - "/home/travis/virtualenv/python3.8" install: - "pip3 install pyflakes --cache-dir $HOME/.pip-cache" script: - "pyflakes ." ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2016 - present Weizhou Pan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # wukong-robot

wukong-robot

wukong-robot 是一个简单、灵活、优雅的中文语音对话机器人/智能音箱项目,目的是让中国的 Maker 和 Haker 们也能快速打造个性化的智能音箱。wukong-robot 还可能是第一个开源的脑机唤醒智能音箱。

截至 2023 年 3 月 31 日,wukong-robot 的安装设备数已超过 13,000 台,唤醒次数累积超过了 700,000 次。

wukong-project 捐赠 Python3.7+ docker-pulls browse-code

## Table of Contents * [特性](#特性) * [Demo](#demo) * [环境要求](#环境要求) * [安装](#安装) * [升级](#升级) * [运行](#运行) * [配置](#配置) * [技能插件](#插件) * [API接口](#api-接口) * [捐赠](#捐赠) * [贡献](#贡献) * [引用](#引用) * [联系](#联系) * [感谢](#感谢) * [FAQ](#faq) * [免责声明](#免责声明) ## 特性

wukong-robot

* 模块化。功能插件、语音识别、语音合成、对话机器人都做到了高度模块化,第三方插件单独维护,方便继承和开发自己的插件。 * 中文支持。集成百度、科大讯飞、阿里、腾讯、OpenAI Whisper、Apple、微软Edge、VITS声音克隆TTS 等多家中文语音识别和语音合成技术,且可以继续扩展。 * 对话机器人支持。支持基于 [AnyQ](https://wukong.hahack.com/#/anyq) 的本地对话机器人,并支持接入图灵机器人、ChatGPT 等在线对话机器人。 * 全局监听,离线唤醒。支持 [Porcupine](https://github.com/Picovoice/porcupine) 和 [snowboy](https://github.com/Kitt-AI/snowboy) 两套离线语音指令唤醒引擎,并支持 Muse [脑机唤醒](https://wukong.hahack.com/#/bci) 以及行空板摇一摇唤醒等其他唤醒方式。 * 灵活可配置。支持定制机器人名字,支持选择语音识别和合成的插件。 * 智能家居。支持和 [小爱音箱](https://wukong.hahack.com/#/linkage)、[Siri](https://wukong.hahack.com/#/linkage)、mqtt、[HomeAssistant](https://wukong.hahack.com/#/smarthome) 等智能家居协议联动,支持语音控制智能家电。 * 后台配套支持。提供配套后台,可实现远程操控、修改配置和日志查看等功能。 * 开放API。可利用后端开放的API,实现更丰富的功能。 * 安装简单,支持更多平台。相比 dingdang-robot ,舍弃了 PocketSphinx 的离线唤醒方案,安装变得更加简单,代码量更少,更易于维护并且能在 Mac 以及更多 Linux 系统中运行。 wukong-robot 的功能还在不断更新迭代中,详见 [更新说明](https://github.com/wzpan/wukong-robot/wiki/update-notes) 。 wukong-robot 的工作模式:

wukong-robot 的工作模式

wukong-robot 被唤醒后,用户的语音指令先经过 ASR 引擎进行 ASR 识别成文本,然后对识别到的文本进行 NLU 解析,再将解析结果进行技能匹配,交给适合处理该指令的技能插件去处理。插件处理完成后,得到的结果再交给 TTS 引擎合成成语音,播放给用户。 虽然一次交互可能包含多次网络请求,不过带来的好处是:每一个环节都可以被修改和定制。而且我认为,到了 5G 时代,音箱的响应速度将不再成为体验问题。可定制和个性化才是未来的主流,而届时 wukong-robot 将会是更好的选择! ## Demo

demo

* Demo视频: - [wukong-robot + ChatGPT 实现支持流式对话的智能音箱(一分半钟)](https://www.bilibili.com/video/BV1Bh411g7t2) - [粉丝向定制版,演示对话+音乐+开放API+智能家居(五分钟)](https://www.bilibili.com/video/av50685517/) - [使用脑机唤醒 wukong-robot](https://www.bilibili.com/video/av76739580/) - [Google AIY Voice Kit + wukong-robot](https://www.bilibili.com/video/av81173082/) - [Siri 联动 wukong-robot + ChatGPT](https://www.bilibili.com/video/BV1yY4y1y7oW) - [小爱同学联动 wukong-robot](https://www.bilibili.com/video/BV1eg4y1b75Y) - [教程:基于树莓派&wukong-robot&VITS的AI泠鸢开源智能音箱的初步实现(by @二维环状无限深势阱)](https://www.bilibili.com/video/BV1Sc411K7dv) - [教程:实现一个虚拟管家:贾维斯(by @Echo)](https://zhuanlan.zhihu.com/p/655865035) * 后台管理端 Demo - 体验地址:https://bot.hahack.com (体验用户名:wukong;体验密码:wukong@2019) ## 环境要求 ## ### Python 版本 ### wukong-robot 只支持 Python >= 3.7 且 < 3.10 ,不支持 Python 2.x 。 ### 设备要求 ### wukong-robot 支持运行在以下的设备和系统中: * Intel Chip Mac (不支持 M1 芯片) * 64bit Ubuntu(12.04 and 14.04) * 全系列的树莓派(Raspbian 系统) * Pine 64 with Debian Jessie 8.5(3.10.102) * Intel Edison with Ubilinux (Debian Wheezy 7.8) * 装有 WSL(Windows Subsystem for Linux) 的 Windows ## 安装 ## 见 [wukong-robot 安装教程](https://wukong.hahack.com/#/install) 。 ## 升级 ``` bash python3 wukong.py update ``` 如果提示升级失败,可以尝试在 wukong-robot 的根目录手动执行以下命令,看看问题出在哪。 ``` sh git pull pip3 install -r requirements.txt ``` ## 运行 ## ``` bash python3 wukong.py ``` 建议在 [tmux](http://blog.jobbole.com/87278/) 或 supervisor 中执行。 第一次启动时将提示你是否要到用户目录下创建一个配置文件,输入 `y` 即可。 然后通过唤醒词 “snowboy” 唤醒 wukong-robot 进行交互(该唤醒词可自定义)。 此外,wukong-robot 默认在运行期间还会启动一个后台管理端,提供了远程对话、查看修改配置、查看 log 等能力。 - 默认地址:http://localhost:5001 - 默认账户名:wukong - 默认密码:wukong@2019 建议正式使用时修改用户名和密码,以免泄漏隐私。 ## 配置 ## 参考[配置文件的注释](https://github.com/wzpan/wukong-robot/blob/master/static/default.yml)进行配置即可。注意不建议直接修改 default.yml 里的内容,否则会给后续通过 `git pull` 更新带来麻烦。你应该拷贝一份放到 `$HOME/.wukong/config.yml` 中,或者在运行的时候按照提示让 wukong-robot 为你完成这件事。 > tips:不论使用哪个厂商的API,都建议注册并填上自己注册的应用信息,而不要用默认的配置。这是因为这些API都有使用频率和并发数限制,过多人同时使用会影响服务质量。 ## 技能插件 ## * [官方插件列表](https://wukong.hahack.com/#/official) * [用户贡献插件](https://wukong.hahack.com/#/contrib) ## API 接口 ## wukong-robot 的后台接口是开放 Web API 的,可以使用 Restful 方式调用,见 [后台API](https://wukong.hahack.com/#/api)。 ## 捐赠 您的捐赠将鼓励我继续完善 wukong-robot。 * 对于个人用户,可以使用支付宝或者微信进行捐赠,单笔超过 100 元的捐赠者,您的 ID 将可以出现在 wukong-robot 后台管理端的捐赠页面中。 | 支付宝 | 微信支付 | | ------ | --------- | | | | 如果以上的图裂了,可以下载图片([支付宝](http://hahack.com/images/misc/alipay.png) | [微信](http://hahack.com/images/misc/wechatpay.jpeg))到本地进行扫描。 * 对于企业用户,建议[成为这个项目的 backer](https://opencollective.com/wukong-robot/contribute/tier/8131-sponsor),您将可以把一个带链接的 logo 放在 wukong-robot 后台管理端的首页、捐赠页面以及 Github 项目首页中。

## 贡献 * 喜欢本项目请先打一颗星; * 提 bug 请到 [issue 页面](https://github.com/wzpan/wukong-robot/issues); * 要贡献代码,欢迎 fork 之后再提 pull request; * 插件请提交到 [wukong-contrib](https://github.com/wzpan/wukong-contrib) ; ## 引用 如果使用本项目的代码或插件,请引用本项目。 ``` @misc{wukong-robot, author = {潘伟洲}, title = {wukong-robot,一个简单、灵活、优雅的中文语音对话机器人/智能音箱项目}, year = {2019}, publisher = {GitHub}, journal = {GitHub repository}, howpublished = {\url{https://github.com/wzpan/wukong-robot}}, } ``` ## 联系 * wukong-robot 的主要开发者是 [潘伟洲](http://hahack.com) 。 * QQ 频道(推荐): 使用 QQ 扫码加入: ![](https://wzpan-1253537070.cos.ap-guangzhou.myqcloud.com/misc/wukong-guild-qrcode-256.png) * QQ 群:580447290(人数将满,为控制人数,需付费20元入群。微信或支付宝支付后,申请入群时贴上转账单号即可。**群收入的前一万元已无偿捐赠给[壹基金等公益项目](https://hahack-1253537070.cos.ap-chengdu.myqcloud.com/images/donate.png)**)。 | 支付宝 | 微信支付 | | ------ | --------- | | | | 如果以上的图裂了,可以下载图片([支付宝](http://hahack.com/images/misc/alipay.png) | [微信](http://hahack.com/images/misc/wechatpay.jpeg))到本地进行扫描。 ## 感谢 * 悟空的前身是 [dingdang-robot](https://github.com/dingdang-robot/dingdang-robot) 项目和 [jasper-client](https://github.com/jasperproject/jasper-client) 项目。感谢 [Shubhro Saha](http://www.shubhro.com/), [Charles Marsh](http://www.crmarsh.com/) and [Jan Holthuis](http://homepage.ruhr-uni-bochum.de/Jan.Holthuis/) 在 Jasper 项目上做出的优秀贡献; * 感谢三咲智子提供了备选的后台管理端 Demo 体验地址。 * 感谢 aliciacai 贡献的 wukong-robot 图标。 * 感谢所有为[本项目](https://github.com/wzpan/wukong-robot/graphs/contributors)、 [wukong-contrib](https://github.com/wzpan/wukong-contrib/graphs/contributors) 项目以及[dingdang-robot](https://github.com/dingdang-robot/dingdang-robot/graphs/contributors) 项目做出过贡献的人! ## Star 历史 [![Star History Chart](https://api.star-history.com/svg?repos=wzpan/wukong-robot&type=Date)](https://star-history.com/#wzpan/wukong-robot&Date) ## 免责声明 * wukong-robot 只用作个人学习研究,如因使用 wukong-robot 导致任何损失,本人概不负责。 * 本开源项目与腾讯叮当助手及优必选悟空项目没有任何关系。 ================================================ FILE: VERSION ================================================ 3.5.3 ================================================ FILE: docker/Dockerfile ================================================ # 使用官方 Python 3.8 基础镜像 FROM python:3.8-slim # 设置工作目录 WORKDIR /app # 安装依赖库 RUN apt-get update && apt-get install -y \ git \ portaudio19-dev \ python3-pyaudio \ sox \ pulseaudio \ libsox-fmt-all \ ffmpeg \ wget \ swig \ libpcre3 \ libpcre3-dev \ libatlas-base-dev \ build-essential \ && rm -rf /var/lib/apt/lists/* # 克隆项目仓库 RUN git clone https://github.com/wzpan/wukong-robot.git . # 安装 PyAudio RUN pip install pyaudio # 安装 Python 依赖 RUN pip install --trusted-host pypi.python.org -r requirements.txt # 安装 wukong-contrib RUN mkdir -p $HOME/.wukong \ && cd $HOME/.wukong \ && git clone http://github.com/wzpan/wukong-contrib.git contrib \ && pip install -r contrib/requirements.txt # 下载并编译 snowboy RUN wget https://wzpan-1253537070.cos.ap-guangzhou.myqcloud.com/misc/snowboy.tar.bz2 \ && tar -xvjf snowboy.tar.bz2 \ && cd snowboy/swig/Python3 \ && make \ && cp _snowboydetect.so /app/snowboy/ # 暴露端口 EXPOSE 5001 # 设置 ENTRYPOINT ENTRYPOINT ["python", "wukong.py"] ================================================ FILE: docker/DockerfileArm ================================================ # 使用官方 Python 3.8 基于 ARM 的镜像 FROM arm32v7/python:3.8-slim MAINTAINER wzpan # 设置工作目录 WORKDIR /app # 安装依赖库 RUN apt-get update && apt-get install -y \ git \ portaudio19-dev \ python3-pyaudio \ sox \ pulseaudio \ libsox-fmt-all \ ffmpeg \ wget \ swig \ libpcre3 \ libpcre3-dev \ libatlas-base-dev \ libffi-dev \ build-essential \ && rm -rf /var/lib/apt/lists/* # 克隆项目仓库 RUN git clone https://github.com/wzpan/wukong-robot.git . # 安装 PyAudio RUN pip install pyaudio # 安装 Python 依赖 RUN pip install --trusted-host pypi.python.org -r requirements.txt # 安装 wukong-contrib RUN mkdir -p $HOME/.wukong \ && cd $HOME/.wukong \ && git clone http://github.com/wzpan/wukong-contrib.git contrib \ && pip install -r contrib/requirements.txt # 下载并编译 snowboy RUN wget https://wzpan-1253537070.cos.ap-guangzhou.myqcloud.com/misc/snowboy.tar.bz2 \ && tar -xvjf snowboy.tar.bz2 \ && cd snowboy/swig/Python3 \ && make \ && cp _snowboydetect.so /app/snowboy/ # 暴露端口 EXPOSE 5001 # 设置 ENTRYPOINT ENTRYPOINT ["python", "wukong.py"] ================================================ FILE: docs/.buildinfo ================================================ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. config: bed81550a26bd552fac818a5876d05a1 tags: 645f666f9bcd5a90fca523b33c5a78b7 ================================================ FILE: docs/.nojekyll ================================================ ================================================ FILE: docs/AI.html ================================================ AI module — wukong-robot 1.2.0 文档

AI module

================================================ FILE: docs/ASR.html ================================================ ASR module — wukong-robot 1.2.0 文档

ASR module

================================================ FILE: docs/Brain.html ================================================ Brain module — wukong-robot 1.2.0 文档

Brain module

================================================ FILE: docs/ConfigMonitor.html ================================================ ConfigMonitor module — wukong-robot 1.2.0 文档

ConfigMonitor module

================================================ FILE: docs/Conversation.html ================================================ Conversation module — wukong-robot 1.2.0 文档

Conversation module

================================================ FILE: docs/Player.html ================================================ Player module — wukong-robot 1.2.0 文档

Player module

================================================ FILE: docs/TTS.html ================================================ TTS module — wukong-robot 1.2.0 文档

TTS module

================================================ FILE: docs/Updater.html ================================================ Updater module — wukong-robot 1.2.0 文档

Updater module

================================================ FILE: docs/_modules/index.html ================================================ 概览:模块代码 — wukong-robot 1.2.0 文档
================================================ FILE: docs/_modules/logging.html ================================================ logging — wukong-robot 1.2.0 文档

logging 源代码

# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

"""
Logging package for Python. Based on PEP 282 and comments thereto in
comp.lang.python.

Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved.

To use, simply 'import logging' and log away!
"""

import sys, os, time, io, traceback, warnings, weakref, collections

from string import Template

__all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
           'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
           'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler',
           'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig',
           'captureWarnings', 'critical', 'debug', 'disable', 'error',
           'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
           'info', 'log', 'makeLogRecord', 'setLoggerClass', 'warn', 'warning',
           'getLogRecordFactory', 'setLogRecordFactory', 'lastResort']

try:
    import threading
except ImportError: #pragma: no cover
    threading = None

__author__  = "Vinay Sajip <vinay_sajip@red-dove.com>"
__status__  = "production"
# The following module attributes are no longer updated.
__version__ = "0.5.1.2"
__date__    = "07 February 2010"

#---------------------------------------------------------------------------
#   Miscellaneous module data
#---------------------------------------------------------------------------

#
#_startTime is used as the base when calculating the relative time of events
#
_startTime = time.time()

#
#raiseExceptions is used to see if exceptions during handling should be
#propagated
#
raiseExceptions = True

#
# If you don't want threading information in the log, set this to zero
#
logThreads = True

#
# If you don't want multiprocessing information in the log, set this to zero
#
logMultiprocessing = True

#
# If you don't want process information in the log, set this to zero
#
logProcesses = True

#---------------------------------------------------------------------------
#   Level related stuff
#---------------------------------------------------------------------------
#
# Default levels and level names, these can be replaced with any positive set
# of values having corresponding names. There is a pseudo-level, NOTSET, which
# is only really there as a lower limit for user-defined levels. Handlers and
# loggers are initialized with NOTSET so that they will log all messages, even
# at user-defined levels.
#

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

_levelToName = {
    CRITICAL: 'CRITICAL',
    ERROR: 'ERROR',
    WARNING: 'WARNING',
    INFO: 'INFO',
    DEBUG: 'DEBUG',
    NOTSET: 'NOTSET',
}
_nameToLevel = {
    'CRITICAL': CRITICAL,
    'ERROR': ERROR,
    'WARN': WARNING,
    'WARNING': WARNING,
    'INFO': INFO,
    'DEBUG': DEBUG,
    'NOTSET': NOTSET,
}

[文档]def getLevelName(level): """ Return the textual representation of logging level 'level'. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with 'level' is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. Otherwise, the string "Level %s" % level is returned. """ # See Issues #22386 and #27937 for why it's this way return (_levelToName.get(level) or _nameToLevel.get(level) or "Level %s" % level)
[文档]def addLevelName(level, levelName): """ Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting. """ _acquireLock() try: #unlikely to cause an exception, but you never know... _levelToName[level] = levelName _nameToLevel[levelName] = level finally: _releaseLock()
if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) else: #pragma: no cover def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except Exception: return sys.exc_info()[2].tb_frame.f_back # # _srcfile is used when walking the stack to check when we've got the first # caller stack frame, by skipping frames whose filename is that of this # module's source. It therefore should contain the filename of this module's # source file. # # Ordinarily we would use __file__ for this, but frozen modules don't always # have __file__ set, for some reason (see Issue #21736). Thus, we get the # filename from a handy code object from a function defined in this module. # (There's no particular reason for picking addLevelName.) # _srcfile = os.path.normcase(addLevelName.__code__.co_filename) # _srcfile is only used in conjunction with sys._getframe(). # To provide compatibility with older versions of Python, set _srcfile # to None if _getframe() is not available; this value will prevent # findCaller() from being called. You can also do this if you want to avoid # the overhead of fetching caller information, even when _getframe() is # available. #if not hasattr(sys, '_getframe'): # _srcfile = None def _checkLevel(level): if isinstance(level, int): rv = level elif str(level) == level: if level not in _nameToLevel: raise ValueError("Unknown level: %r" % level) rv = _nameToLevel[level] else: raise TypeError("Level not an integer or a valid string: %r" % level) return rv #--------------------------------------------------------------------------- # Thread-related stuff #--------------------------------------------------------------------------- # #_lock is used to serialize access to shared data structures in this module. #This needs to be an RLock because fileConfig() creates and configures #Handlers, and so might arbitrary user threads. Since Handler code updates the #shared dictionary _handlers, it needs to acquire the lock. But if configuring, #the lock would already have been acquired - so we need an RLock. #The same argument applies to Loggers and Manager.loggerDict. # if threading: _lock = threading.RLock() else: #pragma: no cover _lock = None def _acquireLock(): """ Acquire the module-level lock for serializing access to shared data. This should be released with _releaseLock(). """ if _lock: _lock.acquire() def _releaseLock(): """ Release the module-level lock acquired by calling _acquireLock(). """ if _lock: _lock.release() #--------------------------------------------------------------------------- # The logging record #---------------------------------------------------------------------------
[文档]class LogRecord(object): """ A LogRecord instance represents an event being logged. LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in msg and args, which are combined using str(msg) % args to create the message field of the record. The record also includes information such as when the record was created, the source line where the logging call was made, and any exception information to be logged. """ def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs): """ Initialize a logging record with interesting information. """ ct = time.time() self.name = name self.msg = msg # # The following statement allows passing of a dictionary as a sole # argument, so that you can do something like # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) # Suggested by Stefan Behnel. # Note that without the test for args[0], we get a problem because # during formatting, we test to see if the arg is present using # 'if self.args:'. If the event being logged is e.g. 'Value is %d' # and if the passed arg fails 'if self.args:' then no formatting # is done. For example, logger.warning('Value is %d', 0) would log # 'Value is %d' instead of 'Value is 0'. # For the use case of passing a dictionary, this should not be a # problem. # Issue #21172: a request was made to relax the isinstance check # to hasattr(args[0], '__getitem__'). However, the docs on string # formatting still seem to suggest a mapping object is required. # Thus, while not removing the isinstance check, it does now look # for collections.Mapping rather than, as before, dict. if (args and len(args) == 1 and isinstance(args[0], collections.Mapping) and args[0]): args = args[0] self.args = args self.levelname = getLevelName(level) self.levelno = level self.pathname = pathname try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info self.exc_text = None # used to cache the traceback text self.stack_info = sinfo self.lineno = lineno self.funcName = func self.created = ct self.msecs = (ct - int(ct)) * 1000 self.relativeCreated = (self.created - _startTime) * 1000 if logThreads and threading: self.thread = threading.get_ident() self.threadName = threading.current_thread().name else: # pragma: no cover self.thread = None self.threadName = None if not logMultiprocessing: # pragma: no cover self.processName = None else: self.processName = 'MainProcess' mp = sys.modules.get('multiprocessing') if mp is not None: # Errors may occur if multiprocessing has not finished loading # yet - e.g. if a custom import hook causes third-party code # to run when multiprocessing calls import. See issue 8200 # for an example try: self.processName = mp.current_process().name except Exception: #pragma: no cover pass if logProcesses and hasattr(os, 'getpid'): self.process = os.getpid() else: self.process = None def __str__(self): return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno, self.pathname, self.lineno, self.msg) __repr__ = __str__
[文档] def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ msg = str(self.msg) if self.args: msg = msg % self.args return msg
# # Determine which class to use when instantiating log records. # _logRecordFactory = LogRecord
[文档]def setLogRecordFactory(factory): """ Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. """ global _logRecordFactory _logRecordFactory = factory
[文档]def getLogRecordFactory(): """ Return the factory to be used when instantiating a log record. """ return _logRecordFactory
[文档]def makeLogRecord(dict): """ Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance. """ rv = _logRecordFactory(None, None, "", 0, "", (), None, None) rv.__dict__.update(dict) return rv
#--------------------------------------------------------------------------- # Formatter classes and functions #--------------------------------------------------------------------------- class PercentStyle(object): default_format = '%(message)s' asctime_format = '%(asctime)s' asctime_search = '%(asctime)' def __init__(self, fmt): self._fmt = fmt or self.default_format def usesTime(self): return self._fmt.find(self.asctime_search) >= 0 def format(self, record): return self._fmt % record.__dict__ class StrFormatStyle(PercentStyle): default_format = '{message}' asctime_format = '{asctime}' asctime_search = '{asctime' def format(self, record): return self._fmt.format(**record.__dict__) class StringTemplateStyle(PercentStyle): default_format = '${message}' asctime_format = '${asctime}' asctime_search = '${asctime}' def __init__(self, fmt): self._fmt = fmt or self.default_format self._tpl = Template(self._fmt) def usesTime(self): fmt = self._fmt return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0 def format(self, record): return self._tpl.substitute(**record.__dict__) BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s" _STYLES = { '%': (PercentStyle, BASIC_FORMAT), '{': (StrFormatStyle, '{levelname}:{name}:{message}'), '$': (StringTemplateStyle, '${levelname}:${name}:${message}'), }
[文档]class Formatter(object): """ Formatter instances are used to convert a LogRecord to text. Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the default value of "%s(message)" is used. The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are pre- formatted into a LogRecord's message attribute. Currently, the useful attributes in a LogRecord are described by: %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) %(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued (if available) %(funcName)s Function name %(created)f Time when the LogRecord was created (time.time() return value) %(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time) %(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted """ converter = time.localtime def __init__(self, fmt=None, datefmt=None, style='%'): """ Initialize the formatter with specified format strings. Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument (if omitted, you get the ISO8601 format). Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:`str.format` (``{}``) formatting or :class:`string.Template` formatting in your format string. .. versionchanged:: 3.2 Added the ``style`` parameter. """ if style not in _STYLES: raise ValueError('Style must be one of: %s' % ','.join( _STYLES.keys())) self._style = _STYLES[style][0](fmt) self._fmt = self._style._fmt self.datefmt = datefmt default_time_format = '%Y-%m-%d %H:%M:%S' default_msec_format = '%s,%03d'
[文档] def formatTime(self, record, datefmt=None): """ Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class. """ ct = self.converter(record.created) if datefmt: s = time.strftime(datefmt, ct) else: t = time.strftime(self.default_time_format, ct) s = self.default_msec_format % (t, record.msecs) return s
[文档] def formatException(self, ei): """ Format and return the specified exception information as a string. This default implementation just uses traceback.print_exception() """ sio = io.StringIO() tb = ei[2] # See issues #9427, #1553375. Commented out for now. #if getattr(self, 'fullstack', False): # traceback.print_stack(tb.tb_frame.f_back, file=sio) traceback.print_exception(ei[0], ei[1], tb, None, sio) s = sio.getvalue() sio.close() if s[-1:] == "\n": s = s[:-1] return s
[文档] def usesTime(self): """ Check if the format uses the creation time of the record. """ return self._style.usesTime()
[文档] def formatMessage(self, record): return self._style.format(record)
[文档] def formatStack(self, stack_info): """ This method is provided as an extension point for specialized formatting of stack information. The input data is a string as returned from a call to :func:`traceback.print_stack`, but with the last trailing newline removed. The base implementation just returns the value passed in. """ return stack_info
[文档] def format(self, record): """ Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message. """ record.message = record.getMessage() if self.usesTime(): record.asctime = self.formatTime(record, self.datefmt) s = self.formatMessage(record) if record.exc_info: # Cache the traceback text to avoid converting it multiple times # (it's constant anyway) if not record.exc_text: record.exc_text = self.formatException(record.exc_info) if record.exc_text: if s[-1:] != "\n": s = s + "\n" s = s + record.exc_text if record.stack_info: if s[-1:] != "\n": s = s + "\n" s = s + self.formatStack(record.stack_info) return s
# # The default formatter to use when no other is specified # _defaultFormatter = Formatter()
[文档]class BufferingFormatter(object): """ A formatter suitable for formatting a number of records. """ def __init__(self, linefmt=None): """ Optionally specify a formatter which will be used to format each individual record. """ if linefmt: self.linefmt = linefmt else: self.linefmt = _defaultFormatter
[文档] def formatHeader(self, records): """ Return the header string for the specified records. """ return ""
[文档] def formatFooter(self, records): """ Return the footer string for the specified records. """ return ""
[文档] def format(self, records): """ Format the specified records and return the result as a string. """ rv = "" if len(records) > 0: rv = rv + self.formatHeader(records) for record in records: rv = rv + self.linefmt.format(record) rv = rv + self.formatFooter(records) return rv
#--------------------------------------------------------------------------- # Filter classes and functions #---------------------------------------------------------------------------
[文档]class Filter(object): """ Filter instances are used to perform arbitrary filtering of LogRecords. Loggers and Handlers can optionally use Filter instances to filter records as desired. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the empty string, all events are passed. """ def __init__(self, name=''): """ Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event. """ self.name = name self.nlen = len(name)
[文档] def filter(self, record): """ Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place. """ if self.nlen == 0: return True elif self.name == record.name: return True elif record.name.find(self.name, 0, self.nlen) != 0: return False return (record.name[self.nlen] == ".")
class Filterer(object): """ A base class for loggers and handlers which allows them to share common code. """ def __init__(self): """ Initialize the list of filters to be an empty list. """ self.filters = [] def addFilter(self, filter): """ Add the specified filter to this handler. """ if not (filter in self.filters): self.filters.append(filter) def removeFilter(self, filter): """ Remove the specified filter from this handler. """ if filter in self.filters: self.filters.remove(filter) def filter(self, record): """ Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero. .. versionchanged:: 3.2 Allow filters to be just callables. """ rv = True for f in self.filters: if hasattr(f, 'filter'): result = f.filter(record) else: result = f(record) # assume callable - will raise if not if not result: rv = False break return rv #--------------------------------------------------------------------------- # Handler classes and functions #--------------------------------------------------------------------------- _handlers = weakref.WeakValueDictionary() #map of handler names to handlers _handlerList = [] # added to allow handlers to be removed in reverse of order initialized def _removeHandlerRef(wr): """ Remove a handler reference from the internal cleanup list. """ # This function can be called during module teardown, when globals are # set to None. It can also be called from another thread. So we need to # pre-emptively grab the necessary globals and check if they're None, # to prevent race conditions and failures during interpreter shutdown. acquire, release, handlers = _acquireLock, _releaseLock, _handlerList if acquire and release and handlers: acquire() try: if wr in handlers: handlers.remove(wr) finally: release() def _addHandlerRef(handler): """ Add a handler to the internal cleanup list using a weak reference. """ _acquireLock() try: _handlerList.append(weakref.ref(handler, _removeHandlerRef)) finally: _releaseLock()
[文档]class Handler(Filterer): """ Handler instances dispatch logging events to specific destinations. The base handler class. Acts as a placeholder which defines the Handler interface. Handlers can optionally use Formatter instances to format records as desired. By default, no formatter is specified; in this case, the 'raw' message as determined by record.message is logged. """ def __init__(self, level=NOTSET): """ Initializes the instance - basically setting the formatter to None and the filter list to empty. """ Filterer.__init__(self) self._name = None self.level = _checkLevel(level) self.formatter = None # Add the handler to the global _handlerList (for cleanup on shutdown) _addHandlerRef(self) self.createLock()
[文档] def get_name(self): return self._name
[文档] def set_name(self, name): _acquireLock() try: if self._name in _handlers: del _handlers[self._name] self._name = name if name: _handlers[name] = self finally: _releaseLock()
name = property(get_name, set_name)
[文档] def createLock(self): """ Acquire a thread lock for serializing access to the underlying I/O. """ if threading: self.lock = threading.RLock() else: #pragma: no cover self.lock = None
[文档] def acquire(self): """ Acquire the I/O thread lock. """ if self.lock: self.lock.acquire()
[文档] def release(self): """ Release the I/O thread lock. """ if self.lock: self.lock.release()
[文档] def setLevel(self, level): """ Set the logging level of this handler. level must be an int or a str. """ self.level = _checkLevel(level)
[文档] def format(self, record): """ Format the specified record. If a formatter is set, use it. Otherwise, use the default formatter for the module. """ if self.formatter: fmt = self.formatter else: fmt = _defaultFormatter return fmt.format(record)
[文档] def emit(self, record): """ Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError. """ raise NotImplementedError('emit must be implemented ' 'by Handler subclasses')
[文档] def handle(self, record): """ Conditionally emit the specified logging record. Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission. """ rv = self.filter(record) if rv: self.acquire() try: self.emit(record) finally: self.release() return rv
[文档] def setFormatter(self, fmt): """ Set the formatter for this handler. """ self.formatter = fmt
[文档] def flush(self): """ Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses. """ pass
[文档] def close(self): """ Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods. """ #get the module data lock, as we're updating a shared structure. _acquireLock() try: #unlikely to raise an exception, but you never know... if self._name and self._name in _handlers: del _handlers[self._name] finally: _releaseLock()
[文档] def handleError(self, record): """ Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method. """ if raiseExceptions and sys.stderr: # see issue 13807 t, v, tb = sys.exc_info() try: sys.stderr.write('--- Logging error ---\n') traceback.print_exception(t, v, tb, None, sys.stderr) sys.stderr.write('Call stack:\n') # Walk the stack frame up until we're out of logging, # so as to print the calling context. frame = tb.tb_frame while (frame and os.path.dirname(frame.f_code.co_filename) == __path__[0]): frame = frame.f_back if frame: traceback.print_stack(frame, file=sys.stderr) else: # couldn't find the right stack frame, for some reason sys.stderr.write('Logged from file %s, line %s\n' % ( record.filename, record.lineno)) # Issue 18671: output logging message and arguments try: sys.stderr.write('Message: %r\n' 'Arguments: %s\n' % (record.msg, record.args)) except Exception: sys.stderr.write('Unable to print the message and arguments' ' - possible formatting error.\nUse the' ' traceback above to help find the error.\n' ) except OSError: #pragma: no cover pass # see issue 5971 finally: del t, v, tb
[文档]class StreamHandler(Handler): """ A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used. """ terminator = '\n' def __init__(self, stream=None): """ Initialize the handler. If stream is not specified, sys.stderr is used. """ Handler.__init__(self) if stream is None: stream = sys.stderr self.stream = stream
[文档] def flush(self): """ Flushes the stream. """ self.acquire() try: if self.stream and hasattr(self.stream, "flush"): self.stream.flush() finally: self.release()
[文档] def emit(self, record): """ Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream. """ try: msg = self.format(record) stream = self.stream stream.write(msg) stream.write(self.terminator) self.flush() except Exception: self.handleError(record)
[文档]class FileHandler(StreamHandler): """ A handler class which writes formatted logging records to disk files. """ def __init__(self, filename, mode='a', encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. """ #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes self.baseFilename = os.path.abspath(filename) self.mode = mode self.encoding = encoding self.delay = delay if delay: #We don't open the stream, but we still need to call the #Handler constructor to set level, formatter, lock etc. Handler.__init__(self) self.stream = None else: StreamHandler.__init__(self, self._open())
[文档] def close(self): """ Closes the stream. """ self.acquire() try: try: if self.stream: try: self.flush() finally: stream = self.stream self.stream = None if hasattr(stream, "close"): stream.close() finally: # Issue #19523: call unconditionally to # prevent a handler leak when delay is set StreamHandler.close(self) finally: self.release()
def _open(self): """ Open the current base file with the (original) mode and encoding. Return the resulting stream. """ return open(self.baseFilename, self.mode, encoding=self.encoding)
[文档] def emit(self, record): """ Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit. """ if self.stream is None: self.stream = self._open() StreamHandler.emit(self, record)
class _StderrHandler(StreamHandler): """ This class is like a StreamHandler using sys.stderr, but always uses whatever sys.stderr is currently set to rather than the value of sys.stderr at handler construction time. """ def __init__(self, level=NOTSET): """ Initialize the handler. """ Handler.__init__(self, level) @property def stream(self): return sys.stderr _defaultLastResort = _StderrHandler(WARNING) lastResort = _defaultLastResort #--------------------------------------------------------------------------- # Manager classes and functions #--------------------------------------------------------------------------- class PlaceHolder(object): """ PlaceHolder instances are used in the Manager logger hierarchy to take the place of nodes for which no loggers have been defined. This class is intended for internal use only and not as part of the public API. """ def __init__(self, alogger): """ Initialize with the specified logger being a child of this placeholder. """ self.loggerMap = { alogger : None } def append(self, alogger): """ Add the specified logger as a child of this placeholder. """ if alogger not in self.loggerMap: self.loggerMap[alogger] = None # # Determine which class to use when instantiating loggers. #
[文档]def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) global _loggerClass _loggerClass = klass
[文档]def getLoggerClass(): """ Return the class to be used when instantiating a logger. """ return _loggerClass
class Manager(object): """ There is [under normal circumstances] just one Manager instance, which holds the hierarchy of loggers. """ def __init__(self, rootnode): """ Initialize the manager with the root node of the logger hierarchy. """ self.root = rootnode self.disable = 0 self.emittedNoHandlerWarning = False self.loggerDict = {} self.loggerClass = None self.logRecordFactory = None def getLogger(self, name): """ Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. """ rv = None if not isinstance(name, str): raise TypeError('A logger name must be a string') _acquireLock() try: if name in self.loggerDict: rv = self.loggerDict[name] if isinstance(rv, PlaceHolder): ph = rv rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupChildren(ph, rv) self._fixupParents(rv) else: rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupParents(rv) finally: _releaseLock() return rv def setLoggerClass(self, klass): """ Set the class to be used when instantiating a logger with this Manager. """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) self.loggerClass = klass def setLogRecordFactory(self, factory): """ Set the factory to be used when instantiating a log record with this Manager. """ self.logRecordFactory = factory def _fixupParents(self, alogger): """ Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy. """ name = alogger.name i = name.rfind(".") rv = None while (i > 0) and not rv: substr = name[:i] if substr not in self.loggerDict: self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] if isinstance(obj, Logger): rv = obj else: assert isinstance(obj, PlaceHolder) obj.append(alogger) i = name.rfind(".", 0, i - 1) if not rv: rv = self.root alogger.parent = rv def _fixupChildren(self, ph, alogger): """ Ensure that children of the placeholder ph are connected to the specified logger. """ name = alogger.name namelen = len(name) for c in ph.loggerMap.keys(): #The if means ... if not c.parent.name.startswith(nm) if c.parent.name[:namelen] != name: alogger.parent = c.parent c.parent = alogger #--------------------------------------------------------------------------- # Logger classes and functions #---------------------------------------------------------------------------
[文档]class Logger(Filterer): """ Instances of the Logger class represent a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of "input processing" might include sub-areas "read CSV files", "read XLS files" and "read Gnumeric files"). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be "input" for the upper level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. There is no arbitrary limit to the depth of nesting. """ def __init__(self, name, level=NOTSET): """ Initialize the logger with a name and an optional level. """ Filterer.__init__(self) self.name = name self.level = _checkLevel(level) self.parent = None self.propagate = True self.handlers = [] self.disabled = False
[文档] def setLevel(self, level): """ Set the logging level of this logger. level must be an int or a str. """ self.level = _checkLevel(level)
[文档] def debug(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) """ if self.isEnabledFor(DEBUG): self._log(DEBUG, msg, args, **kwargs)
[文档] def info(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1) """ if self.isEnabledFor(INFO): self._log(INFO, msg, args, **kwargs)
[文档] def warning(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1) """ if self.isEnabledFor(WARNING): self._log(WARNING, msg, args, **kwargs)
[文档] def warn(self, msg, *args, **kwargs): warnings.warn("The 'warn' method is deprecated, " "use 'warning' instead", DeprecationWarning, 2) self.warning(msg, *args, **kwargs)
[文档] def error(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1) """ if self.isEnabledFor(ERROR): self._log(ERROR, msg, args, **kwargs)
[文档] def exception(self, msg, *args, exc_info=True, **kwargs): """ Convenience method for logging an ERROR with exception information. """ self.error(msg, *args, exc_info=exc_info, **kwargs)
[文档] def critical(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1) """ if self.isEnabledFor(CRITICAL): self._log(CRITICAL, msg, args, **kwargs)
fatal = critical
[文档] def log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) """ if not isinstance(level, int): if raiseExceptions: raise TypeError("level must be an integer") else: return if self.isEnabledFor(level): self._log(level, msg, args, **kwargs)
[文档] def findCaller(self, stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() #On some versions of IronPython, currentframe() returns None if #IronPython isn't run with -X:Frames. if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)", None while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue sinfo = None if stack_info: sio = io.StringIO() sio.write('Stack (most recent call last):\n') traceback.print_stack(f, file=sio) sinfo = sio.getvalue() if sinfo[-1] == '\n': sinfo = sinfo[:-1] sio.close() rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) break return rv
[文档] def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func, sinfo) if extra is not None: for key in extra: if (key in ["message", "asctime"]) or (key in rv.__dict__): raise KeyError("Attempt to overwrite %r in LogRecord" % key) rv.__dict__[key] = extra[key] return rv
def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): """ Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record. """ sinfo = None if _srcfile: #IronPython doesn't track Python frames, so findCaller raises an #exception on some versions of IronPython. We trap it here so that #IronPython can use logging. try: fn, lno, func, sinfo = self.findCaller(stack_info) except ValueError: # pragma: no cover fn, lno, func = "(unknown file)", 0, "(unknown function)" else: # pragma: no cover fn, lno, func = "(unknown file)", 0, "(unknown function)" if exc_info: if isinstance(exc_info, BaseException): exc_info = (type(exc_info), exc_info, exc_info.__traceback__) elif not isinstance(exc_info, tuple): exc_info = sys.exc_info() record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra, sinfo) self.handle(record)
[文档] def handle(self, record): """ Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied. """ if (not self.disabled) and self.filter(record): self.callHandlers(record)
[文档] def addHandler(self, hdlr): """ Add the specified handler to this logger. """ _acquireLock() try: if not (hdlr in self.handlers): self.handlers.append(hdlr) finally: _releaseLock()
[文档] def removeHandler(self, hdlr): """ Remove the specified handler from this logger. """ _acquireLock() try: if hdlr in self.handlers: self.handlers.remove(hdlr) finally: _releaseLock()
[文档] def hasHandlers(self): """ See if this logger has any handlers configured. Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger which is checked for the existence of handlers. """ c = self rv = False while c: if c.handlers: rv = True break if not c.propagate: break else: c = c.parent return rv
[文档] def callHandlers(self, record): """ Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger whose handlers are called. """ c = self found = 0 while c: for hdlr in c.handlers: found = found + 1 if record.levelno >= hdlr.level: hdlr.handle(record) if not c.propagate: c = None #break out else: c = c.parent if (found == 0): if lastResort: if record.levelno >= lastResort.level: lastResort.handle(record) elif raiseExceptions and not self.manager.emittedNoHandlerWarning: sys.stderr.write("No handlers could be found for logger" " \"%s\"\n" % self.name) self.manager.emittedNoHandlerWarning = True
[文档] def getEffectiveLevel(self): """ Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found. """ logger = self while logger: if logger.level: return logger.level logger = logger.parent return NOTSET
[文档] def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ if self.manager.disable >= level: return False return level >= self.getEffectiveLevel()
[文档] def getChild(self, suffix): """ Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. """ if self.root is not self: suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix)
class RootLogger(Logger): """ A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy. """ def __init__(self, level): """ Initialize the logger with the name "root". """ Logger.__init__(self, "root", level) _loggerClass = Logger
[文档]class LoggerAdapter(object): """ An adapter for loggers which makes it easier to specify contextual information in logging output. """ def __init__(self, logger, extra): """ Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) """ self.logger = logger self.extra = extra
[文档] def process(self, msg, kwargs): """ Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. Normally, you'll only need to override this one method in a LoggerAdapter subclass for your specific needs. """ kwargs["extra"] = self.extra return msg, kwargs
# # Boilerplate convenience methods #
[文档] def debug(self, msg, *args, **kwargs): """ Delegate a debug call to the underlying logger. """ self.log(DEBUG, msg, *args, **kwargs)
[文档] def info(self, msg, *args, **kwargs): """ Delegate an info call to the underlying logger. """ self.log(INFO, msg, *args, **kwargs)
[文档] def warning(self, msg, *args, **kwargs): """ Delegate a warning call to the underlying logger. """ self.log(WARNING, msg, *args, **kwargs)
[文档] def warn(self, msg, *args, **kwargs): warnings.warn("The 'warn' method is deprecated, " "use 'warning' instead", DeprecationWarning, 2) self.warning(msg, *args, **kwargs)
[文档] def error(self, msg, *args, **kwargs): """ Delegate an error call to the underlying logger. """ self.log(ERROR, msg, *args, **kwargs)
[文档] def exception(self, msg, *args, exc_info=True, **kwargs): """ Delegate an exception call to the underlying logger. """ self.log(ERROR, msg, *args, exc_info=exc_info, **kwargs)
[文档] def critical(self, msg, *args, **kwargs): """ Delegate a critical call to the underlying logger. """ self.log(CRITICAL, msg, *args, **kwargs)
[文档] def log(self, level, msg, *args, **kwargs): """ Delegate a log call to the underlying logger, after adding contextual information from this adapter instance. """ if self.isEnabledFor(level): msg, kwargs = self.process(msg, kwargs) self.logger._log(level, msg, args, **kwargs)
[文档] def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ if self.logger.manager.disable >= level: return False return level >= self.getEffectiveLevel()
[文档] def setLevel(self, level): """ Set the specified level on the underlying logger. """ self.logger.setLevel(level)
[文档] def getEffectiveLevel(self): """ Get the effective level for the underlying logger. """ return self.logger.getEffectiveLevel()
[文档] def hasHandlers(self): """ See if the underlying logger has any handlers. """ return self.logger.hasHandlers()
root = RootLogger(WARNING) Logger.root = root Logger.manager = Manager(Logger.root) #--------------------------------------------------------------------------- # Configuration classes and functions #---------------------------------------------------------------------------
[文档]def basicConfig(**kwargs): """ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. style If a format string is specified, use this to specify the type of format string (possible values '%', '{', '$', for %-formatting, :meth:`str.format` and :class:`string.Template` - defaults to '%'). level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. handlers If specified, this should be an iterable of already created handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. .. versionchanged:: 3.2 Added the ``style`` parameter. .. versionchanged:: 3.3 Added the ``handlers`` parameter. A ``ValueError`` is now thrown for incompatible arguments (e.g. ``handlers`` specified together with ``filename``/``filemode``, or ``filename``/``filemode`` specified together with ``stream``, or ``handlers`` specified together with ``stream``. """ # Add thread safety in case someone mistakenly calls # basicConfig() from multiple threads _acquireLock() try: if len(root.handlers) == 0: handlers = kwargs.pop("handlers", None) if handlers is None: if "stream" in kwargs and "filename" in kwargs: raise ValueError("'stream' and 'filename' should not be " "specified together") else: if "stream" in kwargs or "filename" in kwargs: raise ValueError("'stream' or 'filename' should not be " "specified together with 'handlers'") if handlers is None: filename = kwargs.pop("filename", None) mode = kwargs.pop("filemode", 'a') if filename: h = FileHandler(filename, mode) else: stream = kwargs.pop("stream", None) h = StreamHandler(stream) handlers = [h] dfs = kwargs.pop("datefmt", None) style = kwargs.pop("style", '%') if style not in _STYLES: raise ValueError('Style must be one of: %s' % ','.join( _STYLES.keys())) fs = kwargs.pop("format", _STYLES[style][1]) fmt = Formatter(fs, dfs, style) for h in handlers: if h.formatter is None: h.setFormatter(fmt) root.addHandler(h) level = kwargs.pop("level", None) if level is not None: root.setLevel(level) if kwargs: keys = ', '.join(kwargs.keys()) raise ValueError('Unrecognised argument(s): %s' % keys) finally: _releaseLock()
#--------------------------------------------------------------------------- # Utility functions at module level. # Basically delegate everything to the root logger. #---------------------------------------------------------------------------
[文档]def getLogger(name=None): """ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. """ if name: return Logger.manager.getLogger(name) else: return root
[文档]def critical(msg, *args, **kwargs): """ Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.critical(msg, *args, **kwargs)
fatal = critical
[文档]def error(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.error(msg, *args, **kwargs)
[文档]def exception(msg, *args, exc_info=True, **kwargs): """ Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format. """ error(msg, *args, exc_info=exc_info, **kwargs)
[文档]def warning(msg, *args, **kwargs): """ Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.warning(msg, *args, **kwargs)
[文档]def warn(msg, *args, **kwargs): warnings.warn("The 'warn' function is deprecated, " "use 'warning' instead", DeprecationWarning, 2) warning(msg, *args, **kwargs)
[文档]def info(msg, *args, **kwargs): """ Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.info(msg, *args, **kwargs)
[文档]def debug(msg, *args, **kwargs): """ Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.debug(msg, *args, **kwargs)
[文档]def log(level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.log(level, msg, *args, **kwargs)
[文档]def disable(level): """ Disable all logging calls of severity 'level' and below. """ root.manager.disable = level
def shutdown(handlerList=_handlerList): """ Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. """ for wr in reversed(handlerList[:]): #errors might occur, for example, if files are locked #we just ignore them if raiseExceptions is not set try: h = wr() if h: try: h.acquire() h.flush() h.close() except (OSError, ValueError): # Ignore errors which might be caused # because handlers have been closed but # references to them are still around at # application exit. pass finally: h.release() except: # ignore everything, as we're shutting down if raiseExceptions: raise #else, swallow #Let's try and shutdown automatically on application exit... import atexit atexit.register(shutdown) # Null handler
[文档]class NullHandler(Handler): """ This handler does nothing. It's intended to be used to avoid the "No handlers could be found for logger XXX" one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be produced; to avoid this, the library developer simply needs to instantiate a NullHandler and add it to the top-level logger of the library module or package. """
[文档] def handle(self, record): """Stub."""
[文档] def emit(self, record): """Stub."""
[文档] def createLock(self): self.lock = None
# Warnings integration _warnings_showwarning = None def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s)
[文档]def captureWarnings(capture): """ If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations. """ global _warnings_showwarning if capture: if _warnings_showwarning is None: _warnings_showwarning = warnings.showwarning warnings.showwarning = _showwarning else: if _warnings_showwarning is not None: warnings.showwarning = _warnings_showwarning _warnings_showwarning = None
================================================ FILE: docs/_modules/plugins/Camera.html ================================================ plugins.Camera — wukong-robot 1.2.0 文档

plugins.Camera 源代码

# -*- coding: utf-8-*-

import os
import subprocess
import time
from robot import config, constants, logging
from robot.sdk.AbstractPlugin import AbstractPlugin

logger = logging.getLogger(__name__)

[文档]class Plugin(AbstractPlugin): SLUG = "camera"
[文档] def handle(self, text, parsed): quality = config.get('/camera/quality', 100) count_down = config.get('/camera/count_down', 3) dest_path = config.get('/camera/dest_path', os.path.expanduser('~/pictures')) device = config.get('/camera/device', '/dev/video0') vertical_flip = config.get('/camera/verical_flip', False) horizontal_flip = config.get('/camera/horizontal_flip', False) sound = config.get('/camera/sound', True) camera_type = config.get('/camera/type', 0) if config.has('/camera/usb_camera') and config.get('/camera/usb_camera'): camera_type = 0 if any(word in text for word in [u"安静", u"偷偷", u"悄悄"]): sound = False try: if not os.path.exists(dest_path): os.makedirs(dest_path) except Exception: self.say(u"抱歉,照片目录创建失败", cache=True) return dest_file = os.path.join(dest_path, "%s.jpg" % time.time()) if camera_type == 0: # usb camera logger.info('usb camera') command = ['fswebcam', '--no-banner', '-r', '1024x765', '-q', '-d', device] if vertical_flip: command.extend(['-s', 'v']) if horizontal_flip: command.extend(['-s', 'h']) command.append(dest_file) elif camera_type == 1: # Raspberry Pi 5MP logger.info('Raspberry Pi 5MP camera') command = ['raspistill', '-o', dest_file, '-q', str(quality)] if count_down > 0 and sound: command.extend(['-t', str(count_down*1000)]) if vertical_flip: command.append('-vf') if horizontal_flip: command.append('-hf') else: # notebook camera logger.info('notebook camera') command = ['imagesnap', dest_file] if count_down > 0 and sound: command.extend(['-w', str(count_down)]) if sound and count_down > 0: self.say(u"收到,%d秒后启动拍照" % (count_down), cache=True) if camera_type == 0: time.sleep(count_down) try: subprocess.run(command, shell=False, check=True) if sound: self.play(constants.getData('camera.wav')) photo_url = 'http://{}:{}/photo/{}'.format(config.get('/server/host'), config.get('/server/port'), os.path.basename(dest_file)) self.say(u'拍照成功:{}'.format(photo_url), cache=True) except subprocess.CalledProcessError as e: logger.error(e) if sound: self.say(u"拍照失败,请检查相机是否连接正确", cache=True)
[文档] def isValid(self, text, parsed): return any(word in text for word in ["拍照", "拍张照"])
================================================ FILE: docs/_modules/plugins/CleanCache.html ================================================ plugins.CleanCache — wukong-robot 1.2.0 文档

plugins.CleanCache 源代码

# -*- coding: utf-8-*-

import os
from robot import constants, utils
from robot.sdk.AbstractPlugin import AbstractPlugin

[文档]class Plugin(AbstractPlugin): SLUG = 'cleancache'
[文档] def handle(self, text, parsed): temp = constants.TEMP_PATH for f in os.listdir(temp): if f != 'DIR': utils.check_and_delete(os.path.join(temp, f)) self.say(u'缓存目录已清空', cache=True)
[文档] def isValid(self, text, parsed): return any(word in text.lower() for word in ["清除缓存", u"清空缓存", u"清缓存"])
================================================ FILE: docs/_modules/plugins/Echo.html ================================================ plugins.Echo — wukong-robot 1.2.0 文档

plugins.Echo 源代码

# -*- coding: utf-8-*-
# author: wzpan
# 写诗

import logging
from robot.sdk.AbstractPlugin import AbstractPlugin

logger = logging.getLogger(__name__)

[文档]class Plugin(AbstractPlugin):
[文档] def handle(self, text, parsed): text = text.lower().replace('echo', '').replace(u'传话', '') self.say(text, cache=False)
[文档] def isValid(self, text, parsed): return any(word in text.lower() for word in ["echo", u"传话"])
================================================ FILE: docs/_modules/plugins/Email.html ================================================ plugins.Email — wukong-robot 1.2.0 文档

plugins.Email 源代码

# -*- coding: utf-8-*-
import imaplib
import email
import time
import datetime
from robot import logging
from dateutil import parser
from robot import config
from robot.sdk.AbstractPlugin import AbstractPlugin

[文档]class Plugin(AbstractPlugin): SLUG = 'email'
[文档] def getSender(self, msg): """ Returns the best-guess sender of an email. Arguments: msg -- the email whose sender is desired Returns: Sender of the sender. """ fromstr = str(msg["From"]) ls = fromstr.split(' ') if(len(ls) == 2): fromname = email.header.decode_header(str(ls[0]).strip('\"')) sender = fromname[0][0] elif(len(ls) > 2): fromname = email.header.decode_header(str(fromstr[:fromstr.find('<')]) .strip('\"')) sender = fromname[0][0] else: sender = msg['From'] if isinstance(sender, bytes): try: return sender.decode('utf-8') except UnicodeDecodeError: return sender.decode('gbk') else: return sender
[文档] def isSelfEmail(self, msg): """ Whether the email is sent by the user """ fromstr = str(msg["From"]) addr = (fromstr[fromstr.find('<')+1:fromstr.find('>')]).strip('\"') address = config.get()[self.SLUG]['address'].strip() return addr == address
[文档] def getSubject(self, msg): """ Returns the title of an email Arguments: msg -- the email Returns: Title of the email. """ subject = email.header.decode_header(msg['subject']) if isinstance(subject[0][0], bytes): try: sub = subject[0][0].decode('utf-8') except UnicodeDecodeError: sub = subject[0][0].decode('gbk') else: sub = subject[0][0] to_read = False if sub.strip() == '': return '' to_read = config.get('/email/read_email_title', True) if to_read: return '邮件标题为 %s' % sub return ''
[文档] def isNewEmail(msg): """ Wether an email is a new email """ date = str(msg['Date']) dtext = date.split(',')[1].split('+')[0].strip() dtime = time.strptime(dtext, '%d %b %Y %H:%M:%S') current = time.localtime() dt = datetime.datetime(*dtime[:6]) cr = datetime.datetime(*current[:6]) return (cr - dt).days == 0
[文档] def getDate(self, email): return parser.parse(email.get('date'))
[文档] def getMostRecentDate(self, emails): """ Returns the most recent date of any email in the list provided. Arguments: emails -- a list of emails to check Returns: Date of the most recent email. """ dates = [self.getDate(e) for e in emails] dates.sort(reverse=True) if dates: return dates[0] return None
[文档] def fetchUnreadEmails(self, since=None, markRead=False, limit=None): """ Fetches a list of unread email objects from a user's email inbox. Arguments: since -- if provided, no emails before this date will be returned markRead -- if True, marks all returned emails as read in target inbox Returns: A list of unread email objects. """ logger = logging.getLogger(__name__) profile = config.get() conn = imaplib.IMAP4(profile[self.SLUG]['imap_server'], profile[self.SLUG]['imap_port']) conn.debug = 0 msgs = [] try: conn.login(profile[self.SLUG]['address'], profile[self.SLUG]['password']) conn.select(readonly=(not markRead)) (retcode, messages) = conn.search(None, '(UNSEEN)') except Exception: logger.warning("抱歉,您的邮箱账户验证失败了,请检查下配置") return None if retcode == 'OK' and messages != [b'']: numUnread = len(messages[0].split(b' ')) if limit and numUnread > limit: return numUnread for num in messages[0].split(b' '): # parse email RFC822 format ret, data = conn.fetch(num, '(RFC822)') if data is None: continue msg = email.message_from_string(data[0][1].decode('utf-8')) if not since or self.getDate(msg) > since: msgs.append(msg) conn.close() conn.logout() return msgs
[文档] def handle(self, text, parsed): msgs = self.fetchUnreadEmails(limit=5) if msgs is None: self.say( u"抱歉,您的邮箱账户验证失败了", cache=True) return if isinstance(msgs, int): response = "您有 %d 封未读邮件" % msgs self.say(response, cache=True) return senders = [str(self.getSender(e)) for e in msgs] if not senders: self.say(u"您没有未读邮件,真棒!", cache=True) elif len(senders) == 1: self.say(u"您有来自 {} 的未读邮件。{}".format(senders[0], self.getSubject(msgs[0]))) else: response = u"您有 %d 封未读邮件" % len( senders) unique_senders = list(set(senders)) if len(unique_senders) > 1: unique_senders[-1] = ', ' + unique_senders[-1] response += "。这些邮件的发件人包括:" response += ' 和 '.join(senders) else: response += ",邮件都来自 " + unique_senders[0] self.say(response)
[文档] def isValid(self, text, parsed): return any(word in text for word in [u'邮箱', u'邮件'])
================================================ FILE: docs/_modules/plugins/Geek.html ================================================ plugins.Geek — wukong-robot 1.2.0 文档

plugins.Geek 源代码

# -*- coding: utf-8-*-
from robot import logging
from robot.sdk.AbstractPlugin import AbstractPlugin

logger = logging.getLogger(__name__)

[文档]class Plugin(AbstractPlugin): IS_IMMERSIVE = True # 这是个沉浸式技能 def __init__(self, con): super(Plugin, self).__init__(con) self.silent_count = 0
[文档] def handle(self, text, parsed): if any (word in text for word in ['开启', '激活', '开始', '进入', '打开']): self.silent_count = 0 self.say('进入极客模式', cache=True, onCompleted=lambda: self.onAsk(self.activeListen(silent=True))) else: self.say('退出极客模式', cache=True)
[文档] def onAsk(self, input): if input: logger.debug('input: {}'.format(input)) self.silent_count = 0 self.con.doResponse(input) else: self.silent_count += 1 if self.silent_count >= 5: self.say('退出极客模式', cache=True) self.clearImmersive() else: self.onAsk(self.activeListen(silent=True))
[文档] def restore(self): logger.debug('restore') self.onAsk(self.activeListen(silent=True))
[文档] def isValidImmersive(self, text, parsed): return '模式' in text and \ any(word in text for word in ['即刻', '即可', '极客', '即客', '集团', '集客']) and \ any(word in text for word in ['退出', '结束', '停止'])
[文档] def isValid(self, text, parsed): return '模式' in text and \ any(word in text for word in ['即刻', '即可', '即客', '集团', '极客', '集客']) and \ any (word in text for word in ['开启', '激活', '开始', '进入', '打开'])
================================================ FILE: docs/_modules/plugins/LocalPlayer.html ================================================ plugins.LocalPlayer — wukong-robot 1.2.0 文档

plugins.LocalPlayer 源代码

# -*- coding: utf-8-*-
import os
from robot import config, logging
from robot.Player import MusicPlayer
from robot.sdk.AbstractPlugin import AbstractPlugin

logger = logging.getLogger(__name__)

[文档]class Plugin(AbstractPlugin): IS_IMMERSIVE = True # 这是个沉浸式技能 def __init__(self, con): super(Plugin, self).__init__(con) self.player = None self.song_list = None
[文档] def get_song_list(self, path): if not os.path.exists(path) or \ not os.path.isdir(path): return [] song_list = list(filter(lambda d: d.endswith('.mp3'), os.listdir(path))) return [os.path.join(path, song) for song in song_list]
[文档] def init_music_player(self): self.song_list = self.get_song_list(config.get('/LocalPlayer/path')) if self.song_list == None: logger.error('{} 插件配置有误'.format(self.SLUG)) logger.info('本地音乐列表:{}'.format(self.song_list)) return MusicPlayer(self.song_list, self)
[文档] def handle(self, text, parsed): if not self.player: self.player = self.init_music_player() if len(self.song_list) == 0: self.clearImmersive() # 去掉沉浸式 self.say('本地音乐目录并没有音乐文件,播放失败') return if self.nlu.hasIntent(parsed, 'MUSICRANK'): self.player.play() elif self.nlu.hasIntent(parsed, 'CHANGE_TO_NEXT'): self.player.next() elif self.nlu.hasIntent(parsed, 'CHANGE_TO_LAST'): self.player.prev() elif self.nlu.hasIntent(parsed, 'CHANGE_VOL'): slots = self.nlu.getSlots(parsed, 'CHANGE_VOL') for slot in slots: if slot['name'] == 'user_d': word = self.nlu.getSlotWords(parsed, 'CHANGE_VOL', 'user_d')[0] if word == '--HIGHER--': self.player.turnUp() else: self.player.turnDown() return elif slot['name'] == 'user_vd': word = self.nlu.getSlotWords(parsed, 'CHANGE_VOL', 'user_vd')[0] if word == '--LOUDER--': self.player.turnUp() else: self.player.turnDown() elif self.nlu.hasIntent(parsed, 'PAUSE'): self.player.pause() elif self.nlu.hasIntent(parsed, 'CONTINUE'): self.player.resume() elif self.nlu.hasIntent(parsed, 'CLOSE_MUSIC'): self.player.stop() self.clearImmersive() # 去掉沉浸式 else: self.say('没听懂你的意思呢,要停止播放,请说停止播放', wait=True) self.player.resume()
[文档] def pause(self): self.player.stop()
[文档] def restore(self): if self.player and not self.player.is_pausing(): self.player.resume()
[文档] def isValidImmersive(self, text, parsed): return any(self.nlu.hasIntent(parsed, intent) for intent in ['CHANGE_TO_LAST', 'CHANGE_TO_NEXT', 'CHANGE_VOL', 'CLOSE_MUSIC', 'PAUSE', 'CONTINUE'])
[文档] def isValid(self, text, parsed): return "本地音乐" in text
================================================ FILE: docs/_modules/plugins/Poem.html ================================================ plugins.Poem — wukong-robot 1.2.0 文档

plugins.Poem 源代码

# -*- coding: utf-8-*-
# author: wzpan
# 写诗

import logging
from robot.sdk.AbstractPlugin import AbstractPlugin

INTENT = "BUILT_POEM"

logger = logging.getLogger(__name__)

[文档]class Plugin(AbstractPlugin): SLUG = "poem"
[文档] def handle(self, text, parsed): try: responds = self.nlu.getSay(parsed, INTENT) self.say(responds, cache=True) except Exception as e: logger.error(e) self.say('抱歉,写诗插件出问题了,请稍后再试', cache=True)
[文档] def isValid(self, text, parsed): return self.nlu.hasIntent(parsed, INTENT) and '写' in text and '诗' in text
================================================ FILE: docs/_modules/robot/AI.html ================================================ robot.AI — wukong-robot 1.2.0 文档

robot.AI 源代码

# -*- coding: utf-8-*-
import requests
import json
from robot import logging
from robot import config
from uuid import getnode as get_mac
from abc import ABCMeta, abstractmethod

logger = logging.getLogger(__name__)

[文档]class AbstractRobot(object): __metaclass__ = ABCMeta
[文档] @classmethod def get_instance(cls): profile = cls.get_config() instance = cls(**profile) return instance
def __init__(self, **kwargs): pass
[文档] @abstractmethod def chat(self, texts): pass
[文档]class TulingRobot(AbstractRobot): SLUG = "tuling" def __init__(self, tuling_key): """ 图灵机器人 """ super(self.__class__, self).__init__() self.tuling_key = tuling_key
[文档] @classmethod def get_config(cls): # Try to get ali_yuyin config from config return config.get('tuling', {})
[文档] def chat(self, texts): """ 使用图灵机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = ''.join(texts) try: url = "http://www.tuling123.com/openapi/api" userid = str(get_mac())[:32] body = {'key': self.tuling_key, 'info': msg, 'userid': userid} r = requests.post(url, data=body) respond = json.loads(r.text) result = '' if respond['code'] == 100000: result = respond['text'].replace('<br>', ' ') result = result.replace(u'\xa0', u' ') elif respond['code'] == 200000: result = respond['url'] elif respond['code'] == 302000: for k in respond['list']: result = result + u"【" + k['source'] + u"】 " +\ k['article'] + "\t" + k['detailurl'] + "\n" else: result = respond['text'].replace('<br>', ' ') result = result.replace(u'\xa0', u' ') logger.info('{} 回答:{}'.format(self.SLUG, result)) return result except Exception: logger.critical("Tuling robot failed to responsed for %r", msg, exc_info=True) return "抱歉, 我的大脑短路了,请稍后再试试."
[文档]class Emotibot(AbstractRobot): SLUG = "emotibot" def __init__(self, appid, location, more): """ Emotibot机器人 """ super(self.__class__, self).__init__() self.appid, self.location, self.more = appid, location, more
[文档] @classmethod def get_config(self): appid = config.get('/emotibot/appid', '') location = config.get('location', '深圳') more = config.get('active_mode', False) return { 'appid': appid, 'location': location, 'more': more }
[文档] def chat(self, texts): """ 使用Emotibot机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = ''.join(texts) try: url = "http://idc.emotibot.com/api/ApiKey/openapi.php" userid = str(get_mac())[:32] register_data = { "cmd": "chat", "appid": self.appid, "userid": userid, "text": msg, "location": self.location } r = requests.post(url, params=register_data) jsondata = json.loads(r.text) result = '' responds = [] if jsondata['return'] == 0: if self.more: datas = jsondata.get('data') for data in datas: if data.get('type') == 'text': responds.append(data.get('value')) else: responds.append(jsondata.get('data')[0].get('value')) result = '\n'.join(responds) else: result = "抱歉, 我的大脑短路了,请稍后再试试." logger.info('{} 回答:{}'.format(self.SLUG, result)) return result except Exception: logger.critical("Emotibot failed to responsed for %r", msg, exc_info=True) return "抱歉, 我的大脑短路了,请稍后再试试."
[文档]def get_robot_by_slug(slug): """ Returns: A robot implementation available on the current platform """ if not slug or type(slug) is not str: raise TypeError("Invalid slug '%s'", slug) selected_robots = list(filter(lambda robot: hasattr(robot, "SLUG") and robot.SLUG == slug, get_robots())) if len(selected_robots) == 0: raise ValueError("No robot found for slug '%s'" % slug) else: if len(selected_robots) > 1: logger.warning("WARNING: Multiple robots found for slug '%s'. " + "This is most certainly a bug." % slug) robot = selected_robots[0] logger.info("使用 {} 对话机器人".format(robot.SLUG)) return robot.get_instance()
[文档]def get_robots(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [robot for robot in list(get_subclasses(AbstractRobot)) if hasattr(robot, 'SLUG') and robot.SLUG]
================================================ FILE: docs/_modules/robot/ASR.html ================================================ robot.ASR — wukong-robot 1.2.0 文档

robot.ASR 源代码

# -*- coding: utf-8-*-
import json
from aip import AipSpeech
from .sdk import TencentSpeech, AliSpeech, XunfeiSpeech
from . import utils, config
from robot import logging
from abc import ABCMeta, abstractmethod

logger = logging.getLogger(__name__)

[文档]class AbstractASR(object): """ Generic parent class for all ASR engines """ __metaclass__ = ABCMeta
[文档] @classmethod def get_config(cls): return {}
[文档] @classmethod def get_instance(cls): profile = cls.get_config() instance = cls(**profile) return instance
[文档] @abstractmethod def transcribe(self, fp): pass
[文档]class BaiduASR(AbstractASR): """ 百度的语音识别API. dev_pid: - 1936: 普通话远场 - 1536:普通话(支持简单的英文识别) - 1537:普通话(纯中文识别) - 1737:英语 - 1637:粤语 - 1837:四川话 要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号, 之后创建一个新应用, 然后在应用管理的"查看key"中获得 API Key 和 Secret Key 填入 config.xml 中. ... baidu_yuyin: appid: '9670645' api_key: 'qg4haN8b2bGvFtCbBGqhrmZy' secret_key: '585d4eccb50d306c401d7df138bb02e7' ... """ SLUG = "baidu-asr" def __init__(self, appid, api_key, secret_key, dev_pid=1936, **args): super(self.__class__, self).__init__() self.client = AipSpeech(appid, api_key, secret_key) self.dev_pid = dev_pid
[文档] @classmethod def get_config(cls): # Try to get baidu_yuyin config from config return config.get('baidu_yuyin', {})
[文档] def transcribe(self, fp): # 识别本地文件 pcm = utils.get_pcm_from_wav(fp) res = self.client.asr(pcm, 'pcm', 16000, { 'dev_pid': self.dev_pid, }) if res['err_no'] == 0: logger.info('{} 语音识别到了:{}'.format(self.SLUG, res['result'])) return ''.join(res['result']) else: logger.info('{} 语音识别出错了: {}'.format(self.SLUG, res['err_msg'])) return ''
[文档]class TencentASR(AbstractASR): """ 腾讯的语音识别API. """ SLUG = "tencent-asr" def __init__(self, appid, secretid, secret_key, region='ap-guangzhou', **args): super(self.__class__, self).__init__() self.engine = TencentSpeech.tencentSpeech(secret_key, secretid) self.region = region
[文档] @classmethod def get_config(cls): # Try to get tencent_yuyin config from config return config.get('tencent_yuyin', {})
[文档] def transcribe(self, fp): mp3_path = utils.convert_wav_to_mp3(fp) r = self.engine.ASR(mp3_path, 'mp3', '1', self.region) utils.check_and_delete(mp3_path) res = json.loads(r) if 'Response' in res and 'Result' in res['Response']: logger.info('{} 语音识别到了:{}'.format(self.SLUG, res['Response']['Result'])) return res['Response']['Result'] else: logger.critical('{} 语音识别出错了'.format(self.SLUG), exc_info=True) return ''
[文档]class XunfeiASR(AbstractASR): """ 科大讯飞的语音识别API. 外网ip查询:https://ip.51240.com/ """ SLUG = "xunfei-asr" def __init__(self, appid, asr_api_key, asr_api_secret, tts_api_key, voice='xiaoyan'): super(self.__class__, self).__init__() self.appid = appid self.api_key = asr_api_key self.api_secret = asr_api_secret
[文档] @classmethod def get_config(cls): # Try to get xunfei_yuyin config from config return config.get('xunfei_yuyin', {})
[文档] def transcribe(self, fp): return XunfeiSpeech.transcribe(fp, self.appid, self.api_key, self.api_secret)
[文档]class AliASR(AbstractASR): """ 阿里的语音识别API. """ SLUG = "ali-asr" def __init__(self, appKey, token, **args): super(self.__class__, self).__init__() self.appKey, self.token = appKey, token
[文档] @classmethod def get_config(cls): # Try to get ali_yuyin config from config return config.get('ali_yuyin', {})
[文档] def transcribe(self, fp): result = AliSpeech.asr(self.appKey, self.token, fp) if result is not None: logger.info('{} 语音识别到了:{}'.format(self.SLUG, result)) return result else: logger.critical('{} 语音识别出错了'.format(self.SLUG), exc_info=True) return ''
[文档]def get_engine_by_slug(slug=None): """ Returns: An ASR Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError("无效的 ASR slug '%s'", slug) selected_engines = list(filter(lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines())) if len(selected_engines) == 0: raise ValueError("错误:找不到名为 {} 的 ASR 引擎".format(slug)) else: if len(selected_engines) > 1: logger.warning("注意: 有多个 ASR 名称与指定的引擎名 {} 匹配").format(slug) engine = selected_engines[0] logger.info("使用 {} ASR 引擎".format(engine.SLUG)) return engine.get_instance()
[文档]def get_engines(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [engine for engine in list(get_subclasses(AbstractASR)) if hasattr(engine, 'SLUG') and engine.SLUG]
================================================ FILE: docs/_modules/robot/Brain.html ================================================ robot.Brain — wukong-robot 1.2.0 文档

robot.Brain 源代码

# -*- coding: utf-8-*-
from robot import logging
from . import plugin_loader

logger = logging.getLogger(__name__)

[文档]class Brain(object): def __init__(self, conversation): """ 大脑模块,负责处理技能的匹配和响应 参数: conversation -- 管理对话 """ self.conversation = conversation self.plugins = plugin_loader.get_plugins(self.conversation) self.handling = False
[文档] def isImmersive(self, plugin, text, parsed): return self.conversation.getImmersiveMode() == plugin.SLUG and \ plugin.isValidImmersive(text, parsed)
[文档] def printPlugins(self): plugin_list = [] for plugin in self.plugins: plugin_list.append(plugin.SLUG) logger.info('已激活插件:{}'.format(plugin_list))
[文档] def query(self, text): """ query 模块 Arguments: text -- 用户输入 """ args = { "service_id": "S13442", "api_key": 'w5v7gUV3iPGsGntcM84PtOOM', "secret_key": 'KffXwW6E1alcGplcabcNs63Li6GvvnfL' } parsed = self.conversation.doParse(text, **args) for plugin in self.plugins: if not plugin.isValid(text, parsed) and not self.isImmersive(plugin, text, parsed): continue logger.info("'{}' 命中技能 {}".format(text, plugin.SLUG)) self.conversation.matchPlugin = plugin.SLUG if plugin.IS_IMMERSIVE: self.conversation.setImmersiveMode(plugin.SLUG) continueHandle = False try: self.handling = True continueHandle = plugin.handle(text, parsed) self.handling = False except Exception: logger.critical('Failed to execute plugin', exc_info=True) reply = u"抱歉,插件{}出故障了,晚点再试试吧".format(plugin.SLUG) self.conversation.say(reply, plugin=plugin.SLUG) else: logger.debug("Handling of phrase '%s' by " + "plugin '%s' completed", text, plugin.SLUG) finally: if not continueHandle: return True logger.debug("No plugin was able to handle phrase {} ".format(text)) return False
[文档] def restore(self): """ 恢复某个技能的处理 """ if not self.conversation.immersiveMode: return for plugin in self.plugins: if plugin.SLUG == self.conversation.immersiveMode and plugin.restore: plugin.restore()
[文档] def pause(self): """ 暂停某个技能的处理 """ if not self.conversation.immersiveMode: return for plugin in self.plugins: if plugin.SLUG == self.conversation.immersiveMode and plugin.pause: plugin.pause()
[文档] def understand(self, fp): if self.conversation and self.conversation.asr: return self.conversation.asr.transcribe(fp) return None
[文档] def say(self, msg, cache=False): if self.conversation and self.conversation.tts: self.conversation.tts.say(msg, cache)
================================================ FILE: docs/_modules/robot/ConfigMonitor.html ================================================ robot.ConfigMonitor — wukong-robot 1.2.0 文档

robot.ConfigMonitor 源代码

# -*- coding: utf-8-*-

from robot import config
from watchdog.events import FileSystemEventHandler

[文档]class ConfigMonitor(FileSystemEventHandler): def __init__(self, conversation): FileSystemEventHandler.__init__(self) self._conversation = conversation # 文件修改
[文档] def on_modified(self, event): if not event.is_directory: config.reload() self._conversation.reload()
================================================ FILE: docs/_modules/robot/Conversation.html ================================================ robot.Conversation — wukong-robot 1.2.0 文档

robot.Conversation 源代码

# -*- coding: utf-8-*-
import time 
import uuid
import cProfile
import pstats
import io
import re
import os
from robot.Brain import Brain
from snowboy import snowboydecoder
from robot import logging, ASR, TTS, NLU, AI, Player, config, constants, utils, statistic


logger = logging.getLogger(__name__)

[文档]class Conversation(object): def __init__(self, profiling=False): self.reload() # 历史会话消息 self.history = [] # 沉浸模式,处于这个模式下,被打断后将自动恢复这个技能 self.matchPlugin = None self.immersiveMode = None self.isRecording = False self.profiling = profiling self.onSay = None self.hasPardon = False
[文档] def getHistory(self): return self.history
[文档] def interrupt(self): if self.player is not None and self.player.is_playing(): self.player.stop() self.player = None if self.immersiveMode: self.brain.pause()
[文档] def reload(self): """ 重新初始化 """ try: self.asr = ASR.get_engine_by_slug(config.get('asr_engine', 'tencent-asr')) self.ai = AI.get_robot_by_slug(config.get('robot', 'tuling')) self.tts = TTS.get_engine_by_slug(config.get('tts_engine', 'baidu-tts')) self.nlu = NLU.get_engine_by_slug(config.get('nlu_engine', 'unit')) self.player = None self.brain = Brain(self) self.brain.printPlugins() except Exception as e: logger.critical("对话初始化失败:{}".format(e))
[文档] def checkRestore(self): if self.immersiveMode: self.brain.restore()
[文档] def doResponse(self, query, UUID='', onSay=None): statistic.report(1) self.interrupt() self.appendHistory(0, query, UUID) if onSay: self.onSay = onSay if query.strip() == '': self.pardon() return lastImmersiveMode = self.immersiveMode if not self.brain.query(query): # 没命中技能,使用机器人回复 msg = self.ai.chat(query) self.say(msg, True, onCompleted=self.checkRestore) else: if lastImmersiveMode is not None and lastImmersiveMode != self.matchPlugin: time.sleep(1) if self.player is not None and self.player.is_playing(): logger.debug('等说完再checkRestore') self.player.appendOnCompleted(lambda: self.checkRestore()) else: logger.debug('checkRestore') self.checkRestore()
[文档] def doParse(self, query, **args): return self.nlu.parse(query, **args)
[文档] def setImmersiveMode(self, slug): self.immersiveMode = slug
[文档] def getImmersiveMode(self): return self.immersiveMode
[文档] def converse(self, fp, callback=None): """ 核心对话逻辑 """ Player.play(constants.getData('beep_lo.wav')) logger.info('结束录音') self.isRecording = False if self.profiling: logger.info('性能调试已打开') pr = cProfile.Profile() pr.enable() self.doConverse(fp, callback) pr.disable() s = io.StringIO() sortby = 'cumulative' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print(s.getvalue()) else: self.doConverse(fp, callback)
[文档] def doConverse(self, fp, callback=None, onSay=None): try: self.interrupt() query = self.asr.transcribe(fp) utils.check_and_delete(fp) self.doResponse(query, callback, onSay) except Exception as e: logger.critical(e) utils.clean()
[文档] def appendHistory(self, t, text, UUID=''): """ 将会话历史加进历史记录 """ if t in (0, 1) and text is not None and text != '': if text.endswith(',') or text.endswith(','): text = text[:-1] if UUID == '' or UUID == None or UUID == 'null': UUID = str(uuid.uuid1()) # 将图片处理成HTML pattern = r'https?://.+\.(?:png|jpg|jpeg|bmp|gif|JPG|PNG|JPEG|BMP|GIF)' url_pattern = r'^https?://.+' imgs = re.findall(pattern, text) for img in imgs: text = text.replace(img, '<img src={} class="img"/>'.format(img)) urls = re.findall(url_pattern, text) for url in urls: text = text.replace(url, '<a href={} target="_blank">{}</a>'.format(url, url)) self.history.append({'type': t, 'text': text, 'time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), 'uuid': UUID})
def _onCompleted(self, msg): if config.get('active_mode', False) and \ ( msg.endswith('?') or msg.endswith(u'?') or u'告诉我' in msg or u'请回答' in msg ): query = self.activeListen() self.doResponse(query)
[文档] def pardon(self): if not self.hasPardon: self.say("抱歉,刚刚没听清,能再说一遍吗?", onCompleted=lambda: self.doResponse(self.activeListen())) self.hasPardon = True else: self.say("没听清呢") self.hasPardon = False
[文档] def say(self, msg, cache=False, plugin='', onCompleted=None, wait=False): """ 说一句话 :param msg: 内容 :param cache: 是否缓存这句话的音频 :param plugin: 来自哪个插件的消息(将带上插件的说明) :param onCompleted: 完成的回调 :param wait: 是否要等待说完(为True将阻塞主线程直至说完这句话) """ if plugin != '': self.appendHistory(1, "[{}] {}".format(plugin, msg)) else: self.appendHistory(1, msg) pattern = r'^https?://.+' if re.match(pattern, msg): logger.info("内容包含URL,所以不读出来") return voice = '' cache_path = '' if utils.getCache(msg): logger.info("命中缓存,播放缓存语音") voice = utils.getCache(msg) cache_path = utils.getCache(msg) else: try: voice = self.tts.get_speech(msg) cache_path = utils.saveCache(voice, msg) except Exception as e: logger.error('保存缓存失败:{}'.format(e)) if self.onSay: logger.info(cache) audio = 'http://{}:{}/audio/{}'.format(config.get('/server/host'), config.get('/server/port'), os.path.basename(cache_path)) logger.info('onSay: {}, {}'.format(msg, audio)) if plugin != '': self.onSay("[{}] {}".format(plugin, msg), audio) else: self.onSay(msg, audio) self.onSay = None if onCompleted is None: onCompleted = lambda: self._onCompleted(msg) self.player = Player.SoxPlayer() self.player.play(voice, not cache, onCompleted, wait) if not cache: utils.check_and_delete(cache_path, 60) # 60秒后将自动清理不缓存的音频 utils.lruCache() # 清理缓存
[文档] def activeListen(self, silent=False): """ 主动问一个问题(适用于多轮对话) """ logger.debug('activeListen') try: if not silent: time.sleep(1) Player.play(constants.getData('beep_hi.wav')) listener = snowboydecoder.ActiveListener([constants.getHotwordModel(config.get('hotword', 'wukong.pmdl'))]) voice = listener.listen( silent_count_threshold=config.get('silent_threshold', 15), recording_timeout=config.get('recording_timeout', 5) * 4 ) if not silent: Player.play(constants.getData('beep_lo.wav')) if voice: query = self.asr.transcribe(voice) utils.check_and_delete(voice) return query return '' except Exception as e: logger.error(e) return ''
[文档] def play(self, src, delete=False, onCompleted=None, volume=1): """ 播放一个音频 """ if self.player: self.interrupt() self.player = Player.SoxPlayer() self.player.play(src, delete, onCompleted=onCompleted, volume=volume)
================================================ FILE: docs/_modules/robot/NLU.html ================================================ robot.NLU — wukong-robot 1.2.0 文档

robot.NLU 源代码

# -*- coding: utf-8-*-
from .sdk import unit
from robot import logging
from abc import ABCMeta, abstractmethod

logger = logging.getLogger(__name__)

[文档]class AbstractNLU(object): """ Generic parent class for all NLU engines """ __metaclass__ = ABCMeta
[文档] @classmethod def get_config(cls): return {}
[文档] @classmethod def get_instance(cls): profile = cls.get_config() instance = cls(**profile) return instance
[文档] @abstractmethod def parse(self, query, **args): """ 进行 NLU 解析 :param query: 用户的指令字符串 :param **args: 可选的参数 """ return None
[文档] @abstractmethod def getIntent(self, parsed): """ 提取意图 :param parsed: 解析结果 :returns: 意图数组 """ return None
[文档] @abstractmethod def hasIntent(self, parsed, intent): """ 判断是否包含某个意图 :param parsed: 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含 """ return False
[文档] @abstractmethod def getSlots(self, parsed, intent): """ 提取某个意图的所有词槽 :param parsed: 解析结果 :param intent: 意图的名称 :returns: 词槽列表。你可以通过 name 属性筛选词槽, 再通过 normalized_word 属性取出相应的值 """ return None
[文档] @abstractmethod def getSlotWords(self, parsed, intent, name): """ 找出命中某个词槽的内容 :param parsed: 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ return None
[文档] @abstractmethod def getSay(self, parsed, intent): """ 提取回复文本 :param parsed: 解析结果 :param intent: 意图的名称 :returns: 回复文本 """ return ""
[文档]class UnitNLU(AbstractNLU): """ 百度UNIT的NLU API. """ SLUG = "unit" def __init__(self): super(self.__class__, self).__init__()
[文档] @classmethod def get_config(cls): """ 百度UNIT的配置 无需配置,所以返回 {} """ return {}
[文档] def parse(self, query, **args): """ 使用百度 UNIT 进行 NLU 解析 :param query: 用户的指令字符串 :param **args: UNIT 的相关参数 - service_id: UNIT 的 service_id - api_key: UNIT apk_key - secret_key: UNIT secret_key :returns: UNIT 解析结果。如果解析失败,返回 None """ if 'service_id' not in args or \ 'api_key' not in args or \ 'secret_key' not in args: logger.critical('{} NLU 失败:参数错误!'.format(self.SLUG)) return None return unit.getUnit(query, args['service_id'], args['api_key'], args['secret_key'])
[文档] def getIntent(self, parsed): """ 提取意图 :param parsed: 解析结果 :returns: 意图数组 """ return unit.getIntent(parsed)
[文档] def hasIntent(self, parsed, intent): """ 判断是否包含某个意图 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含 """ return unit.hasIntent(parsed, intent)
[文档] def getSlots(self, parsed, intent): """ 提取某个意图的所有词槽 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: 词槽列表。你可以通过 name 属性筛选词槽, 再通过 normalized_word 属性取出相应的值 """ return unit.getSlots(parsed, intent)
[文档] def getSlotWords(self, parsed, intent, name): """ 找出命中某个词槽的内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ return unit.getSlotWords(parsed, intent, name)
[文档] def getSay(self, parsed, intent): """ 提取 UNIT 的回复文本 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: UNIT 的回复文本 """ return unit.getSay(parsed, intent)
[文档]def get_engine_by_slug(slug=None): """ Returns: An NLU Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError("无效的 NLU slug '%s'", slug) selected_engines = list(filter(lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines())) if len(selected_engines) == 0: raise ValueError("错误:找不到名为 {} 的 NLU 引擎".format(slug)) else: if len(selected_engines) > 1: logger.warning("注意: 有多个 NLU 名称与指定的引擎名 {} 匹配").format(slug) engine = selected_engines[0] logger.info("使用 {} NLU 引擎".format(engine.SLUG)) return engine.get_instance()
[文档]def get_engines(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [engine for engine in list(get_subclasses(AbstractNLU)) if hasattr(engine, 'SLUG') and engine.SLUG]
================================================ FILE: docs/_modules/robot/Player.html ================================================ robot.Player — wukong-robot 1.2.0 文档

robot.Player 源代码

# -*- coding: utf-8-*-
import subprocess
import os
import platform
from . import utils
import _thread as thread
from robot import logging
from ctypes import CFUNCTYPE, c_char_p, c_int, cdll
from contextlib import contextmanager

logger = logging.getLogger(__name__)

[文档]def py_error_handler(filename, line, function, err, fmt): pass
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p) c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
[文档]@contextmanager def no_alsa_error(): try: asound = cdll.LoadLibrary('libasound.so') asound.snd_lib_error_set_handler(c_error_handler) yield asound.snd_lib_error_set_handler(None) except: yield pass
[文档]def play(fname, onCompleted=None): player = getPlayerByFileName(fname) player.play(fname, onCompleted)
[文档]def getPlayerByFileName(fname): foo, ext = os.path.splitext(fname) if ext in ['.mp3', '.wav']: return SoxPlayer()
[文档]class AbstractPlayer(object): def __init__(self, **kwargs): super(AbstractPlayer, self).__init__()
[文档] def play(self): pass
[文档] def play_block(self): pass
[文档] def stop(self): pass
[文档] def is_playing(self): return False
[文档]class SoxPlayer(AbstractPlayer): SLUG = 'SoxPlayer' def __init__(self, **kwargs): super(SoxPlayer, self).__init__(**kwargs) self.playing = False self.proc = None self.delete = False self.onCompleteds = []
[文档] def doPlay(self): cmd = ['play', str(self.src)] logger.debug('Executing %s', ' '.join(cmd)) self.proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) self.playing = True self.proc.wait() self.playing = False if self.delete: utils.check_and_delete(self.src) logger.debug('play completed') if self.proc.returncode == 0: for onCompleted in self.onCompleteds: if onCompleted: onCompleted() self.onCompleteds = []
[文档] def play(self, src, delete=False, onCompleted=None, wait=False): if (os.path.exists(src)): self.src = src self.delete = delete self.onCompleteds.append(onCompleted) if not wait: thread.start_new_thread(self.doPlay, ()) else: self.doPlay() else: logger.critical('path not exists: {}'.format(src))
[文档] def appendOnCompleted(self, onCompleted): if onCompleted: self.onCompleteds.append(onCompleted)
[文档] def play_block(self): self.run()
[文档] def stop(self): if self.proc: self.onCompleteds = [] self.proc.terminate() if self.delete: utils.check_and_delete(self.src)
[文档] def is_playing(self): return self.playing
[文档]class MusicPlayer(SoxPlayer): """ 给音乐播放器插件使用的, 在 SOXPlayer 的基础上增加了列表的支持, 并支持暂停和恢复播放 """ SLUG = 'MusicPlayer' def __init__(self, playlist, plugin, **kwargs): super(MusicPlayer, self).__init__(**kwargs) self.playlist = playlist self.plugin = plugin self.idx = 0 self.pausing = False self.last_paused = None
[文档] def update_playlist(self, playlist): super().stop() self.playlist = playlist self.idx = 0 self.play()
[文档] def play(self): logger.debug('MusicPlayer play') path = self.playlist[self.idx] super().stop() super().play(path, False, self.next)
[文档] def next(self): logger.debug('MusicPlayer next') super().stop() self.idx = (self.idx+1) % len(self.playlist) self.play()
[文档] def prev(self): logger.debug('MusicPlayer prev') super().stop() self.idx = (self.idx-1) % len(self.playlist) self.play()
[文档] def pause(self): logger.debug('MusicPlayer pause') self.pausing = True
[文档] def stop(self): if self.proc: logger.debug('MusicPlayer stop') # STOP current play process self.last_paused = utils.write_temp_file(str(self.proc.pid), 'pid', 'w') self.onCompleteds = [] subprocess.run(['pkill', '-STOP', '-F', self.last_paused])
[文档] def resume(self): logger.debug('MusicPlayer resume') self.pausing = False self.onCompleteds = [self.next] if self.last_paused is not None: print(self.last_paused) subprocess.run(['pkill', '-CONT', '-F', self.last_paused])
[文档] def is_playing(self): return self.playing
[文档] def is_pausing(self): return self.pausing
[文档] def turnUp(self): system = platform.system() if system == 'Darwin': res = subprocess.run(['osascript', '-e', 'output volume of (get volume settings)'], shell=False, capture_output=True, text=True) volume = int(res.stdout.strip()) volume += 20 if volume >= 100: volume = 100 self.plugin.say('音量已经最大啦', wait=True) subprocess.run(['osascript', '-e', 'set volume output volume {}'.format(volume)]) elif system == 'Linux': res = subprocess.run(["amixer sget Master | grep 'Mono:' | awk -F'[][]' '{ print $2 }'"], shell=True, capture_output=True, text=True) print(res.stdout) if res.stdout != '' and res.stdout.strip().endswith('%'): volume = int(res.stdout.strip().replace('%', '')) volume += 20 if volume >= 100: volume = 100 self.plugin.say('音量已经最大啦', wait=True) subprocess.run(['amixer', 'set', 'Master', '{}%'.format(volume)]) else: subprocess.run(['amixer', 'set', 'Master', '20%+']) else: self.plugin.say('当前系统不支持调节音量') self.resume()
[文档] def turnDown(self): system = platform.system() if system == 'Darwin': res = subprocess.run(['osascript', '-e', 'output volume of (get volume settings)'], shell=False, capture_output=True, text=True) volume = int(res.stdout.strip()) volume -= 20 if volume <= 20: volume = 20 self.plugin.say('音量已经很小啦', wait=True) subprocess.run(['osascript', '-e', 'set volume output volume {}'.format(volume)]) elif system == 'Linux': res = subprocess.run(["amixer sget Master | grep 'Mono:' | awk -F'[][]' '{ print $2 }'"], shell=True, capture_output=True, text=True) if res.stdout != '' and res.stdout.endswith('%'): volume = int(res.stdout.replace('%', '').strip()) volume -= 20 if volume <= 20: volume = 20 self.plugin.say('音量已经最小啦', wait=True) subprocess.run(['amixer', 'set', 'Master', '{}%'.format(volume)]) else: subprocess.run(['amixer', 'set', 'Master', '20%-']) else: self.plugin.say('当前系统不支持调节音量') self.resume()
================================================ FILE: docs/_modules/robot/TTS.html ================================================ robot.TTS — wukong-robot 1.2.0 文档

robot.TTS 源代码

# -*- coding: utf-8-*-
from aip import AipSpeech
from .sdk import TencentSpeech, AliSpeech
from . import utils, config
from robot import logging
import base64
import time
import requests
import hashlib
from abc import ABCMeta, abstractmethod

logger = logging.getLogger(__name__)

[文档]class AbstractTTS(object): """ Generic parent class for all TTS engines """ __metaclass__ = ABCMeta
[文档] @classmethod def get_config(cls): return {}
[文档] @classmethod def get_instance(cls): profile = cls.get_config() instance = cls(**profile) return instance
[文档] @abstractmethod def get_speech(self, phrase): pass
[文档]class BaiduTTS(AbstractTTS): """ 使用百度语音合成技术 要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号, 之后创建一个新应用, 然后在应用管理的"查看key"中获得 API Key 和 Secret Key 填入 config.yml 中. ... baidu_yuyin: appid: '9670645' api_key: 'qg4haN8b2bGvFtCbBGqhrmZy' secret_key: '585d4eccb50d306c401d7df138bb02e7' dev_pid: 1936 per: 1 lan: 'zh' ... """ SLUG = "baidu-tts" def __init__(self, appid, api_key, secret_key, per=1, lan='zh', **args): super(self.__class__, self).__init__() self.client = AipSpeech(appid, api_key, secret_key) self.per, self.lan = str(per), lan
[文档] @classmethod def get_config(cls): # Try to get baidu_yuyin config from config return config.get('baidu_yuyin', {})
[文档] def get_speech(self, phrase): result = self.client.synthesis(phrase, self.lan, 1, {'per': self.per}); # 识别正确返回语音二进制 错误则返回dict 参照下面错误码 if not isinstance(result, dict): tmpfile = utils.write_temp_file(result, '.mp3') logger.info('{} 语音合成成功,合成路径:{}'.format(self.SLUG, tmpfile)) return tmpfile else: logger.critical('{} 合成失败!'.format(self.SLUG), exc_info=True)
[文档]class TencentTTS(AbstractTTS): """ 腾讯的语音合成 region: 服务地域,挑个离自己最近的区域有助于提升速度。 有效值:https://cloud.tencent.com/document/api/441/17365#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 voiceType: - 0:女声1,亲和风格(默认) - 1:男声1,成熟风格 - 2:男声2,成熟风格 language: - 1: 中文,最大100个汉字(标点符号算一个汉子) - 2: 英文,最大支持400个字母(标点符号算一个字母) """ SLUG = "tencent-tts" def __init__(self, appid, secretid, secret_key, region='ap-guangzhou', voiceType=0, language=1, **args): super(self.__class__, self).__init__() self.engine = TencentSpeech.tencentSpeech(secret_key, secretid) self.region, self.voiceType, self.language = region, voiceType, language
[文档] @classmethod def get_config(cls): # Try to get tencent_yuyin config from config return config.get('tencent_yuyin', {})
[文档] def get_speech(self, phrase): result = self.engine.TTS(phrase, self.voiceType, self.language, self.region) if 'Response' in result and 'Audio' in result['Response']: audio = result['Response']['Audio'] data = base64.b64decode(audio) tmpfile = utils.write_temp_file(data, '.wav') logger.info('{} 语音合成成功,合成路径:{}'.format(self.SLUG, tmpfile)) return tmpfile else: logger.critical('{} 合成失败!'.format(self.SLUG), exc_info=True)
[文档]class XunfeiTTS(AbstractTTS): """ 科大讯飞的语音识别API. 外网ip查询:https://ip.51240.com/ voice_name: https://www.xfyun.cn/services/online_tts """ SLUG = "xunfei-tts" def __init__(self, appid, asr_api_key, asr_api_secret, tts_api_key, voice='xiaoyan'): super(self.__class__, self).__init__() self.appid, self.api_key, self.voice_name = appid, tts_api_key, voice
[文档] @classmethod def get_config(cls): # Try to get xunfei_yuyin config from config return config.get('xunfei_yuyin', {})
[文档] def getHeader(self, aue): curTime = str(int(time.time())) # curTime = '1526542623' param = "{\"aue\":\""+aue+"\",\"auf\":\"audio/L16;rate=16000\",\"voice_name\":\"" + self.voice_name + "\",\"engine_type\":\"intp65\"}" logger.debug("param:{}".format(param)) paramBase64 = str(base64.b64encode(param.encode('utf-8')), 'utf-8') logger.debug("x_param:{}".format(paramBase64)) m2 = hashlib.md5() m2.update((self.api_key + curTime + paramBase64).encode('utf-8')) checkSum = m2.hexdigest() header = { 'X-CurTime': curTime, 'X-Param': paramBase64, 'X-Appid': self.appid, 'X-CheckSum': checkSum, 'X-Real-Ip':'127.0.0.1', 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', } return header
[文档] def getBody(self, text): data = {'text':text} return data
[文档] def get_speech(self, phrase): URL = "http://api.xfyun.cn/v1/service/v1/tts" r = requests.post(URL, headers=self.getHeader('lame'), data=self.getBody(phrase)) contentType = r.headers['Content-Type'] if contentType == "audio/mpeg": tmpfile = utils.write_temp_file(r.content, '.mp3') logger.info('{} 语音合成成功,合成路径:{}'.format(self.SLUG, tmpfile)) return tmpfile else : logger.critical('{} 合成失败!{}'.format(self.SLUG, r.text), exc_info=True)
[文档]class AliTTS(AbstractTTS): """ 阿里的TTS voice: 发音人,默认是 xiaoyun 全部发音人列表:https://help.aliyun.com/document_detail/84435.html?spm=a2c4g.11186623.2.24.67ce5275q2RGsT """ SLUG = "ali-tts" def __init__(self, appKey, token, voice='xiaoyun', **args): super(self.__class__, self).__init__() self.appKey, self.token, self.voice = appKey, token, voice
[文档] @classmethod def get_config(cls): # Try to get ali_yuyin config from config return config.get('ali_yuyin', {})
[文档] def get_speech(self, phrase): tmpfile = AliSpeech.tts(self.appKey, self.token, self.voice, phrase) if tmpfile is not None: logger.info('{} 语音合成成功,合成路径:{}'.format(self.SLUG, tmpfile)) return tmpfile else: logger.critical('{} 合成失败!'.format(self.SLUG), exc_info=True)
[文档]def get_engine_by_slug(slug=None): """ Returns: A TTS Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError("无效的 TTS slug '%s'", slug) selected_engines = list(filter(lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines())) if len(selected_engines) == 0: raise ValueError("错误:找不到名为 {} 的 TTS 引擎".format(slug)) else: if len(selected_engines) > 1: logger.warning("注意: 有多个 TTS 名称与指定的引擎名 {} 匹配").format(slug) engine = selected_engines[0] logger.info("使用 {} TTS 引擎".format(engine.SLUG)) return engine.get_instance()
[文档]def get_engines(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [engine for engine in list(get_subclasses(AbstractTTS)) if hasattr(engine, 'SLUG') and engine.SLUG]
================================================ FILE: docs/_modules/robot/Updater.html ================================================ robot.Updater — wukong-robot 1.2.0 文档

robot.Updater 源代码

import os
import requests
import json
import semver
from subprocess import call
from robot import constants, logging
from datetime import datetime, timedelta

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)

_updater = None
URL = 'https://service-e32kknxi-1253537070.ap-hongkong.apigateway.myqcloud.com/release/wukong'
DEV_URL = 'https://service-e32kknxi-1253537070.ap-hongkong.apigateway.myqcloud.com/release/wukong-dev'

[文档]class Updater(object): def __init__(self): self.last_check = datetime.now() - timedelta(days=1.5) self.update_info = {} def _pull(self, cwd, tag): if os.path.exists(cwd): return call(['git checkout master && git pull && git checkout {}'.format(tag, tag, tag)], cwd=cwd, shell=True) == 0 else: logger.error("目录 {} 不存在".format(cwd)) return False def _pip(self, cwd): if os.path.exists(cwd): return call(['pip3', 'install', '-r', 'requirements.txt'], cwd=cwd, shell=False) == 0 else: logger.error("目录 {} 不存在".format(cwd)) return False
[文档] def update(self): update_info = self.fetch() success = True if update_info == {}: logger.info('恭喜你,wukong-robot 已经是最新!') if 'main' in update_info: if self._pull(constants.APP_PATH, update_info['main']['version']) and self._pip(constants.APP_PATH): logger.info('wukong-robot 更新成功!') self.update_info.pop('main') else: logger.info('wukong-robot 更新失败!') success = False if 'contrib' in update_info: if self._pull(constants.CONTRIB_PATH, update_info['contrib']['version']) and self._pip(constants.CONTRIB_PATH): logger.info('wukong-contrib 更新成功!') self.update_info.pop('contrib') else: logger.info('wukong-contrib 更新失败!') success = False return success
def _get_version(self, path, current): if os.path.exists(os.path.join(path, 'VERSION')): with open(os.path.join(path, 'VERSION'), 'r') as f: return f.read().strip() else: return current
[文档] def fetch(self, dev=False): global URL, DEV_URL url = URL if dev: url = DEV_URL now = datetime.now() if (now - self.last_check).seconds <= 1800: logger.debug('30 分钟内已检查过更新,使用上次的检查结果:{}'.format(self.update_info)) return self.update_info try: self.last_check = now r = requests.get(url, timeout=3) info = json.loads(r.text) main_version = info['main']['version'] contrib_version = info['contrib']['version'] # 检查主仓库 current_main_version = self._get_version(constants.APP_PATH, main_version) current_contrib_version = self._get_version(constants.CONTRIB_PATH, contrib_version) if semver.compare(main_version, current_main_version) > 0: logger.info('主仓库检查到更新:{}'.format(info['main'])) self.update_info['main'] = info['main'] if semver.compare(contrib_version, current_contrib_version) > 0: logger.info('插件库检查到更新:{}'.format(info['contrib'])) self.update_info['contrib'] = info['contrib'] if 'notices' in info: self.update_info['notices'] = info['notices'] return self.update_info except Exception as e: logger.error("检查更新失败:", e) return {}
[文档]def fetch(dev): global _updater if not _updater: _updater = Updater() return _updater.fetch(dev)
if __name__ == '__main__': fetch()
================================================ FILE: docs/_modules/robot/config.html ================================================ robot.config — wukong-robot 1.2.0 文档

robot.config 源代码

# -*- coding: utf-8-*-
import yaml
import logging
import os
from . import constants

logger = logging.getLogger(__name__)

_config = {}
has_init = False

[文档]def reload(): """ 重新加载配置 """ logger.info('配置文件发生变更,重新加载配置文件') init()
[文档]def init(): global has_init if os.path.isfile(constants.CONFIG_PATH): logger.critical("错误:{} 应该是个目录,而不应该是个文件".format(constants.CONFIG_PATH)) if not os.path.exists(constants.CONFIG_PATH): os.makedirs(constants.CONFIG_PATH) if not os.path.exists(constants.getConfigPath()): yes_no = input("配置文件{}不存在,要创建吗?(y/n)".format(constants.getConfigPath())) if yes_no.lower() == 'y': constants.newConfig() doInit(constants.getConfigPath()) else: doInit(constants.getDefaultConfigPath()) else: doInit(constants.getConfigPath()) has_init = True
[文档]def doInit(config_file=constants.getDefaultConfigPath()): # Create config dir if it does not exist yet if not os.path.exists(constants.CONFIG_PATH): try: os.makedirs(constants.CONFIG_PATH) except OSError: logger.error("Could not create config dir: '%s'", constants.CONFIG_PATH, exc_info=True) raise # Check if config dir is writable if not os.access(constants.CONFIG_PATH, os.W_OK): logger.critical("Config dir %s is not writable. Dingdang " + "won't work correctly.", constants.CONFIG_PATH) global _config # Read config logger.debug("Trying to read config file: '%s'", config_file) try: with open(config_file, "r") as f: _config = yaml.safe_load(f) except Exception as e: logger.error("配置文件 {} 读取失败: {}".format(config_file, e)) raise
[文档]def get_path(items, default=None): global _config curConfig = _config if isinstance(items, str) and items[0] == '/': items = items.split('/')[1:] for key in items: if key in curConfig: curConfig = curConfig[key] else: logger.warning("/%s not specified in profile, defaulting to " "'%s'", '/'.join(items), default) return default return curConfig
[文档]def has_path(items): global _config curConfig = _config if isinstance(items, str) and items[0] == '/': items = items.split('/')[1:] else: items = [items] for key in items: if key in curConfig: curConfig = curConfig[key] else: return False return True
[文档]def has(item): """ 判断配置里是否包含某个配置项 :param item: 配置项名 :returns: True: 包含; False: 不包含 """ return has_path(item)
[文档]def get(item='', default=None): """ 获取某个配置的值 :param item: 配置项名。如果是多级配置,则以 "/a/b" 的形式提供 :param default: 默认值(可选) :returns: 这个配置的值。如果没有该配置,则提供一个默认值 """ global has_init if not has_init: init() if not item: return _config if item[0] == '/': return get_path(item, default) try: return _config[item] except KeyError: logger.warning("%s not specified in profile, defaulting to '%s'", item, default) return default
[文档]def getConfig(): """ 返回全部配置数据 :returns: 全部配置数据(字典类型) """ return _config
[文档]def getText(): if os.path.exists(constants.getConfigPath()): with open(constants.getConfigPath(), 'r') as f: return f.read() return ''
[文档]def dump(configStr): with open(constants.getConfigPath(), 'w') as f: f.write(configStr)
================================================ FILE: docs/_modules/robot/constants.html ================================================ robot.constants — wukong-robot 1.2.0 文档

robot.constants 源代码

# -*- coding: utf-8-*-
import os
import shutil

# Wukong main directory
APP_PATH = os.path.normpath(os.path.join(
    os.path.dirname(os.path.abspath(__file__)), os.pardir))
 
LIB_PATH = os.path.join(APP_PATH, "robot")
DATA_PATH = os.path.join(APP_PATH, "static")
TEMP_PATH = os.path.join(APP_PATH, "temp")
TEMPLATE_PATH = os.path.join(APP_PATH, "server", "templates")
PLUGIN_PATH = os.path.join(APP_PATH, "plugins")
DEFAULT_CONFIG_NAME = 'default.yml'
CUSTOM_CONFIG_NAME = 'config.yml'

CONFIG_PATH = os.path.expanduser(
    os.getenv('WUKONG_CONFIG', '~/.wukong')
)
CONTRIB_PATH = os.path.expanduser(
    os.getenv('WUKONG_CONFIG', '~/.wukong/contrib')
)
CUSTOM_PATH = os.path.expanduser(
    os.getenv('WUKONG_CONFIG', '~/.wukong/custom')
)

[文档]def getConfigPath(): """ 获取配置文件的路径 returns: 配置文件的存储路径 """ return os.path.join(CONFIG_PATH, CUSTOM_CONFIG_NAME)
[文档]def getConfigData(*fname): """ 获取配置目录下的指定文件的路径 :param *fname: 指定文件名。如果传多个,则自动拼接 :returns: 配置目录下的某个文件的存储路径 """ return os.path.join(CONFIG_PATH, *fname)
[文档]def getData(*fname): """ 获取资源目录下指定文件的路径 :param *fname: 指定文件名。如果传多个,则自动拼接 :returns: 配置文件的存储路径 """ return os.path.join(DATA_PATH, *fname)
[文档]def getDefaultConfigPath(): return getData(DEFAULT_CONFIG_NAME)
[文档]def newConfig(): shutil.copyfile(getDefaultConfigPath(), getConfigPath())
[文档]def getHotwordModel(fname): if os.path.exists(getData(fname)): return getData(fname) else: return getConfigData(fname)
================================================ FILE: docs/_modules/robot/drivers/apa102.html ================================================ robot.drivers.apa102 — wukong-robot 1.2.0 文档

robot.drivers.apa102 源代码

"""
from https://github.com/tinue/APA102_Pi
This is the main driver module for APA102 LEDs
"""
import spidev
from math import ceil

RGB_MAP = { 'rgb': [3, 2, 1], 'rbg': [3, 1, 2], 'grb': [2, 3, 1],
            'gbr': [2, 1, 3], 'brg': [1, 3, 2], 'bgr': [1, 2, 3] }

[文档]class APA102: """ Driver for APA102 LEDS (aka "DotStar"). (c) Martin Erzberger 2016-2017 My very first Python code, so I am sure there is a lot to be optimized ;) Public methods are: - set_pixel - set_pixel_rgb - show - clear_strip - cleanup Helper methods for color manipulation are: - combine_color - wheel The rest of the methods are used internally and should not be used by the user of the library. Very brief overview of APA102: An APA102 LED is addressed with SPI. The bits are shifted in one by one, starting with the least significant bit. An LED usually just forwards everything that is sent to its data-in to data-out. While doing this, it remembers its own color and keeps glowing with that color as long as there is power. An LED can be switched to not forward the data, but instead use the data to change it's own color. This is done by sending (at least) 32 bits of zeroes to data-in. The LED then accepts the next correct 32 bit LED frame (with color information) as its new color setting. After having received the 32 bit color frame, the LED changes color, and then resumes to just copying data-in to data-out. The really clever bit is this: While receiving the 32 bit LED frame, the LED sends zeroes on its data-out line. Because a color frame is 32 bits, the LED sends 32 bits of zeroes to the next LED. As we have seen above, this means that the next LED is now ready to accept a color frame and update its color. So that's really the entire protocol: - Start by sending 32 bits of zeroes. This prepares LED 1 to update its color. - Send color information one by one, starting with the color for LED 1, then LED 2 etc. - Finish off by cycling the clock line a few times to get all data to the very last LED on the strip The last step is necessary, because each LED delays forwarding the data a bit. Imagine ten people in a row. When you yell the last color information, i.e. the one for person ten, to the first person in the line, then you are not finished yet. Person one has to turn around and yell it to person 2, and so on. So it takes ten additional "dummy" cycles until person ten knows the color. When you look closer, you will see that not even person 9 knows its own color yet. This information is still with person 2. Essentially the driver sends additional zeroes to LED 1 as long as it takes for the last color frame to make it down the line to the last LED. """ # Constants MAX_BRIGHTNESS = 31 # Safeguard: Set to a value appropriate for your setup LED_START = 0b11100000 # Three "1" bits, followed by 5 brightness bits def __init__(self, num_led, global_brightness=MAX_BRIGHTNESS, order='rgb', bus=0, device=1, max_speed_hz=8000000): self.num_led = num_led # The number of LEDs in the Strip order = order.lower() self.rgb = RGB_MAP.get(order, RGB_MAP['rgb']) # Limit the brightness to the maximum if it's set higher if global_brightness > self.MAX_BRIGHTNESS: self.global_brightness = self.MAX_BRIGHTNESS else: self.global_brightness = global_brightness self.leds = [self.LED_START,0,0,0] * self.num_led # Pixel buffer self.spi = spidev.SpiDev() # Init the SPI device self.spi.open(bus, device) # Open SPI port 0, slave device (CS) 1 # Up the speed a bit, so that the LEDs are painted faster if max_speed_hz: self.spi.max_speed_hz = max_speed_hz
[文档] def clock_start_frame(self): """Sends a start frame to the LED strip. This method clocks out a start frame, telling the receiving LED that it must update its own color now. """ self.spi.xfer2([0] * 4) # Start frame, 32 zero bits
[文档] def clock_end_frame(self): """Sends an end frame to the LED strip. As explained above, dummy data must be sent after the last real colour information so that all of the data can reach its destination down the line. The delay is not as bad as with the human example above. It is only 1/2 bit per LED. This is because the SPI clock line needs to be inverted. Say a bit is ready on the SPI data line. The sender communicates this by toggling the clock line. The bit is read by the LED and immediately forwarded to the output data line. When the clock goes down again on the input side, the LED will toggle the clock up on the output to tell the next LED that the bit is ready. After one LED the clock is inverted, and after two LEDs it is in sync again, but one cycle behind. Therefore, for every two LEDs, one bit of delay gets accumulated. For 300 LEDs, 150 additional bits must be fed to the input of LED one so that the data can reach the last LED. Ultimately, we need to send additional numLEDs/2 arbitrary data bits, in order to trigger numLEDs/2 additional clock changes. This driver sends zeroes, which has the benefit of getting LED one partially or fully ready for the next update to the strip. An optimized version of the driver could omit the "clockStartFrame" method if enough zeroes have been sent as part of "clockEndFrame". """ # Round up num_led/2 bits (or num_led/16 bytes) for _ in range((self.num_led + 15) // 16): self.spi.xfer2([0x00])
[文档] def clear_strip(self): """ Turns off the strip and shows the result right away.""" for led in range(self.num_led): self.set_pixel(led, 0, 0, 0) self.show()
[文档] def set_pixel(self, led_num, red, green, blue, bright_percent=100): """Sets the color of one pixel in the LED stripe. The changed pixel is not shown yet on the Stripe, it is only written to the pixel buffer. Colors are passed individually. If brightness is not set the global brightness setting is used. """ if led_num < 0: return # Pixel is invisible, so ignore if led_num >= self.num_led: return # again, invisible # Calculate pixel brightness as a percentage of the # defined global_brightness. Round up to nearest integer # as we expect some brightness unless set to 0 brightness = ceil(bright_percent*self.global_brightness/100.0) brightness = int(brightness) # LED startframe is three "1" bits, followed by 5 brightness bits ledstart = (brightness & 0b00011111) | self.LED_START start_index = 4 * led_num self.leds[start_index] = ledstart self.leds[start_index + self.rgb[0]] = red self.leds[start_index + self.rgb[1]] = green self.leds[start_index + self.rgb[2]] = blue
[文档] def set_pixel_rgb(self, led_num, rgb_color, bright_percent=100): """Sets the color of one pixel in the LED stripe. The changed pixel is not shown yet on the Stripe, it is only written to the pixel buffer. Colors are passed combined (3 bytes concatenated) If brightness is not set the global brightness setting is used. """ self.set_pixel(led_num, (rgb_color & 0xFF0000) >> 16, (rgb_color & 0x00FF00) >> 8, rgb_color & 0x0000FF, bright_percent)
[文档] def rotate(self, positions=1): """ Rotate the LEDs by the specified number of positions. Treating the internal LED array as a circular buffer, rotate it by the specified number of positions. The number could be negative, which means rotating in the opposite direction. """ cutoff = 4 * (positions % self.num_led) self.leds = self.leds[cutoff:] + self.leds[:cutoff]
[文档] def show(self): """Sends the content of the pixel buffer to the strip. Todo: More than 1024 LEDs requires more than one xfer operation. """ self.clock_start_frame() # xfer2 kills the list, unfortunately. So it must be copied first # SPI takes up to 4096 Integers. So we are fine for up to 1024 LEDs. self.spi.xfer2(list(self.leds)) self.clock_end_frame()
[文档] def cleanup(self): """Release the SPI device; Call this method at the end""" self.spi.close() # Close SPI port
[文档] @staticmethod def combine_color(red, green, blue): """Make one 3*8 byte color value.""" return (red << 16) + (green << 8) + blue
[文档] def wheel(self, wheel_pos): """Get a color from a color wheel; Green -> Red -> Blue -> Green""" if wheel_pos > 255: wheel_pos = 255 # Safeguard if wheel_pos < 85: # Green -> Red return self.combine_color(wheel_pos * 3, 255 - wheel_pos * 3, 0) if wheel_pos < 170: # Red -> Blue wheel_pos -= 85 return self.combine_color(255 - wheel_pos * 3, 0, wheel_pos * 3) # Blue -> Green wheel_pos -= 170 return self.combine_color(0, wheel_pos * 3, 255 - wheel_pos * 3)
[文档] def dump_array(self): """For debug purposes: Dump the LED array onto the console.""" print(self.leds)
================================================ FILE: docs/_modules/robot/drivers/pixels.html ================================================ robot.drivers.pixels — wukong-robot 1.2.0 文档

robot.drivers.pixels 源代码

from . import apa102
import time
import threading
try:
    import queue as Queue
except ImportError:
    import Queue as Queue


[文档]class Pixels: PIXELS_N = 3 def __init__(self): self.basis = [0] * 3 * self.PIXELS_N self.basis[0] = 1 self.basis[4] = 1 self.basis[8] = 2 self.colors = [0] * 3 * self.PIXELS_N self.dev = apa102.APA102(num_led=self.PIXELS_N) self.next = threading.Event() self.queue = Queue.Queue() self.thread = threading.Thread(target=self._run) self.thread.daemon = True self.thread.start()
[文档] def wakeup(self, direction=0): def f(): self._wakeup(direction) self.next.set() self.queue.put(f)
[文档] def listen(self): self.next.set() self.queue.put(self._listen)
[文档] def think(self): self.next.set() self.queue.put(self._think)
[文档] def speak(self): self.next.set() self.queue.put(self._speak)
[文档] def off(self): self.next.set() self.queue.put(self._off)
def _run(self): while True: func = self.queue.get() func() def _wakeup(self, direction=0): for i in range(1, 25): colors = [i * v for v in self.basis] self.write(colors) time.sleep(0.01) self.colors = colors def _listen(self): for i in range(1, 25): colors = [i * v for v in self.basis] self.write(colors) time.sleep(0.01) self.colors = colors def _think(self): colors = self.colors self.next.clear() while not self.next.is_set(): colors = colors[3:] + colors[:3] self.write(colors) time.sleep(0.2) t = 0.1 for i in range(0, 5): colors = colors[3:] + colors[:3] self.write([(v * (4 - i) / 4) for v in colors]) time.sleep(t) t /= 2 # time.sleep(0.5) self.colors = colors def _speak(self): colors = self.colors self.next.clear() while not self.next.is_set(): for i in range(5, 25): colors = [(v * i / 24) for v in colors] self.write(colors) time.sleep(0.01) time.sleep(0.3) for i in range(24, 4, -1): colors = [(v * i / 24) for v in colors] self.write(colors) time.sleep(0.01) time.sleep(0.3) self._off() def _off(self): self.write([0] * 3 * self.PIXELS_N)
[文档] def write(self, colors): for i in range(self.PIXELS_N): self.dev.set_pixel(i, int(colors[3*i]), int(colors[3*i + 1]), int(colors[3*i + 2])) self.dev.show()
pixels = Pixels() if __name__ == '__main__': while True: try: pixels.wakeup() time.sleep(3) pixels.think() time.sleep(3) pixels.speak() time.sleep(3) pixels.off() time.sleep(3) except KeyboardInterrupt: break pixels.off() time.sleep(1)
================================================ FILE: docs/_modules/robot/logging.html ================================================ robot.logging — wukong-robot 1.2.0 文档

robot.logging 源代码

import logging
import os
from robot import constants
from logging.handlers import RotatingFileHandler

PAGE = 4096

DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR

[文档]def tail(filepath, n=10): """ 实现 tail -n """ res = "" with open(filepath, 'rb') as f: f_len = f.seek(0, 2) rem = f_len % PAGE page_n = f_len // PAGE r_len = rem if rem else PAGE while True: # 如果读取的页大小>=文件大小,直接读取数据输出 if r_len >= f_len: f.seek(0) lines = f.readlines()[::-1] break f.seek(-r_len, 2) # print('f_len: {}, rem: {}, page_n: {}, r_len: {}'.format(f_len, rem, page_n, r_len)) lines = f.readlines()[::-1] count = len(lines) -1 # 末行可能不完整,减一行,加大读取量 if count >= n: # 如果读取到的行数>=指定行数,则退出循环读取数据 break else: # 如果读取行数不够,载入更多的页大小读取数据 r_len += PAGE page_n -= 1 for line in lines[:n][::-1]: res += line.decode('utf-8') return res
[文档]def getLogger(name): """ 作用同标准模块 logging.getLogger(name) :returns: logger """ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(name) logger.setLevel(logging.INFO) # FileHandler file_handler = RotatingFileHandler(os.path.join(constants.TEMP_PATH, 'wukong.log'), maxBytes=1024*1024,backupCount=5) file_handler.setLevel(level=logging.DEBUG) file_handler.setFormatter(formatter) logger.addHandler(file_handler) return logger
[文档]def readLog(lines=200): """ 获取最新的指定行数的 log :param lines: 最大的行数 :returns: 最新指定行数的 log """ log_path = os.path.join(constants.TEMP_PATH, 'wukong.log') if os.path.exists(log_path): return tail(log_path, lines) return ''
================================================ FILE: docs/_modules/robot/plugin_loader.html ================================================ robot.plugin_loader — wukong-robot 1.2.0 文档

robot.plugin_loader 源代码

# -*- coding: utf-8-*-
import pkgutil
from . import constants
from . import config
from robot import logging
from robot.sdk.AbstractPlugin import AbstractPlugin

logger = logging.getLogger(__name__)
_has_init = False

# plugins run at query
_plugins_query = []

[文档]def init_plugins(con): """ 动态加载技能插件 参数: con -- 会话模块 """ global _has_init locations = [ constants.PLUGIN_PATH, constants.CONTRIB_PATH, constants.CUSTOM_PATH ] logger.debug("检查插件目录:{}".format(locations)) global _plugins_query nameSet = set() for finder, name, ispkg in pkgutil.walk_packages(locations): try: loader = finder.find_module(name) mod = loader.load_module(name) except Exception: logger.warning("插件 {} 加载出错,跳过".format(name), exc_info=True) continue if not hasattr(mod, 'Plugin'): logger.debug("模块 {} 非插件,跳过".format(name)) continue # plugins run at query plugin = mod.Plugin(con) if plugin.SLUG == 'AbstractPlugin': plugin.SLUG = name # check conflict if plugin.SLUG in nameSet: logger.warning("插件 {} SLUG({}) 重复,跳过".format(name, plugin.SLUG)) continue nameSet.add(plugin.SLUG) # whether a plugin is enabled if config.has(plugin.SLUG) and 'enable' in config.get(plugin.SLUG): if not config.get(plugin.SLUG)['enable']: logger.info("插件 {} 已被禁用".format(name)) continue if issubclass(mod.Plugin, AbstractPlugin): logger.info("插件 {} 加载成功 ".format(name)) _plugins_query.append(plugin) def sort_priority(m): if hasattr(m, 'PRIORITY'): return m.PRIORITY return 0 _plugins_query.sort(key=sort_priority, reverse=True) _has_init = True
[文档]def get_plugins(con): global _plugins_query _plugins_query = [] init_plugins(con) return _plugins_query
================================================ FILE: docs/_modules/robot/sdk/AbstractPlugin.html ================================================ robot.sdk.AbstractPlugin — wukong-robot 1.2.0 文档

robot.sdk.AbstractPlugin 源代码

from abc import ABCMeta, abstractmethod
from robot import constants
from robot import logging
import sys

logger = logging.getLogger(__name__)

try:
    sys.path.append(constants.CONTRIB_PATH)
except Exception as e:
    logger.debug("未检测到插件目录,Error:{}".format(e))
    
[文档]class AbstractPlugin(metaclass=ABCMeta): """ 技能插件基类 """ SLUG = 'AbstractPlugin' IS_IMMERSIVE = False def __init__(self, con): if self.IS_IMMERSIVE is not None: self.isImmersive = self.IS_IMMERSIVE else: self.isImmersive = False self.priority = 0 self.con = con self.nlu = self.con.nlu
[文档] def play(self, src, delete=False, onCompleted=None, volume=1): self.con.play(src, delete, onCompleted, volume)
[文档] def say(self, text, cache=False, onCompleted=None, wait=False): self.con.say(text, cache=cache, plugin=self.SLUG, onCompleted=onCompleted, wait=wait)
[文档] def activeListen(self, silent=False): return self.con.activeListen(silent)
[文档] def clearImmersive(self): self.con.setImmersiveMode(None)
[文档] @abstractmethod def isValid(self, query, parsed): """ 是否适合由该插件处理 参数: query -- 用户的指令字符串 parsed -- 用户指令经过 NLU 解析后的结果 返回: True: 适合由该插件处理 False: 不适合由该插件处理 """ return False
[文档] @abstractmethod def handle(self, query, parsed): """ 处理逻辑 参数: query -- 用户的指令字符串 parsed -- 用户指令经过 NLU 解析后的结果 """ pass
[文档] def isValidImmersive(self, query, parsed): """ 是否适合在沉浸模式下处理, 仅适用于有沉浸模式的插件(如音乐等) 当用户唤醒时,可以响应更多指令集。 例如:“"上一首"、"下一首" 等 """ return False
[文档] def pause(self): """ 暂停当前正在处理的任务, 当处于该沉浸模式下且被唤醒时, 将自动触发这个方法, 可以用于强制暂停一个耗时的操作 """ return
[文档] def restore(self): """ 恢复当前插件, 仅适用于有沉浸模式的插件(如音乐等) 当用户误唤醒或者唤醒进行闲聊后, 可以自动恢复当前插件的处理逻辑 """ return
================================================ FILE: docs/_modules/robot/sdk/AliSpeech.html ================================================ robot.sdk.AliSpeech — wukong-robot 1.2.0 文档

robot.sdk.AliSpeech 源代码

# -*- coding: UTF-8 -*-

import http.client
import urllib.parse
import json
from robot import utils
from robot import logging

logger = logging.getLogger(__name__)

[文档]def processGETRequest(appKey, token, voice, text, format, sampleRate) : host = 'nls-gateway.cn-shanghai.aliyuncs.com' url = 'https://' + host + '/stream/v1/tts' # 设置URL请求参数 url = url + '?appkey=' + appKey url = url + '&token=' + token url = url + '&text=' + text url = url + '&format=' + format url = url + '&sample_rate=' + str(sampleRate) url = url + '&voice=' + voice logger.debug(url) conn = http.client.HTTPSConnection(host) conn.request(method='GET', url=url) # 处理服务端返回的响应 response = conn.getresponse() logger.debug('Response status and response reason:') logger.debug(response.status ,response.reason) contentType = response.getheader('Content-Type') logger.debug(contentType) body = response.read() if 'audio/mpeg' == contentType : logger.debug('The GET request succeed!') tmpfile = utils.write_temp_file(body, '.mp3') conn.close() return tmpfile else : logger.debug('The GET request failed: ' + str(body)) conn.close() return None
[文档]def processPOSTRequest(appKey, token, voice, text, format, sampleRate) : host = 'nls-gateway.cn-shanghai.aliyuncs.com' url = 'https://' + host + '/stream/v1/tts' # 设置HTTPS Headers httpHeaders = { 'Content-Type': 'application/json' } # 设置HTTPS Body body = {'appkey': appKey, 'token': token, 'text': text, 'format': format, 'sample_rate': sampleRate, 'voice': voice} body = json.dumps(body) logger.debug('The POST request body content: ' + body) # Python 2.x 请使用httplib # conn = httplib.HTTPSConnection(host) # Python 3.x 请使用http.client conn = http.client.HTTPSConnection(host) conn.request(method='POST', url=url, body=body, headers=httpHeaders) # 处理服务端返回的响应 response = conn.getresponse() logger.debug('Response status and response reason:') logger.debug(response.status ,response.reason) contentType = response.getheader('Content-Type') logger.debug(contentType) body = response.read() if 'audio/mpeg' == contentType : logger.debug('The POST request succeed!') tmpfile = utils.write_temp_file(body, '.mp3') conn.close() return tmpfile else : logger.critical('The POST request failed: ' + str(body)) conn.close() return None
[文档]def process(request, token, audioContent) : # 读取音频文件 host = 'nls-gateway.cn-shanghai.aliyuncs.com' # 设置HTTP请求头部 httpHeaders = { 'X-NLS-Token': token, 'Content-type': 'application/octet-stream', 'Content-Length': len(audioContent) } conn = http.client.HTTPConnection(host) conn.request(method='POST', url=request, body=audioContent, headers=httpHeaders) response = conn.getresponse() logger.debug('Response status and response reason:') logger.debug(response.status ,response.reason) body = response.read() try: logger.debug('Recognize response is:') body = json.loads(body) logger.debug(body) status = body['status'] if status == 20000000 : result = body['result'] logger.debug('Recognize result: ' + result) conn.close() return result else : logger.critical('Recognizer failed!') conn.close() return None except ValueError: logger.debug('The response is not json format string') conn.close() return None
[文档]def tts(appKey, token, voice, text): # 采用RFC 3986规范进行urlencode编码 textUrlencode = text textUrlencode = urllib.parse.quote_plus(textUrlencode) textUrlencode = textUrlencode.replace("+", "%20") textUrlencode = textUrlencode.replace("*", "%2A") textUrlencode = textUrlencode.replace("%7E", "~") format = 'mp3' sampleRate = 16000 return processPOSTRequest(appKey, token, voice, text, format, sampleRate)
[文档]def asr(appKey, token, wave_file): # 服务请求地址 url = 'http://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr' pcm = utils.get_pcm_from_wav(wave_file) # 音频文件 format = 'pcm' sampleRate = 16000 enablePunctuationPrediction = True enableInverseTextNormalization = True enableVoiceDetection = False # 设置RESTful请求参数 request = url + '?appkey=' + appKey request = request + '&format=' + format request = request + '&sample_rate=' + str(sampleRate) if enablePunctuationPrediction : request = request + '&enable_punctuation_prediction=' + 'true' if enableInverseTextNormalization : request = request + '&enable_inverse_text_normalization=' + 'true' if enableVoiceDetection : request = request + '&enable_voice_detection=' + 'true' logger.debug('Request: ' + request) return process(request, token, pcm)
================================================ FILE: docs/_modules/robot/sdk/RASRsdk.html ================================================ robot.sdk.RASRsdk — wukong-robot 1.2.0 文档

robot.sdk.RASRsdk 源代码

# -*- coding:utf-8 -*-
import urllib.request
import hmac
import hashlib
import base64
import time
import random
import os
import json


[文档]def formatSignString(param): signstr = "POSTaai.qcloud.com/asr/v1/" for t in param: if 'appid' in t: signstr += str(t[1]) break signstr += "?" for x in param: tmp = x if 'appid' in x: continue for t in tmp: signstr += str(t) signstr += "=" signstr = signstr[:-1] signstr += "&" signstr = signstr[:-1] # print 'signstr',signstr return signstr
[文档]def sign(signstr, secret_key): sign_bytes= bytes(signstr , 'utf-8') secret_bytes = bytes(secret_key, 'utf-8') hmacstr = hmac.new(secret_bytes, sign_bytes, hashlib.sha1).digest() s = base64.b64encode(hmacstr).decode('utf-8') return s
[文档]def randstr(n): seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sa = [] for i in range(n): sa.append(random.choice(seed)) salt = ''.join(sa) # print salt return salt
[文档]def sendVoice(secret_key, secretid, appid, engine_model_type, res_type, result_text_format, voice_format, filepath, cutlength, template_name=""): if len(str(secret_key)) == 0: print('secretKey can not empty') return if len(str(secretid)) == 0: print('secretid can not empty') return if len(str(appid)) == 0: print('appid can not empty') return if len(str(engine_model_type)) == 0 or ( str(engine_model_type) != '8k_0' and str(engine_model_type) != '16k_0' and str( engine_model_type) != '16k_en'): print('engine_model_type is not right') return if len(str(res_type)) == 0 or (str(res_type) != '0' and str(res_type) != '1'): print('res_type is not right') return if len(str(result_text_format)) == 0 or (str(result_text_format) != '0' and str(result_text_format) != '1' and str( result_text_format) != '2' and str(result_text_format) != '3'): print('result_text_format is not right') return if len(str(voice_format)) == 0 or ( str(voice_format) != '1' and str(voice_format) != '4' and str(voice_format) != '6'): print('voice_format is not right') return if len(str(filepath)) == 0: print('filepath can not empty') return if len(str(cutlength)) == 0 or str(cutlength).isdigit() == False or cutlength > 200000: print('cutlength can not empty') return # secret_key = "oaYWFO70LGDmcpfwo8uF1IInayysGtgZ" query_arr = dict() query_arr['appid'] = appid query_arr['projectid'] = 1013976 if len(template_name) > 0: query_arr['template_name'] = template_name query_arr['sub_service_type'] = 1 query_arr['engine_model_type'] = engine_model_type query_arr['res_type'] = res_type query_arr['result_text_format'] = result_text_format query_arr['voice_id'] = randstr(16) query_arr['timeout'] = 100 query_arr['source'] = 0 query_arr['secretid'] = secretid query_arr['timestamp'] = str(int(time.time())) query_arr['expired'] = int(time.time()) + 24 * 60 * 60 query_arr['nonce'] = query_arr['timestamp'][0:4] query_arr['voice_format'] = voice_format file_object = open(filepath, 'rb') file_object.seek(0, os.SEEK_END) datalen = file_object.tell() file_object.seek(0, os.SEEK_SET) seq = 0 response = [] while (datalen > 0): end = 0 if (datalen < cutlength): end = 1 query_arr['end'] = end query_arr['seq'] = seq query = sorted(query_arr.items(), key=lambda d: d[0]) signstr = formatSignString(query) autho = sign(signstr, secret_key) if (datalen < cutlength): content = file_object.read(datalen) else: content = file_object.read(cutlength) seq = seq + 1 datalen = datalen - cutlength headers = dict() headers['Authorization'] = autho headers['Content-Length'] = len(content) requrl = "http://" requrl += signstr[4::] req = urllib.request.Request(requrl, data=content, headers=headers) res_data = urllib.request.urlopen(req) r = res_data.read().decode('utf-8') res = json.loads(r) if res['code'] == 0: response.append(res['text']) file_object.close() return response[len(response)-1]
================================================ FILE: docs/_modules/robot/sdk/TencentSpeech.html ================================================ robot.sdk.TencentSpeech — wukong-robot 1.2.0 文档

robot.sdk.TencentSpeech 源代码

# coding: utf-8
#!/usr/bin/env python3


'Tencent ASR && TTS API'
__author__ = 'Charles Li, Joseph Pan'

import time
import uuid
import json
import random
import requests
import hmac
import base64
import urllib
#腾讯web API一句话识别请求
[文档]class tencentSpeech(object): __slots__ = 'SECRET_ID', 'SECRET_KEY', 'SourceType', 'URL', 'VoiceFormat', 'PrimaryLanguage', 'Text', 'VoiceType', 'Region' def __init__(self, SECRET_KEY, SECRET_ID): self.SECRET_KEY, self.SECRET_ID = SECRET_KEY, SECRET_ID @property def secret_id(self): return self.SECRET_ID @secret_id.setter def secret_id(self, SECRET_ID): if not isinstance(SECRET_ID, str): raise ValueError('SecretId must be a string!') if len(SECRET_ID)==0: raise ValueError('SecretId can not be empty!') self.SECRET_ID = SECRET_ID @property def secret_key(self): return self.SECRET_KEY @secret_key.setter def secret_key(self, SECRET_KEY): if not isinstance(SECRET_KEY, str): raise ValueError('SecretKey must be a string!') if len(SECRET_KEY)==0: raise ValueError('SecretKey can not be empty!') self.SECRET_KEY = SECRET_KEY @property def source_type(self): return self.sourcetype @source_type.setter def source_type(self, SourceType): if not isinstance(SourceType, str): raise ValueError('SecretType must be an string!') if len(SourceType)==0: raise ValueError('SourceType can not be empty!') self.SourceType = SourceType @property def url(self): return self.URL @url.setter def url(self, URL): if not isinstance(URL, str): raise ValueError('url must be an string!') if len(URL)==0: raise ValueError('url can not be empty!') self.URL = URL @property def voiceformat(self): return self.VoiceFormat @voiceformat.setter def voiceformat(self, VoiceFormat): if not isinstance(VoiceFormat, str): raise ValueError('voiceformat must be an string!') if len(VoiceFormat)==0: raise ValueError('voiceformat can not be empty!') self.VoiceFormat = VoiceFormat @property def text(self): return self.Text @text.setter def text(self, Text): if not isinstance(Text, str): raise ValueError('text must be an string!') if len(Text)==0: raise ValueError('text can not be empty!') self.Text = Text @property def region(self): return self.Region @region.setter def region(self, Region): if not isinstance(Region, str): raise ValueError('region must be an string!') if len(Region)==0: raise ValueError('region can not be empty!') self.Region = Region @property def primarylanguage(self): return self.PrimaryLanguage @primarylanguage.setter def primarylanguage(self, PrimaryLanguage): self.PrimaryLanguage = PrimaryLanguage @property def voicetype(self): return self.VoiceType @voicetype.setter def voicetype(self, VoiceType): self.VoiceType = VoiceType
[文档] def TTS(self, text, voicetype, primarylanguage, region): self.text, self.voicetype, self.primarylanguage, self.region = text, voicetype, primarylanguage, region return self.textToSpeech()
[文档] def textToSpeech(self): #生成body def make_body(config_dict, sign_encode): ##注意URL编码的时候分str编码,整段编码会丢data body = '' for a, b in config_dict: body += urllib.parse.quote(a) + '=' + urllib.parse.quote(str(b)) + '&' return body + 'Signature=' + sign_encode HOST = 'aai.tencentcloudapi.com' config_dict= { 'Action' : 'TextToVoice', 'Version' : '2018-05-22', 'ProjectId' : 0, 'Region' : self.Region, 'VoiceType' : self.VoiceType, 'Timestamp' : int(time.time()), 'Nonce' : random.randint(100000, 200000), 'SecretId' : self.SECRET_ID, 'Text' : self.Text, 'PrimaryLanguage': self.PrimaryLanguage, 'ModelType' : 1, 'SessionId' : uuid.uuid1() } #按key排序 config_dict = sorted(config_dict.items()) signstr = self.formatSignString(config_dict) sign_encode = urllib.parse.quote(self.encode_sign(signstr, self.SECRET_KEY)) body = make_body(config_dict, sign_encode) #Get URL req_url = "https://aai.tencentcloudapi.com" header = { 'Host' : HOST, 'Content-Type' : 'application/x-www-form-urlencoded', 'Charset' : 'UTF-8' } request = requests.post(req_url, headers = header, data = body) #有些音频utf8解码失败,存在编码错误 s = request.content.decode("utf8","ignore") return json.loads(s)
[文档] def ASR(self, URL, voiceformat, sourcetype, region): self.url, self.voiceformat, self.source_type, self.region = URL, voiceformat, sourcetype, region return self.oneSentenceRecognition()
[文档] def oneSentenceRecognition(self): #生成body def make_body(config_dict, sign_encode): ##注意URL编码的时候分str编码,整段编码会丢data body = '' for a, b in config_dict: body += urllib.parse.quote(a) + '=' + urllib.parse.quote(str(b)) + '&' return body + 'Signature=' + sign_encode HOST = 'aai.tencentcloudapi.com' config_dict= { 'Action' : 'SentenceRecognition', 'Version' : '2018-05-22', 'Region' : self.Region, 'ProjectId' : 0, 'SubServiceType' : 2, 'EngSerViceType' : '16k', 'VoiceFormat' : self.VoiceFormat, 'UsrAudioKey' : random.randint(0, 20), 'Timestamp' : int(time.time()), 'Nonce' : random.randint(100000, 200000), 'SecretId' : self.SECRET_ID, 'SourceType' : self.SourceType } if self.SourceType == '0': config_dict['Url'] = urllib.parse.quote(str(self.url)) else: #不能大于1M file_path = self.URL file = open(file_path, 'rb') content = file.read() config_dict['DataLen'] = len(content) config_dict['Data'] = base64.b64encode(content).decode() #config_dict['Data'] = content file.close() #按key排序 config_dict = sorted(config_dict.items()) signstr = self.formatSignString(config_dict) sign_encode = urllib.parse.quote(self.encode_sign(signstr, self.SECRET_KEY)) body = make_body(config_dict, sign_encode) #Get URL req_url = "https://aai.tencentcloudapi.com" header = { 'Host' : HOST, 'Content-Type' : 'application/x-www-form-urlencoded', 'Charset' : 'UTF-8' } request = requests.post(req_url, headers = header, data = body) #有些音频utf8解码失败,存在编码错误 s = request.content.decode("utf8","ignore") return s
#拼接url和参数
[文档] def formatSignString(self, config_dict): signstr="POSTaai.tencentcloudapi.com/?" argArr = [] for a, b in config_dict: argArr.append(a + "=" + str(b)) config_str = "&".join(argArr) return signstr + config_str
#生成签名
[文档] def encode_sign(self, signstr, SECRET_KEY): myhmac = hmac.new(SECRET_KEY.encode(), signstr.encode(), digestmod = 'sha1') code = myhmac.digest() #hmac() 完一定要decode()和 python 2 hmac不一样 signature = base64.b64encode(code).decode() return signature
================================================ FILE: docs/_modules/robot/sdk/XunfeiSpeech.html ================================================ robot.sdk.XunfeiSpeech — wukong-robot 1.2.0 文档

robot.sdk.XunfeiSpeech 源代码

import websocket
import hashlib
import base64
import hmac
import json
from urllib.parse import urlencode
import time
import ssl
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
import _thread as thread

from robot import logging
logger = logging.getLogger(__name__)

STATUS_FIRST_FRAME = 0  # 第一帧的标识
STATUS_CONTINUE_FRAME = 1  # 中间帧标识
STATUS_LAST_FRAME = 2  # 最后一帧的标识

wsParam = None
gResult = ''

[文档]class Ws_Param(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, AudioFile): # 控制台鉴权信息 self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret # 固定参数,可不用修改 self.Host = "iat-api.xfyun.cn/v2/iat" self.HttpProto = "HTTP/1.1" self.HttpMethod = "GET" self.RequestUri = "/v2/iat" self.Algorithm = "hmac-sha256" self.url = "wss://" + self.Host + self.RequestUri # 设置测试音频文件 self.AudioFile = AudioFile # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin"} # 生成url
[文档] def create_url(self): url = 'wss://ws-api.xfyun.cn/v2/iat' # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\n" signature_origin += "date: " + date + "\n" signature_origin += "GET " + "/v2/iat " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8') authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % ( self.APIKey, "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8') # 将请求的鉴权参数组合为字典 v = { "authorization": authorization, "date": date, "host": "ws-api.xfyun.cn" } # 拼接鉴权参数,生成url url = url + '?' + urlencode(v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 logger.debug('websocket url :', url) return url
# 收到websocket消息的处理
[文档]def on_message(ws, message): global gResult try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] if code != 0: errMsg = json.loads(message)["message"] logger.critical("xunfei-asr 识别出错了:sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: data = json.loads(message)["data"]["result"]["ws"] result = "" for i in data: for w in i["cw"]: result += w["w"] gResult = gResult + result logger.info("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False))) except Exception as e: logger.critical("xunfei-asr 识别出错了:", e)
# 收到websocket错误的处理
[文档]def on_error(ws, error): logger.error("### error:", error)
# 收到websocket关闭的处理
[文档]def on_close(ws): logger.debug("### closed ###")
# 收到websocket连接建立的处理
[文档]def on_open(ws): global wsParam def run(*args): frameSize = 1220 # 每一帧的音频大小 intervel = 0.04 # 发送音频间隔(单位:s) status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧 with open(wsParam.AudioFile, "rb") as fp: while True: buf = fp.read(frameSize) # 文件结束 if not buf: status = STATUS_LAST_FRAME # 第一帧处理 # 发送第一帧音频,带business 参数 # appid 必须带上,只需第一帧发送 if status == STATUS_FIRST_FRAME: d = {"common": wsParam.CommonArgs, "business": wsParam.BusinessArgs, "data": {"status": 0, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), 'utf-8'), "encoding": "raw"}} d = json.dumps(d) ws.send(d) status = STATUS_CONTINUE_FRAME # 中间帧处理 elif status == STATUS_CONTINUE_FRAME: d = {"data": {"status": 1, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), 'utf-8'), "encoding": "raw"}} ws.send(json.dumps(d)) # 最后一帧处理 elif status == STATUS_LAST_FRAME: d = {"data": {"status": 2, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), 'utf-8'), "encoding": "raw"}} ws.send(json.dumps(d)) time.sleep(1) break # 模拟音频采样间隔 time.sleep(intervel) ws.close() thread.start_new_thread(run, ())
[文档]def transcribe(fpath, appid, api_key, api_secret): """ 科大讯飞ASR """ global wsParam, gResult gResult = '' wsParam = Ws_Param(appid, api_key, APISecret=api_secret, AudioFile=fpath) websocket.enableTrace(False) wsUrl = wsParam.create_url() ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) return gResult
================================================ FILE: docs/_modules/robot/sdk/unit.html ================================================ robot.sdk.unit — wukong-robot 1.2.0 文档

robot.sdk.unit 源代码

# encoding:utf-8
import requests
import datetime
import uuid
import json
import os
from dateutil import parser as dparser
from robot import constants, logging

logger = logging.getLogger(__name__)

[文档]def get_token(api_key, secret_key): cache = open(os.path.join(constants.TEMP_PATH, 'baidustt.ini'), 'a+') try: pms = cache.readlines() if len(pms) > 0: time = pms[0] tk = pms[1] # 计算token是否过期 官方说明一个月,这里保守29天 time = dparser.parse(time) endtime = datetime.datetime.now() if (endtime - time).days <= 29: return tk finally: cache.close() URL = 'http://openapi.baidu.com/oauth/2.0/token' params = {'grant_type': 'client_credentials', 'client_id': api_key, 'client_secret': secret_key} r = requests.get(URL, params=params) try: r.raise_for_status() token = r.json()['access_token'] return token except requests.exceptions.HTTPError: return ''
[文档]def getUnit(query, service_id, api_key, secret_key): """ NLU 解析 :param query: 用户的指令字符串 :param service_id: UNIT 的 service_id :param api_key: UNIT apk_key :param secret_key: UNIT secret_key :returns: UNIT 解析结果。如果解析失败,返回 None """ access_token = get_token(api_key, secret_key) url = 'https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=' + access_token request={ "query":query, "user_id":"888888", } body={ "log_id": str(uuid.uuid1()), "version":"2.0", "service_id": service_id, "session_id": str(uuid.uuid1()), "request":request } try: headers = {'Content-Type': 'application/json'} request = requests.post(url, json=body, headers=headers) return json.loads(request.text) except Exception: return None
[文档]def getIntent(parsed): """ 提取意图 :param parsed: UNIT 解析结果 :returns: 意图数组 """ if parsed is not None and 'result' in parsed and \ 'response_list' in parsed['result']: return parsed['result']['response_list'][0]['schema']['intent'] else: return ''
[文档]def hasIntent(parsed, intent): """ 判断是否包含某个意图 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含 """ if parsed is not None and 'result' in parsed and \ 'response_list' in parsed['result']: response_list = parsed['result']['response_list'] for response in response_list: if response['schema']['intent'] == intent: return True return False else: return False
[文档]def getSlots(parsed, intent=''): """ 提取某个意图的所有词槽 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: 词槽列表。你可以通过 name 属性筛选词槽, 再通过 normalized_word 属性取出相应的值 """ if parsed is not None and 'result' in parsed and \ 'response_list' in parsed['result']: response_list = parsed['result']['response_list'] if intent == '': return parsed['result']['response_list'][0]['schema']['slots'] for response in response_list: if response['schema']['intent'] == intent: return response['schema']['slots'] else: return []
[文档]def getSlotWords(parsed, intent, name): """ 找出命中某个词槽的内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ slots = getSlots(parsed, intent) words = [] for slot in slots: if slot['name'] == name: words.append(slot['normalized_word']) return words
[文档]def getSay(parsed, intent=''): """ 提取 UNIT 的回复文本 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: UNIT 的回复文本 """ if parsed is not None and 'result' in parsed and \ 'response_list' in parsed['result']: response_list = parsed['result']['response_list'] if intent == '': return response_list[0]['action_list'][0]['say'] for response in response_list: if response['schema']['intent'] == intent: return response['action_list'][0]['say'] return '' else: return ''
if __name__ == '__main__': parsed = getUnit('今天的天气', "S13442", 'w5v7gUV3iPGsGntcM84PtOOM', 'KffXwW6E1alcGplcabcNs63Li6GvvnfL') print(parsed)
================================================ FILE: docs/_modules/robot/statistic.html ================================================ robot.statistic — wukong-robot 1.2.0 文档

robot.statistic 源代码

# -*- coding: utf-8-*-

from . import config
import uuid
import requests
import threading

[文档]def getUUID(): mac = uuid.UUID(int=uuid.getnode()).hex[-12:] return ":".join([mac[e:e+2] for e in range(0, 11, 2)])
[文档]def report(t): ReportThread(t).start()
[文档]class ReportThread (threading.Thread): def __init__(self, t): # 需要执行父类的初始化方法 threading.Thread.__init__(self) self.t = t
[文档] def run(self): to_report = config.get('statistic', True) if to_report: try: persona = config.get("robot_name_cn", '孙悟空') url = 'http://livecv.hahack.com:8022/statistic' payload = {'type': str(self.t), 'uuid': getUUID(), 'name': persona, 'project': 'wukong'} requests.post(url, data=payload, timeout=3) except Exception: return
================================================ FILE: docs/_modules/robot/utils.html ================================================ robot.utils — wukong-robot 1.2.0 文档

robot.utils 源代码

# -*- coding: utf-8-*-

import os
import tempfile
import wave
import shutil
import re
import time
import hashlib
import subprocess
from . import constants, config
from robot import logging
from pydub import AudioSegment
from pytz import timezone
import _thread as thread

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

logger = logging.getLogger(__name__)

do_not_bother = False

[文档]def sendEmail(SUBJECT, BODY, ATTACH_LIST, TO, FROM, SENDER, PASSWORD, SMTP_SERVER, SMTP_PORT): """ 发送邮件 :param SUBJECT: 邮件标题 :param BODY: 邮件正文 :param ATTACH_LIST: 附件 :param TO: 收件人 :param FROM: 发件人 :param SENDER: 发件人信息 :param PASSWORD: 密码 :param SMTP_SERVER: smtp 服务器 :param SMTP_PORT: smtp 端口号 :returns: True: 发送成功; False: 发送失败 """ txt = MIMEText(BODY.encode('utf-8'), 'html', 'utf-8') msg = MIMEMultipart() msg.attach(txt) for attach in ATTACH_LIST: try: att = MIMEText(open(attach, 'rb').read(), 'base64', 'utf-8') filename = os.path.basename(attach) att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"' % filename msg.attach(att) except Exception: logger.error(u'附件 %s 发送失败!' % attach) continue msg['From'] = SENDER msg['To'] = TO msg['Subject'] = SUBJECT try: session = smtplib.SMTP() session.connect(SMTP_SERVER, SMTP_PORT) session.starttls() session.login(FROM, PASSWORD) session.sendmail(SENDER, TO, msg.as_string()) session.close() return True except Exception as e: logger.error(e) return False
[文档]def emailUser(SUBJECT="", BODY="", ATTACH_LIST=[]): """ 给用户发送邮件 :param SUBJECT: subject line of the email :param BODY: body text of the email :returns: True: 发送成功; False: 发送失败 """ # add footer if BODY: BODY = u"%s,<br><br>这是您要的内容:<br>%s<br>" % (config['first_name'], BODY) recipient = config.get('/email/address', '') robot_name = config.get('robot_name_cn', 'wukong-robot') recipient = robot_name + " <%s>" % recipient user = config.get('/email/address', '') password = config.get('/email/password', '') server = config.get('/email/smtp_server', '') port = config.get('/email/smtp_port', '') if not recipient or not user or not password or not server or not port: return False try: sendEmail(SUBJECT, BODY, ATTACH_LIST, user, user, recipient, password, server, port) return True except Exception as e: logger.error(e) return False
[文档]def get_file_content(filePath): """ 读取文件内容并返回 :param filePath: 文件路径 :returns: 文件内容 :raises IOError: 读取失败则抛出 IOError """ with open(filePath, 'rb') as fp: return fp.read()
[文档]def check_and_delete(fp, wait=0): """ 检查并删除文件/文件夹 :param fp: 文件路径 """ def run(): if wait > 0: time.sleep(wait) if isinstance(fp, str) and os.path.exists(fp): if os.path.isfile(fp): os.remove(fp) else: shutil.rmtree(fp) thread.start_new_thread(run, ())
[文档]def write_temp_file(data, suffix, mode='w+b'): """ 写入临时文件 :param data: 数据 :param suffix: 后缀名 :param mode: 写入模式,默认为 w+b :returns: 文件保存后的路径 """ with tempfile.NamedTemporaryFile(mode=mode, suffix=suffix, delete=False) as f: f.write(data) tmpfile = f.name return tmpfile
[文档]def get_pcm_from_wav(wav_path): """ 从 wav 文件中读取 pcm :param wav_path: wav 文件路径 :returns: pcm 数据 """ wav = wave.open(wav_path, 'rb') return wav.readframes(wav.getnframes())
[文档]def convert_wav_to_mp3(wav_path): """ 将 wav 文件转成 mp3 :param wav_path: wav 文件路径 :returns: mp3 文件路径 """ if not os.path.exists(wav_path): logger.critical("文件错误 {}".format(wav_path)) return None mp3_path = wav_path.replace('.wav', '.mp3') AudioSegment.from_wav(wav_path).export(mp3_path, format="mp3") return mp3_path
[文档]def convert_mp3_to_wav(mp3_path): """ 将 mp3 文件转成 wav :param mp3_path: mp3 文件路径 :returns: wav 文件路径 """ target = mp3_path.replace(".mp3", ".wav") if not os.path.exists(mp3_path): logger.critical("文件错误 {}".format(mp3_path)) return None AudioSegment.from_mp3(mp3_path).export(target, format="wav") return target
[文档]def clean(): """ 清理垃圾数据 """ temp = constants.TEMP_PATH temp_files = os.listdir(temp) for f in temp_files: if os.path.isfile(os.path.join(temp, f)) and re.match(r'output[\d]*\.wav', os.path.basename(f)): os.remove(os.path.join(temp, f))
[文档]def is_proper_time(): """ 是否合适时间 """ if do_not_bother == True: return False if not config.has('do_not_bother'): return True bother_profile = config.get('do_not_bother') if not bother_profile['enable']: return True if 'since' not in bother_profile or 'till' not in bother_profile: return True since = bother_profile['since'] till = bother_profile['till'] current = time.localtime(time.time()).tm_hour if till > since: return current not in range(since, till) else: return not (current in range(since, 25) or current in range(-1, till))
[文档]def get_do_not_bother_on_hotword(): """ 打开勿扰模式唤醒词 """ return config.get('/do_not_bother/on_hotword', '悟空别吵.pmdl')
[文档]def get_do_not_bother_off_hotword(): """ 关闭勿扰模式唤醒词 """ return config.get('/do_not_bother/off_hotword', '悟空醒醒.pmdl')
[文档]def getTimezone(): """ 获取时区 """ return timezone(config.get('timezone', 'HKT'))
[文档]def getCache(msg): """ 获取缓存的语音 """ md5 = hashlib.md5(msg.encode('utf-8')).hexdigest() mp3_cache = os.path.join(constants.TEMP_PATH, md5 + '.mp3') wav_cache = os.path.join(constants.TEMP_PATH, md5 + '.wav') if os.path.exists(mp3_cache): return mp3_cache elif os.path.exists(wav_cache): return wav_cache return None
[文档]def saveCache(voice, msg): """ 获取缓存的语音 """ foo, ext = os.path.splitext(voice) md5 = hashlib.md5(msg.encode('utf-8')).hexdigest() target = os.path.join(constants.TEMP_PATH, md5+ext) shutil.copyfile(voice, target) return target
[文档]def lruCache(): """ 清理最近未使用的缓存 """ def run(*args): if config.get('/lru_cache/enable', True): days = config.get('/lru_cache/days', 7) subprocess.run('find . -name "*.mp3" -atime +%d -exec rm {} \;' % days, cwd=constants.TEMP_PATH, shell=True) thread.start_new_thread(run, ())
================================================ FILE: docs/_modules/snowboy/snowboydecoder.html ================================================ snowboy.snowboydecoder — wukong-robot 1.2.0 文档

snowboy.snowboydecoder 源代码

#!/usr/bin/env python

import collections
import pyaudio
from . import snowboydetect
from robot import utils, logging
import time
import wave
import os
from ctypes import CFUNCTYPE, c_char_p, c_int, cdll
from contextlib import contextmanager
from robot import constants


logger = logging.getLogger("snowboy")
TOP_DIR = os.path.dirname(os.path.abspath(__file__))

RESOURCE_FILE = os.path.join(TOP_DIR, "resources/common.res")
DETECT_DING = os.path.join(TOP_DIR, "resources/ding.wav")
DETECT_DONG = os.path.join(TOP_DIR, "resources/dong.wav")

[文档]def py_error_handler(filename, line, function, err, fmt): pass
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p) c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
[文档]@contextmanager def no_alsa_error(): try: asound = cdll.LoadLibrary('libasound.so') asound.snd_lib_error_set_handler(c_error_handler) yield asound.snd_lib_error_set_handler(None) except: yield pass
[文档]class RingBuffer(object): """Ring buffer to hold audio from PortAudio""" def __init__(self, size=4096): self._buf = collections.deque(maxlen=size)
[文档] def extend(self, data): """Adds data to the end of buffer""" self._buf.extend(data)
[文档] def get(self): """Retrieves data from the beginning of buffer and clears it""" tmp = bytes(bytearray(self._buf)) self._buf.clear() return tmp
[文档]def play_audio_file(fname=DETECT_DING): """Simple callback function to play a wave file. By default it plays a Ding sound. :param str fname: wave file name :return: None """ ding_wav = wave.open(fname, 'rb') ding_data = ding_wav.readframes(ding_wav.getnframes()) with no_alsa_error(): audio = pyaudio.PyAudio() stream_out = audio.open( format=audio.get_format_from_width(ding_wav.getsampwidth()), channels=ding_wav.getnchannels(), rate=ding_wav.getframerate(), input=False, output=True) stream_out.start_stream() stream_out.write(ding_data) time.sleep(0.2) stream_out.stop_stream() stream_out.close() audio.terminate()
[文档]class ActiveListener(object): """ Active Listening with VAD """ def __init__(self, decoder_model, resource=RESOURCE_FILE): logger.debug("activeListen __init__()") self.recordedData = [] model_str = ",".join(decoder_model) self.detector = snowboydetect.SnowboyDetect( resource_filename=resource.encode(), model_str=model_str.encode()) self.ring_buffer = RingBuffer( self.detector.NumChannels() * self.detector.SampleRate() * 5)
[文档] def listen(self, interrupt_check=lambda: False, sleep_time=0.03, silent_count_threshold=15, recording_timeout=100): """ :param interrupt_check: a function that returns True if the main loop needs to stop. :param silent_count_threshold: indicates how long silence must be heard to mark the end of a phrase that is being recorded. :param float sleep_time: how much time in second every loop waits. :param recording_timeout: limits the maximum length of a recording. :return: recorded file path """ logger.debug("activeListen listen()") self._running = True def audio_callback(in_data, frame_count, time_info, status): self.ring_buffer.extend(in_data) play_data = chr(0) * len(in_data) return play_data, pyaudio.paContinue with no_alsa_error(): self.audio = pyaudio.PyAudio() logger.debug('opening audio stream') try: self.stream_in = self.audio.open( input=True, output=False, format=self.audio.get_format_from_width( self.detector.BitsPerSample() / 8), channels=self.detector.NumChannels(), rate=self.detector.SampleRate(), frames_per_buffer=2048, stream_callback=audio_callback) except Exception as e: logger.critical(e) return logger.debug('audio stream opened') if interrupt_check(): logger.debug("detect voice return") return silentCount = 0 recordingCount = 0 logger.debug("begin activeListen loop") while self._running is True: if interrupt_check(): logger.debug("detect voice break") break data = self.ring_buffer.get() if len(data) == 0: time.sleep(sleep_time) continue status = self.detector.RunDetection(data) if status == -1: logger.warning("Error initializing streams or reading audio data") stopRecording = False if recordingCount > recording_timeout: stopRecording = True elif status == -2: #silence found if silentCount > silent_count_threshold: stopRecording = True else: silentCount = silentCount + 1 elif status == 0: #voice found silentCount = 0 if stopRecording == True: return self.saveMessage() recordingCount = recordingCount + 1 self.recordedData.append(data) logger.debug("finished.")
[文档] def saveMessage(self): """ Save the message stored in self.recordedData to a timestamped file. """ filename = os.path.join(constants.TEMP_PATH, 'output' + str(int(time.time())) + '.wav') data = b''.join(self.recordedData) #use wave to save data wf = wave.open(filename, 'wb') wf.setnchannels(self.detector.NumChannels()) wf.setsampwidth(self.audio.get_sample_size( self.audio.get_format_from_width(self.detector.BitsPerSample() / 8))) wf.setframerate(self.detector.SampleRate()) wf.writeframes(data) wf.close() logger.debug("finished saving: " + filename) self.stream_in.stop_stream() self.stream_in.close() self.audio.terminate() return filename
[文档]class HotwordDetector(object): """ Snowboy decoder to detect whether a keyword specified by `decoder_model` exists in a microphone input stream. :param decoder_model: decoder model file path, a string or a list of strings :param resource: resource file path. :param sensitivity: decoder sensitivity, a float of a list of floats. The bigger the value, the more senstive the decoder. If an empty list is provided, then the default sensitivity in the model will be used. :param audio_gain: multiply input volume by this factor. :param apply_frontend: applies the frontend processing algorithm if True. """ def __init__(self, decoder_model, resource=RESOURCE_FILE, sensitivity=[], audio_gain=1, apply_frontend=False): self._running = False tm = type(decoder_model) ts = type(sensitivity) if tm is not list: decoder_model = [decoder_model] if ts is not list: sensitivity = [sensitivity] model_str = ",".join(decoder_model) self.detector = snowboydetect.SnowboyDetect( resource_filename=resource.encode(), model_str=model_str.encode()) self.detector.SetAudioGain(audio_gain) self.detector.ApplyFrontend(apply_frontend) self.num_hotwords = self.detector.NumHotwords() if len(decoder_model) > 1 and len(sensitivity) == 1: sensitivity = sensitivity * self.num_hotwords if len(sensitivity) != 0: assert self.num_hotwords == len(sensitivity), \ "number of hotwords in decoder_model (%d) and sensitivity " \ "(%d) does not match" % (self.num_hotwords, len(sensitivity)) sensitivity_str = ",".join([str(t) for t in sensitivity]) if len(sensitivity) != 0: self.detector.SetSensitivity(sensitivity_str.encode()) self.ring_buffer = RingBuffer( self.detector.NumChannels() * self.detector.SampleRate() * 5)
[文档] def start(self, detected_callback=play_audio_file, interrupt_check=lambda: False, sleep_time=0.03, audio_recorder_callback=None, silent_count_threshold=15, recording_timeout=100): """ Start the voice detector. For every `sleep_time` second it checks the audio buffer for triggering keywords. If detected, then call corresponding function in `detected_callback`, which can be a single function (single model) or a list of callback functions (multiple models). Every loop it also calls `interrupt_check` -- if it returns True, then breaks from the loop and return. :param detected_callback: a function or list of functions. The number of items must match the number of models in `decoder_model`. :param interrupt_check: a function that returns True if the main loop needs to stop. :param float sleep_time: how much time in second every loop waits. :param audio_recorder_callback: if specified, this will be called after a keyword has been spoken and after the phrase immediately after the keyword has been recorded. The function will be passed the name of the file where the phrase was recorded. :param silent_count_threshold: indicates how long silence must be heard to mark the end of a phrase that is being recorded. :param recording_timeout: limits the maximum length of a recording. :return: None """ self._running = True def audio_callback(in_data, frame_count, time_info, status): self.ring_buffer.extend(in_data) play_data = chr(0) * len(in_data) return play_data, pyaudio.paContinue with no_alsa_error(): self.audio = pyaudio.PyAudio() self.stream_in = self.audio.open( input=True, output=False, format=self.audio.get_format_from_width( self.detector.BitsPerSample() / 8), channels=self.detector.NumChannels(), rate=self.detector.SampleRate(), frames_per_buffer=2048, stream_callback=audio_callback) if interrupt_check(): logger.debug("detect voice return") return tc = type(detected_callback) if tc is not list: detected_callback = [detected_callback] if len(detected_callback) == 1 and self.num_hotwords > 1: detected_callback *= self.num_hotwords assert self.num_hotwords == len(detected_callback), \ "Error: hotwords in your models (%d) do not match the number of " \ "callbacks (%d)" % (self.num_hotwords, len(detected_callback)) logger.debug("detecting...") state = "PASSIVE" while self._running is True: if interrupt_check(): logger.debug("detect voice break") break data = self.ring_buffer.get() if len(data) == 0: time.sleep(sleep_time) continue status = self.detector.RunDetection(data) if status == -1: logger.warning("Error initializing streams or reading audio data") #small state machine to handle recording of phrase after keyword if state == "PASSIVE": if status > 0: #key word found self.recordedData = [] self.recordedData.append(data) silentCount = 0 recordingCount = 0 message = "Keyword " + str(status) + " detected at time: " message += time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) logger.info(message) callback = detected_callback[status-1] if callback is not None: callback() if audio_recorder_callback is not None and status == 1 and utils.is_proper_time(): state = "ACTIVE" continue elif state == "ACTIVE": stopRecording = False if recordingCount > recording_timeout: stopRecording = True elif status == -2: #silence found if silentCount > silent_count_threshold: stopRecording = True else: silentCount = silentCount + 1 elif status == 0: #voice found silentCount = 0 if stopRecording == True: fname = self.saveMessage() audio_recorder_callback(fname) state = "PASSIVE" continue recordingCount = recordingCount + 1 self.recordedData.append(data) logger.debug("finished.")
[文档] def saveMessage(self): """ Save the message stored in self.recordedData to a timestamped file. """ filename = os.path.join(constants.TEMP_PATH, 'output' + str(int(time.time())) + '.wav') data = b''.join(self.recordedData) #use wave to save data wf = wave.open(filename, 'wb') wf.setnchannels(self.detector.NumChannels()) wf.setsampwidth(self.audio.get_sample_size( self.audio.get_format_from_width( self.detector.BitsPerSample() / 8))) wf.setframerate(self.detector.SampleRate()) wf.writeframes(data) wf.close() logger.debug("finished saving: " + filename) return filename
[文档] def terminate(self): """ Terminate audio stream. Users can call start() again to detect. :return: None """ if self._running: self.stream_in.stop_stream() self.stream_in.close() self.audio.terminate() self._running = False
================================================ FILE: docs/_modules/snowboy/snowboydetect.html ================================================ snowboy.snowboydetect — wukong-robot 1.2.0 文档

snowboy.snowboydetect 源代码

# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.

from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
    def swig_import_helper():
        import importlib
        pkg = __name__.rpartition('.')[0]
        mname = '.'.join((pkg, '_snowboydetect')).lstrip('.')
        try:
            return importlib.import_module(mname)
        except ImportError:
            return importlib.import_module('_snowboydetect')
    _snowboydetect = swig_import_helper()
    del swig_import_helper
elif _swig_python_version_info >= (2, 6, 0):
    def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_snowboydetect', [dirname(__file__)])
        except ImportError:
            import _snowboydetect
            return _snowboydetect
        try:
            _mod = imp.load_module('_snowboydetect', fp, pathname, description)
        finally:
            if fp is not None:
                fp.close()
        return _mod
    _snowboydetect = swig_import_helper()
    del swig_import_helper
else:
    import _snowboydetect
del _swig_python_version_info

try:
    _swig_property = property
except NameError:
    pass  # Python < 2.2 doesn't have 'property'.

try:
    import builtins as __builtin__
except ImportError:
    import __builtin__

def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
    if (name == "thisown"):
        return self.this.own(value)
    if (name == "this"):
        if type(value).__name__ == 'SwigPyObject':
            self.__dict__[name] = value
            return
    method = class_type.__swig_setmethods__.get(name, None)
    if method:
        return method(self, value)
    if (not static):
        if _newclass:
            object.__setattr__(self, name, value)
        else:
            self.__dict__[name] = value
    else:
        raise AttributeError("You cannot add attributes to %s" % self)


def _swig_setattr(self, class_type, name, value):
    return _swig_setattr_nondynamic(self, class_type, name, value, 0)


def _swig_getattr(self, class_type, name):
    if (name == "thisown"):
        return self.this.own()
    method = class_type.__swig_getmethods__.get(name, None)
    if method:
        return method(self)
    raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name))


def _swig_repr(self):
    try:
        strthis = "proxy of " + self.this.__repr__()
    except __builtin__.Exception:
        strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)

try:
    _object = object
    _newclass = 1
except __builtin__.Exception:
    class _object:
        pass
    _newclass = 0

[文档]class SnowboyDetect(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, SnowboyDetect, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, SnowboyDetect, name) __repr__ = _swig_repr def __init__(self, resource_filename, model_str): this = _snowboydetect.new_SnowboyDetect(resource_filename, model_str) try: self.this.append(this) except __builtin__.Exception: self.this = this
[文档] def Reset(self): return _snowboydetect.SnowboyDetect_Reset(self)
[文档] def RunDetection(self, *args): return _snowboydetect.SnowboyDetect_RunDetection(self, *args)
[文档] def SetSensitivity(self, sensitivity_str): return _snowboydetect.SnowboyDetect_SetSensitivity(self, sensitivity_str)
[文档] def SetHighSensitivity(self, high_sensitivity_str): return _snowboydetect.SnowboyDetect_SetHighSensitivity(self, high_sensitivity_str)
[文档] def GetSensitivity(self): return _snowboydetect.SnowboyDetect_GetSensitivity(self)
[文档] def SetAudioGain(self, audio_gain): return _snowboydetect.SnowboyDetect_SetAudioGain(self, audio_gain)
[文档] def UpdateModel(self): return _snowboydetect.SnowboyDetect_UpdateModel(self)
[文档] def NumHotwords(self): return _snowboydetect.SnowboyDetect_NumHotwords(self)
[文档] def ApplyFrontend(self, apply_frontend): return _snowboydetect.SnowboyDetect_ApplyFrontend(self, apply_frontend)
[文档] def SampleRate(self): return _snowboydetect.SnowboyDetect_SampleRate(self)
[文档] def NumChannels(self): return _snowboydetect.SnowboyDetect_NumChannels(self)
[文档] def BitsPerSample(self): return _snowboydetect.SnowboyDetect_BitsPerSample(self)
__swig_destroy__ = _snowboydetect.delete_SnowboyDetect __del__ = lambda self: None
SnowboyDetect_swigregister = _snowboydetect.SnowboyDetect_swigregister SnowboyDetect_swigregister(SnowboyDetect)
[文档]class SnowboyVad(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, SnowboyVad, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, SnowboyVad, name) __repr__ = _swig_repr def __init__(self, resource_filename): this = _snowboydetect.new_SnowboyVad(resource_filename) try: self.this.append(this) except __builtin__.Exception: self.this = this
[文档] def Reset(self): return _snowboydetect.SnowboyVad_Reset(self)
[文档] def RunVad(self, *args): return _snowboydetect.SnowboyVad_RunVad(self, *args)
[文档] def SetAudioGain(self, audio_gain): return _snowboydetect.SnowboyVad_SetAudioGain(self, audio_gain)
[文档] def ApplyFrontend(self, apply_frontend): return _snowboydetect.SnowboyVad_ApplyFrontend(self, apply_frontend)
[文档] def SampleRate(self): return _snowboydetect.SnowboyVad_SampleRate(self)
[文档] def NumChannels(self): return _snowboydetect.SnowboyVad_NumChannels(self)
[文档] def BitsPerSample(self): return _snowboydetect.SnowboyVad_BitsPerSample(self)
__swig_destroy__ = _snowboydetect.delete_SnowboyVad __del__ = lambda self: None
SnowboyVad_swigregister = _snowboydetect.SnowboyVad_swigregister SnowboyVad_swigregister(SnowboyVad) # This file is compatible with both classic and new-style classes.
================================================ FILE: docs/_modules/wukong.html ================================================ wukong — wukong-robot 1.2.0 文档

wukong 源代码

# -*- coding: utf-8-*-
from snowboy import snowboydecoder
from robot import config, utils, constants, logging, statistic, Player
from robot.Updater import Updater
from robot.ConfigMonitor import ConfigMonitor
from robot.Conversation import Conversation
from server import server
from watchdog.observers import Observer
import sys
import os
import signal
import hashlib
import fire
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

logger = logging.getLogger(__name__)

[文档]class Wukong(object): _profiling = False _dev = False
[文档] def init(self): global conversation self.detector = None self._interrupted = False print(''' ******************************************************** * wukong-robot - 中文语音对话机器人 * * (c) 2019 潘伟洲 <m@hahack.com> * * https://github.com/wzpan/wukong-robot.git * ******************************************************** 如需退出,可以按 Ctrl-4 组合键。 ''') config.init() self._conversation = Conversation(self._profiling) self._conversation.say('{} 你好!试试对我喊唤醒词叫醒我吧'.format(config.get('first_name', '主人')), True) self._observer = Observer() event_handler = ConfigMonitor(self._conversation) self._observer.schedule(event_handler, constants.CONFIG_PATH, False) self._observer.schedule(event_handler, constants.DATA_PATH, False) self._observer.start()
def _signal_handler(self, signal, frame): self._interrupted = True utils.clean() self._observer.stop() def _detected_callback(self): if not utils.is_proper_time(): logger.warning('勿扰模式开启中') return if self._conversation.isRecording: logger.warning('正在录音中,跳过') return Player.play(constants.getData('beep_hi.wav')) logger.info('开始录音') self._conversation.interrupt() self._conversation.isRecording = True; def _do_not_bother_on_callback(self): if config.get('/do_not_bother/hotword_switch', False): utils.do_not_bother = True Player.play(constants.getData('off.wav')) logger.info('勿扰模式打开') def _do_not_bother_off_callback(self): if config.get('/do_not_bother/hotword_switch', False): utils.do_not_bother = False Player.play(constants.getData('on.wav')) logger.info('勿扰模式关闭') def _interrupt_callback(self): return self._interrupted
[文档] def run(self): self.init() # capture SIGINT signal, e.g., Ctrl+C signal.signal(signal.SIGINT, self._signal_handler) # site server.run(self._conversation, self) statistic.report(0) try: self.initDetector() except AttributeError: logger.error('初始化离线唤醒功能失败') pass
[文档] def initDetector(self): if self.detector is not None: self.detector.terminate() if config.get('/do_not_bother/hotword_switch', False): models = [ constants.getHotwordModel(config.get('hotword', 'wukong.pmdl')), constants.getHotwordModel(utils.get_do_not_bother_on_hotword()), constants.getHotwordModel(utils.get_do_not_bother_off_hotword()) ] else: models = constants.getHotwordModel(config.get('hotword', 'wukong.pmdl')) self.detector = snowboydecoder.HotwordDetector(models, sensitivity=config.get('sensitivity', 0.5)) # main loop try: if config.get('/do_not_bother/hotword_switch', False): callbacks = [self._detected_callback, self._do_not_bother_on_callback, self._do_not_bother_off_callback] else: callbacks = self._detected_callback self.detector.start(detected_callback=callbacks, audio_recorder_callback=self._conversation.converse, interrupt_check=self._interrupt_callback, silent_count_threshold=config.get('silent_threshold', 15), recording_timeout=config.get('recording_timeout', 5) * 4, sleep_time=0.03) self.detector.terminate() except Exception as e: logger.critical('离线唤醒机制初始化失败:{}'.format(e))
[文档] def md5(self, password): return hashlib.md5(password.encode('utf-8')).hexdigest()
[文档] def update(self): updater = Updater() return updater.update()
[文档] def fetch(self): updater = Updater() updater.fetch()
[文档] def restart(self): logger.critical('程序重启...') try: self.detector.terminate() except AttributeError: pass python = sys.executable os.execl(python, python, * sys.argv)
[文档] def profiling(self): logger.info('性能调优') self._profiling = True self.run()
[文档] def dev(self): logger.info('使用测试环境') self._dev = True self.run()
if __name__ == '__main__': if len(sys.argv) == 1: wukong = Wukong() wukong.run() else: fire.Fire(Wukong)
================================================ FILE: docs/_sources/AI.rst.txt ================================================ AI module ========= .. automodule:: AI :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/ASR.rst.txt ================================================ ASR module ========== .. automodule:: ASR :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/Brain.rst.txt ================================================ Brain module ============ .. automodule:: Brain :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/ConfigMonitor.rst.txt ================================================ ConfigMonitor module ==================== .. automodule:: ConfigMonitor :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/Conversation.rst.txt ================================================ Conversation module =================== .. automodule:: Conversation :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/Player.rst.txt ================================================ Player module ============= .. automodule:: Player :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/TTS.rst.txt ================================================ TTS module ========== .. automodule:: TTS :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/Updater.rst.txt ================================================ Updater module ============== .. automodule:: Updater :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/config.rst.txt ================================================ config module ============= .. automodule:: config :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/constants.rst.txt ================================================ constants module ================ .. automodule:: constants :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/drivers.rst.txt ================================================ drivers package =============== Submodules ---------- drivers.apa102 module --------------------- .. automodule:: drivers.apa102 :members: :undoc-members: :show-inheritance: drivers.pixels module --------------------- .. automodule:: drivers.pixels :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: drivers :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/index.rst.txt ================================================ .. wukong-robot documentation master file, created by sphinx-quickstart on Sun Feb 17 01:03:29 2019. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to wukong-robot's documentation! ======================================== .. toctree:: :maxdepth: 2 :caption: Contents: .. automodule:: wukong :members: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` ================================================ FILE: docs/_sources/logging.rst.txt ================================================ logging module ============== .. automodule:: logging :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/modules.rst.txt ================================================ wukong-robot ============ .. toctree:: :maxdepth: 4 plugins robot snowboy wukong ================================================ FILE: docs/_sources/plugin_loader.rst.txt ================================================ plugin\_loader module ===================== .. automodule:: plugin_loader :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/plugins.rst.txt ================================================ plugins package =============== Submodules ---------- plugins.Camera module --------------------- .. automodule:: plugins.Camera :members: :undoc-members: :show-inheritance: plugins.CleanCache module ------------------------- .. automodule:: plugins.CleanCache :members: :undoc-members: :show-inheritance: plugins.Echo module ------------------- .. automodule:: plugins.Echo :members: :undoc-members: :show-inheritance: plugins.Email module -------------------- .. automodule:: plugins.Email :members: :undoc-members: :show-inheritance: plugins.Geek module ------------------- .. automodule:: plugins.Geek :members: :undoc-members: :show-inheritance: plugins.LocalPlayer module -------------------------- .. automodule:: plugins.LocalPlayer :members: :undoc-members: :show-inheritance: plugins.Poem module ------------------- .. automodule:: plugins.Poem :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: plugins :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/robot.drivers.rst.txt ================================================ robot.drivers package ===================== Submodules ---------- robot.drivers.apa102 module --------------------------- .. automodule:: robot.drivers.apa102 :members: :undoc-members: :show-inheritance: robot.drivers.pixels module --------------------------- .. automodule:: robot.drivers.pixels :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: robot.drivers :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/robot.rst.txt ================================================ robot package ============= Subpackages ----------- .. toctree:: robot.sdk Submodules ---------- robot.AI module --------------- .. automodule:: robot.AI :members: :undoc-members: :show-inheritance: robot.ASR module ---------------- .. automodule:: robot.ASR :members: :undoc-members: :show-inheritance: robot.Brain module ------------------ .. automodule:: robot.Brain :members: :undoc-members: :show-inheritance: robot.ConfigMonitor module -------------------------- .. automodule:: robot.ConfigMonitor :members: :undoc-members: :show-inheritance: robot.Conversation module ------------------------- .. automodule:: robot.Conversation :members: :undoc-members: :show-inheritance: robot.NLU module ---------------- .. automodule:: robot.NLU :members: :undoc-members: :show-inheritance: robot.Player module ------------------- .. automodule:: robot.Player :members: :undoc-members: :show-inheritance: robot.TTS module ---------------- .. automodule:: robot.TTS :members: :undoc-members: :show-inheritance: robot.Updater module -------------------- .. automodule:: robot.Updater :members: :undoc-members: :show-inheritance: robot.config module ------------------- .. automodule:: robot.config :members: :undoc-members: :show-inheritance: robot.constants module ---------------------- .. automodule:: robot.constants :members: :undoc-members: :show-inheritance: robot.logging module -------------------- .. automodule:: robot.logging :members: :undoc-members: :show-inheritance: robot.plugin\_loader module --------------------------- .. automodule:: robot.plugin_loader :members: :undoc-members: :show-inheritance: robot.statistic module ---------------------- .. automodule:: robot.statistic :members: :undoc-members: :show-inheritance: robot.utils module ------------------ .. automodule:: robot.utils :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: robot :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/robot.sdk.rst.txt ================================================ robot.sdk package ================= Submodules ---------- robot.sdk.AbstractPlugin module ------------------------------- .. automodule:: robot.sdk.AbstractPlugin :members: :undoc-members: :show-inheritance: robot.sdk.AliSpeech module -------------------------- .. automodule:: robot.sdk.AliSpeech :members: :undoc-members: :show-inheritance: robot.sdk.RASRsdk module ------------------------ .. automodule:: robot.sdk.RASRsdk :members: :undoc-members: :show-inheritance: robot.sdk.TencentSpeech module ------------------------------ .. automodule:: robot.sdk.TencentSpeech :members: :undoc-members: :show-inheritance: robot.sdk.XunfeiSpeech module ----------------------------- .. automodule:: robot.sdk.XunfeiSpeech :members: :undoc-members: :show-inheritance: robot.sdk.unit module --------------------- .. automodule:: robot.sdk.unit :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: robot.sdk :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/snowboy.rst.txt ================================================ snowboy package =============== Submodules ---------- snowboy.snowboydecoder module ----------------------------- .. automodule:: snowboy.snowboydecoder :members: :undoc-members: :show-inheritance: snowboy.snowboydetect module ---------------------------- .. automodule:: snowboy.snowboydetect :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: snowboy :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/statistic.rst.txt ================================================ statistic module ================ .. automodule:: statistic :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/utils.rst.txt ================================================ utils module ============ .. automodule:: utils :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_sources/wukong.rst.txt ================================================ wukong module ============= .. automodule:: wukong :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/_static/alabaster.css ================================================ @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ body { font-family: Georgia, serif; font-size: 17px; background-color: #fff; color: #000; margin: 0; padding: 0; } div.document { width: 940px; margin: 30px auto 0 auto; } div.documentwrapper { float: left; width: 100%; } div.bodywrapper { margin: 0 0 0 220px; } div.sphinxsidebar { width: 220px; font-size: 14px; line-height: 1.5; } hr { border: 1px solid #B1B4B6; } div.body { background-color: #fff; color: #3E4349; padding: 0 30px 0 30px; } div.body > .section { text-align: left; } div.footer { width: 940px; margin: 20px auto 30px auto; font-size: 14px; color: #888; text-align: right; } div.footer a { color: #888; } p.caption { font-family: inherit; font-size: inherit; } div.relations { display: none; } div.sphinxsidebar a { color: #444; text-decoration: none; border-bottom: 1px dotted #999; } div.sphinxsidebar a:hover { border-bottom: 1px solid #999; } div.sphinxsidebarwrapper { padding: 18px 10px; } div.sphinxsidebarwrapper p.logo { padding: 0; margin: -10px 0 0 0px; text-align: center; } div.sphinxsidebarwrapper h1.logo { margin-top: -10px; text-align: center; margin-bottom: 5px; text-align: left; } div.sphinxsidebarwrapper h1.logo-name { margin-top: 0px; } div.sphinxsidebarwrapper p.blurb { margin-top: 0; font-style: normal; } div.sphinxsidebar h3, div.sphinxsidebar h4 { font-family: Georgia, serif; color: #444; font-size: 24px; font-weight: normal; margin: 0 0 5px 0; padding: 0; } div.sphinxsidebar h4 { font-size: 20px; } div.sphinxsidebar h3 a { color: #444; } div.sphinxsidebar p.logo a, div.sphinxsidebar h3 a, div.sphinxsidebar p.logo a:hover, div.sphinxsidebar h3 a:hover { border: none; } div.sphinxsidebar p { color: #555; margin: 10px 0; } div.sphinxsidebar ul { margin: 10px 0; padding: 0; color: #000; } div.sphinxsidebar ul li.toctree-l1 > a { font-size: 120%; } div.sphinxsidebar ul li.toctree-l2 > a { font-size: 110%; } div.sphinxsidebar input { border: 1px solid #CCC; font-family: Georgia, serif; font-size: 1em; } div.sphinxsidebar hr { border: none; height: 1px; color: #AAA; background: #AAA; text-align: left; margin-left: 0; width: 50%; } div.sphinxsidebar .badge { border-bottom: none; } div.sphinxsidebar .badge:hover { border-bottom: none; } /* To address an issue with donation coming after search */ div.sphinxsidebar h3.donation { margin-top: 10px; } /* -- body styles ----------------------------------------------------------- */ a { color: #004B6B; text-decoration: underline; } a:hover { color: #6D4100; text-decoration: underline; } div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6 { font-family: Georgia, serif; font-weight: normal; margin: 30px 0px 10px 0px; padding: 0; } div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } div.body h2 { font-size: 180%; } div.body h3 { font-size: 150%; } div.body h4 { font-size: 130%; } div.body h5 { font-size: 100%; } div.body h6 { font-size: 100%; } a.headerlink { color: #DDD; padding: 0 4px; text-decoration: none; } a.headerlink:hover { color: #444; background: #EAEAEA; } div.body p, div.body dd, div.body li { line-height: 1.4em; } div.admonition { margin: 20px 0px; padding: 10px 30px; background-color: #EEE; border: 1px solid #CCC; } div.admonition tt.xref, div.admonition code.xref, div.admonition a tt { background-color: #FBFBFB; border-bottom: 1px solid #fafafa; } div.admonition p.admonition-title { font-family: Georgia, serif; font-weight: normal; font-size: 24px; margin: 0 0 10px 0; padding: 0; line-height: 1; } div.admonition p.last { margin-bottom: 0; } div.highlight { background-color: #fff; } dt:target, .highlight { background: #FAF3E8; } div.warning { background-color: #FCC; border: 1px solid #FAA; } div.danger { background-color: #FCC; border: 1px solid #FAA; -moz-box-shadow: 2px 2px 4px #D52C2C; -webkit-box-shadow: 2px 2px 4px #D52C2C; box-shadow: 2px 2px 4px #D52C2C; } div.error { background-color: #FCC; border: 1px solid #FAA; -moz-box-shadow: 2px 2px 4px #D52C2C; -webkit-box-shadow: 2px 2px 4px #D52C2C; box-shadow: 2px 2px 4px #D52C2C; } div.caution { background-color: #FCC; border: 1px solid #FAA; } div.attention { background-color: #FCC; border: 1px solid #FAA; } div.important { background-color: #EEE; border: 1px solid #CCC; } div.note { background-color: #EEE; border: 1px solid #CCC; } div.tip { background-color: #EEE; border: 1px solid #CCC; } div.hint { background-color: #EEE; border: 1px solid #CCC; } div.seealso { background-color: #EEE; border: 1px solid #CCC; } div.topic { background-color: #EEE; } p.admonition-title { display: inline; } p.admonition-title:after { content: ":"; } pre, tt, code { font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; font-size: 0.9em; } .hll { background-color: #FFC; margin: 0 -12px; padding: 0 12px; display: block; } img.screenshot { } tt.descname, tt.descclassname, code.descname, code.descclassname { font-size: 0.95em; } tt.descname, code.descname { padding-right: 0.08em; } img.screenshot { -moz-box-shadow: 2px 2px 4px #EEE; -webkit-box-shadow: 2px 2px 4px #EEE; box-shadow: 2px 2px 4px #EEE; } table.docutils { border: 1px solid #888; -moz-box-shadow: 2px 2px 4px #EEE; -webkit-box-shadow: 2px 2px 4px #EEE; box-shadow: 2px 2px 4px #EEE; } table.docutils td, table.docutils th { border: 1px solid #888; padding: 0.25em 0.7em; } table.field-list, table.footnote { border: none; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } table.footnote { margin: 15px 0; width: 100%; border: 1px solid #EEE; background: #FDFDFD; font-size: 0.9em; } table.footnote + table.footnote { margin-top: -15px; border-top: none; } table.field-list th { padding: 0 0.8em 0 0; } table.field-list td { padding: 0; } table.field-list p { margin-bottom: 0.8em; } /* Cloned from * https://github.com/sphinx-doc/sphinx/commit/ef60dbfce09286b20b7385333d63a60321784e68 */ .field-name { -moz-hyphens: manual; -ms-hyphens: manual; -webkit-hyphens: manual; hyphens: manual; } table.footnote td.label { width: .1px; padding: 0.3em 0 0.3em 0.5em; } table.footnote td { padding: 0.3em 0.5em; } dl { margin: 0; padding: 0; } dl dd { margin-left: 30px; } blockquote { margin: 0 0 0 30px; padding: 0; } ul, ol { /* Matches the 30px from the narrow-screen "li > ul" selector below */ margin: 10px 0 10px 30px; padding: 0; } pre { background: #EEE; padding: 7px 30px; margin: 15px 0px; line-height: 1.3em; } div.viewcode-block:target { background: #ffd; } dl pre, blockquote pre, li pre { margin-left: 0; padding-left: 30px; } tt, code { background-color: #ecf0f3; color: #222; /* padding: 1px 2px; */ } tt.xref, code.xref, a tt { background-color: #FBFBFB; border-bottom: 1px solid #fff; } a.reference { text-decoration: none; border-bottom: 1px dotted #004B6B; } /* Don't put an underline on images */ a.image-reference, a.image-reference:hover { border-bottom: none; } a.reference:hover { border-bottom: 1px solid #6D4100; } a.footnote-reference { text-decoration: none; font-size: 0.7em; vertical-align: top; border-bottom: 1px dotted #004B6B; } a.footnote-reference:hover { border-bottom: 1px solid #6D4100; } a:hover tt, a:hover code { background: #EEE; } @media screen and (max-width: 870px) { div.sphinxsidebar { display: none; } div.document { width: 100%; } div.documentwrapper { margin-left: 0; margin-top: 0; margin-right: 0; margin-bottom: 0; } div.bodywrapper { margin-top: 0; margin-right: 0; margin-bottom: 0; margin-left: 0; } ul { margin-left: 0; } li > ul { /* Matches the 30px from the "ul, ol" selector above */ margin-left: 30px; } .document { width: auto; } .footer { width: auto; } .bodywrapper { margin: 0; } .footer { width: auto; } .github { display: none; } } @media screen and (max-width: 875px) { body { margin: 0; padding: 20px 30px; } div.documentwrapper { float: none; background: #fff; } div.sphinxsidebar { display: block; float: none; width: 102.5%; margin: 50px -30px -20px -30px; padding: 10px 20px; background: #333; color: #FFF; } div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, div.sphinxsidebar h3 a { color: #fff; } div.sphinxsidebar a { color: #AAA; } div.sphinxsidebar p.logo { display: none; } div.document { width: 100%; margin: 0; } div.footer { display: none; } div.bodywrapper { margin: 0; } div.body { min-height: 0; padding: 0; } .rtd_doc_footer { display: none; } .document { width: auto; } .footer { width: auto; } .footer { width: auto; } .github { display: none; } } /* misc. */ .revsys-inline { display: none!important; } /* Make nested-list/multi-paragraph items look better in Releases changelog * pages. Without this, docutils' magical list fuckery causes inconsistent * formatting between different release sub-lists. */ div#changelog > div.section > ul > li > p:only-child { margin-bottom: 0; } /* Hide fugly table cell borders in ..bibliography:: directive output */ table.docutils.citation, table.docutils.citation td, table.docutils.citation th { border: none; /* Below needed in some edge cases; if not applied, bottom shadows appear */ -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; } /* relbar */ .related { line-height: 30px; width: 100%; font-size: 0.9rem; } .related.top { border-bottom: 1px solid #EEE; margin-bottom: 20px; } .related.bottom { border-top: 1px solid #EEE; } .related ul { padding: 0; margin: 0; list-style: none; } .related li { display: inline; } nav#rellinks { float: right; } nav#rellinks li+li:before { content: "|"; } nav#breadcrumbs li+li:before { content: "\00BB"; } /* Hide certain items when printing */ @media print { div.related { display: none; } } ================================================ FILE: docs/_static/basic.css ================================================ /* * basic.css * ~~~~~~~~~ * * Sphinx stylesheet -- basic theme. * * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /* -- main layout ----------------------------------------------------------- */ div.clearer { clear: both; } /* -- relbar ---------------------------------------------------------------- */ div.related { width: 100%; font-size: 90%; } div.related h3 { display: none; } div.related ul { margin: 0; padding: 0 0 0 10px; list-style: none; } div.related li { display: inline; } div.related li.right { float: right; margin-right: 5px; } /* -- sidebar --------------------------------------------------------------- */ div.sphinxsidebarwrapper { padding: 10px 5px 0 10px; } div.sphinxsidebar { float: left; width: 230px; margin-left: -100%; font-size: 90%; word-wrap: break-word; overflow-wrap : break-word; } div.sphinxsidebar ul { list-style: none; } div.sphinxsidebar ul ul, div.sphinxsidebar ul.want-points { margin-left: 20px; list-style: square; } div.sphinxsidebar ul ul { margin-top: 0; margin-bottom: 0; } div.sphinxsidebar form { margin-top: 10px; } div.sphinxsidebar input { border: 1px solid #98dbcc; font-family: sans-serif; font-size: 1em; } div.sphinxsidebar #searchbox form.search { overflow: hidden; } div.sphinxsidebar #searchbox input[type="text"] { float: left; width: 80%; padding: 0.25em; box-sizing: border-box; } div.sphinxsidebar #searchbox input[type="submit"] { float: left; width: 20%; border-left: none; padding: 0.25em; box-sizing: border-box; } img { border: 0; max-width: 100%; } /* -- search page ----------------------------------------------------------- */ ul.search { margin: 10px 0 0 20px; padding: 0; } ul.search li { padding: 5px 0 5px 20px; background-image: url(file.png); background-repeat: no-repeat; background-position: 0 7px; } ul.search li a { font-weight: bold; } ul.search li div.context { color: #888; margin: 2px 0 0 30px; text-align: left; } ul.keywordmatches li.goodmatch a { font-weight: bold; } /* -- index page ------------------------------------------------------------ */ table.contentstable { width: 90%; margin-left: auto; margin-right: auto; } table.contentstable p.biglink { line-height: 150%; } a.biglink { font-size: 1.3em; } span.linkdescr { font-style: italic; padding-top: 5px; font-size: 90%; } /* -- general index --------------------------------------------------------- */ table.indextable { width: 100%; } table.indextable td { text-align: left; vertical-align: top; } table.indextable ul { margin-top: 0; margin-bottom: 0; list-style-type: none; } table.indextable > tbody > tr > td > ul { padding-left: 0em; } table.indextable tr.pcap { height: 10px; } table.indextable tr.cap { margin-top: 10px; background-color: #f2f2f2; } img.toggler { margin-right: 3px; margin-top: 3px; cursor: pointer; } div.modindex-jumpbox { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; margin: 1em 0 1em 0; padding: 0.4em; } div.genindex-jumpbox { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; margin: 1em 0 1em 0; padding: 0.4em; } /* -- domain module index --------------------------------------------------- */ table.modindextable td { padding: 2px; border-collapse: collapse; } /* -- general body styles --------------------------------------------------- */ div.body { min-width: 450px; max-width: 800px; } div.body p, div.body dd, div.body li, div.body blockquote { -moz-hyphens: auto; -ms-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } a.headerlink { visibility: hidden; } h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink, caption:hover > a.headerlink, p.caption:hover > a.headerlink, div.code-block-caption:hover > a.headerlink { visibility: visible; } div.body p.caption { text-align: inherit; } div.body td { text-align: left; } .first { margin-top: 0 !important; } p.rubric { margin-top: 30px; font-weight: bold; } img.align-left, .figure.align-left, object.align-left { clear: left; float: left; margin-right: 1em; } img.align-right, .figure.align-right, object.align-right { clear: right; float: right; margin-left: 1em; } img.align-center, .figure.align-center, object.align-center { display: block; margin-left: auto; margin-right: auto; } .align-left { text-align: left; } .align-center { text-align: center; } .align-right { text-align: right; } /* -- sidebars -------------------------------------------------------------- */ div.sidebar { margin: 0 0 0.5em 1em; border: 1px solid #ddb; padding: 7px 7px 0 7px; background-color: #ffe; width: 40%; float: right; } p.sidebar-title { font-weight: bold; } /* -- topics ---------------------------------------------------------------- */ div.topic { border: 1px solid #ccc; padding: 7px 7px 0 7px; margin: 10px 0 10px 0; } p.topic-title { font-size: 1.1em; font-weight: bold; margin-top: 10px; } /* -- admonitions ----------------------------------------------------------- */ div.admonition { margin-top: 10px; margin-bottom: 10px; padding: 7px; } div.admonition dt { font-weight: bold; } div.admonition dl { margin-bottom: 0; } p.admonition-title { margin: 0px 10px 5px 0px; font-weight: bold; } div.body p.centered { text-align: center; margin-top: 25px; } /* -- tables ---------------------------------------------------------------- */ table.docutils { border: 0; border-collapse: collapse; } table.align-center { margin-left: auto; margin-right: auto; } table caption span.caption-number { font-style: italic; } table caption span.caption-text { } table.docutils td, table.docutils th { padding: 1px 8px 1px 5px; border-top: 0; border-left: 0; border-right: 0; border-bottom: 1px solid #aaa; } table.footnote td, table.footnote th { border: 0 !important; } th { text-align: left; padding-right: 5px; } table.citation { border-left: solid 1px gray; margin-left: 1px; } table.citation td { border-bottom: none; } /* -- figures --------------------------------------------------------------- */ div.figure { margin: 0.5em; padding: 0.5em; } div.figure p.caption { padding: 0.3em; } div.figure p.caption span.caption-number { font-style: italic; } div.figure p.caption span.caption-text { } /* -- field list styles ----------------------------------------------------- */ table.field-list td, table.field-list th { border: 0 !important; } .field-list ul { margin: 0; padding-left: 1em; } .field-list p { margin: 0; } .field-name { -moz-hyphens: manual; -ms-hyphens: manual; -webkit-hyphens: manual; hyphens: manual; } /* -- hlist styles ---------------------------------------------------------- */ table.hlist td { vertical-align: top; } /* -- other body styles ----------------------------------------------------- */ ol.arabic { list-style: decimal; } ol.loweralpha { list-style: lower-alpha; } ol.upperalpha { list-style: upper-alpha; } ol.lowerroman { list-style: lower-roman; } ol.upperroman { list-style: upper-roman; } dl { margin-bottom: 15px; } dd p { margin-top: 0px; } dd ul, dd table { margin-bottom: 10px; } dd { margin-top: 3px; margin-bottom: 10px; margin-left: 30px; } dt:target, span.highlighted { background-color: #fbe54e; } rect.highlighted { fill: #fbe54e; } dl.glossary dt { font-weight: bold; font-size: 1.1em; } .optional { font-size: 1.3em; } .sig-paren { font-size: larger; } .versionmodified { font-style: italic; } .system-message { background-color: #fda; padding: 5px; border: 3px solid red; } .footnote:target { background-color: #ffa; } .line-block { display: block; margin-top: 1em; margin-bottom: 1em; } .line-block .line-block { margin-top: 0; margin-bottom: 0; margin-left: 1.5em; } .guilabel, .menuselection { font-family: sans-serif; } .accelerator { text-decoration: underline; } .classifier { font-style: oblique; } abbr, acronym { border-bottom: dotted 1px; cursor: help; } /* -- code displays --------------------------------------------------------- */ pre { overflow: auto; overflow-y: hidden; /* fixes display issues on Chrome browsers */ } span.pre { -moz-hyphens: none; -ms-hyphens: none; -webkit-hyphens: none; hyphens: none; } td.linenos pre { padding: 5px 0px; border: 0; background-color: transparent; color: #aaa; } table.highlighttable { margin-left: 0.5em; } table.highlighttable td { padding: 0 0.5em 0 0.5em; } div.code-block-caption { padding: 2px 5px; font-size: small; } div.code-block-caption code { background-color: transparent; } div.code-block-caption + div > div.highlight > pre { margin-top: 0; } div.code-block-caption span.caption-number { padding: 0.1em 0.3em; font-style: italic; } div.code-block-caption span.caption-text { } div.literal-block-wrapper { padding: 1em 1em 0; } div.literal-block-wrapper div.highlight { margin: 0; } code.descname { background-color: transparent; font-weight: bold; font-size: 1.2em; } code.descclassname { background-color: transparent; } code.xref, a code { background-color: transparent; font-weight: bold; } h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { background-color: transparent; } .viewcode-link { float: right; } .viewcode-back { float: right; font-family: sans-serif; } div.viewcode-block:target { margin: -1px -10px; padding: 0 10px; } /* -- math display ---------------------------------------------------------- */ img.math { vertical-align: middle; } div.body div.math p { text-align: center; } span.eqno { float: right; } span.eqno a.headerlink { position: relative; left: 0px; z-index: 1; } div.math:hover a.headerlink { visibility: visible; } /* -- printout stylesheet --------------------------------------------------- */ @media print { div.document, div.documentwrapper, div.bodywrapper { margin: 0 !important; width: 100%; } div.sphinxsidebar, div.related, div.footer, #top-link { display: none; } } ================================================ FILE: docs/_static/css/badge_only.css ================================================ .fa:before{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:""}.clearfix:after{clear:both}@font-face{font-family:FontAwesome;font-weight:normal;font-style:normal;src:url("../fonts/fontawesome-webfont.eot");src:url("../fonts/fontawesome-webfont.eot?#iefix") format("embedded-opentype"),url("../fonts/fontawesome-webfont.woff") format("woff"),url("../fonts/fontawesome-webfont.ttf") format("truetype"),url("../fonts/fontawesome-webfont.svg#FontAwesome") format("svg")}.fa:before{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;text-decoration:inherit}a .fa{display:inline-block;text-decoration:inherit}li .fa{display:inline-block}li .fa-large:before,li .fa-large:before{width:1.875em}ul.fas{list-style-type:none;margin-left:2em;text-indent:-0.8em}ul.fas li .fa{width:.8em}ul.fas li .fa-large:before,ul.fas li .fa-large:before{vertical-align:baseline}.fa-book:before{content:""}.icon-book:before{content:""}.fa-caret-down:before{content:""}.icon-caret-down:before{content:""}.fa-caret-up:before{content:""}.icon-caret-up:before{content:""}.fa-caret-left:before{content:""}.icon-caret-left:before{content:""}.fa-caret-right:before{content:""}.icon-caret-right:before{content:""}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;z-index:400}.rst-versions a{color:#2980B9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27AE60;*zoom:1}.rst-versions .rst-current-version:before,.rst-versions .rst-current-version:after{display:table;content:""}.rst-versions .rst-current-version:after{clear:both}.rst-versions .rst-current-version .fa{color:#fcfcfc}.rst-versions .rst-current-version .fa-book{float:left}.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#E74C3C;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#F1C40F;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:gray;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:solid 1px #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge .fa-book{float:none}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book{float:left}.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge .rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width: 768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}} ================================================ FILE: docs/_static/css/theme.css ================================================ /* sphinx_rtd_theme version 0.4.3 | MIT license */ /* Built 20190212 16:02 */ *{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}[hidden]{display:none}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:hover,a:active{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}blockquote{margin:0}dfn{font-style:italic}ins{background:#ff9;color:#000;text-decoration:none}mark{background:#ff0;color:#000;font-style:italic;font-weight:bold}pre,code,.rst-content tt,.rst-content code,kbd,samp{font-family:monospace,serif;_font-family:"courier new",monospace;font-size:1em}pre{white-space:pre}q{quotes:none}q:before,q:after{content:"";content:none}small{font-size:85%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}ul,ol,dl{margin:0;padding:0;list-style:none;list-style-image:none}li{list-style:none}dd{margin:0}img{border:0;-ms-interpolation-mode:bicubic;vertical-align:middle;max-width:100%}svg:not(:root){overflow:hidden}figure{margin:0}form{margin:0}fieldset{border:0;margin:0;padding:0}label{cursor:pointer}legend{border:0;*margin-left:-7px;padding:0;white-space:normal}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}button,input{line-height:normal}button,input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button;*overflow:visible}button[disabled],input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0;*width:13px;*height:13px}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top;resize:vertical}table{border-collapse:collapse;border-spacing:0}td{vertical-align:top}.chromeframe{margin:.2em 0;background:#ccc;color:#000;padding:.2em 0}.ir{display:block;border:0;text-indent:-999em;overflow:hidden;background-color:transparent;background-repeat:no-repeat;text-align:left;direction:ltr;*line-height:0}.ir br{display:none}.hidden{display:none !important;visibility:hidden}.visuallyhidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.invisible{visibility:hidden}.relative{position:relative}big,small{font-size:100%}@media print{html,body,section{background:none !important}*{box-shadow:none !important;text-shadow:none !important;filter:none !important;-ms-filter:none !important}a,a:visited{text-decoration:underline}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:.5cm}p,h2,.rst-content .toctree-wrapper p.caption,h3{orphans:3;widows:3}h2,.rst-content .toctree-wrapper p.caption,h3{page-break-after:avoid}}.fa:before,.wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before,.rst-content .admonition-title:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content dl dt .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content table>caption .headerlink:before,.rst-content .code-block-caption .headerlink:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before,.icon:before,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-alert,.rst-content .note,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .warning,.rst-content .seealso,.rst-content .admonition-todo,.rst-content .admonition,.btn,input[type="text"],input[type="password"],input[type="email"],input[type="url"],input[type="date"],input[type="month"],input[type="time"],input[type="datetime"],input[type="datetime-local"],input[type="week"],input[type="number"],input[type="search"],input[type="tel"],input[type="color"],select,textarea,.wy-menu-vertical li.on a,.wy-menu-vertical li.current>a,.wy-side-nav-search>a,.wy-side-nav-search .wy-dropdown>a,.wy-nav-top a{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:""}.clearfix:after{clear:both}/*! * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) */@font-face{font-family:'FontAwesome';src:url("../fonts/fontawesome-webfont.eot?v=4.7.0");src:url("../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0") format("embedded-opentype"),url("../fonts/fontawesome-webfont.woff2?v=4.7.0") format("woff2"),url("../fonts/fontawesome-webfont.woff?v=4.7.0") format("woff"),url("../fonts/fontawesome-webfont.ttf?v=4.7.0") format("truetype"),url("../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular") format("svg");font-weight:normal;font-style:normal}.fa,.wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,.rst-content .admonition-title,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink,.rst-content .code-block-caption .headerlink,.rst-content tt.download span:first-child,.rst-content code.download span:first-child,.icon{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.3333333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.2857142857em;text-align:center}.fa-ul{padding-left:0;margin-left:2.1428571429em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.1428571429em;width:2.1428571429em;top:.1428571429em;text-align:center}.fa-li.fa-lg{left:-1.8571428571em}.fa-border{padding:.2em .25em .15em;border:solid 0.08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.wy-menu-vertical li span.fa-pull-left.toctree-expand,.wy-menu-vertical li.on a span.fa-pull-left.toctree-expand,.wy-menu-vertical li.current>a span.fa-pull-left.toctree-expand,.rst-content .fa-pull-left.admonition-title,.rst-content h1 .fa-pull-left.headerlink,.rst-content h2 .fa-pull-left.headerlink,.rst-content h3 .fa-pull-left.headerlink,.rst-content h4 .fa-pull-left.headerlink,.rst-content h5 .fa-pull-left.headerlink,.rst-content h6 .fa-pull-left.headerlink,.rst-content dl dt .fa-pull-left.headerlink,.rst-content p.caption .fa-pull-left.headerlink,.rst-content table>caption .fa-pull-left.headerlink,.rst-content .code-block-caption .fa-pull-left.headerlink,.rst-content tt.download span.fa-pull-left:first-child,.rst-content code.download span.fa-pull-left:first-child,.fa-pull-left.icon{margin-right:.3em}.fa.fa-pull-right,.wy-menu-vertical li span.fa-pull-right.toctree-expand,.wy-menu-vertical li.on a span.fa-pull-right.toctree-expand,.wy-menu-vertical li.current>a span.fa-pull-right.toctree-expand,.rst-content .fa-pull-right.admonition-title,.rst-content h1 .fa-pull-right.headerlink,.rst-content h2 .fa-pull-right.headerlink,.rst-content h3 .fa-pull-right.headerlink,.rst-content h4 .fa-pull-right.headerlink,.rst-content h5 .fa-pull-right.headerlink,.rst-content h6 .fa-pull-right.headerlink,.rst-content dl dt .fa-pull-right.headerlink,.rst-content p.caption .fa-pull-right.headerlink,.rst-content table>caption .fa-pull-right.headerlink,.rst-content .code-block-caption .fa-pull-right.headerlink,.rst-content tt.download span.fa-pull-right:first-child,.rst-content code.download span.fa-pull-right:first-child,.fa-pull-right.icon{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left,.wy-menu-vertical li span.pull-left.toctree-expand,.wy-menu-vertical li.on a span.pull-left.toctree-expand,.wy-menu-vertical li.current>a span.pull-left.toctree-expand,.rst-content .pull-left.admonition-title,.rst-content h1 .pull-left.headerlink,.rst-content h2 .pull-left.headerlink,.rst-content h3 .pull-left.headerlink,.rst-content h4 .pull-left.headerlink,.rst-content h5 .pull-left.headerlink,.rst-content h6 .pull-left.headerlink,.rst-content dl dt .pull-left.headerlink,.rst-content p.caption .pull-left.headerlink,.rst-content table>caption .pull-left.headerlink,.rst-content .code-block-caption .pull-left.headerlink,.rst-content tt.download span.pull-left:first-child,.rst-content code.download span.pull-left:first-child,.pull-left.icon{margin-right:.3em}.fa.pull-right,.wy-menu-vertical li span.pull-right.toctree-expand,.wy-menu-vertical li.on a span.pull-right.toctree-expand,.wy-menu-vertical li.current>a span.pull-right.toctree-expand,.rst-content .pull-right.admonition-title,.rst-content h1 .pull-right.headerlink,.rst-content h2 .pull-right.headerlink,.rst-content h3 .pull-right.headerlink,.rst-content h4 .pull-right.headerlink,.rst-content h5 .pull-right.headerlink,.rst-content h6 .pull-right.headerlink,.rst-content dl dt .pull-right.headerlink,.rst-content p.caption .pull-right.headerlink,.rst-content table>caption .pull-right.headerlink,.rst-content .code-block-caption .pull-right.headerlink,.rst-content tt.download span.pull-right:first-child,.rst-content code.download span.pull-right:first-child,.pull-right.icon{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:""}.fa-music:before{content:""}.fa-search:before,.icon-search:before{content:""}.fa-envelope-o:before{content:""}.fa-heart:before{content:""}.fa-star:before{content:""}.fa-star-o:before{content:""}.fa-user:before{content:""}.fa-film:before{content:""}.fa-th-large:before{content:""}.fa-th:before{content:""}.fa-th-list:before{content:""}.fa-check:before{content:""}.fa-remove:before,.fa-close:before,.fa-times:before{content:""}.fa-search-plus:before{content:""}.fa-search-minus:before{content:""}.fa-power-off:before{content:""}.fa-signal:before{content:""}.fa-gear:before,.fa-cog:before{content:""}.fa-trash-o:before{content:""}.fa-home:before,.icon-home:before{content:""}.fa-file-o:before{content:""}.fa-clock-o:before{content:""}.fa-road:before{content:""}.fa-download:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before{content:""}.fa-arrow-circle-o-down:before{content:""}.fa-arrow-circle-o-up:before{content:""}.fa-inbox:before{content:""}.fa-play-circle-o:before{content:""}.fa-rotate-right:before,.fa-repeat:before{content:""}.fa-refresh:before{content:""}.fa-list-alt:before{content:""}.fa-lock:before{content:""}.fa-flag:before{content:""}.fa-headphones:before{content:""}.fa-volume-off:before{content:""}.fa-volume-down:before{content:""}.fa-volume-up:before{content:""}.fa-qrcode:before{content:""}.fa-barcode:before{content:""}.fa-tag:before{content:""}.fa-tags:before{content:""}.fa-book:before,.icon-book:before{content:""}.fa-bookmark:before{content:""}.fa-print:before{content:""}.fa-camera:before{content:""}.fa-font:before{content:""}.fa-bold:before{content:""}.fa-italic:before{content:""}.fa-text-height:before{content:""}.fa-text-width:before{content:""}.fa-align-left:before{content:""}.fa-align-center:before{content:""}.fa-align-right:before{content:""}.fa-align-justify:before{content:""}.fa-list:before{content:""}.fa-dedent:before,.fa-outdent:before{content:""}.fa-indent:before{content:""}.fa-video-camera:before{content:""}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:""}.fa-pencil:before{content:""}.fa-map-marker:before{content:""}.fa-adjust:before{content:""}.fa-tint:before{content:""}.fa-edit:before,.fa-pencil-square-o:before{content:""}.fa-share-square-o:before{content:""}.fa-check-square-o:before{content:""}.fa-arrows:before{content:""}.fa-step-backward:before{content:""}.fa-fast-backward:before{content:""}.fa-backward:before{content:""}.fa-play:before{content:""}.fa-pause:before{content:""}.fa-stop:before{content:""}.fa-forward:before{content:""}.fa-fast-forward:before{content:""}.fa-step-forward:before{content:""}.fa-eject:before{content:""}.fa-chevron-left:before{content:""}.fa-chevron-right:before{content:""}.fa-plus-circle:before{content:""}.fa-minus-circle:before{content:""}.fa-times-circle:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before{content:""}.fa-check-circle:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before{content:""}.fa-question-circle:before{content:""}.fa-info-circle:before{content:""}.fa-crosshairs:before{content:""}.fa-times-circle-o:before{content:""}.fa-check-circle-o:before{content:""}.fa-ban:before{content:""}.fa-arrow-left:before{content:""}.fa-arrow-right:before{content:""}.fa-arrow-up:before{content:""}.fa-arrow-down:before{content:""}.fa-mail-forward:before,.fa-share:before{content:""}.fa-expand:before{content:""}.fa-compress:before{content:""}.fa-plus:before{content:""}.fa-minus:before{content:""}.fa-asterisk:before{content:""}.fa-exclamation-circle:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.rst-content .admonition-title:before{content:""}.fa-gift:before{content:""}.fa-leaf:before{content:""}.fa-fire:before,.icon-fire:before{content:""}.fa-eye:before{content:""}.fa-eye-slash:before{content:""}.fa-warning:before,.fa-exclamation-triangle:before{content:""}.fa-plane:before{content:""}.fa-calendar:before{content:""}.fa-random:before{content:""}.fa-comment:before{content:""}.fa-magnet:before{content:""}.fa-chevron-up:before{content:""}.fa-chevron-down:before{content:""}.fa-retweet:before{content:""}.fa-shopping-cart:before{content:""}.fa-folder:before{content:""}.fa-folder-open:before{content:""}.fa-arrows-v:before{content:""}.fa-arrows-h:before{content:""}.fa-bar-chart-o:before,.fa-bar-chart:before{content:""}.fa-twitter-square:before{content:""}.fa-facebook-square:before{content:""}.fa-camera-retro:before{content:""}.fa-key:before{content:""}.fa-gears:before,.fa-cogs:before{content:""}.fa-comments:before{content:""}.fa-thumbs-o-up:before{content:""}.fa-thumbs-o-down:before{content:""}.fa-star-half:before{content:""}.fa-heart-o:before{content:""}.fa-sign-out:before{content:""}.fa-linkedin-square:before{content:""}.fa-thumb-tack:before{content:""}.fa-external-link:before{content:""}.fa-sign-in:before{content:""}.fa-trophy:before{content:""}.fa-github-square:before{content:""}.fa-upload:before{content:""}.fa-lemon-o:before{content:""}.fa-phone:before{content:""}.fa-square-o:before{content:""}.fa-bookmark-o:before{content:""}.fa-phone-square:before{content:""}.fa-twitter:before{content:""}.fa-facebook-f:before,.fa-facebook:before{content:""}.fa-github:before,.icon-github:before{content:""}.fa-unlock:before{content:""}.fa-credit-card:before{content:""}.fa-feed:before,.fa-rss:before{content:""}.fa-hdd-o:before{content:""}.fa-bullhorn:before{content:""}.fa-bell:before{content:""}.fa-certificate:before{content:""}.fa-hand-o-right:before{content:""}.fa-hand-o-left:before{content:""}.fa-hand-o-up:before{content:""}.fa-hand-o-down:before{content:""}.fa-arrow-circle-left:before,.icon-circle-arrow-left:before{content:""}.fa-arrow-circle-right:before,.icon-circle-arrow-right:before{content:""}.fa-arrow-circle-up:before{content:""}.fa-arrow-circle-down:before{content:""}.fa-globe:before{content:""}.fa-wrench:before{content:""}.fa-tasks:before{content:""}.fa-filter:before{content:""}.fa-briefcase:before{content:""}.fa-arrows-alt:before{content:""}.fa-group:before,.fa-users:before{content:""}.fa-chain:before,.fa-link:before,.icon-link:before{content:""}.fa-cloud:before{content:""}.fa-flask:before{content:""}.fa-cut:before,.fa-scissors:before{content:""}.fa-copy:before,.fa-files-o:before{content:""}.fa-paperclip:before{content:""}.fa-save:before,.fa-floppy-o:before{content:""}.fa-square:before{content:""}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:""}.fa-list-ul:before{content:""}.fa-list-ol:before{content:""}.fa-strikethrough:before{content:""}.fa-underline:before{content:""}.fa-table:before{content:""}.fa-magic:before{content:""}.fa-truck:before{content:""}.fa-pinterest:before{content:""}.fa-pinterest-square:before{content:""}.fa-google-plus-square:before{content:""}.fa-google-plus:before{content:""}.fa-money:before{content:""}.fa-caret-down:before,.wy-dropdown .caret:before,.icon-caret-down:before{content:""}.fa-caret-up:before{content:""}.fa-caret-left:before{content:""}.fa-caret-right:before{content:""}.fa-columns:before{content:""}.fa-unsorted:before,.fa-sort:before{content:""}.fa-sort-down:before,.fa-sort-desc:before{content:""}.fa-sort-up:before,.fa-sort-asc:before{content:""}.fa-envelope:before{content:""}.fa-linkedin:before{content:""}.fa-rotate-left:before,.fa-undo:before{content:""}.fa-legal:before,.fa-gavel:before{content:""}.fa-dashboard:before,.fa-tachometer:before{content:""}.fa-comment-o:before{content:""}.fa-comments-o:before{content:""}.fa-flash:before,.fa-bolt:before{content:""}.fa-sitemap:before{content:""}.fa-umbrella:before{content:""}.fa-paste:before,.fa-clipboard:before{content:""}.fa-lightbulb-o:before{content:""}.fa-exchange:before{content:""}.fa-cloud-download:before{content:""}.fa-cloud-upload:before{content:""}.fa-user-md:before{content:""}.fa-stethoscope:before{content:""}.fa-suitcase:before{content:""}.fa-bell-o:before{content:""}.fa-coffee:before{content:""}.fa-cutlery:before{content:""}.fa-file-text-o:before{content:""}.fa-building-o:before{content:""}.fa-hospital-o:before{content:""}.fa-ambulance:before{content:""}.fa-medkit:before{content:""}.fa-fighter-jet:before{content:""}.fa-beer:before{content:""}.fa-h-square:before{content:""}.fa-plus-square:before{content:""}.fa-angle-double-left:before{content:""}.fa-angle-double-right:before{content:""}.fa-angle-double-up:before{content:""}.fa-angle-double-down:before{content:""}.fa-angle-left:before{content:""}.fa-angle-right:before{content:""}.fa-angle-up:before{content:""}.fa-angle-down:before{content:""}.fa-desktop:before{content:""}.fa-laptop:before{content:""}.fa-tablet:before{content:""}.fa-mobile-phone:before,.fa-mobile:before{content:""}.fa-circle-o:before{content:""}.fa-quote-left:before{content:""}.fa-quote-right:before{content:""}.fa-spinner:before{content:""}.fa-circle:before{content:""}.fa-mail-reply:before,.fa-reply:before{content:""}.fa-github-alt:before{content:""}.fa-folder-o:before{content:""}.fa-folder-open-o:before{content:""}.fa-smile-o:before{content:""}.fa-frown-o:before{content:""}.fa-meh-o:before{content:""}.fa-gamepad:before{content:""}.fa-keyboard-o:before{content:""}.fa-flag-o:before{content:""}.fa-flag-checkered:before{content:""}.fa-terminal:before{content:""}.fa-code:before{content:""}.fa-mail-reply-all:before,.fa-reply-all:before{content:""}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:""}.fa-location-arrow:before{content:""}.fa-crop:before{content:""}.fa-code-fork:before{content:""}.fa-unlink:before,.fa-chain-broken:before{content:""}.fa-question:before{content:""}.fa-info:before{content:""}.fa-exclamation:before{content:""}.fa-superscript:before{content:""}.fa-subscript:before{content:""}.fa-eraser:before{content:""}.fa-puzzle-piece:before{content:""}.fa-microphone:before{content:""}.fa-microphone-slash:before{content:""}.fa-shield:before{content:""}.fa-calendar-o:before{content:""}.fa-fire-extinguisher:before{content:""}.fa-rocket:before{content:""}.fa-maxcdn:before{content:""}.fa-chevron-circle-left:before{content:""}.fa-chevron-circle-right:before{content:""}.fa-chevron-circle-up:before{content:""}.fa-chevron-circle-down:before{content:""}.fa-html5:before{content:""}.fa-css3:before{content:""}.fa-anchor:before{content:""}.fa-unlock-alt:before{content:""}.fa-bullseye:before{content:""}.fa-ellipsis-h:before{content:""}.fa-ellipsis-v:before{content:""}.fa-rss-square:before{content:""}.fa-play-circle:before{content:""}.fa-ticket:before{content:""}.fa-minus-square:before{content:""}.fa-minus-square-o:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before{content:""}.fa-level-up:before{content:""}.fa-level-down:before{content:""}.fa-check-square:before{content:""}.fa-pencil-square:before{content:""}.fa-external-link-square:before{content:""}.fa-share-square:before{content:""}.fa-compass:before{content:""}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:""}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:""}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:""}.fa-euro:before,.fa-eur:before{content:""}.fa-gbp:before{content:""}.fa-dollar:before,.fa-usd:before{content:""}.fa-rupee:before,.fa-inr:before{content:""}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:""}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:""}.fa-won:before,.fa-krw:before{content:""}.fa-bitcoin:before,.fa-btc:before{content:""}.fa-file:before{content:""}.fa-file-text:before{content:""}.fa-sort-alpha-asc:before{content:""}.fa-sort-alpha-desc:before{content:""}.fa-sort-amount-asc:before{content:""}.fa-sort-amount-desc:before{content:""}.fa-sort-numeric-asc:before{content:""}.fa-sort-numeric-desc:before{content:""}.fa-thumbs-up:before{content:""}.fa-thumbs-down:before{content:""}.fa-youtube-square:before{content:""}.fa-youtube:before{content:""}.fa-xing:before{content:""}.fa-xing-square:before{content:""}.fa-youtube-play:before{content:""}.fa-dropbox:before{content:""}.fa-stack-overflow:before{content:""}.fa-instagram:before{content:""}.fa-flickr:before{content:""}.fa-adn:before{content:""}.fa-bitbucket:before,.icon-bitbucket:before{content:""}.fa-bitbucket-square:before{content:""}.fa-tumblr:before{content:""}.fa-tumblr-square:before{content:""}.fa-long-arrow-down:before{content:""}.fa-long-arrow-up:before{content:""}.fa-long-arrow-left:before{content:""}.fa-long-arrow-right:before{content:""}.fa-apple:before{content:""}.fa-windows:before{content:""}.fa-android:before{content:""}.fa-linux:before{content:""}.fa-dribbble:before{content:""}.fa-skype:before{content:""}.fa-foursquare:before{content:""}.fa-trello:before{content:""}.fa-female:before{content:""}.fa-male:before{content:""}.fa-gittip:before,.fa-gratipay:before{content:""}.fa-sun-o:before{content:""}.fa-moon-o:before{content:""}.fa-archive:before{content:""}.fa-bug:before{content:""}.fa-vk:before{content:""}.fa-weibo:before{content:""}.fa-renren:before{content:""}.fa-pagelines:before{content:""}.fa-stack-exchange:before{content:""}.fa-arrow-circle-o-right:before{content:""}.fa-arrow-circle-o-left:before{content:""}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:""}.fa-dot-circle-o:before{content:""}.fa-wheelchair:before{content:""}.fa-vimeo-square:before{content:""}.fa-turkish-lira:before,.fa-try:before{content:""}.fa-plus-square-o:before,.wy-menu-vertical li span.toctree-expand:before{content:""}.fa-space-shuttle:before{content:""}.fa-slack:before{content:""}.fa-envelope-square:before{content:""}.fa-wordpress:before{content:""}.fa-openid:before{content:""}.fa-institution:before,.fa-bank:before,.fa-university:before{content:""}.fa-mortar-board:before,.fa-graduation-cap:before{content:""}.fa-yahoo:before{content:""}.fa-google:before{content:""}.fa-reddit:before{content:""}.fa-reddit-square:before{content:""}.fa-stumbleupon-circle:before{content:""}.fa-stumbleupon:before{content:""}.fa-delicious:before{content:""}.fa-digg:before{content:""}.fa-pied-piper-pp:before{content:""}.fa-pied-piper-alt:before{content:""}.fa-drupal:before{content:""}.fa-joomla:before{content:""}.fa-language:before{content:""}.fa-fax:before{content:""}.fa-building:before{content:""}.fa-child:before{content:""}.fa-paw:before{content:""}.fa-spoon:before{content:""}.fa-cube:before{content:""}.fa-cubes:before{content:""}.fa-behance:before{content:""}.fa-behance-square:before{content:""}.fa-steam:before{content:""}.fa-steam-square:before{content:""}.fa-recycle:before{content:""}.fa-automobile:before,.fa-car:before{content:""}.fa-cab:before,.fa-taxi:before{content:""}.fa-tree:before{content:""}.fa-spotify:before{content:""}.fa-deviantart:before{content:""}.fa-soundcloud:before{content:""}.fa-database:before{content:""}.fa-file-pdf-o:before{content:""}.fa-file-word-o:before{content:""}.fa-file-excel-o:before{content:""}.fa-file-powerpoint-o:before{content:""}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:""}.fa-file-zip-o:before,.fa-file-archive-o:before{content:""}.fa-file-sound-o:before,.fa-file-audio-o:before{content:""}.fa-file-movie-o:before,.fa-file-video-o:before{content:""}.fa-file-code-o:before{content:""}.fa-vine:before{content:""}.fa-codepen:before{content:""}.fa-jsfiddle:before{content:""}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:""}.fa-circle-o-notch:before{content:""}.fa-ra:before,.fa-resistance:before,.fa-rebel:before{content:""}.fa-ge:before,.fa-empire:before{content:""}.fa-git-square:before{content:""}.fa-git:before{content:""}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:""}.fa-tencent-weibo:before{content:""}.fa-qq:before{content:""}.fa-wechat:before,.fa-weixin:before{content:""}.fa-send:before,.fa-paper-plane:before{content:""}.fa-send-o:before,.fa-paper-plane-o:before{content:""}.fa-history:before{content:""}.fa-circle-thin:before{content:""}.fa-header:before{content:""}.fa-paragraph:before{content:""}.fa-sliders:before{content:""}.fa-share-alt:before{content:""}.fa-share-alt-square:before{content:""}.fa-bomb:before{content:""}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:""}.fa-tty:before{content:""}.fa-binoculars:before{content:""}.fa-plug:before{content:""}.fa-slideshare:before{content:""}.fa-twitch:before{content:""}.fa-yelp:before{content:""}.fa-newspaper-o:before{content:""}.fa-wifi:before{content:""}.fa-calculator:before{content:""}.fa-paypal:before{content:""}.fa-google-wallet:before{content:""}.fa-cc-visa:before{content:""}.fa-cc-mastercard:before{content:""}.fa-cc-discover:before{content:""}.fa-cc-amex:before{content:""}.fa-cc-paypal:before{content:""}.fa-cc-stripe:before{content:""}.fa-bell-slash:before{content:""}.fa-bell-slash-o:before{content:""}.fa-trash:before{content:""}.fa-copyright:before{content:""}.fa-at:before{content:""}.fa-eyedropper:before{content:""}.fa-paint-brush:before{content:""}.fa-birthday-cake:before{content:""}.fa-area-chart:before{content:""}.fa-pie-chart:before{content:""}.fa-line-chart:before{content:""}.fa-lastfm:before{content:""}.fa-lastfm-square:before{content:""}.fa-toggle-off:before{content:""}.fa-toggle-on:before{content:""}.fa-bicycle:before{content:""}.fa-bus:before{content:""}.fa-ioxhost:before{content:""}.fa-angellist:before{content:""}.fa-cc:before{content:""}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:""}.fa-meanpath:before{content:""}.fa-buysellads:before{content:""}.fa-connectdevelop:before{content:""}.fa-dashcube:before{content:""}.fa-forumbee:before{content:""}.fa-leanpub:before{content:""}.fa-sellsy:before{content:""}.fa-shirtsinbulk:before{content:""}.fa-simplybuilt:before{content:""}.fa-skyatlas:before{content:""}.fa-cart-plus:before{content:""}.fa-cart-arrow-down:before{content:""}.fa-diamond:before{content:""}.fa-ship:before{content:""}.fa-user-secret:before{content:""}.fa-motorcycle:before{content:""}.fa-street-view:before{content:""}.fa-heartbeat:before{content:""}.fa-venus:before{content:""}.fa-mars:before{content:""}.fa-mercury:before{content:""}.fa-intersex:before,.fa-transgender:before{content:""}.fa-transgender-alt:before{content:""}.fa-venus-double:before{content:""}.fa-mars-double:before{content:""}.fa-venus-mars:before{content:""}.fa-mars-stroke:before{content:""}.fa-mars-stroke-v:before{content:""}.fa-mars-stroke-h:before{content:""}.fa-neuter:before{content:""}.fa-genderless:before{content:""}.fa-facebook-official:before{content:""}.fa-pinterest-p:before{content:""}.fa-whatsapp:before{content:""}.fa-server:before{content:""}.fa-user-plus:before{content:""}.fa-user-times:before{content:""}.fa-hotel:before,.fa-bed:before{content:""}.fa-viacoin:before{content:""}.fa-train:before{content:""}.fa-subway:before{content:""}.fa-medium:before{content:""}.fa-yc:before,.fa-y-combinator:before{content:""}.fa-optin-monster:before{content:""}.fa-opencart:before{content:""}.fa-expeditedssl:before{content:""}.fa-battery-4:before,.fa-battery:before,.fa-battery-full:before{content:""}.fa-battery-3:before,.fa-battery-three-quarters:before{content:""}.fa-battery-2:before,.fa-battery-half:before{content:""}.fa-battery-1:before,.fa-battery-quarter:before{content:""}.fa-battery-0:before,.fa-battery-empty:before{content:""}.fa-mouse-pointer:before{content:""}.fa-i-cursor:before{content:""}.fa-object-group:before{content:""}.fa-object-ungroup:before{content:""}.fa-sticky-note:before{content:""}.fa-sticky-note-o:before{content:""}.fa-cc-jcb:before{content:""}.fa-cc-diners-club:before{content:""}.fa-clone:before{content:""}.fa-balance-scale:before{content:""}.fa-hourglass-o:before{content:""}.fa-hourglass-1:before,.fa-hourglass-start:before{content:""}.fa-hourglass-2:before,.fa-hourglass-half:before{content:""}.fa-hourglass-3:before,.fa-hourglass-end:before{content:""}.fa-hourglass:before{content:""}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:""}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:""}.fa-hand-scissors-o:before{content:""}.fa-hand-lizard-o:before{content:""}.fa-hand-spock-o:before{content:""}.fa-hand-pointer-o:before{content:""}.fa-hand-peace-o:before{content:""}.fa-trademark:before{content:""}.fa-registered:before{content:""}.fa-creative-commons:before{content:""}.fa-gg:before{content:""}.fa-gg-circle:before{content:""}.fa-tripadvisor:before{content:""}.fa-odnoklassniki:before{content:""}.fa-odnoklassniki-square:before{content:""}.fa-get-pocket:before{content:""}.fa-wikipedia-w:before{content:""}.fa-safari:before{content:""}.fa-chrome:before{content:""}.fa-firefox:before{content:""}.fa-opera:before{content:""}.fa-internet-explorer:before{content:""}.fa-tv:before,.fa-television:before{content:""}.fa-contao:before{content:""}.fa-500px:before{content:""}.fa-amazon:before{content:""}.fa-calendar-plus-o:before{content:""}.fa-calendar-minus-o:before{content:""}.fa-calendar-times-o:before{content:""}.fa-calendar-check-o:before{content:""}.fa-industry:before{content:""}.fa-map-pin:before{content:""}.fa-map-signs:before{content:""}.fa-map-o:before{content:""}.fa-map:before{content:""}.fa-commenting:before{content:""}.fa-commenting-o:before{content:""}.fa-houzz:before{content:""}.fa-vimeo:before{content:""}.fa-black-tie:before{content:""}.fa-fonticons:before{content:""}.fa-reddit-alien:before{content:""}.fa-edge:before{content:""}.fa-credit-card-alt:before{content:""}.fa-codiepie:before{content:""}.fa-modx:before{content:""}.fa-fort-awesome:before{content:""}.fa-usb:before{content:""}.fa-product-hunt:before{content:""}.fa-mixcloud:before{content:""}.fa-scribd:before{content:""}.fa-pause-circle:before{content:""}.fa-pause-circle-o:before{content:""}.fa-stop-circle:before{content:""}.fa-stop-circle-o:before{content:""}.fa-shopping-bag:before{content:""}.fa-shopping-basket:before{content:""}.fa-hashtag:before{content:""}.fa-bluetooth:before{content:""}.fa-bluetooth-b:before{content:""}.fa-percent:before{content:""}.fa-gitlab:before,.icon-gitlab:before{content:""}.fa-wpbeginner:before{content:""}.fa-wpforms:before{content:""}.fa-envira:before{content:""}.fa-universal-access:before{content:""}.fa-wheelchair-alt:before{content:""}.fa-question-circle-o:before{content:""}.fa-blind:before{content:""}.fa-audio-description:before{content:""}.fa-volume-control-phone:before{content:""}.fa-braille:before{content:""}.fa-assistive-listening-systems:before{content:""}.fa-asl-interpreting:before,.fa-american-sign-language-interpreting:before{content:""}.fa-deafness:before,.fa-hard-of-hearing:before,.fa-deaf:before{content:""}.fa-glide:before{content:""}.fa-glide-g:before{content:""}.fa-signing:before,.fa-sign-language:before{content:""}.fa-low-vision:before{content:""}.fa-viadeo:before{content:""}.fa-viadeo-square:before{content:""}.fa-snapchat:before{content:""}.fa-snapchat-ghost:before{content:""}.fa-snapchat-square:before{content:""}.fa-pied-piper:before{content:""}.fa-first-order:before{content:""}.fa-yoast:before{content:""}.fa-themeisle:before{content:""}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:""}.fa-fa:before,.fa-font-awesome:before{content:""}.fa-handshake-o:before{content:""}.fa-envelope-open:before{content:""}.fa-envelope-open-o:before{content:""}.fa-linode:before{content:""}.fa-address-book:before{content:""}.fa-address-book-o:before{content:""}.fa-vcard:before,.fa-address-card:before{content:""}.fa-vcard-o:before,.fa-address-card-o:before{content:""}.fa-user-circle:before{content:""}.fa-user-circle-o:before{content:""}.fa-user-o:before{content:""}.fa-id-badge:before{content:""}.fa-drivers-license:before,.fa-id-card:before{content:""}.fa-drivers-license-o:before,.fa-id-card-o:before{content:""}.fa-quora:before{content:""}.fa-free-code-camp:before{content:""}.fa-telegram:before{content:""}.fa-thermometer-4:before,.fa-thermometer:before,.fa-thermometer-full:before{content:""}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:""}.fa-thermometer-2:before,.fa-thermometer-half:before{content:""}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:""}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:""}.fa-shower:before{content:""}.fa-bathtub:before,.fa-s15:before,.fa-bath:before{content:""}.fa-podcast:before{content:""}.fa-window-maximize:before{content:""}.fa-window-minimize:before{content:""}.fa-window-restore:before{content:""}.fa-times-rectangle:before,.fa-window-close:before{content:""}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:""}.fa-bandcamp:before{content:""}.fa-grav:before{content:""}.fa-etsy:before{content:""}.fa-imdb:before{content:""}.fa-ravelry:before{content:""}.fa-eercast:before{content:""}.fa-microchip:before{content:""}.fa-snowflake-o:before{content:""}.fa-superpowers:before{content:""}.fa-wpexplorer:before{content:""}.fa-meetup:before{content:""}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}.fa,.wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,.rst-content .admonition-title,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink,.rst-content .code-block-caption .headerlink,.rst-content tt.download span:first-child,.rst-content code.download span:first-child,.icon,.wy-dropdown .caret,.wy-inline-validate.wy-inline-validate-success .wy-input-context,.wy-inline-validate.wy-inline-validate-danger .wy-input-context,.wy-inline-validate.wy-inline-validate-warning .wy-input-context,.wy-inline-validate.wy-inline-validate-info .wy-input-context{font-family:inherit}.fa:before,.wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before,.rst-content .admonition-title:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content dl dt .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content table>caption .headerlink:before,.rst-content .code-block-caption .headerlink:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before,.icon:before,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before{font-family:"FontAwesome";display:inline-block;font-style:normal;font-weight:normal;line-height:1;text-decoration:inherit}a .fa,a .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li a span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,a .rst-content .admonition-title,.rst-content a .admonition-title,a .rst-content h1 .headerlink,.rst-content h1 a .headerlink,a .rst-content h2 .headerlink,.rst-content h2 a .headerlink,a .rst-content h3 .headerlink,.rst-content h3 a .headerlink,a .rst-content h4 .headerlink,.rst-content h4 a .headerlink,a .rst-content h5 .headerlink,.rst-content h5 a .headerlink,a .rst-content h6 .headerlink,.rst-content h6 a .headerlink,a .rst-content dl dt .headerlink,.rst-content dl dt a .headerlink,a .rst-content p.caption .headerlink,.rst-content p.caption a .headerlink,a .rst-content table>caption .headerlink,.rst-content table>caption a .headerlink,a .rst-content .code-block-caption .headerlink,.rst-content .code-block-caption a .headerlink,a .rst-content tt.download span:first-child,.rst-content tt.download a span:first-child,a .rst-content code.download span:first-child,.rst-content code.download a span:first-child,a .icon{display:inline-block;text-decoration:inherit}.btn .fa,.btn .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .btn span.toctree-expand,.btn .wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.on a .btn span.toctree-expand,.btn .wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.current>a .btn span.toctree-expand,.btn .rst-content .admonition-title,.rst-content .btn .admonition-title,.btn .rst-content h1 .headerlink,.rst-content h1 .btn .headerlink,.btn .rst-content h2 .headerlink,.rst-content h2 .btn .headerlink,.btn .rst-content h3 .headerlink,.rst-content h3 .btn .headerlink,.btn .rst-content h4 .headerlink,.rst-content h4 .btn .headerlink,.btn .rst-content h5 .headerlink,.rst-content h5 .btn .headerlink,.btn .rst-content h6 .headerlink,.rst-content h6 .btn .headerlink,.btn .rst-content dl dt .headerlink,.rst-content dl dt .btn .headerlink,.btn .rst-content p.caption .headerlink,.rst-content p.caption .btn .headerlink,.btn .rst-content table>caption .headerlink,.rst-content table>caption .btn .headerlink,.btn .rst-content .code-block-caption .headerlink,.rst-content .code-block-caption .btn .headerlink,.btn .rst-content tt.download span:first-child,.rst-content tt.download .btn span:first-child,.btn .rst-content code.download span:first-child,.rst-content code.download .btn span:first-child,.btn .icon,.nav .fa,.nav .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .nav span.toctree-expand,.nav .wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.on a .nav span.toctree-expand,.nav .wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.current>a .nav span.toctree-expand,.nav .rst-content .admonition-title,.rst-content .nav .admonition-title,.nav .rst-content h1 .headerlink,.rst-content h1 .nav .headerlink,.nav .rst-content h2 .headerlink,.rst-content h2 .nav .headerlink,.nav .rst-content h3 .headerlink,.rst-content h3 .nav .headerlink,.nav .rst-content h4 .headerlink,.rst-content h4 .nav .headerlink,.nav .rst-content h5 .headerlink,.rst-content h5 .nav .headerlink,.nav .rst-content h6 .headerlink,.rst-content h6 .nav .headerlink,.nav .rst-content dl dt .headerlink,.rst-content dl dt .nav .headerlink,.nav .rst-content p.caption .headerlink,.rst-content p.caption .nav .headerlink,.nav .rst-content table>caption .headerlink,.rst-content table>caption .nav .headerlink,.nav .rst-content .code-block-caption .headerlink,.rst-content .code-block-caption .nav .headerlink,.nav .rst-content tt.download span:first-child,.rst-content tt.download .nav span:first-child,.nav .rst-content code.download span:first-child,.rst-content code.download .nav span:first-child,.nav .icon{display:inline}.btn .fa.fa-large,.btn .wy-menu-vertical li span.fa-large.toctree-expand,.wy-menu-vertical li .btn span.fa-large.toctree-expand,.btn .rst-content .fa-large.admonition-title,.rst-content .btn .fa-large.admonition-title,.btn .rst-content h1 .fa-large.headerlink,.rst-content h1 .btn .fa-large.headerlink,.btn .rst-content h2 .fa-large.headerlink,.rst-content h2 .btn .fa-large.headerlink,.btn .rst-content h3 .fa-large.headerlink,.rst-content h3 .btn .fa-large.headerlink,.btn .rst-content h4 .fa-large.headerlink,.rst-content h4 .btn .fa-large.headerlink,.btn .rst-content h5 .fa-large.headerlink,.rst-content h5 .btn .fa-large.headerlink,.btn .rst-content h6 .fa-large.headerlink,.rst-content h6 .btn .fa-large.headerlink,.btn .rst-content dl dt .fa-large.headerlink,.rst-content dl dt .btn .fa-large.headerlink,.btn .rst-content p.caption .fa-large.headerlink,.rst-content p.caption .btn .fa-large.headerlink,.btn .rst-content table>caption .fa-large.headerlink,.rst-content table>caption .btn .fa-large.headerlink,.btn .rst-content .code-block-caption .fa-large.headerlink,.rst-content .code-block-caption .btn .fa-large.headerlink,.btn .rst-content tt.download span.fa-large:first-child,.rst-content tt.download .btn span.fa-large:first-child,.btn .rst-content code.download span.fa-large:first-child,.rst-content code.download .btn span.fa-large:first-child,.btn .fa-large.icon,.nav .fa.fa-large,.nav .wy-menu-vertical li span.fa-large.toctree-expand,.wy-menu-vertical li .nav span.fa-large.toctree-expand,.nav .rst-content .fa-large.admonition-title,.rst-content .nav .fa-large.admonition-title,.nav .rst-content h1 .fa-large.headerlink,.rst-content h1 .nav .fa-large.headerlink,.nav .rst-content h2 .fa-large.headerlink,.rst-content h2 .nav .fa-large.headerlink,.nav .rst-content h3 .fa-large.headerlink,.rst-content h3 .nav .fa-large.headerlink,.nav .rst-content h4 .fa-large.headerlink,.rst-content h4 .nav .fa-large.headerlink,.nav .rst-content h5 .fa-large.headerlink,.rst-content h5 .nav .fa-large.headerlink,.nav .rst-content h6 .fa-large.headerlink,.rst-content h6 .nav .fa-large.headerlink,.nav .rst-content dl dt .fa-large.headerlink,.rst-content dl dt .nav .fa-large.headerlink,.nav .rst-content p.caption .fa-large.headerlink,.rst-content p.caption .nav .fa-large.headerlink,.nav .rst-content table>caption .fa-large.headerlink,.rst-content table>caption .nav .fa-large.headerlink,.nav .rst-content .code-block-caption .fa-large.headerlink,.rst-content .code-block-caption .nav .fa-large.headerlink,.nav .rst-content tt.download span.fa-large:first-child,.rst-content tt.download .nav span.fa-large:first-child,.nav .rst-content code.download span.fa-large:first-child,.rst-content code.download .nav span.fa-large:first-child,.nav .fa-large.icon{line-height:.9em}.btn .fa.fa-spin,.btn .wy-menu-vertical li span.fa-spin.toctree-expand,.wy-menu-vertical li .btn span.fa-spin.toctree-expand,.btn .rst-content .fa-spin.admonition-title,.rst-content .btn .fa-spin.admonition-title,.btn .rst-content h1 .fa-spin.headerlink,.rst-content h1 .btn .fa-spin.headerlink,.btn .rst-content h2 .fa-spin.headerlink,.rst-content h2 .btn .fa-spin.headerlink,.btn .rst-content h3 .fa-spin.headerlink,.rst-content h3 .btn .fa-spin.headerlink,.btn .rst-content h4 .fa-spin.headerlink,.rst-content h4 .btn .fa-spin.headerlink,.btn .rst-content h5 .fa-spin.headerlink,.rst-content h5 .btn .fa-spin.headerlink,.btn .rst-content h6 .fa-spin.headerlink,.rst-content h6 .btn .fa-spin.headerlink,.btn .rst-content dl dt .fa-spin.headerlink,.rst-content dl dt .btn .fa-spin.headerlink,.btn .rst-content p.caption .fa-spin.headerlink,.rst-content p.caption .btn .fa-spin.headerlink,.btn .rst-content table>caption .fa-spin.headerlink,.rst-content table>caption .btn .fa-spin.headerlink,.btn .rst-content .code-block-caption .fa-spin.headerlink,.rst-content .code-block-caption .btn .fa-spin.headerlink,.btn .rst-content tt.download span.fa-spin:first-child,.rst-content tt.download .btn span.fa-spin:first-child,.btn .rst-content code.download span.fa-spin:first-child,.rst-content code.download .btn span.fa-spin:first-child,.btn .fa-spin.icon,.nav .fa.fa-spin,.nav .wy-menu-vertical li span.fa-spin.toctree-expand,.wy-menu-vertical li .nav span.fa-spin.toctree-expand,.nav .rst-content .fa-spin.admonition-title,.rst-content .nav .fa-spin.admonition-title,.nav .rst-content h1 .fa-spin.headerlink,.rst-content h1 .nav .fa-spin.headerlink,.nav .rst-content h2 .fa-spin.headerlink,.rst-content h2 .nav .fa-spin.headerlink,.nav .rst-content h3 .fa-spin.headerlink,.rst-content h3 .nav .fa-spin.headerlink,.nav .rst-content h4 .fa-spin.headerlink,.rst-content h4 .nav .fa-spin.headerlink,.nav .rst-content h5 .fa-spin.headerlink,.rst-content h5 .nav .fa-spin.headerlink,.nav .rst-content h6 .fa-spin.headerlink,.rst-content h6 .nav .fa-spin.headerlink,.nav .rst-content dl dt .fa-spin.headerlink,.rst-content dl dt .nav .fa-spin.headerlink,.nav .rst-content p.caption .fa-spin.headerlink,.rst-content p.caption .nav .fa-spin.headerlink,.nav .rst-content table>caption .fa-spin.headerlink,.rst-content table>caption .nav .fa-spin.headerlink,.nav .rst-content .code-block-caption .fa-spin.headerlink,.rst-content .code-block-caption .nav .fa-spin.headerlink,.nav .rst-content tt.download span.fa-spin:first-child,.rst-content tt.download .nav span.fa-spin:first-child,.nav .rst-content code.download span.fa-spin:first-child,.rst-content code.download .nav span.fa-spin:first-child,.nav .fa-spin.icon{display:inline-block}.btn.fa:before,.wy-menu-vertical li span.btn.toctree-expand:before,.rst-content .btn.admonition-title:before,.rst-content h1 .btn.headerlink:before,.rst-content h2 .btn.headerlink:before,.rst-content h3 .btn.headerlink:before,.rst-content h4 .btn.headerlink:before,.rst-content h5 .btn.headerlink:before,.rst-content h6 .btn.headerlink:before,.rst-content dl dt .btn.headerlink:before,.rst-content p.caption .btn.headerlink:before,.rst-content table>caption .btn.headerlink:before,.rst-content .code-block-caption .btn.headerlink:before,.rst-content tt.download span.btn:first-child:before,.rst-content code.download span.btn:first-child:before,.btn.icon:before{opacity:.5;-webkit-transition:opacity .05s ease-in;-moz-transition:opacity .05s ease-in;transition:opacity .05s ease-in}.btn.fa:hover:before,.wy-menu-vertical li span.btn.toctree-expand:hover:before,.rst-content .btn.admonition-title:hover:before,.rst-content h1 .btn.headerlink:hover:before,.rst-content h2 .btn.headerlink:hover:before,.rst-content h3 .btn.headerlink:hover:before,.rst-content h4 .btn.headerlink:hover:before,.rst-content h5 .btn.headerlink:hover:before,.rst-content h6 .btn.headerlink:hover:before,.rst-content dl dt .btn.headerlink:hover:before,.rst-content p.caption .btn.headerlink:hover:before,.rst-content table>caption .btn.headerlink:hover:before,.rst-content .code-block-caption .btn.headerlink:hover:before,.rst-content tt.download span.btn:first-child:hover:before,.rst-content code.download span.btn:first-child:hover:before,.btn.icon:hover:before{opacity:1}.btn-mini .fa:before,.btn-mini .wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li .btn-mini span.toctree-expand:before,.btn-mini .rst-content .admonition-title:before,.rst-content .btn-mini .admonition-title:before,.btn-mini .rst-content h1 .headerlink:before,.rst-content h1 .btn-mini .headerlink:before,.btn-mini .rst-content h2 .headerlink:before,.rst-content h2 .btn-mini .headerlink:before,.btn-mini .rst-content h3 .headerlink:before,.rst-content h3 .btn-mini .headerlink:before,.btn-mini .rst-content h4 .headerlink:before,.rst-content h4 .btn-mini .headerlink:before,.btn-mini .rst-content h5 .headerlink:before,.rst-content h5 .btn-mini .headerlink:before,.btn-mini .rst-content h6 .headerlink:before,.rst-content h6 .btn-mini .headerlink:before,.btn-mini .rst-content dl dt .headerlink:before,.rst-content dl dt .btn-mini .headerlink:before,.btn-mini .rst-content p.caption .headerlink:before,.rst-content p.caption .btn-mini .headerlink:before,.btn-mini .rst-content table>caption .headerlink:before,.rst-content table>caption .btn-mini .headerlink:before,.btn-mini .rst-content .code-block-caption .headerlink:before,.rst-content .code-block-caption .btn-mini .headerlink:before,.btn-mini .rst-content tt.download span:first-child:before,.rst-content tt.download .btn-mini span:first-child:before,.btn-mini .rst-content code.download span:first-child:before,.rst-content code.download .btn-mini span:first-child:before,.btn-mini .icon:before{font-size:14px;vertical-align:-15%}.wy-alert,.rst-content .note,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .warning,.rst-content .seealso,.rst-content .admonition-todo,.rst-content .admonition{padding:12px;line-height:24px;margin-bottom:24px;background:#e7f2fa}.wy-alert-title,.rst-content .admonition-title{color:#fff;font-weight:bold;display:block;color:#fff;background:#6ab0de;margin:-12px;padding:6px 12px;margin-bottom:12px}.wy-alert.wy-alert-danger,.rst-content .wy-alert-danger.note,.rst-content .wy-alert-danger.attention,.rst-content .wy-alert-danger.caution,.rst-content .danger,.rst-content .error,.rst-content .wy-alert-danger.hint,.rst-content .wy-alert-danger.important,.rst-content .wy-alert-danger.tip,.rst-content .wy-alert-danger.warning,.rst-content .wy-alert-danger.seealso,.rst-content .wy-alert-danger.admonition-todo,.rst-content .wy-alert-danger.admonition{background:#fdf3f2}.wy-alert.wy-alert-danger .wy-alert-title,.rst-content .wy-alert-danger.note .wy-alert-title,.rst-content .wy-alert-danger.attention .wy-alert-title,.rst-content .wy-alert-danger.caution .wy-alert-title,.rst-content .danger .wy-alert-title,.rst-content .error .wy-alert-title,.rst-content .wy-alert-danger.hint .wy-alert-title,.rst-content .wy-alert-danger.important .wy-alert-title,.rst-content .wy-alert-danger.tip .wy-alert-title,.rst-content .wy-alert-danger.warning .wy-alert-title,.rst-content .wy-alert-danger.seealso .wy-alert-title,.rst-content .wy-alert-danger.admonition-todo .wy-alert-title,.rst-content .wy-alert-danger.admonition .wy-alert-title,.wy-alert.wy-alert-danger .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-danger .admonition-title,.rst-content .wy-alert-danger.note .admonition-title,.rst-content .wy-alert-danger.attention .admonition-title,.rst-content .wy-alert-danger.caution .admonition-title,.rst-content .danger .admonition-title,.rst-content .error .admonition-title,.rst-content .wy-alert-danger.hint .admonition-title,.rst-content .wy-alert-danger.important .admonition-title,.rst-content .wy-alert-danger.tip .admonition-title,.rst-content .wy-alert-danger.warning .admonition-title,.rst-content .wy-alert-danger.seealso .admonition-title,.rst-content .wy-alert-danger.admonition-todo .admonition-title,.rst-content .wy-alert-danger.admonition .admonition-title{background:#f29f97}.wy-alert.wy-alert-warning,.rst-content .wy-alert-warning.note,.rst-content .attention,.rst-content .caution,.rst-content .wy-alert-warning.danger,.rst-content .wy-alert-warning.error,.rst-content .wy-alert-warning.hint,.rst-content .wy-alert-warning.important,.rst-content .wy-alert-warning.tip,.rst-content .warning,.rst-content .wy-alert-warning.seealso,.rst-content .admonition-todo,.rst-content .wy-alert-warning.admonition{background:#ffedcc}.wy-alert.wy-alert-warning .wy-alert-title,.rst-content .wy-alert-warning.note .wy-alert-title,.rst-content .attention .wy-alert-title,.rst-content .caution .wy-alert-title,.rst-content .wy-alert-warning.danger .wy-alert-title,.rst-content .wy-alert-warning.error .wy-alert-title,.rst-content .wy-alert-warning.hint .wy-alert-title,.rst-content .wy-alert-warning.important .wy-alert-title,.rst-content .wy-alert-warning.tip .wy-alert-title,.rst-content .warning .wy-alert-title,.rst-content .wy-alert-warning.seealso .wy-alert-title,.rst-content .admonition-todo .wy-alert-title,.rst-content .wy-alert-warning.admonition .wy-alert-title,.wy-alert.wy-alert-warning .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-warning .admonition-title,.rst-content .wy-alert-warning.note .admonition-title,.rst-content .attention .admonition-title,.rst-content .caution .admonition-title,.rst-content .wy-alert-warning.danger .admonition-title,.rst-content .wy-alert-warning.error .admonition-title,.rst-content .wy-alert-warning.hint .admonition-title,.rst-content .wy-alert-warning.important .admonition-title,.rst-content .wy-alert-warning.tip .admonition-title,.rst-content .warning .admonition-title,.rst-content .wy-alert-warning.seealso .admonition-title,.rst-content .admonition-todo .admonition-title,.rst-content .wy-alert-warning.admonition .admonition-title{background:#f0b37e}.wy-alert.wy-alert-info,.rst-content .note,.rst-content .wy-alert-info.attention,.rst-content .wy-alert-info.caution,.rst-content .wy-alert-info.danger,.rst-content .wy-alert-info.error,.rst-content .wy-alert-info.hint,.rst-content .wy-alert-info.important,.rst-content .wy-alert-info.tip,.rst-content .wy-alert-info.warning,.rst-content .seealso,.rst-content .wy-alert-info.admonition-todo,.rst-content .wy-alert-info.admonition{background:#e7f2fa}.wy-alert.wy-alert-info .wy-alert-title,.rst-content .note .wy-alert-title,.rst-content .wy-alert-info.attention .wy-alert-title,.rst-content .wy-alert-info.caution .wy-alert-title,.rst-content .wy-alert-info.danger .wy-alert-title,.rst-content .wy-alert-info.error .wy-alert-title,.rst-content .wy-alert-info.hint .wy-alert-title,.rst-content .wy-alert-info.important .wy-alert-title,.rst-content .wy-alert-info.tip .wy-alert-title,.rst-content .wy-alert-info.warning .wy-alert-title,.rst-content .seealso .wy-alert-title,.rst-content .wy-alert-info.admonition-todo .wy-alert-title,.rst-content .wy-alert-info.admonition .wy-alert-title,.wy-alert.wy-alert-info .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-info .admonition-title,.rst-content .note .admonition-title,.rst-content .wy-alert-info.attention .admonition-title,.rst-content .wy-alert-info.caution .admonition-title,.rst-content .wy-alert-info.danger .admonition-title,.rst-content .wy-alert-info.error .admonition-title,.rst-content .wy-alert-info.hint .admonition-title,.rst-content .wy-alert-info.important .admonition-title,.rst-content .wy-alert-info.tip .admonition-title,.rst-content .wy-alert-info.warning .admonition-title,.rst-content .seealso .admonition-title,.rst-content .wy-alert-info.admonition-todo .admonition-title,.rst-content .wy-alert-info.admonition .admonition-title{background:#6ab0de}.wy-alert.wy-alert-success,.rst-content .wy-alert-success.note,.rst-content .wy-alert-success.attention,.rst-content .wy-alert-success.caution,.rst-content .wy-alert-success.danger,.rst-content .wy-alert-success.error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .wy-alert-success.warning,.rst-content .wy-alert-success.seealso,.rst-content .wy-alert-success.admonition-todo,.rst-content .wy-alert-success.admonition{background:#dbfaf4}.wy-alert.wy-alert-success .wy-alert-title,.rst-content .wy-alert-success.note .wy-alert-title,.rst-content .wy-alert-success.attention .wy-alert-title,.rst-content .wy-alert-success.caution .wy-alert-title,.rst-content .wy-alert-success.danger .wy-alert-title,.rst-content .wy-alert-success.error .wy-alert-title,.rst-content .hint .wy-alert-title,.rst-content .important .wy-alert-title,.rst-content .tip .wy-alert-title,.rst-content .wy-alert-success.warning .wy-alert-title,.rst-content .wy-alert-success.seealso .wy-alert-title,.rst-content .wy-alert-success.admonition-todo .wy-alert-title,.rst-content .wy-alert-success.admonition .wy-alert-title,.wy-alert.wy-alert-success .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-success .admonition-title,.rst-content .wy-alert-success.note .admonition-title,.rst-content .wy-alert-success.attention .admonition-title,.rst-content .wy-alert-success.caution .admonition-title,.rst-content .wy-alert-success.danger .admonition-title,.rst-content .wy-alert-success.error .admonition-title,.rst-content .hint .admonition-title,.rst-content .important .admonition-title,.rst-content .tip .admonition-title,.rst-content .wy-alert-success.warning .admonition-title,.rst-content .wy-alert-success.seealso .admonition-title,.rst-content .wy-alert-success.admonition-todo .admonition-title,.rst-content .wy-alert-success.admonition .admonition-title{background:#1abc9c}.wy-alert.wy-alert-neutral,.rst-content .wy-alert-neutral.note,.rst-content .wy-alert-neutral.attention,.rst-content .wy-alert-neutral.caution,.rst-content .wy-alert-neutral.danger,.rst-content .wy-alert-neutral.error,.rst-content .wy-alert-neutral.hint,.rst-content .wy-alert-neutral.important,.rst-content .wy-alert-neutral.tip,.rst-content .wy-alert-neutral.warning,.rst-content .wy-alert-neutral.seealso,.rst-content .wy-alert-neutral.admonition-todo,.rst-content .wy-alert-neutral.admonition{background:#f3f6f6}.wy-alert.wy-alert-neutral .wy-alert-title,.rst-content .wy-alert-neutral.note .wy-alert-title,.rst-content .wy-alert-neutral.attention .wy-alert-title,.rst-content .wy-alert-neutral.caution .wy-alert-title,.rst-content .wy-alert-neutral.danger .wy-alert-title,.rst-content .wy-alert-neutral.error .wy-alert-title,.rst-content .wy-alert-neutral.hint .wy-alert-title,.rst-content .wy-alert-neutral.important .wy-alert-title,.rst-content .wy-alert-neutral.tip .wy-alert-title,.rst-content .wy-alert-neutral.warning .wy-alert-title,.rst-content .wy-alert-neutral.seealso .wy-alert-title,.rst-content .wy-alert-neutral.admonition-todo .wy-alert-title,.rst-content .wy-alert-neutral.admonition .wy-alert-title,.wy-alert.wy-alert-neutral .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-neutral .admonition-title,.rst-content .wy-alert-neutral.note .admonition-title,.rst-content .wy-alert-neutral.attention .admonition-title,.rst-content .wy-alert-neutral.caution .admonition-title,.rst-content .wy-alert-neutral.danger .admonition-title,.rst-content .wy-alert-neutral.error .admonition-title,.rst-content .wy-alert-neutral.hint .admonition-title,.rst-content .wy-alert-neutral.important .admonition-title,.rst-content .wy-alert-neutral.tip .admonition-title,.rst-content .wy-alert-neutral.warning .admonition-title,.rst-content .wy-alert-neutral.seealso .admonition-title,.rst-content .wy-alert-neutral.admonition-todo .admonition-title,.rst-content .wy-alert-neutral.admonition .admonition-title{color:#404040;background:#e1e4e5}.wy-alert.wy-alert-neutral a,.rst-content .wy-alert-neutral.note a,.rst-content .wy-alert-neutral.attention a,.rst-content .wy-alert-neutral.caution a,.rst-content .wy-alert-neutral.danger a,.rst-content .wy-alert-neutral.error a,.rst-content .wy-alert-neutral.hint a,.rst-content .wy-alert-neutral.important a,.rst-content .wy-alert-neutral.tip a,.rst-content .wy-alert-neutral.warning a,.rst-content .wy-alert-neutral.seealso a,.rst-content .wy-alert-neutral.admonition-todo a,.rst-content .wy-alert-neutral.admonition a{color:#2980B9}.wy-alert p:last-child,.rst-content .note p:last-child,.rst-content .attention p:last-child,.rst-content .caution p:last-child,.rst-content .danger p:last-child,.rst-content .error p:last-child,.rst-content .hint p:last-child,.rst-content .important p:last-child,.rst-content .tip p:last-child,.rst-content .warning p:last-child,.rst-content .seealso p:last-child,.rst-content .admonition-todo p:last-child,.rst-content .admonition p:last-child{margin-bottom:0}.wy-tray-container{position:fixed;bottom:0px;left:0;z-index:600}.wy-tray-container li{display:block;width:300px;background:transparent;color:#fff;text-align:center;box-shadow:0 5px 5px 0 rgba(0,0,0,0.1);padding:0 24px;min-width:20%;opacity:0;height:0;line-height:56px;overflow:hidden;-webkit-transition:all .3s ease-in;-moz-transition:all .3s ease-in;transition:all .3s ease-in}.wy-tray-container li.wy-tray-item-success{background:#27AE60}.wy-tray-container li.wy-tray-item-info{background:#2980B9}.wy-tray-container li.wy-tray-item-warning{background:#E67E22}.wy-tray-container li.wy-tray-item-danger{background:#E74C3C}.wy-tray-container li.on{opacity:1;height:56px}@media screen and (max-width: 768px){.wy-tray-container{bottom:auto;top:0;width:100%}.wy-tray-container li{width:100%}}button{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle;cursor:pointer;line-height:normal;-webkit-appearance:button;*overflow:visible}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}button[disabled]{cursor:default}.btn{display:inline-block;border-radius:2px;line-height:normal;white-space:nowrap;text-align:center;cursor:pointer;font-size:100%;padding:6px 12px 8px 12px;color:#fff;border:1px solid rgba(0,0,0,0.1);background-color:#27AE60;text-decoration:none;font-weight:normal;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;box-shadow:0px 1px 2px -1px rgba(255,255,255,0.5) inset,0px -2px 0px 0px rgba(0,0,0,0.1) inset;outline-none:false;vertical-align:middle;*display:inline;zoom:1;-webkit-user-drag:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-transition:all .1s linear;-moz-transition:all .1s linear;transition:all .1s linear}.btn-hover{background:#2e8ece;color:#fff}.btn:hover{background:#2cc36b;color:#fff}.btn:focus{background:#2cc36b;outline:0}.btn:active{box-shadow:0px -1px 0px 0px rgba(0,0,0,0.05) inset,0px 2px 0px 0px rgba(0,0,0,0.1) inset;padding:8px 12px 6px 12px}.btn:visited{color:#fff}.btn:disabled{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:.4;cursor:not-allowed;box-shadow:none}.btn-disabled{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:.4;cursor:not-allowed;box-shadow:none}.btn-disabled:hover,.btn-disabled:focus,.btn-disabled:active{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:.4;cursor:not-allowed;box-shadow:none}.btn::-moz-focus-inner{padding:0;border:0}.btn-small{font-size:80%}.btn-info{background-color:#2980B9 !important}.btn-info:hover{background-color:#2e8ece !important}.btn-neutral{background-color:#f3f6f6 !important;color:#404040 !important}.btn-neutral:hover{background-color:#e5ebeb !important;color:#404040}.btn-neutral:visited{color:#404040 !important}.btn-success{background-color:#27AE60 !important}.btn-success:hover{background-color:#295 !important}.btn-danger{background-color:#E74C3C !important}.btn-danger:hover{background-color:#ea6153 !important}.btn-warning{background-color:#E67E22 !important}.btn-warning:hover{background-color:#e98b39 !important}.btn-invert{background-color:#222}.btn-invert:hover{background-color:#2f2f2f !important}.btn-link{background-color:transparent !important;color:#2980B9;box-shadow:none;border-color:transparent !important}.btn-link:hover{background-color:transparent !important;color:#409ad5 !important;box-shadow:none}.btn-link:active{background-color:transparent !important;color:#409ad5 !important;box-shadow:none}.btn-link:visited{color:#9B59B6}.wy-btn-group .btn,.wy-control .btn{vertical-align:middle}.wy-btn-group{margin-bottom:24px;*zoom:1}.wy-btn-group:before,.wy-btn-group:after{display:table;content:""}.wy-btn-group:after{clear:both}.wy-dropdown{position:relative;display:inline-block}.wy-dropdown-active .wy-dropdown-menu{display:block}.wy-dropdown-menu{position:absolute;left:0;display:none;float:left;top:100%;min-width:100%;background:#fcfcfc;z-index:100;border:solid 1px #cfd7dd;box-shadow:0 2px 2px 0 rgba(0,0,0,0.1);padding:12px}.wy-dropdown-menu>dd>a{display:block;clear:both;color:#404040;white-space:nowrap;font-size:90%;padding:0 12px;cursor:pointer}.wy-dropdown-menu>dd>a:hover{background:#2980B9;color:#fff}.wy-dropdown-menu>dd.divider{border-top:solid 1px #cfd7dd;margin:6px 0}.wy-dropdown-menu>dd.search{padding-bottom:12px}.wy-dropdown-menu>dd.search input[type="search"]{width:100%}.wy-dropdown-menu>dd.call-to-action{background:#e3e3e3;text-transform:uppercase;font-weight:500;font-size:80%}.wy-dropdown-menu>dd.call-to-action:hover{background:#e3e3e3}.wy-dropdown-menu>dd.call-to-action .btn{color:#fff}.wy-dropdown.wy-dropdown-up .wy-dropdown-menu{bottom:100%;top:auto;left:auto;right:0}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu{background:#fcfcfc;margin-top:2px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a{padding:6px 12px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a:hover{background:#2980B9;color:#fff}.wy-dropdown.wy-dropdown-left .wy-dropdown-menu{right:0;left:auto;text-align:right}.wy-dropdown-arrow:before{content:" ";border-bottom:5px solid #f5f5f5;border-left:5px solid transparent;border-right:5px solid transparent;position:absolute;display:block;top:-4px;left:50%;margin-left:-3px}.wy-dropdown-arrow.wy-dropdown-arrow-left:before{left:11px}.wy-form-stacked select{display:block}.wy-form-aligned input,.wy-form-aligned textarea,.wy-form-aligned select,.wy-form-aligned .wy-help-inline,.wy-form-aligned label{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-form-aligned .wy-control-group>label{display:inline-block;vertical-align:middle;width:10em;margin:6px 12px 0 0;float:left}.wy-form-aligned .wy-control{float:left}.wy-form-aligned .wy-control label{display:block}.wy-form-aligned .wy-control select{margin-top:6px}fieldset{border:0;margin:0;padding:0}legend{display:block;width:100%;border:0;padding:0;white-space:normal;margin-bottom:24px;font-size:150%;*margin-left:-7px}label{display:block;margin:0 0 .3125em 0;color:#333;font-size:90%}input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}.wy-control-group{margin-bottom:24px;*zoom:1;max-width:68em;margin-left:auto;margin-right:auto;*zoom:1}.wy-control-group:before,.wy-control-group:after{display:table;content:""}.wy-control-group:after{clear:both}.wy-control-group:before,.wy-control-group:after{display:table;content:""}.wy-control-group:after{clear:both}.wy-control-group.wy-control-group-required>label:after{content:" *";color:#E74C3C}.wy-control-group .wy-form-full,.wy-control-group .wy-form-halves,.wy-control-group .wy-form-thirds{padding-bottom:12px}.wy-control-group .wy-form-full select,.wy-control-group .wy-form-halves select,.wy-control-group .wy-form-thirds select{width:100%}.wy-control-group .wy-form-full input[type="text"],.wy-control-group .wy-form-full input[type="password"],.wy-control-group .wy-form-full input[type="email"],.wy-control-group .wy-form-full input[type="url"],.wy-control-group .wy-form-full input[type="date"],.wy-control-group .wy-form-full input[type="month"],.wy-control-group .wy-form-full input[type="time"],.wy-control-group .wy-form-full input[type="datetime"],.wy-control-group .wy-form-full input[type="datetime-local"],.wy-control-group .wy-form-full input[type="week"],.wy-control-group .wy-form-full input[type="number"],.wy-control-group .wy-form-full input[type="search"],.wy-control-group .wy-form-full input[type="tel"],.wy-control-group .wy-form-full input[type="color"],.wy-control-group .wy-form-halves input[type="text"],.wy-control-group .wy-form-halves input[type="password"],.wy-control-group .wy-form-halves input[type="email"],.wy-control-group .wy-form-halves input[type="url"],.wy-control-group .wy-form-halves input[type="date"],.wy-control-group .wy-form-halves input[type="month"],.wy-control-group .wy-form-halves input[type="time"],.wy-control-group .wy-form-halves input[type="datetime"],.wy-control-group .wy-form-halves input[type="datetime-local"],.wy-control-group .wy-form-halves input[type="week"],.wy-control-group .wy-form-halves input[type="number"],.wy-control-group .wy-form-halves input[type="search"],.wy-control-group .wy-form-halves input[type="tel"],.wy-control-group .wy-form-halves input[type="color"],.wy-control-group .wy-form-thirds input[type="text"],.wy-control-group .wy-form-thirds input[type="password"],.wy-control-group .wy-form-thirds input[type="email"],.wy-control-group .wy-form-thirds input[type="url"],.wy-control-group .wy-form-thirds input[type="date"],.wy-control-group .wy-form-thirds input[type="month"],.wy-control-group .wy-form-thirds input[type="time"],.wy-control-group .wy-form-thirds input[type="datetime"],.wy-control-group .wy-form-thirds input[type="datetime-local"],.wy-control-group .wy-form-thirds input[type="week"],.wy-control-group .wy-form-thirds input[type="number"],.wy-control-group .wy-form-thirds input[type="search"],.wy-control-group .wy-form-thirds input[type="tel"],.wy-control-group .wy-form-thirds input[type="color"]{width:100%}.wy-control-group .wy-form-full{float:left;display:block;margin-right:2.3576515979%;width:100%;margin-right:0}.wy-control-group .wy-form-full:last-child{margin-right:0}.wy-control-group .wy-form-halves{float:left;display:block;margin-right:2.3576515979%;width:48.821174201%}.wy-control-group .wy-form-halves:last-child{margin-right:0}.wy-control-group .wy-form-halves:nth-of-type(2n){margin-right:0}.wy-control-group .wy-form-halves:nth-of-type(2n+1){clear:left}.wy-control-group .wy-form-thirds{float:left;display:block;margin-right:2.3576515979%;width:31.7615656014%}.wy-control-group .wy-form-thirds:last-child{margin-right:0}.wy-control-group .wy-form-thirds:nth-of-type(3n){margin-right:0}.wy-control-group .wy-form-thirds:nth-of-type(3n+1){clear:left}.wy-control-group.wy-control-group-no-input .wy-control{margin:6px 0 0 0;font-size:90%}.wy-control-no-input{display:inline-block;margin:6px 0 0 0;font-size:90%}.wy-control-group.fluid-input input[type="text"],.wy-control-group.fluid-input input[type="password"],.wy-control-group.fluid-input input[type="email"],.wy-control-group.fluid-input input[type="url"],.wy-control-group.fluid-input input[type="date"],.wy-control-group.fluid-input input[type="month"],.wy-control-group.fluid-input input[type="time"],.wy-control-group.fluid-input input[type="datetime"],.wy-control-group.fluid-input input[type="datetime-local"],.wy-control-group.fluid-input input[type="week"],.wy-control-group.fluid-input input[type="number"],.wy-control-group.fluid-input input[type="search"],.wy-control-group.fluid-input input[type="tel"],.wy-control-group.fluid-input input[type="color"]{width:100%}.wy-form-message-inline{display:inline-block;padding-left:.3em;color:#666;vertical-align:middle;font-size:90%}.wy-form-message{display:block;color:#999;font-size:70%;margin-top:.3125em;font-style:italic}.wy-form-message p{font-size:inherit;font-style:italic;margin-bottom:6px}.wy-form-message p:last-child{margin-bottom:0}input{line-height:normal}input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;*overflow:visible}input[type="text"],input[type="password"],input[type="email"],input[type="url"],input[type="date"],input[type="month"],input[type="time"],input[type="datetime"],input[type="datetime-local"],input[type="week"],input[type="number"],input[type="search"],input[type="tel"],input[type="color"]{-webkit-appearance:none;padding:6px;display:inline-block;border:1px solid #ccc;font-size:80%;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;box-shadow:inset 0 1px 3px #ddd;border-radius:0;-webkit-transition:border .3s linear;-moz-transition:border .3s linear;transition:border .3s linear}input[type="datetime-local"]{padding:.34375em .625em}input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0;margin-right:.3125em;*height:13px;*width:13px}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}input[type="text"]:focus,input[type="password"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus{outline:0;outline:thin dotted \9;border-color:#333}input.no-focus:focus{border-color:#ccc !important}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:1px auto #129FEA}input[type="text"][disabled],input[type="password"][disabled],input[type="email"][disabled],input[type="url"][disabled],input[type="date"][disabled],input[type="month"][disabled],input[type="time"][disabled],input[type="datetime"][disabled],input[type="datetime-local"][disabled],input[type="week"][disabled],input[type="number"][disabled],input[type="search"][disabled],input[type="tel"][disabled],input[type="color"][disabled]{cursor:not-allowed;background-color:#fafafa}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#E74C3C;border:1px solid #E74C3C}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#E74C3C}input[type="file"]:focus:invalid:focus,input[type="radio"]:focus:invalid:focus,input[type="checkbox"]:focus:invalid:focus{outline-color:#E74C3C}input.wy-input-large{padding:12px;font-size:100%}textarea{overflow:auto;vertical-align:top;width:100%;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif}select,textarea{padding:.5em .625em;display:inline-block;border:1px solid #ccc;font-size:80%;box-shadow:inset 0 1px 3px #ddd;-webkit-transition:border .3s linear;-moz-transition:border .3s linear;transition:border .3s linear}select{border:1px solid #ccc;background-color:#fff}select[multiple]{height:auto}select:focus,textarea:focus{outline:0}select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#fafafa}input[type="radio"][disabled],input[type="checkbox"][disabled]{cursor:not-allowed}.wy-checkbox,.wy-radio{margin:6px 0;color:#404040;display:block}.wy-checkbox input,.wy-radio input{vertical-align:baseline}.wy-form-message-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-input-prefix,.wy-input-suffix{white-space:nowrap;padding:6px}.wy-input-prefix .wy-input-context,.wy-input-suffix .wy-input-context{line-height:27px;padding:0 8px;display:inline-block;font-size:80%;background-color:#f3f6f6;border:solid 1px #ccc;color:#999}.wy-input-suffix .wy-input-context{border-left:0}.wy-input-prefix .wy-input-context{border-right:0}.wy-switch{position:relative;display:block;height:24px;margin-top:12px;cursor:pointer}.wy-switch:before{position:absolute;content:"";display:block;left:0;top:0;width:36px;height:12px;border-radius:4px;background:#ccc;-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.wy-switch:after{position:absolute;content:"";display:block;width:18px;height:18px;border-radius:4px;background:#999;left:-3px;top:-3px;-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.wy-switch span{position:absolute;left:48px;display:block;font-size:12px;color:#ccc;line-height:1}.wy-switch.active:before{background:#1e8449}.wy-switch.active:after{left:24px;background:#27AE60}.wy-switch.disabled{cursor:not-allowed;opacity:.8}.wy-control-group.wy-control-group-error .wy-form-message,.wy-control-group.wy-control-group-error>label{color:#E74C3C}.wy-control-group.wy-control-group-error input[type="text"],.wy-control-group.wy-control-group-error input[type="password"],.wy-control-group.wy-control-group-error input[type="email"],.wy-control-group.wy-control-group-error input[type="url"],.wy-control-group.wy-control-group-error input[type="date"],.wy-control-group.wy-control-group-error input[type="month"],.wy-control-group.wy-control-group-error input[type="time"],.wy-control-group.wy-control-group-error input[type="datetime"],.wy-control-group.wy-control-group-error input[type="datetime-local"],.wy-control-group.wy-control-group-error input[type="week"],.wy-control-group.wy-control-group-error input[type="number"],.wy-control-group.wy-control-group-error input[type="search"],.wy-control-group.wy-control-group-error input[type="tel"],.wy-control-group.wy-control-group-error input[type="color"]{border:solid 1px #E74C3C}.wy-control-group.wy-control-group-error textarea{border:solid 1px #E74C3C}.wy-inline-validate{white-space:nowrap}.wy-inline-validate .wy-input-context{padding:.5em .625em;display:inline-block;font-size:80%}.wy-inline-validate.wy-inline-validate-success .wy-input-context{color:#27AE60}.wy-inline-validate.wy-inline-validate-danger .wy-input-context{color:#E74C3C}.wy-inline-validate.wy-inline-validate-warning .wy-input-context{color:#E67E22}.wy-inline-validate.wy-inline-validate-info .wy-input-context{color:#2980B9}.rotate-90{-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.rotate-180{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.rotate-270{-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.mirror{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1);-ms-transform:scaleX(-1);-o-transform:scaleX(-1);transform:scaleX(-1)}.mirror.rotate-90{-webkit-transform:scaleX(-1) rotate(90deg);-moz-transform:scaleX(-1) rotate(90deg);-ms-transform:scaleX(-1) rotate(90deg);-o-transform:scaleX(-1) rotate(90deg);transform:scaleX(-1) rotate(90deg)}.mirror.rotate-180{-webkit-transform:scaleX(-1) rotate(180deg);-moz-transform:scaleX(-1) rotate(180deg);-ms-transform:scaleX(-1) rotate(180deg);-o-transform:scaleX(-1) rotate(180deg);transform:scaleX(-1) rotate(180deg)}.mirror.rotate-270{-webkit-transform:scaleX(-1) rotate(270deg);-moz-transform:scaleX(-1) rotate(270deg);-ms-transform:scaleX(-1) rotate(270deg);-o-transform:scaleX(-1) rotate(270deg);transform:scaleX(-1) rotate(270deg)}@media only screen and (max-width: 480px){.wy-form button[type="submit"]{margin:.7em 0 0}.wy-form input[type="text"],.wy-form input[type="password"],.wy-form input[type="email"],.wy-form input[type="url"],.wy-form input[type="date"],.wy-form input[type="month"],.wy-form input[type="time"],.wy-form input[type="datetime"],.wy-form input[type="datetime-local"],.wy-form input[type="week"],.wy-form input[type="number"],.wy-form input[type="search"],.wy-form input[type="tel"],.wy-form input[type="color"]{margin-bottom:.3em;display:block}.wy-form label{margin-bottom:.3em;display:block}.wy-form input[type="password"],.wy-form input[type="email"],.wy-form input[type="url"],.wy-form input[type="date"],.wy-form input[type="month"],.wy-form input[type="time"],.wy-form input[type="datetime"],.wy-form input[type="datetime-local"],.wy-form input[type="week"],.wy-form input[type="number"],.wy-form input[type="search"],.wy-form input[type="tel"],.wy-form input[type="color"]{margin-bottom:0}.wy-form-aligned .wy-control-group label{margin-bottom:.3em;text-align:left;display:block;width:100%}.wy-form-aligned .wy-control{margin:1.5em 0 0 0}.wy-form .wy-help-inline,.wy-form-message-inline,.wy-form-message{display:block;font-size:80%;padding:6px 0}}@media screen and (max-width: 768px){.tablet-hide{display:none}}@media screen and (max-width: 480px){.mobile-hide{display:none}}.float-left{float:left}.float-right{float:right}.full-width{width:100%}.wy-table,.rst-content table.docutils,.rst-content table.field-list{border-collapse:collapse;border-spacing:0;empty-cells:show;margin-bottom:24px}.wy-table caption,.rst-content table.docutils caption,.rst-content table.field-list caption{color:#000;font:italic 85%/1 arial,sans-serif;padding:1em 0;text-align:center}.wy-table td,.rst-content table.docutils td,.rst-content table.field-list td,.wy-table th,.rst-content table.docutils th,.rst-content table.field-list th{font-size:90%;margin:0;overflow:visible;padding:8px 16px}.wy-table td:first-child,.rst-content table.docutils td:first-child,.rst-content table.field-list td:first-child,.wy-table th:first-child,.rst-content table.docutils th:first-child,.rst-content table.field-list th:first-child{border-left-width:0}.wy-table thead,.rst-content table.docutils thead,.rst-content table.field-list thead{color:#000;text-align:left;vertical-align:bottom;white-space:nowrap}.wy-table thead th,.rst-content table.docutils thead th,.rst-content table.field-list thead th{font-weight:bold;border-bottom:solid 2px #e1e4e5}.wy-table td,.rst-content table.docutils td,.rst-content table.field-list td{background-color:transparent;vertical-align:middle}.wy-table td p,.rst-content table.docutils td p,.rst-content table.field-list td p{line-height:18px}.wy-table td p:last-child,.rst-content table.docutils td p:last-child,.rst-content table.field-list td p:last-child{margin-bottom:0}.wy-table .wy-table-cell-min,.rst-content table.docutils .wy-table-cell-min,.rst-content table.field-list .wy-table-cell-min{width:1%;padding-right:0}.wy-table .wy-table-cell-min input[type=checkbox],.rst-content table.docutils .wy-table-cell-min input[type=checkbox],.rst-content table.field-list .wy-table-cell-min input[type=checkbox],.wy-table .wy-table-cell-min input[type=checkbox],.rst-content table.docutils .wy-table-cell-min input[type=checkbox],.rst-content table.field-list .wy-table-cell-min input[type=checkbox]{margin:0}.wy-table-secondary{color:gray;font-size:90%}.wy-table-tertiary{color:gray;font-size:80%}.wy-table-odd td,.wy-table-striped tr:nth-child(2n-1) td,.rst-content table.docutils:not(.field-list) tr:nth-child(2n-1) td{background-color:#f3f6f6}.wy-table-backed{background-color:#f3f6f6}.wy-table-bordered-all,.rst-content table.docutils{border:1px solid #e1e4e5}.wy-table-bordered-all td,.rst-content table.docutils td{border-bottom:1px solid #e1e4e5;border-left:1px solid #e1e4e5}.wy-table-bordered-all tbody>tr:last-child td,.rst-content table.docutils tbody>tr:last-child td{border-bottom-width:0}.wy-table-bordered{border:1px solid #e1e4e5}.wy-table-bordered-rows td{border-bottom:1px solid #e1e4e5}.wy-table-bordered-rows tbody>tr:last-child td{border-bottom-width:0}.wy-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.wy-table-horizontal td,.wy-table-horizontal th{border-width:0 0 1px 0;border-bottom:1px solid #e1e4e5}.wy-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.wy-table-responsive{margin-bottom:24px;max-width:100%;overflow:auto}.wy-table-responsive table{margin-bottom:0 !important}.wy-table-responsive table td,.wy-table-responsive table th{white-space:nowrap}a{color:#2980B9;text-decoration:none;cursor:pointer}a:hover{color:#3091d1}a:visited{color:#9B59B6}html{height:100%;overflow-x:hidden}body{font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;font-weight:normal;color:#404040;min-height:100%;overflow-x:hidden;background:#edf0f2}.wy-text-left{text-align:left}.wy-text-center{text-align:center}.wy-text-right{text-align:right}.wy-text-large{font-size:120%}.wy-text-normal{font-size:100%}.wy-text-small,small{font-size:80%}.wy-text-strike{text-decoration:line-through}.wy-text-warning{color:#E67E22 !important}a.wy-text-warning:hover{color:#eb9950 !important}.wy-text-info{color:#2980B9 !important}a.wy-text-info:hover{color:#409ad5 !important}.wy-text-success{color:#27AE60 !important}a.wy-text-success:hover{color:#36d278 !important}.wy-text-danger{color:#E74C3C !important}a.wy-text-danger:hover{color:#ed7669 !important}.wy-text-neutral{color:#404040 !important}a.wy-text-neutral:hover{color:#595959 !important}h1,h2,.rst-content .toctree-wrapper p.caption,h3,h4,h5,h6,legend{margin-top:0;font-weight:700;font-family:"Roboto Slab","ff-tisa-web-pro","Georgia",Arial,sans-serif}p{line-height:24px;margin:0;font-size:16px;margin-bottom:24px}h1{font-size:175%}h2,.rst-content .toctree-wrapper p.caption{font-size:150%}h3{font-size:125%}h4{font-size:115%}h5{font-size:110%}h6{font-size:100%}hr{display:block;height:1px;border:0;border-top:1px solid #e1e4e5;margin:24px 0;padding:0}code,.rst-content tt,.rst-content code{white-space:nowrap;max-width:100%;background:#fff;border:solid 1px #e1e4e5;font-size:75%;padding:0 5px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;color:#E74C3C;overflow-x:auto}code.code-large,.rst-content tt.code-large{font-size:90%}.wy-plain-list-disc,.rst-content .section ul,.rst-content .toctree-wrapper ul,article ul{list-style:disc;line-height:24px;margin-bottom:24px}.wy-plain-list-disc li,.rst-content .section ul li,.rst-content .toctree-wrapper ul li,article ul li{list-style:disc;margin-left:24px}.wy-plain-list-disc li p:last-child,.rst-content .section ul li p:last-child,.rst-content .toctree-wrapper ul li p:last-child,article ul li p:last-child{margin-bottom:0}.wy-plain-list-disc li ul,.rst-content .section ul li ul,.rst-content .toctree-wrapper ul li ul,article ul li ul{margin-bottom:0}.wy-plain-list-disc li li,.rst-content .section ul li li,.rst-content .toctree-wrapper ul li li,article ul li li{list-style:circle}.wy-plain-list-disc li li li,.rst-content .section ul li li li,.rst-content .toctree-wrapper ul li li li,article ul li li li{list-style:square}.wy-plain-list-disc li ol li,.rst-content .section ul li ol li,.rst-content .toctree-wrapper ul li ol li,article ul li ol li{list-style:decimal}.wy-plain-list-decimal,.rst-content .section ol,.rst-content ol.arabic,article ol{list-style:decimal;line-height:24px;margin-bottom:24px}.wy-plain-list-decimal li,.rst-content .section ol li,.rst-content ol.arabic li,article ol li{list-style:decimal;margin-left:24px}.wy-plain-list-decimal li p:last-child,.rst-content .section ol li p:last-child,.rst-content ol.arabic li p:last-child,article ol li p:last-child{margin-bottom:0}.wy-plain-list-decimal li ul,.rst-content .section ol li ul,.rst-content ol.arabic li ul,article ol li ul{margin-bottom:0}.wy-plain-list-decimal li ul li,.rst-content .section ol li ul li,.rst-content ol.arabic li ul li,article ol li ul li{list-style:disc}.wy-breadcrumbs{*zoom:1}.wy-breadcrumbs:before,.wy-breadcrumbs:after{display:table;content:""}.wy-breadcrumbs:after{clear:both}.wy-breadcrumbs li{display:inline-block}.wy-breadcrumbs li.wy-breadcrumbs-aside{float:right}.wy-breadcrumbs li a{display:inline-block;padding:5px}.wy-breadcrumbs li a:first-child{padding-left:0}.wy-breadcrumbs li code,.wy-breadcrumbs li .rst-content tt,.rst-content .wy-breadcrumbs li tt{padding:5px;border:none;background:none}.wy-breadcrumbs li code.literal,.wy-breadcrumbs li .rst-content tt.literal,.rst-content .wy-breadcrumbs li tt.literal{color:#404040}.wy-breadcrumbs-extra{margin-bottom:0;color:#b3b3b3;font-size:80%;display:inline-block}@media screen and (max-width: 480px){.wy-breadcrumbs-extra{display:none}.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}@media print{.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}html{font-size:16px}.wy-affix{position:fixed;top:1.618em}.wy-menu a:hover{text-decoration:none}.wy-menu-horiz{*zoom:1}.wy-menu-horiz:before,.wy-menu-horiz:after{display:table;content:""}.wy-menu-horiz:after{clear:both}.wy-menu-horiz ul,.wy-menu-horiz li{display:inline-block}.wy-menu-horiz li:hover{background:rgba(255,255,255,0.1)}.wy-menu-horiz li.divide-left{border-left:solid 1px #404040}.wy-menu-horiz li.divide-right{border-right:solid 1px #404040}.wy-menu-horiz a{height:32px;display:inline-block;line-height:32px;padding:0 16px}.wy-menu-vertical{width:300px}.wy-menu-vertical header,.wy-menu-vertical p.caption{color:#3a7ca8;height:32px;display:inline-block;line-height:32px;padding:0 1.618em;margin:12px 0 0 0;display:block;font-weight:bold;text-transform:uppercase;font-size:85%;white-space:nowrap}.wy-menu-vertical ul{margin-bottom:0}.wy-menu-vertical li.divide-top{border-top:solid 1px #404040}.wy-menu-vertical li.divide-bottom{border-bottom:solid 1px #404040}.wy-menu-vertical li.current{background:#e3e3e3}.wy-menu-vertical li.current a{color:gray;border-right:solid 1px #c9c9c9;padding:.4045em 2.427em}.wy-menu-vertical li.current a:hover{background:#d6d6d6}.wy-menu-vertical li code,.wy-menu-vertical li .rst-content tt,.rst-content .wy-menu-vertical li tt{border:none;background:inherit;color:inherit;padding-left:0;padding-right:0}.wy-menu-vertical li span.toctree-expand{display:block;float:left;margin-left:-1.2em;font-size:.8em;line-height:1.6em;color:#4d4d4d}.wy-menu-vertical li.on a,.wy-menu-vertical li.current>a{color:#404040;padding:.4045em 1.618em;font-weight:bold;position:relative;background:#fcfcfc;border:none;padding-left:1.618em -4px}.wy-menu-vertical li.on a:hover,.wy-menu-vertical li.current>a:hover{background:#fcfcfc}.wy-menu-vertical li.on a:hover span.toctree-expand,.wy-menu-vertical li.current>a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand{display:block;font-size:.8em;line-height:1.6em;color:#333}.wy-menu-vertical li.toctree-l1.current>a{border-bottom:solid 1px #c9c9c9;border-top:solid 1px #c9c9c9}.wy-menu-vertical li.toctree-l2 a,.wy-menu-vertical li.toctree-l3 a,.wy-menu-vertical li.toctree-l4 a{color:#404040}.wy-menu-vertical li.toctree-l1.current li.toctree-l2>ul,.wy-menu-vertical li.toctree-l2.current li.toctree-l3>ul{display:none}.wy-menu-vertical li.toctree-l1.current li.toctree-l2.current>ul,.wy-menu-vertical li.toctree-l2.current li.toctree-l3.current>ul{display:block}.wy-menu-vertical li.toctree-l2.current>a{background:#c9c9c9;padding:.4045em 2.427em}.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a{display:block;background:#c9c9c9;padding:.4045em 4.045em}.wy-menu-vertical li.toctree-l2 a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.toctree-l2 span.toctree-expand{color:#a3a3a3}.wy-menu-vertical li.toctree-l3{font-size:.9em}.wy-menu-vertical li.toctree-l3.current>a{background:#bdbdbd;padding:.4045em 4.045em}.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a{display:block;background:#bdbdbd;padding:.4045em 5.663em}.wy-menu-vertical li.toctree-l3 a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.toctree-l3 span.toctree-expand{color:#969696}.wy-menu-vertical li.toctree-l4{font-size:.9em}.wy-menu-vertical li.current ul{display:block}.wy-menu-vertical li ul{margin-bottom:0;display:none}.wy-menu-vertical li ul li a{margin-bottom:0;color:#d9d9d9;font-weight:normal}.wy-menu-vertical a{display:inline-block;line-height:18px;padding:.4045em 1.618em;display:block;position:relative;font-size:90%;color:#d9d9d9}.wy-menu-vertical a:hover{background-color:#4e4a4a;cursor:pointer}.wy-menu-vertical a:hover span.toctree-expand{color:#d9d9d9}.wy-menu-vertical a:active{background-color:#2980B9;cursor:pointer;color:#fff}.wy-menu-vertical a:active span.toctree-expand{color:#fff}.wy-side-nav-search{display:block;width:300px;padding:.809em;margin-bottom:.809em;z-index:200;background-color:#2980B9;text-align:center;padding:.809em;display:block;color:#fcfcfc;margin-bottom:.809em}.wy-side-nav-search input[type=text]{width:100%;border-radius:50px;padding:6px 12px;border-color:#2472a4}.wy-side-nav-search img{display:block;margin:auto auto .809em auto;height:45px;width:45px;background-color:#2980B9;padding:5px;border-radius:100%}.wy-side-nav-search>a,.wy-side-nav-search .wy-dropdown>a{color:#fcfcfc;font-size:100%;font-weight:bold;display:inline-block;padding:4px 6px;margin-bottom:.809em}.wy-side-nav-search>a:hover,.wy-side-nav-search .wy-dropdown>a:hover{background:rgba(255,255,255,0.1)}.wy-side-nav-search>a img.logo,.wy-side-nav-search .wy-dropdown>a img.logo{display:block;margin:0 auto;height:auto;width:auto;border-radius:0;max-width:100%;background:transparent}.wy-side-nav-search>a.icon img.logo,.wy-side-nav-search .wy-dropdown>a.icon img.logo{margin-top:.85em}.wy-side-nav-search>div.version{margin-top:-.4045em;margin-bottom:.809em;font-weight:normal;color:rgba(255,255,255,0.3)}.wy-nav .wy-menu-vertical header{color:#2980B9}.wy-nav .wy-menu-vertical a{color:#b3b3b3}.wy-nav .wy-menu-vertical a:hover{background-color:#2980B9;color:#fff}[data-menu-wrap]{-webkit-transition:all .2s ease-in;-moz-transition:all .2s ease-in;transition:all .2s ease-in;position:absolute;opacity:1;width:100%;opacity:0}[data-menu-wrap].move-center{left:0;right:auto;opacity:1}[data-menu-wrap].move-left{right:auto;left:-100%;opacity:0}[data-menu-wrap].move-right{right:-100%;left:auto;opacity:0}.wy-body-for-nav{background:#fcfcfc}.wy-grid-for-nav{position:absolute;width:100%;height:100%}.wy-nav-side{position:fixed;top:0;bottom:0;left:0;padding-bottom:2em;width:300px;overflow-x:hidden;overflow-y:hidden;min-height:100%;color:#9b9b9b;background:#343131;z-index:200}.wy-side-scroll{width:320px;position:relative;overflow-x:hidden;overflow-y:scroll;height:100%}.wy-nav-top{display:none;background:#2980B9;color:#fff;padding:.4045em .809em;position:relative;line-height:50px;text-align:center;font-size:100%;*zoom:1}.wy-nav-top:before,.wy-nav-top:after{display:table;content:""}.wy-nav-top:after{clear:both}.wy-nav-top a{color:#fff;font-weight:bold}.wy-nav-top img{margin-right:12px;height:45px;width:45px;background-color:#2980B9;padding:5px;border-radius:100%}.wy-nav-top i{font-size:30px;float:left;cursor:pointer;padding-top:inherit}.wy-nav-content-wrap{margin-left:300px;background:#fcfcfc;min-height:100%}.wy-nav-content{padding:1.618em 3.236em;height:100%;max-width:800px;margin:auto}.wy-body-mask{position:fixed;width:100%;height:100%;background:rgba(0,0,0,0.2);display:none;z-index:499}.wy-body-mask.on{display:block}footer{color:gray}footer p{margin-bottom:12px}footer span.commit code,footer span.commit .rst-content tt,.rst-content footer span.commit tt{padding:0px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;font-size:1em;background:none;border:none;color:gray}.rst-footer-buttons{*zoom:1}.rst-footer-buttons:before,.rst-footer-buttons:after{width:100%}.rst-footer-buttons:before,.rst-footer-buttons:after{display:table;content:""}.rst-footer-buttons:after{clear:both}.rst-breadcrumbs-buttons{margin-top:12px;*zoom:1}.rst-breadcrumbs-buttons:before,.rst-breadcrumbs-buttons:after{display:table;content:""}.rst-breadcrumbs-buttons:after{clear:both}#search-results .search li{margin-bottom:24px;border-bottom:solid 1px #e1e4e5;padding-bottom:24px}#search-results .search li:first-child{border-top:solid 1px #e1e4e5;padding-top:24px}#search-results .search li a{font-size:120%;margin-bottom:12px;display:inline-block}#search-results .context{color:gray;font-size:90%}.genindextable li>ul{margin-left:24px}@media screen and (max-width: 768px){.wy-body-for-nav{background:#fcfcfc}.wy-nav-top{display:block}.wy-nav-side{left:-300px}.wy-nav-side.shift{width:85%;left:0}.wy-side-scroll{width:auto}.wy-side-nav-search{width:auto}.wy-menu.wy-menu-vertical{width:auto}.wy-nav-content-wrap{margin-left:0}.wy-nav-content-wrap .wy-nav-content{padding:1.618em}.wy-nav-content-wrap.shift{position:fixed;min-width:100%;left:85%;top:0;height:100%;overflow:hidden}}@media screen and (min-width: 1100px){.wy-nav-content-wrap{background:rgba(0,0,0,0.05)}.wy-nav-content{margin:0;background:#fcfcfc}}@media print{.rst-versions,footer,.wy-nav-side{display:none}.wy-nav-content-wrap{margin-left:0}}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;z-index:400}.rst-versions a{color:#2980B9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27AE60;*zoom:1}.rst-versions .rst-current-version:before,.rst-versions .rst-current-version:after{display:table;content:""}.rst-versions .rst-current-version:after{clear:both}.rst-versions .rst-current-version .fa,.rst-versions .rst-current-version .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .rst-versions .rst-current-version span.toctree-expand,.rst-versions .rst-current-version .rst-content .admonition-title,.rst-content .rst-versions .rst-current-version .admonition-title,.rst-versions .rst-current-version .rst-content h1 .headerlink,.rst-content h1 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h2 .headerlink,.rst-content h2 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h3 .headerlink,.rst-content h3 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h4 .headerlink,.rst-content h4 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h5 .headerlink,.rst-content h5 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h6 .headerlink,.rst-content h6 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content dl dt .headerlink,.rst-content dl dt .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content p.caption .headerlink,.rst-content p.caption .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content table>caption .headerlink,.rst-content table>caption .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content .code-block-caption .headerlink,.rst-content .code-block-caption .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content tt.download span:first-child,.rst-content tt.download .rst-versions .rst-current-version span:first-child,.rst-versions .rst-current-version .rst-content code.download span:first-child,.rst-content code.download .rst-versions .rst-current-version span:first-child,.rst-versions .rst-current-version .icon{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#E74C3C;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#F1C40F;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:gray;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:solid 1px #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge .rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width: 768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}}.rst-content img{max-width:100%;height:auto}.rst-content div.figure{margin-bottom:24px}.rst-content div.figure p.caption{font-style:italic}.rst-content div.figure p:last-child.caption{margin-bottom:0px}.rst-content div.figure.align-center{text-align:center}.rst-content .section>img,.rst-content .section>a>img{margin-bottom:24px}.rst-content abbr[title]{text-decoration:none}.rst-content.style-external-links a.reference.external:after{font-family:FontAwesome;content:"";color:#b3b3b3;vertical-align:super;font-size:60%;margin:0 .2em}.rst-content blockquote{margin-left:24px;line-height:24px;margin-bottom:24px}.rst-content pre.literal-block{white-space:pre;margin:0;padding:12px 12px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;display:block;overflow:auto}.rst-content pre.literal-block,.rst-content div[class^='highlight']{border:1px solid #e1e4e5;overflow-x:auto;margin:1px 0 24px 0}.rst-content pre.literal-block div[class^='highlight'],.rst-content div[class^='highlight'] div[class^='highlight']{padding:0px;border:none;margin:0}.rst-content div[class^='highlight'] td.code{width:100%}.rst-content .linenodiv pre{border-right:solid 1px #e6e9ea;margin:0;padding:12px 12px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;user-select:none;pointer-events:none}.rst-content div[class^='highlight'] pre{white-space:pre;margin:0;padding:12px 12px;display:block;overflow:auto}.rst-content div[class^='highlight'] pre .hll{display:block;margin:0 -12px;padding:0 12px}.rst-content pre.literal-block,.rst-content div[class^='highlight'] pre,.rst-content .linenodiv pre{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;font-size:12px;line-height:1.4}.rst-content .code-block-caption{font-style:italic;font-size:85%;line-height:1;padding:1em 0;text-align:center}@media print{.rst-content .codeblock,.rst-content div[class^='highlight'],.rst-content div[class^='highlight'] pre{white-space:pre-wrap}}.rst-content .note .last,.rst-content .attention .last,.rst-content .caution .last,.rst-content .danger .last,.rst-content .error .last,.rst-content .hint .last,.rst-content .important .last,.rst-content .tip .last,.rst-content .warning .last,.rst-content .seealso .last,.rst-content .admonition-todo .last,.rst-content .admonition .last{margin-bottom:0}.rst-content .admonition-title:before{margin-right:4px}.rst-content .admonition table{border-color:rgba(0,0,0,0.1)}.rst-content .admonition table td,.rst-content .admonition table th{background:transparent !important;border-color:rgba(0,0,0,0.1) !important}.rst-content .section ol.loweralpha,.rst-content .section ol.loweralpha li{list-style:lower-alpha}.rst-content .section ol.upperalpha,.rst-content .section ol.upperalpha li{list-style:upper-alpha}.rst-content .section ol p,.rst-content .section ul p{margin-bottom:12px}.rst-content .section ol p:last-child,.rst-content .section ul p:last-child{margin-bottom:24px}.rst-content .line-block{margin-left:0px;margin-bottom:24px;line-height:24px}.rst-content .line-block .line-block{margin-left:24px;margin-bottom:0px}.rst-content .topic-title{font-weight:bold;margin-bottom:12px}.rst-content .toc-backref{color:#404040}.rst-content .align-right{float:right;margin:0px 0px 24px 24px}.rst-content .align-left{float:left;margin:0px 24px 24px 0px}.rst-content .align-center{margin:auto}.rst-content .align-center:not(table){display:block}.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content .toctree-wrapper p.caption .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink,.rst-content .code-block-caption .headerlink{visibility:hidden;font-size:14px}.rst-content h1 .headerlink:after,.rst-content h2 .headerlink:after,.rst-content .toctree-wrapper p.caption .headerlink:after,.rst-content h3 .headerlink:after,.rst-content h4 .headerlink:after,.rst-content h5 .headerlink:after,.rst-content h6 .headerlink:after,.rst-content dl dt .headerlink:after,.rst-content p.caption .headerlink:after,.rst-content table>caption .headerlink:after,.rst-content .code-block-caption .headerlink:after{content:"";font-family:FontAwesome}.rst-content h1:hover .headerlink:after,.rst-content h2:hover .headerlink:after,.rst-content .toctree-wrapper p.caption:hover .headerlink:after,.rst-content h3:hover .headerlink:after,.rst-content h4:hover .headerlink:after,.rst-content h5:hover .headerlink:after,.rst-content h6:hover .headerlink:after,.rst-content dl dt:hover .headerlink:after,.rst-content p.caption:hover .headerlink:after,.rst-content table>caption:hover .headerlink:after,.rst-content .code-block-caption:hover .headerlink:after{visibility:visible}.rst-content table>caption .headerlink:after{font-size:12px}.rst-content .centered{text-align:center}.rst-content .sidebar{float:right;width:40%;display:block;margin:0 0 24px 24px;padding:24px;background:#f3f6f6;border:solid 1px #e1e4e5}.rst-content .sidebar p,.rst-content .sidebar ul,.rst-content .sidebar dl{font-size:90%}.rst-content .sidebar .last{margin-bottom:0}.rst-content .sidebar .sidebar-title{display:block;font-family:"Roboto Slab","ff-tisa-web-pro","Georgia",Arial,sans-serif;font-weight:bold;background:#e1e4e5;padding:6px 12px;margin:-24px;margin-bottom:24px;font-size:100%}.rst-content .highlighted{background:#F1C40F;display:inline-block;font-weight:bold;padding:0 6px}.rst-content .footnote-reference,.rst-content .citation-reference{vertical-align:baseline;position:relative;top:-0.4em;line-height:0;font-size:90%}.rst-content table.docutils.citation,.rst-content table.docutils.footnote{background:none;border:none;color:gray}.rst-content table.docutils.citation td,.rst-content table.docutils.citation tr,.rst-content table.docutils.footnote td,.rst-content table.docutils.footnote tr{border:none;background-color:transparent !important;white-space:normal}.rst-content table.docutils.citation td.label,.rst-content table.docutils.footnote td.label{padding-left:0;padding-right:0;vertical-align:top}.rst-content table.docutils.citation tt,.rst-content table.docutils.citation code,.rst-content table.docutils.footnote tt,.rst-content table.docutils.footnote code{color:#555}.rst-content .wy-table-responsive.citation,.rst-content .wy-table-responsive.footnote{margin-bottom:0}.rst-content .wy-table-responsive.citation+:not(.citation),.rst-content .wy-table-responsive.footnote+:not(.footnote){margin-top:24px}.rst-content .wy-table-responsive.citation:last-child,.rst-content .wy-table-responsive.footnote:last-child{margin-bottom:24px}.rst-content table.docutils th{border-color:#e1e4e5}.rst-content table.docutils td .last,.rst-content table.docutils td .last :last-child{margin-bottom:0}.rst-content table.field-list{border:none}.rst-content table.field-list td{border:none}.rst-content table.field-list td p{font-size:inherit;line-height:inherit}.rst-content table.field-list td>strong{display:inline-block}.rst-content table.field-list .field-name{padding-right:10px;text-align:left;white-space:nowrap}.rst-content table.field-list .field-body{text-align:left}.rst-content tt,.rst-content tt,.rst-content code{color:#000;font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace;padding:2px 5px}.rst-content tt big,.rst-content tt em,.rst-content tt big,.rst-content code big,.rst-content tt em,.rst-content code em{font-size:100% !important;line-height:normal}.rst-content tt.literal,.rst-content tt.literal,.rst-content code.literal{color:#E74C3C}.rst-content tt.xref,a .rst-content tt,.rst-content tt.xref,.rst-content code.xref,a .rst-content tt,a .rst-content code{font-weight:bold;color:#404040}.rst-content pre,.rst-content kbd,.rst-content samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",Courier,monospace}.rst-content a tt,.rst-content a tt,.rst-content a code{color:#2980B9}.rst-content dl{margin-bottom:24px}.rst-content dl dt{font-weight:bold;margin-bottom:12px}.rst-content dl p,.rst-content dl table,.rst-content dl ul,.rst-content dl ol{margin-bottom:12px !important}.rst-content dl dd{margin:0 0 12px 24px;line-height:24px}.rst-content dl:not(.docutils){margin-bottom:24px}.rst-content dl:not(.docutils) dt{display:table;margin:6px 0;font-size:90%;line-height:normal;background:#e7f2fa;color:#2980B9;border-top:solid 3px #6ab0de;padding:6px;position:relative}.rst-content dl:not(.docutils) dt:before{color:#6ab0de}.rst-content dl:not(.docutils) dt .headerlink{color:#404040;font-size:100% !important}.rst-content dl:not(.docutils) dl dt{margin-bottom:6px;border:none;border-left:solid 3px #ccc;background:#f0f0f0;color:#555}.rst-content dl:not(.docutils) dl dt .headerlink{color:#404040;font-size:100% !important}.rst-content dl:not(.docutils) dt:first-child{margin-top:0}.rst-content dl:not(.docutils) tt,.rst-content dl:not(.docutils) tt,.rst-content dl:not(.docutils) code{font-weight:bold}.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) tt.descclassname,.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) code.descname,.rst-content dl:not(.docutils) tt.descclassname,.rst-content dl:not(.docutils) code.descclassname{background-color:transparent;border:none;padding:0;font-size:100% !important}.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) code.descname{font-weight:bold}.rst-content dl:not(.docutils) .optional{display:inline-block;padding:0 4px;color:#000;font-weight:bold}.rst-content dl:not(.docutils) .property{display:inline-block;padding-right:8px}.rst-content .viewcode-link,.rst-content .viewcode-back{display:inline-block;color:#27AE60;font-size:80%;padding-left:24px}.rst-content .viewcode-back{display:block;float:right}.rst-content p.rubric{margin-bottom:12px;font-weight:bold}.rst-content tt.download,.rst-content code.download{background:inherit;padding:inherit;font-weight:normal;font-family:inherit;font-size:inherit;color:inherit;border:inherit;white-space:inherit}.rst-content tt.download span:first-child,.rst-content code.download span:first-child{-webkit-font-smoothing:subpixel-antialiased}.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before{margin-right:4px}.rst-content .guilabel{border:1px solid #7fbbe3;background:#e7f2fa;font-size:80%;font-weight:700;border-radius:4px;padding:2.4px 6px;margin:auto 2px}.rst-content .versionmodified{font-style:italic}@media screen and (max-width: 480px){.rst-content .sidebar{width:100%}}span[id*='MathJax-Span']{color:#404040}.math{text-align:center}@font-face{font-family:"Lato";src:url("../fonts/Lato/lato-regular.eot");src:url("../fonts/Lato/lato-regular.eot?#iefix") format("embedded-opentype"),url("../fonts/Lato/lato-regular.woff2") format("woff2"),url("../fonts/Lato/lato-regular.woff") format("woff"),url("../fonts/Lato/lato-regular.ttf") format("truetype");font-weight:400;font-style:normal}@font-face{font-family:"Lato";src:url("../fonts/Lato/lato-bold.eot");src:url("../fonts/Lato/lato-bold.eot?#iefix") format("embedded-opentype"),url("../fonts/Lato/lato-bold.woff2") format("woff2"),url("../fonts/Lato/lato-bold.woff") format("woff"),url("../fonts/Lato/lato-bold.ttf") format("truetype");font-weight:700;font-style:normal}@font-face{font-family:"Lato";src:url("../fonts/Lato/lato-bolditalic.eot");src:url("../fonts/Lato/lato-bolditalic.eot?#iefix") format("embedded-opentype"),url("../fonts/Lato/lato-bolditalic.woff2") format("woff2"),url("../fonts/Lato/lato-bolditalic.woff") format("woff"),url("../fonts/Lato/lato-bolditalic.ttf") format("truetype");font-weight:700;font-style:italic}@font-face{font-family:"Lato";src:url("../fonts/Lato/lato-italic.eot");src:url("../fonts/Lato/lato-italic.eot?#iefix") format("embedded-opentype"),url("../fonts/Lato/lato-italic.woff2") format("woff2"),url("../fonts/Lato/lato-italic.woff") format("woff"),url("../fonts/Lato/lato-italic.ttf") format("truetype");font-weight:400;font-style:italic}@font-face{font-family:"Roboto Slab";font-style:normal;font-weight:400;src:url("../fonts/RobotoSlab/roboto-slab.eot");src:url("../fonts/RobotoSlab/roboto-slab-v7-regular.eot?#iefix") format("embedded-opentype"),url("../fonts/RobotoSlab/roboto-slab-v7-regular.woff2") format("woff2"),url("../fonts/RobotoSlab/roboto-slab-v7-regular.woff") format("woff"),url("../fonts/RobotoSlab/roboto-slab-v7-regular.ttf") format("truetype")}@font-face{font-family:"Roboto Slab";font-style:normal;font-weight:700;src:url("../fonts/RobotoSlab/roboto-slab-v7-bold.eot");src:url("../fonts/RobotoSlab/roboto-slab-v7-bold.eot?#iefix") format("embedded-opentype"),url("../fonts/RobotoSlab/roboto-slab-v7-bold.woff2") format("woff2"),url("../fonts/RobotoSlab/roboto-slab-v7-bold.woff") format("woff"),url("../fonts/RobotoSlab/roboto-slab-v7-bold.ttf") format("truetype")} ================================================ FILE: docs/_static/custom.css ================================================ /* This file intentionally left blank. */ ================================================ FILE: docs/_static/doctools.js ================================================ /* * doctools.js * ~~~~~~~~~~~ * * Sphinx JavaScript utilities for all documentation. * * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ /** * select a different prefix for underscore */ $u = _.noConflict(); /** * make the code below compatible with browsers without * an installed firebug like debugger if (!window.console || !console.firebug) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; } */ /** * small helper function to urldecode strings */ jQuery.urldecode = function(x) { return decodeURIComponent(x).replace(/\+/g, ' '); }; /** * small helper function to urlencode strings */ jQuery.urlencode = encodeURIComponent; /** * This function returns the parsed url parameters of the * current request. Multiple values per key are supported, * it will always return arrays of strings for the value parts. */ jQuery.getQueryParameters = function(s) { if (typeof s === 'undefined') s = document.location.search; var parts = s.substr(s.indexOf('?') + 1).split('&'); var result = {}; for (var i = 0; i < parts.length; i++) { var tmp = parts[i].split('=', 2); var key = jQuery.urldecode(tmp[0]); var value = jQuery.urldecode(tmp[1]); if (key in result) result[key].push(value); else result[key] = [value]; } return result; }; /** * highlight a given string on a jquery object by wrapping it in * span elements with the given class name. */ jQuery.fn.highlightText = function(text, className) { function highlight(node, addItems) { if (node.nodeType === 3) { var val = node.nodeValue; var pos = val.toLowerCase().indexOf(text); if (pos >= 0 && !jQuery(node.parentNode).hasClass(className) && !jQuery(node.parentNode).hasClass("nohighlight")) { var span; var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); if (isInSVG) { span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); } else { span = document.createElement("span"); span.className = className; } span.appendChild(document.createTextNode(val.substr(pos, text.length))); node.parentNode.insertBefore(span, node.parentNode.insertBefore( document.createTextNode(val.substr(pos + text.length)), node.nextSibling)); node.nodeValue = val.substr(0, pos); if (isInSVG) { var bbox = span.getBBox(); var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); rect.x.baseVal.value = bbox.x; rect.y.baseVal.value = bbox.y; rect.width.baseVal.value = bbox.width; rect.height.baseVal.value = bbox.height; rect.setAttribute('class', className); var parentOfText = node.parentNode.parentNode; addItems.push({ "parent": node.parentNode, "target": rect}); } } } else if (!jQuery(node).is("button, select, textarea")) { jQuery.each(node.childNodes, function() { highlight(this, addItems); }); } } var addItems = []; var result = this.each(function() { highlight(this, addItems); }); for (var i = 0; i < addItems.length; ++i) { jQuery(addItems[i].parent).before(addItems[i].target); } return result; }; /* * backward compatibility for jQuery.browser * This will be supported until firefox bug is fixed. */ if (!jQuery.browser) { jQuery.uaMatch = function(ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; jQuery.browser = {}; jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; } /** * Small JavaScript module for the documentation. */ var Documentation = { init : function() { this.fixFirefoxAnchorBug(); this.highlightSearchWords(); this.initIndexTable(); if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { this.initOnKeyListeners(); } }, /** * i18n support */ TRANSLATIONS : {}, PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, LOCALE : 'unknown', // gettext and ngettext don't access this so that the functions // can safely bound to a different name (_ = Documentation.gettext) gettext : function(string) { var translated = Documentation.TRANSLATIONS[string]; if (typeof translated === 'undefined') return string; return (typeof translated === 'string') ? translated : translated[0]; }, ngettext : function(singular, plural, n) { var translated = Documentation.TRANSLATIONS[singular]; if (typeof translated === 'undefined') return (n == 1) ? singular : plural; return translated[Documentation.PLURALEXPR(n)]; }, addTranslations : function(catalog) { for (var key in catalog.messages) this.TRANSLATIONS[key] = catalog.messages[key]; this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); this.LOCALE = catalog.locale; }, /** * add context elements like header anchor links */ addContextElements : function() { $('div[id] > :header:first').each(function() { $('\u00B6'). attr('href', '#' + this.id). attr('title', _('Permalink to this headline')). appendTo(this); }); $('dt[id]').each(function() { $('\u00B6'). attr('href', '#' + this.id). attr('title', _('Permalink to this definition')). appendTo(this); }); }, /** * workaround a firefox stupidity * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 */ fixFirefoxAnchorBug : function() { if (document.location.hash && $.browser.mozilla) window.setTimeout(function() { document.location.href += ''; }, 10); }, /** * highlight the search words provided in the url in the text */ highlightSearchWords : function() { var params = $.getQueryParameters(); var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; if (terms.length) { var body = $('div.body'); if (!body.length) { body = $('body'); } window.setTimeout(function() { $.each(terms, function() { body.highlightText(this.toLowerCase(), 'highlighted'); }); }, 10); $('') .appendTo($('#searchbox')); } }, /** * init the domain index toggle buttons */ initIndexTable : function() { var togglers = $('img.toggler').click(function() { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); $('tr.cg-' + idnum).toggle(); if (src.substr(-9) === 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); }).css('display', ''); if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { togglers.click(); } }, /** * helper function to hide the search marks again */ hideSearchWords : function() { $('#searchbox .highlight-link').fadeOut(300); $('span.highlighted').removeClass('highlighted'); }, /** * make the url absolute */ makeURL : function(relativeURL) { return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; }, /** * get the current relative url */ getCurrentURL : function() { var path = document.location.pathname; var parts = path.split(/\//); $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { if (this === '..') parts.pop(); }); var url = parts.join('/'); return path.substring(url.lastIndexOf('/') + 1, path.length - 1); }, initOnKeyListeners: function() { $(document).keyup(function(event) { var activeElementType = document.activeElement.tagName; // don't navigate when in search box or textarea if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { switch (event.keyCode) { case 37: // left var prevHref = $('link[rel="prev"]').prop('href'); if (prevHref) { window.location.href = prevHref; return false; } case 39: // right var nextHref = $('link[rel="next"]').prop('href'); if (nextHref) { window.location.href = nextHref; return false; } } } }); } }; // quick alias for translations _ = Documentation.gettext; $(document).ready(function() { Documentation.init(); }); ================================================ FILE: docs/_static/documentation_options.js ================================================ var DOCUMENTATION_OPTIONS = { URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), VERSION: '1.2.0', LANGUAGE: 'zh_CN', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt', NAVIGATION_WITH_KEYS: false, }; ================================================ FILE: docs/_static/jquery-3.2.1.js ================================================ /*! * jQuery JavaScript Library v3.2.1 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2017-03-20T18:59Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var document = window.document; var getProto = Object.getPrototypeOf; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; function DOMEval( code, doc ) { doc = doc || document; var script = doc.createElement( "script" ); script.text = code; doc.head.appendChild( script ).parentNode.removeChild( script ); } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.2.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android <=4.0 only // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && Array.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // As of jQuery 3.0, isNumeric is limited to // strings and numbers (primitives or objects) // that can be coerced to finite numbers (gh-2662) var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && // parseFloat NaNs numeric-cast false positives ("") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN !isNaN( obj - parseFloat( obj ) ); }, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { /* eslint-disable no-unused-vars */ // See https://github.com/eslint/eslint/issues/6125 var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { DOMEval( code ); }, // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 13 // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android <=4.0 only trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.3 * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-08-08 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, disabledAncestor = addCombinator( function( elem ) { return elem.disabled === true && ("form" in elem || "label" in elem); }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && disabledAncestor( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID filter and find if ( support.getById ) { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( (elem = elems[i++]) ) { node = elem.getAttributeNode("id"); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "" + ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "" + ""; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( el ) { el.innerHTML = ""; return el.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( el ) { el.innerHTML = ""; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( el ) { return el.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Simple selector that can be filtered directly, removing non-Elements if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } // Complex selector, compare the two sets, removing non-Elements qualifier = jQuery.filter( qualifier, elements ); return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; } ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } if ( elems.length === 1 && elem.nodeType === 1 ) { return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; } return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { if ( nodeName( elem, "iframe" ) ) { return elem.contentDocument; } // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only // Treat the template element as a regular one in browsers that // don't support it. if ( nodeName( elem, "template" ) ) { elem = elem.content || elem; } return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject, noValue ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: // * false: [ value ].slice( 0 ) => resolve( value ) // * true: [ value ].slice( 1 ) => resolve() resolve.apply( undefined, [ value ].slice( noValue ) ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.apply( undefined, [ value ] ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( jQuery.isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }; var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ jQuery.camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ jQuery.camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( jQuery.camelCase ); } else { key = jQuery.camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || Array.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. jQuery.contains( elem.ownerDocument, elem ) && jQuery.css( elem, "display" ) === "none"; }; var swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE <=9 only option: [ 1, "" ], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting or other required elements. thead: [ 1, "", "
" ], col: [ 2, "", "
" ], tr: [ 2, "", "
" ], td: [ 3, "", "
" ], _default: [ 0, "", "" ] }; // Support: IE <=9 only wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { ret = context.getElementsByTagName( tag || "*" ); } else if ( typeof context.querySelectorAll !== "undefined" ) { ret = context.querySelectorAll( tag || "*" ); } else { ret = []; } if ( tag === undefined || tag && nodeName( context, tag ) ) { return jQuery.merge( [ context ], ret ); } return ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); var documentElement = document.documentElement; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 only // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = {}; } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { // Make a writable jQuery.Event from the native event object var event = jQuery.event.fix( nativeEvent ); var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers if ( delegateCount && // Support: IE <=9 // Black-hole SVG instance trees (trac-13180) cur.nodeType && // Support: Firefox <=42 // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click // Support: IE 11 only // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matchedSelectors[ sel ] ) { matchedHandlers.push( handleObj ); } } if ( matchedHandlers.length ) { handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers cur = this; if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: jQuery.isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { if ( button & 1 ) { return 1; } if ( button & 2 ) { return 3; } if ( button & 4 ) { return 2; } return 0; } return event.which; } }, jQuery.event.addProp ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var /* eslint-disable max-len */ // See https://github.com/eslint/eslint/issues/3229 rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, /* eslint-enable */ // Support: IE <=10 - 11, Edge 12 - 13 // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( ">tbody", elem )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rmargin = ( /^margin/ ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } div.style.cssText = "box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; div.innerHTML = ""; documentElement.appendChild( container ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = divStyle.marginLeft === "2px"; boxSizingReliableVal = divStyle.width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = divStyle.marginRight === "4px"; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; container.appendChild( div ); jQuery.extend( support, { pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelMarginRight: function() { computeStyleTests(); return pixelMarginRightVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, // Support: Firefox 51+ // Retrieving style before computed somehow // fixes an issue with getting wrong values // on detached elements style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is needed for: // .css('filter') (IE 9 only, #12537) // .css('--customProperty) (#3144) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // Shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return name; } // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } // Return a property mapped along what jQuery.cssProps suggests or to // a vendor prefixed property. function finalPropName( name ) { var ret = jQuery.cssProps[ name ]; if ( !ret ) { ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; } return ret; } function setPositiveNumber( elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i, val = 0; // If we already have the right measurement, avoid augmentation if ( extra === ( isBorderBox ? "border" : "content" ) ) { i = 4; // Otherwise initialize for horizontal or vertical properties } else { i = name === "width" ? 1 : 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with computed style var valueIsBorderBox, styles = getStyles( elem ), val = curCSS( elem, name, styles ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test( val ) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Fall back to offsetWidth/Height when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) if ( val === "auto" ) { val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ]; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) if ( type === "number" ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { style[ name ] = value; } } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); } ) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var matches, styles = extra && getStyles( elem ), subtract = extra && augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ); // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ name ] = value; value = jQuery.css( elem, name ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( Array.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 only // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back compat <1.8 extension point jQuery.fx.step = {}; var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function schedule() { if ( inProgress ) { if ( document.hidden === false && window.requestAnimationFrame ) { window.requestAnimationFrame( schedule ); } else { window.setTimeout( schedule, jQuery.fx.interval ); } jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11, Edge 12 - 13 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } /* eslint-disable no-loop-func */ anim.done( function() { /* eslint-enable no-loop-func */ // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( Array.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); // If there's more to do, yield if ( percent < 1 && length ) { return remaining; } // If this was an empty animation, synthesize a final progress notification if ( !length ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); } // Resolve the animation and report its conclusion deferred.resolveWith( elem, [ animation ] ); return false; }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, result ); } return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } // Attach callbacks from options animation .progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); return animation; } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnothtmlwhite ); } var prop, index = 0, length = props.length; for ( ; index < length; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; // Go to the end state if fx are off if ( jQuery.fx.off ) { opt.duration = 0; } else { if ( typeof opt.duration !== "number" ) { if ( opt.duration in jQuery.fx.speeds ) { opt.duration = jQuery.fx.speeds[ opt.duration ]; } else { opt.duration = jQuery.fx.speeds._default; } } } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Run the timer and safely remove it when done (allowing for external removal) if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); jQuery.fx.start(); }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( inProgress ) { return; } inProgress = true; schedule(); }; jQuery.fx.stop = function() { inProgress = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, // Attribute names can contain non-HTML whitespace characters // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 attrNames = value && value.match( rnothtmlwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { return parseInt( tabindex, 10 ); } if ( rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup // eslint rule "no-unused-expressions" is disabled for this code // since it considers such accessions noop if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); // Strip and collapse whitespace according to HTML spec // https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnothtmlwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnothtmlwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( type === "string" ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = value.match( rnothtmlwhite ) || []; while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, isFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; // Handle most common string cases if ( typeof ret === "string" ) { return ret.replace( rreturn, "" ); } // Handle cases where value is null/undef or number return ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( Array.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if ( index < 0 ) { i = max; } else { i = one ? index : 0; } // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; /* eslint-disable no-cond-assign */ if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( Array.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); jQuery.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); support.focusin = "onfocusin" in window; // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = jQuery.now(); var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( Array.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = jQuery.isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; // If an array was passed in, assume that it is an array of form elements. if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( i, elem ) { var val = jQuery( this ).val(); if ( val == null ) { return null; } if ( Array.isArray( val ) ) { return jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ); } return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11, Edge 12 - 13 // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11 only // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available, append data to url if ( s.data ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add or update anti-cache param if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rantiCache, "$1" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery._evalUrl = function( url ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, async: false, global: false, "throws": true } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( jQuery.isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE <=9 only // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE <=9 only // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE <=9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) jQuery.ajaxPrefilter( function( s ) { if ( s.crossDomain ) { s.contents.script = false; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "

config module

================================================ FILE: docs/constants.html ================================================ constants module — wukong-robot 1.2.0 文档

constants module

================================================ FILE: docs/drivers.html ================================================ drivers package — wukong-robot 1.2.0 文档

drivers package

Submodules

drivers.apa102 module

drivers.pixels module

Module contents

================================================ FILE: docs/genindex.html ================================================ 索引 — wukong-robot 1.2.0 文档

索引

A | B | C | D | E | F | G | H | I | L | M | N | O | P | Q | R | S | T | U | V | W | X

A

B

C

D

E

F

G

H

I

L

M

N

O

P

Q

R

S

T

U

V

W

X

================================================ FILE: docs/index.html ================================================ Welcome to wukong-robot’s documentation! — wukong-robot 1.2.0 文档

Welcome to wukong-robot’s documentation!

Indices and tables

================================================ FILE: docs/logging.html ================================================ logging module — wukong-robot 1.2.0 文档

logging module

Logging package for Python. Based on PEP 282 and comments thereto in comp.lang.python.

Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved.

To use, simply ‘import logging’ and log away!

class logging.BufferingFormatter(linefmt=None)[源代码]

基类:object

A formatter suitable for formatting a number of records.

format(records)[源代码]

Format the specified records and return the result as a string.

formatFooter(records)[源代码]

Return the footer string for the specified records.

formatHeader(records)[源代码]

Return the header string for the specified records.

class logging.FileHandler(filename, mode='a', encoding=None, delay=False)[源代码]

基类:logging.StreamHandler

A handler class which writes formatted logging records to disk files.

close()[源代码]

Closes the stream.

emit(record)[源代码]

Emit a record.

If the stream was not opened because ‘delay’ was specified in the constructor, open it before calling the superclass’s emit.

class logging.Filter(name='')[源代码]

基类:object

Filter instances are used to perform arbitrary filtering of LogRecords.

Loggers and Handlers can optionally use Filter instances to filter records as desired. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with “A.B” will allow events logged by loggers “A.B”, “A.B.C”, “A.B.C.D”, “A.B.D” etc. but not “A.BB”, “B.A.B” etc. If initialized with the empty string, all events are passed.

filter(record)[源代码]

Determine if the specified record is to be logged.

Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.

class logging.Formatter(fmt=None, datefmt=None, style='%')[源代码]

基类:object

Formatter instances are used to convert a LogRecord to text.

Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the default value of “%s(message)” is used.

The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user’s message and arguments are pre- formatted into a LogRecord’s message attribute. Currently, the useful attributes in a LogRecord are described by:

%(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO,

WARNING, ERROR, CRITICAL)
%(levelname)s Text logging level for the message (“DEBUG”, “INFO”,
“WARNING”, “ERROR”, “CRITICAL”)
%(pathname)s Full pathname of the source file where the logging
call was issued (if available)

%(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued

(if available)

%(funcName)s Function name %(created)f Time when the LogRecord was created (time.time()

return value)

%(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created,

relative to the time the logging module was loaded (typically at application startup time)

%(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as

the record is emitted
converter()
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time. When ‘seconds’ is not passed in, convert the current time instead.

default_msec_format = '%s,%03d'
default_time_format = '%Y-%m-%d %H:%M:%S'
format(record)[源代码]

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

formatException(ei)[源代码]

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

formatMessage(record)[源代码]
formatStack(stack_info)[源代码]

This method is provided as an extension point for specialized formatting of stack information.

The input data is a string as returned from a call to traceback.print_stack(), but with the last trailing newline removed.

The base implementation just returns the value passed in.

formatTime(record, datefmt=None)[源代码]

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

usesTime()[源代码]

Check if the format uses the creation time of the record.

class logging.Handler(level=0)[源代码]

基类:logging.Filterer

Handler instances dispatch logging events to specific destinations.

The base handler class. Acts as a placeholder which defines the Handler interface. Handlers can optionally use Formatter instances to format records as desired. By default, no formatter is specified; in this case, the ‘raw’ message as determined by record.message is logged.

acquire()[源代码]

Acquire the I/O thread lock.

close()[源代码]

Tidy up any resources used by the handler.

This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.

createLock()[源代码]

Acquire a thread lock for serializing access to the underlying I/O.

emit(record)[源代码]

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

flush()[源代码]

Ensure all logging output has been flushed.

This version does nothing and is intended to be implemented by subclasses.

format(record)[源代码]

Format the specified record.

If a formatter is set, use it. Otherwise, use the default formatter for the module.

get_name()[源代码]
handle(record)[源代码]

Conditionally emit the specified logging record.

Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.

handleError(record)[源代码]

Handle errors which occur during an emit() call.

This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method.

name
release()[源代码]

Release the I/O thread lock.

setFormatter(fmt)[源代码]

Set the formatter for this handler.

setLevel(level)[源代码]

Set the logging level of this handler. level must be an int or a str.

set_name(name)[源代码]
class logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs)[源代码]

基类:object

A LogRecord instance represents an event being logged.

LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in msg and args, which are combined using str(msg) % args to create the message field of the record. The record also includes information such as when the record was created, the source line where the logging call was made, and any exception information to be logged.

getMessage()[源代码]

Return the message for this LogRecord.

Return the message for this LogRecord after merging any user-supplied arguments with the message.

class logging.Logger(name, level=0)[源代码]

基类:logging.Filterer

Instances of the Logger class represent a single logging channel. A “logging channel” indicates an area of an application. Exactly how an “area” is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of “input processing” might include sub-areas “read CSV files”, “read XLS files” and “read Gnumeric files”). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be “input” for the upper level, and “input.csv”, “input.xls” and “input.gnu” for the sub-levels. There is no arbitrary limit to the depth of nesting.

addHandler(hdlr)[源代码]

Add the specified handler to this logger.

callHandlers(record)[源代码]

Pass a record to all relevant handlers.

Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the “propagate” attribute set to zero is found - that will be the last logger whose handlers are called.

critical(msg, *args, **kwargs)[源代码]

Log ‘msg % args’ with severity ‘CRITICAL’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

debug(msg, *args, **kwargs)[源代码]

Log ‘msg % args’ with severity ‘DEBUG’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.debug(“Houston, we have a %s”, “thorny problem”, exc_info=1)

error(msg, *args, **kwargs)[源代码]

Log ‘msg % args’ with severity ‘ERROR’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.error(“Houston, we have a %s”, “major problem”, exc_info=1)

exception(msg, *args, exc_info=True, **kwargs)[源代码]

Convenience method for logging an ERROR with exception information.

fatal(msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘CRITICAL’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

findCaller(stack_info=False)[源代码]

Find the stack frame of the caller so that we can note the source file name, line number and function name.

getChild(suffix)[源代码]

Get a logger which is a descendant to this one.

This is a convenience method, such that

logging.getLogger(‘abc’).getChild(‘def.ghi’)

is the same as

logging.getLogger(‘abc.def.ghi’)

It’s useful, for example, when the parent logger is named using __name__ rather than a literal string.

getEffectiveLevel()[源代码]

Get the effective level for this logger.

Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found.

handle(record)[源代码]

Call the handlers for the specified record.

This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied.

hasHandlers()[源代码]

See if this logger has any handlers configured.

Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the “propagate” attribute set to zero is found - that will be the last logger which is checked for the existence of handlers.

info(msg, *args, **kwargs)[源代码]

Log ‘msg % args’ with severity ‘INFO’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

isEnabledFor(level)[源代码]

Is this logger enabled for level ‘level’?

log(level, msg, *args, **kwargs)[源代码]

Log ‘msg % args’ with the integer severity ‘level’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.log(level, “We have a %s”, “mysterious problem”, exc_info=1)

makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)[源代码]

A factory method which can be overridden in subclasses to create specialized LogRecords.

manager = <logging.Manager object>
removeHandler(hdlr)[源代码]

Remove the specified handler from this logger.

root = <logging.RootLogger object>
setLevel(level)[源代码]

Set the logging level of this logger. level must be an int or a str.

warn(msg, *args, **kwargs)[源代码]
warning(msg, *args, **kwargs)[源代码]

Log ‘msg % args’ with severity ‘WARNING’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.warning(“Houston, we have a %s”, “bit of a problem”, exc_info=1)

class logging.LoggerAdapter(logger, extra)[源代码]

基类:object

An adapter for loggers which makes it easier to specify contextual information in logging output.

critical(msg, *args, **kwargs)[源代码]

Delegate a critical call to the underlying logger.

debug(msg, *args, **kwargs)[源代码]

Delegate a debug call to the underlying logger.

error(msg, *args, **kwargs)[源代码]

Delegate an error call to the underlying logger.

exception(msg, *args, exc_info=True, **kwargs)[源代码]

Delegate an exception call to the underlying logger.

getEffectiveLevel()[源代码]

Get the effective level for the underlying logger.

hasHandlers()[源代码]

See if the underlying logger has any handlers.

info(msg, *args, **kwargs)[源代码]

Delegate an info call to the underlying logger.

isEnabledFor(level)[源代码]

Is this logger enabled for level ‘level’?

log(level, msg, *args, **kwargs)[源代码]

Delegate a log call to the underlying logger, after adding contextual information from this adapter instance.

process(msg, kwargs)[源代码]

Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs.

Normally, you’ll only need to override this one method in a LoggerAdapter subclass for your specific needs.

setLevel(level)[源代码]

Set the specified level on the underlying logger.

warn(msg, *args, **kwargs)[源代码]
warning(msg, *args, **kwargs)[源代码]

Delegate a warning call to the underlying logger.

class logging.NullHandler(level=0)[源代码]

基类:logging.Handler

This handler does nothing. It’s intended to be used to avoid the “No handlers could be found for logger XXX” one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be produced; to avoid this, the library developer simply needs to instantiate a NullHandler and add it to the top-level logger of the library module or package.

createLock()[源代码]

Acquire a thread lock for serializing access to the underlying I/O.

emit(record)[源代码]

Stub.

handle(record)[源代码]

Stub.

class logging.StreamHandler(stream=None)[源代码]

基类:logging.Handler

A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used.

emit(record)[源代码]

Emit a record.

If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.

flush()[源代码]

Flushes the stream.

terminator = '\n'
logging.addLevelName(level, levelName)[源代码]

Associate ‘levelName’ with ‘level’.

This is used when converting levels to text during message formatting.

logging.basicConfig(**kwargs)[源代码]

Do basic configuration for the logging system.

This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package.

The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger.

A number of optional keyword arguments may be specified, which can alter the default behaviour.

filename Specifies that a FileHandler be created, using the specified
filename, rather than a StreamHandler.
filemode Specifies the mode to open the file, if filename is specified
(if filemode is unspecified, it defaults to ‘a’).

format Use the specified format string for the handler. datefmt Use the specified date/time format. style If a format string is specified, use this to specify the

type of format string (possible values ‘%’, ‘{‘, ‘$’, for %-formatting, str.format() and string.Template - defaults to ‘%’).

level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note

that this argument is incompatible with ‘filename’ - if both are present, ‘stream’ is ignored.
handlers If specified, this should be an iterable of already created
handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function.

Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed.

在 3.2 版更改: Added the style parameter.

在 3.3 版更改: Added the handlers parameter. A ValueError is now thrown for incompatible arguments (e.g. handlers specified together with filename/filemode, or filename/filemode specified together with stream, or handlers specified together with stream.

logging.captureWarnings(capture)[源代码]

If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations.

logging.critical(msg, *args, **kwargs)[源代码]

Log a message with severity ‘CRITICAL’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

logging.debug(msg, *args, **kwargs)[源代码]

Log a message with severity ‘DEBUG’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

logging.disable(level)[源代码]

Disable all logging calls of severity ‘level’ and below.

logging.error(msg, *args, **kwargs)[源代码]

Log a message with severity ‘ERROR’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

logging.exception(msg, *args, exc_info=True, **kwargs)[源代码]

Log a message with severity ‘ERROR’ on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format.

logging.fatal(msg, *args, **kwargs)

Log a message with severity ‘CRITICAL’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

logging.getLevelName(level)[源代码]

Return the textual representation of logging level ‘level’.

If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with ‘level’ is returned.

If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned.

Otherwise, the string “Level %s” % level is returned.

logging.getLogger(name=None)[源代码]

Return a logger with the specified name, creating it if necessary.

If no name is specified, return the root logger.

logging.getLoggerClass()[源代码]

Return the class to be used when instantiating a logger.

logging.info(msg, *args, **kwargs)[源代码]

Log a message with severity ‘INFO’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

logging.log(level, msg, *args, **kwargs)[源代码]

Log ‘msg % args’ with the integer severity ‘level’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

logging.makeLogRecord(dict)[源代码]

Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance.

logging.setLoggerClass(klass)[源代码]

Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__()

logging.warn(msg, *args, **kwargs)[源代码]
logging.warning(msg, *args, **kwargs)[源代码]

Log a message with severity ‘WARNING’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

logging.getLogRecordFactory()[源代码]

Return the factory to be used when instantiating a log record.

logging.setLogRecordFactory(factory)[源代码]

Set the factory to be used when instantiating a log record.

参数:factory – A callable which will be called to instantiate

a log record.

================================================ FILE: docs/modules.html ================================================ wukong-robot — wukong-robot 1.2.0 文档 ================================================ FILE: docs/plugin_loader.html ================================================ plugin_loader module — wukong-robot 1.2.0 文档

plugin_loader module

================================================ FILE: docs/plugins.html ================================================ plugins package — wukong-robot 1.2.0 文档

plugins package

Submodules

plugins.Camera module

class plugins.Camera.Plugin(con)[源代码]

基类:robot.sdk.AbstractPlugin.AbstractPlugin

SLUG = 'camera'
handle(text, parsed)[源代码]

处理逻辑

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

isValid(text, parsed)[源代码]

是否适合由该插件处理

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

返回: True: 适合由该插件处理 False: 不适合由该插件处理

plugins.CleanCache module

class plugins.CleanCache.Plugin(con)[源代码]

基类:robot.sdk.AbstractPlugin.AbstractPlugin

SLUG = 'cleancache'
handle(text, parsed)[源代码]

处理逻辑

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

isValid(text, parsed)[源代码]

是否适合由该插件处理

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

返回: True: 适合由该插件处理 False: 不适合由该插件处理

plugins.Echo module

class plugins.Echo.Plugin(con)[源代码]

基类:robot.sdk.AbstractPlugin.AbstractPlugin

handle(text, parsed)[源代码]

处理逻辑

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

isValid(text, parsed)[源代码]

是否适合由该插件处理

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

返回: True: 适合由该插件处理 False: 不适合由该插件处理

plugins.Email module

class plugins.Email.Plugin(con)[源代码]

基类:robot.sdk.AbstractPlugin.AbstractPlugin

SLUG = 'email'
fetchUnreadEmails(since=None, markRead=False, limit=None)[源代码]

Fetches a list of unread email objects from a user’s email inbox.

Arguments: since – if provided, no emails before this date will be returned markRead – if True, marks all returned emails as read in target inbox

Returns: A list of unread email objects.

getDate(email)[源代码]
getMostRecentDate(emails)[源代码]

Returns the most recent date of any email in the list provided.

Arguments: emails – a list of emails to check

Returns: Date of the most recent email.

getSender(msg)[源代码]

Returns the best-guess sender of an email.

Arguments: msg – the email whose sender is desired

Returns: Sender of the sender.

getSubject(msg)[源代码]

Returns the title of an email

Arguments: msg – the email

Returns: Title of the email.

handle(text, parsed)[源代码]

处理逻辑

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

isNewEmail()[源代码]

Wether an email is a new email

isSelfEmail(msg)[源代码]

Whether the email is sent by the user

isValid(text, parsed)[源代码]

是否适合由该插件处理

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

返回: True: 适合由该插件处理 False: 不适合由该插件处理

plugins.Geek module

class plugins.Geek.Plugin(con)[源代码]

基类:robot.sdk.AbstractPlugin.AbstractPlugin

IS_IMMERSIVE = True
handle(text, parsed)[源代码]

处理逻辑

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

isValid(text, parsed)[源代码]

是否适合由该插件处理

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

返回: True: 适合由该插件处理 False: 不适合由该插件处理

isValidImmersive(text, parsed)[源代码]

是否适合在沉浸模式下处理, 仅适用于有沉浸模式的插件(如音乐等) 当用户唤醒时,可以响应更多指令集。 例如:“”上一首”、”下一首” 等

onAsk(input)[源代码]
restore()[源代码]

恢复当前插件, 仅适用于有沉浸模式的插件(如音乐等) 当用户误唤醒或者唤醒进行闲聊后, 可以自动恢复当前插件的处理逻辑

plugins.LocalPlayer module

class plugins.LocalPlayer.Plugin(con)[源代码]

基类:robot.sdk.AbstractPlugin.AbstractPlugin

IS_IMMERSIVE = True
get_song_list(path)[源代码]
handle(text, parsed)[源代码]

处理逻辑

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

init_music_player()[源代码]
isValid(text, parsed)[源代码]

是否适合由该插件处理

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

返回: True: 适合由该插件处理 False: 不适合由该插件处理

isValidImmersive(text, parsed)[源代码]

是否适合在沉浸模式下处理, 仅适用于有沉浸模式的插件(如音乐等) 当用户唤醒时,可以响应更多指令集。 例如:“”上一首”、”下一首” 等

pause()[源代码]

暂停当前正在处理的任务, 当处于该沉浸模式下且被唤醒时, 将自动触发这个方法, 可以用于强制暂停一个耗时的操作

restore()[源代码]

恢复当前插件, 仅适用于有沉浸模式的插件(如音乐等) 当用户误唤醒或者唤醒进行闲聊后, 可以自动恢复当前插件的处理逻辑

plugins.Poem module

class plugins.Poem.Plugin(con)[源代码]

基类:robot.sdk.AbstractPlugin.AbstractPlugin

SLUG = 'poem'
handle(text, parsed)[源代码]

处理逻辑

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

isValid(text, parsed)[源代码]

是否适合由该插件处理

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

返回: True: 适合由该插件处理 False: 不适合由该插件处理

Module contents

================================================ FILE: docs/py-modindex.html ================================================ Python 模块索引 — wukong-robot 1.2.0 文档
  • Docs »
  • Python 模块索引

================================================ FILE: docs/robot.drivers.html ================================================ robot.drivers package — wukong-robot 1.2.0 文档

robot.drivers package

Submodules

robot.drivers.apa102 module

robot.drivers.pixels module

Module contents

================================================ FILE: docs/robot.html ================================================ robot package — wukong-robot 1.2.0 文档

robot package

Submodules

robot.AI module

class robot.AI.AbstractRobot(**kwargs)[源代码]

基类:object

chat(texts)[源代码]
classmethod get_instance()[源代码]
class robot.AI.Emotibot(appid, location, more)[源代码]

基类:robot.AI.AbstractRobot

SLUG = 'emotibot'
chat(texts)[源代码]

使用Emotibot机器人聊天

Arguments: texts – user input, typically speech, to be parsed by a module

classmethod get_config()[源代码]
class robot.AI.TulingRobot(tuling_key)[源代码]

基类:robot.AI.AbstractRobot

SLUG = 'tuling'
chat(texts)[源代码]

使用图灵机器人聊天

Arguments: texts – user input, typically speech, to be parsed by a module

classmethod get_config()[源代码]
robot.AI.get_robot_by_slug(slug)[源代码]
Returns:
A robot implementation available on the current platform
robot.AI.get_robots()[源代码]

robot.ASR module

class robot.ASR.AbstractASR[源代码]

基类:object

Generic parent class for all ASR engines

classmethod get_config()[源代码]
classmethod get_instance()[源代码]
transcribe(fp)[源代码]
class robot.ASR.AliASR(appKey, token, **args)[源代码]

基类:robot.ASR.AbstractASR

阿里的语音识别API.

SLUG = 'ali-asr'
classmethod get_config()[源代码]
transcribe(fp)[源代码]
class robot.ASR.BaiduASR(appid, api_key, secret_key, dev_pid=1936, **args)[源代码]

基类:robot.ASR.AbstractASR

百度的语音识别API. dev_pid:

  • 1936: 普通话远场
  • 1536:普通话(支持简单的英文识别)
  • 1537:普通话(纯中文识别)
  • 1737:英语
  • 1637:粤语
  • 1837:四川话

要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号, 之后创建一个新应用, 然后在应用管理的”查看key”中获得 API Key 和 Secret Key 填入 config.xml 中. …

baidu_yuyin:
appid: ‘9670645’ api_key: ‘qg4haN8b2bGvFtCbBGqhrmZy’ secret_key: ‘585d4eccb50d306c401d7df138bb02e7’

SLUG = 'baidu-asr'
classmethod get_config()[源代码]
transcribe(fp)[源代码]
class robot.ASR.TencentASR(appid, secretid, secret_key, region='ap-guangzhou', **args)[源代码]

基类:robot.ASR.AbstractASR

腾讯的语音识别API.

SLUG = 'tencent-asr'
classmethod get_config()[源代码]
transcribe(fp)[源代码]
class robot.ASR.XunfeiASR(appid, asr_api_key, asr_api_secret, tts_api_key, voice='xiaoyan')[源代码]

基类:robot.ASR.AbstractASR

科大讯飞的语音识别API. 外网ip查询:https://ip.51240.com/

SLUG = 'xunfei-asr'
classmethod get_config()[源代码]
transcribe(fp)[源代码]
robot.ASR.get_engine_by_slug(slug=None)[源代码]
Returns:
An ASR Engine implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
robot.ASR.get_engines()[源代码]

robot.Brain module

class robot.Brain.Brain(conversation)[源代码]

基类:object

isImmersive(plugin, text, parsed)[源代码]
pause()[源代码]

暂停某个技能的处理

printPlugins()[源代码]
query(text)[源代码]

query 模块

Arguments: text – 用户输入

restore()[源代码]

恢复某个技能的处理

say(msg, cache=False)[源代码]
understand(fp)[源代码]

robot.ConfigMonitor module

class robot.ConfigMonitor.ConfigMonitor(conversation)[源代码]

基类:watchdog.events.FileSystemEventHandler

on_modified(event)[源代码]

Called when a file or directory is modified.

参数:event (DirModifiedEvent or FileModifiedEvent) – Event representing file/directory modification.

robot.Conversation module

class robot.Conversation.Conversation(profiling=False)[源代码]

基类:object

activeListen(silent=False)[源代码]

主动问一个问题(适用于多轮对话)

appendHistory(t, text, UUID='')[源代码]

将会话历史加进历史记录

checkRestore()[源代码]
converse(fp, callback=None)[源代码]

核心对话逻辑

doConverse(fp, callback=None, onSay=None)[源代码]
doParse(query, **args)[源代码]
doResponse(query, UUID='', onSay=None)[源代码]
getHistory()[源代码]
getImmersiveMode()[源代码]
interrupt()[源代码]
pardon()[源代码]
play(src, delete=False, onCompleted=None, volume=1)[源代码]

播放一个音频

reload()[源代码]

重新初始化

say(msg, cache=False, plugin='', onCompleted=None, wait=False)[源代码]

说一句话 :param msg: 内容 :param cache: 是否缓存这句话的音频 :param plugin: 来自哪个插件的消息(将带上插件的说明) :param onCompleted: 完成的回调 :param wait: 是否要等待说完(为True将阻塞主线程直至说完这句话)

setImmersiveMode(slug)[源代码]

robot.NLU module

class robot.NLU.AbstractNLU[源代码]

基类:object

Generic parent class for all NLU engines

getIntent(parsed)[源代码]

提取意图

参数:parsed – 解析结果
返回:意图数组
getSay(parsed, intent)[源代码]

提取回复文本

参数:
  • parsed – 解析结果
  • intent – 意图的名称
返回:

回复文本

getSlotWords(parsed, intent, name)[源代码]

找出命中某个词槽的内容

参数:
  • parsed – 解析结果
  • intent – 意图的名称
  • name – 词槽名
返回:

命中该词槽的值的列表。

getSlots(parsed, intent)[源代码]

提取某个意图的所有词槽

参数:
  • parsed – 解析结果
  • intent – 意图的名称
返回:

词槽列表。你可以通过 name 属性筛选词槽,

再通过 normalized_word 属性取出相应的值

classmethod get_config()[源代码]
classmethod get_instance()[源代码]
hasIntent(parsed, intent)[源代码]

判断是否包含某个意图

参数:
  • parsed – 解析结果
  • intent – 意图的名称
返回:

True: 包含; False: 不包含

parse(query, **args)[源代码]

进行 NLU 解析

参数:
  • query – 用户的指令字符串
  • **args

    可选的参数

class robot.NLU.UnitNLU[源代码]

基类:robot.NLU.AbstractNLU

百度UNIT的NLU API.

SLUG = 'unit'
getIntent(parsed)[源代码]

提取意图

参数:parsed – 解析结果
返回:意图数组
getSay(parsed, intent)[源代码]

提取 UNIT 的回复文本

参数:
  • parsed – UNIT 解析结果
  • intent – 意图的名称
返回:

UNIT 的回复文本

getSlotWords(parsed, intent, name)[源代码]

找出命中某个词槽的内容

参数:
  • parsed – UNIT 解析结果
  • intent – 意图的名称
  • name – 词槽名
返回:

命中该词槽的值的列表。

getSlots(parsed, intent)[源代码]

提取某个意图的所有词槽

参数:
  • parsed – UNIT 解析结果
  • intent – 意图的名称
返回:

词槽列表。你可以通过 name 属性筛选词槽,

再通过 normalized_word 属性取出相应的值

classmethod get_config()[源代码]

百度UNIT的配置

无需配置,所以返回 {}

hasIntent(parsed, intent)[源代码]

判断是否包含某个意图

参数:
  • parsed – UNIT 解析结果
  • intent – 意图的名称
返回:

True: 包含; False: 不包含

parse(query, **args)[源代码]

使用百度 UNIT 进行 NLU 解析

参数:
  • query – 用户的指令字符串
  • **args

    UNIT 的相关参数 - service_id: UNIT 的 service_id - api_key: UNIT apk_key - secret_key: UNIT secret_key

返回:

UNIT 解析结果。如果解析失败,返回 None

robot.NLU.get_engine_by_slug(slug=None)[源代码]
Returns:
An NLU Engine implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
robot.NLU.get_engines()[源代码]

robot.Player module

class robot.Player.AbstractPlayer(**kwargs)[源代码]

基类:object

is_playing()[源代码]
play()[源代码]
play_block()[源代码]
stop()[源代码]
class robot.Player.MusicPlayer(playlist, plugin, **kwargs)[源代码]

基类:robot.Player.SoxPlayer

给音乐播放器插件使用的, 在 SOXPlayer 的基础上增加了列表的支持, 并支持暂停和恢复播放

SLUG = 'MusicPlayer'
is_pausing()[源代码]
is_playing()[源代码]
next()[源代码]
pause()[源代码]
play()[源代码]
prev()[源代码]
resume()[源代码]
stop()[源代码]
turnDown()[源代码]
turnUp()[源代码]
update_playlist(playlist)[源代码]
class robot.Player.SoxPlayer(**kwargs)[源代码]

基类:robot.Player.AbstractPlayer

SLUG = 'SoxPlayer'
appendOnCompleted(onCompleted)[源代码]
doPlay()[源代码]
is_playing()[源代码]
play(src, delete=False, onCompleted=None, wait=False)[源代码]
play_block()[源代码]
stop()[源代码]
robot.Player.getPlayerByFileName(fname)[源代码]
robot.Player.no_alsa_error()[源代码]
robot.Player.play(fname, onCompleted=None)[源代码]
robot.Player.py_error_handler(filename, line, function, err, fmt)[源代码]

robot.TTS module

class robot.TTS.AbstractTTS[源代码]

基类:object

Generic parent class for all TTS engines

classmethod get_config()[源代码]
classmethod get_instance()[源代码]
get_speech(phrase)[源代码]
class robot.TTS.AliTTS(appKey, token, voice='xiaoyun', **args)[源代码]

基类:robot.TTS.AbstractTTS

阿里的TTS voice: 发音人,默认是 xiaoyun

SLUG = 'ali-tts'
classmethod get_config()[源代码]
get_speech(phrase)[源代码]
class robot.TTS.BaiduTTS(appid, api_key, secret_key, per=1, lan='zh', **args)[源代码]

基类:robot.TTS.AbstractTTS

使用百度语音合成技术 要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号, 之后创建一个新应用, 然后在应用管理的”查看key”中获得 API Key 和 Secret Key 填入 config.yml 中. …

baidu_yuyin:
appid: ‘9670645’ api_key: ‘qg4haN8b2bGvFtCbBGqhrmZy’ secret_key: ‘585d4eccb50d306c401d7df138bb02e7’ dev_pid: 1936 per: 1 lan: ‘zh’

SLUG = 'baidu-tts'
classmethod get_config()[源代码]
get_speech(phrase)[源代码]
class robot.TTS.TencentTTS(appid, secretid, secret_key, region='ap-guangzhou', voiceType=0, language=1, **args)[源代码]

基类:robot.TTS.AbstractTTS

腾讯的语音合成 region: 服务地域,挑个离自己最近的区域有助于提升速度。

voiceType:
  • 0:女声1,亲和风格(默认)
  • 1:男声1,成熟风格
  • 2:男声2,成熟风格
language:
  • 1: 中文,最大100个汉字(标点符号算一个汉子)
  • 2: 英文,最大支持400个字母(标点符号算一个字母)
SLUG = 'tencent-tts'
classmethod get_config()[源代码]
get_speech(phrase)[源代码]
class robot.TTS.XunfeiTTS(appid, asr_api_key, asr_api_secret, tts_api_key, voice='xiaoyan')[源代码]

基类:robot.TTS.AbstractTTS

科大讯飞的语音识别API. 外网ip查询:https://ip.51240.com/ voice_name: https://www.xfyun.cn/services/online_tts

SLUG = 'xunfei-tts'
getBody(text)[源代码]
getHeader(aue)[源代码]
classmethod get_config()[源代码]
get_speech(phrase)[源代码]
robot.TTS.get_engine_by_slug(slug=None)[源代码]
Returns:
A TTS Engine implementation available on the current platform
Raises:
ValueError if no speaker implementation is supported on this platform
robot.TTS.get_engines()[源代码]

robot.Updater module

class robot.Updater.Updater[源代码]

基类:object

fetch(dev=False)[源代码]
update()[源代码]
robot.Updater.fetch(dev)[源代码]

robot.config module

robot.config.doInit(config_file='/Users/panweizhou/Documents/projects/wukong-robot/static/default.yml')[源代码]
robot.config.dump(configStr)[源代码]
robot.config.get(item='', default=None)[源代码]

获取某个配置的值

参数:
  • item – 配置项名。如果是多级配置,则以 “/a/b” 的形式提供
  • default – 默认值(可选)
返回:

这个配置的值。如果没有该配置,则提供一个默认值

robot.config.getConfig()[源代码]

返回全部配置数据

返回:全部配置数据(字典类型)
robot.config.getText()[源代码]
robot.config.get_path(items, default=None)[源代码]
robot.config.has(item)[源代码]

判断配置里是否包含某个配置项

参数:item – 配置项名
返回:True: 包含; False: 不包含
robot.config.has_path(items)[源代码]
robot.config.init()[源代码]
robot.config.reload()[源代码]

重新加载配置

robot.constants module

robot.constants.getConfigData(*fname)[源代码]

获取配置目录下的指定文件的路径

参数:*fname

指定文件名。如果传多个,则自动拼接

返回:配置目录下的某个文件的存储路径
robot.constants.getConfigPath()[源代码]

获取配置文件的路径

returns: 配置文件的存储路径

robot.constants.getData(*fname)[源代码]

获取资源目录下指定文件的路径

参数:*fname

指定文件名。如果传多个,则自动拼接

返回:配置文件的存储路径
robot.constants.getDefaultConfigPath()[源代码]
robot.constants.getHotwordModel(fname)[源代码]
robot.constants.newConfig()[源代码]

robot.logging module

robot.logging.getLogger(name)[源代码]

作用同标准模块 logging.getLogger(name)

返回:logger
robot.logging.readLog(lines=200)[源代码]

获取最新的指定行数的 log

参数:lines – 最大的行数
返回:最新指定行数的 log
robot.logging.tail(filepath, n=10)[源代码]

实现 tail -n

robot.plugin_loader module

robot.plugin_loader.get_plugins(con)[源代码]
robot.plugin_loader.init_plugins(con)[源代码]

动态加载技能插件

参数: con – 会话模块

robot.statistic module

class robot.statistic.ReportThread(t)[源代码]

基类:threading.Thread

run()[源代码]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

robot.statistic.getUUID()[源代码]
robot.statistic.report(t)[源代码]

robot.utils module

robot.utils.check_and_delete(fp, wait=0)[源代码]

检查并删除文件/文件夹

参数:fp – 文件路径
robot.utils.clean()[源代码]

清理垃圾数据

robot.utils.convert_mp3_to_wav(mp3_path)[源代码]

将 mp3 文件转成 wav

参数:mp3_path – mp3 文件路径
返回:wav 文件路径
robot.utils.convert_wav_to_mp3(wav_path)[源代码]

将 wav 文件转成 mp3

参数:wav_path – wav 文件路径
返回:mp3 文件路径
robot.utils.emailUser(SUBJECT='', BODY='', ATTACH_LIST=[])[源代码]

给用户发送邮件

参数:
  • SUBJECT – subject line of the email
  • BODY – body text of the email
返回:

True: 发送成功; False: 发送失败

robot.utils.getCache(msg)[源代码]

获取缓存的语音

robot.utils.getTimezone()[源代码]

获取时区

robot.utils.get_do_not_bother_off_hotword()[源代码]

关闭勿扰模式唤醒词

robot.utils.get_do_not_bother_on_hotword()[源代码]

打开勿扰模式唤醒词

robot.utils.get_file_content(filePath)[源代码]

读取文件内容并返回

参数:filePath – 文件路径
返回:文件内容
引发:IOError – 读取失败则抛出 IOError
robot.utils.get_pcm_from_wav(wav_path)[源代码]

从 wav 文件中读取 pcm

参数:wav_path – wav 文件路径
返回:pcm 数据
robot.utils.is_proper_time()[源代码]

是否合适时间

robot.utils.lruCache()[源代码]

清理最近未使用的缓存

robot.utils.saveCache(voice, msg)[源代码]

获取缓存的语音

robot.utils.sendEmail(SUBJECT, BODY, ATTACH_LIST, TO, FROM, SENDER, PASSWORD, SMTP_SERVER, SMTP_PORT)[源代码]

发送邮件

参数:
  • SUBJECT – 邮件标题
  • BODY – 邮件正文
  • ATTACH_LIST – 附件
  • TO – 收件人
  • FROM – 发件人
  • SENDER – 发件人信息
  • PASSWORD – 密码
  • SMTP_SERVER – smtp 服务器
  • SMTP_PORT – smtp 端口号
返回:

True: 发送成功; False: 发送失败

robot.utils.write_temp_file(data, suffix, mode='w+b')[源代码]

写入临时文件

参数:
  • data – 数据
  • suffix – 后缀名
  • mode – 写入模式,默认为 w+b
返回:

文件保存后的路径

Module contents

================================================ FILE: docs/robot.sdk.html ================================================ robot.sdk package — wukong-robot 1.2.0 文档

robot.sdk package

Submodules

robot.sdk.AbstractPlugin module

class robot.sdk.AbstractPlugin.AbstractPlugin(con)[源代码]

基类:object

技能插件基类

IS_IMMERSIVE = False
SLUG = 'AbstractPlugin'
activeListen(silent=False)[源代码]
clearImmersive()[源代码]
handle(query, parsed)[源代码]

处理逻辑

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

isValid(query, parsed)[源代码]

是否适合由该插件处理

参数: query – 用户的指令字符串 parsed – 用户指令经过 NLU 解析后的结果

返回: True: 适合由该插件处理 False: 不适合由该插件处理

isValidImmersive(query, parsed)[源代码]

是否适合在沉浸模式下处理, 仅适用于有沉浸模式的插件(如音乐等) 当用户唤醒时,可以响应更多指令集。 例如:“”上一首”、”下一首” 等

pause()[源代码]

暂停当前正在处理的任务, 当处于该沉浸模式下且被唤醒时, 将自动触发这个方法, 可以用于强制暂停一个耗时的操作

play(src, delete=False, onCompleted=None, volume=1)[源代码]
restore()[源代码]

恢复当前插件, 仅适用于有沉浸模式的插件(如音乐等) 当用户误唤醒或者唤醒进行闲聊后, 可以自动恢复当前插件的处理逻辑

say(text, cache=False, onCompleted=None, wait=False)[源代码]

robot.sdk.AliSpeech module

robot.sdk.AliSpeech.asr(appKey, token, wave_file)[源代码]
robot.sdk.AliSpeech.process(request, token, audioContent)[源代码]
robot.sdk.AliSpeech.processGETRequest(appKey, token, voice, text, format, sampleRate)[源代码]
robot.sdk.AliSpeech.processPOSTRequest(appKey, token, voice, text, format, sampleRate)[源代码]
robot.sdk.AliSpeech.tts(appKey, token, voice, text)[源代码]

robot.sdk.RASRsdk module

robot.sdk.RASRsdk.formatSignString(param)[源代码]
robot.sdk.RASRsdk.randstr(n)[源代码]
robot.sdk.RASRsdk.sendVoice(secret_key, secretid, appid, engine_model_type, res_type, result_text_format, voice_format, filepath, cutlength, template_name='')[源代码]
robot.sdk.RASRsdk.sign(signstr, secret_key)[源代码]

robot.sdk.TencentSpeech module

Tencent ASR && TTS API

class robot.sdk.TencentSpeech.tencentSpeech(SECRET_KEY, SECRET_ID)[源代码]

基类:object

ASR(URL, voiceformat, sourcetype, region)[源代码]
PrimaryLanguage
Region
SECRET_ID
SECRET_KEY
SourceType
TTS(text, voicetype, primarylanguage, region)[源代码]
Text
URL
VoiceFormat
VoiceType
encode_sign(signstr, SECRET_KEY)[源代码]
formatSignString(config_dict)[源代码]
oneSentenceRecognition()[源代码]
primarylanguage
region
secret_id
secret_key
source_type
text
textToSpeech()[源代码]
url
voiceformat
voicetype

robot.sdk.XunfeiSpeech module

class robot.sdk.XunfeiSpeech.Ws_Param(APPID, APIKey, APISecret, AudioFile)[源代码]

基类:object

create_url()[源代码]
robot.sdk.XunfeiSpeech.on_close(ws)[源代码]
robot.sdk.XunfeiSpeech.on_error(ws, error)[源代码]
robot.sdk.XunfeiSpeech.on_message(ws, message)[源代码]
robot.sdk.XunfeiSpeech.on_open(ws)[源代码]
robot.sdk.XunfeiSpeech.transcribe(fpath, appid, api_key, api_secret)[源代码]

科大讯飞ASR

robot.sdk.unit module

robot.sdk.unit.getIntent(parsed)[源代码]

提取意图

参数:parsed – UNIT 解析结果
返回:意图数组
robot.sdk.unit.getSay(parsed, intent='')[源代码]

提取 UNIT 的回复文本

参数:
  • parsed – UNIT 解析结果
  • intent – 意图的名称
返回:

UNIT 的回复文本

robot.sdk.unit.getSlotWords(parsed, intent, name)[源代码]

找出命中某个词槽的内容

参数:
  • parsed – UNIT 解析结果
  • intent – 意图的名称
  • name – 词槽名
返回:

命中该词槽的值的列表。

robot.sdk.unit.getSlots(parsed, intent='')[源代码]

提取某个意图的所有词槽

param parsed:UNIT 解析结果
param intent:意图的名称
returns:词槽列表。你可以通过 name 属性筛选词槽,

再通过 normalized_word 属性取出相应的值

robot.sdk.unit.getUnit(query, service_id, api_key, secret_key)[源代码]

NLU 解析

参数:
  • query – 用户的指令字符串
  • service_id – UNIT 的 service_id
  • api_key – UNIT apk_key
  • secret_key – UNIT secret_key
返回:

UNIT 解析结果。如果解析失败,返回 None

robot.sdk.unit.get_token(api_key, secret_key)[源代码]
robot.sdk.unit.hasIntent(parsed, intent)[源代码]

判断是否包含某个意图

参数:
  • parsed – UNIT 解析结果
  • intent – 意图的名称
返回:

True: 包含; False: 不包含

Module contents

================================================ FILE: docs/search.html ================================================ 搜索 — wukong-robot 1.2.0 文档

================================================ FILE: docs/searchindex.js ================================================ Search.setIndex({docnames:["index","modules","plugins","robot","robot.drivers","robot.sdk","snowboy","wukong"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,"sphinx.ext.viewcode":1,sphinx:55},filenames:["index.rst","modules.rst","plugins.rst","robot.rst","robot.drivers.rst","robot.sdk.rst","snowboy.rst","wukong.rst"],objects:{"":{plugins:[2,0,0,"-"],robot:[3,0,0,"-"],snowboy:[6,0,0,"-"],wukong:[7,0,0,"-"]},"plugins.Camera":{Plugin:[2,1,1,""]},"plugins.Camera.Plugin":{SLUG:[2,2,1,""],handle:[2,3,1,""],isValid:[2,3,1,""]},"plugins.CleanCache":{Plugin:[2,1,1,""]},"plugins.CleanCache.Plugin":{SLUG:[2,2,1,""],handle:[2,3,1,""],isValid:[2,3,1,""]},"plugins.Echo":{Plugin:[2,1,1,""]},"plugins.Echo.Plugin":{handle:[2,3,1,""],isValid:[2,3,1,""]},"plugins.Email":{Plugin:[2,1,1,""]},"plugins.Email.Plugin":{SLUG:[2,2,1,""],fetchUnreadEmails:[2,3,1,""],getDate:[2,3,1,""],getMostRecentDate:[2,3,1,""],getSender:[2,3,1,""],getSubject:[2,3,1,""],handle:[2,3,1,""],isNewEmail:[2,3,1,""],isSelfEmail:[2,3,1,""],isValid:[2,3,1,""]},"plugins.Geek":{Plugin:[2,1,1,""]},"plugins.Geek.Plugin":{IS_IMMERSIVE:[2,2,1,""],handle:[2,3,1,""],isValid:[2,3,1,""],isValidImmersive:[2,3,1,""],onAsk:[2,3,1,""],restore:[2,3,1,""]},"plugins.LocalPlayer":{Plugin:[2,1,1,""]},"plugins.LocalPlayer.Plugin":{IS_IMMERSIVE:[2,2,1,""],get_song_list:[2,3,1,""],handle:[2,3,1,""],init_music_player:[2,3,1,""],isValid:[2,3,1,""],isValidImmersive:[2,3,1,""],pause:[2,3,1,""],restore:[2,3,1,""]},"plugins.Poem":{Plugin:[2,1,1,""]},"plugins.Poem.Plugin":{SLUG:[2,2,1,""],handle:[2,3,1,""],isValid:[2,3,1,""]},"robot.AI":{AbstractRobot:[3,1,1,""],Emotibot:[3,1,1,""],TulingRobot:[3,1,1,""],get_robot_by_slug:[3,5,1,""],get_robots:[3,5,1,""]},"robot.AI.AbstractRobot":{chat:[3,3,1,""],get_instance:[3,4,1,""]},"robot.AI.Emotibot":{SLUG:[3,2,1,""],chat:[3,3,1,""],get_config:[3,4,1,""]},"robot.AI.TulingRobot":{SLUG:[3,2,1,""],chat:[3,3,1,""],get_config:[3,4,1,""]},"robot.ASR":{AbstractASR:[3,1,1,""],AliASR:[3,1,1,""],BaiduASR:[3,1,1,""],TencentASR:[3,1,1,""],XunfeiASR:[3,1,1,""],get_engine_by_slug:[3,5,1,""],get_engines:[3,5,1,""]},"robot.ASR.AbstractASR":{get_config:[3,4,1,""],get_instance:[3,4,1,""],transcribe:[3,3,1,""]},"robot.ASR.AliASR":{SLUG:[3,2,1,""],get_config:[3,4,1,""],transcribe:[3,3,1,""]},"robot.ASR.BaiduASR":{SLUG:[3,2,1,""],get_config:[3,4,1,""],transcribe:[3,3,1,""]},"robot.ASR.TencentASR":{SLUG:[3,2,1,""],get_config:[3,4,1,""],transcribe:[3,3,1,""]},"robot.ASR.XunfeiASR":{SLUG:[3,2,1,""],get_config:[3,4,1,""],transcribe:[3,3,1,""]},"robot.Brain":{Brain:[3,1,1,""]},"robot.Brain.Brain":{isImmersive:[3,3,1,""],pause:[3,3,1,""],printPlugins:[3,3,1,""],query:[3,3,1,""],restore:[3,3,1,""],say:[3,3,1,""],understand:[3,3,1,""]},"robot.ConfigMonitor":{ConfigMonitor:[3,1,1,""]},"robot.ConfigMonitor.ConfigMonitor":{on_modified:[3,3,1,""]},"robot.Conversation":{Conversation:[3,1,1,""]},"robot.Conversation.Conversation":{activeListen:[3,3,1,""],appendHistory:[3,3,1,""],checkRestore:[3,3,1,""],converse:[3,3,1,""],doConverse:[3,3,1,""],doParse:[3,3,1,""],doResponse:[3,3,1,""],getHistory:[3,3,1,""],getImmersiveMode:[3,3,1,""],interrupt:[3,3,1,""],pardon:[3,3,1,""],play:[3,3,1,""],reload:[3,3,1,""],say:[3,3,1,""],setImmersiveMode:[3,3,1,""]},"robot.NLU":{AbstractNLU:[3,1,1,""],UnitNLU:[3,1,1,""],get_engine_by_slug:[3,5,1,""],get_engines:[3,5,1,""]},"robot.NLU.AbstractNLU":{getIntent:[3,3,1,""],getSay:[3,3,1,""],getSlotWords:[3,3,1,""],getSlots:[3,3,1,""],get_config:[3,4,1,""],get_instance:[3,4,1,""],hasIntent:[3,3,1,""],parse:[3,3,1,""]},"robot.NLU.UnitNLU":{SLUG:[3,2,1,""],getIntent:[3,3,1,""],getSay:[3,3,1,""],getSlotWords:[3,3,1,""],getSlots:[3,3,1,""],get_config:[3,4,1,""],hasIntent:[3,3,1,""],parse:[3,3,1,""]},"robot.Player":{AbstractPlayer:[3,1,1,""],MusicPlayer:[3,1,1,""],SoxPlayer:[3,1,1,""],getPlayerByFileName:[3,5,1,""],no_alsa_error:[3,5,1,""],play:[3,5,1,""],py_error_handler:[3,5,1,""]},"robot.Player.AbstractPlayer":{is_playing:[3,3,1,""],play:[3,3,1,""],play_block:[3,3,1,""],stop:[3,3,1,""]},"robot.Player.MusicPlayer":{SLUG:[3,2,1,""],is_pausing:[3,3,1,""],is_playing:[3,3,1,""],next:[3,3,1,""],pause:[3,3,1,""],play:[3,3,1,""],prev:[3,3,1,""],resume:[3,3,1,""],stop:[3,3,1,""],turnDown:[3,3,1,""],turnUp:[3,3,1,""],update_playlist:[3,3,1,""]},"robot.Player.SoxPlayer":{SLUG:[3,2,1,""],appendOnCompleted:[3,3,1,""],doPlay:[3,3,1,""],is_playing:[3,3,1,""],play:[3,3,1,""],play_block:[3,3,1,""],stop:[3,3,1,""]},"robot.TTS":{AbstractTTS:[3,1,1,""],AliTTS:[3,1,1,""],BaiduTTS:[3,1,1,""],TencentTTS:[3,1,1,""],XunfeiTTS:[3,1,1,""],get_engine_by_slug:[3,5,1,""],get_engines:[3,5,1,""]},"robot.TTS.AbstractTTS":{get_config:[3,4,1,""],get_instance:[3,4,1,""],get_speech:[3,3,1,""]},"robot.TTS.AliTTS":{SLUG:[3,2,1,""],get_config:[3,4,1,""],get_speech:[3,3,1,""]},"robot.TTS.BaiduTTS":{SLUG:[3,2,1,""],get_config:[3,4,1,""],get_speech:[3,3,1,""]},"robot.TTS.TencentTTS":{SLUG:[3,2,1,""],get_config:[3,4,1,""],get_speech:[3,3,1,""]},"robot.TTS.XunfeiTTS":{SLUG:[3,2,1,""],getBody:[3,3,1,""],getHeader:[3,3,1,""],get_config:[3,4,1,""],get_speech:[3,3,1,""]},"robot.Updater":{Updater:[3,1,1,""],fetch:[3,5,1,""]},"robot.Updater.Updater":{fetch:[3,3,1,""],update:[3,3,1,""]},"robot.config":{doInit:[3,5,1,""],dump:[3,5,1,""],get:[3,5,1,""],getConfig:[3,5,1,""],getText:[3,5,1,""],get_path:[3,5,1,""],has:[3,5,1,""],has_path:[3,5,1,""],init:[3,5,1,""],reload:[3,5,1,""]},"robot.constants":{getConfigData:[3,5,1,""],getConfigPath:[3,5,1,""],getData:[3,5,1,""],getDefaultConfigPath:[3,5,1,""],getHotwordModel:[3,5,1,""],newConfig:[3,5,1,""]},"robot.logging":{getLogger:[3,5,1,""],readLog:[3,5,1,""],tail:[3,5,1,""]},"robot.plugin_loader":{get_plugins:[3,5,1,""],init_plugins:[3,5,1,""]},"robot.sdk":{AbstractPlugin:[5,0,0,"-"],AliSpeech:[5,0,0,"-"],RASRsdk:[5,0,0,"-"],TencentSpeech:[5,0,0,"-"],XunfeiSpeech:[5,0,0,"-"],unit:[5,0,0,"-"]},"robot.sdk.AbstractPlugin":{AbstractPlugin:[5,1,1,""]},"robot.sdk.AbstractPlugin.AbstractPlugin":{IS_IMMERSIVE:[5,2,1,""],SLUG:[5,2,1,""],activeListen:[5,3,1,""],clearImmersive:[5,3,1,""],handle:[5,3,1,""],isValid:[5,3,1,""],isValidImmersive:[5,3,1,""],pause:[5,3,1,""],play:[5,3,1,""],restore:[5,3,1,""],say:[5,3,1,""]},"robot.sdk.AliSpeech":{asr:[5,5,1,""],process:[5,5,1,""],processGETRequest:[5,5,1,""],processPOSTRequest:[5,5,1,""],tts:[5,5,1,""]},"robot.sdk.RASRsdk":{formatSignString:[5,5,1,""],randstr:[5,5,1,""],sendVoice:[5,5,1,""],sign:[5,5,1,""]},"robot.sdk.TencentSpeech":{tencentSpeech:[5,1,1,""]},"robot.sdk.TencentSpeech.tencentSpeech":{ASR:[5,3,1,""],PrimaryLanguage:[5,2,1,""],Region:[5,2,1,""],SECRET_ID:[5,2,1,""],SECRET_KEY:[5,2,1,""],SourceType:[5,2,1,""],TTS:[5,3,1,""],Text:[5,2,1,""],URL:[5,2,1,""],VoiceFormat:[5,2,1,""],VoiceType:[5,2,1,""],encode_sign:[5,3,1,""],formatSignString:[5,3,1,""],oneSentenceRecognition:[5,3,1,""],primarylanguage:[5,2,1,""],region:[5,2,1,""],secret_id:[5,2,1,""],secret_key:[5,2,1,""],source_type:[5,2,1,""],text:[5,2,1,""],textToSpeech:[5,3,1,""],url:[5,2,1,""],voiceformat:[5,2,1,""],voicetype:[5,2,1,""]},"robot.sdk.XunfeiSpeech":{Ws_Param:[5,1,1,""],on_close:[5,5,1,""],on_error:[5,5,1,""],on_message:[5,5,1,""],on_open:[5,5,1,""],transcribe:[5,5,1,""]},"robot.sdk.XunfeiSpeech.Ws_Param":{create_url:[5,3,1,""]},"robot.sdk.unit":{getIntent:[5,5,1,""],getSay:[5,5,1,""],getSlotWords:[5,5,1,""],getSlots:[5,5,1,""],getUnit:[5,5,1,""],get_token:[5,5,1,""],hasIntent:[5,5,1,""]},"robot.statistic":{ReportThread:[3,1,1,""],getUUID:[3,5,1,""],report:[3,5,1,""]},"robot.statistic.ReportThread":{run:[3,3,1,""]},"robot.utils":{check_and_delete:[3,5,1,""],clean:[3,5,1,""],convert_mp3_to_wav:[3,5,1,""],convert_wav_to_mp3:[3,5,1,""],emailUser:[3,5,1,""],getCache:[3,5,1,""],getTimezone:[3,5,1,""],get_do_not_bother_off_hotword:[3,5,1,""],get_do_not_bother_on_hotword:[3,5,1,""],get_file_content:[3,5,1,""],get_pcm_from_wav:[3,5,1,""],is_proper_time:[3,5,1,""],lruCache:[3,5,1,""],saveCache:[3,5,1,""],sendEmail:[3,5,1,""],write_temp_file:[3,5,1,""]},"snowboy.snowboydecoder":{ActiveListener:[6,1,1,""],HotwordDetector:[6,1,1,""],RingBuffer:[6,1,1,""],no_alsa_error:[6,5,1,""],play_audio_file:[6,5,1,""],py_error_handler:[6,5,1,""]},"snowboy.snowboydecoder.ActiveListener":{listen:[6,3,1,""],saveMessage:[6,3,1,""]},"snowboy.snowboydecoder.HotwordDetector":{saveMessage:[6,3,1,""],start:[6,3,1,""],terminate:[6,3,1,""]},"snowboy.snowboydecoder.RingBuffer":{extend:[6,3,1,""],get:[6,3,1,""]},"snowboy.snowboydetect":{SnowboyDetect:[6,1,1,""],SnowboyVad:[6,1,1,""]},"snowboy.snowboydetect.SnowboyDetect":{ApplyFrontend:[6,3,1,""],BitsPerSample:[6,3,1,""],GetSensitivity:[6,3,1,""],NumChannels:[6,3,1,""],NumHotwords:[6,3,1,""],Reset:[6,3,1,""],RunDetection:[6,3,1,""],SampleRate:[6,3,1,""],SetAudioGain:[6,3,1,""],SetHighSensitivity:[6,3,1,""],SetSensitivity:[6,3,1,""],UpdateModel:[6,3,1,""]},"snowboy.snowboydetect.SnowboyVad":{ApplyFrontend:[6,3,1,""],BitsPerSample:[6,3,1,""],NumChannels:[6,3,1,""],Reset:[6,3,1,""],RunVad:[6,3,1,""],SampleRate:[6,3,1,""],SetAudioGain:[6,3,1,""]},"wukong.Wukong":{dev:[7,3,1,""],fetch:[7,3,1,""],init:[7,3,1,""],initDetector:[7,3,1,""],md5:[7,3,1,""],profiling:[7,3,1,""],restart:[7,3,1,""],run:[7,3,1,""],update:[7,3,1,""]},plugins:{Camera:[2,0,0,"-"],CleanCache:[2,0,0,"-"],Echo:[2,0,0,"-"],Email:[2,0,0,"-"],Geek:[2,0,0,"-"],LocalPlayer:[2,0,0,"-"],Poem:[2,0,0,"-"]},robot:{AI:[3,0,0,"-"],ASR:[3,0,0,"-"],Brain:[3,0,0,"-"],ConfigMonitor:[3,0,0,"-"],Conversation:[3,0,0,"-"],NLU:[3,0,0,"-"],Player:[3,0,0,"-"],TTS:[3,0,0,"-"],Updater:[3,0,0,"-"],config:[3,0,0,"-"],constants:[3,0,0,"-"],drivers:[4,0,0,"-"],logging:[3,0,0,"-"],plugin_loader:[3,0,0,"-"],sdk:[5,0,0,"-"],statistic:[3,0,0,"-"],utils:[3,0,0,"-"]},snowboy:{snowboydecoder:[6,0,0,"-"],snowboydetect:[6,0,0,"-"]},wukong:{Wukong:[7,1,1,""]}},objnames:{"0":["py","module","Python \u6a21\u5757"],"1":["py","class","Python \u7c7b"],"2":["py","attribute","Python \u5c5e\u6027"],"3":["py","method","Python \u65b9\u6cd5"],"4":["py","classmethod","Python \u7c7b\u65b9\u6cd5"],"5":["py","function","Python \u51fd\u6570"]},objtypes:{"0":"py:module","1":"py:class","2":"py:attribute","3":"py:method","4":"py:classmethod","5":"py:function"},terms:{"03":6,"03d":[],"10":3,"100":[3,6],"1024":[],"11186623":3,"15":6,"150":[],"1536":3,"1537":3,"1637":3,"17365":3,"1737":3,"1837":3,"1936":3,"200":3,"2001":[],"2016":[],"2017":[],"224":[],"24":3,"282":[],"300":[],"31":[],"32":[],"400":3,"4096":6,"441":3,"51240":3,"585d4eccb50d306c401d7df138bb02e7":3,"67ce5275q2rgst":3,"8000000":[],"84435":3,"88":3,"9670645":3,"97":3,"9c":3,"9f":3,"break":6,"byte":[],"case":[],"class":[2,3,5,6,7],"default":[3,6],"do":[],"float":6,"for":[3,6],"function":[3,6],"if":[2,3,6],"import":[],"in":[2,3,6],"int":[],"long":6,"new":2,"public":[],"return":[2,3,5,6],"static":3,"switch":[],"true":[2,3,5,6],"while":[],"with":[3,6],__init__:[],__name__:[],_handler:[],a1:3,a2c4g:3,a8:3,abc:[],about:[],abov:[],abstractasr:3,abstractnlu:3,abstractplay:3,abstractplugin:[1,2,3],abstractrobot:3,abstractsoundplay:[],abstracttt:3,accept:[],access:[],accumul:[],acquir:[],acquisit:[],act:[],activ:[3,6],activelisten:[3,5,6],actual:[],adapt:[],add:6,added:[],addhandl:[],adding:[],addit:[],addlevelnam:[],address:[],after:6,again:6,ai:1,aka:[],algorithm:6,ali:3,aliasr:3,alispeech:[1,3],alitt:3,aliyun:3,all:[2,3],allow:[],alreadi:[],also:6,alter:[],am:[],an:[2,3,6],and:[3,6],ani:[2,3],ap:3,apa102:[],apa102_pi:[],api:[3,5],api_kei:[3,5],api_secret:5,apikei:5,apisecret:5,apk_kei:[3,5],append:[],appendhistori:3,appendoncomplet:3,appid:[3,5],appkei:[3,5],appli:6,applic:[],apply_frontend:6,applyfrontend:6,appropri:[],arbitrari:[],are:[],area:[],arg:[3,6],argument:[2,3],around:[],arrai:[],as:[2,3],asctim:[],asr:[1,5],asr_api_kei:3,asr_api_secret:3,assign:[],associ:[],at:[],attach_list:3,attribut:[],audio:6,audio_gain:6,audio_recorder_callback:6,audiocont:5,audiofil:5,aue:3,avail:3,avoid:[],awai:[],b0:3,bad:[],baidu:3,baidu_yuyin:3,baiduasr:3,baidutt:3,base:[],basic:[],basic_format:[],basicconfig:[],bb:[],be:[2,3,6],becaus:[],been:6,befor:2,begin:6,behaviour:[],behind:[],being:6,below:[],benefit:[],best:2,bigger:6,bit:[],bitspersampl:6,blue:[],bodi:3,both:[],brain:1,brief:[],bright:[],bright_perc:[],buffer:6,bufferingformatt:[],bus:[],but:[],by:[2,3,6],cach:[3,5],call:[3,6],callabl:3,callback:[3,6],caller:[],callhandl:[],camera:1,can:6,captur:[],capturewarn:[],care:[],carri:[],cater:[],certain:[],chang:[],channel:[],chat:3,check:[2,6],check_and_delet:3,checkrestor:3,circular:[],classmethod:3,clean:3,cleancach:1,cleanup:[],clear:6,clear_strip:[],clearimmers:5,clever:[],clock:[],clock_end_fram:[],clock_start_fram:[],clockendfram:[],clockstartfram:[],close:[],closer:[],cloud:3,cn:3,code:[],color:[],colour:[],com:3,combin:[],combine_color:[],comment:[],common:6,commun:[],comp:[],comput:[],con:[2,3,5],concaten:[],condition:[],config:1,config_dict:5,config_fil:3,configmonitor:1,configstr:3,configur:[],connect:[],consol:[],constant:1,construct:[],constructor:3,contain:[],content:1,contextu:[],conveni:[],convers:1,convert:[],convert_mp3_to_wav:3,convert_wav_to_mp3:3,copi:[],copyright:[],correct:[],correspond:6,could:[],coupl:[],creat:[],create_url:5,createlock:[],creation:[],critic:[],csv:[],current:3,custom:[],cutlength:5,cycl:[],data:[3,6],date:2,datefmt:[],debug:[],decod:6,decoder_model:6,deem:[],def:[],default_msec_format:[],default_time_format:[],defin:[],delai:[],deleg:[],delet:[3,5],depend:[],depth:[],descend:[],describ:[],desir:2,destin:[],detect:6,detected_callback:6,detector:6,determin:[],dev:[3,7],dev_pid:3,develop:[],devic:[],dict:[],dictionari:[],ding:6,direct:[],directori:3,dirmodifiedev:3,disabl:[],disast:[],disk:[],dispatch:[],doconvers:3,document:[3,6],document_detail:3,doe:[],doing:[],doinit:3,done:[],dopars:3,doplai:3,dorespons:3,dotstar:[],down:[],driver:[],dummi:[],dump:3,dump_arrai:[],dure:[],e5:3,e8:3,each:[],easier:[],echo:1,effect:[],ei:[],either:[],els:[],email:[1,3],emailus:3,emiss:[],emit:[],emotibot:3,empti:6,enabl:[],encod:[],encode_sign:5,encount:[],end:6,engin:3,engine_model_typ:5,enginetyp:[],enough:[],ensur:[],entir:[],epoch:[],err:[3,6],error:5,erzberg:[],essenti:[],etc:[],even:[],event:3,everi:6,everyth:[],exactli:[],exampl:[],exc_info:[],except:[],exist:6,explain:[],express:[],extend:6,extens:[],extern:[],extra:[],fact:[],factor:6,factori:[],fals:[2,3,5,6],fatal:[],fed:[],fetch:[2,3,7],fetchunreademail:2,few:[],field:[],file:[3,6],filehandl:[],filemod:[],filemodifiedev:3,filenam:[3,6],filepath:[3,5],filesystemeventhandl:3,filter:[],find:[],findcal:[],finish:[],first:[],flush:[],fmt:[3,6],fn:[],fname:[3,6],follow:[],footer:[],format:5,formatexcept:[],formatfoot:[],formathead:[],formatmessag:[],formatsignstr:5,formatstack:[],formatt:[],formattim:[],forward:[],found:[],fp:3,fpath:5,frame:[],from:[2,3,6],frontend:6,full:[],fulli:[],func:[],funcnam:[],geek:1,gener:3,get:[3,6],get_config:3,get_do_not_bother_off_hotword:3,get_do_not_bother_on_hotword:3,get_engin:3,get_engine_by_slug:3,get_file_cont:3,get_inst:3,get_nam:[],get_path:3,get_pcm_from_wav:3,get_plugin:3,get_robot:3,get_robot_by_slug:3,get_song_list:2,get_speech:3,get_token:5,getbodi:3,getcach:3,getchild:[],getconfig:3,getconfigdata:3,getconfigpath:3,getdat:2,getdata:3,getdefaultconfigpath:3,geteffectivelevel:[],gethead:3,gethistori:3,gethotwordmodel:3,getimmersivemod:3,getint:[3,5],getlevelnam:[],getlogg:3,getloggerclass:[],getlogrecordfactori:[],getmessag:[],getmostrecentd:2,getplayerbyfilenam:3,getsai:[3,5],getsend:2,getsensit:6,getslot:[3,5],getslotword:[3,5],getsubject:2,gettext:3,gettimezon:3,getunit:5,getuuid:3,ghi:[],github:[],given:[],global:[],global_bright:[],glow:[],gmt:[],gmtime:[],gnu:[],gnumer:[],goe:[],green:[],guangzhou:3,guess:2,handl:[2,5],handleerror:[],handler:[],has:[3,6],has_path:3,hashandl:[],hasint:[3,5],have:[],hdlr:[],header:[],heard:6,help:3,helper:[],hierarchi:[],high_sensitivity_str:6,hold:6,home:[],hotworddetector:6,houston:[],how:6,howev:[],html:3,http:3,human:[],id:[],identifi:[],ignor:[],imagin:[],immedi:6,immers:[],immersivemod:[],implement:3,inbox:2,includ:[],incompat:[],indic:6,individu:[],info:[],inform:[],init:[3,7],init_music_play:2,init_plugin:3,initdetector:7,initi:[],input:[2,3,6],insert:[],instanc:[],instanti:[],instead:[],integ:[],intend:[],intent:[3,5],interact:[],interest:[],interfac:[],intern:[],interpret:[],interrupt:3,interrupt_check:6,into:[],invert:[],invok:3,ioerror:3,ip:3,is:[2,3,6],is_immers:[2,5],is_paus:3,is_plai:3,is_proper_tim:3,isenabledfor:[],isimmers:3,isnewemail:2,iso8601:[],isselfemail:2,issu:[],isvalid:[2,5],isvalidimmers:[2,5],it:6,item:[3,6],iter:[],its:[],itself:[],java:[],just:[],keep:[],kei:3,keyword:[3,6],klass:[],know:[],knowledg:[],kwarg:3,lambda:6,lan:3,lang:[],languag:3,last:[],least:[],led:[],led_num:[],led_start:[],length:6,level:[],levelnam:[],levelno:[],librari:[],like:[],limit:[2,6],line:[3,6],linefmt:[],lineno:[],list:[2,6],listen:6,liter:[],ll:[],lno:[],load:[],local:[],localplay:1,localtim:[],locat:3,lock:[],log:1,logger:3,loggeradapt:[],logrecord:[],look:[],lookup:[],loop:6,lot:[],lrucach:3,made:[],mai:3,main:6,major:[],make:[],makelogrecord:[],makerecord:[],manag:[],manipul:[],map:[],mark:[2,6],markread:2,martin:[],match:6,max_bright:[],max_speed_hz:[],maximum:6,md5:7,mean:[],mention:[],merg:[],messag:[5,6],method:3,mic:[],microphon:6,might:[],millisecond:[],mode:3,model:6,model_str:6,modif:3,modifi:3,modul:1,more:[3,6],most:2,mostli:[],mp3:3,mp3_path:3,msec:[],msg:[2,3],much:6,multipl:6,multipli:6,musicplay:3,must:6,my:[],mysteri:[],name:[3,5,6],namespac:[],natur:[],necessari:[],need:6,neg:[],nest:[],newconfig:3,newlin:[],next:3,nlu:[1,2,5],no:[2,3],no_alsa_error:[3,6],non:[],none:[2,3,5,6],nonzero:[],normal:[],normalized_word:[3,5],not:[],note:[],noth:[],notimplementederror:[],now:[],nullhandl:[],num_l:[],number:6,numchannel:6,numer:[],numhotword:6,numl:[],object:[2,3,5,6,7],occur:[],of:[2,3,6],off:[],omit:[],on:3,on_clos:5,on_error:5,on_messag:5,on_modifi:3,on_open:5,onask:2,oncomplet:[3,5],one:[],onesentencerecognit:5,onli:[],online_tt:3,onsai:3,onto:[],open:[],oper:[],operand:[],opposit:[],optim:[],option:[],or:[3,6],order:[],organ:[],origin:[],otherwis:[],out:[],output:[],over:[],overrid:3,overridden:[],overview:[],own:[],packag:1,panweizh:[3,6],param:[3,5],paramet:[],pardon:3,parent:3,pars:[2,3,5],part:[],partial:[],particular:[],pass:[3,6],password:[3,7],path:[2,6],pathnam:[],paus:[2,3,5],pcm:3,peopl:[],pep:[],per:3,perform:[],period:[],person:[],pertin:[],phrase:[3,6],pi:[],pixel:[],pixels_n:[],place:[],placehold:[],plai:[3,5,6],platform:3,play_audio_fil:6,play_block:3,player:1,playlist:3,plugin:[1,3],plugin_load:1,poem:1,point:[],portaudio:6,portion:[],posit:[],possibl:[],power:[],pre:[],predefin:[],prepar:[],preparatori:[],present:[],prev:3,primarylanguag:5,print_except:[],print_stack:[],printplugin:3,problem:[],process:[5,6],processgetrequest:5,processpostrequest:5,produc:[],profil:[3,7],project:[3,6],propag:[],protocol:[],provid:[2,6],purpos:[],py_error_handl:[3,6],python:[],qg4han8b2bgvftcbbgqhrmzi:3,queri:[2,3,5],rais:3,raiseexcept:[],randstr:5,rasrsdk:[1,3],rather:[],raw:[],reach:[],read:2,readi:[],readlog:3,real:[],realli:[],receiv:[],recent:2,record:6,recordeddata:6,recording_timeout:6,red:[],redirect:[],region:[3,5],rel:[],relat:[],relativecr:[],releas:[],relev:[],reload:3,rememb:[],remov:[],removehandl:[],replac:[],report:3,reportthread:3,repres:3,represent:[],request:5,requir:[],res:6,res_typ:5,reserv:[],reset:6,resourc:6,resource_filenam:6,respect:3,respond:[],respons:[],rest:[],restart:7,restor:[2,3,5],result:[],result_text_format:5,resum:3,retriev:6,rgb:[],rgb_color:[],right:[],ring:6,ringbuff:6,robot:[2,6],root:[],rootlogg:[],rotat:[],row:[],run:[3,7],rundetect:6,runvad:6,sai:[3,5],sajip:[],same:[],sampler:[5,6],save:6,savecach:3,savemessag:6,script:[],sdk:[1,2,3],search:[],second:6,secret:3,secret_id:5,secret_kei:[3,5],secretid:[3,5],see:[],seen:[],self:6,send:[],sendemail:3,sender:[2,3],sendvoic:5,sensit:6,sensitivity_str:6,senstiv:6,sent:2,separ:[],sequenti:3,serial:[],servic:3,service_id:[3,5],set:[],set_nam:[],set_pixel:[],set_pixel_rgb:[],setaudiogain:6,setformatt:[],sethighsensit:6,setimmersivemod:3,setlevel:[],setloggerclass:[],setlogrecordfactori:[],setsensit:6,sever:[],shift:[],shot:[],should:[],show:[],shown:[],side:[],sign:5,signatur:[],signific:[],signstr:5,silenc:6,silent:[3,5],silent_count_threshold:6,simpl:6,simpli:[],sinc:2,sinfo:[],singl:6,size:6,sleep_tim:6,slug:[2,3,5],smtp:3,smtp_port:3,smtp_server:3,snowboi:1,snowboydecod:1,snowboydetect:1,snowboyvad:6,so:[],socket:[],someth:[],sound:6,sourc:[],source_typ:5,sourcetyp:5,soxplay:3,speak:[],speaker:3,special:[],specif:[],specifi:6,speech:3,spi:[],spm:3,spoken:6,src:[3,5],stack:[],stack_info:[],standard:3,start:6,startup:[],statist:1,stderr:[],stdout:[],step:[],still:[],stop:[3,6],store:6,str:6,stream:6,streamhandl:[],strftime:[],string:6,strip:[],stripe:[],structur:[],stub:[],style:[],sub:[],subclass:3,subject:3,submodul:1,subpackag:1,such:[],suffix:3,suit:[],suitabl:[],superclass:[],suppli:[],support:3,sure:[],sync:[],sys:[],system:[],tail:3,take:[],taken:3,target:[2,3],tell:[],templat:[],template_nam:5,ten:[],tencent:[3,5],tencentasr:3,tencentspeech:[1,3],tencenttt:3,termin:6,text:[2,3,5],texttospeech:5,textual:[],than:[],that:6,the:[2,3,6],thei:[],their:[],then:6,there:[],therefor:[],thereto:[],thi:[2,3,6],think:[],thorni:[],those:[],thread:3,threadnam:[],through:[],thrown:[],tidi:[],time:6,timestamp:6,tinu:[],titl:2,tm_hour:[],tm_isdst:[],tm_mdai:[],tm_min:[],tm_mon:[],tm_sec:[],tm_wdai:[],tm_ydai:[],tm_year:[],to:[2,3,6],todo:[],togeth:[],toggl:[],token:[3,5],top:[],traceback:[],trail:[],transcrib:[3,5],treat:[],trigger:6,tts:[1,5],tts_api_kei:3,tule:3,tuling_kei:3,tulingrobot:3,tupl:[],turn:[],turndown:3,turnup:3,two:[],type:[],typic:3,ultim:[],underli:[],understand:3,uniqu:[],unit:[1,3],unitnlu:3,unpickl:[],unread:2,unspecifi:[],until:[],up:[],updat:[1,7],update_playlist:3,updatemodel:6,upper:[],url:5,use:[],used:6,useful:[],user:[2,3,6],uses:[],usestim:[],using:[],usual:[],util:1,uuid:3,vad:6,valu:6,valueerror:3,veri:[],version:[],vinai:[],voic:[3,5,6],voice_format:5,voice_nam:3,voiceformat:5,voicetyp:[3,5],volum:[3,5,6],wait:[3,5,6],wakeup:[],want:[],warn:[],was:6,watchdog:3,wav:[3,6],wav_path:3,wave:6,wave_fil:5,wavplay:[],we:[],weather:[],well:[],wether:2,what:[],whatev:[],wheel:[],wheel_po:[],when:3,whenev:[],where:6,wherea:[],whether:[2,6],which:6,whose:2,will:[2,6],wish:[],wrap:[],write:[],write_temp_fil:3,written:[],ws:5,ws_param:5,wukong:[3,6],www:3,xfer:[],xfyun:3,xiaoyan:3,xiaoyun:3,xls:[],xml:3,xunfei:3,xunfeiasr:3,xunfeispeech:[1,3],xunfeitt:3,xxx:[],yell:[],yes:[],yet:[],yield:[],yml:3,you:3,your:[],yuyin:3,zero:[],zh:3},titles:["Welcome to wukong-robot\u2019s documentation!","wukong-robot","plugins package","robot package","robot.drivers package","robot.sdk package","snowboy package","wukong module"],titleterms:{abstractplugin:5,ai:3,alispeech:5,and:0,apa102:4,asr:3,brain:3,camera:2,cleancach:2,config:3,configmonitor:3,constant:3,content:[2,3,4,5,6],convers:3,document:0,driver:4,echo:2,email:2,geek:2,indic:0,localplay:2,log:3,modul:[2,3,4,5,6,7],nlu:3,packag:[2,3,4,5,6],pixel:4,player:3,plugin:2,plugin_load:3,poem:2,rasrsdk:5,robot:[0,1,3,4,5],sdk:5,snowboi:6,snowboydecod:6,snowboydetect:6,statist:3,submodul:[2,3,4,5,6],subpackag:3,tabl:0,tencentspeech:5,to:0,tts:3,unit:5,updat:3,util:3,welcom:0,wukong:[0,1,7],xunfeispeech:5}}) ================================================ FILE: docs/snowboy.html ================================================ snowboy package — wukong-robot 1.2.0 文档

snowboy package

Submodules

snowboy.snowboydecoder module

class snowboy.snowboydecoder.ActiveListener(decoder_model, resource='/Users/panweizhou/Documents/projects/wukong-robot/snowboy/resources/common.res')[源代码]

基类:object

Active Listening with VAD

listen(interrupt_check=<function ActiveListener.<lambda>>, sleep_time=0.03, silent_count_threshold=15, recording_timeout=100)[源代码]
参数:
  • interrupt_check – a function that returns True if the main loop needs to stop.
  • silent_count_threshold – indicates how long silence must be heard to mark the end of a phrase that is being recorded.
  • sleep_time (float) – how much time in second every loop waits.
  • recording_timeout – limits the maximum length of a recording.
返回:

recorded file path

saveMessage()[源代码]

Save the message stored in self.recordedData to a timestamped file.

class snowboy.snowboydecoder.HotwordDetector(decoder_model, resource='/Users/panweizhou/Documents/projects/wukong-robot/snowboy/resources/common.res', sensitivity=[], audio_gain=1, apply_frontend=False)[源代码]

基类:object

Snowboy decoder to detect whether a keyword specified by decoder_model exists in a microphone input stream.

参数:
  • decoder_model – decoder model file path, a string or a list of strings
  • resource – resource file path.
  • sensitivity – decoder sensitivity, a float of a list of floats. The bigger the value, the more senstive the decoder. If an empty list is provided, then the default sensitivity in the model will be used.
  • audio_gain – multiply input volume by this factor.
  • apply_frontend – applies the frontend processing algorithm if True.
saveMessage()[源代码]

Save the message stored in self.recordedData to a timestamped file.

start(detected_callback=<function play_audio_file>, interrupt_check=<function HotwordDetector.<lambda>>, sleep_time=0.03, audio_recorder_callback=None, silent_count_threshold=15, recording_timeout=100)[源代码]

Start the voice detector. For every sleep_time second it checks the audio buffer for triggering keywords. If detected, then call corresponding function in detected_callback, which can be a single function (single model) or a list of callback functions (multiple models). Every loop it also calls interrupt_check – if it returns True, then breaks from the loop and return.

参数:
  • detected_callback – a function or list of functions. The number of items must match the number of models in decoder_model.
  • interrupt_check – a function that returns True if the main loop needs to stop.
  • sleep_time (float) – how much time in second every loop waits.
  • audio_recorder_callback – if specified, this will be called after a keyword has been spoken and after the phrase immediately after the keyword has been recorded. The function will be passed the name of the file where the phrase was recorded.
  • silent_count_threshold – indicates how long silence must be heard to mark the end of a phrase that is being recorded.
  • recording_timeout – limits the maximum length of a recording.
返回:

None

terminate()[源代码]

Terminate audio stream. Users can call start() again to detect. :return: None

class snowboy.snowboydecoder.RingBuffer(size=4096)[源代码]

基类:object

Ring buffer to hold audio from PortAudio

extend(data)[源代码]

Adds data to the end of buffer

get()[源代码]

Retrieves data from the beginning of buffer and clears it

snowboy.snowboydecoder.no_alsa_error()[源代码]
snowboy.snowboydecoder.play_audio_file(fname='/Users/panweizhou/Documents/projects/wukong-robot/snowboy/resources/ding.wav')[源代码]

Simple callback function to play a wave file. By default it plays a Ding sound.

参数:fname (str) – wave file name
返回:None
snowboy.snowboydecoder.py_error_handler(filename, line, function, err, fmt)[源代码]

snowboy.snowboydetect module

class snowboy.snowboydetect.SnowboyDetect(resource_filename, model_str)[源代码]

基类:object

ApplyFrontend(apply_frontend)[源代码]
BitsPerSample()[源代码]
GetSensitivity()[源代码]
NumChannels()[源代码]
NumHotwords()[源代码]
Reset()[源代码]
RunDetection(*args)[源代码]
SampleRate()[源代码]
SetAudioGain(audio_gain)[源代码]
SetHighSensitivity(high_sensitivity_str)[源代码]
SetSensitivity(sensitivity_str)[源代码]
UpdateModel()[源代码]
class snowboy.snowboydetect.SnowboyVad(resource_filename)[源代码]

基类:object

ApplyFrontend(apply_frontend)[源代码]
BitsPerSample()[源代码]
NumChannels()[源代码]
Reset()[源代码]
RunVad(*args)[源代码]
SampleRate()[源代码]
SetAudioGain(audio_gain)[源代码]

Module contents

================================================ FILE: docs/statistic.html ================================================ statistic module — wukong-robot 1.2.0 文档

statistic module

================================================ FILE: docs/utils.html ================================================ utils module — wukong-robot 1.2.0 文档

utils module

================================================ FILE: docs/wukong.html ================================================ wukong module — wukong-robot 1.2.0 文档

wukong module

class wukong.Wukong[源代码]

基类:object

dev()[源代码]
fetch()[源代码]
init()[源代码]
initDetector()[源代码]
md5(password)[源代码]
profiling()[源代码]
restart()[源代码]
run()[源代码]
update()[源代码]
================================================ FILE: plugins/Camera.py ================================================ # -*- coding: utf-8 -*- import os import subprocess import time from robot import config, constants, logging from robot.sdk.AbstractPlugin import AbstractPlugin logger = logging.getLogger(__name__) class Plugin(AbstractPlugin): SLUG = "camera" def handle(self, text, parsed): quality = config.get("/camera/quality", 100) count_down = config.get("/camera/count_down", 3) dest_path = config.get("/camera/dest_path", os.path.expanduser("~/pictures")) device = config.get("/camera/device", "/dev/video0") vertical_flip = config.get("/camera/vetical_flip", False) horizontal_flip = config.get("/camera/horizontal_flip", False) sound = config.get("/camera/sound", True) camera_type = config.get("/camera/type", 0) if config.has("/camera/usb_camera") and config.get("/camera/usb_camera"): camera_type = 0 if any(word in text for word in ["安静", "偷偷", "悄悄"]): sound = False try: if not os.path.exists(dest_path): os.makedirs(dest_path) except Exception: self.say("抱歉,照片目录创建失败", cache=True) return dest_file = os.path.join(dest_path, "%s.jpg" % time.time()).replace(".", "", 1) if camera_type == 0: # usb camera logger.info("usb camera") command = ["fswebcam", "--no-banner", "-r", "1024x765", "-q", "-d", device] if vertical_flip: command.extend(["-s", "v"]) if horizontal_flip: command.extend(["-s", "h"]) command.append(dest_file) elif camera_type == 1: # Raspberry Pi 5MP logger.info("Raspberry Pi 5MP camera") command = ["raspistill", "-o", dest_file, "-q", str(quality)] if count_down > 0 and sound: command.extend(["-t", str(count_down * 1000)]) if vertical_flip: command.append("-vf") if horizontal_flip: command.append("-hf") else: # notebook camera logger.info("notebook camera") command = ["imagesnap", dest_file] if count_down > 0 and sound: command.extend(["-w", str(count_down)]) if sound and count_down > 0: self.say("收到,%d秒后启动拍照" % (count_down), cache=True) if camera_type == 0: time.sleep(count_down) try: subprocess.run(command, shell=False, check=True) if sound: self.play(constants.getData("camera.wav")) photo_url = "http://{}:{}/photo/{}".format( config.get("/server/host"), config.get("/server/port"), os.path.basename(dest_file), ) self.say("拍照成功", cache=True) self.say(photo_url) except subprocess.CalledProcessError as e: logger.error(e, stack_info=True) if sound: self.say("拍照失败,请检查相机是否连接正确", cache=True) def isValid(self, text, parsed): return any(word in text for word in ["拍照", "拍张照"]) and not any( word in text for word in ["拍照成功", "拍照失败", "后启动拍照"] ) ================================================ FILE: plugins/CleanCache.py ================================================ # -*- coding: utf-8 -*- import os from robot import constants, utils from robot.sdk.AbstractPlugin import AbstractPlugin class Plugin(AbstractPlugin): SLUG = "cleancache" def handle(self, text, parsed): temp = constants.TEMP_PATH for f in os.listdir(temp): if f != "DIR": utils.check_and_delete(os.path.join(temp, f)) self.say("缓存目录已清空", cache=True) def isValid(self, text, parsed): return any(word in text.lower() for word in ["清除缓存", "清空缓存", "清缓存"]) ================================================ FILE: plugins/Echo.py ================================================ # -*- coding: utf-8 -*- # author: wzpan # 回声 import logging from robot.sdk.AbstractPlugin import AbstractPlugin logger = logging.getLogger(__name__) class Plugin(AbstractPlugin): def handle(self, text, parsed): text = text.lower().replace("echo", "").replace("传话", "") self.say(text, cache=False) def isValid(self, text, parsed): return any(word in text.lower() for word in ["echo", "传话"]) ================================================ FILE: plugins/Email.py ================================================ # -*- coding: utf-8 -*- import imaplib import email import time import datetime from robot import logging from dateutil import parser from robot import config from robot.sdk.AbstractPlugin import AbstractPlugin class Plugin(AbstractPlugin): SLUG = "email" def getSender(self, msg): """ Returns the best-guess sender of an email. Arguments: msg -- the email whose sender is desired Returns: Sender of the sender. """ fromstr = str(msg["From"]) ls = fromstr.split(" ") if len(ls) == 2: fromname = email.header.decode_header(str(ls[0]).strip('"')) sender = fromname[0][0] elif len(ls) > 2: fromname = email.header.decode_header( str(fromstr[: fromstr.find("<")]).strip('"') ) sender = fromname[0][0] else: sender = msg["From"] if isinstance(sender, bytes): try: return sender.decode("utf-8") except UnicodeDecodeError: return sender.decode("gbk") else: return sender def isSelfEmail(self, msg): """Whether the email is sent by the user""" fromstr = str(msg["From"]) addr = (fromstr[fromstr.find("<") + 1 : fromstr.find(">")]).strip('"') address = config.get()[self.SLUG]["address"].strip() return addr == address def getSubject(self, msg): """ Returns the title of an email Arguments: msg -- the email Returns: Title of the email. """ subject = email.header.decode_header(msg["subject"]) if isinstance(subject[0][0], bytes): try: sub = subject[0][0].decode("utf-8") except UnicodeDecodeError: sub = subject[0][0].decode("gbk") else: sub = subject[0][0] to_read = False if sub.strip() == "": return "" to_read = config.get("/email/read_email_title", True) if to_read: return "邮件标题为 %s" % sub return "" def isNewEmail(msg): """Wether an email is a new email""" date = str(msg["Date"]) dtext = date.split(",")[1].split("+")[0].strip() dtime = time.strptime(dtext, "%d %b %Y %H:%M:%S") current = time.localtime() dt = datetime.datetime(*dtime[:6]) cr = datetime.datetime(*current[:6]) return (cr - dt).days == 0 def getDate(self, email): return parser.parse(email.get("date")) def getMostRecentDate(self, emails): """ Returns the most recent date of any email in the list provided. Arguments: emails -- a list of emails to check Returns: Date of the most recent email. """ dates = [self.getDate(e) for e in emails] dates.sort(reverse=True) if dates: return dates[0] return None def fetchUnreadEmails(self, since=None, markRead=False, limit=None): """ Fetches a list of unread email objects from a user's email inbox. Arguments: since -- if provided, no emails before this date will be returned markRead -- if True, marks all returned emails as read in target inbox Returns: A list of unread email objects. """ logger = logging.getLogger(__name__) profile = config.get() conn = imaplib.IMAP4( profile[self.SLUG]["imap_server"], profile[self.SLUG]["imap_port"] ) conn.debug = 0 msgs = [] try: conn.login(profile[self.SLUG]["address"], profile[self.SLUG]["password"]) conn.select(readonly=(not markRead)) (retcode, messages) = conn.search(None, "(UNSEEN)") except Exception: logger.warning("抱歉,您的邮箱账户验证失败了,请检查下配置") return None if retcode == "OK" and messages != [b""]: numUnread = len(messages[0].split(b" ")) if limit and numUnread > limit: return numUnread for num in messages[0].split(b" "): # parse email RFC822 format ret, data = conn.fetch(num, "(RFC822)") if data is None: continue msg = email.message_from_string(data[0][1].decode("utf-8")) if not since or self.getDate(msg) > since: msgs.append(msg) conn.close() conn.logout() return msgs def handle(self, text, parsed): msgs = self.fetchUnreadEmails(limit=5) if msgs is None: self.say("抱歉,您的邮箱账户验证失败了", cache=True) return if isinstance(msgs, int): response = "您有 %d 封未读邮件" % msgs self.say(response, cache=True) return senders = [str(self.getSender(e)) for e in msgs] if not senders: self.say("您没有未读邮件,真棒!", cache=True) elif len(senders) == 1: self.say(f"您有来自 {senders[0]} 的未读邮件。{self.getSubject(msgs[0])}") else: response = "您有 %d 封未读邮件" % len(senders) unique_senders = list(set(senders)) if len(unique_senders) > 1: unique_senders[-1] = ", " + unique_senders[-1] response += "。这些邮件的发件人包括:" response += " 和 ".join(senders) else: response += ",邮件都来自 " + unique_senders[0] self.say(response) def isValid(self, text, parsed): return any(word in text for word in ["邮箱", "邮件"]) ================================================ FILE: plugins/Geek.py ================================================ # -*- coding: utf-8 -*- from robot import config, logging from robot.sdk.AbstractPlugin import AbstractPlugin logger = logging.getLogger(__name__) class Plugin(AbstractPlugin): IS_IMMERSIVE = True # 这是个沉浸式技能 SLUG = "geek" def __init__(self, con): super(Plugin, self).__init__(con) self.silent_count = 0 def handle(self, text, parsed): if any(word in text for word in ["开启", "激活", "开始", "进入", "打开"]): self.silent_count = 0 self.say( "进入极客模式", cache=True, onCompleted=lambda: self.onAsk(self.activeListen(silent=True)), ) else: self.say("退出极客模式", cache=True) self.clearImmersive() def onAsk(self, input): if input: logger.debug(f"input: {input}") self.silent_count = 0 self.con.doResponse(input) else: self.silent_count += 1 if self.silent_count >= config.get("/geek/max_silent_count", 20): self.say("退出极客模式", cache=True) self.clearImmersive() else: self.onAsk(self.activeListen(silent=True)) def restore(self): self.onAsk(self.activeListen(silent=True)) def isValidImmersive(self, text, parsed): return ( "模式" in text and any(word in text for word in ["即刻", "即可", "极客", "即客", "集团", "集客"]) and any(word in text for word in ["退出", "结束", "停止"]) ) def isValid(self, text, parsed): return ( "模式" in text and any(word in text for word in ["即刻", "即可", "即客", "集团", "极客", "集客"]) and any(word in text for word in ["开启", "激活", "开始", "进入", "打开"]) ) ================================================ FILE: plugins/Gossip.py ================================================ # -*- coding: utf-8 -*- # author: wzpan # 闲聊一下 import logging from robot.sdk.AbstractPlugin import AbstractPlugin logger = logging.getLogger(__name__) ENTRY_WORDS = ["进入", "打开", "激活", "开启", "一下"] CLOSE_WORDS = ["退出", "结束", "停止"] class Plugin(AbstractPlugin): IS_IMMERSIVE = True def handle(self, text, parsed): if "闲聊一下" in text or "进入闲聊" in text: # 进入闲聊模式 self.say("好的,已进入闲聊模式", cache=True) else: self.clearImmersive() # 去掉沉浸式 self.say("结束闲聊", cache=True) def isValidImmersive(self, text, parsed): return "闲聊" in text and any(word in text for word in CLOSE_WORDS) def isValid(self, text, parsed): return "闲聊" in text and any(word in text for word in ENTRY_WORDS) ================================================ FILE: plugins/LocalPlayer.py ================================================ # -*- coding: utf-8 -*- import os import platform from robot import config, logging from robot.Player import MusicPlayer from robot.sdk.AbstractPlugin import AbstractPlugin logger = logging.getLogger(__name__) class Plugin(AbstractPlugin): IS_IMMERSIVE = True # 这是个沉浸式技能 def __init__(self, con): super(Plugin, self).__init__(con) self.player = None self.song_list = None def get_song_list(self, path): if not os.path.exists(path) or not os.path.isdir(path): return [] song_list = list( filter(lambda d: d.endswith(".mp3") or d.endswith("wav"), os.listdir(path)) ) return [os.path.join(path, song) for song in song_list] def init_music_player(self): self.song_list = self.get_song_list(config.get("/LocalPlayer/path")) if self.song_list == None: logger.error(f"{self.SLUG} 插件配置有误", stack_info=True) logger.info(f"本地音乐列表:{self.song_list}") return MusicPlayer(self.song_list, self) def handle(self, text, parsed): if not self.player: self.player = self.init_music_player() if len(self.song_list) == 0: self.clearImmersive() # 去掉沉浸式 self.say("本地音乐目录并没有音乐文件,播放失败") return if self.nlu.hasIntent(parsed, "MUSICRANK"): self.player.play() elif self.nlu.hasIntent(parsed, "CHANGE_TO_NEXT"): self.player.next() elif self.nlu.hasIntent(parsed, "CHANGE_TO_LAST"): self.player.prev() elif self.nlu.hasIntent(parsed, "CHANGE_VOL"): slots = self.nlu.getSlots(parsed, "CHANGE_VOL") for slot in slots: if slot["name"] == "user_d": word = self.nlu.getSlotWords(parsed, "CHANGE_VOL", "user_d")[0] if word == "--HIGHER--": self.player.turnUp() else: self.player.turnDown() return elif slot["name"] == "user_vd": word = self.nlu.getSlotWords(parsed, "CHANGE_VOL", "user_vd")[0] if word == "--LOUDER--": self.player.turnUp() else: self.player.turnDown() elif self.nlu.hasIntent(parsed, "CONTINUE"): logger.info("继续播放") self.player.resume() elif self.nlu.hasIntent(parsed, "CLOSE_MUSIC") or self.nlu.hasIntent( parsed, "PAUSE" ): logger.info("停止播放") self.player.stop() self.clearImmersive() # 去掉沉浸式 else: self.say("没听懂你的意思呢,要停止播放,请说停止播放") self.player.resume() def pause(self): if self.player: system = platform.system() # BigSur 以上 Mac 系统的 pkill 无法正常暂停音频, # 因此改成直接停止播放,不再支持沉浸模式 if system == "Darwin" and float(platform.mac_ver()[0][:5]) >= 10.16: logger.warning("注意:Mac BigSur 以上系统无法正常暂停音频,将停止播放,不支持恢复播放") self.player.stop() return self.player.pause() def restore(self): if self.player and self.player.is_pausing(): self.player.resume() def isValidImmersive(self, text, parsed): return any( self.nlu.hasIntent(parsed, intent) for intent in [ "CHANGE_TO_LAST", "CHANGE_TO_NEXT", "CHANGE_VOL", "CLOSE_MUSIC", "PAUSE", "CONTINUE", ] ) def isValid(self, text, parsed): return "本地音乐" in text ================================================ FILE: plugins/Poem.py ================================================ # -*- coding: utf-8 -*- # author: wzpan # 写诗 import logging from robot.sdk.AbstractPlugin import AbstractPlugin INTENT = "BUILT_POEM" logger = logging.getLogger(__name__) class Plugin(AbstractPlugin): SLUG = "poem" def handle(self, text, parsed): try: responds = self.nlu.getSay(parsed, INTENT) self.say(responds, cache=True) except Exception as e: logger.error(e, stack_info=True) self.say("抱歉,写诗插件出问题了,请稍后再试", cache=True) def isValid(self, text, parsed): return self.nlu.hasIntent(parsed, INTENT) and "写" in text and "诗" in text ================================================ FILE: plugins/Reminder.py ================================================ # -*- coding: utf-8 -*- # author: wzpan # 闹钟 import logging import os import pickle import time from robot import config, constants, utils from robot.sdk.AbstractPlugin import AbstractPlugin logger = logging.getLogger(__name__) LOCAL_REMINDER = os.path.join(constants.TEMP_PATH, "reminder.pkl") class Plugin(AbstractPlugin): def __init__(self, con): super(Plugin, self).__init__(con) def _dump_reminders(self): logger.info("写入日程提醒信息") with open(LOCAL_REMINDER, "wb") as f: pickle.dump(self.con.scheduler.get_jobs(), f) def alarm(self, remind_time, content, job_id): self.con.player.stop() # 停止所有音频 content = utils.stripPunctuation(content) self.say( f"现在是{time.strftime('%H:%M:%S', time.localtime(time.time()))},该{content}了。" * int(config.get("/reminder/repeat", 3)) ) # 非周期性提醒,提醒完即删除 if "repeat" not in remind_time: self.con.scheduler.del_job_by_id(job_id) self._dump_reminders() def list_reminder(self, parsed): """ 列举所有的日程 """ logger.info("list_reminder") _jobs = self.con.scheduler.get_jobs() if len(_jobs) == 0: self.say(f"您当前没有提醒。", cache=True) elif len(_jobs) > 1: self.say(f"您当前有{len(_jobs)}个提醒。", cache=True) index = 0 for job in _jobs: self.say(f"第{index+1}个提醒内容是{job.describe}") logger.info(f"index: {index}, job.job_id: {job.job_id}") index += 1 elif len(_jobs) == 1: self.say(f"您当前有1个提醒。", cache=True) self.say(f"提醒内容是{_jobs[0].describe}") def add_reminder(self, parsed): logger.info("add_reminder") remind_times = self.nlu.getSlotWords(parsed, "SET_REMIND", "user_remind_time") original_times = self.nlu.getSlotOriginalWords( parsed, "SET_REMIND", "user_remind_time" ) contents = self.nlu.getSlotWords(parsed, "SET_REMIND", "user_wild_content") if len(remind_times) < 0 or "|" not in remind_times[0]: self.say("添加提醒失败。请说明需要我提醒的时间", cache=True) return if len(contents) < 0: self.say("添加提醒失败。请说明需要我提醒做什么", cache=True) return remind_time, original_time, content = ( remind_times[0], original_times[0], contents[0], ) job_id = utils.getTimemStap() job = self.con.scheduler.add_job( remind_time, original_time, content, lambda: self.alarm(remind_time, content, job_id), job_id=job_id, ) if job: self._dump_reminders() logger.info(f"added reminder: {job.describe}, job_id: {job_id}") self.say(f"好的,已为您添加提醒:{job.describe}") else: self.say("抱歉,添加提醒失败了") def _assure(self): pick = self.activeListen() if "不" in pick: self.say("好的。取消删除", cache=True) return False elif any(yes in pick for yes in ("是", "要", "删除")): return True else: self.say("取消删除", cache=True) return False def _ask_which(self): self.say(f"要删除哪一个提醒呢", cache=True) pick = self.activeListen() parsed = self.parse(pick) if self.nlu.hasIntent(parsed, "HASS_INDEX"): _jobs = self.con.scheduler.get_jobs() index = int( float( self.nlu.getSlotWords(parsed, "HASS_INDEX", "user_index")[0].split( "|" )[0] ) ) logger.info(f"用户选择了第{index}个") if index < 0 or index > len(_jobs): self.say("没有找到符合条件的提醒,删除失败", cache=True) return -1 job = _jobs[index - 1] return job.job_id else: self.say("没有找到符合条件的提醒,删除失败", cache=True) return "" def del_reminder(self, parsed): logger.info("del_reminder") self.list_reminder(parsed) _jobs = self.con.scheduler.get_jobs() if len(_jobs) == 1: self.say("要删除这个提醒吗", cache=True) if self._assure(): try: self.con.scheduler.del_job_by_id(_jobs[0].job_id) self._dump_reminders() self.say("好的,已删除该提醒") except Exception as e: logger.error(f"删除失败: {e}") self.say("删除提醒失败") elif len(_jobs) > 1: job_id = self._ask_which() if job_id: try: self.con.scheduler.del_job_by_id(job_id) self._dump_reminders() self.say("好的,已删除该提醒") except Exception as e: logger.error(f"删除失败: {e}") self.say("删除提醒失败") def handle(self, text, parsed): logger.info("Reminder handle") if self.nlu.hasIntent(parsed, "CHECK_REMIND"): # 查询当前设置的提醒 self.list_reminder(parsed) elif self.nlu.hasIntent(parsed, "DELETE_REMIND"): # 删除指定的提醒 self.del_reminder(parsed) elif self.nlu.hasIntent(parsed, "SET_REMIND"): # 设置提醒 self.add_reminder(parsed) def isValid(self, text, parsed): return any( self.nlu.hasIntent(parsed, intent) for intent in ["CHECK_REMIND", "DELETE_REMIND", "SET_REMIND"] ) ================================================ FILE: plugins/Volume.py ================================================ # -*- coding: utf-8 -*- from robot.Player import MusicPlayer from robot import logging from robot.sdk.AbstractPlugin import AbstractPlugin logger = logging.getLogger(__name__) class Plugin(AbstractPlugin): def __init__(self, con): super(Plugin, self).__init__(con) self.player = None def handle(self, text, parsed): if not self.player: self.player = MusicPlayer([], self) if self.nlu.hasIntent(parsed, "CHANGE_VOL"): slots = self.nlu.getSlots(parsed, "CHANGE_VOL") for slot in slots: if slot["name"] == "user_d": word = self.nlu.getSlotWords(parsed, "CHANGE_VOL", "user_d")[0] if word == "--HIGHER--": self.player.turnUp() self.say("好的", cache=True) else: self.player.turnDown() self.say("好的", cache=True) return elif slot["name"] == "user_vd": word = self.nlu.getSlotWords(parsed, "CHANGE_VOL", "user_vd")[0] if word == "--LOUDER--": self.player.turnUp() self.say("好的", cache=True) else: self.player.turnDown() self.say("好的", cache=True) def isValid(self, text, parsed): return self.nlu.hasIntent(parsed, "CHANGE_VOL") ================================================ FILE: plugins/__init__.py ================================================ ================================================ FILE: requirements.txt ================================================ pyyaml>=4.2b1 requests==2.31.0 baidu-aip==2.0.0.1 pydub==0.23.1 python-dateutil==2.7.5 watchdog==0.9.0 pytz==2018.9 fire==0.1.3 tornado==6.3.3 markdown==3.0.1 semver==2.8.1 websocket==0.2.1 websocket-client pypinyin jieba pvporcupine pvrecorder==1.1.1 openai apscheduler asyncio edge-tts nest_asyncio funasr_onnx ================================================ FILE: robot/AI.py ================================================ # -*- coding: utf-8 -*- import os import json import random import requests from uuid import getnode as get_mac from abc import ABCMeta, abstractmethod from robot import logging, config, utils from robot.sdk import unit logger = logging.getLogger(__name__) class AbstractRobot(object): __metaclass__ = ABCMeta @classmethod def get_instance(cls): profile = cls.get_config() instance = cls(**profile) return instance def __init__(self, **kwargs): pass @abstractmethod def chat(self, texts, parsed): pass @abstractmethod def stream_chat(self, texts): pass class TulingRobot(AbstractRobot): SLUG = "tuling" def __init__(self, tuling_key): """ 图灵机器人 """ super(self.__class__, self).__init__() self.tuling_key = tuling_key @classmethod def get_config(cls): return config.get("tuling", {}) def chat(self, texts, parsed=None): """ 使用图灵机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = "".join(texts) msg = utils.stripPunctuation(msg) try: url = "http://openapi.turingapi.com/openapi/api/v2" userid = str(get_mac())[:32] body = { "perception": {"inputText": {"text": msg}}, "userInfo": {"apiKey": self.tuling_key, "userId": userid}, } r = requests.post(url, json=body) respond = json.loads(r.text) result = "" if "results" in respond: for res in respond["results"]: result += "\n".join(res["values"].values()) else: result = "图灵机器人服务异常,请联系作者" logger.info(f"{self.SLUG} 回答:{result}") return result except Exception: logger.critical( "Tuling robot failed to response for %r", msg, exc_info=True ) return "抱歉, 图灵机器人服务回答失败" class UnitRobot(AbstractRobot): SLUG = "unit" def __init__(self): """ 百度UNIT机器人 """ super(self.__class__, self).__init__() @classmethod def get_config(cls): return {} def chat(self, texts, parsed): """ 使用百度UNIT机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = "".join(texts) msg = utils.stripPunctuation(msg) try: result = unit.getSay(parsed) logger.info("{} 回答:{}".format(self.SLUG, result)) return result except Exception: logger.critical("UNIT robot failed to response for %r", msg, exc_info=True) return "抱歉, 百度UNIT服务回答失败" class BingRobot(AbstractRobot): SLUG = "bing" def __init__(self, prefix, proxy, mode): """ bing """ super(self.__class__, self).__init__() self.prefix = prefix self.proxy = proxy self.mode = mode @classmethod def get_config(cls): return config.get("bing", {}) def chat(self, texts, parsed): """ Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = "".join(texts) msg = utils.stripPunctuation(msg) try: import asyncio, json from EdgeGPT.EdgeGPT import Chatbot, ConversationStyle async def query_bing(): # Passing cookies is "optional" bot = await Chatbot.create(proxy=self.proxy) m2s = { "creative": ConversationStyle.creative, "balanced": ConversationStyle.balanced, "precise": ConversationStyle.precise } response = await bot.ask(prompt=self.prefix + "\n" + msg, conversation_style=m2s[self.mode], simplify_response=True) #print(json.dumps(response, indent=2)) # Returns return response["text"] await bot.close() result = asyncio.run(query_bing()) logger.info("{} 回答:{}".format(self.SLUG, result)) return result except Exception: logger.critical("bing robot failed to response for %r", msg, exc_info=True) return "抱歉, bing回答失败" class AnyQRobot(AbstractRobot): SLUG = "anyq" def __init__(self, host, port, solr_port, threshold, secondary): """ AnyQ机器人 """ super(self.__class__, self).__init__() self.host = host self.threshold = threshold self.port = port self.secondary = secondary @classmethod def get_config(cls): # Try to get anyq config from config return config.get("anyq", {}) def chat(self, texts, parsed): """ 使用AnyQ机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = "".join(texts) msg = utils.stripPunctuation(msg) try: url = f"http://{self.host}:{self.port}/anyq?question={msg}" r = requests.get(url) respond = json.loads(r.text) logger.info(f"anyq response: {respond}") if len(respond) > 0: # 有命中,进一步判断 confidence 是否达到要求 confidence = respond[0]["confidence"] if confidence >= self.threshold: # 命中该问题,返回回答 answer = respond[0]["answer"] if utils.validjson(answer): answer = random.choice(json.loads(answer)) logger.info(f"{self.SLUG} 回答:{answer}") return answer # 没有命中,走兜底 if self.secondary != "null" and self.secondary: try: ai = get_robot_by_slug(self.secondary) return ai.chat(texts, parsed) except Exception: logger.critical( f"Secondary robot {self.secondary} failed to response for {msg}" ) return get_unknown_response() else: return get_unknown_response() except Exception: logger.critical("AnyQ robot failed to response for %r", msg, exc_info=True) return "抱歉, AnyQ回答失败" class OPENAIRobot(AbstractRobot): SLUG = "openai" def __init__( self, openai_api_key, model, provider, api_version, temperature, max_tokens, top_p, frequency_penalty, presence_penalty, stop_ai, prefix="", proxy="", api_base="", ): """ OpenAI机器人 """ super(self.__class__, self).__init__() self.openai = None try: import openai self.openai = openai if not openai_api_key: openai_api_key = os.getenv("OPENAI_API_KEY") self.openai.api_key = openai_api_key if proxy: logger.info(f"{self.SLUG} 使用代理:{proxy}") self.openai.proxy = proxy else: self.openai.proxy = None except Exception: logger.critical("OpenAI 初始化失败,请升级 Python 版本至 > 3.6") self.model = model self.prefix = prefix self.provider = provider self.api_version = api_version self.temperature = temperature self.max_tokens = max_tokens self.top_p = top_p self.frequency_penalty = frequency_penalty self.presence_penalty = presence_penalty self.stop_ai = stop_ai self.api_base = api_base if api_base else "https://api.openai.com/v1/chat" self.context = [] @classmethod def get_config(cls): # Try to get anyq config from config return config.get("openai", {}) def stream_chat(self, texts): """ 从ChatGPT API获取回复 :return: 回复 """ msg = "".join(texts) msg = utils.stripPunctuation(msg) msg = self.prefix + msg # 增加一段前缀 logger.info("msg: " + msg) self.context.append({"role": "user", "content": msg}) header = { "Content-Type": "application/json", # "Authorization": "Bearer " + self.openai.api_key } if self.provider == 'openai': header['Authorization'] = "Bearer " + self.openai.api_key elif self.provider == 'azure': header['api-key'] = self.openai.api_key else: raise ValueError("Please check your config file, OpenAiRobot's provider should be openai or azure.") data = {"model": self.model, "messages": self.context, "stream": True} logger.info(f"使用模型:{self.model},开始流式请求") url = self.api_base + "/completions" if self.provider == 'azure': url = f"{self.api_base}/openai/deployments/{self.model}/chat/completions?api-version={self.api_version}" # 请求接收流式数据 try: response = requests.request( "POST", url, headers=header, json=data, stream=True, proxies={"https": self.openai.proxy}, ) def generate(): stream_content = str() one_message = {"role": "assistant", "content": stream_content} self.context.append(one_message) i = 0 for line in response.iter_lines(): line_str = str(line, encoding="utf-8") if line_str.startswith("data:") and line_str[5:]: if line_str.startswith("data: [DONE]"): break line_json = json.loads(line_str[5:]) if "choices" in line_json: if len(line_json["choices"]) > 0: choice = line_json["choices"][0] if "delta" in choice: delta = choice["delta"] if "role" in delta: role = delta["role"] elif "content" in delta: delta_content = delta["content"] i += 1 if i < 40: logger.debug(delta_content, end="") elif i == 40: logger.debug("......") one_message["content"] = ( one_message["content"] + delta_content ) yield delta_content elif len(line_str.strip()) > 0: logger.debug(line_str) yield line_str except Exception as e: ee = e def generate(): yield "request error:\n" + str(ee) return generate def chat(self, texts, parsed): """ 使用OpenAI机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = "".join(texts) msg = utils.stripPunctuation(msg) msg = self.prefix + msg # 增加一段前缀 logger.info("msg: " + msg) try: respond = "" self.context.append({"role": "user", "content": msg}) if self.provider == "openai": response = self.openai.Completion.create( model=self.model, messages=self.context, temperature=self.temperature, max_tokens=self.max_tokens, top_p=self.top_p, frequency_penalty=self.frequency_penalty, presence_penalty=self.presence_penalty, stop=self.stop_ai, api_base=self.api_base ) else: from openai import AzureOpenAI client = AzureOpenAI( azure_endpoint = self.api_base, api_key=self.openai_api_key, api_version=self.api_version ) response = client.chat.completions.create( model=self.model, messages=self.context ) message = response.choices[0].message respond = message.content self.context.append(message) return respond except self.openai.error.InvalidRequestError: logger.warning("token超出长度限制,丢弃历史会话") self.context = [] return self.chat(texts, parsed) except Exception: logger.critical( "openai robot failed to response for %r", msg, exc_info=True ) return "抱歉,OpenAI 回答失败" class WenxinRobot(AbstractRobot): SLUG = "wenxin" def __init__(self, api_key, secret_key): """ Wenxin机器人 """ super(self.__class__, self).__init__() self.api_key = api_key self.secret_key = secret_key @classmethod def get_config(cls): return config.get("wenxin", {}) def chat(self, texts, _): """ 使用Wenxin机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = "".join(texts) msg = utils.stripPunctuation(msg) wenxinurl = f"https://aip.baidubce.com/oauth/2.0/token?client_id={self.api_key}&\ client_secret={self.secret_key}&grant_type=client_credentials" try: headers = { "Content-Type": "application/json", "Accept": "application/json", } payload = json.dumps({ "question": [ { "role": "user", "content": msg, } ] }) response = requests.request("POST", wenxinurl, headers=headers) logger.info(f"wenxin response: {response}") return response.text except Exception: logger.critical("Wenxin robot failed to response for %r", msg, exc_info=True) return "抱歉, Wenxin回答失败" class TongyiRobot(AbstractRobot): ''' usage: pip install dashscope echo "export DASHSCOPE_API_KEY=YOUR_KEY" >> /.bashrc ''' SLUG = "tongyi" def __init__(self, api_key): """ Tongyi机器人 """ super(self.__class__, self).__init__() self.api_key = api_key @classmethod def get_config(cls): return config.get("tongyi", {}) def chat(self, texts, _): """ 使用Tongyi机器人聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = "".join(texts) msg = utils.stripPunctuation(msg) msg = [{"role": "user", "content": msg}] try: response = dashscope.Generation.call( model='qwen1.5-72b-chat', messages=msg, result_format='message', # set the result to be "message" format. ) logger.info(f"tongyi response: {response}") return response['output']['choices'][0]['message']['content'] except Exception: logger.critical("Tongyi robot failed to response for %r", msg, exc_info=True) return "抱歉, Tongyi回答失败" class CozeRobot(AbstractRobot): SLUG = "coze" def __init__(self, botid, token, **kwargs): super(self.__class__, self).__init__() self.botid = botid self.token = token self.userid = str(get_mac())[:32] @classmethod def get_config(cls): return config.get("coze", {}) def chat(self, texts, parsed=None): """ 使用coze聊天 Arguments: texts -- user input, typically speech, to be parsed by a module """ msg = "".join(texts) msg = utils.stripPunctuation(msg) try: url = "https://api.coze.cn/open_api/v2/chat" body = { "conversation_id": "123", "bot_id": self.botid, "user": self.userid, "query": msg, "stream": False } headers = { "Authorization": "Bearer " + self.token, "Content-Type": "application/json", "Accept": "*/*", "Host": "api.coze.cn", "Connection": "keep-alive" } r = requests.post(url, headers=headers, json=body) respond = json.loads(r.text) result = "" logger.info(f"{self.SLUG} 回答:{respond}") if "messages" in respond: for m in respond["messages"]: if m["type"] == "answer": result = m["content"].replace("\n", "").replace("\r", "") else: result = "抱歉,扣子回答失败" if result == "": result = "抱歉,扣子回答失败" logger.info(f"{self.SLUG} 回答:{result}") return result except Exception: logger.critical( "Tuling robot failed to response for %r", msg, exc_info=True ) return "抱歉, 扣子回答失败" def get_unknown_response(): """ 不知道怎么回答的情况下的答复 :returns: 表示不知道的答复 """ results = ["抱歉,我不会这个呢", "我不会这个呢", "我还不会这个呢", "我还没学会这个呢", "对不起,你说的这个,我还不会"] return random.choice(results) def get_robot_by_slug(slug): """ Returns: A robot implementation available on the current platform """ if not slug or type(slug) is not str: raise TypeError("Invalid slug '%s'", slug) selected_robots = list( filter( lambda robot: hasattr(robot, "SLUG") and robot.SLUG == slug, get_robots() ) ) if len(selected_robots) == 0: raise ValueError("No robot found for slug '%s'" % slug) else: if len(selected_robots) > 1: logger.warning( "WARNING: Multiple robots found for slug '%s'. " + "This is most certainly a bug." % slug ) robot = selected_robots[0] logger.info(f"使用 {robot.SLUG} 对话机器人") return robot.get_instance() def get_robots(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [ robot for robot in list(get_subclasses(AbstractRobot)) if hasattr(robot, "SLUG") and robot.SLUG ] ================================================ FILE: robot/ASR.py ================================================ # -*- coding: utf-8 -*- import json from aip import AipSpeech from .sdk import TencentSpeech, AliSpeech, XunfeiSpeech, BaiduSpeech, FunASREngine, VolcengineSpeech from . import utils, config from robot import logging from abc import ABCMeta, abstractmethod import requests logger = logging.getLogger(__name__) class AbstractASR(object): """ Generic parent class for all ASR engines """ __metaclass__ = ABCMeta @classmethod def get_config(cls): return {} @classmethod def get_instance(cls): profile = cls.get_config() instance = cls(**profile) return instance @abstractmethod def transcribe(self, fp): pass class AzureASR(AbstractASR): """ 微软的语音识别API """ SLUG = "azure-asr" def __init__(self, secret_key, region, lang="zh-CN", **args): super(self.__class__, self).__init__() self.post_url = "https://.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1".replace( "", region ) self.post_header = { "Ocp-Apim-Subscription-Key": secret_key, "Content-Type": "audio/wav; codecs=audio/pcm; samplerate=16000", "Accept": "application/json", } self.post_param = {"language": lang, "profanity": "raw"} self.sess = requests.session() @classmethod def get_config(cls): # Try to get azure_yuyin config from config return config.get("azure_yuyin", {}) def transcribe(self, fp): # 识别本地文件 pcm = utils.get_pcm_from_wav(fp) ret = self.sess.post( url=self.post_url, data=pcm, headers=self.post_header, params=self.post_param, ) if ret.status_code == 200: res = ret.json() logger.info(f"{self.SLUG} 语音识别到了:{res['DisplayText']}") return "".join(res["DisplayText"]) else: logger.info(f"{self.SLUG} 语音识别出错了: {res.text}") return "" class BaiduASR(AbstractASR): """ 百度的语音识别API. dev_pid: - 1936: 普通话远场 - 1536:普通话(支持简单的英文识别) - 1537:普通话(纯中文识别) - 1737:英语 - 1637:粤语 - 1837:四川话 要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号, 之后创建一个新应用, 然后在应用管理的"查看key"中获得 API Key 和 Secret Key 填入 config.xml 中. ... baidu_yuyin: appid: '9670645' api_key: 'qg4haN8b2bGvFtCbBGqhrmZy' secret_key: '585d4eccb50d306c401d7df138bb02e7' ... """ SLUG = "baidu-asr" def __init__(self, appid, api_key, secret_key, dev_pid=1936, **args): super(self.__class__, self).__init__() if dev_pid != 80001: self.client = AipSpeech(appid, api_key, secret_key) else: self.client = BaiduSpeech.baiduSpeech(api_key, secret_key, dev_pid) self.dev_pid = dev_pid @classmethod def get_config(cls): # Try to get baidu_yuyin config from config return config.get("baidu_yuyin", {}) def transcribe(self, fp): # 识别本地文件 pcm = utils.get_pcm_from_wav(fp) res = self.client.asr(pcm, "pcm", 16000, {"dev_pid": self.dev_pid}) if res["err_no"] == 0: logger.info(f"{self.SLUG} 语音识别到了:{res['result']}") return "".join(res["result"]) else: logger.info(f"{self.SLUG} 语音识别出错了: {res['err_msg']}") if res["err_msg"] == "request pv too much": logger.info(" 出现这个原因很可能是你的百度语音服务调用量超出限制,或未开通付费") return "" class TencentASR(AbstractASR): """ 腾讯的语音识别API. """ SLUG = "tencent-asr" def __init__(self, appid, secretid, secret_key, region="ap-guangzhou", **args): super(self.__class__, self).__init__() self.engine = TencentSpeech.tencentSpeech(secret_key, secretid) self.region = region @classmethod def get_config(cls): # Try to get tencent_yuyin config from config return config.get("tencent_yuyin", {}) def transcribe(self, fp): mp3_path = utils.convert_wav_to_mp3(fp) r = self.engine.ASR(mp3_path, "mp3", "1", self.region) utils.check_and_delete(mp3_path) res = json.loads(r) if "Response" in res and "Result" in res["Response"]: logger.info(f"{self.SLUG} 语音识别到了:{res['Response']['Result']}") return res["Response"]["Result"] else: logger.critical(f"{self.SLUG} 语音识别出错了: {res}", stack_info=True) return "" class XunfeiASR(AbstractASR): """ 科大讯飞的语音识别API. 外网ip查询:https://ip.51240.com/ """ SLUG = "xunfei-asr" def __init__(self, appid, api_key, api_secret, **args): super(self.__class__, self).__init__() self.appid = appid self.api_key = api_key self.api_secret = api_secret @classmethod def get_config(cls): # Try to get xunfei_yuyin config from config return config.get("xunfei_yuyin", {}) def transcribe(self, fp): return XunfeiSpeech.transcribe(fp, self.appid, self.api_key, self.api_secret) class AliASR(AbstractASR): """ 阿里的语音识别API. """ SLUG = "ali-asr" def __init__(self, appKey, token, **args): super(self.__class__, self).__init__() self.appKey, self.token = appKey, token @classmethod def get_config(cls): # Try to get ali_yuyin config from config return config.get("ali_yuyin", {}) def transcribe(self, fp): result = AliSpeech.asr(self.appKey, self.token, fp) if result: logger.info(f"{self.SLUG} 语音识别到了:{result}") return result else: logger.critical(f"{self.SLUG} 语音识别出错了", stack_info=True) return "" class WhisperASR(AbstractASR): """ OpenAI 的 whisper 语音识别API """ SLUG = "openai" def __init__(self, openai_api_key, **args): super(self.__class__, self).__init__() try: import openai self.openai = openai self.openai.api_key = openai_api_key print(openai_api_key) except Exception: logger.critical("OpenAI 初始化失败,请升级 Python 版本至 > 3.6") @classmethod def get_config(cls): return config.get("openai", {}) def transcribe(self, fp): if self.openai: try: with open(fp, "rb") as f: result = self.openai.Audio.transcribe("whisper-1", f) if result: logger.info(f"{self.SLUG} 语音识别到了:{result.text}") return result.text except Exception: logger.critical(f"{self.SLUG} 语音识别出错了", stack_info=True) return "" logger.critical(f"{self.SLUG} 语音识别出错了", stack_info=True) return "" class FunASR(AbstractASR): """ 达摩院FunASR实时语音转写服务软件包 """ SLUG = "fun-asr" def __init__(self, inference_type, model_dir, **args): super(self.__class__, self).__init__() self.engine = FunASREngine.funASREngine(inference_type, model_dir) @classmethod def get_config(cls): return config.get("fun_asr", {}) def transcribe(self, fp): result = self.engine(fp) if result: logger.info(f"{self.SLUG} 语音识别到了:{result}") return result else: logger.critical(f"{self.SLUG} 语音识别出错了", stack_info=True) return "" class VolcengineASR(AbstractASR): """ VolcengineASR 实时语音转写服务软件包 """ SLUG = "volcengine-asr" def __init__(self, **kargs): super(self.__class__, self).__init__() self.volcengine_asr = VolcengineSpeech.VolcengineASR(**kargs) @classmethod def get_config(cls): return config.get("volcengine-asr", {}) def transcribe(self, fp): result = self.volcengine_asr.execute(fp) if result: logger.info(f"{self.SLUG} 语音识别到了:{result}") return result else: logger.critical(f"{self.SLUG} 语音识别出错了", stack_info=True) return "" def get_engine_by_slug(slug=None): """ Returns: An ASR Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError("无效的 ASR slug '%s'", slug) selected_engines = list( filter( lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines(), ) ) if len(selected_engines) == 0: raise ValueError(f"错误:找不到名为 {slug} 的 ASR 引擎") else: if len(selected_engines) > 1: logger.warning(f"注意: 有多个 ASR 名称与指定的引擎名 {slug} 匹配") engine = selected_engines[0] logger.info(f"使用 {engine.SLUG} ASR 引擎") return engine.get_instance() def get_engines(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [ engine for engine in list(get_subclasses(AbstractASR)) if hasattr(engine, "SLUG") and engine.SLUG ] ================================================ FILE: robot/BCI.py ================================================ import importlib import multiprocessing from robot import config, logging from datetime import datetime, timedelta logger = logging.getLogger(__name__) class MuseBCI(object): def __init__(self, event): self._wakeup_event = event self.last_blink = datetime.now() - timedelta(days=1.5) self.last_jaw = datetime.now() - timedelta(days=1.5) def start(self): osc_process = multiprocessing.Process(target=self._start_osc) osc_process.start() def blink_handler(self, unused_addr, args, blink): if blink: logger.info("blink detected") self.last_blink = datetime.now() if (self.last_blink - self.last_jaw) <= timedelta(seconds=1): self._wakeup_event.set() def jaw_clench_handler(self, unused_addr, args, jaw): if jaw: logger.info("Jaw_Clench detected") self.last_jaw = datetime.now() if (self.last_jaw - self.last_blink) <= timedelta(seconds=1): self._wakeup_event.set() def _start_osc(self): if not importlib.util.find_spec("pythonosc"): logger.critical("错误:请先安装 python-osc !") return from pythonosc import dispatcher as dsp from pythonosc import osc_server dispatcher = dsp.Dispatcher() dispatcher.map("/muse/elements/blink", self.blink_handler, "EEG") dispatcher.map("/muse/elements/jaw_clench", self.jaw_clench_handler, "EEG") try: server = osc_server.ThreadingOSCUDPServer( ( config.get("/muse/ip", "127.0.0.1"), int(config.get("/muse/port", "5001")), ), dispatcher, ) logger.info(f"Muse serving on {server.server_address}") server.serve_forever() except Exception as e: logger.error(e, stack_info=True) ================================================ FILE: robot/Brain.py ================================================ # -*- coding: utf-8 -*- import re import traceback from robot import config from robot import logging from . import plugin_loader logger = logging.getLogger(__name__) class Brain(object): def __init__(self, conversation): """ 大脑模块,负责处理技能的匹配和响应 参数: conversation -- 管理对话 """ self.conversation = conversation self.plugins = plugin_loader.get_plugins(self.conversation) self.handling = False def match(self, patterns, text): for pattern in patterns: if re.match(pattern, text): return True return False def isValid(self, plugin, text, parsed): patterns = config.get(f"/{plugin.SLUG}/patterns", []) if len(patterns) > 0: return plugin.isValid(text, parsed) or self.match(patterns, text) else: return plugin.isValid(text, parsed) def isValidImmersive(self, plugin, text, parsed): patterns = config.get(f"/{plugin.SLUG}/patterns", []) if len(patterns) > 0: return plugin.isValidImmersive(text, parsed) or self.match(patterns, text) else: return plugin.isValidImmersive(text, parsed) def isImmersive(self, plugin, text, parsed): return ( self.conversation.getImmersiveMode() == plugin.SLUG and self.isValidImmersive(plugin, text, parsed) ) def printPlugins(self): plugin_list = [] for plugin in self.plugins: plugin_list.append(plugin.SLUG) logger.info(f"已激活插件:{plugin_list}") def query(self, text, parsed): """ query 模块 Arguments: text -- 原文本 parsed -- ULU解析出来的结果 """ for plugin in self.plugins: if not self.isValid(plugin, text, parsed) and not self.isImmersive( plugin, text, parsed ): continue logger.info(f"'{text}' 命中技能 {plugin.SLUG}") self.conversation.matchPlugin = plugin.SLUG if plugin.IS_IMMERSIVE: self.conversation.setImmersiveMode(plugin.SLUG) continueHandle = False try: self.handling = True continueHandle = plugin.handle(text, parsed) self.handling = False except Exception as e: logger.critical(f"Failed to execute plugin: {e}", stack_info=True) traceback.print_exc() reply = f"抱歉,插件{plugin.SLUG}出故障了,晚点再试试吧" self.conversation.say(reply, plugin=plugin.SLUG) else: logger.debug( "Handling of phrase '%s' by " + "plugin '%s' completed", text, plugin.SLUG, ) finally: if not continueHandle: return True logger.debug(f"No plugin was able to handle phrase {text} ") return False def restore(self): """恢复某个技能的处理""" if not self.conversation.immersiveMode: return for plugin in self.plugins: if plugin.SLUG == self.conversation.immersiveMode and plugin.restore: logger.warning(f"{plugin.SLUG}: restore") plugin.restore() def pause(self): """暂停某个技能的处理""" if not self.conversation.immersiveMode: return for plugin in self.plugins: if plugin.SLUG == self.conversation.immersiveMode and plugin.pause: plugin.pause() def understand(self, fp): if self.conversation and self.conversation.asr: return self.conversation.asr.transcribe(fp) return None def say(self, msg, cache=False): if self.conversation and self.conversation.tts: self.conversation.tts.say(msg, cache) ================================================ FILE: robot/ConfigMonitor.py ================================================ # -*- coding: utf-8 -*- import os from robot import config, utils, logging from watchdog.events import FileSystemEventHandler logger = logging.getLogger(__name__) class ConfigMonitor(FileSystemEventHandler): def __init__(self, conversation): FileSystemEventHandler.__init__(self) self._conversation = conversation # 文件修改 def on_modified(self, event): if event.is_directory: return filename = event.src_path extension = os.path.splitext(filename)[-1].lower() if extension in (".yaml", ".yml"): if utils.validyaml(filename): logger.info(f"检测到文件 {filename} 发生变更") config.reload() self._conversation.reInit() ================================================ FILE: robot/Conversation.py ================================================ # -*- coding: utf-8 -*- import time import uuid import cProfile import pstats import io import re import os import threading import traceback from concurrent.futures import ThreadPoolExecutor, as_completed from snowboy import snowboydecoder from robot.LifeCycleHandler import LifeCycleHandler from robot.Brain import Brain from robot.Scheduler import Scheduler from robot.sdk import History from robot import ( AI, ASR, config, constants, logging, NLU, Player, statistic, TTS, utils, ) logger = logging.getLogger(__name__) class Conversation(object): def __init__(self, profiling=False): self.brain, self.asr, self.ai, self.tts, self.nlu = None, None, None, None, None self.reInit() self.scheduler = Scheduler(self) # 历史会话消息 self.history = History.History() # 沉浸模式,处于这个模式下,被打断后将自动恢复这个技能 self.matchPlugin = None self.immersiveMode = None self.isRecording = False self.profiling = profiling self.onSay = None self.onStream = None self.hasPardon = False self.player = Player.SoxPlayer() self.lifeCycleHandler = LifeCycleHandler(self) self.tts_count = 0 self.tts_index = 0 self.tts_lock = threading.Lock() self.play_lock = threading.Lock() def _lastCompleted(self, index, onCompleted): # logger.debug(f"{index}, {self.tts_index}, {self.tts_count}") if index >= self.tts_count - 1: # logger.debug(f"执行onCompleted") onCompleted and onCompleted() def _ttsAction(self, msg, cache, index, onCompleted=None): if msg: voice = "" if utils.getCache(msg): logger.info(f"第{index}段TTS命中缓存,播放缓存语音") voice = utils.getCache(msg) while index != self.tts_index: # 阻塞直到轮到这个音频播放 continue with self.play_lock: self.player.play( voice, not cache, onCompleted=lambda: self._lastCompleted(index, onCompleted), ) self.tts_index += 1 return voice else: try: voice = self.tts.get_speech(msg) logger.info(f"第{index}段TTS合成成功。msg: {msg}") while index != self.tts_index: # 阻塞直到轮到这个音频播放 continue with self.play_lock: logger.info(f"即将播放第{index}段TTS。msg: {msg}") self.player.play( voice, not cache, onCompleted=lambda: self._lastCompleted(index, onCompleted), ) self.tts_index += 1 return voice except Exception as e: logger.error(f"语音合成失败:{e}", stack_info=True) self.tts_index += 1 traceback.print_exc() return None def getHistory(self): return self.history def interrupt(self): if self.player and self.player.is_playing(): self.player.stop() if self.immersiveMode: self.brain.pause() def reInit(self): """重新初始化""" try: self.asr = ASR.get_engine_by_slug(config.get("asr_engine", "tencent-asr")) self.ai = AI.get_robot_by_slug(config.get("robot", "tuling")) self.tts = TTS.get_engine_by_slug(config.get("tts_engine", "baidu-tts")) self.nlu = NLU.get_engine_by_slug(config.get("nlu_engine", "unit")) self.player = Player.SoxPlayer() self.brain = Brain(self) self.brain.printPlugins() except Exception as e: logger.critical(f"对话初始化失败:{e}", stack_info=True) def checkRestore(self): if self.immersiveMode: logger.info("处于沉浸模式,恢复技能") self.lifeCycleHandler.onRestore() self.brain.restore() def _InGossip(self, query): return self.immersiveMode in ["Gossip"] and not "闲聊" in query def doResponse(self, query, UUID="", onSay=None, onStream=None): """ 响应指令 :param query: 指令 :UUID: 指令的UUID :onSay: 朗读时的回调 :onStream: 流式输出时的回调 """ statistic.report(1) self.interrupt() self.appendHistory(0, query, UUID) if onSay: self.onSay = onSay if onStream: self.onStream = onStream if query.strip() == "": self.pardon() return lastImmersiveMode = self.immersiveMode parsed = self.doParse(query) if self._InGossip(query) or not self.brain.query(query, parsed): # 进入闲聊 if self.nlu.hasIntent(parsed, "PAUSE") or "闭嘴" in query: # 停止说话 self.player.stop() else: # 没命中技能,使用机器人回复 if self.ai.SLUG == "openai": stream = self.ai.stream_chat(query) self.stream_say(stream, True, onCompleted=self.checkRestore) else: msg = self.ai.chat(query, parsed) self.say(msg, True, onCompleted=self.checkRestore) else: # 命中技能 if lastImmersiveMode and lastImmersiveMode != self.matchPlugin: if self.player: if self.player.is_playing(): logger.debug("等说完再checkRestore") self.player.appendOnCompleted(lambda: self.checkRestore()) else: logger.debug("checkRestore") self.checkRestore() def doParse(self, query): args = { "service_id": config.get("/unit/service_id", "S13442"), "api_key": config.get("/unit/api_key", "w5v7gUV3iPGsGntcM84PtOOM"), "secret_key": config.get( "/unit/secret_key", "KffXwW6E1alcGplcabcNs63Li6GvvnfL" ), } return self.nlu.parse(query, **args) def setImmersiveMode(self, slug): self.immersiveMode = slug def getImmersiveMode(self): return self.immersiveMode def converse(self, fp, callback=None): """核心对话逻辑""" logger.info("结束录音") self.lifeCycleHandler.onThink() self.isRecording = False if self.profiling: logger.info("性能调试已打开") pr = cProfile.Profile() pr.enable() self.doConverse(fp, callback) pr.disable() s = io.StringIO() sortby = "cumulative" ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print(s.getvalue()) else: self.doConverse(fp, callback) def doConverse(self, fp, callback=None, onSay=None, onStream=None): self.interrupt() try: query = self.asr.transcribe(fp) except Exception as e: logger.critical(f"ASR识别失败:{e}", stack_info=True) traceback.print_exc() utils.check_and_delete(fp) try: self.doResponse(query, callback, onSay, onStream) except Exception as e: logger.critical(f"回复失败:{e}", stack_info=True) traceback.print_exc() utils.clean() def appendHistory(self, t, text, UUID="", plugin=""): """将会话历史加进历史记录""" if t in (0, 1) and text: if text.endswith(",") or text.endswith(","): text = text[:-1] if UUID == "" or UUID == None or UUID == "null": UUID = str(uuid.uuid1()) # 将图片处理成HTML pattern = r"https?://.+\.(?:png|jpg|jpeg|bmp|gif|JPG|PNG|JPEG|BMP|GIF)" url_pattern = r"^https?://.+" imgs = re.findall(pattern, text) for img in imgs: text = text.replace( img, f'', ) urls = re.findall(url_pattern, text) for url in urls: text = text.replace(url, f'{url}') self.lifeCycleHandler.onResponse(t, text) self.history.add_message( { "type": t, "text": text, "time": time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime(time.time()) ), "uuid": UUID, "plugin": plugin, } ) def _onCompleted(self, msg): pass def pardon(self): if not self.hasPardon: self.say("抱歉,刚刚没听清,能再说一遍吗?", cache=True) self.hasPardon = True else: self.say("没听清呢") self.hasPardon = False def _tts_line(self, line, cache, index=0, onCompleted=None): """ 对单行字符串进行 TTS 并返回合成后的音频 :param line: 字符串 :param cache: 是否缓存 TTS 结果 :param index: 合成序号 :param onCompleted: 播放完成的操作 """ line = line.strip() pattern = r"http[s]?://.+" if re.match(pattern, line): logger.info("内容包含URL,屏蔽后续内容") return None line.replace("- ", "") if line: result = self._ttsAction(line, cache, index, onCompleted) return result return None def _tts(self, lines, cache, onCompleted=None): """ 对字符串进行 TTS 并返回合成后的音频 :param lines: 字符串列表 :param cache: 是否缓存 TTS 结果 """ audios = [] pattern = r"http[s]?://.+" logger.info("_tts") with self.tts_lock: with ThreadPoolExecutor(max_workers=config.get("tts_parallel", 5)) as pool: all_task = [] index = 0 for line in lines: if re.match(pattern, line): logger.info("内容包含URL,屏蔽后续内容") self.tts_count -= 1 continue if line: task = pool.submit( self._ttsAction, line.strip(), cache, index, onCompleted ) index += 1 all_task.append(task) else: self.tts_count -= 1 for future in as_completed(all_task): audio = future.result() if audio: audios.append(audio) return audios def _after_play(self, msg, audios, plugin=""): cached_audios = [ f"http://{config.get('/server/host')}:{config.get('/server/port')}/audio/{os.path.basename(voice)}" for voice in audios ] if self.onSay: logger.info(f"onSay: {msg}, {cached_audios}") self.onSay(msg, cached_audios, plugin=plugin) self.onSay = None utils.lruCache() # 清理缓存 def stream_say(self, stream, cache=False, onCompleted=None): """ 从流中逐字逐句生成语音 :param stream: 文字流,可迭代对象 :param cache: 是否缓存 TTS 结果 :param onCompleted: 声音播报完成后的回调 """ lines = [] line = "" resp_uuid = str(uuid.uuid1()) audios = [] if onCompleted is None: onCompleted = lambda: self._onCompleted(msg) self.tts_index = 0 self.tts_count = 0 index = 0 skip_tts = False for data in stream(): if self.onStream: self.onStream(data, resp_uuid) line += data if any(char in data for char in utils.getPunctuations()): if "```" in line.strip(): skip_tts = True if not skip_tts: audio = self._tts_line(line.strip(), cache, index, onCompleted) if audio: self.tts_count += 1 audios.append(audio) index += 1 else: logger.info(f"{line} 属于代码段,跳过朗读") lines.append(line) line = "" if line.strip(): lines.append(line) if skip_tts: self._tts_line("内容包含代码,我就不念了", True, index, onCompleted) msg = "".join(lines) self.appendHistory(1, msg, UUID=resp_uuid, plugin="") self._after_play(msg, audios, "") def say(self, msg, cache=False, plugin="", onCompleted=None, append_history=True): """ 说一句话 :param msg: 内容 :param cache: 是否缓存这句话的音频 :param plugin: 来自哪个插件的消息(将带上插件的说明) :param onCompleted: 完成的回调 :param append_history: 是否要追加到聊天记录 """ if append_history: self.appendHistory(1, msg, plugin=plugin) msg = utils.stripPunctuation(msg).strip() if not msg: return logger.info(f"即将朗读语音:{msg}") lines = re.split("。|!|?|\!|\?|\n", msg) if onCompleted is None: onCompleted = lambda: self._onCompleted(msg) self.tts_index = 0 self.tts_count = len(lines) logger.debug(f"tts_count: {self.tts_count}") audios = self._tts(lines, cache, onCompleted) self._after_play(msg, audios, plugin) def activeListen(self, silent=False): """ 主动问一个问题(适用于多轮对话) :param silent: 是否不触发唤醒表现(主要用于极客模式) :param """ if self.immersiveMode: self.player.stop() elif self.player.is_playing(): self.player.join() # 确保所有音频都播完 logger.info("进入主动聆听...") try: if not silent: self.lifeCycleHandler.onWakeup() listener = snowboydecoder.ActiveListener( [constants.getHotwordModel(config.get("hotword", "wukong.pmdl"))] ) voice = listener.listen( silent_count_threshold=config.get("silent_threshold", 15), recording_timeout=config.get("recording_timeout", 5) * 4, ) if not silent: self.lifeCycleHandler.onThink() if voice: query = self.asr.transcribe(voice) utils.check_and_delete(voice) return query return "" except Exception as e: logger.error(f"主动聆听失败:{e}", stack_info=True) traceback.print_exc() return "" def play(self, src, delete=False, onCompleted=None, volume=1): """播放一个音频""" if self.player: self.interrupt() self.player = Player.SoxPlayer() self.player.play(src, delete=delete, onCompleted=onCompleted) ================================================ FILE: robot/LifeCycleHandler.py ================================================ import logging import multiprocessing import os import time import pickle import time import _thread as thread from watchdog.observers import Observer from robot import config, constants, statistic, Player from robot.ConfigMonitor import ConfigMonitor from robot.sdk import LED logger = logging.getLogger(__name__) LOCAL_REMINDER = os.path.join(constants.TEMP_PATH, "reminder.pkl") def singleton(cls): _instance = {} def inner(conversation): if cls not in _instance: _instance[cls] = cls(conversation) return _instance[cls] return inner """ 抽象出来的生命周期, 方便在这里针对 wukong 的各个状态做定制 """ @singleton class LifeCycleHandler(object): def __init__(self, conversation): self._observer = Observer() self._unihiker = None self._wakeup = None self._conversation = conversation def onInit(self): """ wukong-robot 初始化 """ config.init() statistic.report(0) # 初始化配置监听器 config_event_handler = ConfigMonitor(self._conversation) self._observer.schedule(config_event_handler, constants.CONFIG_PATH, False) self._observer.schedule(config_event_handler, constants.DATA_PATH, False) self._observer.start() # 加载历史提醒 self._read_reminders() # 行空板 self._init_unihiker() # LED 灯 self._init_LED() # Muse 头环 self._init_muse() def _read_reminders(self): logger.info("重新加载提醒信息") if os.path.exists(LOCAL_REMINDER): with open(LOCAL_REMINDER, "rb") as f: jobs = pickle.load(f) for job in jobs: if "repeat" in job.remind_time or int(time.time()) < int( job.job_id ): logger.info(f"加入提醒: {job.describe}, job_id: {job.job_id}") if not (self._conversation.scheduler.has_job(job.job_id)): self._conversation.scheduler.add_job( job.remind_time, job.original_time, job.content, lambda: self.alarm( job.remind_time, job.content, job.job_id ), job_id=job.job_id, ) def _init_unihiker(self): global unihiker if config.get("/unihiker/enable", False): try: from robot.sdk.Unihiker import Unihiker self._unihiker = Unihiker() thread.start_new_thread(self._unihiker_shake_event, ()) except ImportError: logger.error("错误:请确保当前硬件环境为行空板", stack_info=True) def _init_LED(self): if config.get("/LED/enable", False) and config.get("/LED/type") == "aiy": thread.start_new_thread(self._aiy_button_event, ()) def _init_muse(self): if config.get("/muse/enable", False): try: from robot import BCI self._wakeup = multiprocessing.Event() bci = BCI.MuseBCI(self._wakeup) bci.start() thread.start_new_thread(self._muse_loop_event, ()) except ImportError: logger.error("错误:请确保当前硬件搭配了Muse头环并安装了相关驱动", stack_info=True) def _unihiker_shake_event(self): """ 行空板摇一摇的监听逻辑 """ while True: from pinpong.extension.unihiker import accelerometer if accelerometer.get_strength() >= 1.5: logger.info("行空板摇一摇触发唤醒") self._conversation.interrupt() query = self._conversation.activeListen() self._conversation.doResponse(query) time.sleep(0.1) def _aiy_button_event(self): """ Google AIY VoiceKit 的监听逻辑 """ try: from aiy.board import Board except ImportError: logger.error("错误:请确保当前硬件环境为Google AIY VoiceKit并正确安装了驱动", stack_info=True) return with Board() as board: while True: board.button.wait_for_press() logger.info("Google AIY Voicekit 触发唤醒") self._conversation.interrupt() query = self._conversation.activeListen() self._conversation.doResponse(query) def _muse_loop_event(self): """ Muse 头环的监听逻辑 """ while True: self._wakeup.wait() self._conversation.interrupt() logger.info("Muse 头环触发唤醒") query = self._conversation.activeListen() self._conversation.doResponse(query) self._wakeup.clear() def _beep_hi(self, onCompleted=None): Player.play(constants.getData("beep_hi.wav"), onCompleted) def _beep_lo(self): Player.play(constants.getData("beep_lo.wav")) def onWakeup(self, onCompleted=None): """ 唤醒并进入录音的状态 """ logger.info("onWakeup") self._beep_hi(onCompleted=onCompleted) if config.get("/LED/enable", False): LED.wakeup() self._unihiker and self._unihiker.record(1, "我正在聆听...") self._unihiker and self._unihiker.wakeup() def onThink(self): """ 录音结束并进入思考的状态 """ logger.info("onThink") self._beep_lo() self._unihiker and self._unihiker.think() self._unihiker and self._unihiker.record(1, "我正在思考...") if config.get("/LED/enable", False): LED.think() def onResponse(self, t=1, text=""): """ 思考完成并播放结果的状态 """ if t == 1: text = text[:60] + "..." if len(text) >= 60 else text else: text = text[:9] + "..." if len(text) >= 9 else text self._unihiker and self._unihiker.record(t, text) if config.get("/LED/enable", False): LED.off() def onRestore(self): """ 恢复沉浸式技能的状态 """ logger.info("onRestore") def onKilled(self): logger.info("onKill") self._observer.stop() ================================================ FILE: robot/NLU.py ================================================ # -*- coding: utf-8 -*- from .sdk import unit from robot import logging from abc import ABCMeta, abstractmethod logger = logging.getLogger(__name__) class AbstractNLU(object): """ Generic parent class for all NLU engines """ __metaclass__ = ABCMeta @classmethod def get_config(cls): return {} @classmethod def get_instance(cls): profile = cls.get_config() instance = cls(**profile) return instance @abstractmethod def parse(self, query, **args): """ 进行 NLU 解析 :param query: 用户的指令字符串 :param **args: 可选的参数 """ return None @abstractmethod def getIntent(self, parsed): """ 提取意图 :param parsed: 解析结果 :returns: 意图数组 """ return None @abstractmethod def hasIntent(self, parsed, intent): """ 判断是否包含某个意图 :param parsed: 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含 """ return False @abstractmethod def getSlots(self, parsed, intent): """ 提取某个意图的所有词槽 :param parsed: 解析结果 :param intent: 意图的名称 :returns: 词槽列表。你可以通过 name 属性筛选词槽, 再通过 normalized_word 属性取出相应的值 """ return None @abstractmethod def getSlotWords(self, parsed, intent, name): """ 找出命中某个词槽的内容 :param parsed: 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ return None @abstractmethod def getSay(self, parsed, intent): """ 提取回复文本 :param parsed: 解析结果 :param intent: 意图的名称 :returns: 回复文本 """ return "" class UnitNLU(AbstractNLU): """ 百度UNIT的NLU API. """ SLUG = "unit" def __init__(self): super(self.__class__, self).__init__() @classmethod def get_config(cls): """ 百度UNIT的配置 无需配置,所以返回 {} """ return {} def parse(self, query, **args): """ 使用百度 UNIT 进行 NLU 解析 :param query: 用户的指令字符串 :param **args: UNIT 的相关参数 - service_id: UNIT 的 service_id - api_key: UNIT apk_key - secret_key: UNIT secret_key :returns: UNIT 解析结果。如果解析失败,返回 None """ if ( "service_id" not in args or "api_key" not in args or "secret_key" not in args ): logger.critical(f"{self.SLUG} NLU 失败:参数错误!", stack_info=True) return None return unit.getUnit( query, args["service_id"], args["api_key"], args["secret_key"] ) def getIntent(self, parsed): """ 提取意图 :param parsed: 解析结果 :returns: 意图数组 """ return unit.getIntent(parsed) def hasIntent(self, parsed, intent): """ 判断是否包含某个意图 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含 """ return unit.hasIntent(parsed, intent) def getSlots(self, parsed, intent): """ 提取某个意图的所有词槽 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: 词槽列表。你可以通过 name 属性筛选词槽, 再通过 normalized_word 属性取出相应的值 """ return unit.getSlots(parsed, intent) def getSlotWords(self, parsed, intent, name): """ 找出命中某个词槽的内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ return unit.getSlotWords(parsed, intent, name) def getSlotOriginalWords(self, parsed, intent, name): """ 找出命中某个词槽的原始内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ return unit.getSlotOriginalWords(parsed, intent, name) def getSay(self, parsed, intent): """ 提取 UNIT 的回复文本 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: UNIT 的回复文本 """ return unit.getSay(parsed, intent) def get_engine_by_slug(slug=None): """ Returns: An NLU Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError("无效的 NLU slug '%s'", slug) selected_engines = list( filter( lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines(), ) ) if len(selected_engines) == 0: raise ValueError(f"错误:找不到名为 {slug} 的 NLU 引擎") else: if len(selected_engines) > 1: logger.warning(f"注意: 有多个 NLU 名称与指定的引擎名 {slug} 匹配") engine = selected_engines[0] logger.info(f"使用 {engine.SLUG} NLU 引擎") return engine.get_instance() def get_engines(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [ engine for engine in list(get_subclasses(AbstractNLU)) if hasattr(engine, "SLUG") and engine.SLUG ] ================================================ FILE: robot/Player.py ================================================ # -*- coding: utf-8 -*- import asyncio import subprocess import os import platform import queue import signal import threading from robot import logging from ctypes import CFUNCTYPE, c_char_p, c_int, cdll from contextlib import contextmanager from . import utils logger = logging.getLogger(__name__) def py_error_handler(filename, line, function, err, fmt): pass ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p) c_error_handler = ERROR_HANDLER_FUNC(py_error_handler) @contextmanager def no_alsa_error(): try: asound = cdll.LoadLibrary("libasound.so") asound.snd_lib_error_set_handler(c_error_handler) yield asound.snd_lib_error_set_handler(None) except: yield pass def play(fname, onCompleted=None): player = getPlayerByFileName(fname) player.play(fname, onCompleted=onCompleted) def getPlayerByFileName(fname): foo, ext = os.path.splitext(fname) if ext in [".mp3", ".wav"]: return SoxPlayer() class AbstractPlayer(object): def __init__(self, **kwargs): super(AbstractPlayer, self).__init__() def play(self): pass def play_block(self): pass def stop(self): pass def is_playing(self): return False def join(self): pass class SoxPlayer(AbstractPlayer): SLUG = "SoxPlayer" def __init__(self, **kwargs): super(SoxPlayer, self).__init__(**kwargs) self.playing = False self.proc = None self.delete = False self.onCompleteds = [] # 创建一个锁用于保证同一时间只有一个音频在播放 self.play_lock = threading.Lock() self.play_queue = queue.Queue() # 播放队列 self.consumer_thread = threading.Thread(target=self.playLoop) self.consumer_thread.start() self.loop = asyncio.new_event_loop() # 创建事件循环 self.thread_loop = threading.Thread(target=self.loop.run_forever) self.thread_loop.start() def executeOnCompleted(self, res, onCompleted): # 全部播放完成,播放统一的 onCompleted() res and onCompleted and onCompleted() if self.play_queue.empty(): for onCompleted in self.onCompleteds: onCompleted and onCompleted() def playLoop(self): while True: (src, onCompleted) = self.play_queue.get() if src: with self.play_lock: logger.info(f"开始播放音频:{src}") self.src = src res = self.doPlay(src) self.play_queue.task_done() # 将 onCompleted() 方法的调用放到事件循环的线程中执行 self.loop.call_soon_threadsafe( self.executeOnCompleted, res, onCompleted ) def doPlay(self, src): system = platform.system() if system == "Darwin": cmd = ["afplay", str(src)] else: cmd = ["play", str(src)] logger.debug("Executing %s", " ".join(cmd)) self.proc = subprocess.Popen( cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) self.playing = True self.proc.wait() self.playing = False if self.delete: utils.check_and_delete(src) logger.info(f"播放完成:{src}") return self.proc and self.proc.returncode == 0 def play(self, src, delete=False, onCompleted=None): if src and (os.path.exists(src) or src.startswith("http")): self.delete = delete self.play_queue.put((src, onCompleted)) else: logger.critical(f"path not exists: {src}", stack_info=True) def preappendCompleted(self, onCompleted): onCompleted and self.onCompleteds.insert(0, onCompleted) def appendOnCompleted(self, onCompleted): onCompleted and self.onCompleteds.append(onCompleted) def play_block(self): self.run() def stop(self): if self.proc: self.onCompleteds = [] self.proc.terminate() self.proc.kill() self.proc = None self.playing = False self._clear_queue() if self.delete: utils.check_and_delete(self.src) def is_playing(self): return self.playing or not self.play_queue.empty() def join(self): self.play_queue.join() def _clear_queue(self): with self.play_queue.mutex: self.play_queue.queue.clear() class MusicPlayer(SoxPlayer): """ 给音乐播放器插件使用的, 在 SOXPlayer 的基础上增加了列表的支持, 并支持暂停和恢复播放 """ SLUG = "MusicPlayer" def __init__(self, playlist, plugin, **kwargs): super(MusicPlayer, self).__init__(**kwargs) self.playlist = playlist self.plugin = plugin self.idx = 0 self.pausing = False def update_playlist(self, playlist): super().stop() self.playlist = playlist self.idx = 0 self.play() def play(self): logger.debug("MusicPlayer play") path = self.playlist[self.idx] super().stop() super().play(path, False, self.next) def next(self): logger.debug("MusicPlayer next") super().stop() self.idx = (self.idx + 1) % len(self.playlist) self.play() def prev(self): logger.debug("MusicPlayer prev") super().stop() self.idx = (self.idx - 1) % len(self.playlist) self.play() def pause(self): logger.debug("MusicPlayer pause") self.pausing = True if self.proc: os.kill(self.proc.pid, signal.SIGSTOP) def stop(self): if self.proc: logger.debug(f"MusicPlayer stop {self.proc.pid}") self.onCompleteds = [] os.kill(self.proc.pid, signal.SIGSTOP) self.proc.terminate() self.proc.kill() self.proc = None def resume(self): logger.debug("MusicPlayer resume") self.pausing = False self.onCompleteds = [self.next] if self.proc: os.kill(self.proc.pid, signal.SIGCONT) def is_playing(self): return self.playing def is_pausing(self): return self.pausing def turnUp(self): system = platform.system() if system == "Darwin": res = subprocess.run( ["osascript", "-e", "output volume of (get volume settings)"], shell=False, capture_output=True, universal_newlines=True, ) volume = int(res.stdout.strip()) volume += 20 if volume >= 100: volume = 100 self.plugin.say("音量已经最大啦") subprocess.run(["osascript", "-e", f"set volume output volume {volume}"]) elif system == "Linux": res = subprocess.run( ["amixer sget Master | grep 'Mono:' | awk -F'[][]' '{ print $2 }'"], shell=True, capture_output=True, universal_newlines=True, ) if res.stdout != "" and res.stdout.strip().endswith("%"): volume = int(res.stdout.strip().replace("%", "")) volume += 20 if volume >= 100: volume = 100 self.plugin.say("音量已经最大啦") subprocess.run(["amixer", "set", "Master", f"{volume}%"]) else: subprocess.run(["amixer", "set", "Master", "20%+"]) else: self.plugin.say("当前系统不支持调节音量") self.resume() def turnDown(self): system = platform.system() if system == "Darwin": res = subprocess.run( ["osascript", "-e", "output volume of (get volume settings)"], shell=False, capture_output=True, universal_newlines=True, ) volume = int(res.stdout.strip()) volume -= 20 if volume <= 20: volume = 20 self.plugin.say("音量已经很小啦") subprocess.run(["osascript", "-e", f"set volume output volume {volume}"]) elif system == "Linux": res = subprocess.run( ["amixer sget Master | grep 'Mono:' | awk -F'[][]' '{ print $2 }'"], shell=True, capture_output=True, universal_newlines=True, ) if res.stdout != "" and res.stdout.endswith("%"): volume = int(res.stdout.replace("%", "").strip()) volume -= 20 if volume <= 20: volume = 20 self.plugin.say("音量已经最小啦") subprocess.run(["amixer", "set", "Master", f"{volume}%"]) else: subprocess.run(["amixer", "set", "Master", "20%-"]) else: self.plugin.say("当前系统不支持调节音量") self.resume() ================================================ FILE: robot/Scheduler.py ================================================ # wukong-robot 的提醒机制 # 基于 BackgroundScheduler 做二次封装 import datetime from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from robot import logging, utils, constants logger = logging.getLogger(__name__) class Job(object): """ 任务类 """ def __init__(self, remind_time, original_time, content, describe, job_id): self.remind_time = remind_time self.original_time = original_time self.content = utils.stripPunctuation(content) self.describe = describe self.job_id = job_id class Scheduler(object): """ wukong-robot 的提醒器, 用于实现日程提醒功能 """ def __init__(self, con): self._jobs = [] self._sched = BackgroundScheduler() self._sched.start() self.con = con def _get_datetime(self, norm_str): date, time = norm_str.split("|") year, mon, day = date.split("-") hour, min, sec = time.split(":") return datetime.datetime( int(year), int(mon), int(day), int(hour), int(min), int(sec) ) def _add_interval_job(self, alarm, job_id, norm_str): interval, count = norm_str.split("-")[1:] interval_type = interval + "s" self._sched.add_job( alarm, "interval", **{interval_type: int(count)}, id=job_id, misfire_grace_time=60, ) return True def _parse_cron_rule(self, rule_str): # 解析规则字符串 rule_type, rule_time = rule_str.split("|") rule_time_parts = rule_time.split(" ") hour, minute, second = 0, 0, 0 if len(rule_time_parts) > 1: hour, minute, second = map(int, rule_time_parts[1].split(":")) else: hour, minute, second = map(int, rule_time_parts[0].split(":")) if rule_type.startswith("repeat-day"): # 每天执行 return CronTrigger(second=second, minute=minute, hour=hour) elif rule_type.startswith("repeat-week"): # 每周执行 day_of_week = rule_time_parts[0].split("-")[1] return CronTrigger( second=second, minute=minute, hour=hour, day_of_week=day_of_week ) elif rule_type.startswith("repeat-month"): # 每月执行 day_of_month = rule_time_parts[0].split("-")[1] return CronTrigger( second=second, minute=minute, hour=hour, day=day_of_month ) elif rule_type.startswith("repeat-year"): # 每年执行 month, day = rule_time_parts[0].split("-") return CronTrigger( second=second, minute=minute, hour=hour, day=day, month=month ) else: return None def _add_cron_job(self, alarm, job_id, norm_str): # 解析规则字符串 cron_trigger = self._parse_cron_rule(norm_str) if cron_trigger: self._sched.add_job(alarm, trigger=cron_trigger, misfire_grace_time=60) return True return False def get_jobs(self): """ 检查当前有多少提醒 """ return self._jobs def set_jobs(self, jobs): self._jobs = jobs def add_job(self, remind_time, original_time, content, onAlarm, job_id=None): """ 添加提醒 :param remind_time: 提醒时间 :param content: 提醒事项 :param onAlarm: 提醒的时候触发的响应 :returns: 添加成功:添加的提醒;添加失败:None """ if not job_id: job_id = utils.getTimemStap() job = Job( remind_time=remind_time, original_time=original_time, content=content, describe=f"时间:{remind_time},事项:{content}" if "repeat" not in remind_time else f"时间:{original_time}, 事项:{content}", job_id=job_id, ) success = False if "repeat" in remind_time: if "|" in remind_time: # cron 任务 success = self._add_cron_job(onAlarm, job_id, remind_time) else: # interval 任务 success = self._add_interval_job(onAlarm, job_id, remind_time) else: success = self._sched.add_job( onAlarm, "date", run_date=self._get_datetime(remind_time), id=job_id, misfire_grace_time=60, ) if success: self._jobs.append(job) return job return None def has_job(self, job_id): return self._sched.get_job(job_id) def del_job_by_id(self, job_id): """ 删除指定 job_id 的提醒 :param job_id: 提醒id """ try: if self._sched.get_job(job_id=job_id): self._sched.remove_job(job_id=job_id) self._jobs = [job for job in self._jobs if job.job_id != job_id] except Exception as e: logger.warning(f"id {job_id} 的提醒已被删除。删除失败。") ================================================ FILE: robot/TTS.py ================================================ # -*- coding: utf -8-*- import os import base64 import tempfile import pypinyin import subprocess import uuid import asyncio import edge_tts import nest_asyncio from aip import AipSpeech from . import utils, config, constants from robot import logging from pathlib import Path from pypinyin import lazy_pinyin from pydub import AudioSegment from abc import ABCMeta, abstractmethod from .sdk import TencentSpeech, AliSpeech, XunfeiSpeech, atc, VITSClient, VolcengineSpeech import requests from xml.etree import ElementTree logger = logging.getLogger(__name__) nest_asyncio.apply() class AbstractTTS(object): """ Generic parent class for all TTS engines """ __metaclass__ = ABCMeta @classmethod def get_config(cls): return {} @classmethod def get_instance(cls): profile = cls.get_config() instance = cls(**profile) return instance @abstractmethod def get_speech(self, phrase): pass class HanTTS(AbstractTTS): """ HanTTS:https://github.com/junzew/HanTTS 要使用本模块, 需要先从 SourceForge 下载语音库 syllables.zip : https://sourceforge.net/projects/hantts/files/?source=navbar 并解压到 ~/.wukong 目录下 """ SLUG = "han-tts" CHUNK = 1024 punctuation = [ ",", "。", "?", "!", "“", "”", ";", ":", "(", ")", ":", ";", ",", ".", "?", "!", '"', "'", "(", ")", ] def __init__(self, voice="syllables", **args): super(self.__class__, self).__init__() self.voice = voice @classmethod def get_config(cls): # Try to get han-tts config from config return config.get("han-tts", {}) def get_speech(self, phrase): """ Synthesize .wav from text """ src = os.path.join(constants.CONFIG_PATH, self.voice) text = phrase def preprocess(syllables): temp = [] for syllable in syllables: for p in self.punctuation: syllable = syllable.replace(p, "") if syllable.isdigit(): syllable = atc.num2chinese(syllable) new_sounds = lazy_pinyin(syllable, style=pypinyin.TONE3) for e in new_sounds: temp.append(e) else: temp.append(syllable) return temp if not os.path.exists(src): logger.error( f"{self.SLUG} 合成失败: 请先下载 syllables.zip (https://sourceforge.net/projects/hantts/files/?source=navbar) 并解压到 ~/.wukong 目录下", stack_info=True, ) return None logger.debug(f"{self.SLUG} 合成中...") delay = 0 increment = 355 # milliseconds pause = 500 # pause for punctuation syllables = lazy_pinyin(text, style=pypinyin.TONE3) syllables = preprocess(syllables) # initialize to be complete silence, each character takes up ~500ms result = AudioSegment.silent(duration=500 * len(text)) for syllable in syllables: path = os.path.join(src, syllable + ".wav") sound_file = Path(path) # insert 500 ms silence for punctuation marks if syllable in self.punctuation: short_silence = AudioSegment.silent(duration=pause) result = result.overlay(short_silence, position=delay) delay += increment continue # skip sound file that doesn't exist if not sound_file.is_file(): continue segment = AudioSegment.from_wav(path) result = result.overlay(segment, position=delay) delay += increment tmpfile = "" with tempfile.NamedTemporaryFile() as f: tmpfile = f.name result.export(tmpfile, format="wav") logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile class AzureTTS(AbstractTTS): """ 使用微软语音合成技术 """ SLUG = "azure-tts" def __init__( self, secret_key, region, lang="zh-CN", voice="zh-CN-XiaoxiaoNeural", **args ) -> None: super(self.__class__, self).__init__() self.post_url = "https://INSERT_REGION_HERE.tts.speech.microsoft.com/cognitiveservices/v1".replace( "INSERT_REGION_HERE", region ) self.post_header = { "Ocp-Apim-Subscription-Key": secret_key, "Content-Type": "application/ssml+xml", "X-Microsoft-OutputFormat": "audio-16khz-128kbitrate-mono-mp3", "User-Agent": "curl", } self.sess = requests.session() body = ElementTree.Element("speak", version="1.0") body.set("xml:lang", "en-us") vc = ElementTree.SubElement(body, "voice") vc.set("xml:lang", lang) vc.set("name", voice) self.body = body self.vc = vc @classmethod def get_config(cls): # Try to get baidu_yuyin config from config return config.get("azure_yuyin", {}) def get_speech(self, phrase): self.vc.text = phrase result = self.sess.post( self.post_url, headers=self.post_header, data=ElementTree.tostring(self.body), ) # 识别正确返回语音二进制,http状态码为200 if result.status_code == 200: tmpfile = utils.write_temp_file(result.content, ".mp3") logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile else: logger.critical(f"{self.SLUG} 合成失败!", stack_info=True) class BaiduTTS(AbstractTTS): """ 使用百度语音合成技术 要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号, 之后创建一个新应用, 然后在应用管理的"查看key"中获得 API Key 和 Secret Key 填入 config.yml 中. ... baidu_yuyin: appid: '9670645' api_key: 'qg4haN8b2bGvFtCbBGqhrmZy' secret_key: '585d4eccb50d306c401d7df138bb02e7' dev_pid: 1936 per: 1 lan: 'zh' ... """ SLUG = "baidu-tts" def __init__(self, appid, api_key, secret_key, per=1, lan="zh", **args): super(self.__class__, self).__init__() self.client = AipSpeech(appid, api_key, secret_key) self.per, self.lan = str(per), lan @classmethod def get_config(cls): # Try to get baidu_yuyin config from config return config.get("baidu_yuyin", {}) def get_speech(self, phrase): result = self.client.synthesis(phrase, self.lan, 1, {"per": self.per}) # 识别正确返回语音二进制 错误则返回dict 参照下面错误码 if not isinstance(result, dict): tmpfile = utils.write_temp_file(result, ".mp3") logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile else: logger.critical(f"{self.SLUG} 合成失败!", stack_info=True) class TencentTTS(AbstractTTS): """ 腾讯的语音合成 region: 服务地域,挑个离自己最近的区域有助于提升速度。 有效值:https://cloud.tencent.com/document/api/441/17365#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 voiceType: - 0:女声1,亲和风格(默认) - 1:男声1,成熟风格 - 2:男声2,成熟风格 language: - 1: 中文,最大100个汉字(标点符号算一个汉子) - 2: 英文,最大支持400个字母(标点符号算一个字母) """ SLUG = "tencent-tts" def __init__( self, appid, secretid, secret_key, region="ap-guangzhou", voiceType=0, language=1, **args, ): super(self.__class__, self).__init__() self.engine = TencentSpeech.tencentSpeech(secret_key, secretid) self.region, self.voiceType, self.language = region, voiceType, language @classmethod def get_config(cls): # Try to get tencent_yuyin config from config return config.get("tencent_yuyin", {}) def get_speech(self, phrase): result = self.engine.TTS(phrase, self.voiceType, self.language, self.region) if "Response" in result and "Audio" in result["Response"]: audio = result["Response"]["Audio"] data = base64.b64decode(audio) tmpfile = utils.write_temp_file(data, ".wav") logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile else: logger.critical(f"{self.SLUG} 合成失败:{result}", stack_info=True) class XunfeiTTS(AbstractTTS): """ 科大讯飞的语音识别API. """ SLUG = "xunfei-tts" def __init__(self, appid, api_key, api_secret, voice="xiaoyan"): super(self.__class__, self).__init__() self.appid, self.api_key, self.api_secret, self.voice_name = ( appid, api_key, api_secret, voice, ) @classmethod def get_config(cls): # Try to get xunfei_yuyin config from config return config.get("xunfei_yuyin", {}) def get_speech(self, phrase): return XunfeiSpeech.synthesize( phrase, self.appid, self.api_key, self.api_secret, self.voice_name ) class AliTTS(AbstractTTS): """ 阿里的TTS voice: 发音人,默认是 xiaoyun 全部发音人列表:https://help.aliyun.com/document_detail/84435.html?spm=a2c4g.11186623.2.24.67ce5275q2RGsT """ SLUG = "ali-tts" def __init__(self, appKey, token, voice="xiaoyun", **args): super(self.__class__, self).__init__() self.appKey, self.token, self.voice = appKey, token, voice @classmethod def get_config(cls): # Try to get ali_yuyin config from config return config.get("ali_yuyin", {}) def get_speech(self, phrase): tmpfile = AliSpeech.tts(self.appKey, self.token, self.voice, phrase) if tmpfile: logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile else: logger.critical(f"{self.SLUG} 合成失败!", stack_info=True) class EdgeTTS(AbstractTTS): """ edge-tts 引擎 voice: 发音人,默认是 zh-CN-XiaoxiaoNeural 全部发音人列表:命令行执行 edge-tts --list-voices 可以打印所有语音 """ SLUG = "edge-tts" def __init__(self, voice="zh-CN-XiaoxiaoNeural", **args): super(self.__class__, self).__init__() self.voice = voice @classmethod def get_config(cls): # Try to get ali_yuyin config from config return config.get("edge-tts", {}) async def async_get_speech(self, phrase): try: tmpfile = os.path.join(constants.TEMP_PATH, uuid.uuid4().hex + ".mp3") tts = edge_tts.Communicate(text=phrase, voice=self.voice) await tts.save(tmpfile) logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile except Exception as e: logger.critical(f"{self.SLUG} 合成失败:{str(e)}!", stack_info=True) return None def get_speech(self, phrase): event_loop = asyncio.new_event_loop() tmpfile = event_loop.run_until_complete(self.async_get_speech(phrase)) event_loop.close() return tmpfile class MacTTS(AbstractTTS): """ macOS 系统自带的TTS voice: 发音人,默认是 Tingting 全部发音人列表:命令行执行 say -v '?' 可以打印所有语音 中文推荐 Tingting(普通话)或者 Sinji(粤语) """ SLUG = "mac-tts" def __init__(self, voice="Tingting", **args): super(self.__class__, self).__init__() self.voice = voice @classmethod def get_config(cls): # Try to get ali_yuyin config from config return config.get("mac-tts", {}) def get_speech(self, phrase): tmpfile = os.path.join(constants.TEMP_PATH, uuid.uuid4().hex + ".asiff") res = subprocess.run( ["say", "-v", self.voice, "-o", tmpfile, str(phrase)], shell=False, universal_newlines=True, ) if res.returncode == 0: logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile else: logger.critical(f"{self.SLUG} 合成失败!", stack_info=True) class VITS(AbstractTTS): """ VITS 语音合成 需要自行搭建vits-simple-api服务器:https://github.com/Artrajz/vits-simple-api server_url : 服务器url,如http://127.0.0.1:23456 api_key : 若服务器配置了API Key,在此填入 speaker_id : 说话人ID,由所使用的模型决定 length : 调节语音长度,相当于调节语速,该数值越大语速越慢。 noise : 噪声 noisew : 噪声偏差 max : 分段阈值,按标点符号分段,加起来大于max时为一段文本。max<=0表示不分段。 timeout: 响应超时时间,根据vits-simple-api服务器性能不同配置合理的超时时间。 """ SLUG = "VITS" def __init__(self, server_url, api_key, speaker_id, length, noise, noisew, max, timeout, **args): super(self.__class__, self).__init__() self.server_url, self.api_key, self.speaker_id, self.length, self.noise, self.noisew, self.max, self.timeout = ( server_url, api_key, speaker_id, length, noise, noisew, max, timeout) @classmethod def get_config(cls): return config.get("VITS", {}) def get_speech(self, phrase): result = VITSClient.tts(phrase, self.server_url, self.api_key, self.speaker_id, self.length, self.noise, self.noisew, self.max, self.timeout) tmpfile = utils.write_temp_file(result, ".wav") logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile def get_engine_by_slug(slug=None): """ Returns: A TTS Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError("无效的 TTS slug '%s'", slug) selected_engines = list( filter( lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines(), ) ) if len(selected_engines) == 0: raise ValueError(f"错误:找不到名为 {slug} 的 TTS 引擎") else: if len(selected_engines) > 1: logger.warning(f"注意: 有多个 TTS 名称与指定的引擎名 {slug} 匹配") engine = selected_engines[0] logger.info(f"使用 {engine.SLUG} TTS 引擎") return engine.get_instance() class VolcengineTTS(AbstractTTS): """ VolcengineTTS 语音合成 """ SLUG = "volcengine-tts" def __init__(self, appid, token, cluster, voice_type, **args): super(self.__class__, self).__init__() self.engine = VolcengineSpeech.VolcengineTTS(appid=appid, token=token, cluster=cluster, voice_type=voice_type) @classmethod def get_config(cls): # Try to get ali_yuyin config from config return config.get("volcengine-tts", {}) def get_speech(self, text): result = self.engine.execute(text) if result is None: logger.critical(f"{self.SLUG} 合成失败!", stack_info=True) else: tmpfile = os.path.join(constants.TEMP_PATH, uuid.uuid4().hex + ".mp3") with open(tmpfile, "wb") as f: f.write(result) logger.info(f"{self.SLUG} 语音合成成功,合成路径:{tmpfile}") return tmpfile def get_engines(): def get_subclasses(cls): subclasses = set() for subclass in cls.__subclasses__(): subclasses.add(subclass) subclasses.update(get_subclasses(subclass)) return subclasses return [ engine for engine in list(get_subclasses(AbstractTTS)) if hasattr(engine, "SLUG") and engine.SLUG ] ================================================ FILE: robot/Updater.py ================================================ import os import requests import json import semver from subprocess import call from robot import constants, logging from datetime import datetime, timedelta logger = logging.getLogger(__name__) logger.setLevel(level=logging.INFO) _updater = None URL = "https://service-e32kknxi-1253537070.ap-hongkong.apigateway.myqcloud.com/release/wukong" DEV_URL = "https://service-e32kknxi-1253537070.ap-hongkong.apigateway.myqcloud.com/release/wukong-dev" class Updater(object): def __init__(self): self.last_check = datetime.now() - timedelta(days=1.5) self.update_info = {} def _pull(self, cwd, tag): if os.path.exists(cwd): return ( call( [f"git checkout master && git pull && git checkout {tag}"], cwd=cwd, shell=True, ) == 0 ) else: logger.error(f"目录 {cwd} 不存在") return False def _pip(self, cwd): if os.path.exists(cwd): return ( call( ["pip3", "install", "-r", "requirements.txt"], cwd=cwd, shell=False ) == 0 ) else: logger.error(f"目录 {cwd} 不存在") return False def update(self): update_info = self.fetch() success = True if update_info == {}: logger.info("恭喜你,wukong-robot 已经是最新!") if "main" in update_info: if self._pull( constants.APP_PATH, update_info["main"]["version"] ) and self._pip(constants.APP_PATH): logger.info("wukong-robot 更新成功!") self.update_info.pop("main") else: logger.info("wukong-robot 更新失败!") success = False if "contrib" in update_info: if self._pull( constants.CONTRIB_PATH, update_info["contrib"]["version"] ) and self._pip(constants.CONTRIB_PATH): logger.info("wukong-contrib 更新成功!") self.update_info.pop("contrib") else: logger.info("wukong-contrib 更新失败!") success = False return success def _get_version(self, path, current): if os.path.exists(os.path.join(path, "VERSION")): with open(os.path.join(path, "VERSION"), "r") as f: return f.read().strip() else: return current def fetch(self): global URL, DEV_URL url = URL now = datetime.now() if (now - self.last_check).seconds <= 1800: logger.debug(f"30 分钟内已检查过更新,使用上次的检查结果:{self.update_info}") return self.update_info try: self.last_check = now r = requests.get(url, timeout=3) info = json.loads(r.text) main_version = info["main"]["version"] contrib_version = info["contrib"]["version"] # 检查主仓库 current_main_version = self._get_version(constants.APP_PATH, main_version) current_contrib_version = self._get_version( constants.CONTRIB_PATH, contrib_version ) if semver.compare(main_version, current_main_version) > 0: logger.info(f"主仓库检查到更新:{info['main']}") self.update_info["main"] = info["main"] if semver.compare(contrib_version, current_contrib_version) > 0: logger.info(f"插件库检查到更新:{info['contrib']}") self.update_info["contrib"] = info["contrib"] if "notices" in info: self.update_info["notices"] = info["notices"] return self.update_info except Exception as e: logger.error(f"检查更新失败:{e}", stack_info=True) return {} def fetch(): global _updater if not _updater: _updater = Updater() return _updater.fetch() if __name__ == "__main__": fetch() ================================================ FILE: robot/__init__.py ================================================ ================================================ FILE: robot/config.py ================================================ # -*- coding: utf-8 -*- import yaml import logging import os from . import constants logger = logging.getLogger(__name__) _config = {} has_init = False def reload(): """ 重新加载配置 """ logger.info("配置文件发生变更,重新加载配置文件") init() def init(): global has_init if os.path.isfile(constants.CONFIG_PATH): logger.critical(f"错误:{constants.CONFIG_PATH} 应该是个目录,而不应该是个文件") if not os.path.exists(constants.CONFIG_PATH): os.makedirs(constants.CONFIG_PATH) if not os.path.exists(constants.getConfigPath()): yes_no = input(f"配置文件{constants.getConfigPath()}不存在,要创建吗?(y/n)") if yes_no.lower() == "y": constants.newConfig() doInit(constants.getConfigPath()) else: doInit(constants.getDefaultConfigPath()) else: doInit(constants.getConfigPath()) has_init = True def doInit(config_file=constants.getDefaultConfigPath()): # Create config dir if it does not exist yet if not os.path.exists(constants.CONFIG_PATH): try: os.makedirs(constants.CONFIG_PATH) except OSError: logger.error( f"Could not create config dir: '{constants.CONFIG_PATH}'", stack_info=True, ) raise # Check if config dir is writable if not os.access(constants.CONFIG_PATH, os.W_OK): logger.critical( "Config dir %s is not writable. Dingdang " + "won't work correctly.", constants.CONFIG_PATH, ) global _config # Read config logger.debug("Trying to read config file: '%s'", config_file) try: with open(config_file, "r") as f: _config = yaml.safe_load(f) except Exception as e: logger.error(f"配置文件 {config_file} 读取失败: {e}", stack_info=True) raise def get_path(items, default=None, warn=False): global _config curConfig = _config if isinstance(items, str) and items[0] == "/": items = items.split("/")[1:] for key in items: if key in curConfig: curConfig = curConfig[key] else: if warn: logger.warning( "/%s not specified in profile, defaulting to " "'%s'", "/".join(items), default, ) else: logger.debug( "/%s not specified in profile, defaulting to " "'%s'", "/".join(items), default, ) return default return curConfig def has_path(items): global _config curConfig = _config if isinstance(items, str) and items[0] == "/": items = items.split("/")[1:] else: items = [items] for key in items: if key in curConfig: curConfig = curConfig[key] else: return False return True def has(item): """ 判断配置里是否包含某个配置项 :param item: 配置项名 :returns: True: 包含; False: 不包含 """ return has_path(item) def get(item="", default=None, warn=False): """ 获取某个配置的值 :param item: 配置项名。如果是多级配置,则以 "/a/b" 的形式提供 :param default: 默认值(可选) :param warn: 不存在该配置时,是否告警 :returns: 这个配置的值。如果没有该配置,则提供一个默认值 """ global has_init if not has_init: init() if not item: return _config if item[0] == "/": return get_path(item, default, warn) try: return _config[item] except KeyError: if warn: logger.warning( "%s not specified in profile, defaulting to '%s'", item, default ) else: logger.debug( "%s not specified in profile, defaulting to '%s'", item, default ) return default def getConfig(): """ 返回全部配置数据 :returns: 全部配置数据(字典类型) """ return _config def getText(): if os.path.exists(constants.getConfigPath()): with open(constants.getConfigPath(), "r") as f: return f.read() return "" def dump(configStr): with open(constants.getConfigPath(), "w") as f: f.write(configStr) ================================================ FILE: robot/constants.py ================================================ # -*- coding: utf-8 -*- import os import shutil # Wukong main directory APP_PATH = os.path.normpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir) ) LIB_PATH = os.path.join(APP_PATH, "robot") DATA_PATH = os.path.join(APP_PATH, "static") TEMP_PATH = os.path.join(APP_PATH, "temp") TEMPLATE_PATH = os.path.join(APP_PATH, "server", "templates") PLUGIN_PATH = os.path.join(APP_PATH, "plugins") DEFAULT_CONFIG_NAME = "default.yml" CUSTOM_CONFIG_NAME = "config.yml" CONFIG_PATH = os.path.expanduser(os.getenv("WUKONG_CONFIG", "~/.wukong")) CONTRIB_PATH = os.path.expanduser(os.getenv("WUKONG_CONFIG", "~/.wukong/contrib")) CUSTOM_PATH = os.path.expanduser(os.getenv("WUKONG_CONFIG", "~/.wukong/custom")) def getConfigPath(): """ 获取配置文件的路径 returns: 配置文件的存储路径 """ return os.path.join(CONFIG_PATH, CUSTOM_CONFIG_NAME) def getQAPath(): """ 获取QA数据集文件的路径 returns: QA数据集文件的存储路径 """ qa_source = os.path.join(DATA_PATH, "qa.csv") qa_dst = os.path.join(CONFIG_PATH, "qa.csv") if not os.path.exists(qa_dst): shutil.copyfile(qa_source, qa_dst) return qa_dst def getConfigData(*fname): """ 获取配置目录下的指定文件的路径 :param *fname: 指定文件名。如果传多个,则自动拼接 :returns: 配置目录下的某个文件的存储路径 """ return os.path.join(CONFIG_PATH, *fname) def getData(*fname): """ 获取资源目录下指定文件的路径 :param *fname: 指定文件名。如果传多个,则自动拼接 :returns: 配置文件的存储路径 """ return os.path.join(DATA_PATH, *fname) def getDefaultConfigPath(): return getData(DEFAULT_CONFIG_NAME) def newConfig(): shutil.copyfile(getDefaultConfigPath(), getConfigPath()) def getHotwordModel(fname): if os.path.exists(getData(fname)): return getData(fname) else: return getConfigData(fname) ================================================ FILE: robot/detector.py ================================================ import time from snowboy import snowboydecoder from robot import config, logging, utils, constants logger = logging.getLogger(__name__) detector = None recorder = None porcupine = None def initDetector(wukong): """ 初始化离线唤醒热词监听器,支持 snowboy 和 porcupine 两大引擎 """ global porcupine, recorder, detector if config.get("detector", "snowboy") == "porcupine": logger.info("使用 porcupine 进行离线唤醒") import pvporcupine from pvrecorder import PvRecorder access_key = config.get("/porcupine/access_key") keyword_paths = config.get("/porcupine/keyword_paths") keywords = config.get("/porcupine/keywords", ["porcupine"]) if keyword_paths: porcupine = pvporcupine.create( access_key=access_key, keyword_paths=[constants.getConfigData(kw) for kw in keyword_paths], sensitivities=[config.get("sensitivity", 0.5)] * len(keyword_paths), ) else: porcupine = pvporcupine.create( access_key=access_key, keywords=keywords, sensitivities=[config.get("sensitivity", 0.5)] * len(keywords), ) recorder = PvRecorder(device_index=-1, frame_length=porcupine.frame_length) recorder.start() try: while True: pcm = recorder.read() result = porcupine.process(pcm) if result >= 0: kw = keyword_paths[result] if keyword_paths else keywords[result] logger.info( "[porcupine] Keyword {} Detected at time {}".format( kw, time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime(time.time()) ), ) ) wukong._detected_callback(False) recorder.stop() wukong.conversation.interrupt() query = wukong.conversation.activeListen() wukong.conversation.doResponse(query) recorder.start() except pvporcupine.PorcupineActivationError as e: logger.error("[Porcupine] AccessKey activation error", stack_info=True) raise e except pvporcupine.PorcupineActivationLimitError as e: logger.error( f"[Porcupine] AccessKey {access_key} has reached it's temporary device limit", stack_info=True, ) raise e except pvporcupine.PorcupineActivationRefusedError as e: logger.error( "[Porcupine] AccessKey '%s' refused" % access_key, stack_info=True ) raise e except pvporcupine.PorcupineActivationThrottledError as e: logger.error( "[Porcupine] AccessKey '%s' has been throttled" % access_key, stack_info=True, ) raise e except pvporcupine.PorcupineError as e: logger.error("[Porcupine] 初始化 Porcupine 失败", stack_info=True) raise e except KeyboardInterrupt: logger.info("Stopping ...") finally: porcupine and porcupine.delete() recorder and recorder.delete() else: logger.info("使用 snowboy 进行离线唤醒") detector and detector.terminate() models = constants.getHotwordModel(config.get("hotword", "wukong.pmdl")) detector = snowboydecoder.HotwordDetector( models, sensitivity=config.get("sensitivity", 0.5) ) # main loop try: callbacks = wukong._detected_callback detector.start( detected_callback=callbacks, audio_recorder_callback=wukong.conversation.converse, interrupt_check=wukong._interrupt_callback, silent_count_threshold=config.get("silent_threshold", 15), recording_timeout=config.get("recording_timeout", 5) * 4, sleep_time=0.03, ) detector.terminate() except Exception as e: logger.critical(f"离线唤醒机制初始化失败:{e}", stack_info=True) ================================================ FILE: robot/drivers/AIY.py ================================================ import time class AIY: def __init__(self): self._wakeup = False self._think = False def wakeup(self): from aiy.board import Board, Led from aiy.leds import Leds, Pattern, Color self._wakeup = True with Board() as board: with Leds() as leds: while self._wakeup: board.led.state = Led.ON leds.pattern = Pattern.breathe(1000) leds.update(Leds.rgb_pattern(Color.BLUE)) time.sleep(1) def think(self): from aiy.leds import Leds, Pattern, Color self._wakeup = False self._think = True with Leds() as leds: while self._think: leds.pattern = Pattern.blink(500) leds.update(Leds.rgb_pattern(Color.GREEN)) time.sleep(1) def off(self): from aiy.board import Board, Led self._wakeup = False self._think = False with Board() as board: board.led.state = Led.OFF self.led = False ================================================ FILE: robot/drivers/__init__.py ================================================ ================================================ FILE: robot/drivers/apa102.py ================================================ """ from https://github.com/tinue/APA102_Pi This is the main driver module for APA102 LEDs """ import spidev from math import ceil RGB_MAP = { "rgb": [3, 2, 1], "rbg": [3, 1, 2], "grb": [2, 3, 1], "gbr": [2, 1, 3], "brg": [1, 3, 2], "bgr": [1, 2, 3], } class APA102: """ Driver for APA102 LEDS (aka "DotStar"). (c) Martin Erzberger 2016-2017 My very first Python code, so I am sure there is a lot to be optimized ;) Public methods are: - set_pixel - set_pixel_rgb - show - clear_strip - cleanup Helper methods for color manipulation are: - combine_color - wheel The rest of the methods are used internally and should not be used by the user of the library. Very brief overview of APA102: An APA102 LED is addressed with SPI. The bits are shifted in one by one, starting with the least significant bit. An LED usually just forwards everything that is sent to its data-in to data-out. While doing this, it remembers its own color and keeps glowing with that color as long as there is power. An LED can be switched to not forward the data, but instead use the data to change it's own color. This is done by sending (at least) 32 bits of zeroes to data-in. The LED then accepts the next correct 32 bit LED frame (with color information) as its new color setting. After having received the 32 bit color frame, the LED changes color, and then resumes to just copying data-in to data-out. The really clever bit is this: While receiving the 32 bit LED frame, the LED sends zeroes on its data-out line. Because a color frame is 32 bits, the LED sends 32 bits of zeroes to the next LED. As we have seen above, this means that the next LED is now ready to accept a color frame and update its color. So that's really the entire protocol: - Start by sending 32 bits of zeroes. This prepares LED 1 to update its color. - Send color information one by one, starting with the color for LED 1, then LED 2 etc. - Finish off by cycling the clock line a few times to get all data to the very last LED on the strip The last step is necessary, because each LED delays forwarding the data a bit. Imagine ten people in a row. When you yell the last color information, i.e. the one for person ten, to the first person in the line, then you are not finished yet. Person one has to turn around and yell it to person 2, and so on. So it takes ten additional "dummy" cycles until person ten knows the color. When you look closer, you will see that not even person 9 knows its own color yet. This information is still with person 2. Essentially the driver sends additional zeroes to LED 1 as long as it takes for the last color frame to make it down the line to the last LED. """ # Constants MAX_BRIGHTNESS = 31 # Safeguard: Set to a value appropriate for your setup LED_START = 0b11100000 # Three "1" bits, followed by 5 brightness bits def __init__( self, num_led, global_brightness=MAX_BRIGHTNESS, order="rgb", bus=0, device=1, max_speed_hz=8000000, ): self.num_led = num_led # The number of LEDs in the Strip order = order.lower() self.rgb = RGB_MAP.get(order, RGB_MAP["rgb"]) # Limit the brightness to the maximum if it's set higher if global_brightness > self.MAX_BRIGHTNESS: self.global_brightness = self.MAX_BRIGHTNESS else: self.global_brightness = global_brightness self.leds = [self.LED_START, 0, 0, 0] * self.num_led # Pixel buffer self.spi = spidev.SpiDev() # Init the SPI device self.spi.open(bus, device) # Open SPI port 0, slave device (CS) 1 # Up the speed a bit, so that the LEDs are painted faster if max_speed_hz: self.spi.max_speed_hz = max_speed_hz def clock_start_frame(self): """Sends a start frame to the LED strip. This method clocks out a start frame, telling the receiving LED that it must update its own color now. """ self.spi.xfer2([0] * 4) # Start frame, 32 zero bits def clock_end_frame(self): """Sends an end frame to the LED strip. As explained above, dummy data must be sent after the last real colour information so that all of the data can reach its destination down the line. The delay is not as bad as with the human example above. It is only 1/2 bit per LED. This is because the SPI clock line needs to be inverted. Say a bit is ready on the SPI data line. The sender communicates this by toggling the clock line. The bit is read by the LED and immediately forwarded to the output data line. When the clock goes down again on the input side, the LED will toggle the clock up on the output to tell the next LED that the bit is ready. After one LED the clock is inverted, and after two LEDs it is in sync again, but one cycle behind. Therefore, for every two LEDs, one bit of delay gets accumulated. For 300 LEDs, 150 additional bits must be fed to the input of LED one so that the data can reach the last LED. Ultimately, we need to send additional numLEDs/2 arbitrary data bits, in order to trigger numLEDs/2 additional clock changes. This driver sends zeroes, which has the benefit of getting LED one partially or fully ready for the next update to the strip. An optimized version of the driver could omit the "clockStartFrame" method if enough zeroes have been sent as part of "clockEndFrame". """ # Round up num_led/2 bits (or num_led/16 bytes) for _ in range((self.num_led + 15) // 16): self.spi.xfer2([0x00]) def clear_strip(self): """Turns off the strip and shows the result right away.""" for led in range(self.num_led): self.set_pixel(led, 0, 0, 0) self.show() def set_pixel(self, led_num, red, green, blue, bright_percent=100): """Sets the color of one pixel in the LED stripe. The changed pixel is not shown yet on the Stripe, it is only written to the pixel buffer. Colors are passed individually. If brightness is not set the global brightness setting is used. """ if led_num < 0: return # Pixel is invisible, so ignore if led_num >= self.num_led: return # again, invisible # Calculate pixel brightness as a percentage of the # defined global_brightness. Round up to nearest integer # as we expect some brightness unless set to 0 brightness = ceil(bright_percent * self.global_brightness / 100.0) brightness = int(brightness) # LED startframe is three "1" bits, followed by 5 brightness bits ledstart = (brightness & 0b00011111) | self.LED_START start_index = 4 * led_num self.leds[start_index] = ledstart self.leds[start_index + self.rgb[0]] = red self.leds[start_index + self.rgb[1]] = green self.leds[start_index + self.rgb[2]] = blue def set_pixel_rgb(self, led_num, rgb_color, bright_percent=100): """Sets the color of one pixel in the LED stripe. The changed pixel is not shown yet on the Stripe, it is only written to the pixel buffer. Colors are passed combined (3 bytes concatenated) If brightness is not set the global brightness setting is used. """ self.set_pixel( led_num, (rgb_color & 0xFF0000) >> 16, (rgb_color & 0x00FF00) >> 8, rgb_color & 0x0000FF, bright_percent, ) def rotate(self, positions=1): """Rotate the LEDs by the specified number of positions. Treating the internal LED array as a circular buffer, rotate it by the specified number of positions. The number could be negative, which means rotating in the opposite direction. """ cutoff = 4 * (positions % self.num_led) self.leds = self.leds[cutoff:] + self.leds[:cutoff] def show(self): """Sends the content of the pixel buffer to the strip. Todo: More than 1024 LEDs requires more than one xfer operation. """ self.clock_start_frame() # xfer2 kills the list, unfortunately. So it must be copied first # SPI takes up to 4096 Integers. So we are fine for up to 1024 LEDs. self.spi.xfer2(list(self.leds)) self.clock_end_frame() def cleanup(self): """Release the SPI device; Call this method at the end""" self.spi.close() # Close SPI port @staticmethod def combine_color(red, green, blue): """Make one 3*8 byte color value.""" return (red << 16) + (green << 8) + blue def wheel(self, wheel_pos): """Get a color from a color wheel; Green -> Red -> Blue -> Green""" if wheel_pos > 255: wheel_pos = 255 # Safeguard if wheel_pos < 85: # Green -> Red return self.combine_color(wheel_pos * 3, 255 - wheel_pos * 3, 0) if wheel_pos < 170: # Red -> Blue wheel_pos -= 85 return self.combine_color(255 - wheel_pos * 3, 0, wheel_pos * 3) # Blue -> Green wheel_pos -= 170 return self.combine_color(0, wheel_pos * 3, 255 - wheel_pos * 3) def dump_array(self): """For debug purposes: Dump the LED array onto the console.""" print(self.leds) ================================================ FILE: robot/drivers/pixels.py ================================================ from . import apa102 import time import threading try: import queue as Queue except ImportError: import Queue as Queue class Pixels: PIXELS_N = 3 def __init__(self): self.basis = [0] * 3 * self.PIXELS_N self.basis[0] = 1 self.basis[4] = 1 self.basis[8] = 2 self.colors = [0] * 3 * self.PIXELS_N self.dev = apa102.APA102(num_led=self.PIXELS_N) self.next = threading.Event() self.queue = Queue.Queue() self.thread = threading.Thread(target=self._run) self.thread.daemon = True self.thread.start() def wakeup(self, direction=0): def f(): self._wakeup(direction) self.next.set() self.queue.put(f) def listen(self): self.next.set() self.queue.put(self._listen) def think(self): self.next.set() self.queue.put(self._think) def speak(self): self.next.set() self.queue.put(self._speak) def off(self): self.next.set() self.queue.put(self._off) def _run(self): while True: func = self.queue.get() func() def _wakeup(self, direction=0): for i in range(1, 25): colors = [i * v for v in self.basis] self.write(colors) time.sleep(0.01) self.colors = colors def _listen(self): for i in range(1, 25): colors = [i * v for v in self.basis] self.write(colors) time.sleep(0.01) self.colors = colors def _think(self): colors = self.colors self.next.clear() while not self.next.is_set(): colors = colors[3:] + colors[:3] self.write(colors) time.sleep(0.2) t = 0.1 for i in range(0, 5): colors = colors[3:] + colors[:3] self.write([(v * (4 - i) / 4) for v in colors]) time.sleep(t) t /= 2 # time.sleep(0.5) self.colors = colors def _speak(self): colors = self.colors self.next.clear() while not self.next.is_set(): for i in range(5, 25): colors = [(v * i / 24) for v in colors] self.write(colors) time.sleep(0.01) time.sleep(0.3) for i in range(24, 4, -1): colors = [(v * i / 24) for v in colors] self.write(colors) time.sleep(0.01) time.sleep(0.3) self._off() def _off(self): self.write([0] * 3 * self.PIXELS_N) def write(self, colors): for i in range(self.PIXELS_N): self.dev.set_pixel( i, int(colors[3 * i]), int(colors[3 * i + 1]), int(colors[3 * i + 2]) ) self.dev.show() pixels = Pixels() if __name__ == "__main__": while True: try: pixels.wakeup() time.sleep(3) pixels.think() time.sleep(3) pixels.speak() time.sleep(3) pixels.off() time.sleep(3) except KeyboardInterrupt: break pixels.off() time.sleep(1) ================================================ FILE: robot/logging.py ================================================ import logging import os from robot import constants from logging.handlers import RotatingFileHandler PAGE = 4096 DEBUG = logging.DEBUG INFO = logging.INFO WARNING = logging.WARNING ERROR = logging.ERROR def tail(filepath, n=10): """ 实现 tail -n """ res = "" with open(filepath, "rb") as f: f_len = f.seek(0, 2) rem = f_len % PAGE page_n = f_len // PAGE r_len = rem if rem else PAGE while True: # 如果读取的页大小>=文件大小,直接读取数据输出 if r_len >= f_len: f.seek(0) lines = f.readlines()[::-1] break f.seek(-r_len, 2) lines = f.readlines()[::-1] count = len(lines) - 1 # 末行可能不完整,减一行,加大读取量 if count >= n: # 如果读取到的行数>=指定行数,则退出循环读取数据 break else: # 如果读取行数不够,载入更多的页大小读取数据 r_len += PAGE page_n -= 1 for line in lines[:n][::-1]: res += line.decode("utf-8") return res def getLogger(name): """ 作用同标准模块 logging.getLogger(name) :returns: logger """ format = "%(asctime)s - %(name)s - %(filename)s - %(funcName)s - line %(lineno)s - %(levelname)s - %(message)s" formatter = logging.Formatter(format) logging.basicConfig(format=format) logger = logging.getLogger(name) logger.setLevel(logging.INFO) # FileHandler file_handler = RotatingFileHandler( os.path.join(constants.TEMP_PATH, "wukong.log"), maxBytes=1024 * 1024, backupCount=5, ) file_handler.setLevel(level=logging.NOTSET) file_handler.setFormatter(formatter) logger.addHandler(file_handler) return logger def readLog(lines=200): """ 获取最新的指定行数的 log :param lines: 最大的行数 :returns: 最新指定行数的 log """ log_path = os.path.join(constants.TEMP_PATH, "wukong.log") if os.path.exists(log_path): return tail(log_path, lines) return "" ================================================ FILE: robot/plugin_loader.py ================================================ # -*- coding: utf-8 -*- import pkgutil from . import config from . import constants from robot import logging from robot.sdk.AbstractPlugin import AbstractPlugin logger = logging.getLogger(__name__) _has_init = False # plugins run at query _plugins_query = [] def init_plugins(con): """ 动态加载技能插件 参数: con -- 会话模块 """ global _has_init locations = [constants.PLUGIN_PATH, constants.CONTRIB_PATH, constants.CUSTOM_PATH] logger.debug(f"检查插件目录:{locations}") global _plugins_query nameSet = set() for finder, name, ispkg in pkgutil.walk_packages(locations): try: loader = finder.find_module(name) mod = loader.load_module(name) except Exception: logger.warning(f"插件 {name} 加载出错,跳过", exc_info=True) continue if not hasattr(mod, "Plugin"): logger.debug(f"模块 {name} 非插件,跳过") continue # plugins run at query plugin = mod.Plugin(con) if plugin.SLUG == "AbstractPlugin": plugin.SLUG = name # check conflict if plugin.SLUG in nameSet: logger.warning(f"插件 {name} SLUG({plugin.SLUG}) 重复,跳过") continue nameSet.add(plugin.SLUG) # whether a plugin is enabled if config.has(plugin.SLUG) and "enable" in config.get(plugin.SLUG): if not config.get(plugin.SLUG)["enable"]: logger.info(f"插件 {name} 已被禁用") continue if issubclass(mod.Plugin, AbstractPlugin): logger.info(f"插件 {name} 加载成功 ") _plugins_query.append(plugin) def sort_priority(m): if hasattr(m, "PRIORITY"): return m.PRIORITY return 0 _plugins_query.sort(key=sort_priority, reverse=True) _has_init = True def get_plugins(con): global _plugins_query _plugins_query = [] init_plugins(con) return _plugins_query ================================================ FILE: robot/sdk/AbstractPlugin.py ================================================ import sys from robot import logging from robot import constants from abc import ABCMeta, abstractmethod logger = logging.getLogger(__name__) try: sys.path.append(constants.CONTRIB_PATH) except Exception as e: logger.error(f"未检测到插件目录, Error: {e}", stack_info=True) class AbstractPlugin(metaclass=ABCMeta): """技能插件基类""" SLUG = "AbstractPlugin" IS_IMMERSIVE = False def __init__(self, con): if self.IS_IMMERSIVE: self.isImmersive = self.IS_IMMERSIVE else: self.isImmersive = False self.priority = 0 self.con = con self.nlu = self.con.nlu def play(self, src, delete=False, onCompleted=None, volume=1): """ 播放音频 :param play: 要播放的音频地址 :param delete: 播放完成是否要删除,默认不删除 :param onCompleted: 播放完后的回调 :param volume: 音量 """ self.con.play(src, delete, onCompleted, volume) def say(self, text, cache=False, onCompleted=None, wait=False): """ 使用TTS说一句话 :param text: 要说话的内容 :param cache: 是否要缓存该音频,默认不缓存 :param onCompleted: 播放完后的回调 :param wait: 已废弃 """ self.con.say(text, cache=cache, plugin=self.SLUG, onCompleted=onCompleted) def activeListen(self, silent=False): if ( self.SLUG != "geek" and self.con.immersiveMode and self.con.immersiveMode == "geek" ): # 极客模式下禁止其他插件主动聆听,以避免异常问题 self.con.player.stop() self.critical("错误:请退出极客模式后再试") self.say("错误:请退出极客模式后再试") return "" return self.con.activeListen(silent) def clearImmersive(self): self.con.setImmersiveMode(None) def parse(self, query): """ NLU 解析 """ return self.con.doParse(query) @abstractmethod def isValid(self, query, parsed): """ 是否适合由该插件处理 参数: query -- 用户的指令字符串 parsed -- 用户指令经过 NLU 解析后的结果 返回: True: 适合由该插件处理 False: 不适合由该插件处理 """ return False @abstractmethod def handle(self, query, parsed): """ 处理逻辑 参数: query -- 用户的指令字符串 parsed -- 用户指令经过 NLU 解析后的结果 """ pass def isValidImmersive(self, query, parsed): """ 是否适合在沉浸模式下处理, 仅适用于有沉浸模式的插件(如音乐等) 当用户唤醒时,可以响应更多指令集。 例如:“"上一首"、"下一首" 等 """ return False def pause(self): """ 暂停当前正在处理的任务, 当处于该沉浸模式下且被唤醒时, 将自动触发这个方法, 可以用于强制暂停一个耗时的操作 """ return def restore(self): """ 恢复当前插件, 仅适用于有沉浸模式的插件(如音乐等) 当用户误唤醒或者唤醒进行闲聊后, 可以自动恢复当前插件的处理逻辑 """ return ================================================ FILE: robot/sdk/AliSpeech.py ================================================ # -*- coding: UTF-8 -*- import http.client import urllib.parse import json from robot import utils from robot import logging logger = logging.getLogger(__name__) def processGETRequest(appKey, token, voice, text, format, sampleRate): host = "nls-gateway.cn-shanghai.aliyuncs.com" url = "https://" + host + "/stream/v1/tts" # 设置URL请求参数 url = url + "?appkey=" + appKey url = url + "&token=" + token url = url + "&text=" + text url = url + "&format=" + format url = url + "&sample_rate=" + str(sampleRate) url = url + "&voice=" + voice logger.debug(url) conn = http.client.HTTPSConnection(host) conn.request(method="GET", url=url) # 处理服务端返回的响应 response = conn.getresponse() logger.debug("Response status and response reason:") logger.debug(response.status, response.reason) contentType = response.getheader("Content-Type") logger.debug(contentType) body = response.read() if "audio/mpeg" == contentType: logger.debug("The GET request succeed!") tmpfile = utils.write_temp_file(body, ".mp3") conn.close() return tmpfile else: logger.debug("The GET request failed: " + str(body)) conn.close() return None def processPOSTRequest(appKey, token, voice, text, format, sampleRate): host = "nls-gateway.cn-shanghai.aliyuncs.com" url = "https://" + host + "/stream/v1/tts" # 设置HTTPS Headers httpHeaders = {"Content-Type": "application/json"} # 设置HTTPS Body body = { "appkey": appKey, "token": token, "text": text, "format": format, "sample_rate": sampleRate, "voice": voice, } body = json.dumps(body) logger.debug("The POST request body content: " + body) # Python 2.x 请使用httplib # conn = httplib.HTTPSConnection(host) # Python 3.x 请使用http.client conn = http.client.HTTPSConnection(host) conn.request(method="POST", url=url, body=body, headers=httpHeaders) # 处理服务端返回的响应 response = conn.getresponse() logger.debug("Response status and response reason:") logger.debug(response.status, response.reason) contentType = response.getheader("Content-Type") logger.debug(contentType) body = response.read() if "audio/mpeg" == contentType: logger.debug("The POST request succeed!") tmpfile = utils.write_temp_file(body, ".mp3") conn.close() return tmpfile else: logger.critical("The POST request failed: " + str(body), stack_info=True) conn.close() return None def process(request, token, audioContent): # 读取音频文件 host = "nls-gateway.cn-shanghai.aliyuncs.com" # 设置HTTP请求头部 httpHeaders = { "X-NLS-Token": token, "Content-type": "application/octet-stream", "Content-Length": len(audioContent), } conn = http.client.HTTPConnection(host) conn.request(method="POST", url=request, body=audioContent, headers=httpHeaders) response = conn.getresponse() logger.debug("Response status and response reason:") logger.debug(response.status, response.reason) body = response.read() try: logger.debug("Recognize response is:") body = json.loads(body) logger.debug(body) status = body["status"] if status == 20000000: result = body["result"] logger.debug("Recognize result: " + result) conn.close() return result else: logger.critical("Recognizer failed!", stack_info=True) conn.close() return None except ValueError: logger.debug("The response is not json format string") conn.close() return None def tts(appKey, token, voice, text): # 采用RFC 3986规范进行urlencode编码 textUrlencode = text textUrlencode = urllib.parse.quote_plus(textUrlencode) textUrlencode = textUrlencode.replace("+", "%20") textUrlencode = textUrlencode.replace("*", "%2A") textUrlencode = textUrlencode.replace("%7E", "~") format = "mp3" sampleRate = 16000 return processPOSTRequest(appKey, token, voice, text, format, sampleRate) def asr(appKey, token, wave_file): # 服务请求地址 url = "http://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr" pcm = utils.get_pcm_from_wav(wave_file) # 音频文件 format = "pcm" sampleRate = 16000 enablePunctuationPrediction = True enableInverseTextNormalization = True enableVoiceDetection = False # 设置RESTful请求参数 request = url + "?appkey=" + appKey request = request + "&format=" + format request = request + "&sample_rate=" + str(sampleRate) if enablePunctuationPrediction: request = request + "&enable_punctuation_prediction=" + "true" if enableInverseTextNormalization: request = request + "&enable_inverse_text_normalization=" + "true" if enableVoiceDetection: request = request + "&enable_voice_detection=" + "true" logger.debug("Request: " + request) return process(request, token, pcm) ================================================ FILE: robot/sdk/BaiduSpeech.py ================================================ # -*- coding:utf-8 -*- import os import json import requests import time from robot import logging logger = logging.getLogger(__name__) TOKEN_PATH = os.path.expanduser("~/.wukong/.baiduSpeech_token") # 百度语音识别 REST_API极速版 class baiduSpeech(object): def __init__(self, api_key, secret_key, dev_pid): self.api_key, self.secret_key, self.dev_pid = api_key, secret_key, dev_pid if not os.path.exists(TOKEN_PATH): self.token = self.fetch_token() else: self.token = self.load() def fetch_token(self): token_url = "http://openapi.baidu.com/oauth/2.0/token" body = { "grant_type": "client_credentials", "client_id": self.api_key, "client_secret": self.secret_key, } try: req = requests.post( token_url, headers={"Content-Type": "application/json; charset=UTF-8"}, data=body, ) s = req.content.decode("utf-8", "ignore") result = json.loads(s) if "access_token" in result.keys() and "scope" in result.keys(): if not "brain_enhanced_asr" in result["scope"].split(" "): logger.error("当前百度云api_id尚未有语音识别的授权。") #### 请求access_token成功. with open(TOKEN_PATH, "w") as f: result = { key: result.get(key) for key in ["access_token", "expires_in"] } result["get_time"] = time.time() data = json.dumps(result) f.write(data) return result["access_token"] except Exception as err: logger.error(f"请求token_access失败: {err}", stack_info=True) def load(self): def is_json(f): try: json_object = json.load(f) except ValueError: return False return json_object try: with open(TOKEN_PATH, "r") as f: access_token = is_json(f) if not access_token: return self.fetch_token() elif ( time.time() - access_token["expires_in"] - access_token["get_time"] >= 0 ): return self.fetch_token() else: return access_token["access_token"] except (OSError, KeyError, ValueError) as e: print(f"加载.baiduSpeech_token文件失败,请检查!原因是{e}") def asr(self, pcm, file_type, sample_rate, dev_pid): asr_url = "http://vop.baidu.com/pro_api" length = len(pcm) if length == 0: logger.error(f"这个语音文件 {pcm} 是空的") headers = { "Content-Type": "audio/" + file_type + ";rate=" + str(sample_rate), "Content-Length": str(length), } params = {"cuid": "wukong-Robot", "token": self.token, "dev_pid": self.dev_pid} try: req = requests.post(asr_url, params=params, headers=headers, data=pcm) s = req.content.decode("utf-8") return json.loads(s) except Exception as err: logger.error(f"百度ASR极速版请求失败: {err}", stack_info=True) ================================================ FILE: robot/sdk/FunASREngine.py ================================================ from typing import Any class funASREngine(object): def __init__(self, inference_type, model_dir=''): assert inference_type in ['onnxruntime'] # 当前只实现了onnxruntime的推理方案 self.inference_type = inference_type if self.inference_type == 'onnxruntime': # 调用下面的引擎进初始化引擎太慢了,因此放在条件分支里面 from funasr_onnx import Paraformer self.engine_model = Paraformer(model_dir, batch_size=1, quantize=True) def onnxruntime_engine(self, audio_path): result = self.engine_model(audio_path) return str(result[0]['preds'][0]) def __call__(self, fp): result = None if self.inference_type == 'onnxruntime': result = self.onnxruntime_engine(fp) return result ================================================ FILE: robot/sdk/History.py ================================================ # -*- coding: utf-8 -*- # 用于维护历史消息 import tornado.locks def Singleton(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton @Singleton class History(object): def __init__(self): # cond is notified whenever the message cache is updated self.cond = tornado.locks.Condition() self.cache = [] self.cache_size = 200 def get_messages_since(self, cursor): """Returns a list of messages newer than the given cursor. ``cursor`` should be the ``uuid`` of the last message received. """ results = [] for msg in reversed(self.cache): if msg["uuid"] == cursor: break results.append(msg) results.reverse() return results def add_message(self, message): self.cache.append(message) if len(self.cache) > self.cache_size: self.cache = self.cache[-self.cache_size :] self.cond.notify_all() ================================================ FILE: robot/sdk/LED.py ================================================ import _thread as thread from robot import config, logging from robot.drivers.AIY import AIY logger = logging.getLogger(__name__) aiy = AIY() def wakeup(): if config.get("/LED/enable", False): if config.get("/LED/type") == "aiy": thread.start_new_thread(aiy.wakeup, ()) elif config.get("/LED/type") == "respeaker": from robot.drivers.pixels import pixels pixels.wakeup() else: logger.error("错误:不支持的灯光类型", stack_info=True) def think(): if config.get("/LED/enable", False): if config.get("/LED/type") == "aiy": thread.start_new_thread(aiy.think, ()) elif config.get("/LED/type") == "respeaker": from robot.drivers.pixels import pixels pixels.think() else: logger.error("错误:不支持的灯光类型", stack_info=True) def off(): if config.get("/LED/enable", False): if config.get("/LED/type") == "aiy": thread.start_new_thread(aiy.off, ()) elif config.get("/LED/type") == "respeaker": from robot.drivers.pixels import pixels pixels.off() else: logger.error("错误:不支持的灯光类型", stack_info=True) ================================================ FILE: robot/sdk/RASRsdk.py ================================================ # -*- coding:utf-8 -*- import urllib.request import hmac import hashlib import base64 import time import random import os import json def formatSignString(param): signstr = "POSTaai.qcloud.com/asr/v1/" for t in param: if "appid" in t: signstr += str(t[1]) break signstr += "?" for x in param: tmp = x if "appid" in x: continue for t in tmp: signstr += str(t) signstr += "=" signstr = signstr[:-1] signstr += "&" signstr = signstr[:-1] # print 'signstr',signstr return signstr def sign(signstr, secret_key): sign_bytes = bytes(signstr, "utf-8") secret_bytes = bytes(secret_key, "utf-8") hmacstr = hmac.new(secret_bytes, sign_bytes, hashlib.sha1).digest() s = base64.b64encode(hmacstr).decode("utf-8") return s def randstr(n): seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sa = [] for i in range(n): sa.append(random.choice(seed)) salt = "".join(sa) # print salt return salt def sendVoice( secret_key, secretid, appid, engine_model_type, res_type, result_text_format, voice_format, filepath, cutlength, template_name="", ): if len(str(secret_key)) == 0: print("secretKey can not empty") return if len(str(secretid)) == 0: print("secretid can not empty") return if len(str(appid)) == 0: print("appid can not empty") return if len(str(engine_model_type)) == 0 or ( str(engine_model_type) != "8k_0" and str(engine_model_type) != "16k_0" and str(engine_model_type) != "16k_en" ): print("engine_model_type is not right") return if len(str(res_type)) == 0 or (str(res_type) != "0" and str(res_type) != "1"): print("res_type is not right") return if len(str(result_text_format)) == 0 or ( str(result_text_format) != "0" and str(result_text_format) != "1" and str(result_text_format) != "2" and str(result_text_format) != "3" ): print("result_text_format is not right") return if len(str(voice_format)) == 0 or ( str(voice_format) != "1" and str(voice_format) != "4" and str(voice_format) != "6" ): print("voice_format is not right") return if len(str(filepath)) == 0: print("filepath can not empty") return if ( len(str(cutlength)) == 0 or str(cutlength).isdigit() == False or cutlength > 200000 ): print("cutlength can not empty") return # secret_key = "oaYWFO70LGDmcpfwo8uF1IInayysGtgZ" query_arr = dict() query_arr["appid"] = appid query_arr["projectid"] = 1013976 if len(template_name) > 0: query_arr["template_name"] = template_name query_arr["sub_service_type"] = 1 query_arr["engine_model_type"] = engine_model_type query_arr["res_type"] = res_type query_arr["result_text_format"] = result_text_format query_arr["voice_id"] = randstr(16) query_arr["timeout"] = 100 query_arr["source"] = 0 query_arr["secretid"] = secretid query_arr["timestamp"] = str(int(time.time())) query_arr["expired"] = int(time.time()) + 24 * 60 * 60 query_arr["nonce"] = query_arr["timestamp"][0:4] query_arr["voice_format"] = voice_format file_object = open(filepath, "rb") file_object.seek(0, os.SEEK_END) datalen = file_object.tell() file_object.seek(0, os.SEEK_SET) seq = 0 response = [] while datalen > 0: end = 0 if datalen < cutlength: end = 1 query_arr["end"] = end query_arr["seq"] = seq query = sorted(query_arr.items(), key=lambda d: d[0]) signstr = formatSignString(query) autho = sign(signstr, secret_key) if datalen < cutlength: content = file_object.read(datalen) else: content = file_object.read(cutlength) seq = seq + 1 datalen = datalen - cutlength headers = dict() headers["Authorization"] = autho headers["Content-Length"] = len(content) requrl = "http://" requrl += signstr[4::] req = urllib.request.Request(requrl, data=content, headers=headers) res_data = urllib.request.urlopen(req) r = res_data.read().decode("utf-8") res = json.loads(r) if res["code"] == 0: response.append(res["text"]) file_object.close() return response[len(response) - 1] ================================================ FILE: robot/sdk/TencentSpeech.py ================================================ # coding: utf-8 #!/usr/bin/env python3 "Tencent ASR && TTS API" __author__ = "Charles Li, Joseph Pan" import time import uuid import json import random import requests import hmac import base64 import urllib # 腾讯web API一句话识别请求 class tencentSpeech(object): __slots__ = ( "SECRET_ID", "SECRET_KEY", "SourceType", "URL", "VoiceFormat", "PrimaryLanguage", "Text", "VoiceType", "Region", ) def __init__(self, SECRET_KEY, SECRET_ID): self.SECRET_KEY, self.SECRET_ID = SECRET_KEY, SECRET_ID @property def secret_id(self): return self.SECRET_ID @secret_id.setter def secret_id(self, SECRET_ID): if not isinstance(SECRET_ID, str): raise ValueError("SecretId must be a string!") if len(SECRET_ID) == 0: raise ValueError("SecretId can not be empty!") self.SECRET_ID = SECRET_ID @property def secret_key(self): return self.SECRET_KEY @secret_key.setter def secret_key(self, SECRET_KEY): if not isinstance(SECRET_KEY, str): raise ValueError("SecretKey must be a string!") if len(SECRET_KEY) == 0: raise ValueError("SecretKey can not be empty!") self.SECRET_KEY = SECRET_KEY @property def source_type(self): return self.sourcetype @source_type.setter def source_type(self, SourceType): if not isinstance(SourceType, str): raise ValueError("SecretType must be an string!") if len(SourceType) == 0: raise ValueError("SourceType can not be empty!") self.SourceType = SourceType @property def url(self): return self.URL @url.setter def url(self, URL): if not isinstance(URL, str): raise ValueError("url must be an string!") if len(URL) == 0: raise ValueError("url can not be empty!") self.URL = URL @property def voiceformat(self): return self.VoiceFormat @voiceformat.setter def voiceformat(self, VoiceFormat): if not isinstance(VoiceFormat, str): raise ValueError("voiceformat must be an string!") if len(VoiceFormat) == 0: raise ValueError("voiceformat can not be empty!") self.VoiceFormat = VoiceFormat @property def text(self): return self.Text @text.setter def text(self, Text): if not isinstance(Text, str): raise ValueError("text must be an string!") if len(Text) == 0: raise ValueError("text can not be empty!") self.Text = Text @property def region(self): return self.Region @region.setter def region(self, Region): if not isinstance(Region, str): raise ValueError("region must be an string!") if len(Region) == 0: raise ValueError("region can not be empty!") self.Region = Region @property def primarylanguage(self): return self.PrimaryLanguage @primarylanguage.setter def primarylanguage(self, PrimaryLanguage): self.PrimaryLanguage = PrimaryLanguage @property def voicetype(self): return self.VoiceType @voicetype.setter def voicetype(self, VoiceType): self.VoiceType = VoiceType def TTS(self, text, voicetype, primarylanguage, region): self.text, self.voicetype, self.primarylanguage, self.region = ( text, voicetype, primarylanguage, region, ) return self.textToSpeech() def textToSpeech(self): # 生成body def make_body(config_dict, sign_encode): ##注意URL编码的时候分str编码,整段编码会丢data body = "" for a, b in config_dict: body += urllib.parse.quote(a) + "=" + urllib.parse.quote(str(b)) + "&" return body + "Signature=" + sign_encode HOST = "aai.tencentcloudapi.com" config_dict = { "Action": "TextToVoice", "Version": "2018-05-22", "ProjectId": 0, "Region": self.Region, "VoiceType": self.VoiceType, "Timestamp": int(time.time()), "Nonce": random.randint(100000, 200000), "SecretId": self.SECRET_ID, "Text": self.Text, "PrimaryLanguage": self.PrimaryLanguage, "ModelType": 1, "SessionId": uuid.uuid1(), } # 按key排序 config_dict = sorted(config_dict.items()) signstr = self.formatSignString(config_dict) sign_encode = urllib.parse.quote(self.encode_sign(signstr, self.SECRET_KEY)) body = make_body(config_dict, sign_encode) # Get URL req_url = "https://aai.tencentcloudapi.com" header = { "Host": HOST, "Content-Type": "application/x-www-form-urlencoded", "Charset": "UTF-8", } request = requests.post(req_url, headers=header, data=body) # 有些音频utf8解码失败,存在编码错误 s = request.content.decode("utf8", "ignore") return json.loads(s) def ASR(self, URL, voiceformat, sourcetype, region): self.url, self.voiceformat, self.source_type, self.region = ( URL, voiceformat, sourcetype, region, ) return self.oneSentenceRecognition() def oneSentenceRecognition(self): # 生成body def make_body(config_dict, sign_encode): ##注意URL编码的时候分str编码,整段编码会丢data body = "" for a, b in config_dict: body += urllib.parse.quote(a) + "=" + urllib.parse.quote(str(b)) + "&" return body + "Signature=" + sign_encode HOST = "aai.tencentcloudapi.com" config_dict = { "Action": "SentenceRecognition", "Version": "2018-05-22", "Region": self.Region, "ProjectId": 0, "SubServiceType": 2, "EngSerViceType": "16k", "VoiceFormat": self.VoiceFormat, "UsrAudioKey": random.randint(0, 20), "Timestamp": int(time.time()), "Nonce": random.randint(100000, 200000), "SecretId": self.SECRET_ID, "SourceType": self.SourceType, } if self.SourceType == "0": config_dict["Url"] = urllib.parse.quote(str(self.url)) else: # 不能大于1M file_path = self.URL file = open(file_path, "rb") content = file.read() config_dict["DataLen"] = len(content) config_dict["Data"] = base64.b64encode(content).decode() # config_dict['Data'] = content file.close() # 按key排序 config_dict = sorted(config_dict.items()) signstr = self.formatSignString(config_dict) sign_encode = urllib.parse.quote(self.encode_sign(signstr, self.SECRET_KEY)) body = make_body(config_dict, sign_encode) # Get URL req_url = "https://aai.tencentcloudapi.com" header = { "Host": HOST, "Content-Type": "application/x-www-form-urlencoded", "Charset": "UTF-8", } request = requests.post(req_url, headers=header, data=body) # 有些音频utf8解码失败,存在编码错误 s = request.content.decode("utf8", "ignore") return s # 拼接url和参数 def formatSignString(self, config_dict): signstr = "POSTaai.tencentcloudapi.com/?" argArr = [] for a, b in config_dict: argArr.append(a + "=" + str(b)) config_str = "&".join(argArr) return signstr + config_str # 生成签名 def encode_sign(self, signstr, SECRET_KEY): myhmac = hmac.new(SECRET_KEY.encode(), signstr.encode(), digestmod="sha1") code = myhmac.digest() # hmac() 完一定要decode()和 python 2 hmac不一样 signature = base64.b64encode(code).decode() return signature ================================================ FILE: robot/sdk/Unihiker.py ================================================ from robot import constants, config from unihiker import Audio, GUI from pinpong.board import Board, Pin, Tone from pinpong.extension.unihiker import * class Unihiker(object): def __init__(self): Board().begin() self._gui = GUI() self._tone = Tone(Pin(Pin.P26)) self._gui.draw_image(w=240, h=320, image=constants.getData("background.png")) self._my_bubble = self._gui.draw_text( x=20, y=25, w=150, color="red", text="(请说唤醒词)", font_size=10 ) self._bot_bubble = self._gui.draw_text( x=40, y=80, w=150, color="black", text="", font_size=10 ) def _play_tones(self, tones, duration): for tone in tones: self._tone.freq(tone) self._tone.on() time.sleep(duration) self._tone.off() def wakeup(self): if config.get("/unihiker/beep", False): self._play_tones([225, 329], 0.1) def think(self): if config.get("/unihiker/beep", False): self._play_tones([329, 225], 0.1) def record(self, t, text=""): self._my_bubble.config( text=text, color="black" ) if t == 0 else self._bot_bubble.config(text=text) ================================================ FILE: robot/sdk/VITSClient.py ================================================ # coding: utf-8 # !/usr/bin/env python3 """VITS TTS API""" import requests def tts(text, server_url, api_key, speaker_id, length, noise, noisew, max, timeout): data = { "text": text, "id": speaker_id, "format": "wav", "lang": "auto", "length": length, "noise": noise, "noisew": noisew, "max": max } headers = {"X-API-KEY": api_key} url = f"{server_url}/voice" res = requests.post(url=url, data=data, headers=headers, timeout=timeout) res.raise_for_status() return res.content ================================================ FILE: robot/sdk/VolcengineSpeech.py ================================================ #coding=utf-8 """ requires Python 3.6 or later pip install asyncio pip install websockets """ import asyncio import base64 from cProfile import run import gzip import hmac import json import requests import logging import os from typing_extensions import Self import uuid import wave from enum import Enum from hashlib import sha256 from io import BytesIO from typing import List from urllib.parse import urlparse import time import websockets from robot import config audio_format = "wav" # wav 或者 mp3,根据实际音频格式设置 PROTOCOL_VERSION = 0b0001 DEFAULT_HEADER_SIZE = 0b0001 PROTOCOL_VERSION_BITS = 4 HEADER_BITS = 4 MESSAGE_TYPE_BITS = 4 MESSAGE_TYPE_SPECIFIC_FLAGS_BITS = 4 MESSAGE_SERIALIZATION_BITS = 4 MESSAGE_COMPRESSION_BITS = 4 RESERVED_BITS = 8 # Message Type: CLIENT_FULL_REQUEST = 0b0001 CLIENT_AUDIO_ONLY_REQUEST = 0b0010 SERVER_FULL_RESPONSE = 0b1001 SERVER_ACK = 0b1011 SERVER_ERROR_RESPONSE = 0b1111 # Message Type Specific Flags NO_SEQUENCE = 0b0000 # no check sequence POS_SEQUENCE = 0b0001 NEG_SEQUENCE = 0b0010 NEG_SEQUENCE_1 = 0b0011 # Message Serialization NO_SERIALIZATION = 0b0000 JSON = 0b0001 THRIFT = 0b0011 CUSTOM_TYPE = 0b1111 # Message Compression NO_COMPRESSION = 0b0000 GZIP = 0b0001 CUSTOM_COMPRESSION = 0b1111 def generate_header( version=PROTOCOL_VERSION, message_type=CLIENT_FULL_REQUEST, message_type_specific_flags=NO_SEQUENCE, serial_method=JSON, compression_type=GZIP, reserved_data=0x00, extension_header=bytes() ): """ protocol_version(4 bits), header_size(4 bits), message_type(4 bits), message_type_specific_flags(4 bits) serialization_method(4 bits) message_compression(4 bits) reserved (8bits) 保留字段 header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) ) """ header = bytearray() header_size = int(len(extension_header) / 4) + 1 header.append((version << 4) | header_size) header.append((message_type << 4) | message_type_specific_flags) header.append((serial_method << 4) | compression_type) header.append(reserved_data) header.extend(extension_header) return header def generate_full_default_header(): return generate_header() def generate_audio_default_header(): return generate_header( message_type=CLIENT_AUDIO_ONLY_REQUEST ) def generate_last_audio_default_header(): return generate_header( message_type=CLIENT_AUDIO_ONLY_REQUEST, message_type_specific_flags=NEG_SEQUENCE ) def parse_response(res): """ protocol_version(4 bits), header_size(4 bits), message_type(4 bits), message_type_specific_flags(4 bits) serialization_method(4 bits) message_compression(4 bits) reserved (8bits) 保留字段 header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) ) payload 类似与http 请求体 """ protocol_version = res[0] >> 4 header_size = res[0] & 0x0f message_type = res[1] >> 4 message_type_specific_flags = res[1] & 0x0f serialization_method = res[2] >> 4 message_compression = res[2] & 0x0f reserved = res[3] header_extensions = res[4:header_size * 4] payload = res[header_size * 4:] result = {} payload_msg = None payload_size = 0 if message_type == SERVER_FULL_RESPONSE: payload_size = int.from_bytes(payload[:4], "big", signed=True) payload_msg = payload[4:] elif message_type == SERVER_ACK: seq = int.from_bytes(payload[:4], "big", signed=True) result['seq'] = seq if len(payload) >= 8: payload_size = int.from_bytes(payload[4:8], "big", signed=False) payload_msg = payload[8:] elif message_type == SERVER_ERROR_RESPONSE: code = int.from_bytes(payload[:4], "big", signed=False) result['code'] = code payload_size = int.from_bytes(payload[4:8], "big", signed=False) payload_msg = payload[8:] if payload_msg is None: return result if message_compression == GZIP: payload_msg = gzip.decompress(payload_msg) if serialization_method == JSON: payload_msg = json.loads(str(payload_msg, "utf-8")) elif serialization_method != NO_SERIALIZATION: payload_msg = str(payload_msg, "utf-8") result['payload_msg'] = payload_msg result['payload_size'] = payload_size return result def read_wav_info(data: bytes = None): with BytesIO(data) as _f: wave_fp = wave.open(_f, 'rb') nchannels, sampwidth, framerate, nframes = wave_fp.getparams()[:4] wave_bytes = wave_fp.readframes(nframes) return nchannels, sampwidth, framerate, nframes, len(wave_bytes) class AudioType(Enum): LOCAL = 1 # 使用本地音频文件 class AsrWsClient: def __init__(self, audio_path, cluster, **kwargs): """ :param config: config """ self.audio_path = audio_path self.cluster = cluster self.success_code = 1000 # success code, default is 1000 self.seg_duration = int(kwargs.get("seg_duration", 15000)) self.nbest = int(kwargs.get("nbest", 1)) self.appid = kwargs.get("appid", "") self.token = kwargs.get("token", "") self.ws_url = kwargs.get("ws_url", "wss://openspeech.bytedance.com/api/v2/asr") self.uid = kwargs.get("uid", "streaming_asr_demo") self.workflow = kwargs.get("workflow", "audio_in,resample,partition,vad,fe,decode,itn,nlu_punctuate") self.show_language = kwargs.get("show_language", False) self.show_utterances = kwargs.get("show_utterances", False) self.result_type = kwargs.get("result_type", "full") self.format = kwargs.get("format", "wav") self.rate = kwargs.get("sample_rate", 16000) self.language = kwargs.get("language", "zh-CN") self.bits = kwargs.get("bits", 16) self.channel = kwargs.get("channel", 1) self.codec = kwargs.get("codec", "raw") self.audio_type = kwargs.get("audio_type", AudioType.LOCAL) self.secret = kwargs.get("secret", "access_secret") self.auth_method = kwargs.get("auth_method", "token") self.mp3_seg_size = int(kwargs.get("mp3_seg_size", 10000)) def construct_request(self, reqid): req = { 'app': { 'appid': self.appid, 'cluster': self.cluster, 'token': self.token, }, 'user': { 'uid': self.uid }, 'request': { 'reqid': reqid, 'nbest': self.nbest, 'workflow': self.workflow, 'show_language': self.show_language, 'show_utterances': self.show_utterances, 'result_type': self.result_type, "sequence": 1 }, 'audio': { 'format': self.format, 'rate': self.rate, 'language': self.language, 'bits': self.bits, 'channel': self.channel, 'codec': self.codec } } return req @staticmethod def slice_data(data: bytes, chunk_size: int): """ slice data :param data: wav data :param chunk_size: the segment size in one request :return: segment data, last flag """ data_len = len(data) offset = 0 while offset + chunk_size < data_len: yield data[offset: offset + chunk_size], False offset += chunk_size else: yield data[offset: data_len], True def _real_processor(self, request_params: dict) -> dict: pass def token_auth(self): return {'Authorization': 'Bearer; {}'.format(self.token)} def signature_auth(self, data): header_dicts = { 'Custom': 'auth_custom', } url_parse = urlparse(self.ws_url) input_str = 'GET {} HTTP/1.1\n'.format(url_parse.path) auth_headers = 'Custom' for header in auth_headers.split(','): input_str += '{}\n'.format(header_dicts[header]) input_data = bytearray(input_str, 'utf-8') input_data += data mac = base64.urlsafe_b64encode( hmac.new(self.secret.encode('utf-8'), input_data, digestmod=sha256).digest()) header_dicts['Authorization'] = 'HMAC256; access_token="{}"; mac="{}"; h="{}"'.format(self.token, str(mac, 'utf-8'), auth_headers) return header_dicts async def segment_data_processor(self, wav_data: bytes, segment_size: int): reqid = str(uuid.uuid4()) # 构建 full client request,并序列化压缩 request_params = self.construct_request(reqid) payload_bytes = str.encode(json.dumps(request_params)) payload_bytes = gzip.compress(payload_bytes) full_client_request = bytearray(generate_full_default_header()) full_client_request.extend((len(payload_bytes)).to_bytes(4, 'big')) # payload size(4 bytes) full_client_request.extend(payload_bytes) # payload header = None if self.auth_method == "token": header = self.token_auth() elif self.auth_method == "signature": header = self.signature_auth(full_client_request) async with websockets.connect(self.ws_url, extra_headers=header, max_size=1000000000) as ws: # 发送 full client request await ws.send(full_client_request) res = await ws.recv() result = parse_response(res) if 'payload_msg' in result and result['payload_msg']['code'] != self.success_code: return result for seq, (chunk, last) in enumerate(AsrWsClient.slice_data(wav_data, segment_size), 1): # if no compression, comment this line payload_bytes = gzip.compress(chunk) audio_only_request = bytearray(generate_audio_default_header()) if last: audio_only_request = bytearray(generate_last_audio_default_header()) audio_only_request.extend((len(payload_bytes)).to_bytes(4, 'big')) # payload size(4 bytes) audio_only_request.extend(payload_bytes) # payload # 发送 audio-only client request await ws.send(audio_only_request) res = await ws.recv() result = parse_response(res) if 'payload_msg' in result and result['payload_msg']['code'] != self.success_code: return result return result async def execute(self): with open(self.audio_path, mode="rb") as _f: data = _f.read() audio_data = bytes(data) if self.format == "mp3": segment_size = self.mp3_seg_size return await self.segment_data_processor(audio_data, segment_size) if self.format != "wav": raise Exception("format should in wav or mp3") nchannels, sampwidth, framerate, nframes, wav_len = read_wav_info( audio_data) size_per_sec = nchannels * sampwidth * framerate segment_size = int(size_per_sec * self.seg_duration / 1000) return await self.segment_data_processor(audio_data, segment_size) class VolcengineASR(object): def __init__(self, **kwargs) -> None: self.appid = kwargs['appid'] self.token = kwargs['token'] self.cluster = kwargs['cluster'] def execute(self, path): """ :param audio_item: {"path": "xxx"} :return: """ audio_type = AudioType.LOCAL text = "" asr_http_client = AsrWsClient( audio_path=path, cluster= self.cluster, appid = self.appid, token = self.token, audio_type=audio_type, ) try: result = asyncio.run(asr_http_client.execute()) if result['payload_msg']['code'] == 1000: text = result["payload_msg"]["result"][0]["text"] except Exception as e: text = "" return text class VolcengineTTS(object): def __init__(self, appid, token, cluster, voice_type) -> None: self.appid, self.token, self.cluster, self.voice_type = appid, token, cluster, voice_type def execute(self, text): api_url = "https://openspeech.bytedance.com/api/v1/tts" header = {"Authorization": f"Bearer;{self.token}"} request_json = { "app": { "appid": self.appid, "token": self.token, "cluster": self.cluster }, "user": { "uid": "388808087185088" }, "audio": { "voice_type": self.voice_type, "encoding": "mp3", "speed_ratio": 1.0, "volume_ratio": 1.0, "pitch_ratio": 1.0, }, "request": { "reqid": str(uuid.uuid4()), "text": text, "text_type": "plain", "operation": "query", "with_frontend": 1, "frontend_type": "unitTson" } } try: resp = requests.post(api_url, json.dumps(request_json), headers=header) if "data" in resp.json(): data = resp.json()["data"] return base64.b64decode(data) except Exception as e: e.with_traceback() return None ================================================ FILE: robot/sdk/XunfeiSpeech.py ================================================ import websocket import hashlib import base64 import hmac import json import wave import tempfile from urllib.parse import urlencode import time import ssl from wsgiref.handlers import format_date_time from datetime import datetime from time import mktime import _thread as thread from robot import logging logger = logging.getLogger(__name__) STATUS_FIRST_FRAME = 0 # 第一帧的标识 STATUS_CONTINUE_FRAME = 1 # 中间帧标识 STATUS_LAST_FRAME = 2 # 最后一帧的标识 asrWsParam = None ttsWsParam = None gResult = "" gTTSResult = "" class ASR_Ws_Param(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, AudioFile): # 控制台鉴权信息 self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.AudioFile = AudioFile # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin"} # 生成url def create_url(self): url = "wss://ws-api.xfyun.cn/v2/iat" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\n" signature_origin += "date: " + date + "\n" signature_origin += "GET " + "/v2/iat " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new( self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256, ).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = ( 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha) ) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode( encoding="utf-8" ) # 将请求的鉴权参数组合为字典 v = {"authorization": authorization, "date": date, "host": "ws-api.xfyun.cn"} # 拼接鉴权参数,生成url url = url + "?" + urlencode(v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 logger.debug("websocket url :", url) return url class TTS_Ws_Param(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, Text, voice_name="xiaoyan"): self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.Text = Text # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = { "aue": "raw", "auf": "audio/L16;rate=16000", "vcn": voice_name, "tte": "utf8", } self.Data = { "status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8"), } # 生成url def create_url(self): url = "wss://tts-api.xfyun.cn/v2/tts" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\n" signature_origin += "date: " + date + "\n" signature_origin += "GET " + "/v2/tts " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new( self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256, ).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = ( 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha) ) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode( encoding="utf-8" ) # 将请求的鉴权参数组合为字典 v = {"authorization": authorization, "date": date, "host": "ws-api.xfyun.cn"} # 拼接鉴权参数,生成url url = url + "?" + urlencode(v) # print("date: ",date) # print("v: ",v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url # ASR 收到websocket消息的处理 def asr_on_message(ws, message): global gResult try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] if code != 0: errMsg = json.loads(message)["message"] logger.critical( "xunfei-asr 识别出错了:sid:%s call error:%s code is:%s" % (sid, errMsg, code), stack_info=True, ) else: data = json.loads(message)["data"]["result"]["ws"] result = "" for i in data: for w in i["cw"]: result += w["w"] gResult = gResult + result logger.info( "sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False)) ) except Exception as e: logger.critical(f"xunfei-asr 识别出错了:{e}", stack_info=True) # ASR 收到websocket错误的处理 def asr_on_error(ws, error): logger.error("xunfei-asr 识别出错:", error) # ASR 收到websocket关闭的处理 def asr_on_close(ws, _foo, _bar): logger.debug("### closed ###") # ASR 收到websocket连接建立的处理 def asr_on_open(ws): global asrWsParam def run(*args): frameSize = 1220 # 每一帧的音频大小 intervel = 0.04 # 发送音频间隔(单位:s) status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧 with open(asrWsParam.AudioFile, "rb") as fp: while True: buf = fp.read(frameSize) # 文件结束 if not buf: status = STATUS_LAST_FRAME # 第一帧处理 # 发送第一帧音频,带business 参数 # appid 必须带上,只需第一帧发送 if status == STATUS_FIRST_FRAME: d = { "common": asrWsParam.CommonArgs, "business": asrWsParam.BusinessArgs, "data": { "status": 0, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw", }, } d = json.dumps(d) ws.send(d) status = STATUS_CONTINUE_FRAME # 中间帧处理 elif status == STATUS_CONTINUE_FRAME: d = { "data": { "status": 1, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw", } } ws.send(json.dumps(d)) # 最后一帧处理 elif status == STATUS_LAST_FRAME: d = { "data": { "status": 2, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw", } } ws.send(json.dumps(d)) time.sleep(1) break # 模拟音频采样间隔 time.sleep(intervel) ws.close() thread.start_new_thread(run, ()) # 收到websocket消息的处理 def tts_on_message(ws, message): try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] audio = json.loads(message)["data"]["audio"] audio = base64.b64decode(audio) if code != 0: errMsg = json.loads(message)["message"] logger.error("sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: with open(gTTSPath, "ab") as f: f.write(audio) except Exception as e: logger.error("receive msg,but parse exception:", e) # 收到websocket错误的处理 def tts_on_error(ws, error): logger.error("xunfei-tts 合成出错:", error) # 收到websocket关闭的处理 def tts_on_close(ws, _foo, _bar): global gTTSResult logger.debug("### closed ###") pcmdata = None try: with open(gTTSPath, "rb") as pcmfile: pcmdata = pcmfile.read() tmpfile = "" with tempfile.NamedTemporaryFile() as f: tmpfile = f.name with wave.open(tmpfile, "wb") as wavfile: wavfile.setparams((1, 2, 16000, 0, "NONE", "NONE")) wavfile.writeframes(pcmdata) gTTSResult = tmpfile except Exception as e: logger.error(f"XunfeiSpeech error: {e}", stack_info=True) # 收到websocket连接建立的处理 def tts_on_open(ws): global ttsWsParam def run(*args): intervel = 2 # 等待结果间隔(单位:s) d = { "common": ttsWsParam.CommonArgs, "business": ttsWsParam.BusinessArgs, "data": ttsWsParam.Data, } d = json.dumps(d) ws.send(d) # sleep等待服务端返回结果 time.sleep(intervel) ws.close() thread.start_new_thread(run, ()) def transcribe(fpath, appid, api_key, api_secret): """ 科大讯飞ASR """ global asrWsParam, gResult gResult = "" asrWsParam = ASR_Ws_Param(appid, api_key, APISecret=api_secret, AudioFile=fpath) websocket.enableTrace(False) wsUrl = asrWsParam.create_url() ws = websocket.WebSocketApp( wsUrl, on_message=asr_on_message, on_error=asr_on_error, on_close=asr_on_close ) ws.on_open = asr_on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) return gResult def synthesize(msg, appid, api_key, api_secret, voice_name="xiaoyan"): """ 科大讯飞TTS """ global ttsWsParam, gTTSPath, gTTSResult with tempfile.NamedTemporaryFile() as f: gTTSPath = f.name ttsWsParam = TTS_Ws_Param( APPID=appid, APIKey=api_key, APISecret=api_secret, Text=msg, voice_name=voice_name, ) websocket.enableTrace(False) wsUrl = ttsWsParam.create_url() ws = websocket.WebSocketApp( wsUrl, on_message=tts_on_message, on_error=tts_on_error, on_close=tts_on_close ) ws.on_open = tts_on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) return gTTSResult ================================================ FILE: robot/sdk/__init__.py ================================================ ================================================ FILE: robot/sdk/atc.py ================================================ # # -*- coding=utf-8 -*- # digit=['零','一','二','三','四','五','六','七','八','九'] # unit=['零','十','百','千','万','亿'] # def arabic_to_chinese(number): # if number < 0: # raise Exception("negative arg") # if number < 10: # return digit[number] # elif number < 100: # h = number // 10 # if h != 1: # return str(h) + "十" + arabic_to_chinese(number % 10) # else: # return "十" + arabic_to_chinese(number % 10) # elif number < 1000: # th = number // 100 # return str(th) + "百" + arabic_to_chinese(number % 100) # elif number < 10000: # w = number // 1000 # return str(w) + "千" + arabic_to_chinese(number % 1000) # else: # pass # c = 1 # def test(num, expected): # global c # actual = arabic_to_chinese(num) # if (actual != expected): # print(c, actual, expected) # else: # print(c, "pass") # c+=1 # test(0, '零') # test(1, '一') # test(5, '五') # test(12, '十二') # test(30, '三十') # test(37, '三十七') # test(100, '一百') # test(150,'一百五十') # test(156,'一百五十六') # test(999,'九百九十九') # test(1000 ,'一千') # test(1001 ,'一千零一') # test(1001 ,'一千零一') # -*- coding: utf-8 -*- # Licensed under WTFPL or the Unlicense or CC0. # This uses Python 3, but it's easy to port to Python 2 by changing # strings to u'xx'. import itertools def num2chinese(num, big=False, simp=True, o=False, twoalt=False): """ Converts numbers to Chinese representations. `big` : use financial characters. `simp` : use simplified characters instead of traditional characters. `o` : use 〇 for zero. `twoalt`: use 两/兩 for two when appropriate. Note that `o` and `twoalt` is ignored when `big` is used, and `twoalt` is ignored when `o` is used for formal representations. """ # check num first nd = str(num) if abs(float(nd)) >= 1e48: raise ValueError("number out of range") elif "e" in nd: raise ValueError("scientific notation is not supported") c_symbol = "正负点" if simp else "正負點" if o: # formal twoalt = False if big: c_basic = "零壹贰叁肆伍陆柒捌玖" if simp else "零壹貳參肆伍陸柒捌玖" c_unit1 = "拾佰仟" c_twoalt = "贰" if simp else "貳" else: c_basic = "〇一二三四五六七八九" if o else "零一二三四五六七八九" c_unit1 = "十百千" if twoalt: c_twoalt = "两" if simp else "兩" else: c_twoalt = "二" c_unit2 = "万亿兆京垓秭穰沟涧正载" if simp else "萬億兆京垓秭穰溝澗正載" revuniq = lambda l: "".join(k for k, g in itertools.groupby(reversed(l))) nd = str(num) result = [] if nd[0] == "+": result.append(c_symbol[0]) elif nd[0] == "-": result.append(c_symbol[1]) if "." in nd: integer, remainder = nd.lstrip("+-").split(".") else: integer, remainder = nd.lstrip("+-"), None if int(integer): splitted = [integer[max(i - 4, 0) : i] for i in range(len(integer), 0, -4)] intresult = [] for nu, unit in enumerate(splitted): # special cases if int(unit) == 0: # 0000 intresult.append(c_basic[0]) continue elif nu > 0 and int(unit) == 2: # 0002 intresult.append(c_twoalt + c_unit2[nu - 1]) continue ulist = [] unit = unit.zfill(4) for nc, ch in enumerate(reversed(unit)): if ch == "0": if ulist: # ???0 ulist.append(c_basic[0]) elif nc == 0: ulist.append(c_basic[int(ch)]) elif nc == 1 and ch == "1" and unit[1] == "0": # special case for tens # edit the 'elif' if you don't like # 十四, 三千零十四, 三千三百一十四 ulist.append(c_unit1[0]) elif nc > 1 and ch == "2": ulist.append(c_twoalt + c_unit1[nc - 1]) else: ulist.append(c_basic[int(ch)] + c_unit1[nc - 1]) ustr = revuniq(ulist) if nu == 0: intresult.append(ustr) else: intresult.append(ustr + c_unit2[nu - 1]) result.append(revuniq(intresult).strip(c_basic[0])) else: result.append(c_basic[0]) if remainder: result.append(c_symbol[2]) result.append("".join(c_basic[int(ch)] for ch in remainder)) return "".join(result) ================================================ FILE: robot/sdk/unit.py ================================================ # encoding:utf-8 import os import uuid import json import requests import datetime from uuid import getnode as get_mac from robot import constants, logging from dateutil import parser as dparser logger = logging.getLogger(__name__) def get_token(api_key, secret_key): cache = open(os.path.join(constants.TEMP_PATH, "baidustt.ini"), "a+") try: pms = cache.readlines() if len(pms) > 0: time = pms[0] tk = pms[1] # 计算token是否过期 官方说明一个月,这里保守29天 time = dparser.parse(time) endtime = datetime.datetime.now() if (endtime - time).days <= 29: return tk finally: cache.close() URL = "http://openapi.baidu.com/oauth/2.0/token" params = { "grant_type": "client_credentials", "client_id": api_key, "client_secret": secret_key, } r = requests.get(URL, params=params) try: r.raise_for_status() token = r.json()["access_token"] return token except requests.exceptions.HTTPError: return "" def getUnit(query, service_id, api_key, secret_key): """ NLU 解析 :param query: 用户的指令字符串 :param service_id: UNIT 的 service_id :param api_key: UNIT apk_key :param secret_key: UNIT secret_key :returns: UNIT 解析结果。如果解析失败,返回 None """ access_token = get_token(api_key, secret_key) url = ( "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + access_token ) request = {"query": query, "user_id": str(get_mac())[:32]} body = { "log_id": str(uuid.uuid1()), "version": "2.0", "service_id": service_id, "session_id": str(uuid.uuid1()), "request": request, } try: headers = {"Content-Type": "application/json"} request = requests.post(url, json=body, headers=headers) return json.loads(request.text) except Exception: return None def getIntent(parsed): """ 提取意图 :param parsed: UNIT 解析结果 :returns: 意图数组 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: try: return parsed["result"]["response_list"][0]["schema"]["intent"] except Exception as e: logger.warning(e) return "" else: return "" def hasIntent(parsed, intent): """ 判断是否包含某个意图 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: True: 包含; False: 不包含 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] for response in response_list: if ( "schema" in response and "intent" in response["schema"] and response["schema"]["intent"] == intent ): return True return False else: return False def getSlots(parsed, intent=""): """ 提取某个意图的所有词槽 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: 词槽列表。你可以通过 name 属性筛选词槽, 再通过 normalized_word 属性取出相应的值 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] if intent == "": try: return parsed["result"]["response_list"][0]["schema"]["slots"] except Exception as e: logger.warning(e) return [] for response in response_list: if ( "schema" in response and "intent" in response["schema"] and "slots" in response["schema"] and response["schema"]["intent"] == intent ): return response["schema"]["slots"] return [] else: return [] def getSlotWords(parsed, intent, name): """ 找出命中某个词槽的内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ slots = getSlots(parsed, intent) words = [] for slot in slots: if slot["name"] == name: words.append(slot["normalized_word"]) return words def getSlotOriginalWords(parsed, intent, name): """ 找出命中某个词槽的原始内容 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :param name: 词槽名 :returns: 命中该词槽的值的列表。 """ slots = getSlots(parsed, intent) words = [] for slot in slots: if slot["name"] == name: words.append(slot["original_word"]) return words def getSayByConfidence(parsed): """ 提取 UNIT 置信度最高的回复文本 :param parsed: UNIT 解析结果 :returns: UNIT 的回复文本 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] answer = {} for response in response_list: if ( "schema" in response and "intent_confidence" in response["schema"] and ( not answer or response["schema"]["intent_confidence"] > answer["schema"]["intent_confidence"] ) ): answer = response return answer["action_list"][0]["say"] else: return "" def getSay(parsed, intent=""): """ 提取 UNIT 的回复文本 :param parsed: UNIT 解析结果 :param intent: 意图的名称 :returns: UNIT 的回复文本 """ if parsed and "result" in parsed and "response_list" in parsed["result"]: response_list = parsed["result"]["response_list"] if intent == "": try: return response_list[0]["action_list"][0]["say"] except Exception as e: logger.warning(e) return "" for response in response_list: if ( "schema" in response and "intent" in response["schema"] and response["schema"]["intent"] == intent ): try: return response["action_list"][0]["say"] except Exception as e: logger.warning(e) return "" return "" else: return "" if __name__ == "__main__": parsed = getUnit( "今天的天气", "S13442", "w5v7gUV3iPGsGntcM84PtOOM", "KffXwW6E1alcGplcabcNs63Li6GvvnfL", ) print(parsed) ================================================ FILE: robot/statistic.py ================================================ # -*- coding: utf -8-*- from . import config import uuid import requests import threading def getUUID(): mac = uuid.UUID(int=uuid.getnode()).hex[-12:] return ":".join([mac[e : e + 2] for e in range(0, 11, 2)]) def report(t): ReportThread(t).start() class ReportThread(threading.Thread): def __init__(self, t): # 需要执行父类的初始化方法 threading.Thread.__init__(self) self.t = t def run(self): to_report = config.get("statistic", True) if to_report: try: persona = config.get("robot_name_cn", "孙悟空") url = "http://livecv.hahack.com:8022/statistic" payload = { "type": str(self.t), "uuid": getUUID(), "name": persona, "project": "wukong", } requests.post(url, data=payload, timeout=3) except Exception: return ================================================ FILE: robot/utils.py ================================================ # -*- coding: utf-8 -*- import os import tempfile import wave import shutil import re import time import json import yaml import hashlib import subprocess from . import constants, config from robot import logging from pydub import AudioSegment from pytz import timezone import _thread as thread import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart logger = logging.getLogger(__name__) do_not_bother = False is_recordable = True def sendEmail( SUBJECT, BODY, ATTACH_LIST, TO, FROM, SENDER, PASSWORD, SMTP_SERVER, SMTP_PORT ): """ 发送邮件 :param SUBJECT: 邮件标题 :param BODY: 邮件正文 :param ATTACH_LIST: 附件 :param TO: 收件人 :param FROM: 发件人 :param SENDER: 发件人信息 :param PASSWORD: 密码 :param SMTP_SERVER: smtp 服务器 :param SMTP_PORT: smtp 端口号 :returns: True: 发送成功; False: 发送失败 """ txt = MIMEText(BODY.encode("utf-8"), "html", "utf-8") msg = MIMEMultipart() msg.attach(txt) for attach in ATTACH_LIST: try: att = MIMEText(open(attach, "rb").read(), "base64", "utf-8") filename = os.path.basename(attach) att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = 'attachment; filename="%s"' % filename msg.attach(att) except Exception: logger.error(f"附件 {attach} 发送失败!", stack_info=True) continue msg["From"] = SENDER msg["To"] = TO msg["Subject"] = SUBJECT try: session = smtplib.SMTP(SMTP_SERVER) session.connect(SMTP_SERVER, SMTP_PORT) session.starttls() session.login(FROM, PASSWORD) session.sendmail(SENDER, TO, msg.as_string()) session.close() return True except Exception as e: logger.error(e, stack_info=True) return False def emailUser(SUBJECT="", BODY="", ATTACH_LIST=[]): """ 给用户发送邮件 :param SUBJECT: subject line of the email :param BODY: body text of the email :returns: True: 发送成功; False: 发送失败 """ # add footer if BODY: BODY = "%s,

这是您要的内容:
%s
" % (config["first_name"], BODY) recipient = config.get("/email/address", "") robot_name = config.get("robot_name_cn", "wukong-robot") recipient = robot_name + " <%s>" % recipient user = config.get("/email/address", "") password = config.get("/email/password", "") server = config.get("/email/smtp_server", "") port = config.get("/email/smtp_port", "") if not recipient or not user or not password or not server or not port: return False try: sendEmail( SUBJECT, BODY, ATTACH_LIST, user, user, recipient, password, server, port ) return True except Exception as e: logger.error(e, stack_info=True) return False def get_file_content(filePath, flag="rb"): """ 读取文件内容并返回 :param filePath: 文件路径 :returns: 文件内容 :raises IOError: 读取失败则抛出 IOError """ with open(filePath, flag) as fp: return fp.read() def check_and_delete(fp, wait=0): """ 检查并删除文件/文件夹 :param fp: 文件路径 """ def run(): if wait > 0: time.sleep(wait) if isinstance(fp, str) and os.path.exists(fp): if os.path.isfile(fp): os.remove(fp) else: shutil.rmtree(fp) thread.start_new_thread(run, ()) def write_temp_file(data, suffix, mode="w+b"): """ 写入临时文件 :param data: 数据 :param suffix: 后缀名 :param mode: 写入模式,默认为 w+b :returns: 文件保存后的路径 """ with tempfile.NamedTemporaryFile(mode=mode, suffix=suffix, delete=False) as f: f.write(data) tmpfile = f.name return tmpfile def get_pcm_from_wav(wav_path): """ 从 wav 文件中读取 pcm :param wav_path: wav 文件路径 :returns: pcm 数据 """ wav = wave.open(wav_path, "rb") return wav.readframes(wav.getnframes()) def convert_wav_to_mp3(wav_path): """ 将 wav 文件转成 mp3 :param wav_path: wav 文件路径 :returns: mp3 文件路径 """ if not os.path.exists(wav_path): logger.critical(f"文件错误 {wav_path}", stack_info=True) return None mp3_path = wav_path.replace(".wav", ".mp3") AudioSegment.from_wav(wav_path).export(mp3_path, format="mp3") return mp3_path def convert_mp3_to_wav(mp3_path): """ 将 mp3 文件转成 wav :param mp3_path: mp3 文件路径 :returns: wav 文件路径 """ target = mp3_path.replace(".mp3", ".wav") if not os.path.exists(mp3_path): logger.critical(f"文件错误 {mp3_path}", stack_info=True) return None AudioSegment.from_mp3(mp3_path).export(target, format="wav") return target def clean(): """清理垃圾数据""" temp = constants.TEMP_PATH temp_files = os.listdir(temp) for f in temp_files: if os.path.isfile(os.path.join(temp, f)) and re.match( r"output[\d]*\.wav", os.path.basename(f) ): os.remove(os.path.join(temp, f)) def setRecordable(value): """设置是否可以开始录制语音""" global is_recordable is_recordable = value def isRecordable(): """是否可以开始录制语音""" global is_recordable return is_recordable def is_proper_time(): """是否合适时间""" global do_not_bother if do_not_bother == True: return False if not config.has("do_not_bother"): return True bother_profile = config.get("do_not_bother") if not bother_profile["enable"]: return True if "since" not in bother_profile or "till" not in bother_profile: return True since = bother_profile["since"] till = bother_profile["till"] current = time.localtime(time.time()).tm_hour if till > since: return current not in range(since, till) else: return not (current in range(since, 25) or current in range(-1, till)) def get_do_not_bother_on_hotword(): """打开勿扰模式唤醒词""" return config.get("/do_not_bother/on_hotword", "悟空别吵.pmdl") def get_do_not_bother_off_hotword(): """关闭勿扰模式唤醒词""" return config.get("/do_not_bother/off_hotword", "悟空醒醒.pmdl") def getTimezone(): """获取时区""" return timezone(config.get("timezone", "HKT")) def getTimemStap(): """获取时间戳""" return str(time.time()).replace(".", "") def getCache(msg): """获取缓存的语音""" md5 = hashlib.md5(msg.encode("utf-8")).hexdigest() cache_paths = [ os.path.join(constants.TEMP_PATH, md5 + ext) for ext in [".mp3", ".wav", ".asiff"] ] return next((path for path in cache_paths if os.path.exists(path)), None) def saveCache(voice, msg): """获取缓存的语音""" _, ext = os.path.splitext(voice) md5 = hashlib.md5(msg.encode("utf-8")).hexdigest() target = os.path.join(constants.TEMP_PATH, md5 + ext) shutil.copyfile(voice, target) return target def lruCache(): """清理最近未使用的缓存""" def run(*args): if config.get("/lru_cache/enable", True): days = config.get("/lru_cache/days", 7) subprocess.run( 'find . -name "*.mp3" -atime +%d -exec rm {} \;' % days, cwd=constants.TEMP_PATH, shell=True, ) thread.start_new_thread(run, ()) def validyaml(filename): """ 校验 YAML 格式是否正确 :param filename: yaml文件路径 :returns: True: 正确; False: 不正确 """ try: with open(filename) as f: str = f.read() yaml.safe_load(str) return True except Exception: return False def validjson(s): """ 校验某个 JSON 字符串是否正确 :param s: JOSN字符串 :returns: True: 正确; False: 不正确 """ try: json.loads(s) return True except Exception: return False def getPunctuations(): return [",", ",", ".", "。", "?", "?", "!", "!", "\n"] def stripPunctuation(s): """ 移除字符串末尾的标点 """ punctuations = getPunctuations() if any(s.endswith(p) for p in punctuations): s = s[:-1] return s ================================================ FILE: server/server.py ================================================ import os import yaml import json import time import base64 import random import hashlib import asyncio import requests import markdown import threading import subprocess import tornado.web import tornado.ioloop import tornado.options import tornado.httpserver from tornado.websocket import WebSocketHandler from urllib.parse import unquote from robot.sdk.History import History from robot import config, utils, logging, Updater, constants from tools import make_json, solr_tools logger = logging.getLogger(__name__) conversation, wukong = None, None commiting = False suggestions = [ "现在几点", "你吃饭了吗", "上海的天气", "写一首关于大海的诗", "来玩成语接龙", "我有多少邮件", "你叫什么名字", "讲个笑话", ] class BaseHandler(tornado.web.RequestHandler): def isValidated(self): if not self.get_secure_cookie("validation"): return False return str( self.get_secure_cookie("validation"), encoding="utf-8" ) == config.get("/server/validate", "") def validate(self, validation): if validation and '"' in validation: validation = validation.replace('"', "") return validation == config.get("/server/validate", "") or validation == str( self.get_cookie("validation") ) class MainHandler(BaseHandler): def get(self): global conversation, wukong, suggestions if not self.isValidated(): self.redirect("/login") return if conversation: info = Updater.fetch() suggestion = random.choice(suggestions) notices = None if "notices" in info: notices = info["notices"] self.render( "index.html", update_info=info, suggestion=suggestion, notices=notices, location=self.request.host, ) else: self.render("index.html") class MessageUpdatesHandler(BaseHandler): """Long-polling request for new messages. Waits until new messages are available before returning anything. """ async def post(self): if not self.validate(self.get_argument("validate", default=None)): res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) else: cursor = self.get_argument("cursor", None) history = History() messages = history.get_messages_since(cursor) while not messages: # Save the Future returned here so we can cancel it in # on_connection_close. self.wait_future = history.cond.wait(timeout=1) try: await self.wait_future except asyncio.CancelledError: return messages = history.get_messages_since(cursor) if self.request.connection.stream.closed(): return res = {"code": 0, "message": "ok", "history": json.dumps(messages)} self.write(json.dumps(res)) self.finish() def on_connection_close(self): self.wait_future.cancel() """ 负责跟前端通信,把机器人的响应内容传输给前端 """ class ChatWebSocketHandler(WebSocketHandler, BaseHandler): clients = set() def open(self): self.clients.add(self) def on_close(self): self.clients.remove(self) def send_response(self, msg, uuid, plugin=""): response = { "action": "new_message", "type": 1, "text": msg, "uuid": uuid, "plugin": plugin, } self.write_message(json.dumps(response)) class ChatHandler(BaseHandler): def onResp(self, msg, audio, plugin): logger.info(f"response msg: {msg}") res = { "code": 0, "message": "ok", "resp": msg, "audio": audio, "plugin": plugin, } try: self.write(json.dumps(res)) self.flush() except: pass def onStream(self, data, uuid): # 通过 ChatWebSocketHandler 发送给前端 for client in ChatWebSocketHandler.clients: client.send_response(data, uuid, "") def post(self): global conversation if self.validate(self.get_argument("validate", default=None)): if self.get_argument("type") == "text": query = self.get_argument("query") uuid = self.get_argument("uuid") if query == "": res = {"code": 1, "message": "query text is empty"} self.write(json.dumps(res)) else: conversation.doResponse( query, uuid, onSay=lambda msg, audio, plugin: self.onResp( msg, audio, plugin ), onStream=lambda data, resp_uuid: self.onStream(data, resp_uuid), ) elif self.get_argument("type") == "voice": voice_data = self.get_argument("voice") tmpfile = utils.write_temp_file(base64.b64decode(voice_data), ".wav") fname, suffix = os.path.splitext(tmpfile) nfile = fname + "-16k" + suffix # downsampling soxCall = "sox " + tmpfile + " " + nfile + " rate 16k" subprocess.call([soxCall], shell=True, close_fds=True) utils.check_and_delete(tmpfile) conversation.doConverse( nfile, onSay=lambda msg, audio, plugin: self.onResp(msg, audio, plugin), onStream=lambda data, resp_uuid: self.onStream( data, resp_uuid) ) else: res = {"code": 1, "message": "illegal type"} self.write(json.dumps(res)) else: res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) self.finish() class GetHistoryHandler(BaseHandler): def get(self): global conversation if not self.validate(self.get_argument("validate", default=None)): res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) else: res = { "code": 0, "message": "ok", "history": json.dumps(conversation.getHistory().cache), } self.write(json.dumps(res)) self.finish() class GetLogHandler(BaseHandler): def get(self): if not self.validate(self.get_argument("validate", default=None)): res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) else: lines = self.get_argument("lines", default=200) res = {"code": 0, "message": "ok", "log": logging.readLog(lines)} self.write(json.dumps(res)) self.finish() class LogPageHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") else: self.render("log.html") class OperateHandler(BaseHandler): def post(self): global wukong if self.validate(self.get_argument("validate", default=None)): type = self.get_argument("type") if type in ["restart", "0"]: res = {"code": 0, "message": "ok"} self.write(json.dumps(res)) self.finish() time.sleep(3) wukong.restart() else: res = {"code": 1, "message": f"illegal type {type}"} self.write(json.dumps(res)) self.finish() else: res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) self.finish() class ConfigPageHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") else: self.render("config.html", sensitivity=config.get("sensitivity")) class ConfigHandler(BaseHandler): def get(self): if not self.validate(self.get_argument("validate", default=None)): res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) else: key = self.get_argument("key", default="") res = "" if key == "": res = { "code": 0, "message": "ok", "config": config.getText(), "sensitivity": config.get("sensitivity", 0.5), } else: res = {"code": 0, "message": "ok", "value": config.get(key)} self.write(json.dumps(res)) self.finish() def post(self): if self.validate(self.get_argument("validate", default=None)): configStr = self.get_argument("config") try: cfg = unquote(configStr) yaml.safe_load(cfg) config.dump(cfg) res = {"code": 0, "message": "ok"} self.write(json.dumps(res)) except: res = {"code": 1, "message": "YAML解析失败,请检查内容"} self.write(json.dumps(res)) else: res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) self.finish() class DonateHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") return r = requests.get( "https://raw.githubusercontent.com/wzpan/wukong-contrib/master/docs/donate.md" ) content = markdown.markdown( r.text, extensions=["codehilite", "tables", "fenced_code", "meta", "nl2br", "toc"], ) self.render("donate.html", content=content) class QAHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") else: content = "" with open(constants.getQAPath(), "r") as f: content = f.read() self.render("qa.html", content=content) def post(self): if self.validate(self.get_argument("validate", default=None)): qaStr = self.get_argument("qa") qaJson = os.path.join(constants.TEMP_PATH, "qa_json") try: make_json.convert(qaStr, qaJson) solr_tools.clear_documents( config.get("/anyq/host", "0.0.0.0"), "collection1", config.get("/anyq/solr_port", "8900"), ) solr_tools.upload_documents( config.get("/anyq/host", "0.0.0.0"), "collection1", config.get("/anyq/solr_port", "8900"), qaJson, 10, ) with open(constants.getQAPath(), "w") as f: f.write(qaStr) res = {"code": 0, "message": "ok"} self.write(json.dumps(res)) except Exception as e: logger.error(e, stack_info=True) res = {"code": 1, "message": "提交失败,请检查内容"} self.write(json.dumps(res)) else: res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) self.finish() class APIHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") else: content = "" r = requests.get( "https://raw.githubusercontent.com/wzpan/wukong-contrib/master/docs/api.md" ) content = markdown.markdown( r.text, extensions=[ "codehilite", "tables", "fenced_code", "meta", "nl2br", "toc", ], ) self.render("api.html", content=content) class UpdateHandler(BaseHandler): def post(self): global wukong if self.validate(self.get_argument("validate", default=None)): if wukong.update(): res = {"code": 0, "message": "ok"} self.write(json.dumps(res)) self.finish() time.sleep(3) wukong.restart() else: res = {"code": 1, "message": "更新失败,请手动更新"} self.write(json.dumps(res)) else: res = {"code": 1, "message": "illegal visit"} self.write(json.dumps(res)) self.finish() class LoginHandler(BaseHandler): def get(self): if self.isValidated(): self.redirect("/") else: self.render("login.html", error=None) def post(self): if self.get_argument("username") == config.get( "/server/username" ) and hashlib.md5( self.get_argument("password").encode("utf-8") ).hexdigest() == config.get( "/server/validate" ): logger.info("login success") self.set_secure_cookie("validation", config.get("/server/validate")) self.redirect("/") else: self.render("login.html", error="登录失败") class LogoutHandler(BaseHandler): def get(self): if self.isValidated(): self.set_secure_cookie("validation", "") self.redirect("/login") settings = { "cookie_secret": config.get( "/server/cookie_secret", "__GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__" ), "template_path": os.path.join(constants.APP_PATH, "server/templates"), "static_path": os.path.join(constants.APP_PATH, "server/static"), "login_url": "/login", "debug": False, } application = tornado.web.Application( [ (r"/", MainHandler), (r"/login", LoginHandler), (r"/history", GetHistoryHandler), (r"/chat", ChatHandler), (r"/websocket", ChatWebSocketHandler), (r"/chat/updates", MessageUpdatesHandler), (r"/config", ConfigHandler), (r"/configpage", ConfigPageHandler), (r"/operate", OperateHandler), (r"/logpage", LogPageHandler), (r"/log", GetLogHandler), (r"/logout", LogoutHandler), (r"/api", APIHandler), (r"/qa", QAHandler), (r"/upgrade", UpdateHandler), (r"/donate", DonateHandler), # 废弃老接口 (r"/getlog", GetLogHandler), (r"/gethistory", GetHistoryHandler), (r"/getconfig", ConfigHandler), ( r"/photo/(.+\.(?:png|jpg|jpeg|bmp|gif|JPG|PNG|JPEG|BMP|GIF))", tornado.web.StaticFileHandler, {"path": config.get("/camera/dest_path", "server/static")}, ), ( r"/audio/(.+\.(?:mp3|wav|pcm))", tornado.web.StaticFileHandler, {"path": constants.TEMP_PATH}, ), (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "server/static"}), ], **settings, ) def start_server(con, wk): global conversation, wukong conversation = con wukong = wk if config.get("/server/enable", False): port = config.get("/server/port", "5001") try: asyncio.set_event_loop(asyncio.new_event_loop()) application.listen(int(port)) tornado.ioloop.IOLoop.instance().start() except Exception as e: logger.critical(f"服务器启动失败: {e}", stack_info=True) def run(conversation, wukong, debug=False): settings["debug"] = debug t = threading.Thread(target=lambda: start_server(conversation, wukong)) t.start() ================================================ FILE: server/static/api.css ================================================ table { margin-top:15px; border-collapse:collapse; border:1px solid #aaa; width:100%; margin-bottom:2em; } table th { vertical-align:baseline; padding:5px 15px 5px 6px; background-color:#3F3F3F; border:1px solid #3F3F3F; text-align:left; color:#fff; } table td { vertical-align:middle; padding:6px 15px 6px 6px; border:1px solid #aaa; } table tr:nth-child(odd) { background-color:#F5F5F5; } table tr:nth-child(even) { background-color:#fff; } h1{ line-height:1.2em; } h2 { margin-top:1em; margin-bottom:0.6667em; } h1,h2,h3,h4,h5,h6{ text-rendering:optimizelegibility; font-weight:bold } pre { word-break: break-all; white-space: pre-wrap; } ================================================ FILE: server/static/bootbox.js ================================================ /** * bootbox.js [v4.4.0] * * http://bootboxjs.com/license.txt */ // @see https://github.com/makeusabrew/bootbox/issues/180 // @see https://github.com/makeusabrew/bootbox/issues/186 (function (root, factory) { "use strict"; if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery"], factory); } else if (typeof exports === "object") { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { // Browser globals (root is window) root.bootbox = factory(root.jQuery); } }(this, function init($, undefined) { "use strict"; // the base DOM structure needed to create a modal var templates = { dialog: "", header: "", footer: "", closeButton: "", form: "
", inputs: { text: "", textarea: "", email: "", select: "", checkbox: "
", date: "", time: "", number: "", password: "" } }; var defaults = { // default language locale: "en", // show backdrop or not. Default to static so user has to interact with dialog backdrop: "static", // animate the modal in/out animate: true, // additional class string applied to the top level dialog className: null, // whether or not to include a close button closeButton: true, // show the dialog immediately by default show: true, // dialog container container: "body" }; // our public object; augmented after our private API var exports = {}; /** * @private */ function _t(key) { var locale = locales[defaults.locale]; return locale ? locale[key] : locales.en[key]; } function processCallback(e, dialog, callback) { e.stopPropagation(); e.preventDefault(); // by default we assume a callback will get rid of the dialog, // although it is given the opportunity to override this // so, if the callback can be invoked and it *explicitly returns false* // then we'll set a flag to keep the dialog active... var preserveDialog = $.isFunction(callback) && callback.call(dialog, e) === false; // ... otherwise we'll bin it if (!preserveDialog) { dialog.modal("hide"); } } function getKeyLength(obj) { // @TODO defer to Object.keys(x).length if available? var k, t = 0; for (k in obj) { t ++; } return t; } function each(collection, iterator) { var index = 0; $.each(collection, function(key, value) { iterator(key, value, index++); }); } function sanitize(options) { var buttons; var total; if (typeof options !== "object") { throw new Error("Please supply an object of options"); } if (!options.message) { throw new Error("Please specify a message"); } // make sure any supplied options take precedence over defaults options = $.extend({}, defaults, options); if (!options.buttons) { options.buttons = {}; } buttons = options.buttons; total = getKeyLength(buttons); each(buttons, function(key, button, index) { if ($.isFunction(button)) { // short form, assume value is our callback. Since button // isn't an object it isn't a reference either so re-assign it button = buttons[key] = { callback: button }; } // before any further checks make sure by now button is the correct type if ($.type(button) !== "object") { throw new Error("button with key " + key + " must be an object"); } if (!button.label) { // the lack of an explicit label means we'll assume the key is good enough button.label = key; } if (!button.className) { if (total <= 2 && index === total-1) { // always add a primary to the main option in a two-button dialog button.className = "btn-primary"; } else { button.className = "btn-default"; } } }); return options; } /** * map a flexible set of arguments into a single returned object * if args.length is already one just return it, otherwise * use the properties argument to map the unnamed args to * object properties * so in the latter case: * mapArguments(["foo", $.noop], ["message", "callback"]) * -> { message: "foo", callback: $.noop } */ function mapArguments(args, properties) { var argn = args.length; var options = {}; if (argn < 1 || argn > 2) { throw new Error("Invalid argument length"); } if (argn === 2 || typeof args[0] === "string") { options[properties[0]] = args[0]; options[properties[1]] = args[1]; } else { options = args[0]; } return options; } /** * merge a set of default dialog options with user supplied arguments */ function mergeArguments(defaults, args, properties) { return $.extend( // deep merge true, // ensure the target is an empty, unreferenced object {}, // the base options object for this type of dialog (often just buttons) defaults, // args could be an object or array; if it's an array properties will // map it to a proper options object mapArguments( args, properties ) ); } /** * this entry-level method makes heavy use of composition to take a simple * range of inputs and return valid options suitable for passing to bootbox.dialog */ function mergeDialogOptions(className, labels, properties, args) { // build up a base set of dialog properties var baseOptions = { className: "bootbox-" + className, buttons: createLabels.apply(null, labels) }; // ensure the buttons properties generated, *after* merging // with user args are still valid against the supplied labels return validateButtons( // merge the generated base properties with user supplied arguments mergeArguments( baseOptions, args, // if args.length > 1, properties specify how each arg maps to an object key properties ), labels ); } /** * from a given list of arguments return a suitable object of button labels * all this does is normalise the given labels and translate them where possible * e.g. "ok", "confirm" -> { ok: "OK, cancel: "Annuleren" } */ function createLabels() { var buttons = {}; for (var i = 0, j = arguments.length; i < j; i++) { var argument = arguments[i]; var key = argument.toLowerCase(); var value = argument.toUpperCase(); buttons[key] = { label: _t(value) }; } return buttons; } function validateButtons(options, buttons) { var allowedButtons = {}; each(buttons, function(key, value) { allowedButtons[value] = true; }); each(options.buttons, function(key) { if (allowedButtons[key] === undefined) { throw new Error("button key " + key + " is not allowed (options are " + buttons.join("\n") + ")"); } }); return options; } exports.alert = function() { var options; options = mergeDialogOptions("alert", ["ok"], ["message", "callback"], arguments); if (options.callback && !$.isFunction(options.callback)) { throw new Error("alert requires callback property to be a function when provided"); } /** * overrides */ options.buttons.ok.callback = options.onEscape = function() { if ($.isFunction(options.callback)) { return options.callback.call(this); } return true; }; return exports.dialog(options); }; exports.confirm = function() { var options; options = mergeDialogOptions("confirm", ["cancel", "confirm"], ["message", "callback"], arguments); /** * overrides; undo anything the user tried to set they shouldn't have */ options.buttons.cancel.callback = options.onEscape = function() { return options.callback.call(this, false); }; options.buttons.confirm.callback = function() { return options.callback.call(this, true); }; // confirm specific validation if (!$.isFunction(options.callback)) { throw new Error("confirm requires a callback"); } return exports.dialog(options); }; exports.prompt = function() { var options; var defaults; var dialog; var form; var input; var shouldShow; var inputOptions; // we have to create our form first otherwise // its value is undefined when gearing up our options // @TODO this could be solved by allowing message to // be a function instead... form = $(templates.form); // prompt defaults are more complex than others in that // users can override more defaults // @TODO I don't like that prompt has to do a lot of heavy // lifting which mergeDialogOptions can *almost* support already // just because of 'value' and 'inputType' - can we refactor? defaults = { className: "bootbox-prompt", buttons: createLabels("cancel", "confirm"), value: "", inputType: "text" }; options = validateButtons( mergeArguments(defaults, arguments, ["title", "callback"]), ["cancel", "confirm"] ); // capture the user's show value; we always set this to false before // spawning the dialog to give us a chance to attach some handlers to // it, but we need to make sure we respect a preference not to show it shouldShow = (options.show === undefined) ? true : options.show; /** * overrides; undo anything the user tried to set they shouldn't have */ options.message = form; options.buttons.cancel.callback = options.onEscape = function() { return options.callback.call(this, null); }; options.buttons.confirm.callback = function() { var value; switch (options.inputType) { case "text": case "textarea": case "email": case "select": case "date": case "time": case "number": case "password": value = input.val(); break; case "checkbox": var checkedItems = input.find("input:checked"); // we assume that checkboxes are always multiple, // hence we default to an empty array value = []; each(checkedItems, function(_, item) { value.push($(item).val()); }); break; } return options.callback.call(this, value); }; options.show = false; // prompt specific validation if (!options.title) { throw new Error("prompt requires a title"); } if (!$.isFunction(options.callback)) { throw new Error("prompt requires a callback"); } if (!templates.inputs[options.inputType]) { throw new Error("invalid prompt type"); } // create the input based on the supplied type input = $(templates.inputs[options.inputType]); switch (options.inputType) { case "text": case "textarea": case "email": case "date": case "time": case "number": case "password": input.val(options.value); break; case "select": var groups = {}; inputOptions = options.inputOptions || []; if (!$.isArray(inputOptions)) { throw new Error("Please pass an array of input options"); } if (!inputOptions.length) { throw new Error("prompt with select requires options"); } each(inputOptions, function(_, option) { // assume the element to attach to is the input... var elem = input; if (option.value === undefined || option.text === undefined) { throw new Error("given options in wrong format"); } // ... but override that element if this option sits in a group if (option.group) { // initialise group if necessary if (!groups[option.group]) { groups[option.group] = $("").attr("label", option.group); } elem = groups[option.group]; } elem.append(""); }); each(groups, function(_, group) { input.append(group); }); // safe to set a select's value as per a normal input input.val(options.value); break; case "checkbox": var values = $.isArray(options.value) ? options.value : [options.value]; inputOptions = options.inputOptions || []; if (!inputOptions.length) { throw new Error("prompt with checkbox requires options"); } if (!inputOptions[0].value || !inputOptions[0].text) { throw new Error("given options in wrong format"); } // checkboxes have to nest within a containing element, so // they break the rules a bit and we end up re-assigning // our 'input' element to this container instead input = $("
"); each(inputOptions, function(_, option) { var checkbox = $(templates.inputs[options.inputType]); checkbox.find("input").attr("value", option.value); checkbox.find("label").append(option.text); // we've ensured values is an array so we can always iterate over it each(values, function(_, value) { if (value === option.value) { checkbox.find("input").prop("checked", true); } }); input.append(checkbox); }); break; } // @TODO provide an attributes option instead // and simply map that as keys: vals if (options.placeholder) { input.attr("placeholder", options.placeholder); } if (options.pattern) { input.attr("pattern", options.pattern); } if (options.maxlength) { input.attr("maxlength", options.maxlength); } // now place it in our form form.append(input); form.on("submit", function(e) { e.preventDefault(); // Fix for SammyJS (or similar JS routing library) hijacking the form post. e.stopPropagation(); // @TODO can we actually click *the* button object instead? // e.g. buttons.confirm.click() or similar dialog.find(".btn-primary").click(); }); dialog = exports.dialog(options); // clear the existing handler focusing the submit button... dialog.off("shown.bs.modal"); // ...and replace it with one focusing our input, if possible dialog.on("shown.bs.modal", function() { // need the closure here since input isn't // an object otherwise input.focus(); }); if (shouldShow === true) { dialog.modal("show"); } return dialog; }; exports.dialog = function(options) { options = sanitize(options); var dialog = $(templates.dialog); var innerDialog = dialog.find(".modal-dialog"); var body = dialog.find(".modal-body"); var buttons = options.buttons; var buttonStr = ""; var callbacks = { onEscape: options.onEscape }; if ($.fn.modal === undefined) { throw new Error( "$.fn.modal is not defined; please double check you have included " + "the Bootstrap JavaScript library. See http://getbootstrap.com/javascript/ " + "for more details." ); } each(buttons, function(key, button) { // @TODO I don't like this string appending to itself; bit dirty. Needs reworking // can we just build up button elements instead? slower but neater. Then button // can just become a template too buttonStr += ""; callbacks[key] = button.callback; }); body.find(".bootbox-body").html(options.message); if (options.animate === true) { dialog.addClass("fade"); } if (options.className) { dialog.addClass(options.className); } if (options.size === "large") { innerDialog.addClass("modal-lg"); } else if (options.size === "small") { innerDialog.addClass("modal-sm"); } if (options.title) { body.before(templates.header); } if (options.closeButton) { var closeButton = $(templates.closeButton); if (options.title) { dialog.find(".modal-header").prepend(closeButton); } else { closeButton.css("margin-top", "-10px").prependTo(body); } } if (options.title) { dialog.find(".modal-title").html(options.title); } if (buttonStr.length) { body.after(templates.footer); dialog.find(".modal-footer").html(buttonStr); } /** * Bootstrap event listeners; used handle extra * setup & teardown required after the underlying * modal has performed certain actions */ dialog.on("hidden.bs.modal", function(e) { // ensure we don't accidentally intercept hidden events triggered // by children of the current dialog. We shouldn't anymore now BS // namespaces its events; but still worth doing if (e.target === this) { dialog.remove(); } }); /* dialog.on("show.bs.modal", function() { // sadly this doesn't work; show is called *just* before // the backdrop is added so we'd need a setTimeout hack or // otherwise... leaving in as would be nice if (options.backdrop) { dialog.next(".modal-backdrop").addClass("bootbox-backdrop"); } }); */ dialog.on("shown.bs.modal", function() { dialog.find(".btn-primary:first").focus(); }); /** * Bootbox event listeners; experimental and may not last * just an attempt to decouple some behaviours from their * respective triggers */ if (options.backdrop !== "static") { // A boolean true/false according to the Bootstrap docs // should show a dialog the user can dismiss by clicking on // the background. // We always only ever pass static/false to the actual // $.modal function because with `true` we can't trap // this event (the .modal-backdrop swallows it) // However, we still want to sort of respect true // and invoke the escape mechanism instead dialog.on("click.dismiss.bs.modal", function(e) { // @NOTE: the target varies in >= 3.3.x releases since the modal backdrop // moved *inside* the outer dialog rather than *alongside* it if (dialog.children(".modal-backdrop").length) { e.currentTarget = dialog.children(".modal-backdrop").get(0); } if (e.target !== e.currentTarget) { return; } dialog.trigger("escape.close.bb"); }); } dialog.on("escape.close.bb", function(e) { if (callbacks.onEscape) { processCallback(e, dialog, callbacks.onEscape); } }); /** * Standard jQuery event listeners; used to handle user * interaction with our dialog */ dialog.on("click", ".modal-footer button", function(e) { var callbackKey = $(this).data("bb-handler"); processCallback(e, dialog, callbacks[callbackKey]); }); dialog.on("click", ".bootbox-close-button", function(e) { // onEscape might be falsy but that's fine; the fact is // if the user has managed to click the close button we // have to close the dialog, callback or not processCallback(e, dialog, callbacks.onEscape); }); dialog.on("keyup", function(e) { if (e.which === 27) { dialog.trigger("escape.close.bb"); } }); // the remainder of this method simply deals with adding our // dialogent to the DOM, augmenting it with Bootstrap's modal // functionality and then giving the resulting object back // to our caller $(options.container).append(dialog); dialog.modal({ backdrop: options.backdrop ? "static": false, keyboard: false, show: false }); if (options.show) { dialog.modal("show"); } // @TODO should we return the raw element here or should // we wrap it in an object on which we can expose some neater // methods, e.g. var d = bootbox.alert(); d.hide(); instead // of d.modal("hide"); /* function BBDialog(elem) { this.elem = elem; } BBDialog.prototype = { hide: function() { return this.elem.modal("hide"); }, show: function() { return this.elem.modal("show"); } }; */ return dialog; }; exports.setDefaults = function() { var values = {}; if (arguments.length === 2) { // allow passing of single key/value... values[arguments[0]] = arguments[1]; } else { // ... and as an object too values = arguments[0]; } $.extend(defaults, values); }; exports.hideAll = function() { $(".bootbox").modal("hide"); return exports; }; /** * standard locales. Please add more according to ISO 639-1 standard. Multiple language variants are * unlikely to be required. If this gets too large it can be split out into separate JS files. */ var locales = { bg_BG : { OK : "Ок", CANCEL : "Отказ", CONFIRM : "Потвърждавам" }, br : { OK : "OK", CANCEL : "Cancelar", CONFIRM : "Sim" }, cs : { OK : "OK", CANCEL : "Zrušit", CONFIRM : "Potvrdit" }, da : { OK : "OK", CANCEL : "Annuller", CONFIRM : "Accepter" }, de : { OK : "OK", CANCEL : "Abbrechen", CONFIRM : "Akzeptieren" }, el : { OK : "Εντάξει", CANCEL : "Ακύρωση", CONFIRM : "Επιβεβαίωση" }, en : { OK : "OK", CANCEL : "Cancel", CONFIRM : "OK" }, es : { OK : "OK", CANCEL : "Cancelar", CONFIRM : "Aceptar" }, et : { OK : "OK", CANCEL : "Katkesta", CONFIRM : "OK" }, fa : { OK : "قبول", CANCEL : "لغو", CONFIRM : "تایید" }, fi : { OK : "OK", CANCEL : "Peruuta", CONFIRM : "OK" }, fr : { OK : "OK", CANCEL : "Annuler", CONFIRM : "D'accord" }, he : { OK : "אישור", CANCEL : "ביטול", CONFIRM : "אישור" }, hu : { OK : "OK", CANCEL : "Mégsem", CONFIRM : "Megerősít" }, hr : { OK : "OK", CANCEL : "Odustani", CONFIRM : "Potvrdi" }, id : { OK : "OK", CANCEL : "Batal", CONFIRM : "OK" }, it : { OK : "OK", CANCEL : "Annulla", CONFIRM : "Conferma" }, ja : { OK : "OK", CANCEL : "キャンセル", CONFIRM : "確認" }, lt : { OK : "Gerai", CANCEL : "Atšaukti", CONFIRM : "Patvirtinti" }, lv : { OK : "Labi", CANCEL : "Atcelt", CONFIRM : "Apstiprināt" }, nl : { OK : "OK", CANCEL : "Annuleren", CONFIRM : "Accepteren" }, no : { OK : "OK", CANCEL : "Avbryt", CONFIRM : "OK" }, pl : { OK : "OK", CANCEL : "Anuluj", CONFIRM : "Potwierdź" }, pt : { OK : "OK", CANCEL : "Cancelar", CONFIRM : "Confirmar" }, ru : { OK : "OK", CANCEL : "Отмена", CONFIRM : "Применить" }, sq : { OK : "OK", CANCEL : "Anulo", CONFIRM : "Prano" }, sv : { OK : "OK", CANCEL : "Avbryt", CONFIRM : "OK" }, th : { OK : "ตกลง", CANCEL : "ยกเลิก", CONFIRM : "ยืนยัน" }, tr : { OK : "Tamam", CANCEL : "İptal", CONFIRM : "Onayla" }, zh_CN : { OK : "OK", CANCEL : "取消", CONFIRM : "确认" }, zh_TW : { OK : "OK", CANCEL : "取消", CONFIRM : "確認" } }; exports.addLocale = function(name, values) { $.each(["OK", "CANCEL", "CONFIRM"], function(_, v) { if (!values[v]) { throw new Error("Please supply a translation for '" + v + "'"); } }); locales[name] = { OK: values.OK, CANCEL: values.CANCEL, CONFIRM: values.CONFIRM }; return exports; }; exports.removeLocale = function(name) { delete locales[name]; return exports; }; exports.setLocale = function(name) { return exports.setDefaults("locale", name); }; exports.init = function(_$) { return init(_$ || $); }; return exports; })); ================================================ FILE: server/static/bubble.css ================================================ /* ------------------------------------------ PURE CSS SPEECH BUBBLES by Nicolas Gallagher - http://nicolasgallagher.com/pure-css-speech-bubbles/ http://nicolasgallagher.com http://twitter.com/necolas Created: 02 March 2010 Version: 1.2 (03 March 2011) Dual licensed under MIT and GNU GPLv2 � Nicolas Gallagher ------------------------------------------ */ /* NOTE: Some declarations use longhand notation so that it can be clearly explained what specific properties or values do and what their relationship is to other properties or values in creating the effect */ .right { float:right; width:100%; } .left { float:left; width:100%; /*ie6 hack*/_background:none; _border:none;} /* ============================================================================================================================ == BUBBLE ORANGE ** ============================================================================================================================ */ /* THE SPEECH BUBBLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-orange { width:auto; max-width:40%; position:relative; padding:15px 15px 20px; margin:0.5em 0 0.5em; background: #f3961c; word-break: break-all; color:#fff; /* css3 */ -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; } /* Variant : for left positioned triangle ------------------------------------------ */ .left .bubble-orange { margin-left:100px; float:left; } /* Variant : for right positioned triangle ------------------------------------------ */ .right .bubble-orange { margin-right:100px; float:right; } .bubble-orange:hover{ background:#f9d835; color:#000; } /* THE TRIANGLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-orange:after { content:""; position:absolute; bottom:-20px; /* value = - border-top-width - border-bottom-width */ left:50px; /* controls horizontal position */ border-width:15px 15px 0; /* vary these values to change the angle of the vertex */ border-style:solid; border-color:#f3961c transparent; /* reduce the damage in FF3.0 */ display:block; width:0; } /* Variant : left ------------------------------------------ */ /* creates the smaller triangle */ .left .bubble-orange:after { top:16px; /* value = (:before top) + (:before border-top) - (:after border-top) */ bottom:auto; left:-21px; /* value = - border-left-width - border-right-width */ border-width:9px 21px 9px 0; border-color:transparent #f3961c; } /* Variant : right ------------------------------------------ */ /* creates the smaller triangle */ .right .bubble-orange:after { top:16px; /* value = (:before top) + (:before border-top) - (:after border-top) */ bottom:auto; left:auto; right:-21px; /* value = - border-left-width - border-right-width */ border-width:9px 0 9px 21px; border-color:transparent #f3961c; } /* ============================================================================================================================ == BUBBLE WHITE ** ============================================================================================================================ */ /* THE SPEECH BUBBLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-white { width:auto; max-width:95%; white-space: normal; overflow-x: auto; /*word-break: break-all;*/ position:relative; padding:15px 15px 5px; margin:0.5em 0 0.5em; background: #fcfcfc; color:#000; /* css3 */ -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; } /* Variant : for left positioned triangle ------------------------------------------ */ .left .bubble-white { float:left; } /* Variant : for right positioned triangle ------------------------------------------ */ .right .bubble-white { float:right; } /* THE TRIANGLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-white:after { content:""; position:absolute; bottom:-20px; /* value = - border-top-width - border-bottom-width */ left:50px; /* controls horizontal position */ border-width:15px 15px 0; /* vary these values to change the angle of the vertex */ border-style:solid; border-color:#ccc transparent; /* reduce the damage in FF3.0 */ display:block; width:0; } /* Variant : left ------------------------------------------ */ /* creates the smaller triangle */ .left .bubble-white:after { top:16px; /* value = (:before top) + (:before border-top) - (:after border-top) */ bottom:auto; left:-21px; /* value = - border-left-width - border-right-width */ border-width:9px 21px 9px 0; border-color:transparent #fcfcfc; } /* Variant : right ------------------------------------------ */ /* creates the smaller triangle */ .right .bubble-white:after { top:16px; /* value = (:before top) + (:before border-top) - (:after border-top) */ bottom:auto; left:auto; right:-21px; /* value = - border-left-width - border-right-width */ border-width:9px 0 9px 21px; border-color:transparent #fcfcfc; } /* ============================================================================================================================ == BUBBLE BLUE ** ============================================================================================================================ */ /* THE SPEECH BUBBLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-blue { width:auto; max-width:50%; word-break: break-all; position:relative; padding:15px; margin:0.5em 0 0.5em; color:#fff; background:#075698; /* default background for browsers without gradient support */ /* css3 */ -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; } /* Variant : for left positioned triangle ------------------------------------------ */ .left .bubble-blue { margin-left:100px; float:left; } /* Variant : for right positioned triangle ------------------------------------------ */ .right .bubble-blue { float:right; } .bubble-blue:hover{ background:#2e88c4; color:#000; } /* THE TRIANGLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-blue:after { content:""; position:absolute; bottom:-20px; /* value = - border-top-width - border-bottom-width */ left:50px; /* controls horizontal position */ border-width:20px 0 0 20px; /* vary these values to change the angle of the vertex */ border-style:solid; border-color:#075698 transparent; /* reduce the damage in FF3.0 */ display:block; width:0; } /* Variant : left ------------------------------------------ */ .left .bubble-blue:after { top:16px; left:-40px; /* value = - border-left-width - border-right-width */ bottom:auto; border-width:15px 40px 0 0; /* vary these values to change the angle of the vertex */ border-color:transparent #075698; } /* Variant : right ------------------------------------------ */ .right .bubble-blue:after { top:16px; right:-40px; /* value = - border-left-width - border-right-width */ bottom:auto; left:auto; border-width:15px 0 0 40px; /* vary these values to change the angle of the vertex */ border-color:transparent #075698 ; } /* ============================================================================================================================ == BUBBLE RED ** ============================================================================================================================ */ /* THE SPEECH BUBBLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-red { width:auto; max-width:30%; word-break: break-all; position:relative; padding:15px; margin:0.5em 0 0.5em; color:#fff; background:#c81e2b; /* default background for browsers without gradient support */ /* css3 */ -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; } /* Variant : for left positioned triangle ------------------------------------------ */ .left .bubble-red { margin-left:100px; float:left; } /* Variant : for right positioned triangle ------------------------------------------ */ .right .bubble-red { margin-right:100px; float:right; } .bubble-red:hover{ background:#f04349; color:#000; } /* THE TRIANGLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-red:after { content:""; position:absolute; bottom:-20px; /* value = - border-top-width - border-bottom-width */ left:50px; /* controls horizontal position */ border-width:20px 0 0 20px; /* vary these values to change the angle of the vertex */ border-style:solid; border-color:#c81e2b transparent; /* reduce the damage in FF3.0 */ display:block; width:0; } /* Variant : left ------------------------------------------ */ .left .bubble-red:after { top:16px; left:-40px; /* value = - border-left-width - border-right-width */ bottom:auto; border-width:15px 40px 0 0; /* vary these values to change the angle of the vertex */ border-color:transparent #c81e2b; } /* Variant : right ------------------------------------------ */ .right .bubble-red:after { top:16px; right:-40px; /* value = - border-left-width - border-right-width */ bottom:auto; left:auto; border-width:15px 0 0 40px; /* vary these values to change the angle of the vertex */ border-color:transparent #c81e2b ; } /* ============================================================================================================================ == BUBBLE GREEN ** ============================================================================================================================ */ /* THE SPEECH BUBBLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-green { width:auto; max-width:40%; word-break: break-all; position:relative; padding:15px 15px 5px; margin:0.5em 0 0.5em; background: #7CCD7C; color:#000; /* css3 */ -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px; } .bubble-text { text-align: left; margin-bottom: 10px } /* Variant : for left positioned triangle ------------------------------------------ */ .left .bubble-green { float:left; } /* Variant : for right positioned triangle ------------------------------------------ */ .right .bubble-green { margin-right:20px; float:right; } /* THE TRIANGLE ------------------------------------------------------------------------------------------------------------------------------- */ .bubble-green:after { content:""; position:absolute; bottom:-20px; /* value = - border-top-width - border-bottom-width */ left:50px; /* controls horizontal position */ border-width:15px 15px 0; /* vary these values to change the angle of the vertex */ border-style:solid; border-color:#7CCD7C transparent; /* reduce the damage in FF3.0 */ display:block; width:0; } /* Variant : left ------------------------------------------ */ /* creates the smaller triangle */ .left .bubble-green:after { top:16px; /* value = (:before top) + (:before border-top) - (:after border-top) */ bottom:auto; left:-21px; /* value = - border-left-width - border-right-width */ border-width:9px 21px 9px 0; border-color:transparent #7CCD7C; } /* Variant : right ------------------------------------------ */ /* creates the smaller triangle */ .right .bubble-green:after { top:16px; /* value = (:before top) + (:before border-top) - (:after border-top) */ bottom:auto; left:auto; right:-21px; /* value = - border-left-width - border-right-width */ border-width:9px 0 9px 21px; border-color:transparent #7CCD7C; } .right .bubble-avatar{ width:80px; height:38px; text-align:center; position:absolute; right: -110px; color: #000; } .left .bubble-avatar{ width:80px; height:38px; text-align:center; position:absolute; left: -110px; color: #000; } ================================================ FILE: server/static/config.js ================================================ function saveConfig(msg) { if (window.location.href.indexOf('bot.hahack.com') >= 0) { bootbox.alert("demo 站点禁止修改配置!"); return; } $.ajax({ url: '/config', type: "POST", data: {"config": encodeURIComponent($('#config-input').val()), 'validate': getCookie('validation')}, success: function(res) { var data = JSON.parse(res); if (!msg) msg=''; if (data.code == 0) { toastr.success('设置成功'+msg); } else { toastr.error(data.message, '设置失败'); } }, error: function() { toastr.error('服务器异常', '设置失败'); } }); } $(function() { $.ajax({ url: '/config', type: "GET", data: {'validate': getCookie('validation')}, success: function(res) { var data = JSON.parse(res); if (data.code == 0) { let config = data.config; let sensitivity = data.sensitivity; if (config == '') { $('#config-placeholder').append(`

找不到配置文件 ~/.wukong/config.yml ,请先创建一份!

`); } else { $('#config-placeholder').append(`
config.yml

 
`); } $('#sensitivitiy-value').text(sensitivity); $('input#sensitivitiy').val(parseFloat(sensitivity)); $('input#sensitivity').on('input propertychange', function(e) { e.preventDefault(); var value = $(this).val(); $('#sensitivitiy-value').text(value); }); $('input#sensitivity').on('change', function(e) { e.preventDefault(); var value = $(this).val(); var config = $('#config-input').val(); config.indexOf('') var subStr=new RegExp('sensitivity: [0-9]+\.?[0-9]?') result = config.replace(subStr, "sensitivity: " + value + " "); $('#config-input').text(result); saveConfig(',请重启生效'); }); $('button#RESTART').on('click', function(e) { restart(); }); $('button#SAVE').on('click', function(e) { saveConfig(); }); } else { toastr.error(data.message, '指令发送失败'); } }, error: function() { toastr.error('服务器异常', '指令发送失败'); } }); }); ================================================ FILE: server/static/index.js ================================================ var md = window.markdownit({ html: true, linkify: true, typographer: true, highlight: function (str, lang) { if (lang && hljs.getLanguage(lang)) { try { return '
' +
                 hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                 '
'; } catch (__) {} } return '
' + md.utils.escapeHtml(str) + '
'; } }); function appendHistory(type, message, uuid, plugin) { if (!uuid) return; if (type == 0) { // 用户消息 $('.history').append(`
${message}
`); } else { messages = message.split('\n'); $('.history').append(`
`); $(`#${uuid}`).append(md.render(`${message}`)); if (plugin) { $(`#${uuid}`).after(` ${plugin} `); } } $("#"+uuid).hide(); $("#"+uuid).fadeIn(500, ()=>{ var scrollHeight = $('.history').prop("scrollHeight"); $('.history').scrollTop(scrollHeight, 200); }); } function showProgress() { progressJs().increase(); } function upgrade() { var args = {'validate': getCookie('validation')} $.ajax({ url: '/upgrade', type: "POST", data: $.param(args), success: function(res) { $('.UPDATE-SPIN')[0].hidden = true; $('.UPDATE')[0].disabled = false; res = JSON.parse(res); if (res.code == 0) { toastr.success('更新成功,5秒后将自动重启') $('#updateModal').modal('hide') progressJs().start(); setInterval("showProgress()", 1000); setTimeout(()=>{ progressJs().end(); clearInterval(); location.reload(); }, 5000); } else { toastr.error(res.message, '更新失败'); $('#updateModal').modal('hide') } }, error: function() { toastr.error('服务器异常', '更新失败'); $('#updateModal').modal('hide') } }); } //用于生成uuid function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); } function guid() { return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); } // 创建WebSocket连接 var socket = new WebSocket("ws://" + location.host + "/websocket"); // 监听WebSocket打开事件 socket.onopen = function (e) { console.log("WebSocket连接已打开"); }; // 监听WebSocket关闭事件 socket.onclose = function (e) { console.log("WebSocket连接已关闭"); }; var rawData = {} var showMessage = function(data) { var existing = $("#" + data.uuid); if (existing.length > 0) { // 如果存在,追加内容,并重新用 markdown 渲染 if (rawData[data.uuid] == undefined) { rawData[data.uuid] = data['text']; } else { rawData[data.uuid] += data['text']; } $(`#${data.uuid}`)[0].innerHTML = md.render(rawData[data.uuid]); } else { rawData[data.uuid] = data['text']; appendHistory(data['type'], data['text'], data['uuid'], data['plugin']); } } // 监听WebSocket消息事件 socket.onmessage = function (e) { var data = JSON.parse(e.data); if (data.action === "new_message") { // console.log("收到新消息: ", data); showMessage(data) let scrollHeight = $('.history').prop("scrollHeight"); $('.history').scrollTop(scrollHeight, 200); } }; $(document).ready(function() { if (!window.console) window.console = {}; if (!window.console.log) window.console.log = function() {}; $('.CHAT').on('click', function(e) { e.preventDefault(); var disabled = $('#query'); disabled.disable(); var uuid = 'chat' + guid(); var query = $("input#query")[0].value; if (query.trim() == '') { toastr.error('请输入有效的命令'); return; } appendHistory(0, query, uuid); $('input#query').val(''); var args = {"type": "text", "query": query, 'validate': getCookie('validation'), "uuid": uuid} $.ajax({ url: '/chat', type: "POST", data: $.param(args), success: function(res) { disabled.enable(); if (!res) return; var data = JSON.parse(res); if (data.code == 0) { toastr.success('指令发送成功'); } else { toastr.error(data.message, '指令发送失败'); } }, error: function() { disabled.enable(); toastr.error('服务器异常', '指令发送失败'); } }); }); $('.UPDATE').on('click', function(e) { $('.UPDATE-SPIN')[0].hidden = false; $(this)[0].disabled = true; upgrade(); }); updater.poll(); }); jQuery.fn.disable = function() { this.enable(false); return this; }; jQuery.fn.enable = function(opt_enable) { if (arguments.length && !opt_enable) { this.attr("disabled", "disabled"); } else { this.removeAttr("disabled"); } return this; }; var updater = { errorSleepTime: 500, cursor: null, poll: function() { console.log('updater poll'); var args = {'validate': getCookie('validation')} if (updater.cursor) args.cursor = updater.cursor; $.ajax({ url: '/chat/updates', type: "POST", data: $.param(args), success: updater.onSuccess, error: updater.onError }); }, onSuccess: function(response) { console.log("updater poll success") try { var res = JSON.parse(response); updater.newMessages(res); } catch (e) { updater.onError(); return; } updater.errorSleepTime = 500; window.setTimeout(updater.poll, 0); }, onError: function(response) { updater.errorSleepTime *= 2; console.error("get history failed! sleeping for", updater.errorSleepTime, "ms"); window.setTimeout(updater.poll, updater.errorSleepTime); }, newMessages: function(response) { if (response.code != 0 || !response.history) return; var messages = JSON.parse(response.history); updater.cursor = messages[messages.length - 1].uuid; console.log(messages.length, "new messages, cursor:", updater.cursor); for (var i = 0; i < messages.length; i++) { updater.showMessage(messages[i]); } }, showMessage: function(message) { var existing = $("#" + message.uuid); if (existing.length > 0) return; appendHistory(message['type'], message['text'], message['uuid'], message['plugin']); } }; ================================================ FILE: server/static/jquery.fancybox.css ================================================ body.compensate-for-scrollbar { overflow: hidden; } .fancybox-active { height: auto; } .fancybox-is-hidden { left: -9999px; margin: 0; position: absolute !important; top: -9999px; visibility: hidden; } .fancybox-container { -webkit-backface-visibility: hidden; backface-visibility: hidden; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; height: 100%; left: 0; position: fixed; -webkit-tap-highlight-color: transparent; top: 0; -webkit-transform: translateZ(0); transform: translateZ(0); width: 100%; z-index: 99992; } .fancybox-container * { box-sizing: border-box; } .fancybox-outer, .fancybox-inner, .fancybox-bg, .fancybox-stage { bottom: 0; left: 0; position: absolute; right: 0; top: 0; } .fancybox-outer { -webkit-overflow-scrolling: touch; overflow-y: auto; } .fancybox-bg { background: #1e1e1e; opacity: 0; transition-duration: inherit; transition-property: opacity; transition-timing-function: cubic-bezier(0.47, 0, 0.74, 0.71); } .fancybox-is-open .fancybox-bg { opacity: .87; transition-timing-function: cubic-bezier(0.22, 0.61, 0.36, 1); } .fancybox-infobar, .fancybox-toolbar, .fancybox-caption, .fancybox-navigation .fancybox-button { direction: ltr; opacity: 0; position: absolute; transition: opacity .25s, visibility 0s linear .25s; visibility: hidden; z-index: 99997; } .fancybox-show-infobar .fancybox-infobar, .fancybox-show-toolbar .fancybox-toolbar, .fancybox-show-caption .fancybox-caption, .fancybox-show-nav .fancybox-navigation .fancybox-button { opacity: 1; transition: opacity .25s, visibility 0s; visibility: visible; } .fancybox-infobar { color: #ccc; font-size: 13px; -webkit-font-smoothing: subpixel-antialiased; height: 44px; left: 0; line-height: 44px; min-width: 44px; mix-blend-mode: difference; padding: 0 10px; pointer-events: none; text-align: center; top: 0; -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .fancybox-toolbar { right: 0; top: 0; } .fancybox-stage { direction: ltr; overflow: visible; -webkit-transform: translate3d(0, 0, 0); z-index: 99994; } .fancybox-is-open .fancybox-stage { overflow: hidden; } .fancybox-slide { -webkit-backface-visibility: hidden; backface-visibility: hidden; display: none; height: 100%; left: 0; outline: none; overflow: auto; -webkit-overflow-scrolling: touch; padding: 44px; position: absolute; text-align: center; top: 0; transition-property: opacity, -webkit-transform; transition-property: transform, opacity; transition-property: transform, opacity, -webkit-transform; white-space: normal; width: 100%; z-index: 99994; } .fancybox-slide::before { content: ''; display: inline-block; height: 100%; margin-right: -.25em; vertical-align: middle; width: 0; } .fancybox-is-sliding .fancybox-slide, .fancybox-slide--previous, .fancybox-slide--current, .fancybox-slide--next { display: block; } .fancybox-slide--next { z-index: 99995; } .fancybox-slide--image { overflow: visible; padding: 44px 0; } .fancybox-slide--image::before { display: none; } .fancybox-slide--html { padding: 6px 6px 0 6px; } .fancybox-slide--iframe { padding: 44px 44px 0; } .fancybox-content { background: #fff; display: inline-block; margin: 0 0 6px 0; max-width: 100%; overflow: auto; padding: 0; padding: 24px; position: relative; text-align: left; vertical-align: middle; } .fancybox-slide--image .fancybox-content { -webkit-animation-timing-function: cubic-bezier(0.5, 0, 0.14, 1); animation-timing-function: cubic-bezier(0.5, 0, 0.14, 1); -webkit-backface-visibility: hidden; backface-visibility: hidden; background: transparent; background-repeat: no-repeat; background-size: 100% 100%; left: 0; margin: 0; max-width: none; overflow: visible; padding: 0; position: absolute; top: 0; -webkit-transform-origin: top left; -ms-transform-origin: top left; transform-origin: top left; transition-property: opacity, -webkit-transform; transition-property: transform, opacity; transition-property: transform, opacity, -webkit-transform; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; z-index: 99995; } .fancybox-can-zoomOut .fancybox-content { cursor: -webkit-zoom-out; cursor: zoom-out; } .fancybox-can-zoomIn .fancybox-content { cursor: -webkit-zoom-in; cursor: zoom-in; } .fancybox-can-drag .fancybox-content { cursor: -webkit-grab; cursor: grab; } .fancybox-is-dragging .fancybox-content { cursor: -webkit-grabbing; cursor: grabbing; } .fancybox-container [data-selectable='true'] { cursor: text; } .fancybox-image, .fancybox-spaceball { background: transparent; border: 0; height: 100%; left: 0; margin: 0; max-height: none; max-width: none; padding: 0; position: absolute; top: 0; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; width: 100%; } .fancybox-spaceball { z-index: 1; } .fancybox-slide--html .fancybox-content { margin-bottom: 6px; } .fancybox-slide--video .fancybox-content, .fancybox-slide--map .fancybox-content, .fancybox-slide--iframe .fancybox-content { height: 100%; margin: 0; overflow: visible; padding: 0; width: 100%; } .fancybox-slide--video .fancybox-content { background: #000; } .fancybox-slide--map .fancybox-content { background: #e5e3df; } .fancybox-slide--iframe .fancybox-content { background: #fff; height: calc(100% - 44px); margin-bottom: 44px; } .fancybox-video, .fancybox-iframe { background: transparent; border: 0; height: 100%; margin: 0; overflow: hidden; padding: 0; width: 100%; } .fancybox-iframe { vertical-align: top; } .fancybox-error { background: #fff; cursor: default; max-width: 400px; padding: 40px; width: 100%; } .fancybox-error p { color: #444; font-size: 16px; line-height: 20px; margin: 0; padding: 0; } /* Buttons */ .fancybox-button { background: rgba(30, 30, 30, 0.6); border: 0; border-radius: 0; cursor: pointer; display: inline-block; height: 44px; margin: 0; outline: none; padding: 10px; transition: color .2s; vertical-align: top; width: 44px; } .fancybox-button, .fancybox-button:visited, .fancybox-button:link { color: #ccc; } .fancybox-button:focus, .fancybox-button:hover { color: #fff; } .fancybox-button.disabled, .fancybox-button.disabled:hover, .fancybox-button[disabled], .fancybox-button[disabled]:hover { color: #888; cursor: default; } .fancybox-button svg { display: block; overflow: visible; position: relative; shape-rendering: geometricPrecision; } .fancybox-button svg path { fill: transparent; stroke: currentColor; stroke-linejoin: round; stroke-width: 3; } .fancybox-button--play svg path:nth-child(2) { display: none; } .fancybox-button--pause svg path:nth-child(1) { display: none; } .fancybox-button--play svg path, .fancybox-button--share svg path, .fancybox-button--thumbs svg path { fill: currentColor; } .fancybox-button--share svg path { stroke-width: 1; } /* Navigation arrows */ .fancybox-navigation .fancybox-button { height: 38px; opacity: 0; padding: 6px; position: absolute; top: 50%; width: 38px; } .fancybox-show-nav .fancybox-navigation .fancybox-button { transition: opacity .25s, visibility 0s, color .25s; } .fancybox-navigation .fancybox-button::after { content: ''; left: -25px; padding: 50px; position: absolute; top: -25px; } .fancybox-navigation .fancybox-button--arrow_left { left: 6px; } .fancybox-navigation .fancybox-button--arrow_right { right: 6px; } /* Close button on the top right corner of html content */ .fancybox-close-small { background: transparent; border: 0; border-radius: 0; color: #555; cursor: pointer; height: 44px; margin: 0; padding: 6px; position: absolute; right: 0; top: 0; width: 44px; z-index: 10; } .fancybox-close-small svg { fill: transparent; opacity: .8; stroke: currentColor; stroke-width: 1.5; transition: stroke .1s; } .fancybox-close-small:focus { outline: none; } .fancybox-close-small:hover svg { opacity: 1; } .fancybox-slide--image .fancybox-close-small, .fancybox-slide--video .fancybox-close-small, .fancybox-slide--iframe .fancybox-close-small { color: #ccc; padding: 5px; right: -12px; top: -44px; } .fancybox-slide--image .fancybox-close-small:hover svg, .fancybox-slide--video .fancybox-close-small:hover svg, .fancybox-slide--iframe .fancybox-close-small:hover svg { background: transparent; color: #fff; } .fancybox-is-scaling .fancybox-close-small, .fancybox-is-zoomable.fancybox-can-drag .fancybox-close-small { display: none; } /* Caption */ .fancybox-caption { bottom: 0; color: #fff; font-size: 14px; font-weight: 400; left: 0; line-height: 1.5; padding: 25px 44px 25px 44px; right: 0; } .fancybox-caption::before { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAEtCAQAAABjBcL7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAHRJREFUKM+Vk8EOgDAIQ0vj/3+xBw8qIZZueFnIKC90MCAI8DlrkHGeqqGIU6lVigrBtpCWqeRWoHDNqs0F7VNVBVxmHRlvoVqjaYkdnDIaivH2HqZ5+oZj3JUzWB+cOz4G48Bg+tsJ/tqu4dLC/4Xb+0GcF5BwBC0AA53qAAAAAElFTkSuQmCC); background-repeat: repeat-x; background-size: contain; bottom: 0; content: ''; display: block; left: 0; pointer-events: none; position: absolute; right: 0; top: -25px; z-index: -1; } .fancybox-caption::after { border-bottom: 1px solid rgba(255, 255, 255, 0.3); content: ''; display: block; left: 44px; position: absolute; right: 44px; top: 0; } .fancybox-caption a, .fancybox-caption a:link, .fancybox-caption a:visited { color: #ccc; text-decoration: none; } .fancybox-caption a:hover { color: #fff; text-decoration: underline; } /* Loading indicator */ .fancybox-loading { -webkit-animation: fancybox-rotate .8s infinite linear; animation: fancybox-rotate .8s infinite linear; background: transparent; border: 6px solid rgba(100, 100, 100, 0.5); border-radius: 100%; border-top-color: #fff; height: 60px; left: 50%; margin: -30px 0 0 -30px; opacity: .6; padding: 0; position: absolute; top: 50%; width: 60px; z-index: 99999; } @-webkit-keyframes fancybox-rotate { from { -webkit-transform: rotate(0deg); transform: rotate(0deg); } to { -webkit-transform: rotate(359deg); transform: rotate(359deg); } } @keyframes fancybox-rotate { from { -webkit-transform: rotate(0deg); transform: rotate(0deg); } to { -webkit-transform: rotate(359deg); transform: rotate(359deg); } } /* Transition effects */ .fancybox-animated { transition-timing-function: cubic-bezier(0, 0, 0.25, 1); } /* transitionEffect: slide */ .fancybox-fx-slide.fancybox-slide--previous { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } .fancybox-fx-slide.fancybox-slide--next { opacity: 0; -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } .fancybox-fx-slide.fancybox-slide--current { opacity: 1; -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } /* transitionEffect: fade */ .fancybox-fx-fade.fancybox-slide--previous, .fancybox-fx-fade.fancybox-slide--next { opacity: 0; transition-timing-function: cubic-bezier(0.19, 1, 0.22, 1); } .fancybox-fx-fade.fancybox-slide--current { opacity: 1; } /* transitionEffect: zoom-in-out */ .fancybox-fx-zoom-in-out.fancybox-slide--previous { opacity: 0; -webkit-transform: scale3d(1.5, 1.5, 1.5); transform: scale3d(1.5, 1.5, 1.5); } .fancybox-fx-zoom-in-out.fancybox-slide--next { opacity: 0; -webkit-transform: scale3d(0.5, 0.5, 0.5); transform: scale3d(0.5, 0.5, 0.5); } .fancybox-fx-zoom-in-out.fancybox-slide--current { opacity: 1; -webkit-transform: scale3d(1, 1, 1); transform: scale3d(1, 1, 1); } /* transitionEffect: rotate */ .fancybox-fx-rotate.fancybox-slide--previous { opacity: 0; -webkit-transform: rotate(-360deg); -ms-transform: rotate(-360deg); transform: rotate(-360deg); } .fancybox-fx-rotate.fancybox-slide--next { opacity: 0; -webkit-transform: rotate(360deg); -ms-transform: rotate(360deg); transform: rotate(360deg); } .fancybox-fx-rotate.fancybox-slide--current { opacity: 1; -webkit-transform: rotate(0deg); -ms-transform: rotate(0deg); transform: rotate(0deg); } /* transitionEffect: circular */ .fancybox-fx-circular.fancybox-slide--previous { opacity: 0; -webkit-transform: scale3d(0, 0, 0) translate3d(-100%, 0, 0); transform: scale3d(0, 0, 0) translate3d(-100%, 0, 0); } .fancybox-fx-circular.fancybox-slide--next { opacity: 0; -webkit-transform: scale3d(0, 0, 0) translate3d(100%, 0, 0); transform: scale3d(0, 0, 0) translate3d(100%, 0, 0); } .fancybox-fx-circular.fancybox-slide--current { opacity: 1; -webkit-transform: scale3d(1, 1, 1) translate3d(0, 0, 0); transform: scale3d(1, 1, 1) translate3d(0, 0, 0); } /* transitionEffect: tube */ .fancybox-fx-tube.fancybox-slide--previous { -webkit-transform: translate3d(-100%, 0, 0) scale(0.1) skew(-10deg); transform: translate3d(-100%, 0, 0) scale(0.1) skew(-10deg); } .fancybox-fx-tube.fancybox-slide--next { -webkit-transform: translate3d(100%, 0, 0) scale(0.1) skew(10deg); transform: translate3d(100%, 0, 0) scale(0.1) skew(10deg); } .fancybox-fx-tube.fancybox-slide--current { -webkit-transform: translate3d(0, 0, 0) scale(1); transform: translate3d(0, 0, 0) scale(1); } /* Share */ .fancybox-share { background: #f4f4f4; border-radius: 3px; max-width: 90%; padding: 30px; text-align: center; } .fancybox-share h1 { color: #222; font-size: 35px; font-weight: 700; margin: 0 0 20px 0; } .fancybox-share p { margin: 0; padding: 0; } .fancybox-share__button { border: 0; border-radius: 3px; display: inline-block; font-size: 14px; font-weight: 700; line-height: 40px; margin: 0 5px 10px 5px; min-width: 130px; padding: 0 15px; text-decoration: none; transition: all .2s; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; white-space: nowrap; } .fancybox-share__button:visited, .fancybox-share__button:link { color: #fff; } .fancybox-share__button:hover { text-decoration: none; } .fancybox-share__button--fb { background: #3b5998; } .fancybox-share__button--fb:hover { background: #344e86; } .fancybox-share__button--pt { background: #bd081d; } .fancybox-share__button--pt:hover { background: #aa0719; } .fancybox-share__button--tw { background: #1da1f2; } .fancybox-share__button--tw:hover { background: #0d95e8; } .fancybox-share__button svg { height: 25px; margin-right: 7px; position: relative; top: -1px; vertical-align: middle; width: 25px; } .fancybox-share__button svg path { fill: #fff; } .fancybox-share__input { background: transparent; border: 0; border-bottom: 1px solid #d7d7d7; border-radius: 0; color: #5d5b5b; font-size: 14px; margin: 10px 0 0 0; outline: none; padding: 10px 15px; width: 100%; } /* Thumbs */ .fancybox-thumbs { background: #fff; bottom: 0; display: none; margin: 0; -webkit-overflow-scrolling: touch; -ms-overflow-style: -ms-autohiding-scrollbar; padding: 2px 2px 4px 2px; position: absolute; right: 0; -webkit-tap-highlight-color: transparent; top: 0; width: 212px; z-index: 99995; } .fancybox-thumbs-x { overflow-x: auto; overflow-y: hidden; } .fancybox-show-thumbs .fancybox-thumbs { display: block; } .fancybox-show-thumbs .fancybox-inner { right: 212px; } .fancybox-thumbs > ul { font-size: 0; height: 100%; list-style: none; margin: 0; overflow-x: hidden; overflow-y: auto; padding: 0; position: absolute; position: relative; white-space: nowrap; width: 100%; } .fancybox-thumbs-x > ul { overflow: hidden; } .fancybox-thumbs-y > ul::-webkit-scrollbar { width: 7px; } .fancybox-thumbs-y > ul::-webkit-scrollbar-track { background: #fff; border-radius: 10px; box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); } .fancybox-thumbs-y > ul::-webkit-scrollbar-thumb { background: #2a2a2a; border-radius: 10px; } .fancybox-thumbs > ul > li { -webkit-backface-visibility: hidden; backface-visibility: hidden; cursor: pointer; float: left; height: 75px; margin: 2px; max-height: calc(100% - 8px); max-width: calc(50% - 4px); outline: none; overflow: hidden; padding: 0; position: relative; -webkit-tap-highlight-color: transparent; width: 100px; } .fancybox-thumbs-loading { background: rgba(0, 0, 0, 0.1); } .fancybox-thumbs > ul > li { background-position: center center; background-repeat: no-repeat; background-size: cover; } .fancybox-thumbs > ul > li:before { border: 4px solid #4ea7f9; bottom: 0; content: ''; left: 0; opacity: 0; position: absolute; right: 0; top: 0; transition: all 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94); z-index: 99991; } .fancybox-thumbs .fancybox-thumbs-active:before { opacity: 1; } /* Styling for Small-Screen Devices */ @media all and (max-width: 800px) { .fancybox-thumbs { width: 110px; } .fancybox-show-thumbs .fancybox-inner { right: 110px; } .fancybox-thumbs > ul > li { max-width: calc(100% - 10px); } } ================================================ FILE: server/static/jquery.fancybox.js ================================================ // ================================================== // fancyBox v3.3.5 // // Licensed GPLv3 for open source use // or fancyBox Commercial License for commercial use // // http://fancyapps.com/fancybox/ // Copyright 2018 fancyApps // // ================================================== (function(window, document, $, undefined) { "use strict"; window.console = window.console || { info: function(stuff) {} }; // If there's no jQuery, fancyBox can't work // ========================================= if (!$) { return; } // Check if fancyBox is already initialized // ======================================== if ($.fn.fancybox) { console.info("fancyBox already initialized"); return; } // Private default settings // ======================== var defaults = { // Enable infinite gallery navigation loop: false, // Horizontal space between slides gutter: 50, // Enable keyboard navigation keyboard: true, // Should display navigation arrows at the screen edges arrows: true, // Should display counter at the top left corner infobar: true, // Should display close button (using `btnTpl.smallBtn` template) over the content // Can be true, false, "auto" // If "auto" - will be automatically enabled for "html", "inline" or "ajax" items smallBtn: "auto", // Should display toolbar (buttons at the top) // Can be true, false, "auto" // If "auto" - will be automatically hidden if "smallBtn" is enabled toolbar: "auto", // What buttons should appear in the top right corner. // Buttons will be created using templates from `btnTpl` option // and they will be placed into toolbar (class="fancybox-toolbar"` element) buttons: [ "zoom", //"share", //"slideShow", //"fullScreen", //"download", "thumbs", "close" ], // Detect "idle" time in seconds idleTime: 3, // Disable right-click and use simple image protection for images protect: false, // Shortcut to make content "modal" - disable keyboard navigtion, hide buttons, etc modal: false, image: { // Wait for images to load before displaying // true - wait for image to load and then display; // false - display thumbnail and load the full-sized image over top, // requires predefined image dimensions (`data-width` and `data-height` attributes) preload: false }, ajax: { // Object containing settings for ajax request settings: { // This helps to indicate that request comes from the modal // Feel free to change naming data: { fancybox: true } } }, iframe: { // Iframe template tpl: '', // Preload iframe before displaying it // This allows to calculate iframe content width and height // (note: Due to "Same Origin Policy", you can't get cross domain data). preload: true, // Custom CSS styling for iframe wrapping element // You can use this to set custom iframe dimensions css: {}, // Iframe tag attributes attr: { scrolling: "auto" } }, // Default content type if cannot be detected automatically defaultType: "image", // Open/close animation type // Possible values: // false - disable // "zoom" - zoom images from/to thumbnail // "fade" // "zoom-in-out" // animationEffect: "zoom", // Duration in ms for open/close animation animationDuration: 366, // Should image change opacity while zooming // If opacity is "auto", then opacity will be changed if image and thumbnail have different aspect ratios zoomOpacity: "auto", // Transition effect between slides // // Possible values: // false - disable // "fade' // "slide' // "circular' // "tube' // "zoom-in-out' // "rotate' // transitionEffect: "fade", // Duration in ms for transition animation transitionDuration: 366, // Custom CSS class for slide element slideClass: "", // Custom CSS class for layout baseClass: "", // Base template for layout baseTpl: '", // Loading indicator template spinnerTpl: '
', // Error message template errorTpl: '

{{ERROR}}

', btnTpl: { download: '' + '' + '' + "" + "", zoom: '", close: '", // This small close button will be appended to your html/inline/ajax content by default, // if "smallBtn" option is not set to false smallBtn: '', // Arrows arrowLeft: '' + '' + '' + "" + "", arrowRight: '' + '' + '' + "" + "" }, // Container is injected into this element parentEl: "body", // Focus handling // ============== // Try to focus on the first focusable element after opening autoFocus: false, // Put focus back to active element after closing backFocus: true, // Do not let user to focus on element outside modal content trapFocus: true, // Module specific options // ======================= fullScreen: { autoStart: false }, // Set `touch: false` to disable dragging/swiping touch: { vertical: true, // Allow to drag content vertically momentum: true // Continue movement after releasing mouse/touch when panning }, // Hash value when initializing manually, // set `false` to disable hash change hash: null, // Customize or add new media types // Example: /* media : { youtube : { params : { autoplay : 0 } } } */ media: {}, slideShow: { autoStart: false, speed: 4000 }, thumbs: { autoStart: false, // Display thumbnails on opening hideOnClose: true, // Hide thumbnail grid when closing animation starts parentEl: ".fancybox-container", // Container is injected into this element axis: "y" // Vertical (y) or horizontal (x) scrolling }, // Use mousewheel to navigate gallery // If 'auto' - enabled for images only wheel: "auto", // Callbacks //========== // See Documentation/API/Events for more information // Example: /* afterShow: function( instance, current ) { console.info( 'Clicked element:' ); console.info( current.opts.$orig ); } */ onInit: $.noop, // When instance has been initialized beforeLoad: $.noop, // Before the content of a slide is being loaded afterLoad: $.noop, // When the content of a slide is done loading beforeShow: $.noop, // Before open animation starts afterShow: $.noop, // When content is done loading and animating beforeClose: $.noop, // Before the instance attempts to close. Return false to cancel the close. afterClose: $.noop, // After instance has been closed onActivate: $.noop, // When instance is brought to front onDeactivate: $.noop, // When other instance has been activated // Interaction // =========== // Use options below to customize taken action when user clicks or double clicks on the fancyBox area, // each option can be string or method that returns value. // // Possible values: // "close" - close instance // "next" - move to next gallery item // "nextOrClose" - move to next gallery item or close if gallery has only one item // "toggleControls" - show/hide controls // "zoom" - zoom image (if loaded) // false - do nothing // Clicked on the content clickContent: function(current, event) { return current.type === "image" ? "zoom" : false; }, // Clicked on the slide clickSlide: "close", // Clicked on the background (backdrop) element; // if you have not changed the layout, then most likely you need to use `clickSlide` option clickOutside: "close", // Same as previous two, but for double click dblclickContent: false, dblclickSlide: false, dblclickOutside: false, // Custom options when mobile device is detected // ============================================= mobile: { idleTime: false, clickContent: function(current, event) { return current.type === "image" ? "toggleControls" : false; }, clickSlide: function(current, event) { return current.type === "image" ? "toggleControls" : "close"; }, dblclickContent: function(current, event) { return current.type === "image" ? "zoom" : false; }, dblclickSlide: function(current, event) { return current.type === "image" ? "zoom" : false; } }, // Internationalization // ==================== lang: "en", i18n: { en: { CLOSE: "Close", NEXT: "Next", PREV: "Previous", ERROR: "The requested content cannot be loaded.
Please try again later.", PLAY_START: "Start slideshow", PLAY_STOP: "Pause slideshow", FULL_SCREEN: "Full screen", THUMBS: "Thumbnails", DOWNLOAD: "Download", SHARE: "Share", ZOOM: "Zoom" }, de: { CLOSE: "Schliessen", NEXT: "Weiter", PREV: "Zurück", ERROR: "Die angeforderten Daten konnten nicht geladen werden.
Bitte versuchen Sie es später nochmal.", PLAY_START: "Diaschau starten", PLAY_STOP: "Diaschau beenden", FULL_SCREEN: "Vollbild", THUMBS: "Vorschaubilder", DOWNLOAD: "Herunterladen", SHARE: "Teilen", ZOOM: "Maßstab" } } }; // Few useful variables and methods // ================================ var $W = $(window); var $D = $(document); var called = 0; // Check if an object is a jQuery object and not a native JavaScript object // ======================================================================== var isQuery = function(obj) { return obj && obj.hasOwnProperty && obj instanceof $; }; // Handle multiple browsers for "requestAnimationFrame" and "cancelAnimationFrame" // =============================================================================== var requestAFrame = (function() { return ( window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || // if all else fails, use setTimeout function(callback) { return window.setTimeout(callback, 1000 / 60); } ); })(); // Detect the supported transition-end event property name // ======================================================= var transitionEnd = (function() { var el = document.createElement("fakeelement"), t; var transitions = { transition: "transitionend", OTransition: "oTransitionEnd", MozTransition: "transitionend", WebkitTransition: "webkitTransitionEnd" }; for (t in transitions) { if (el.style[t] !== undefined) { return transitions[t]; } } return "transitionend"; })(); // Force redraw on an element. // This helps in cases where the browser doesn't redraw an updated element properly // ================================================================================ var forceRedraw = function($el) { return $el && $el.length && $el[0].offsetHeight; }; // Exclude array (`buttons`) options from deep merging // =================================================== var mergeOpts = function(opts1, opts2) { var rez = $.extend(true, {}, opts1, opts2); $.each(opts2, function(key, value) { if ($.isArray(value)) { rez[key] = value; } }); return rez; }; // Class definition // ================ var FancyBox = function(content, opts, index) { var self = this; self.opts = mergeOpts({index: index}, $.fancybox.defaults); if ($.isPlainObject(opts)) { self.opts = mergeOpts(self.opts, opts); } if ($.fancybox.isMobile) { self.opts = mergeOpts(self.opts, self.opts.mobile); } self.id = self.opts.id || ++called; self.currIndex = parseInt(self.opts.index, 10) || 0; self.prevIndex = null; self.prevPos = null; self.currPos = 0; self.firstRun = true; // All group items self.group = []; // Existing slides (for current, next and previous gallery items) self.slides = {}; // Create group elements self.addContent(content); if (!self.group.length) { return; } // Save last active element self.$lastFocus = $(document.activeElement).trigger("blur"); self.init(); }; $.extend(FancyBox.prototype, { // Create DOM structure // ==================== init: function() { var self = this, firstItem = self.group[self.currIndex], firstItemOpts = firstItem.opts, scrollbarWidth = $.fancybox.scrollbarWidth, $scrollDiv, $container, buttonStr; // Hide scrollbars // =============== if (!$.fancybox.getInstance() && firstItemOpts.hideScrollbar !== false) { $("body").addClass("fancybox-active"); if (!$.fancybox.isMobile && document.body.scrollHeight > window.innerHeight) { if (scrollbarWidth === undefined) { $scrollDiv = $('
').appendTo("body"); scrollbarWidth = $.fancybox.scrollbarWidth = $scrollDiv[0].offsetWidth - $scrollDiv[0].clientWidth; $scrollDiv.remove(); } $("head").append( '" ); $("body").addClass("compensate-for-scrollbar"); } } // Build html markup and set references // ==================================== // Build html code for buttons and insert into main template buttonStr = ""; $.each(firstItemOpts.buttons, function(index, value) { buttonStr += firstItemOpts.btnTpl[value] || ""; }); // Create markup from base template, it will be initially hidden to // avoid unnecessary work like painting while initializing is not complete $container = $( self.translate( self, firstItemOpts.baseTpl .replace("{{buttons}}", buttonStr) .replace("{{arrows}}", firstItemOpts.btnTpl.arrowLeft + firstItemOpts.btnTpl.arrowRight) ) ) .attr("id", "fancybox-container-" + self.id) .addClass("fancybox-is-hidden") .addClass(firstItemOpts.baseClass) .data("FancyBox", self) .appendTo(firstItemOpts.parentEl); // Create object holding references to jQuery wrapped nodes self.$refs = { container: $container }; ["bg", "inner", "infobar", "toolbar", "stage", "caption", "navigation"].forEach(function(item) { self.$refs[item] = $container.find(".fancybox-" + item); }); self.trigger("onInit"); // Enable events, deactive previous instances self.activate(); // Build slides, load and reveal content self.jumpTo(self.currIndex); }, // Simple i18n support - replaces object keys found in template // with corresponding values // ============================================================ translate: function(obj, str) { var arr = obj.opts.i18n[obj.opts.lang]; return str.replace(/\{\{(\w+)\}\}/g, function(match, n) { var value = arr[n]; if (value === undefined) { return match; } return value; }); }, // Populate current group with fresh content // Check if each object has valid type and content // =============================================== addContent: function(content) { var self = this, items = $.makeArray(content), thumbs; $.each(items, function(i, item) { var obj = {}, opts = {}, $item, type, found, src, srcParts; // Step 1 - Make sure we have an object // ==================================== if ($.isPlainObject(item)) { // We probably have manual usage here, something like // $.fancybox.open( [ { src : "image.jpg", type : "image" } ] ) obj = item; opts = item.opts || item; } else if ($.type(item) === "object" && $(item).length) { // Here we probably have jQuery collection returned by some selector $item = $(item); // Support attributes like `data-options='{"touch" : false}'` and `data-touch='false'` opts = $item.data() || {}; opts = $.extend(true, {}, opts, opts.options); // Here we store clicked element opts.$orig = $item; obj.src = self.opts.src || opts.src || $item.attr("href"); // Assume that simple syntax is used, for example: // `$.fancybox.open( $("#test"), {} );` if (!obj.type && !obj.src) { obj.type = "inline"; obj.src = item; } } else { // Assume we have a simple html code, for example: // $.fancybox.open( '

Hi!

' ); obj = { type: "html", src: item + "" }; } // Each gallery object has full collection of options obj.opts = $.extend(true, {}, self.opts, opts); // Do not merge buttons array if ($.isArray(opts.buttons)) { obj.opts.buttons = opts.buttons; } // Step 2 - Make sure we have content type, if not - try to guess // ============================================================== type = obj.type || obj.opts.type; src = obj.src || ""; if (!type && src) { if ((found = src.match(/\.(mp4|mov|ogv)((\?|#).*)?$/i))) { type = "video"; if (!obj.opts.videoFormat) { obj.opts.videoFormat = "video/" + (found[1] === "ogv" ? "ogg" : found[1]); } } else if (src.match(/(^data:image\/[a-z0-9+\/=]*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg|ico)((\?|#).*)?$)/i)) { type = "image"; } else if (src.match(/\.(pdf)((\?|#).*)?$/i)) { type = "iframe"; } else if (src.charAt(0) === "#") { type = "inline"; } } if (type) { obj.type = type; } else { self.trigger("objectNeedsType", obj); } if (!obj.contentType) { obj.contentType = $.inArray(obj.type, ["html", "inline", "ajax"]) > -1 ? "html" : obj.type; } // Step 3 - Some adjustments // ========================= obj.index = self.group.length; if (obj.opts.smallBtn == "auto") { obj.opts.smallBtn = $.inArray(obj.type, ["html", "inline", "ajax"]) > -1; } if (obj.opts.toolbar === "auto") { obj.opts.toolbar = !obj.opts.smallBtn; } // Find thumbnail image if (obj.opts.$trigger && obj.index === self.opts.index) { obj.opts.$thumb = obj.opts.$trigger.find("img:first"); } if ((!obj.opts.$thumb || !obj.opts.$thumb.length) && obj.opts.$orig) { obj.opts.$thumb = obj.opts.$orig.find("img:first"); } // "caption" is a "special" option, it can be used to customize caption per gallery item .. if ($.type(obj.opts.caption) === "function") { obj.opts.caption = obj.opts.caption.apply(item, [self, obj]); } if ($.type(self.opts.caption) === "function") { obj.opts.caption = self.opts.caption.apply(item, [self, obj]); } // Make sure we have caption as a string or jQuery object if (!(obj.opts.caption instanceof $)) { obj.opts.caption = obj.opts.caption === undefined ? "" : obj.opts.caption + ""; } // Check if url contains "filter" used to filter the content // Example: "ajax.html #something" if (obj.type === "ajax") { srcParts = src.split(/\s+/, 2); if (srcParts.length > 1) { obj.src = srcParts.shift(); obj.opts.filter = srcParts.shift(); } } // Hide all buttons and disable interactivity for modal items if (obj.opts.modal) { obj.opts = $.extend(true, obj.opts, { // Remove buttons infobar: 0, toolbar: 0, smallBtn: 0, // Disable keyboard navigation keyboard: 0, // Disable some modules slideShow: 0, fullScreen: 0, thumbs: 0, touch: 0, // Disable click event handlers clickContent: false, clickSlide: false, clickOutside: false, dblclickContent: false, dblclickSlide: false, dblclickOutside: false }); } // Step 4 - Add processed object to group // ====================================== self.group.push(obj); }); // Update controls if gallery is already opened if (Object.keys(self.slides).length) { self.updateControls(); // Update thumbnails, if needed thumbs = self.Thumbs; if (thumbs && thumbs.isActive) { thumbs.create(); thumbs.focus(); } } }, // Attach an event handler functions for: // - navigation buttons // - browser scrolling, resizing; // - focusing // - keyboard // - detect idle // ====================================== addEvents: function() { var self = this; self.removeEvents(); // Make navigation elements clickable self.$refs.container .on("click.fb-close", "[data-fancybox-close]", function(e) { e.stopPropagation(); e.preventDefault(); self.close(e); }) .on("touchstart.fb-prev click.fb-prev", "[data-fancybox-prev]", function(e) { e.stopPropagation(); e.preventDefault(); self.previous(); }) .on("touchstart.fb-next click.fb-next", "[data-fancybox-next]", function(e) { e.stopPropagation(); e.preventDefault(); self.next(); }) .on("click.fb", "[data-fancybox-zoom]", function(e) { // Click handler for zoom button self[self.isScaledDown() ? "scaleToActual" : "scaleToFit"](); }); // Handle page scrolling and browser resizing $W.on("orientationchange.fb resize.fb", function(e) { if (e && e.originalEvent && e.originalEvent.type === "resize") { requestAFrame(function() { self.update(); }); } else { self.$refs.stage.hide(); setTimeout(function() { self.$refs.stage.show(); self.update(); }, $.fancybox.isMobile ? 600 : 250); } }); // Trap keyboard focus inside of the modal, so the user does not accidentally tab outside of the modal // (a.k.a. "escaping the modal") $D.on("focusin.fb", function(e) { var instance = $.fancybox ? $.fancybox.getInstance() : null; if ( instance.isClosing || !instance.current || !instance.current.opts.trapFocus || $(e.target).hasClass("fancybox-container") || $(e.target).is(document) ) { return; } if (instance && $(e.target).css("position") !== "fixed" && !instance.$refs.container.has(e.target).length) { e.stopPropagation(); instance.focus(); } }); // Enable keyboard navigation $D.on("keydown.fb", function(e) { var current = self.current, keycode = e.keyCode || e.which; if (!current || !current.opts.keyboard) { return; } if (e.ctrlKey || e.altKey || e.shiftKey || $(e.target).is("input") || $(e.target).is("textarea")) { return; } // Backspace and Esc keys if (keycode === 8 || keycode === 27) { e.preventDefault(); self.close(e); return; } // Left arrow and Up arrow if (keycode === 37 || keycode === 38) { e.preventDefault(); self.previous(); return; } // Righ arrow and Down arrow if (keycode === 39 || keycode === 40) { e.preventDefault(); self.next(); return; } self.trigger("afterKeydown", e, keycode); }); // Hide controls after some inactivity period if (self.group[self.currIndex].opts.idleTime) { self.idleSecondsCounter = 0; $D.on( "mousemove.fb-idle mouseleave.fb-idle mousedown.fb-idle touchstart.fb-idle touchmove.fb-idle scroll.fb-idle keydown.fb-idle", function(e) { self.idleSecondsCounter = 0; if (self.isIdle) { self.showControls(); } self.isIdle = false; } ); self.idleInterval = window.setInterval(function() { self.idleSecondsCounter++; if (self.idleSecondsCounter >= self.group[self.currIndex].opts.idleTime && !self.isDragging) { self.isIdle = true; self.idleSecondsCounter = 0; self.hideControls(); } }, 1000); } }, // Remove events added by the core // =============================== removeEvents: function() { var self = this; $W.off("orientationchange.fb resize.fb"); $D.off("focusin.fb keydown.fb .fb-idle"); this.$refs.container.off(".fb-close .fb-prev .fb-next"); if (self.idleInterval) { window.clearInterval(self.idleInterval); self.idleInterval = null; } }, // Change to previous gallery item // =============================== previous: function(duration) { return this.jumpTo(this.currPos - 1, duration); }, // Change to next gallery item // =========================== next: function(duration) { return this.jumpTo(this.currPos + 1, duration); }, // Switch to selected gallery item // =============================== jumpTo: function(pos, duration) { var self = this, groupLen = self.group.length, firstRun, loop, current, previous, canvasWidth, currentPos, transitionProps; if (self.isDragging || self.isClosing || (self.isAnimating && self.firstRun)) { return; } pos = parseInt(pos, 10); // Should loop? loop = self.current ? self.current.opts.loop : self.opts.loop; if (!loop && (pos < 0 || pos >= groupLen)) { return false; } firstRun = self.firstRun = !Object.keys(self.slides).length; if (groupLen < 2 && !firstRun && !!self.isDragging) { return; } previous = self.current; self.prevIndex = self.currIndex; self.prevPos = self.currPos; // Create slides current = self.createSlide(pos); if (groupLen > 1) { if (loop || current.index > 0) { self.createSlide(pos - 1); } if (loop || current.index < groupLen - 1) { self.createSlide(pos + 1); } } self.current = current; self.currIndex = current.index; self.currPos = current.pos; self.trigger("beforeShow", firstRun); self.updateControls(); currentPos = $.fancybox.getTranslate(current.$slide); current.isMoved = (currentPos.left !== 0 || currentPos.top !== 0) && !current.$slide.hasClass("fancybox-animated"); // Validate duration length current.forcedDuration = undefined; if ($.isNumeric(duration)) { current.forcedDuration = duration; } else { duration = current.opts[firstRun ? "animationDuration" : "transitionDuration"]; } duration = parseInt(duration, 10); // Fresh start - reveal container, current slide and start loading content if (firstRun) { if (current.opts.animationEffect && duration) { self.$refs.container.css("transition-duration", duration + "ms"); } self.$refs.container.removeClass("fancybox-is-hidden"); forceRedraw(self.$refs.container); self.$refs.container.addClass("fancybox-is-open"); forceRedraw(self.$refs.container); // Make current slide visible current.$slide.addClass("fancybox-slide--previous"); // Attempt to load content into slide; // at this point image would start loading, but inline/html content would load immediately self.loadSlide(current); current.$slide.removeClass("fancybox-slide--previous").addClass("fancybox-slide--current"); self.preload("image"); return; } // Clean up $.each(self.slides, function(index, slide) { $.fancybox.stop(slide.$slide); }); // Make current that slide is visible even if content is still loading current.$slide.removeClass("fancybox-slide--next fancybox-slide--previous").addClass("fancybox-slide--current"); // If slides have been dragged, animate them to correct position if (current.isMoved) { canvasWidth = Math.round(current.$slide.width()); $.each(self.slides, function(index, slide) { var pos = slide.pos - current.pos; $.fancybox.animate( slide.$slide, { top: 0, left: pos * canvasWidth + pos * slide.opts.gutter }, duration, function() { slide.$slide.removeAttr("style").removeClass("fancybox-slide--next fancybox-slide--previous"); if (slide.pos === self.currPos) { current.isMoved = false; self.complete(); } } ); }); } else { self.$refs.stage.children().removeAttr("style"); } // Start transition that reveals current content // or wait when it will be loaded if (current.isLoaded) { self.revealContent(current); } else { self.loadSlide(current); } self.preload("image"); if (previous.pos === current.pos) { return; } // Handle previous slide // ===================== transitionProps = "fancybox-slide--" + (previous.pos > current.pos ? "next" : "previous"); previous.$slide.removeClass("fancybox-slide--complete fancybox-slide--current fancybox-slide--next fancybox-slide--previous"); previous.isComplete = false; if (!duration || (!current.isMoved && !current.opts.transitionEffect)) { return; } if (current.isMoved) { previous.$slide.addClass(transitionProps); } else { transitionProps = "fancybox-animated " + transitionProps + " fancybox-fx-" + current.opts.transitionEffect; $.fancybox.animate(previous.$slide, transitionProps, duration, function() { previous.$slide.removeClass(transitionProps).removeAttr("style"); }); } }, // Create new "slide" element // These are gallery items that are actually added to DOM // ======================================================= createSlide: function(pos) { var self = this, $slide, index; index = pos % self.group.length; index = index < 0 ? self.group.length + index : index; if (!self.slides[pos] && self.group[index]) { $slide = $('
').appendTo(self.$refs.stage); self.slides[pos] = $.extend(true, {}, self.group[index], { pos: pos, $slide: $slide, isLoaded: false }); self.updateSlide(self.slides[pos]); } return self.slides[pos]; }, // Scale image to the actual size of the image; // x and y values should be relative to the slide // ============================================== scaleToActual: function(x, y, duration) { var self = this, current = self.current, $content = current.$content, canvasWidth = $.fancybox.getTranslate(current.$slide).width, canvasHeight = $.fancybox.getTranslate(current.$slide).height, newImgWidth = current.width, newImgHeight = current.height, imgPos, posX, posY, scaleX, scaleY; if (self.isAnimating || !$content || !(current.type == "image" && current.isLoaded && !current.hasError)) { return; } $.fancybox.stop($content); self.isAnimating = true; x = x === undefined ? canvasWidth * 0.5 : x; y = y === undefined ? canvasHeight * 0.5 : y; imgPos = $.fancybox.getTranslate($content); imgPos.top -= $.fancybox.getTranslate(current.$slide).top; imgPos.left -= $.fancybox.getTranslate(current.$slide).left; scaleX = newImgWidth / imgPos.width; scaleY = newImgHeight / imgPos.height; // Get center position for original image posX = canvasWidth * 0.5 - newImgWidth * 0.5; posY = canvasHeight * 0.5 - newImgHeight * 0.5; // Make sure image does not move away from edges if (newImgWidth > canvasWidth) { posX = imgPos.left * scaleX - (x * scaleX - x); if (posX > 0) { posX = 0; } if (posX < canvasWidth - newImgWidth) { posX = canvasWidth - newImgWidth; } } if (newImgHeight > canvasHeight) { posY = imgPos.top * scaleY - (y * scaleY - y); if (posY > 0) { posY = 0; } if (posY < canvasHeight - newImgHeight) { posY = canvasHeight - newImgHeight; } } self.updateCursor(newImgWidth, newImgHeight); $.fancybox.animate( $content, { top: posY, left: posX, scaleX: scaleX, scaleY: scaleY }, duration || 330, function() { self.isAnimating = false; } ); // Stop slideshow if (self.SlideShow && self.SlideShow.isActive) { self.SlideShow.stop(); } }, // Scale image to fit inside parent element // ======================================== scaleToFit: function(duration) { var self = this, current = self.current, $content = current.$content, end; if (self.isAnimating || !$content || !(current.type == "image" && current.isLoaded && !current.hasError)) { return; } $.fancybox.stop($content); self.isAnimating = true; end = self.getFitPos(current); self.updateCursor(end.width, end.height); $.fancybox.animate( $content, { top: end.top, left: end.left, scaleX: end.width / $content.width(), scaleY: end.height / $content.height() }, duration || 330, function() { self.isAnimating = false; } ); }, // Calculate image size to fit inside viewport // =========================================== getFitPos: function(slide) { var self = this, $content = slide.$content, width = slide.width || slide.opts.width, height = slide.height || slide.opts.height, maxWidth, maxHeight, minRatio, margin, aspectRatio, rez = {}; if (!slide.isLoaded || !$content || !$content.length) { return false; } margin = { top: parseInt(slide.$slide.css("paddingTop"), 10), right: parseInt(slide.$slide.css("paddingRight"), 10), bottom: parseInt(slide.$slide.css("paddingBottom"), 10), left: parseInt(slide.$slide.css("paddingLeft"), 10) }; // We can not use $slide width here, because it can have different diemensions while in transiton maxWidth = parseInt(self.$refs.stage.width(), 10) - (margin.left + margin.right); maxHeight = parseInt(self.$refs.stage.height(), 10) - (margin.top + margin.bottom); if (!width || !height) { width = maxWidth; height = maxHeight; } minRatio = Math.min(1, maxWidth / width, maxHeight / height); // Use floor rounding to make sure it really fits width = Math.floor(minRatio * width); height = Math.floor(minRatio * height); if (slide.type === "image") { rez.top = Math.floor((maxHeight - height) * 0.5) + margin.top; rez.left = Math.floor((maxWidth - width) * 0.5) + margin.left; } else if (slide.contentType === "video") { // Force aspect ratio for the video // "I say the whole world must learn of our peaceful ways… by force!" aspectRatio = slide.opts.width && slide.opts.height ? width / height : slide.opts.ratio || 16 / 9; if (height > width / aspectRatio) { height = width / aspectRatio; } else if (width > height * aspectRatio) { width = height * aspectRatio; } } rez.width = width; rez.height = height; return rez; }, // Update content size and position for all slides // ============================================== update: function() { var self = this; $.each(self.slides, function(key, slide) { self.updateSlide(slide); }); }, // Update slide content position and size // ====================================== updateSlide: function(slide, duration) { var self = this, $content = slide && slide.$content, width = slide.width || slide.opts.width, height = slide.height || slide.opts.height; if ($content && (width || height || slide.contentType === "video") && !slide.hasError) { $.fancybox.stop($content); $.fancybox.setTranslate($content, self.getFitPos(slide)); if (slide.pos === self.currPos) { self.isAnimating = false; self.updateCursor(); } } slide.$slide.trigger("refresh"); self.$refs.toolbar.toggleClass("compensate-for-scrollbar", slide.$slide.get(0).scrollHeight > slide.$slide.get(0).clientHeight); self.trigger("onUpdate", slide); }, // Horizontally center slide // ========================= centerSlide: function(slide, duration) { var self = this, canvasWidth, pos; if (self.current) { canvasWidth = Math.round(slide.$slide.width()); pos = slide.pos - self.current.pos; $.fancybox.animate( slide.$slide, { top: 0, left: pos * canvasWidth + pos * slide.opts.gutter, opacity: 1 }, duration === undefined ? 0 : duration, null, false ); } }, // Update cursor style depending if content can be zoomed // ====================================================== updateCursor: function(nextWidth, nextHeight) { var self = this, current = self.current, $container = self.$refs.container.removeClass("fancybox-is-zoomable fancybox-can-zoomIn fancybox-can-drag fancybox-can-zoomOut"), isZoomable; if (!current || self.isClosing) { return; } isZoomable = self.isZoomable(); $container.toggleClass("fancybox-is-zoomable", isZoomable); $("[data-fancybox-zoom]").prop("disabled", !isZoomable); // Set cursor to zoom in/out if click event is 'zoom' if ( isZoomable && (current.opts.clickContent === "zoom" || ($.isFunction(current.opts.clickContent) && current.opts.clickContent(current) === "zoom")) ) { if (self.isScaledDown(nextWidth, nextHeight)) { // If image is scaled down, then, obviously, it can be zoomed to full size $container.addClass("fancybox-can-zoomIn"); } else { if (current.opts.touch) { // If image size ir largen than available available and touch module is not disable, // then user can do panning $container.addClass("fancybox-can-drag"); } else { $container.addClass("fancybox-can-zoomOut"); } } } else if (current.opts.touch && current.contentType !== "video") { $container.addClass("fancybox-can-drag"); } }, // Check if current slide is zoomable // ================================== isZoomable: function() { var self = this, current = self.current, fitPos; // Assume that slide is zoomable if: // - image is still loading // - actual size of the image is smaller than available area if (current && !self.isClosing && current.type === "image" && !current.hasError) { if (!current.isLoaded) { return true; } fitPos = self.getFitPos(current); if (current.width > fitPos.width || current.height > fitPos.height) { return true; } } return false; }, // Check if current image dimensions are smaller than actual // ========================================================= isScaledDown: function(nextWidth, nextHeight) { var self = this, rez = false, current = self.current, $content = current.$content; if (nextWidth !== undefined && nextHeight !== undefined) { rez = nextWidth < current.width && nextHeight < current.height; } else if ($content) { rez = $.fancybox.getTranslate($content); rez = rez.width < current.width && rez.height < current.height; } return rez; }, // Check if image dimensions exceed parent element // =============================================== canPan: function() { var self = this, rez = false, current = self.current, $content; if (current.type === "image" && ($content = current.$content) && !current.hasError) { rez = self.getFitPos(current); rez = Math.abs($content.width() - rez.width) > 1 || Math.abs($content.height() - rez.height) > 1; } return rez; }, // Load content into the slide // =========================== loadSlide: function(slide) { var self = this, type, $slide, ajaxLoad; if (slide.isLoading || slide.isLoaded) { return; } slide.isLoading = true; self.trigger("beforeLoad", slide); type = slide.type; $slide = slide.$slide; $slide .off("refresh") .trigger("onReset") .addClass(slide.opts.slideClass); // Create content depending on the type switch (type) { case "image": self.setImage(slide); break; case "iframe": self.setIframe(slide); break; case "html": self.setContent(slide, slide.src || slide.content); break; case "video": self.setContent( slide, '