PNA.fi koodi

food.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. #!/usr/bin/env perl
  2. # encoding: UTF-8
  3. # Ruokalistaparseri
  4. # Copyright (c) 2016 Toni Fadjukoff
  5. # Based on food.pl by
  6. # Copyright (c) 2007-2010 Timo Sirainen
  7. # 2011-2016 Toni Fadjukoff
  8. # This is Public Domain
  9. day_names = [ "Maanantai", "Tiistai", "Keskiviikko", "Torstai",
  10. "Perjantai", "Lauantai", "Sunnuntai" ]
  11. import amica
  12. import sodexo
  13. import juvenes
  14. import pikante
  15. allergies = [ "M", "L", "VL", "G", "K", "Ve" ]
  16. allergy_descriptions = {
  17. "M": "Maidoton",
  18. "L": "Laktoositon","VL": "Vähälaktoosinen",
  19. "G": "Gluteiiniton",
  20. "K": "Kasvis",
  21. "Ve": "Vegaani"
  22. }
  23. import os
  24. import time
  25. import datetime
  26. import re
  27. global_prefix = "";
  28. use_old = True; # 1 is good for testing, 0 for production system!
  29. unordered = []
  30. l = time.localtime()
  31. this_week = datetime.datetime.now().isocalendar()[1]
  32. unordered += amica.get_restaurants(use_old)
  33. unordered += juvenes.get_restaurants(use_old)
  34. unordered += sodexo.get_restaurants(use_old)
  35. unordered += pikante.get_restaurants(use_old)
  36. print(unordered)
  37. max_week = 0;
  38. for r in unordered:
  39. week = r[2]
  40. max_week = week if week > max_week or week == 1 else max_week
  41. if l[6] != 0 and this_week != max_week:
  42. # it's not sunday, don't force next week's menu yet
  43. max_week = this_week
  44. stamp = time.time() - 3600*24*7
  45. max_week_daterange = ""
  46. if max_week >= 1 and max_week <= 52:
  47. # figure out the date range
  48. while True:
  49. stamp_week = int(time.strftime("%W", time.localtime(stamp)))
  50. if stamp_week == max_week:
  51. break
  52. stamp += 3600*24
  53. l1 = time.localtime(stamp)
  54. l2 = time.localtime(stamp + 3600*24*6)
  55. if l1[1] == l2[1]:
  56. # same month
  57. max_week_daterange = "{monday}-{sunday}.{month}.".format(monday=l1[2], sunday=l2[2], month=l1[1])
  58. else:
  59. # different months
  60. max_week_daterange = "{monday}.{month}.-{sunday}.{next_month}.".format(monday=l1[2], month=l1[1],
  61. sunday=l2[2], next_month=l2[1])
  62. max_week_daterange = " (" + str(max_week_daterange) + ")"
  63. file_header = '''<?xml version="1.0" encoding="utf-8"?>
  64. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  65. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi" lang="fi">
  66. <head>
  67. <title>Ruokalistat</title>
  68. <link rel="stylesheet" type="text/css" href="{global_prefix}/ruoka.css" />
  69. </head>
  70. <body>
  71. <div id="notice" style="border: 1px solid black; border-radius: 5px; padding: 5px;">
  72. PNA.fi on kolmannen osapuolen tarjoama palvelu. En voi taata ruokalistojen oikeellisuutta. Virallisen ruokalistan saat näkyviin siirtymällä ravintolan omille sivuille painamalla sen nimestä. Jos huomaat ruokalistassa virheen, nopeiten virhe saadaan pois näkyvistä kun lähetät minulle siitä sähköpostia: <a href="mailto:lamperi+pna@gmail.com">lamperi+pna@gmail.com</a>
  73. </div>
  74. <form method="get" action="/cgi-bin/food.cgi">
  75. '''.format(global_prefix=global_prefix)
  76. file_footer = """
  77. <div class="footer">Päivitetty {stamp}"
  78. <input type="submit\" value=\"Päivitä nyt\" />
  79. / Palaute <a href=\"mailto:lamperi+pna\@gmail.com\">lamperi+pna\@gmail.com</a>
  80. / <a href="{global_prefix}/code.html\">Koodit täältä</a>
  81. / <a href="{global_prefix}/pna.html\">Mikä on PNA?</a>
  82. </div>
  83. </form>
  84. </body>
  85. </html>
  86. """.format(global_prefix=global_prefix, stamp=time.strftime("%d.%m.%Y %H:%M:%S"))
  87. def find_last_day_with_foods(restaurants):
  88. last_day = 0
  89. for r in restaurants:
  90. for day in range(7):
  91. if day in r[3]:
  92. last_day = day if day > last_day else last_day
  93. return last_day
  94. def write_days_header(fout, day, last_day):
  95. fout.write( " <span class=\"days\">")
  96. for i in range(last_day):
  97. if i == day:
  98. fout.write("{0} ".format(day_names[i]))
  99. else:
  100. fout.write("<a href=\"{0}.html\">{1}</a> ".format(i+1, day_names[i]))
  101. if day < 0:
  102. fout.write("Taulukko")
  103. else:
  104. fout.write("<a href=\"table.html\">Taulukko</a>")
  105. fout.write("</span>\n")
  106. def write_prefix_header(fout, prefix, day):
  107. day = "table" if day == 0 else day
  108. fout.write("<span class=\"location\">")
  109. if prefix == "":
  110. fout.write("Kaikki ")
  111. else:
  112. fout.write("<a href=\"{global_prefix}/{day}.html\">Kaikki</a> ".format(global_prefix=global_prefix, day=day))
  113. if prefix == "tay/":
  114. fout.write("TaY ")
  115. else:
  116. fout.write("<a href=\"{global_prefix}/tay/{day}.html\">TaY</a> ".format(global_prefix=global_prefix, day=day))
  117. if prefix == "tays/":
  118. fout.write("TAYS ")
  119. else:
  120. fout.write("<a href=\"{global_prefix}/tays/{day}.html\">TAYS</a> ".format(global_prefix=global_prefix, day=day))
  121. if prefix == "tty/":
  122. fout.write("TTY ")
  123. else:
  124. fout.write("<a href=\"{global_prefix}/tty/{day}.html\">TTY</a> ".format(global_prefix=global_prefix, day=day))
  125. fout.write("</span>\n")
  126. def write_day(day, header, outfname, last_day, restaurants, prefix):
  127. with open(outfname, "w") as fout:
  128. fout.write("{file_header}<h1>{header}</h1>\n".format(file_header=file_header, header=header))
  129. # print weekday links
  130. fout.write("<div class=\"title\">\n")
  131. write_days_header(fout, day, last_day)
  132. fout.write(" <span class=\"allergy\">Näytä: ")
  133. for a in allergies:
  134. fout.write("<input type=\"checkbox\" name=\"allergy_{a}\" id=\"allergy_{a}\" onclick=\"highlight()\" />".format(a=a))
  135. fout.write("<span title=\"{allergy_description}\">{a}</span>".format(allergy_description=allergy_descriptions[a], a=a))
  136. fout.write("</span>\n")
  137. write_prefix_header(fout, prefix, day+1);
  138. fout.write("</div>\n")
  139. # print foods
  140. foodnum = 0
  141. eatable_food_numbers = {}
  142. maybe_eatable_food_numbers = {}
  143. for a in allergies:
  144. eatable_food_numbers[a] = []
  145. maybe_eatable_food_numbers[a] = []
  146. css_class = "left"
  147. fout.write("div class=\"foods\"><div class=\"{css_class}\">\n".format(css_class=css_class))
  148. for r in restaurants:
  149. title, open_hours, week, week_foods, info = r
  150. title2, url, lazy_allergies, info_class = info[0:4]
  151. if day in week_foods or day < 5:
  152. if info_class != css_class:
  153. css_class = info_class
  154. fout.write("</div><div class=\"{css_class}\">\n".format(css_class=css_class))
  155. url = url.replace("&", "&amp;")
  156. fout.write("<h2><a href=\"{url}\">{title}</a></h2>\n".format(url=url, title=title))
  157. if not day in week_foods:
  158. fout.write("<p class=\"missing\">Ruokalistaa ei saatavilla.</p>")
  159. continue
  160. if week != "" and week != max_week:
  161. if week > max_week or (week == 1 and max_week == 52):
  162. # early..
  163. fout.write("<p class=\"nextweek\">Viikon {week} ruokalista:</p>".format(week=week))
  164. else:
  165. fout.write("<p class=\"missing\">Saatavilla vain viikon {week} ruokalista.</p>".format(week=week))
  166. continue
  167. if len(week_foods[day]) == 0:
  168. fout.write("<p class=\"missing\">Ei ruokatietoja päivälle.</p>")
  169. continue
  170. fout.write("<ul class=\"food\">\n")
  171. for food in week_foods[day]:
  172. output = ""
  173. total_allergies = {}
  174. maybe_allergies = {}
  175. for a in allergies:
  176. total_allergies[a] = 0
  177. maybe_allergies[a] = 0
  178. part_count = 0
  179. for part in food.split("\n"):
  180. # who cares?
  181. if re.match("Peruna|Riisi", part):
  182. continue
  183. # fries: well, maybe we do care, but we don't care about allergy stuff
  184. # and keep it in the same line as the previous food so as not to
  185. # waste visible space
  186. (part, fries) = re.subn("Tikkuperunat|Ranskalaiset perunat", "", part)
  187. fries = fries > 0
  188. part_count += 1
  189. # add missing () around allergies
  190. part = re.sub(" (([MLGK]|VL|Ve|Veg|Hot)(,([MLGK]|VL|Ve|Veg|Hot|))+)$", " (\\1)", part)
  191. match = re.match("^(.*) \\(([^\\)]+)\\)$", part)
  192. if match:
  193. # fix allergy issues
  194. food = match.group(1)
  195. allergy = match.group(2)
  196. # standardization
  197. allergy = re.sub("Kasvis", "K", allergy)
  198. allergy = re.sub("([MLGK]|VL)([MLGK]|[VL])", "\\1,\\2", allergy)
  199. # spaces to commas
  200. allergy = re.sub("saatavana[: ]+(.*)$", "eriks: \\1", allergy)
  201. allergy = re.sub(" +", ",", allergy)
  202. # remove double commas
  203. allergy = re.sub(",+", ",", allergy)
  204. # eriks: standardization
  205. allergy = re.sub(",?eriks:,?", ", eriks: ", allergy)
  206. # remove extra commas/spaces from beginning/end
  207. allergy = re.sub("^[, ]+", "", allergy)
  208. allergy = re.sub("[, ]+$", "", allergy)
  209. part = "{food} ({allergy})".format(food=food, allergy=allergy)
  210. if output != "" and not fries:
  211. output += "<br />\n"
  212. match = re.search("Saatavana myös: (.*)", part)
  213. if match:
  214. alt = match.group(1)
  215. alt = re.sub(r"^\((.*)\)$", r"\1", alt)
  216. alt = re.sub("[, ]+", r",", alt)
  217. alt = re.sub("^,+", "", alt)
  218. alt = re.sub(",+$", "", alt)
  219. part = re.sub(r"\)[- ]*Saatavana myös:.*", "eriks: {alt})".format(alt=alt), part)
  220. part = re.sub(r"[- ]*Saatavana myös:.*", "(eriks: {alt})".format(alt=alt), part)
  221. match = re.match(r"^(.*)(\([^\)]+\))$", part)
  222. if match:
  223. text = match.group(1)
  224. allergy = match.group(2)
  225. if fries:
  226. output += ", {text}".format(text=text)
  227. else:
  228. output += "{text} <span class=\"allergy\">{allergy}</span>".format(text=text, allergy=allergy)
  229. allergy = re.sub(r"^\((.*)\)$", r"\1", allergy)
  230. allergy = re.sub(" *eriks: ", "", allergy)
  231. this_allergies = set()
  232. for a in re.split("[, ]", allergy):
  233. for al in allergies:
  234. if a == al:
  235. this_allergies.add(a)
  236. break
  237. if "L" in this_allergies:
  238. this_allergies.add("VL")
  239. for a in this_allergies:
  240. if a in total_allergies:
  241. total_allergies[a] += 1
  242. if a in maybe_allergies:
  243. maybe_allergies[a] += 1
  244. match = re.search("M", lazy_allergies)
  245. if match:
  246. if "L" in this_allergies and not "M" in this_allergies:
  247. maybe_allergies["M"] += 1
  248. else:
  249. if lazy_allergies == "all":
  250. for a in allergies:
  251. maybe_allergies[a] += 1
  252. output += part
  253. allergy_output = ""
  254. for a in allergies:
  255. if total_allergies[a] == part_count:
  256. eatable_food_numbers[a].append(foodnum)
  257. elif maybe_allergies[a]== part_count:
  258. maybe_eatable_food_numbers[a].append(foodnum)
  259. fout.write(" <li id=\"f{foodnum}\">{output}</li>\n".format(foodnum=foodnum, output=output))
  260. foodnum += 1
  261. fout.write("</ul>\n")
  262. # write allergy scripts
  263. fout.write('<script type="text/javascript" src="{global_prefix}/ruoka.js"></script>'.format(global_prefix=global_prefix))
  264. fout.write('<script type="text/javascript">')
  265. fout.write("var eatable_foods = [];")
  266. fout.write("var maybe_eatable_foods = [];")
  267. for a in allergies:
  268. fout.write("eatable_foods[\"{a}\"] = [{eatable_food_number}];\n".format(a=a, eatable_food_number=",".join(str(e) for e in eatable_food_numbers[a])))
  269. fout.write("maybe_eatable_foods[\"{a}\"] = [{maybe_eatable_food_number}];\n".format(a=a, maybe_eatable_food_number=",".join(str(e) for e in maybe_eatable_food_numbers[a])))
  270. allergy_string = ",".join('"{a}"'.format(a=a) for a in allergies)
  271. fout.write("var allergies = {allergies}];\n".format(allergies = allergy_string))
  272. fout.write("var food_count = $foodnum;\n")
  273. fout.write("window.onload = function() { set_allergies(); show_warning(); };\n")
  274. fout.write("</script>\n")
  275. fout.write("</div></div>{file_footer}".format(file_footer=file_footer))
  276. def write_all_days(restaurants, prefix, title):
  277. try:
  278. os.mkdir(prefix)
  279. except OSError as err:
  280. pass # hope it already exists
  281. last_day = find_last_day_with_foods(restaurants);
  282. for day in range(7):
  283. outfname = "{prefix}{day}.html".format(prefix=prefix, day=day+1)
  284. if day > last_day:
  285. try:
  286. os.unlink(outfname)
  287. except OSError as err:
  288. pass # probably did not exist
  289. continue
  290. header = "{day_name} - {title} vko {max_week}{max_week_daterange}".format(day_name=day_names[day], title=title,
  291. max_week=max_week, max_week_daterange=max_week_daterange)
  292. write_day(day, header, outfname, last_day, restaurants, prefix)
  293. def write_table(restaurants, prefix, title):
  294. last_day = find_last_day_with_foods(restaurants);
  295. outfname = "{prefix}table.html".format(prefix=prefix)
  296. with open(outfname, "w") as fout:
  297. header = "{title} vko {max_week}{max_week_daterange}".format(title=title, max_week=max_week, max_week_daterange=max_week_daterange)
  298. fout.write("{file_header}<h1>{header}</h1>\n".format(file_header=file_header, header=header))
  299. fout.write("<div class=\"title\">\n")
  300. write_days_header(fout, -1, last_day)
  301. write_prefix_header(fout, prefix, 0)
  302. fout.write("</div><table border=\"1\"><tr><th>Päivä</th>")
  303. for r in restaurants:
  304. (title, open_hours, week, week_foods, info) = r
  305. (title2, url) = info[0:2]
  306. url = re.sub("&", "&nbsp;", url)
  307. fout.write("<th><a href=\"{url}\">{title}</a></th>")
  308. fout.write("</tr>\n")
  309. for day in range(last_day):
  310. fout.write("<tr><td>{day_name}</td>\n".format(day_name=day_names[day]))
  311. for r in restaurants:
  312. (title, open_hours, week, week_foods, info) = r
  313. if day in week_foods and (week == "" or week == max_week):
  314. fout.write("<td><ul>\n")
  315. for food in week_foods[day]:
  316. fout.write("<li>{food}</li>".format(food=food))
  317. fout.write("</ul></td>\n")
  318. else:
  319. fout.write("<td></td>\n")
  320. fout.write("</tr\n")
  321. fout.write("</table>{file_footer}".format(file_footer=file_footer))
  322. def get_restaurants_sorted(restaurants):
  323. # consider writing comparator
  324. out = []
  325. for r in restaurants:
  326. if r[4][3] == "left":
  327. out.append(r)
  328. for r in restaurants:
  329. if r[4][3] == "right":
  330. out.append(r)
  331. for r in restaurants:
  332. if r[4][3] == "middle" and not re.search("TAMK", r[4][1]):
  333. out.append(r)
  334. for r in restaurants:
  335. if r[4][3] == "middle" and re.search("TAMK", r[4][1]):
  336. out.append(r)
  337. return out
  338. def get_restaurants_with_prefix(prefix, restaurants):
  339. out = []
  340. for r in restaurants:
  341. if re.search(prefix, r[4][1]):
  342. out.append(r)
  343. return get_restaurants_sorted(out)
  344. tty_title = "TTY:n ruokalistat";
  345. tty = get_restaurants_with_prefix("TTY", unordered);
  346. write_all_days(tty, "tty/", tty_title);
  347. write_table(tty, "tty/", tty_title);
  348. tay_title = "Tampereen yliopiston ruokalistat";
  349. tay = get_restaurants_with_prefix("TaY", unordered);
  350. write_all_days(tay, "tay/", tay_title);
  351. write_table(tay, "tay/", tay_title);
  352. tays_title = "TAYS:n ruokalistat";
  353. tays = get_restaurants_with_prefix("TAYS", unordered);
  354. write_all_days(tays, "tays/", tays_title);
  355. write_table(tays, "tays/", tays_title);
  356. for r in unordered:
  357. if re.search(r"^\(TaY\)", r[0]):
  358. r[4][3] = "left"
  359. if re.search(r"^\(TTY\)", r[0]):
  360. r[4][3] = "right"
  361. if re.search(r"^\(TAYS\)", r[0]):
  362. r[4][3] = "middle"
  363. all_title = "Tampereen yliopistojen ruokalistat";
  364. all_restaurants = get_restaurants_sorted(unordered);
  365. # move fusion kitchen last
  366. #fusion = splice(@all_restaurants, 1, 1);
  367. #splice(@all_restaurants, 4, 0, @fusion);
  368. write_all_days(all_restaurants, "", all_title);
  369. write_table(all_restaurants, "", all_title);