vancauwe commited on
Commit
2f87aad
Β·
1 Parent(s): 828f42d

feat: content split to page and gallery maps good to go

Browse files
requirements.txt CHANGED
@@ -28,8 +28,13 @@ pillow==10.4.0
28
  opencv-python-headless==4.5.5.64
29
  albumentations==1.1.0
30
 
 
 
 
31
  # documentation: mkdocs
32
  mkdocs~=1.6.0
33
  mkdocstrings[python]>=0.25.1
34
  mkdocs-material~=9.5.27
35
  mkdocs-homepage-copier~=1.0.0
 
 
 
28
  opencv-python-headless==4.5.5.64
29
  albumentations==1.1.0
30
 
31
+ # for states
32
+ transitions
33
+
34
  # documentation: mkdocs
35
  mkdocs~=1.6.0
36
  mkdocstrings[python]>=0.25.1
37
  mkdocs-material~=9.5.27
38
  mkdocs-homepage-copier~=1.0.0
39
+
40
+
src/home.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+
4
+ import logging
5
+
6
+ st.set_page_config(
7
+ page_title="Home",
8
+ page_icon="🐳",
9
+ )
10
+
11
+ # one toggle for all the extra debug text
12
+ if "MODE_DEV_STATEFUL" not in st.session_state:
13
+ st.session_state.MODE_DEV_STATEFUL = False
14
+
15
+ # get a global var for logger accessor in this module
16
+ LOG_LEVEL = logging.DEBUG
17
+ g_logger = logging.getLogger(__name__)
18
+ g_logger.setLevel(LOG_LEVEL)
19
+
20
+ from utils.st_logs import init_logging_session_states
21
+ from utils.workflow_ui import init_workflow_session_states, init_workflow_viz
22
+ from input.input_handling import init_input_container_states, init_input_data_session_states
23
+ from classifier.classifier_image import init_classifier_session_states
24
+ # initialise various session state variables
25
+ init_logging_session_states() # logging init should be early
26
+ init_workflow_session_states()
27
+ init_input_data_session_states()
28
+ init_input_container_states()
29
+ init_workflow_viz()
30
+ init_classifier_session_states()
31
+
32
+ st.write("# Welcome to Cetacean Research Data Infrastructure! πŸ¬ΛšΛ–π“’Φ΄ΰ»‹ πŸ‹βœ§Λš.⋆")
33
+
34
+ st.sidebar.success("Here are the pages.")
35
+
36
+ st.markdown(
37
+ """
38
+ About: blablabla
39
+ """
40
+ )
41
+
42
+ g_logger.info("App started.")
43
+ g_logger.warning(f"[D] Streamlit version: {st.__version__}. Python version: {os.sys.version}")
44
+
45
+ #g_logger.debug("debug message")
46
+ #g_logger.info("info message")
47
+ #g_logger.warning("warning message")
src/input/input_handling.py CHANGED
@@ -424,7 +424,7 @@ def add_input_UI_elements() -> None:
424
  # which are not created in the same order.
425
 
426
  st.divider()
427
- st.title("Input image and data")
428
 
429
  # create and style a container for the file uploader/other one-off inputs
430
  st.markdown('<style>.st-key-container_file_uploader_id { border: 1px solid skyblue; border-radius: 5px; }</style>', unsafe_allow_html=True)
 
424
  # which are not created in the same order.
425
 
426
  st.divider()
427
+ st.title("Input your images")
428
 
429
  # create and style a container for the file uploader/other one-off inputs
430
  st.markdown('<style>.st-key-container_file_uploader_id { border: 1px solid skyblue; border-radius: 5px; }</style>', unsafe_allow_html=True)
