#!/usr/local/bin/python
## -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import sys
from datetime import datetime, timedelta
from datetime import date as Date
import codecs
intent = None
date = None
period = None
machine_name = None
def get_parameters(): # {{{
global intent, date, period, machine_name
today = Date.today()
inp = json.load(sys.stdin)
try:
_result = inp['result']
_metadata = _result['metadata']
_params = _result['parameters']
intent = _metadata['intentName']
date = _params.get('date', "")
period = _params.get('date-period', "")
machine_name = _params.get('machine-name', "")
except:
pass
if date:
d = datetime.strptime(date, "%Y-%m-%d")
date = Date(d.year, d.month, d.day)
if date > today: # no future. people always wants "PAST" event
date = Date(d.year-1, d.month, d.day)
elif not period: # if there were no date infos, a good guess is "TODAY"
date = today
# }}}
def _dec(s): # {{{
return codecs.decode(s,'rot13')
# }}}
def weekdiff(d): # {{{
_, cday, _ = d.isocalendar()
_, tday, _ = (Date.today()+timedelta(1)).isocalendar()
if tday > cday:
return tday - cday
else:
return 52+ tday -cday
# }}}
def machine(date, period): # {{{
import urllib2
import lxml.html
import re
week = ""
if period:
sfrom, _ = period.split('/')
d = datetime.strptime(sfrom, "%Y-%m-%d")
f = Date(d.year, d.month, d.day)
diff = weekdiff(f)
if diff > 0:
week = "?week=%d" % diff
if date:
diff = weekdiff(date)
if diff > 0:
week = "?week=%d" % diff
today = date.strftime("%-m/%d")
else:
today = ""
url = 'http://ist.ksc.kwansei.ac.jp/~tutimura/cgi-bin/lab/' + week
user = 'whaov'
password = 'Tey12ufw'
headers ={}
headers["authorization"] = "Basic " + (_dec(user) + ":" + _dec(password)).encode("base64")[:-1]
req = urllib2.Request(url=url, headers=headers)
res = urllib2.urlopen(req)
tree = lxml.html.etree.HTML(res.read().decode('utf-8'))
table = tree[1][-4]
days = table[0][1:]
line = ""
for i in range(len(days)):
if today and days[i].text[:len(today)] != today:
continue
tmp = ""
for j in table[1:]:
if j[0].text == "二重排除":
if j[i+1].findall('a'):
tmp += ",二重排除が何件かでているようです。"
else:
entries = [l.text[0] + " " + l.text[1] + " " + l.text[2:] for l in j[i+1].findall('a')]
s = u"と".join(entries)
if s != '':
tmp += u"," + s + u"が" + j[0].text + u"のようです。"
if tmp:
day = re.sub('/', u'月', days[i].text)
line += day
line += tmp
if line == "":
line = u"なにもありません。平和でなによりです"
return line
# }}}
def ondotori(date, period): # {{{
import csv
if date == "":
date = Date.today()
today = date.strftime("%Y/%m/%d")
comlog = csv.reader(open("ComLog.txt"))
ok = {}
for row in comlog:
if row[0].startswith(today):
data = [x.decode('shiftjis') for x in row]
if data[1] in ok and ok[data[1]] == u'成功':
continue
ok[data[1]] = data[3]
s = u""
for x in ok:
if ok[x] != u'成功':
s += x+ u"番,"
if s == u"":
s = "全部成功です。やった!"
else:
s += "が失敗しています"
return "センサー" + s
# }}}
def _search(name): # {{{
return [
("f", "w", 1), ("f", "w", 1), ("f", "w", 1), ("f", "w", 1),
("f", "w", 2), ("f", "w", 2), ("f", "w", 2), ("f", "w", 2),
("f", "w", 3), ("f", "w", 3), ("f", "w", 3), ("f", "w", 3),
("f", "w", 4), ("f", "w", 4), ("f", "w", 4), ("f", "w", 4),
("b", "w", 5), ("b", "w", 5), ("b", "w", 5), ("b", "w", 5),
("f", "m", 6), ("f", "m", 6), ("f", "m", 6), ("f", "m", 6),
("f", "m", 7), ("f", "m", 7), ("f", "m", 7), ("f", "m", 7),
("f", "m", 8), ("f", "m", 8), ("f", "m", 8), ("f", "m", 8),
("f", "m", 9), ("f", "m", 9), ("f", "m", 9), ("f", "m", 9),
("b", "m",10), ("f", "m",10), ("f", "m",10), ("f", "m",10),
("f", "c", 1), ("f", "c", 1), ("f", "c", 1), ("f", "c", 1),
("f", "c", 1), ("f", "c", 1), ("f", "c", 1), ("f", "c", 1),
("f", "c", 1), ("f", "c", 1), ("f", "c", 1), ("f", "c", 1),
("f", "c", 1), ("f", "c", 1), ("f", "c", 1), ("f", "c", 1),
("b", "c", 1), ("f", "c", 1), ("f", "c", 1), ("f", "c", 1),
("f", "w", 1), ("f", "w", 1), ("f", "w", 1), ("j", "w", 1),
("j", "w", 1), ("f", "w", 1), ("f", "w", 1), ("f", "w", 1),
][int(name)]
# }}}
def location(name): #{{{
room, col, n = _search(name)
s = ""
if room == "f":
s += "前側の部屋,"
elif room == "b":
s += "後側の部屋,"
if col == "w":
s += "窓側"
elif col == "c":
s += "廊下側"
elif col == "m":
s += "真ん中"
s += "前から" + str(n) + "番目の島です"
if room == "j":
s = "準備室ですよ。ボケてるんですか?"
return s
# }}}
def log(name): # {{{
url = 'http://ist.ksc.kwansei.ac.jp/~tutimura/cgi-bin/lab/?room=HSJ-' + name.rjust(2,'0')
user = 'whaov'
password = 'Tey12ufw'
headers ={}
headers["authorization"] = "Basic " + (_dec(user) + ":" + _dec(password)).encode("base64")[:-1]
req = urllib2.Request(url=url, headers=headers)
res = urllib2.urlopen(req)
tree = lxml.html.etree.HTML(res.read().decode('utf-8'))
return "わかりません"
#}}}
get_parameters()
answer = ""
if intent == "ondotoriIntent":
answer += ondotori(date, period)
elif intent == "machineIntent":
answer += machine(date, period)
elif intent == "locationIntent":
answer += location(machine_name)
elif intent == "logIntent":
answer += log(machine_name)
if answer == "":
from random import choice
answer = choice((
u"なにかおかしいです -- ",
u"よくわかりませんでした",
u"困っちゃいました",
u"残念です",
u"主語について言われたことが、或る場合には、主語の概念という意味をもつが、別の場合には、主語の述語または偶有性の意味しかもたないのであるが、このことは、思弁的な態度と論証的(形式的)態度を混合しさえしなければ、避けられたはずの困難から生れるのである。",
u"えっ?",
u"なにかおかしいです -- "))
output = {"speech": answer}
d = json.dumps(output, ensure_ascii=False)
print "Content-Type: application/json; charset=UTF-8\n"
print d.encode("utf-8")
# vim:foldmethod=marker:ts=4:sw=4:expandtab: