view pics3/pics_flask_app.py @ 131:221d6ea7c6c8

cs: add cs_flask_app files
author paulo
date Thu, 20 Jan 2022 00:44:05 -0800
parents d216dd8e63da
children 41a6e2d99f68
line source
1 import csv
2 import datetime
3 import random
4 import os
6 import flask
7 import google.cloud.storage
8 from html3.html3 import HTML
10 app = flask.Flask(__name__)
12 GCS_CLIENT = google.cloud.storage.Client()
13 GCS_BUCKET = GCS_CLIENT.get_bucket(os.environ.get("GCS_BUCKET"))
14 PIN = os.environ.get("PIN")
17 class PinFailError(Exception):
18 def __str__(self):
19 return "PIN FAIL!"
21 class PinSetupError(Exception):
22 def __str__(self):
23 return "PIN SETUP ERROR!"
26 class PicsDialect(csv.Dialect):
27 delimiter = '\t'
28 quoting = csv.QUOTE_NONE
29 lineterminator = '\n'
31 PICSDIALECT = PicsDialect()
34 def _parse_dt(dts):
35 return datetime.datetime.strptime(dts, "%Y%m%d")
38 def _format_dt(dt):
39 return dt.strftime("%Y-%m-%d")
42 def _numeric_pad_basename(path, maxdigits=20):
43 return os.path.basename(path).zfill(maxdigits)
46 def _get_images(d):
47 exts = (".jpg", ".webm")
48 thumb_dir = f"pics/{d}/thumbs"
49 browse_dir = f"pics/{d}/browse"
51 thumb_fns = [i.name for i in GCS_CLIENT.list_blobs(GCS_BUCKET, prefix=thumb_dir) if i.name.endswith(exts)]
52 thumb_fns = sorted(thumb_fns, key=_numeric_pad_basename)
54 browse_contents = set(i.name for i in GCS_CLIENT.list_blobs(GCS_BUCKET, prefix=browse_dir) if i.name.endswith(exts))
55 browse_fns = []
56 for i in thumb_fns:
57 i_basename = os.path.splitext(os.path.basename(i))[0]
58 try:
59 for j in exts:
60 browse_fn = browse_dir + "/" + i_basename + j
61 if browse_fn in browse_contents:
62 browse_fns.append(browse_fn)
63 raise StopIteration
64 except StopIteration:
65 pass
66 else:
67 raise RuntimeError(f"Cannot find browse image for {i}")
69 return zip(thumb_fns, browse_fns)
72 def _get_standard_html_doc(title):
73 root = HTML("html")
75 header = root.head
76 header.link(rel="stylesheet", type="text/css", href=flask.url_for("static", filename="index.css"))
77 header.title(title)
79 body = root.body
80 body.h1(title)
82 return (root, header, body)
85 def _go_thumbnail_links_to_browse_imgs_html_body(body, d, t, b, a_args={}, img_args={}, lazyload=False):
86 thumb_img_url = GCS_BUCKET.get_blob(t).public_url
87 browse_url = flask.url_for("browse", d=d, img=os.path.basename(b))
89 a = body.a(href=browse_url, **a_args)
90 if lazyload:
91 img_args = dict(img_args)
92 img_args["data-src"] = thumb_img_url
93 a.img(**img_args)
94 else:
95 a.img(src=thumb_img_url, **img_args)
97 body.text(" ")
100 def _go_thumbnail_links_to_thumbs_html_body(body, d, t, a_args={}, img_args={}):
101 thumb_img_url = GCS_BUCKET.get_blob(t).public_url
102 thumbs_url_args = {"from": os.path.basename(t), "_anchor": "selected"}
103 thumbs_url = flask.url_for("thumbs", d=d, **thumbs_url_args)
105 a = body.a(href=thumbs_url, **a_args)
106 a.img(src=thumb_img_url, **img_args)
108 body.text(" ")
111 @app.route("/")
112 def index():
113 n = 5 # number of thumbnails to display per dir
115 (root, header, body) = _get_standard_html_doc("Pictures")
116 header.script('', type="text/javascript", src=flask.url_for("static", filename="lazyload.js"))
118 if not PIN:
119 raise PinSetupError
120 elif flask.request.cookies.get("lahat") != PIN:
121 raise PinFailError
123 pics_dirs = []
124 pics_dirs_index_blob = GCS_BUCKET.get_blob("pics/index.tsv")
125 if pics_dirs_index_blob:
126 pics_dirs_index_strlist = pics_dirs_index_blob.download_as_text().splitlines()
127 pics_dirs_index_reader = csv.reader(pics_dirs_index_strlist, PICSDIALECT)
128 pics_dirs = sorted(pics_dirs_index_reader, key=lambda x: x[0], reverse=True)
130 for (dts, d) in pics_dirs:
131 dt = _parse_dt(dts)
132 body.h2.a(d, href=flask.url_for("thumbs", d=d))
133 body.h3(_format_dt(dt))
135 imgs = _get_images(d)
136 imgs_idx = [(i, img) for (i, img) in enumerate(imgs)]
138 sampled_imgs_idx = random.sample(imgs_idx, min(len(imgs_idx), n))
139 sampled_imgs_idx.sort(key=lambda x: x[0])
141 p = body.p
142 for (i, (t, b)) in sampled_imgs_idx:
143 _go_thumbnail_links_to_browse_imgs_html_body(p, d, t, b, lazyload=True)
145 return str(root).encode("utf-8")
148 @app.route("/<d>/browse/<img>")
149 def browse(d, img):
150 browse_img_blob = GCS_BUCKET.get_blob(f"pics/{d}/browse/{img}")
151 if not browse_img_blob:
152 flask.abort(404)
154 imgs = list(_get_images(d))
156 # thumbnail preview ribbon
157 w = 7 # must be odd
158 v = int(w/2)
159 imgs_circ = [None] * w
160 x = None
161 n = len(imgs)
162 for (i, (t, b)) in enumerate(imgs):
163 if os.path.basename(b) == img:
164 x = i + 1
165 imgs_circ[v] = (t, b)
166 for j in range(1, v + 1):
167 if (i + j) < n: imgs_circ[v + j] = imgs[i + j]
168 if (i - j) >= 0: imgs_circ[v - j] = imgs[i - j]
169 break
171 if x is None:
172 raise AssertionError
174 (root, header, body) = _get_standard_html_doc(f"{d} \u2014 {x} of {n}")
175 header.script('', type="text/javascript", src=flask.url_for("static", filename="np_keys.js"))
177 browse_img_url = browse_img_blob.public_url
178 ext = os.path.splitext(img)[1]
179 p = body.p
180 if ext == ".webm":
181 p.video(src=browse_img_url, autoplay="true", loop="true")
182 else:
183 p.img(src=browse_img_url)
185 p = body.p
186 for (i, img_c) in enumerate(imgs_circ):
187 if img_c is not None:
188 (t, b) = img_c
189 a_args = {}
190 img_args = {}
191 if os.path.basename(b) == img:
192 a_args = {"id": "up"}
193 img_args = {"klass": "sel"}
194 b = None
195 elif i == v + 1:
196 a_args = {"id": "next"}
197 elif i == v - 1:
198 a_args = {"id": "prev"}
200 if b is None:
201 _go_thumbnail_links_to_thumbs_html_body(p, d, t, a_args, img_args)
202 else:
203 _go_thumbnail_links_to_browse_imgs_html_body(p, d, t, b, a_args, img_args)
205 return str(root).encode("utf-8")
208 @app.route("/<d>")
209 def thumbs(d):
210 args = flask.request.args
211 print(f"args = {args}")
213 from_img = args.get("from")
215 imgs = list(_get_images(d))
216 (root, header, body) = _get_standard_html_doc(d)
218 p = body.p
219 for (t, b) in imgs:
220 img_args = {}
221 if os.path.basename(b) == from_img:
222 img_args={"klass": "sel2", "id":"selected"}
223 _go_thumbnail_links_to_browse_imgs_html_body(p, d, t, b, img_args=img_args)
225 return str(root).encode("utf-8")