krandiash/test-nginx-1
0
1"""A reactive image viewer that allows you to select a class and see 16 random2images from that class.3 4This is a tutorial on how to use `reactive` functions in Meerkat, to5build complex reactive workflows.6"""7 8import meerkat as mk9 10df = mk.get("imagenette", version="160px")11IMAGE_COL = "img"12LABEL_COL = "label"13 14 15@mk.reactive()16def random_images(df: mk.DataFrame):17 images = df.sample(16)[IMAGE_COL]18 formatter = images.formatters["base"]19 # formatter = images.formatters['tiny']20 return [formatter.encode(img) for img in images]21 22 23labels = list(df[LABEL_COL].unique())24class_selector = mk.gui.Select(25 values=list(labels),26 value=labels[0],27)28 29# Note that neither of these will work:30# filtered_df = df[df[LABEL_COL] == class_selector.value]31# (doesn't react to changes in class_selector.value)32# filtered_df = mk.reactive(lambda df: df[df[LABEL_COL] == class_selector.value])(df)33# (doesn't react to changes in class_selector.value)34filtered_df = mk.reactive(lambda df, label: df[df[LABEL_COL] == label])(35 df, class_selector.value36)37 38images = random_images(filtered_df)39 40# This won't work with a simple reactive fn like a random_images41# that only has df.sample42# as the encoding needs to be done in the reactive fn43# grid = mk.gui.html.gridcols2([44# mk.gui.Image(data=images.formatters["base"].encode(img)) for img in images45# ])46 47grid = mk.gui.html.div(48 [49 # Make the image square50 mk.gui.html.div(mk.gui.Image(data=img))51 for img in images52 ],53 classes="h-fit grid grid-cols-4 gap-1",54)55 56layout = mk.gui.html.div(57 [58 mk.gui.html.div(59 [mk.gui.Caption("Choose a class:"), class_selector],60 classes="flex justify-center items-center mb-2 gap-2",61 ),62 grid,63 ],64 classes="h-full flex flex-col m-2",65)66 67page = mk.gui.Page(layout, id="reactive-viewer")68page.launch()69 