Skip to content

Instantly share code, notes, and snippets.

@meganehouser
Last active February 10, 2018 04:21
Show Gist options
  • Save meganehouser/07a7aa8526ab233e4867e6810a5115be to your computer and use it in GitHub Desktop.
Save meganehouser/07a7aa8526ab233e4867e6810a5115be to your computer and use it in GitHub Desktop.
ゴミの日をGoogle homeで教えてもらう
# coding: utf-8
from datetime import date
from pathlib import Path
import os
import hashlib
import threading
import time
from wsgiref import simple_server
import pychromecast
from gtts import gTTS
import falcon
import settings as conf
weekdays = ['月', '火', '水', '木', '金', '土', '日']
def get_nweekday(d: date) -> (int, int):
first = date(d.year, d.month, 1).weekday()
weekdays = [(first + x) % 7 for x in range(0, d.day)]
wd = d.weekday()
cnt = weekdays.count(wd)
return cnt, wd
def generate_talk(text, lang):
text_token = hashlib.sha256((lang + text).encode()).hexdigest()
talk_path = conf.talks_dir / text_token
if not talk_path.exists():
tts = gTTS(text=text, lang=lang)
tts.save(talk_path)
return text_token
class Talk():
def __init__(self, token):
self.token = token
def on_get(self, req, resp):
resp.content_type = 'audio/mp3'
audio_path = conf.talks_dir / self.token
stream = audio_path.open(mode='rb')
size = os.path.getsize(audio_path)
resp.stream, resp.stream_len = stream, size
def talk_home():
chcasts = pychromecast.get_chromecasts()
for ch in chcasts:
if ch.device.friendly_name == conf.device_name:
chcast = ch
break
url = f"http://{conf.server_ipaddr}:{conf.server_port}/talk"
chcast.wait()
mc = chcast.media_controller
mc.play_media(url, 'audio/mp3')
def create_app(talk:str):
token = generate_talk(talk, 'ja')
api = falcon.API()
api.add_route('/talk', Talk(token))
return api
def serve_app(message: str):
api = create_app(message)
with simple_server.make_server(conf.server_ipaddr, conf.server_port, api) as httpd:
httpd.handle_request()
def talk_grbg(d: date):
n, wday = get_nweekday(d)
weekday = weekdays[wday]
key = (str(n), weekday)
message = None
if key in conf.grbg_days:
grbg = conf.grbg_days[key]
message = f"今日は第{n}{weekday}曜日。{grbg}の日だよ。"
elif ('*', weekday) in conf.grbg_days:
grbg = conf.grbg_days[('*', weekday)]
message = f"今日は{weekday}曜日。{grbg}の日だよ。"
if message:
print(message)
talk_thread = threading.Thread(target=serve_app, name="talk server", args=(message,))
talk_thread.setDaemon(True)
talk_thread.start()
time.sleep(10)
talk_home()
talk_thread.join(timeout=10)
if __name__ == '__main__':
d = date.today()
talk_grbg(d)
# coding: utf-8
import os
from pathlib import Path
server_ipaddr = '127.0.0.1'
server_port = 8818
device_name = 'My Google Home'
talks_dir = Path(os.path.dirname(__file__)) / 'talks'
grbg_days = [{('*', '月'), "古紙回収"},
{('*', '火'), "資源回収"},
{('*', '水'), "燃やすゴミ"},
{('1', '木'), "燃やさなゴミ"},
{('3', '木'), "燃やさなゴミ"},
{('*', '土'), "燃やすゴミ"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment