PNA.fi koodi

food.py 19KB

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