Spaces:
Build error
Build error
rmm commited on
Commit ·
ba6e051
1
Parent(s): cd85869
chore: reorganise code out of main, and docstrings in input_handling
Browse filesFiles changed (2)
- src/input/input_handling.py+88-31
- src/main.py+6-18
89 unmodified lines9091929394959629 unmodified lines1261271281291301315 unmodified lines13713813914014114214314414514614714814947 unmodified lines19719819920020120220320420520620720828 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582592602612623 unmodified lines26626726826927027127227327427527627727827928028128228318 unmodified lines30230330430589 unmodified linesreturn all([v is not None for v in vals])def buffer_files():# buffer info from the file_uploader that doesn't require further user input# - the image, the hash, the filename# a separate function takes care of per-file user inputs for metadata29 unmodified linesdef load_file_and_hash(file:UploadedFile) -> Tuple[np.ndarray, str]:# two operations that require reading the file done together for efficiency# load the file, compute the hash, return the image and hash_bytes = file.read()5 unmodified linesdef metadata_inputs_one_file(file:UploadedFile, image_hash:str, dbg_ix:int=0) -> InputObservation:# dbg_ix is a hack to have different data in each input group, checking persistenceif st.session_state.container_metadata_inputs is not None:_viewcontainer = st.session_state.container_metadata_inputselse:_viewcontainer = st.sidebarprint(f"[W] `container_metadata_inputs` is None, using sidebar")47 unmodified linesuploaded_file=file, image_md5=image_hash)# TODO: pass in the hash to InputObservation, so it is done once only. (need to refactor the class a bit)return observationdef _setup_dynamic_inputs() -> None:# for each file uploaded,# - add the UI elements for the metadata28 unmodified linesdef _setup_oneoff_inputs() -> None:'''Add the UI input elements for which we have one each'''st.title("Input image and data")# setup containers for consistent layout order with dynamic elements#container_file_uploader = st.container(border=False, key="container_file_uploader")container_file_uploader = st.session_state.container_file_uploader# - a container for the dynamic input elements (this one matters)#if "container_per_file_input_elems" not in st.session_state:# if st.session_state.container_per_file_input_elems is None:# #st.session_state.container_per_file_input_elems = None# c = st.container(border=True, key="container_per_file_input_elems")# with c:# st.write("No files uploaded yet.")# print(f"[D] initialised the container..... {id(c)} | {c=}")# st.session_state.container_per_file_input_elems = c# else:# print(f"[D] already present, don't redo... {id(st.session_state.container_per_file_input_elems)} | {st.session_state.container_per_file_input_elems=}")with container_file_uploader:# 1. Input the author email3 unmodified linesst.error("Please enter a valid email address.")# 2. Image Selectorst.file_uploader("Upload one or more images", type=["png", 'jpg', 'jpeg', 'webp'],accept_multiple_files=True,key="file_uploader_data",on_change=buffer_files)if 1:uploaded_files = st.session_state.file_uploader_datafor ix, file in enumerate(uploaded_files):print(f"[DD] rechecking file {file.name}. {file.file_id} {file.type} {file.size}")pass18 unmodified lines# setup dynamic UI input elements, based on the data that is buffered in session_state_setup_dynamic_inputs()89 unmodified lines9091929394959697989910010110210310410510610710810911029 unmodified lines1401411421431441451461471481491501511521531541551565 unmodified lines16216316416516616716816917017117217317417517617717817918018118218318447 unmodified lines23223323423523623723823924024124224324424524624724824928 unmodified lines2782792802812822832842852862872882892902913 unmodified lines29529629729829930030130230330430530618 unmodified lines32532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136289 unmodified linesreturn all([v is not None for v in vals])def buffer_uploaded_files():"""Buffers uploaded files to session_state (images, image_hashes, filenames).Buffers uploaded files by extracting and storing filenames, images, andimage hashes in the session state.Adds the following keys to `st.session_state`:- `images`: dict mapping image hashes to image data (numpy arrays)- `files`: list of uploaded files- `image_hashes`: list of image hashes- `image_filenames`: list of filenames"""# buffer info from the file_uploader that doesn't require further user input# - the image, the hash, the filename# a separate function takes care of per-file user inputs for metadata29 unmodified linesdef load_file_and_hash(file:UploadedFile) -> Tuple[np.ndarray, str]:"""Loads an image file and computes its MD5 hash.Since both operations require reading the full file contentsV, they are donetogether for efficiency.Args:file (UploadedFile): The uploaded file to be processed.Returns:Tuple[np.ndarray, str]: A tuple containing the decoded image as a NumPy array and the MD5 hash of the file's contents."""# two operations that require reading the file done together for efficiency# load the file, compute the hash, return the image and hash_bytes = file.read()5 unmodified linesdef metadata_inputs_one_file(file:UploadedFile, image_hash:str, dbg_ix:int=0) -> InputObservation:"""Creates and parses metadata inputs for a single fileArgs:file (UploadedFile): The uploaded file for which metadata is being handled.image_hash (str): The hash of the image.dbg_ix (int, optional): Debug index to differentiate data in each input group. Defaults to 0.Returns:InputObservation: An object containing the metadata and other information for the input file."""# dbg_ix is a hack to have different data in each input group, checking persistenceif st.session_state.container_metadata_inputs is not None:_viewcontainer = st.session_state.container_metadata_inputselse:_viewcontainer = st.sidebarm_logger.warning(f"[W] `container_metadata_inputs` is None, using sidebar")47 unmodified linesuploaded_file=file, image_md5=image_hash)return observationdef _setup_dynamic_inputs() -> None:"""Setup metadata inputs dynamically for each uploaded file, and process.This operates on the data buffered in the session state, and writesthe observation objects back to the session state."""# for each file uploaded,# - add the UI elements for the metadata28 unmodified linesdef _setup_oneoff_inputs() -> None:'''Add the UI input elements for which we have one covering all files- author email- file uploader (accepts multiple files)'''# fetch the container for the file uploader input elementscontainer_file_uploader = st.session_state.container_file_uploaderwith container_file_uploader:# 1. Input the author email3 unmodified linesst.error("Please enter a valid email address.")# 2. Image Selectorst.file_uploader("Upload one or more images", type=["png", 'jpg', 'jpeg', 'webp'],accept_multiple_files=True,key="file_uploader_data", on_change=buffer_uploaded_files)18 unmodified lines# setup dynamic UI input elements, based on the data that is buffered in session_state_setup_dynamic_inputs()def init_input_container_states() -> None:'''Initialise the layout containers used in the input handling'''#if "container_per_file_input_elems" not in st.session_state:# st.session_state.container_per_file_input_elems = Noneif "container_file_uploader" not in st.session_state:st.session_state.container_file_uploader = Noneif "container_metadata_inputs" not in st.session_state:st.session_state.container_metadata_inputs = Nonedef add_input_UI_elements() -> None:'''Create the containers within which user input elements will be placed'''# we make containers ahead of time, allowing consistent order of elements# which are not created in the same order.st.divider()st.title("Input image and data")# create and style a container for the file uploader/other one-off inputsst.markdown('<style>.st-key-container_file_uploader_id { border: 1px solid skyblue; border-radius: 5px; }</style>', unsafe_allow_html=True)container_file_uploader = st.container(border=True, key="container_file_uploader_id")st.session_state.container_file_uploader = container_file_uploader# create and style a container for the dynamic metadata inputsst.markdown('<style>.st-key-container_metadata_inputs_id { border: 1px solid lightgreen; border-radius: 5px; }</style>', unsafe_allow_html=True)container_metadata_inputs = st.container(border=True, key="container_metadata_inputs_id")container_metadata_inputs.write("Metadata Inputs... wait for file upload ")st.session_state.container_metadata_inputs = container_metadata_inputs
16 unmodified lines17181920212259 unmodified lines828384858687888990919293949561 unmodified lines15715815916016116216316416516616716816917017117216 unmodified linesimport whale_gallery as galleryimport whale_viewer as viewerfrom input.input_handling import setup_input, check_inputs_are_setfrom maps.alps_map import present_alps_mapfrom maps.obs_map import present_obs_mapfrom utils.st_logs import setup_logging, parse_log_buffer59 unmodified lines# create and init the state machinest.session_state.workflow_fsm = WorkflowFSM(FSM_STATES)if "container_per_file_input_elems" not in st.session_state:st.session_state.container_per_file_input_elems = Noneif "container_file_uploader" not in st.session_state:st.session_state.container_file_uploader = Noneif "container_metadata_inputs" not in st.session_state:st.session_state.container_metadata_inputs = Nonedef refresh_progress():with st.sidebar:61 unmodified lines# create a sidebar, and parse all the input (returned as `observations` object)with st.sidebar:st.divider()st.markdown('<style>.st-key-container_file_uploader_id { border: 1px solid skyblue; border-radius: 5px; }</style>', unsafe_allow_html=True)container_file_uploader = st.container(border=True, key="container_file_uploader_id")st.session_state.container_file_uploader = container_file_uploaderst.markdown('<style>.st-key-container_metadata_inputs_id { border: 1px solid lightgreen; border-radius: 5px; }</style>', unsafe_allow_html=True)container_metadata_inputs = st.container(border=True, key="container_metadata_inputs_id")container_metadata_inputs.write("Metadata Inputs... wait for file upload ")st.session_state.container_metadata_inputs = container_metadata_inputssetup_input()16 unmodified lines171819202122232459 unmodified lines8485868788899061 unmodified lines15215315415515615715815916016 unmodified linesimport whale_gallery as galleryimport whale_viewer as viewerfrom input.input_handling import setup_input, check_inputs_are_setfrom input.input_handling import init_input_container_states, add_input_UI_elementsfrom maps.alps_map import present_alps_mapfrom maps.obs_map import present_obs_mapfrom utils.st_logs import setup_logging, parse_log_buffer59 unmodified lines# create and init the state machinest.session_state.workflow_fsm = WorkflowFSM(FSM_STATES)init_input_container_states()def refresh_progress():with st.sidebar:61 unmodified lines# create a sidebar, and parse all the input (returned as `observations` object)with st.sidebar:# layout handlingadd_input_UI_elements()# input elements (file upload, text input, etc)setup_input()
src/input/input_handling.py+88-31
src/main.py+6-18