Skip to content

Instantly share code, notes, and snippets.

@syxolk
Created May 14, 2017 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syxolk/dd87169afe547a9648e31900d3c7403b to your computer and use it in GitHub Desktop.
Save syxolk/dd87169afe547a9648e31900d3c7403b to your computer and use it in GitHub Desktop.
Check www.mvg.de for S-Bahn/U-Bahn/Bus departures and use Google TTS to speak it out loud.
#!/usr/bin/env python3
import requests
import datetime
import argparse
from gtts import gTTS
import math
import subprocess
import hashlib
import os.path
import tempfile
import json
def departures(station, line, dest):
slug = "{0}-{1}-{2}".format(station, line, dest)
hash = hashlib.sha1(slug.encode("utf-8")).hexdigest()
filename = "mvgit-{0}.json".format(hash)
path = os.path.join(tempfile.gettempdir(), filename)
try:
with open(path) as data_file:
data = json.load(data_file)
now = datetime.datetime.now()
future_departs = list(filter(lambda x: datetime.datetime.fromtimestamp(x) > now, data))
if len(future_departs) >= 2:
return future_departs
else:
raise ValueError('Cache is too old')
except:
# Either cache file was not found or data is outdated.
print("Ask MVG ...")
r = requests.get("https://www.mvg.de/fahrinfo/api/departure/" + str(station),
params={"footway": 0},
headers={
"X-MVG-Authorization-Key": "5af1beca494712ed38d313714d4caff6",
"User-Agent": "MVGit/0.1.0"
})
deps = r.json()["departures"]
data = [
x["departureTime"] // 1000
for x in deps
if x["product"].upper() + x["label"] == line and dest in x["destination"]
]
with open(path, 'w') as cache_file:
json.dump(data, cache_file)
return data
def build_sentence(departures):
now = datetime.datetime.now()
departures = [
str(math.floor((datetime.datetime.fromtimestamp(x) - now).total_seconds() / 60))
for x in departures[0:2]
]
if len(departures) >= 2:
part = "{0} oder {1}".format(departures[0], departures[1])
elif len(departures) == 1:
part = departures[0]
else:
return "Heute fährt nichts."
return "Der Bus fährt in {0} Minuten.".format(part)
def main():
parser = argparse.ArgumentParser(description="MVG Departures")
parser.add_argument('--station', type=int, required=True,
help='Station ID (2 for Marienplatz)')
parser.add_argument('--line', required=True,
help='Transportation Line (e.g. U6, B690, S1)')
parser.add_argument('--dest', required=True,
help='Substring of destination')
args = parser.parse_args()
text = build_sentence(departures(args.station, args.line, args.dest))
#print(text)
filename = "mvgit-{0}.mp3".format(hashlib.sha1(text.encode("utf-8")).hexdigest())
path = os.path.join(tempfile.gettempdir(), filename)
if not os.path.isfile(path):
print("Ask Google ...")
tts = gTTS(text=text, lang='de')
tts.save(path)
subprocess.call(["mpg321", "-q", path])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment