PNA.fi koodi

food.py 19KB

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