Spaces:
Sleeping
Sleeping
Download app.py from MitchellAcoustics/Soundscapy_web: direct link, hf CLI and curl.
- Browser
- Download file 20.9 kB
-
https://huggingface.co/spaces/MitchellAcoustics/Soundscapy_web/resolve/main/app.py
- Command line
-
hf download hf://spaces/MitchellAcoustics/Soundscapy_web/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MitchellAcoustics/Soundscapy_web/resolve/main/app.py
20.9 kB
| # /// script | |
| # requires-python = ">=3.12" | |
| # dependencies = [ | |
| # "marimo", | |
| # "matplotlib==3.9.2", | |
| # "ordered-set==4.1.0", | |
| # "pandas==2.2.3", | |
| # "soundscapy==0.7.6", | |
| # ] | |
| # /// | |
| import marimo | |
| __generated_with = "0.9.19" | |
| app = marimo.App(width="full", app_title="Soundscapy_viz") | |
| def __(): | |
| import marimo as mo | |
| mo.sidebar( | |
| [ | |
| mo.image( | |
| src="https://raw.githubusercontent.com/MitchellAcoustics/Soundscapy/main/docs/img/LightLogo.png" | |
| ), | |
| mo.md( | |
| "" | |
| ).center(), | |
| mo.nav_menu( | |
| { | |
| "Links": { | |
| "https://soundscapy.readthedocs.io/en/latest/": f"{mo.icon('oui:documentation')} Documentation", | |
| "https://github.com/MitchellAcoustics/Soundscapy": f"{mo.icon('logos:github-icon')} GitHub", | |
| }, | |
| }, | |
| orientation="vertical", | |
| ), | |
| ] | |
| ) | |
| return (mo,) | |
| def __(mo): | |
| with mo.status.spinner(subtitle="Loading ...") as _spinner: | |
| import soundscapy as sspy | |
| from soundscapy.surveys.survey_utils import ( | |
| EQUAL_ANGLES, | |
| PAQ, | |
| PAQ_LABELS, | |
| PAQ_IDS, | |
| ) | |
| from soundscapy.plotting import ( | |
| CircumplexPlotParams, | |
| CircumplexPlot, | |
| PlotType, | |
| Backend, | |
| ) | |
| import pandas as pd | |
| from pandas.errors import UndefinedVariableError | |
| import io | |
| from ordered_set import OrderedSet | |
| from dataclasses import dataclass | |
| import matplotlib.pyplot as plt | |
| return ( | |
| Backend, | |
| CircumplexPlot, | |
| CircumplexPlotParams, | |
| EQUAL_ANGLES, | |
| OrderedSet, | |
| PAQ, | |
| PAQ_IDS, | |
| PAQ_LABELS, | |
| PlotType, | |
| UndefinedVariableError, | |
| dataclass, | |
| io, | |
| pd, | |
| plt, | |
| sspy, | |
| ) | |
| def __(mo): | |
| mo.hstack( | |
| [mo.md("# Explore one of our datasets or load your own data").center()], | |
| gap=6.0, | |
| justify="space-around", | |
| ) | |
| return | |
| def __(mo): | |
| # Data Loading | |
| included_data_source_mo = mo.ui.dropdown( | |
| options=["ISD", "SATP", "ARAUS"], | |
| value="ISD", | |
| label="Select Dataset", | |
| full_width=True, | |
| ) | |
| upload_file_mo = mo.ui.file( | |
| filetypes=[".csv"], kind="area", label="**Load your own data**" | |
| ) | |
| data_load_mo = mo.vstack( | |
| [ | |
| mo.md("## Load Data"), | |
| included_data_source_mo, | |
| upload_file_mo, | |
| ] | |
| ) | |
| mo.vstack( | |
| [ | |
| mo.hstack( | |
| [ | |
| mo.md( | |
| r""" | |
| `soundscapy` was built to work with soundscape survey data. We make it super simple to load up and explore a few supported datasets. | |
| Simply select which dataset you'd like to explore and we'll automatically load it for you. | |
| But, that's not all! You don't just have to use one of our supported datasets! You can also load in your own data and create some lovely soundscapy-style plots. Just scroll on down to the load your data button. | |
| """ | |
| ), | |
| data_load_mo, | |
| ], | |
| widths=[5, 3], | |
| align="center", | |
| justify="center", | |
| gap=8.0, | |
| ), | |
| mo.md("---"), | |
| ], | |
| justify="center", | |
| gap=6.0, | |
| ) | |
| return data_load_mo, included_data_source_mo, upload_file_mo | |
| def __(data_loading, included_data_source_mo, upload_file_mo): | |
| raw_data, data_source = data_loading(included_data_source_mo, upload_file_mo) | |
| return data_source, raw_data | |
| def __( | |
| calc_iso_coords_check, | |
| circumplex_angles, | |
| column_filter, | |
| column_to_filter_by, | |
| custom_iso_names, | |
| grouped_filter_table, | |
| mo, | |
| p_mo, | |
| paq_val_range, | |
| plot_title, | |
| plot_type_option, | |
| plotting_backend, | |
| query_filters, | |
| remove_missing_vals_option, | |
| rename_paqs_option, | |
| seaborn_color, | |
| seaborn_diag_lines, | |
| seaborn_hue, | |
| seaborn_palette, | |
| validate_data_check, | |
| ): | |
| data_settings = mo.vstack( | |
| [ | |
| mo.md("### Data Settings"), | |
| validate_data_check, | |
| calc_iso_coords_check, | |
| paq_val_range.vstack(), | |
| mo.accordion( | |
| { | |
| "Set custom names for the ISO Coordinates": custom_iso_names.vstack(), | |
| "Select Columns": column_filter.form( | |
| label="Select Columns to include: " | |
| ), | |
| "Filter Rows": mo.vstack( | |
| [column_to_filter_by, grouped_filter_table] | |
| ), | |
| "Extra Filters": query_filters.vstack(), | |
| "Rename PAQs": rename_paqs_option.vstack(), | |
| "Extra Options": mo.vstack( | |
| [ | |
| remove_missing_vals_option, | |
| mo.accordion({"Custom Angles": circumplex_angles.vstack()}), | |
| ] | |
| ), | |
| } | |
| ), | |
| ] | |
| ) | |
| plot_settings = mo.vstack( | |
| [ | |
| mo.md("### Plot Settings"), | |
| plot_title, | |
| seaborn_hue, | |
| seaborn_palette, | |
| seaborn_color, | |
| plot_type_option, | |
| plotting_backend, | |
| seaborn_diag_lines, | |
| ] | |
| ) | |
| mo.output.append( | |
| mo.hstack([data_settings, p_mo, plot_settings], gap=4.0, justify="space-around") | |
| ) | |
| return data_settings, plot_settings | |
| def __(data, data_description, data_source, mo, plot_data, raw_data): | |
| with mo.status.spinner(subtitle="Preparing data ...") as _spinner: | |
| explore_data = mo.ui.tabs( | |
| { | |
| "Data Overview": mo.ui.table( | |
| data_description(data_source, data), page_size=20, selection=None | |
| ), | |
| "Data": mo.ui.table(plot_data, selection=None, page_size=20), | |
| "Original Data": mo.ui.table(raw_data, selection=None, page_size=20), | |
| "Explore Data": mo.ui.data_explorer(plot_data), | |
| } | |
| ).style(max_width="100%") | |
| mo.vstack( | |
| [ | |
| mo.md("---"), | |
| explore_data, | |
| ] | |
| ).style(max_width="100%") | |
| return (explore_data,) | |
| def __(mo, plot_data, seaborn_hue): | |
| if seaborn_hue.value != None: | |
| seaborn_loc = mo.ui.multiselect.from_series( | |
| plot_data[seaborn_hue.value], value=None, label="Select groups: " | |
| ) | |
| return (seaborn_loc,) | |
| def __(): | |
| # from typing import TypedDict | |
| # @dataclass(frozen=True) | |
| # class VegaItem: | |
| # id: str | |
| # dict_path: list | |
| # default: Any | |
| # @dataclass(frozen=True) | |
| # class VegaConfig: | |
| # x = VegaItem("x", ["encoding", "x", "field"], custom_iso_names.value[0]) | |
| # y = VegaItem("y", ["encoding", "y", "field"], custom_iso_names.value[0]) | |
| # hue = VegaItem("hue", ["encoding", "color", "field"], "LocationID") | |
| # color = VegaItem("color", ["encoding", "color", "field"], None) | |
| # row = VegaItem("row", ["encoding", "row", "field"], None) | |
| # column = VegaItem("column", ["encoding", "column", "field"], None) | |
| # size = VegaItem("size", ["encoding", "size", "field"], None) | |
| # shape = VegaItem("shape", ["encoding", "shape", "field"], None) | |
| # _vega_config = data_explorer.value | |
| # def get_item(self, id: str): | |
| # return getattr(self, id) | |
| # def traverse_dict(self, id: str) -> Any: | |
| # """ | |
| # Get a value nested in a dictionary by its nested path. | |
| # """ | |
| # default = self.get_item(id).default | |
| # value_path = self.get_item(id).dict_path | |
| # dict_chain = self._vega_config | |
| # while value_path: | |
| # dict_chain = dict_chain.get(value_path.pop(0), default) | |
| # return dict_chain | |
| # p = VegaConfig() | |
| # p.traverse_dict("x") | |
| return | |
| def __(EQUAL_ANGLES, PAQ_IDS, PAQ_LABELS, mo): | |
| # Setup marimo inputs for iso parameters | |
| validate_data_check = mo.ui.checkbox( | |
| value=True, label="Apply ISD-style data validation?" | |
| ) | |
| calc_iso_coords_check = mo.ui.checkbox( | |
| value=True, label="Calculate ISD Coordinates?" | |
| ) | |
| custom_iso_names = mo.ui.array( | |
| [ | |
| mo.ui.text(value="ISOPleasant", label="X label: ", debounce=True), | |
| mo.ui.text(value="ISOEventful", label="Y label: ", debounce=True), | |
| ], | |
| ) | |
| paq_val_range = mo.ui.array( | |
| [ | |
| mo.ui.number( | |
| value=1, | |
| step=1, | |
| label="PAQ Min value", | |
| full_width=True, | |
| debounce=True, | |
| ), | |
| mo.ui.number( | |
| value=5, | |
| step=1, | |
| label="PAQ Max value", | |
| full_width=True, | |
| debounce=True, | |
| ), | |
| ] | |
| ) | |
| rename_paqs_option = mo.ui.dictionary( | |
| { | |
| f"{PAQ_IDS[i]}": mo.ui.text( | |
| label=f"{PAQ_IDS[i]}: ", value=paq_label, debounce=True | |
| ) | |
| for i, paq_label in enumerate(PAQ_LABELS) | |
| } | |
| ) | |
| remove_missing_vals_option = mo.ui.checkbox( | |
| value=False, label="Remove all missing values?" | |
| ) | |
| circumplex_angles = mo.ui.array( | |
| [ | |
| mo.ui.number(value=EQUAL_ANGLES[i], label=f"{paq}: ", debounce=True) | |
| for i, paq in enumerate(PAQ_IDS) | |
| ] | |
| ) | |
| return ( | |
| calc_iso_coords_check, | |
| circumplex_angles, | |
| custom_iso_names, | |
| paq_val_range, | |
| remove_missing_vals_option, | |
| rename_paqs_option, | |
| validate_data_check, | |
| ) | |
| def __(mo, raw_data): | |
| # Data filtering 1 | |
| column_to_filter_by = mo.ui.dropdown( | |
| label="Column to filter by:", | |
| options=list(raw_data.columns), | |
| allow_select_none=True, | |
| value=None, | |
| full_width=True, | |
| ) | |
| return (column_to_filter_by,) | |
| def __(OrderedSet, column_to_filter_by, custom_iso_names, mo, raw_data): | |
| # Data filtering 2 | |
| column_filter = mo.ui.table( | |
| data=list( | |
| OrderedSet( | |
| list(raw_data.columns)[:4] | |
| + [name for name in custom_iso_names.value] | |
| + list(raw_data.columns)[4:] | |
| ) | |
| ), | |
| page_size=10, | |
| ) | |
| # Set up table to select a column to filter rows by and select row values to filter | |
| if column_to_filter_by.value is not None: | |
| grouped_filter_table = mo.ui.table( | |
| data=list(raw_data[column_to_filter_by.value].unique()), | |
| page_size=10, | |
| ).form(label="Select rows to include:") | |
| else: | |
| grouped_filter_table = mo.md("No column selected for filtering.") | |
| grouped_filter_table.value = None | |
| query_filters = mo.ui.array( | |
| [ | |
| mo.ui.text( | |
| label="pd.query command for filtering: ", | |
| placeholder="e.g.: LocationID in ['CamdenTown', 'PancrasLock']", | |
| full_width=True, | |
| ) | |
| for _ in range(4) | |
| ] | |
| ) | |
| return column_filter, grouped_filter_table, query_filters | |
| def __(mo, plot_data): | |
| # Setup Seaborn arguments | |
| plot_title = mo.ui.text(value="Soundscapy plot", label="Title: ", full_width=True) | |
| available_palettes = ( | |
| "deep", | |
| "muted", | |
| "bright", | |
| "pastel", | |
| "dark", | |
| "colorblind", | |
| ) | |
| seaborn_palette = mo.ui.dropdown( | |
| options=available_palettes, | |
| value="colorblind", | |
| label="Palette: ", | |
| full_width=True, | |
| ) | |
| seaborn_color = mo.ui.text(value="blue", label="Color: ", full_width=True) | |
| seaborn_diag_lines = mo.ui.checkbox( | |
| value=False, label="Show secondary axes lines and labels on sspy plot?" | |
| ) | |
| seaborn_hue = mo.ui.dropdown( | |
| plot_data.columns.tolist(), | |
| value=None, | |
| allow_select_none=True, | |
| label="Split dataset by: ", | |
| full_width=True, | |
| ) | |
| plot_type_option = mo.ui.dropdown( | |
| ["scatter", "density", "simple_density", "joint"], | |
| value="density", | |
| label="Seaborn plot type: ", | |
| full_width=True, | |
| ) | |
| plotting_backend = mo.ui.dropdown( | |
| ["seaborn", "plotly"], value="seaborn", full_width=True | |
| ) | |
| return ( | |
| available_palettes, | |
| plot_title, | |
| plot_type_option, | |
| plotting_backend, | |
| seaborn_color, | |
| seaborn_diag_lines, | |
| seaborn_hue, | |
| seaborn_palette, | |
| ) | |
| def __( | |
| calc_iso_coords_check, | |
| circumplex_angles, | |
| column_filter, | |
| column_to_filter_by, | |
| custom_iso_names, | |
| data_sspy_setup, | |
| grouped_filter_table, | |
| paq_val_range, | |
| query_filters, | |
| raw_data, | |
| remove_missing_vals_option, | |
| rename_paqs_option, | |
| validate_data_check, | |
| ): | |
| data = data_sspy_setup( | |
| raw_data, | |
| validate_data_check.value, | |
| calc_iso_coords_check.value, | |
| column_filter.value, | |
| query_filters.value, | |
| rename_paqs_option.value, | |
| remove_missing_vals_option.value, | |
| paq_val_range.value, | |
| custom_iso_names.value, | |
| circumplex_angles.value, | |
| column_to_filter_by.value, | |
| grouped_filter_table.value, | |
| ) | |
| plot_data = data.copy() | |
| return data, plot_data | |
| def __( | |
| PlotType, | |
| create_sspy_plot, | |
| custom_iso_names, | |
| mo, | |
| plot_data, | |
| plot_title, | |
| plot_type_option, | |
| plotting_backend, | |
| seaborn_color, | |
| seaborn_diag_lines, | |
| seaborn_hue, | |
| seaborn_palette, | |
| ): | |
| try: | |
| p = create_sspy_plot( | |
| plot_data, | |
| custom_iso_names.value, | |
| PlotType(plot_type_option.value), | |
| plot_title.value, | |
| seaborn_palette.value, | |
| seaborn_color.value, | |
| seaborn_diag_lines.value, | |
| seaborn_hue.value, | |
| plotting_backend.value, | |
| ) | |
| p_mo = p.get_figure() | |
| except Exception as e: | |
| p_mo = mo.md(f"{e}").callout(kind="danger") | |
| return p, p_mo | |
| def sspy_data_setup(OrderedSet, UndefinedVariableError, mo, pd, sspy): | |
| def add_coords_to_sspy_df(data, isopl, isoev, names, overwrite=False): | |
| for name in names: | |
| if name in data.columns: | |
| if overwrite: | |
| data = data.drop(name, axis=1) | |
| else: | |
| raise Warning( | |
| f"{name} already in dataframe. Use overwrite=Trueoverwrite=True to replace it." | |
| ) | |
| data = data.assign(**{names[0]: isopl, names[1]: isoev}) | |
| return data | |
| def data_sspy_setup( | |
| data: pd.DataFrame, | |
| validate_data: bool, | |
| calc_iso_coords: bool, | |
| column_filter, | |
| query_filters: list[str], | |
| rename_paqs_option_dict: dict[str, str], | |
| remove_missing_vals: bool, | |
| paq_val_range: list[int], | |
| custom_iso_names: list[str], | |
| circumplex_angles: list[int], | |
| column_to_filter_by: str = None, | |
| grouped_filter_table: pd.DataFrame | list = None, | |
| ): | |
| # try: | |
| if validate_data is True: | |
| data, excl_data = sspy.isd.validate( | |
| data, | |
| paq_aliases={ | |
| v: k for k, v in rename_paqs_option_dict.items() | |
| }, # Need to reverse key-val mapping | |
| allow_paq_na=remove_missing_vals, | |
| val_range=paq_val_range, | |
| ) | |
| if calc_iso_coords is True: | |
| isopl, isoev = sspy.surveys.processing.calculate_iso_coords( | |
| data, | |
| val_range=paq_val_range, | |
| angles=circumplex_angles, | |
| ) | |
| data = add_coords_to_sspy_df( | |
| data, | |
| isopl.round(2), | |
| isoev.round(2), | |
| names=custom_iso_names, | |
| overwrite=True, | |
| ) | |
| # except Exception as e: | |
| # mo.stop(True, mo.md(f"data_sspy_setup 1: {e}").callout("danger")) | |
| # try: | |
| if column_to_filter_by is not None and grouped_filter_table is not None: | |
| if len(grouped_filter_table) != 0: | |
| data = data[data[column_to_filter_by].isin(grouped_filter_table)] | |
| column_filter_set = OrderedSet(column_filter) | |
| if len(column_filter_set) >= 1: | |
| data = data[column_filter_set] | |
| for query_filter_element in query_filters: | |
| if query_filter_element != "": | |
| try: | |
| data.query(query_filter_element, inplace=True) | |
| except UndefinedVariableError as e: | |
| mo.md(e) | |
| return data | |
| # except Exception as e: | |
| # mo.stop(True, mo.md(f"data_sspy_setup 2: {e}").callout("danger")) | |
| return add_coords_to_sspy_df, data_sspy_setup | |
| def __(sspy): | |
| def data_description(data_source, data): | |
| if data_source == "isd": | |
| try: | |
| return sspy.isd.soundscapy_describe(data) | |
| except: | |
| return data.describe().round(2) | |
| else: | |
| return data.describe().round(2) | |
| return (data_description,) | |
| def __(Tuple, io, mo, pd, sspy): | |
| def data_loading( | |
| included_data_source_mo, uploaded_file_mo | |
| ) -> Tuple[pd.DataFrame, str]: | |
| try: | |
| if included_data_source_mo is None and uploaded_file_mo is None: | |
| mo.md("Need to load some data!").callout("neutral") | |
| return | |
| file_has_been_uploaded = True if uploaded_file_mo.name() else False | |
| if file_has_been_uploaded: | |
| data = pd.read_csv(io.StringIO(uploaded_file_mo.contents().decode())) | |
| data_source = "upload" | |
| elif included_data_source_mo.value in ["SATP", "ARAUS"]: | |
| data = pd.DataFrame() | |
| mo.md("Only ISD has been implemented.").callout("danger") | |
| elif included_data_source_mo.value == "ISD": | |
| data = sspy.isd.load() | |
| data = sspy.surveys.survey_utils.return_paqs( | |
| data, | |
| incl_ids=True, | |
| other_cols=[ | |
| "Language", | |
| "Survey_Version", | |
| "start_time", | |
| "end_time", | |
| "latitude", | |
| "longitude", | |
| "ssi01", | |
| "ssi02", | |
| "ssi03", | |
| "ssi04", | |
| "sss01", | |
| "sss02", | |
| "sss03", | |
| "sss04", | |
| "sss05", | |
| "WHO_Sum", | |
| "age00", | |
| "gen00", | |
| "RecordingLength", | |
| "LZeq_L_Max", | |
| "LAeq_L(A)_Max", | |
| "LCeq_L(C)_Max", | |
| "LAeq_L10(A)_Max", | |
| "LAeq_L90(A)_Max", | |
| "N_N5_Max", | |
| "S_S_Max", | |
| "R_R_Max", | |
| "T_TonalityHMS_Max", | |
| "FS_F_Max", | |
| "I_I_Max", | |
| "SIL4_SIL(rms)_Max", | |
| "THD_THD_Max", | |
| ], | |
| ) | |
| data_source = "isd" | |
| return data, data_source | |
| except Exception as e: | |
| mo.stop(True, mo.md(f"{e}").callout("danger")) | |
| return (data_loading,) | |
| def __(Backend, CircumplexPlot, CircumplexPlotParams, PlotType): | |
| def create_sspy_plot( | |
| data, | |
| custom_iso_names, | |
| plot_type, | |
| plot_title, | |
| seaborn_palette, | |
| seaborn_color, | |
| seaborn_diag_lines, | |
| seaborn_hue, | |
| plotting_backend, | |
| ): | |
| circ_params = CircumplexPlotParams( | |
| x=custom_iso_names[0], | |
| y=custom_iso_names[1], | |
| hue=seaborn_hue, | |
| title=plot_title, | |
| palette=seaborn_palette, | |
| incl_outline=True if plot_type == PlotType.SIMPLE_DENSITY else False, | |
| diagonal_lines=seaborn_diag_lines, | |
| ) | |
| circ_plot = CircumplexPlot(data, circ_params, Backend(plotting_backend)) | |
| return circ_plot._create_plot(plot_type) | |
| return (create_sspy_plot,) | |
| if __name__ == "__main__": | |
| app.run() | |