src/main.py DELETED
@@ -1,16 +0,0 @@
1
- import streamlit as st
2
-
3
- st.set_page_config(
4
- page_title="Home",
5
- page_icon="🐳",
6
- )
7
-
8
- st.write("# Welcome to Cetacean Research Data Infrastructure! πŸ¬ΛšΛ–π“’Φ΄ΰ»‹ πŸ‹βœ§Λš.⋆")
9
-
10
- st.sidebar.success("Here are the pages.")
11
-
12
- st.markdown(
13
- """
14
- About: blablabla
15
- """
16
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/maps/obs_map.py CHANGED
@@ -197,7 +197,7 @@ def present_obs_map(dataset_id:str = "Saving-Willy/Happywhale-kaggle",
197
  _df = pd.DataFrame({
198
  'lat': metadata["train"]["latitude"],
199
  'lon': metadata["train"]["longitude"],
200
- 'species': metadata["train"]["predicted_class"],}
201
  )
202
 
203
  if dbg_show_extra:
 
197
  _df = pd.DataFrame({
198
  'lat': metadata["train"]["latitude"],
199
  'lon': metadata["train"]["longitude"],
200
+ 'species': metadata["train"]["selected_class"],}
201
  )
202
 
203
  if dbg_show_extra:
src/old_main.py CHANGED
@@ -6,60 +6,54 @@ import streamlit as st
6
  import folium
7
  from streamlit_folium import st_folium
8
 
9
- from transformers import pipeline
10
- from transformers import AutoModelForImageClassification
11
 
12
- from maps.obs_map import add_obs_map_header
13
- from classifier.classifier_image import add_classifier_header
14
- from datasets import disable_caching
15
- disable_caching()
16
 
17
- import whale_gallery as gallery
18
- import whale_viewer as viewer
19
- from input.input_handling import setup_input, check_inputs_are_set
20
- from input.input_handling import init_input_container_states, add_input_UI_elements, init_input_data_session_states
21
- from input.input_handling import dbg_show_observation_hashes
22
 
23
- from maps.alps_map import present_alps_map
24
- from maps.obs_map import present_obs_map
25
- from utils.st_logs import parse_log_buffer, init_logging_session_states
26
- from utils.workflow_ui import refresh_progress_display, init_workflow_viz, init_workflow_session_states
27
- from hf_push_observations import push_all_observations
28
 
29
- from classifier.classifier_image import cetacean_just_classify, cetacean_show_results_and_review, cetacean_show_results, init_classifier_session_states
30
- from classifier.classifier_hotdog import hotdog_classify
 
 
 
31
 
 
 
32
 
33
- # setup for the ML model on huggingface (our wrapper)
34
- os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
 
35
  #classifier_revision = '0f9c15e2db4d64e7f622ade518854b488d8d35e6'
36
- classifier_revision = 'main' # default/latest version
37
- # and the dataset of observations (hf dataset in our space)
38
- dataset_id = "Saving-Willy/temp_dataset"
39
- data_files = "data/train-00000-of-00001.parquet"
40
 
41
- USE_BASIC_MAP = False
42
- DEV_SIDEBAR_LIB = True
43
 
44
- # one toggle for all the extra debug text
45
- if "MODE_DEV_STATEFUL" not in st.session_state:
46
- st.session_state.MODE_DEV_STATEFUL = False
47
 
48
 
49
  # get a global var for logger accessor in this module
50
- LOG_LEVEL = logging.DEBUG
51
- g_logger = logging.getLogger(__name__)
52
- g_logger.setLevel(LOG_LEVEL)
 
 
53
 
54
- st.set_page_config(layout="wide")
55
 
56
- # initialise various session state variables
57
- init_logging_session_states() # logging init should be early
58
- init_workflow_session_states()
59
- init_input_data_session_states()
60
- init_input_container_states()
61
- init_workflow_viz()
62
- init_classifier_session_states()
63
 
64
 
65
  def main() -> None:
@@ -82,87 +76,87 @@ def main() -> None:
82
 
83
  """
84
 
85
- g_logger.info("App started.")
86
- g_logger.warning(f"[D] Streamlit version: {st.__version__}. Python version: {os.sys.version}")
87
 
88
  #g_logger.debug("debug message")
89
  #g_logger.info("info message")
90
  #g_logger.warning("warning message")
91
 
92
  # Streamlit app
93
- tab_inference, tab_hotdogs, tab_map, tab_coords, tab_log, tab_gallery = \
94
- st.tabs(["Cetecean classifier", "Hotdog classifier", "Map", "*:gray[Dev:coordinates]*", "Log", "Beautiful cetaceans"])
95
 
96
- # put this early so the progress indicator is at the top (also refreshed at end)
97
- refresh_progress_display()
98
 
99
- # create a sidebar, and parse all the input (returned as `observations` object)
100
- with st.sidebar:
101
- # layout handling
102
- add_input_UI_elements()
103
- # input elements (file upload, text input, etc)
104
- setup_input()
105
 
106
 
107
- with tab_map:
108
- # visual structure: a couple of toggles at the top, then the map inlcuding a
109
- # dropdown for tileset selection.
110
- add_obs_map_header()
111
- tab_map_ui_cols = st.columns(2)
112
- with tab_map_ui_cols[0]:
113
- show_db_points = st.toggle("Show Points from DB", True)
114
- with tab_map_ui_cols[1]:
115
- dbg_show_extra = st.toggle("Show Extra points (test)", False)
116
 
117
- if show_db_points:
118
- # show a nicer map, observations marked, tileset selectable.
119
- st_observation = present_obs_map(
120
- dataset_id=dataset_id, data_files=data_files,
121
- dbg_show_extra=dbg_show_extra)
122
 
123
- else:
124
- # development map.
125
- st_observation = present_alps_map()
126
 
127
 
128
- with tab_log:
129
- handler = st.session_state['handler']
130
- if handler is not None:
131
- records = parse_log_buffer(handler.buffer)
132
- st.dataframe(records[::-1], use_container_width=True,)
133
- st.info(f"Length of records: {len(records)}")
134
- else:
135
- st.error("⚠️ No log handler found!")
136
 
137
 
138
 
139
- with tab_coords:
140
- # the goal of this tab is to allow selection of the new obsvation's location by map click/adjust.
141
- st.markdown("Coming later! :construction:")
142
- st.markdown(
143
- """*The goal is to allow interactive definition for the coordinates of a new
144
- observation, by click/drag points on the map.*""")
145
 
146
 
147
- st.write("Click on the map to capture a location.")
148
- #m = folium.Map(location=visp_loc, zoom_start=7)
149
- mm = folium.Map(location=[39.949610, -75.150282], zoom_start=16)
150
- folium.Marker( [39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell"
151
- ).add_to(mm)
152
-
153
- st_data2 = st_folium(mm, width=725)
154
- st.write("below the map...")
155
- if st_data2['last_clicked'] is not None:
156
- print(st_data2)
157
- st.info(st_data2['last_clicked'])
158
-
159
-
160
- with tab_gallery:
161
- # here we make a container to allow filtering css properties
162
- # specific to the gallery (otherwise we get side effects)
163
- tg_cont = st.container(key="swgallery")
164
- with tg_cont:
165
- gallery.render_whale_gallery(n_cols=4)
166
 
167
 
168
  # state handling re data_entry phases
@@ -173,30 +167,30 @@ def main() -> None:
173
  # - at this point do we also want to disable changes to the metadata selectors?
174
  # anyway, simple first.
175
 
176
- if st.session_state.workflow_fsm.is_in_state('doing_data_entry'):
177
- # can we advance state? - only when all inputs are set for all uploaded files
178
- all_inputs_set = check_inputs_are_set(debug=True, empty_ok=False)
179
- if all_inputs_set:
180
- st.session_state.workflow_fsm.complete_current_state()
181
- # -> data_entry_complete
182
- else:
183
- # button, disabled; no state change yet.
184
- st.sidebar.button(":gray[*Validate*]", disabled=True, help="Please fill in all fields.")
185
 
186
 
187
- if st.session_state.workflow_fsm.is_in_state('data_entry_complete'):
188
- # can we advance state? - only when the validate button is pressed
189
- if st.sidebar.button(":white_check_mark:[**Validate**]"):
190
- # create a dictionary with the submitted observation
191
- tab_log.info(f"{st.session_state.observations}")
192
- df = pd.DataFrame([obs.to_dict() for obs in st.session_state.observations.values()])
193
- #df = pd.DataFrame(st.session_state.observations, index=[0])
194
- with tab_coords:
195
- st.table(df)
196
- # there doesn't seem to be any actual validation here?? TODO: find validator function (each element is validated by the input box, but is there something at the whole image level?)
197
- # hmm, maybe it should actually just be "I'm done with data entry"
198
- st.session_state.workflow_fsm.complete_current_state()
199
- # -> data_entry_validated
200
 
201
  # state handling re inference phases (tab_inference)
202
  # 3. validation button pressed, validation done -> enable the inference button.
@@ -205,114 +199,114 @@ def main() -> None:
205
  # 5. ML done -> show results, and manual validation options
206
  # 6. manual validation done -> enable the upload buttons
207
  #
208
- with tab_inference:
209
- # inside the inference tab, on button press we call the model (on huggingface hub)
210
- # which will be run locally.
211
- # - the model predicts the top 3 most likely species from the input image
212
- # - these species are shown
213
- # - the user can override the species prediction using the dropdown
214
- # - an observation is uploaded if the user chooses.
215
 
216
 
217
- if st.session_state.MODE_DEV_STATEFUL:
218
- dbg_show_observation_hashes()
219
-
220
- add_classifier_header()
221
- # if we are before data_entry_validated, show the button, disabled.
222
- if not st.session_state.workflow_fsm.is_in_state_or_beyond('data_entry_validated'):
223
- tab_inference.button(":gray[*Identify with cetacean classifier*]", disabled=True,
224
- help="Please validate inputs before proceeding",
225
- key="button_infer_ceteans")
226
 
227
- if st.session_state.workflow_fsm.is_in_state('data_entry_validated'):
228
- # show the button, enabled. If pressed, we start the ML model (And advance state)
229
- if tab_inference.button("Identify with cetacean classifier",
230
- key="button_infer_ceteans"):
231
- cetacean_classifier = AutoModelForImageClassification.from_pretrained(
232
- "Saving-Willy/cetacean-classifier",
233
- revision=classifier_revision,
234
- trust_remote_code=True)
235
-
236
- cetacean_just_classify(cetacean_classifier)
237
- st.session_state.workflow_fsm.complete_current_state()
238
- # trigger a refresh too (refreshhing the prog indicator means the script reruns and
239
- # we can enter the next state - visualising the results / review)
240
- # ok it doesn't if done programmatically. maybe interacting with teh button? check docs.
241
- refresh_progress_display()
242
- #TODO: validate this doesn't harm performance adversely.
243
- st.rerun()
244
 
245
- elif st.session_state.workflow_fsm.is_in_state('ml_classification_completed'):
246
- # show the results, and allow manual validation
247
- st.markdown("""### Inference results and manual validation/adjustment """)
248
- if st.session_state.MODE_DEV_STATEFUL:
249
- s = ""
250
- for k, v in st.session_state.whale_prediction1.items():
251
- s += f"* Image {k}: {v}\n"
252
 
253
- st.markdown(s)
254
 
255
- # add a button to advance the state
256
- if st.button("Confirm species predictions", help="Confirm that all species are selected correctly"):
257
- st.session_state.workflow_fsm.complete_current_state()
258
- # -> manual_inspection_completed
259
- st.rerun()
260
 
261
- cetacean_show_results_and_review()
262
 
263
- elif st.session_state.workflow_fsm.is_in_state('manual_inspection_completed'):
264
- # show the ML results, and allow the user to upload the observation
265
- st.markdown("""### Inference Results (after manual validation) """)
266
 
267
 
268
- if st.button("Upload all observations to THE INTERNET!"):
269
- # let this go through to the push_all func, since it just reports to log for now.
270
- push_all_observations(enable_push=False)
271
- st.session_state.workflow_fsm.complete_current_state()
272
- # -> data_uploaded
273
- st.rerun()
274
-
275
- cetacean_show_results()
276
 
277
- elif st.session_state.workflow_fsm.is_in_state('data_uploaded'):
278
- # the data has been sent. Lets show the observations again
279
- # but no buttons to upload (or greyed out ok)
280
- st.markdown("""### Observation(s) uploaded - thank you!""")
281
- cetacean_show_results()
282
-
283
- st.divider()
284
- #df = pd.DataFrame(st.session_state.observations, index=[0])
285
- df = pd.DataFrame([obs.to_dict() for obs in st.session_state.observations.values()])
286
- st.table(df)
287
-
288
- # didn't decide what the next state is here - I think we are in the terminal state.
289
- #st.session_state.workflow_fsm.complete_current_state()
290
 
291
 
292
- # inside the hotdog tab, on button press we call a 2nd model (totally unrelated at present, just for demo
293
- # purposes, an hotdog image classifier) which will be run locally.
294
- # - this model predicts if the image is a hotdog or not, and returns probabilities
295
- # - the input image is the same as for the ceteacean classifier - defined in the sidebar
296
- tab_hotdogs.title("Hot Dog? Or Not?")
297
- tab_hotdogs.write("""
298
- *Run alternative classifer on input images. Here we are using
299
- a binary classifier - hotdog or not - from
300
- huggingface.co/julien-c/hotdog-not-hotdog.*""")
301
-
302
- if tab_hotdogs.button("Get Hotdog Prediction"):
303
 
304
- pipeline_hot_dog = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")
305
 
306
- if st.session_state.image is None:
307
- st.info("Please upload an image first.")
308
- #st.info(str(observations.to_dict()))
309
 
310
- else:
311
- hotdog_classify(pipeline_hot_dog, tab_hotdogs)
312
 
313
 
314
- # after all other processing, we can show the stage/state
315
- refresh_progress_display()
316
 
317
 
318
  if __name__ == "__main__":
 
6
  import folium
7
  from streamlit_folium import st_folium
8
 
9
+ # from transformers import pipeline
10
+ # from transformers import AutoModelForImageClassification
11
 
12
+ # from maps.obs_map import add_obs_map_header
 
 
 
13
 
14
+ # from datasets import disable_caching
15
+ # disable_caching()
 
 
 
16
 
17
+ # import whale_gallery as gallery
18
+ # import whale_viewer as viewer
19
+ # from input.input_handling import setup_input, check_inputs_are_set
20
+ # from input.input_handling import init_input_container_states, add_input_UI_elements, init_input_data_session_states
21
+ # from input.input_handling import dbg_show_observation_hashes
22
 
23
+ # from maps.alps_map import present_alps_map
24
+ # from maps.obs_map import present_obs_map
25
+ # from utils.st_logs import parse_log_buffer, init_logging_session_states
26
+ # from utils.workflow_ui import refresh_progress_display, init_workflow_viz, init_workflow_session_states
27
+ # from hf_push_observations import push_all_observations
28
 
29
+ # from classifier.classifier_image import cetacean_just_classify, cetacean_show_results_and_review, cetacean_show_results, init_classifier_session_states
30
+ # from classifier.classifier_hotdog import hotdog_classify
31
 
32
+
33
+ # # setup for the ML model on huggingface (our wrapper)
34
+ # os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
35
  #classifier_revision = '0f9c15e2db4d64e7f622ade518854b488d8d35e6'
36
+ # classifier_revision = 'main' # default/latest version
37
+ # # and the dataset of observations (hf dataset in our space)
38
+ # dataset_id = "Saving-Willy/temp_dataset"
39
+ # data_files = "data/train-00000-of-00001.parquet"
40
 
41
+ # USE_BASIC_MAP = False
42
+ # DEV_SIDEBAR_LIB = True
43
 
44
+ # # one toggle for all the extra debug text
45
+ # if "MODE_DEV_STATEFUL" not in st.session_state:
46
+ # st.session_state.MODE_DEV_STATEFUL = False
47
 
48
 
49
  # get a global var for logger accessor in this module
50
+ # LOG_LEVEL = logging.DEBUG
51
+ # g_logger = logging.getLogger(__name__)
52
+ # g_logger.setLevel(LOG_LEVEL)
53
+
54
+ # st.set_page_config(layout="wide")
55
 
 
56
 
 
 
 
 
 
 
 
57
 
58
 
59
  def main() -> None:
 
76
 
77
  """
78
 
79
+ # g_logger.info("App started.")
80
+ # g_logger.warning(f"[D] Streamlit version: {st.__version__}. Python version: {os.sys.version}")
81
 
82
  #g_logger.debug("debug message")
83
  #g_logger.info("info message")
84
  #g_logger.warning("warning message")
85
 
86
  # Streamlit app
87
+ # tab_inference, tab_hotdogs, tab_map, tab_coords, tab_log, tab_gallery = \
88
+ # st.tabs(["Cetecean classifier", "Hotdog classifier", "Map", "*:gray[Dev:coordinates]*", "Log", "Beautiful cetaceans"])
89
 
90
+ # # put this early so the progress indicator is at the top (also refreshed at end)
91
+ # refresh_progress_display()
92
 
93
+ # # create a sidebar, and parse all the input (returned as `observations` object)
94
+ # with st.sidebar:
95
+ # # layout handling
96
+ # add_input_UI_elements()
97
+ # # input elements (file upload, text input, etc)
98
+ # setup_input()
99
 
100
 
101
+ # with tab_map:
102
+ # # visual structure: a couple of toggles at the top, then the map inlcuding a
103
+ # # dropdown for tileset selection.
104
+ # add_obs_map_header()
105
+ # tab_map_ui_cols = st.columns(2)
106
+ # with tab_map_ui_cols[0]:
107
+ # show_db_points = st.toggle("Show Points from DB", True)
108
+ # with tab_map_ui_cols[1]:
109
+ # dbg_show_extra = st.toggle("Show Extra points (test)", False)
110
 
111
+ # if show_db_points:
112
+ # # show a nicer map, observations marked, tileset selectable.
113
+ # st_observation = present_obs_map(
114
+ # dataset_id=dataset_id, data_files=data_files,
115
+ # dbg_show_extra=dbg_show_extra)
116
 
117
+ # else:
118
+ # # development map.
119
+ # st_observation = present_alps_map()
120
 
121
 
122
+ # with tab_log:
123
+ # handler = st.session_state['handler']
124
+ # if handler is not None:
125
+ # records = parse_log_buffer(handler.buffer)
126
+ # st.dataframe(records[::-1], use_container_width=True,)
127
+ # st.info(f"Length of records: {len(records)}")
128
+ # else:
129
+ # st.error("⚠️ No log handler found!")
130
 
131
 
132
 
133
+ # with tab_coords:
134
+ # # the goal of this tab is to allow selection of the new obsvation's location by map click/adjust.
135
+ # st.markdown("Coming later! :construction:")
136
+ # st.markdown(
137
+ # """*The goal is to allow interactive definition for the coordinates of a new
138
+ # observation, by click/drag points on the map.*""")
139
 
140
 
141
+ # st.write("Click on the map to capture a location.")
142
+ # #m = folium.Map(location=visp_loc, zoom_start=7)
143
+ # mm = folium.Map(location=[39.949610, -75.150282], zoom_start=16)
144
+ # folium.Marker( [39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell"
145
+ # ).add_to(mm)
146
+
147
+ # st_data2 = st_folium(mm, width=725)
148
+ # st.write("below the map...")
149
+ # if st_data2['last_clicked'] is not None:
150
+ # print(st_data2)
151
+ # st.info(st_data2['last_clicked'])
152
+
153
+
154
+ # with tab_gallery:
155
+ # # here we make a container to allow filtering css properties
156
+ # # specific to the gallery (otherwise we get side effects)
157
+ # tg_cont = st.container(key="swgallery")
158
+ # with tg_cont:
159
+ # gallery.render_whale_gallery(n_cols=4)
160
 
161
 
162
  # state handling re data_entry phases
 
167
  # - at this point do we also want to disable changes to the metadata selectors?
168
  # anyway, simple first.
169
 
170
+ # if st.session_state.workflow_fsm.is_in_state('doing_data_entry'):
171
+ # # can we advance state? - only when all inputs are set for all uploaded files
172
+ # all_inputs_set = check_inputs_are_set(debug=True, empty_ok=False)
173
+ # if all_inputs_set:
174
+ # st.session_state.workflow_fsm.complete_current_state()
175
+ # # -> data_entry_complete
176
+ # else:
177
+ # # button, disabled; no state change yet.
178
+ # st.sidebar.button(":gray[*Validate*]", disabled=True, help="Please fill in all fields.")
179
 
180
 
181
+ # if st.session_state.workflow_fsm.is_in_state('data_entry_complete'):
182
+ # # can we advance state? - only when the validate button is pressed
183
+ # if st.sidebar.button(":white_check_mark:[**Validate**]"):
184
+ # # create a dictionary with the submitted observation
185
+ # tab_log.info(f"{st.session_state.observations}")
186
+ # df = pd.DataFrame([obs.to_dict() for obs in st.session_state.observations.values()])
187
+ # #df = pd.DataFrame(st.session_state.observations, index=[0])
188
+ # with tab_coords:
189
+ # st.table(df)
190
+ # # there doesn't seem to be any actual validation here?? TODO: find validator function (each element is validated by the input box, but is there something at the whole image level?)
191
+ # # hmm, maybe it should actually just be "I'm done with data entry"
192
+ # st.session_state.workflow_fsm.complete_current_state()
193
+ # # -> data_entry_validated
194
 
195
  # state handling re inference phases (tab_inference)
196
  # 3. validation button pressed, validation done -> enable the inference button.
 
199
  # 5. ML done -> show results, and manual validation options
200
  # 6. manual validation done -> enable the upload buttons
201
  #
202
+ # with tab_inference:
203
+ # # inside the inference tab, on button press we call the model (on huggingface hub)
204
+ # # which will be run locally.
205
+ # # - the model predicts the top 3 most likely species from the input image
206
+ # # - these species are shown
207
+ # # - the user can override the species prediction using the dropdown
208
+ # # - an observation is uploaded if the user chooses.
209
 
210
 
211
+ # if st.session_state.MODE_DEV_STATEFUL:
212
+ # dbg_show_observation_hashes()
213
+
214
+ # add_classifier_header()
215
+ # # if we are before data_entry_validated, show the button, disabled.
216
+ # if not st.session_state.workflow_fsm.is_in_state_or_beyond('data_entry_validated'):
217
+ # tab_inference.button(":gray[*Identify with cetacean classifier*]", disabled=True,
218
+ # help="Please validate inputs before proceeding",
219
+ # key="button_infer_ceteans")
220
 
221
+ # if st.session_state.workflow_fsm.is_in_state('data_entry_validated'):
222
+ # # show the button, enabled. If pressed, we start the ML model (And advance state)
223
+ # if tab_inference.button("Identify with cetacean classifier",
224
+ # key="button_infer_ceteans"):
225
+ # cetacean_classifier = AutoModelForImageClassification.from_pretrained(
226
+ # "Saving-Willy/cetacean-classifier",
227
+ # revision=classifier_revision,
228
+ # trust_remote_code=True)
229
+
230
+ # cetacean_just_classify(cetacean_classifier)
231
+ # st.session_state.workflow_fsm.complete_current_state()
232
+ # # trigger a refresh too (refreshhing the prog indicator means the script reruns and
233
+ # # we can enter the next state - visualising the results / review)
234
+ # # ok it doesn't if done programmatically. maybe interacting with teh button? check docs.
235
+ # refresh_progress_display()
236
+ # #TODO: validate this doesn't harm performance adversely.
237
+ # st.rerun()
238
 
239
+ # elif st.session_state.workflow_fsm.is_in_state('ml_classification_completed'):
240
+ # # show the results, and allow manual validation
241
+ # st.markdown("""### Inference results and manual validation/adjustment """)
242
+ # if st.session_state.MODE_DEV_STATEFUL:
243
+ # s = ""
244
+ # for k, v in st.session_state.whale_prediction1.items():
245
+ # s += f"* Image {k}: {v}\n"
246
 
247
+ # st.markdown(s)
248
 
249
+ # # add a button to advance the state
250
+ # if st.button("Confirm species predictions", help="Confirm that all species are selected correctly"):
251
+ # st.session_state.workflow_fsm.complete_current_state()
252
+ # # -> manual_inspection_completed
253
+ # st.rerun()
254
 
255
+ # cetacean_show_results_and_review()
256
 
257
+ # elif st.session_state.workflow_fsm.is_in_state('manual_inspection_completed'):
258
+ # # show the ML results, and allow the user to upload the observation
259
+ # st.markdown("""### Inference Results (after manual validation) """)
260
 
261
 
262
+ # if st.button("Upload all observations to THE INTERNET!"):
263
+ # # let this go through to the push_all func, since it just reports to log for now.
264
+ # push_all_observations(enable_push=False)
265
+ # st.session_state.workflow_fsm.complete_current_state()
266
+ # # -> data_uploaded
267
+ # st.rerun()
268
+
269
+ # cetacean_show_results()
270
 
271
+ # elif st.session_state.workflow_fsm.is_in_state('data_uploaded'):
272
+ # # the data has been sent. Lets show the observations again
273
+ # # but no buttons to upload (or greyed out ok)
274
+ # st.markdown("""### Observation(s) uploaded - thank you!""")
275
+ # cetacean_show_results()
276
+
277
+ # st.divider()
278
+ # #df = pd.DataFrame(st.session_state.observations, index=[0])
279
+ # df = pd.DataFrame([obs.to_dict() for obs in st.session_state.observations.values()])
280
+ # st.table(df)
281
+
282
+ # # didn't decide what the next state is here - I think we are in the terminal state.
283
+ # #st.session_state.workflow_fsm.complete_current_state()
284
 
285
 
286
+ # # inside the hotdog tab, on button press we call a 2nd model (totally unrelated at present, just for demo
287
+ # # purposes, an hotdog image classifier) which will be run locally.
288
+ # # - this model predicts if the image is a hotdog or not, and returns probabilities
289
+ # # - the input image is the same as for the ceteacean classifier - defined in the sidebar
290
+ # tab_hotdogs.title("Hot Dog? Or Not?")
291
+ # tab_hotdogs.write("""
292
+ # *Run alternative classifer on input images. Here we are using
293
+ # a binary classifier - hotdog or not - from
294
+ # huggingface.co/julien-c/hotdog-not-hotdog.*""")
295
+
296
+ # if tab_hotdogs.button("Get Hotdog Prediction"):
297
 
298
+ # pipeline_hot_dog = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")
299
 
300
+ # if st.session_state.image is None:
301
+ # st.info("Please upload an image first.")
302
+ # #st.info(str(observations.to_dict()))
303
 
304
+ # else:
305
+ # hotdog_classify(pipeline_hot_dog, tab_hotdogs)
306
 
307
 
308
+ # # after all other processing, we can show the stage/state
309
+ # refresh_progress_display()
310
 
311
 
312
  if __name__ == "__main__":
src/pages/1_home.py DELETED
File without changes
src/pages/1_πŸ‹_about.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ st.set_page_config(
4
+ page_title="About",
5
+ page_icon="πŸ‹",
6
+ )
7
+
8
+ st.markdown(
9
+ """
10
+ # About
11
+ We created this web app in a hackathon.
12
+ This interface is a Proof of Concept of a Community-driven Research Data Infrastructure for the Cetacean Conservation Community.
13
+
14
+ Please reach out for feedback, suggestions, or if you want to join the project.
15
+
16
+ # Open Source Resources
17
+
18
+ The space is hosted on Hugging Face.
19
+ The code is available on Github.
20
+ All model codes are open.
21
+
22
+ # Credits and Thanks
23
+
24
+ Developers:
25
+ - Rob Mills
26
+ - Laure Vancauwenberghe
27
+
28
+ Thanks to:
29
+ - EDMAKTUB for their advice.
30
+ - SDSC for the hackathon that started the project.
31
+
32
+ """
33
+ )
src/pages/2_classifiers.py DELETED
File without changes
src/pages/2_🌍_map.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ st.set_page_config(
4
+ page_title="About",
5
+ page_icon="🌍",
6
+ layout="wide",
7
+ )
8
+
9
+ from utils.st_logs import parse_log_buffer, init_logging_session_states
10
+
11
+ from maps.obs_map import add_obs_map_header
12
+ from maps.alps_map import present_alps_map
13
+ from maps.obs_map import present_obs_map
14
+
15
+ from datasets import disable_caching
16
+ disable_caching()
17
+
18
+ ############################################################
19
+ # TO- DO: MAKE ENV FILE
20
+ # the dataset of observations (hf dataset in our space)
21
+ dataset_id = "Saving-Willy/temp_dataset"
22
+ data_files = "data/train-00000-of-00001.parquet"
23
+ USE_BASIC_MAP = False
24
+ DEV_SIDEBAR_LIB = True
25
+ ############################################################
26
+
27
+ # visual structure: a couple of toggles at the top, then the map inlcuding a
28
+ # dropdown for tileset selection.
29
+ add_obs_map_header()
30
+ tab_map_ui_cols = st.columns(2)
31
+ with tab_map_ui_cols[0]:
32
+ show_db_points = st.toggle("Show Points from DB", True)
33
+ with tab_map_ui_cols[1]:
34
+ dbg_show_extra = st.toggle("Show Extra points (test)", False)
35
+
36
+ if show_db_points:
37
+ # show a nicer map, observations marked, tileset selectable.
38
+ st_observation = present_obs_map(
39
+ dataset_id=dataset_id, data_files=data_files,
40
+ dbg_show_extra=dbg_show_extra)
41
+
42
+ else:
43
+ # development map.
44
+ st_observation = present_alps_map()
src/pages/3_benchmarking.py DELETED
File without changes
src/pages/3_πŸ”₯_classifiers.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import pandas as pd
4
+
5
+ st.set_page_config(
6
+ page_title="ML Models",
7
+ page_icon="πŸ”₯",
8
+ )
9
+
10
+ from utils.st_logs import parse_log_buffer, init_logging_session_states
11
+
12
+ from transformers import pipeline
13
+ from transformers import AutoModelForImageClassification
14
+ from classifier.classifier_image import add_classifier_header
15
+
16
+ from input.input_handling import setup_input, check_inputs_are_set
17
+ from input.input_handling import init_input_container_states, add_input_UI_elements, init_input_data_session_states
18
+ from input.input_handling import dbg_show_observation_hashes
19
+
20
+ from utils.workflow_ui import refresh_progress_display, init_workflow_viz, init_workflow_session_states
21
+ from hf_push_observations import push_all_observations
22
+
23
+ from classifier.classifier_image import cetacean_just_classify, cetacean_show_results_and_review, cetacean_show_results, init_classifier_session_states
24
+ from classifier.classifier_hotdog import hotdog_classify
25
+
26
+ # setup for the ML model on huggingface (our wrapper)
27
+ os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
28
+
29
+ ############################################################
30
+ # TO- DO: MAKE ENV FILE
31
+ #classifier_revision = '0f9c15e2db4d64e7f622ade518854b488d8d35e6'
32
+ classifier_revision = 'main' # default/latest version
33
+ # and the dataset of observations (hf dataset in our space)
34
+ dataset_id = "Saving-Willy/temp_dataset"
35
+ data_files = "data/train-00000-of-00001.parquet"
36
+ ############################################################
37
+
38
+ st.sidebar.success("classifiers")
39
+
40
+ # Streamlit app
41
+ tab_inference, tab_hotdogs= \
42
+ st.tabs(["Cetecean classifier", "Hotdog classifier"])
43
+
44
+ # put this early so the progress indicator is at the top (also refreshed at end)
45
+ refresh_progress_display()
46
+
47
+ # create a sidebar, and parse all the input (returned as `observations` object)
48
+ with st.sidebar:
49
+ # layout handling
50
+ add_input_UI_elements()
51
+ # input elements (file upload, text input, etc)
52
+ setup_input()
53
+
54
+ if st.session_state.workflow_fsm.is_in_state('doing_data_entry'):
55
+ # can we advance state? - only when all inputs are set for all uploaded files
56
+ all_inputs_set = check_inputs_are_set(debug=True, empty_ok=False)
57
+ if all_inputs_set:
58
+ st.session_state.workflow_fsm.complete_current_state()
59
+ # -> data_entry_complete
60
+ else:
61
+ # button, disabled; no state change yet.
62
+ st.sidebar.button(":gray[*Validate*]", disabled=True, help="Please fill in all fields.")
63
+
64
+
65
+ if st.session_state.workflow_fsm.is_in_state('data_entry_complete'):
66
+ # can we advance state? - only when the validate button is pressed
67
+ if st.sidebar.button(":white_check_mark:[**Validate**]"):
68
+ # create a dictionary with the submitted observation
69
+
70
+ # TO-DO NEED TO ADAPT.
71
+ #tab_log.info(f"{st.session_state.observations}")
72
+
73
+ df = pd.DataFrame([obs.to_dict() for obs in st.session_state.observations.values()])
74
+ #df = pd.DataFrame(st.session_state.observations, index=[0])
75
+ # with tab_coords:
76
+ # st.table(df)
77
+ # there doesn't seem to be any actual validation here?? TODO: find validator function (each element is validated by the input box, but is there something at the whole image level?)
78
+ # hmm, maybe it should actually just be "I'm done with data entry"
79
+ st.session_state.workflow_fsm.complete_current_state()
80
+ # -> data_entry_validated
81
+
82
+ if st.session_state.MODE_DEV_STATEFUL:
83
+ dbg_show_observation_hashes()
84
+
85
+ add_classifier_header()
86
+ # if we are before data_entry_validated, show the button, disabled.
87
+ if not st.session_state.workflow_fsm.is_in_state_or_beyond('data_entry_validated'):
88
+ tab_inference.button(":gray[*Identify with cetacean classifier*]", disabled=True,
89
+ help="Please validate inputs before proceeding",
90
+ key="button_infer_ceteans")
91
+
92
+ if st.session_state.workflow_fsm.is_in_state('data_entry_validated'):
93
+ # show the button, enabled. If pressed, we start the ML model (And advance state)
94
+ if tab_inference.button("Identify with cetacean classifier",
95
+ key="button_infer_ceteans"):
96
+ cetacean_classifier = AutoModelForImageClassification.from_pretrained(
97
+ "Saving-Willy/cetacean-classifier",
98
+ revision=classifier_revision,
99
+ trust_remote_code=True)
100
+
101
+ cetacean_just_classify(cetacean_classifier)
102
+ st.session_state.workflow_fsm.complete_current_state()
103
+ # trigger a refresh too (refreshhing the prog indicator means the script reruns and
104
+ # we can enter the next state - visualising the results / review)
105
+ # ok it doesn't if done programmatically. maybe interacting with teh button? check docs.
106
+ refresh_progress_display()
107
+ #TODO: validate this doesn't harm performance adversely.
108
+ st.rerun()
109
+
110
+ elif st.session_state.workflow_fsm.is_in_state('ml_classification_completed'):
111
+ # show the results, and allow manual validation
112
+ st.markdown("""### Inference results and manual validation/adjustment """)
113
+ if st.session_state.MODE_DEV_STATEFUL:
114
+ s = ""
115
+ for k, v in st.session_state.whale_prediction1.items():
116
+ s += f"* Image {k}: {v}\n"
117
+
118
+ st.markdown(s)
119
+
120
+ # add a button to advance the state
121
+ if st.button("Confirm species predictions", help="Confirm that all species are selected correctly"):
122
+ st.session_state.workflow_fsm.complete_current_state()
123
+ # -> manual_inspection_completed
124
+ st.rerun()
125
+
126
+ cetacean_show_results_and_review()
127
+
128
+ elif st.session_state.workflow_fsm.is_in_state('manual_inspection_completed'):
129
+ # show the ML results, and allow the user to upload the observation
130
+ st.markdown("""### Inference Results (after manual validation) """)
131
+
132
+
133
+ if st.button("Upload all observations to THE INTERNET!"):
134
+ # let this go through to the push_all func, since it just reports to log for now.
135
+ push_all_observations(enable_push=False)
136
+ st.session_state.workflow_fsm.complete_current_state()
137
+ # -> data_uploaded
138
+ st.rerun()
139
+
140
+ cetacean_show_results()
141
+
142
+ elif st.session_state.workflow_fsm.is_in_state('data_uploaded'):
143
+ # the data has been sent. Lets show the observations again
144
+ # but no buttons to upload (or greyed out ok)
145
+ st.markdown("""### Observation(s) uploaded - thank you!""")
146
+ cetacean_show_results()
147
+
148
+ st.divider()
149
+ #df = pd.DataFrame(st.session_state.observations, index=[0])
150
+ df = pd.DataFrame([obs.to_dict() for obs in st.session_state.observations.values()])
151
+ st.table(df)
152
+
153
+ # didn't decide what the next state is here - I think we are in the terminal state.
154
+ #st.session_state.workflow_fsm.complete_current_state()
155
+
156
+
157
+ # inside the hotdog tab, on button press we call a 2nd model (totally unrelated at present, just for demo
158
+ # purposes, an hotdog image classifier) which will be run locally.
159
+ # - this model predicts if the image is a hotdog or not, and returns probabilities
160
+ # - the input image is the same as for the ceteacean classifier - defined in the sidebar
161
+ tab_hotdogs.title("Hot Dog? Or Not?")
162
+ tab_hotdogs.write("""
163
+ *Run alternative classifer on input images. Here we are using
164
+ a binary classifier - hotdog or not - from
165
+ huggingface.co/julien-c/hotdog-not-hotdog.*""")
166
+
167
+ if tab_hotdogs.button("Get Hotdog Prediction"):
168
+
169
+ pipeline_hot_dog = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")
170
+
171
+ if st.session_state.image is None:
172
+ st.info("Please upload an image first.")
173
+ #st.info(str(observations.to_dict()))
174
+
175
+ else:
176
+ hotdog_classify(pipeline_hot_dog, tab_hotdogs)
177
+
178
+
179
+ # after all other processing, we can show the stage/state
180
+ refresh_progress_display()
src/pages/4_requests.py DELETED
File without changes
src/pages/4_πŸ†_benchmarking.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ st.set_page_config(
4
+ page_title="Benchmarking",
5
+ page_icon="πŸ†",
6
+ )
7
+
8
+ from utils.st_logs import parse_log_buffer, init_logging_session_states
src/pages/5_🀝_requests.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ st.set_page_config(
4
+ page_title="Requests",
5
+ page_icon="🀝",
6
+ )
7
+
8
+ from utils.st_logs import parse_log_buffer, init_logging_session_states
src/pages/6_🌊_gallery.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ st.set_page_config(
4
+ page_title="ML Models",
5
+ page_icon="🌊",
6
+ layout="wide",
7
+ )
8
+ from utils.st_logs import parse_log_buffer, init_logging_session_states
9
+
10
+ import whale_gallery as gallery
11
+ import whale_viewer as viewer
12
+
13
+ # here we make a container to allow filtering css properties
14
+ # specific to the gallery (otherwise we get side effects)
15
+ tg_cont = st.container(key="swgallery")
16
+ with tg_cont:
17
+ gallery.render_whale_gallery(n_cols=4)
src/pages/7_🚧_coordinates.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import folium
3
+ from streamlit_folium import st_folium
4
+
5
+ st.set_page_config(
6
+ page_title="Coordinates",
7
+ page_icon="🚧",
8
+ layout="wide",
9
+ )
10
+
11
+ # the goal of this tab is to allow selection of the new obsvation's location by map click/adjust.
12
+ st.markdown("Coming later! :construction:")
13
+ st.markdown(
14
+ """*The goal is to allow interactive definition for the coordinates of a new
15
+ observation, by click/drag points on the map.*""")
16
+
17
+
18
+ st.write("Click on the map to capture a location.")
19
+ #m = folium.Map(location=visp_loc, zoom_start=7)
20
+ mm = folium.Map(location=[39.949610, -75.150282], zoom_start=16)
21
+ folium.Marker( [39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell"
22
+ ).add_to(mm)
23
+
24
+ st_data2 = st_folium(mm, width=725)
25
+ st.write("below the map...")
26
+ if st_data2['last_clicked'] is not None:
27
+ print(st_data2)
28
+ st.info(st_data2['last_clicked'])
src/pages/πŸ“Š_logs.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+
4
+ st.set_page_config(
5
+ page_title="Logs",
6
+ page_icon="πŸ“Š",
7
+ )
8
+
9
+ from utils.st_logs import parse_log_buffer
10
+
11
+ handler = st.session_state['handler']
12
+ if handler is not None:
13
+ records = parse_log_buffer(handler.buffer)
14
+ st.dataframe(records[::-1], use_container_width=True,)
15
+ st.info(f"Length of records: {len(records)}")
16
+ else:
17
+ st.error("⚠️ No log handler found!")