instance_id
stringlengths
10
57
base_commit
stringlengths
40
40
created_at
stringdate
2014-04-30 14:58:36
2025-04-30 20:14:11
environment_setup_commit
stringlengths
40
40
hints_text
stringlengths
0
273k
patch
stringlengths
251
7.06M
problem_statement
stringlengths
11
52.5k
repo
stringlengths
7
53
test_patch
stringlengths
231
997k
meta
dict
version
stringclasses
864 values
install_config
dict
requirements
stringlengths
93
34.2k
environment
stringlengths
760
20.5k
FAIL_TO_PASS
listlengths
1
9.39k
FAIL_TO_FAIL
listlengths
0
2.69k
PASS_TO_PASS
listlengths
0
7.87k
PASS_TO_FAIL
listlengths
0
192
license_name
stringclasses
56 values
docker_image
stringlengths
42
89
image_name
stringlengths
42
89
0b01001001__spectree-64
a091fab020ac26548250c907bae0855273a98778
2020-10-12 13:21:50
a091fab020ac26548250c907bae0855273a98778
diff --git a/setup.py b/setup.py index 1b3cb64..4ef21e6 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f: setup( name='spectree', - version='0.3.7', + version='0.3.8', author='Keming Yang', author_email='kemingy94@gmail.com', description=('generate OpenAPI document and validate request&response ' diff --git a/spectree/utils.py b/spectree/utils.py index bb5698d..73d6c71 100644 --- a/spectree/utils.py +++ b/spectree/utils.py @@ -54,6 +54,7 @@ def parse_params(func, params, models): 'in': 'query', 'schema': schema, 'required': name in query.get('required', []), + 'description': schema.get('description', ''), }) if hasattr(func, 'headers'): @@ -64,6 +65,7 @@ def parse_params(func, params, models): 'in': 'header', 'schema': schema, 'required': name in headers.get('required', []), + 'description': schema.get('description', ''), }) if hasattr(func, 'cookies'): @@ -74,6 +76,7 @@ def parse_params(func, params, models): 'in': 'cookie', 'schema': schema, 'required': name in cookies.get('required', []), + 'description': schema.get('description', ''), }) return params
[BUG]description for query paramters can not show in swagger ui Hi, when I add a description for a schema used in query, it can not show in swagger ui but can show in Redoc ```py @HELLO.route('/', methods=['GET']) @api.validate(query=HelloForm) def hello(): """ hello 注释 :return: """ return 'ok' class HelloForm(BaseModel): """ hello表单 """ user: str # 用户名称 msg: str = Field(description='msg test', example='aa') index: int data: HelloGetListForm list: List[HelloListForm] ``` ![截屏2020-10-12 下午7 54 52](https://user-images.githubusercontent.com/60063723/95743785-de70f480-0cc4-11eb-857b-fffd3d7e9cdd.png) ![截屏2020-10-12 下午7 53 59](https://user-images.githubusercontent.com/60063723/95743805-e5980280-0cc4-11eb-99ae-11e6439bae02.png)
0b01001001/spectree
diff --git a/tests/common.py b/tests/common.py index 0f2d696..83b4140 100644 --- a/tests/common.py +++ b/tests/common.py @@ -1,7 +1,7 @@ from enum import IntEnum, Enum from typing import List -from pydantic import BaseModel, root_validator +from pydantic import BaseModel, root_validator, Field class Order(IntEnum): @@ -43,7 +43,7 @@ class Cookies(BaseModel): class DemoModel(BaseModel): uid: int limit: int - name: str + name: str = Field(..., description='user name') def get_paths(spec): diff --git a/tests/test_utils.py b/tests/test_utils.py index bf3426d..53dd3e1 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -98,8 +98,10 @@ def test_parse_params(): 'name': 'uid', 'in': 'query', 'required': True, + 'description': '', 'schema': { 'title': 'Uid', 'type': 'integer', } } + assert params[2]['description'] == 'user name'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[flask,falcon,starlette]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
annotated-types==0.7.0 anyio==4.9.0 blinker==1.9.0 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 exceptiongroup==1.2.2 falcon==4.0.2 Flask==3.1.0 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 itsdangerous==2.2.0 Jinja2==3.1.6 MarkupSafe==3.0.2 packaging==24.2 pluggy==1.5.0 pydantic==2.11.1 pydantic_core==2.33.0 pytest==8.3.5 requests==2.32.3 sniffio==1.3.1 -e git+https://github.com/0b01001001/spectree.git@a091fab020ac26548250c907bae0855273a98778#egg=spectree starlette==0.46.1 tomli==2.2.1 typing-inspection==0.4.0 typing_extensions==4.13.0 urllib3==2.3.0 Werkzeug==3.1.3 zipp==3.21.0
name: spectree channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - annotated-types==0.7.0 - anyio==4.9.0 - blinker==1.9.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - exceptiongroup==1.2.2 - falcon==4.0.2 - flask==3.1.0 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - itsdangerous==2.2.0 - jinja2==3.1.6 - markupsafe==3.0.2 - packaging==24.2 - pluggy==1.5.0 - pydantic==2.11.1 - pydantic-core==2.33.0 - pytest==8.3.5 - requests==2.32.3 - sniffio==1.3.1 - starlette==0.46.1 - tomli==2.2.1 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - urllib3==2.3.0 - werkzeug==3.1.3 - zipp==3.21.0 prefix: /opt/conda/envs/spectree
[ "tests/test_utils.py::test_parse_params" ]
[]
[ "tests/test_utils.py::test_comments", "tests/test_utils.py::test_parse_code", "tests/test_utils.py::test_parse_name", "tests/test_utils.py::test_has_model", "tests/test_utils.py::test_parse_resp", "tests/test_utils.py::test_parse_request" ]
[]
Apache License 2.0
swerebench/sweb.eval.x86_64.0b01001001_1776_spectree-64
swerebench/sweb.eval.x86_64.0b01001001_1776_spectree-64
12rambau__sepal_ui-347
4554f35da3fab21c32c35c4bd557ecfdec9c60c5
2021-11-19 12:32:22
114063b50ee5b1ccbab680424bb048e11939b870
diff --git a/sepal_ui/mapping/__init__.py b/sepal_ui/mapping/__init__.py index 7f72a0eb..aa84ddee 100644 --- a/sepal_ui/mapping/__init__.py +++ b/sepal_ui/mapping/__init__.py @@ -2,6 +2,7 @@ from .aoi_control import * from .draw_control import * from .fullscreen_control import * from .layer import * +from .layer_state_control import * from .map_btn import * from .sepal_map import * from .value_inspector import * diff --git a/sepal_ui/mapping/layer_state_control.py b/sepal_ui/mapping/layer_state_control.py new file mode 100644 index 00000000..eff80080 --- /dev/null +++ b/sepal_ui/mapping/layer_state_control.py @@ -0,0 +1,99 @@ +from traitlets import Int, observe +from ipyleaflet import WidgetControl + +from sepal_ui import sepalwidgets as sw +from sepal_ui.message import ms + + +class LayerStateControl(WidgetControl): + """ + A specific statebar dedicated to the the counting of loading tiles in the map + + every time a map is added to the map the counter will be raised by one. same behaviour with removed. + """ + + m = None + "SepalMap: the map connected to the control" + + w_state = None + "sw.StateBar: the stateBar displaying the number of layer loading on the map" + + nb_layer = Int(0).tag(sync=True) + "Int: the number of layers in the map" + + nb_loading_layer = Int(0).tag(sync=True) + "Int: the number of loading layer in the map" + + def __init__(self, m, **kwargs): + + # save the map as a member of the widget + self.m = m + + # create a statebar + msg = ms.layer_state.complete.format(self.nb_layer) + self.w_state = sw.StateBar(loading=False, msg=msg) + + # overwrite the widget set in the kwargs (if any) + kwargs["widget"] = self.w_state + kwargs["position"] = kwargs.pop("position", "topleft") + kwargs["transparent_bg"] = True + + # create the widget + super().__init__(**kwargs) + + # add js behaviour + self.m.observe(self.update_nb_layer, "layers") + + def update_nb_layer(self, change): + """ + Update the number of layer monitored by the statebar + """ + + # exit if nothing changed + # for example we change a layer parameters and it trigger this one + if len(change["new"]) == len(change["old"]): + return + + self.nb_layer = len([lyr for lyr in change["new"] if not lyr.base]) + + # identify the modified layer + modified_layer = list(set(change["new"]) ^ set(change["old"]))[0] + if modified_layer.base is True: + return + + # add a layer + if len(change["new"]) > len(change["old"]): + modified_layer.observe(self.update_loading, "loading") + + # remove a layer + elif len(change["new"]) < len(change["old"]): + # the test is splitted as not all the layers have a loading trait + if hasattr(modified_layer, "loading") is True: + if modified_layer.loading is True: + self.nb_loading_layer += -1 + + return + + def update_loading(self, change): + """update the nb_loading_layer value according to the number of tile loading on the map""" + + increment = [-1, 1] + self.nb_loading_layer += increment[change["new"]] + + return + + @observe("nb_loading_layer", "nb_layer") + def _update_state(self, change): + + # check if anything is loading + self.loading = bool(self.nb_loading_layer) + + # update the message + if self.loading is True: + msg = ms.layer_state.loading.format(self.nb_loading_layer, self.nb_layer) + else: + msg = ms.layer_state.complete.format(self.nb_layer) + + self.w_state.msg = msg + + return diff --git a/sepal_ui/mapping/sepal_map.py b/sepal_ui/mapping/sepal_map.py index e2860daf..4ef41d1a 100644 --- a/sepal_ui/mapping/sepal_map.py +++ b/sepal_ui/mapping/sepal_map.py @@ -31,6 +31,7 @@ import sepal_ui.frontend.styles as styles from sepal_ui.mapping.basemaps import basemap_tiles from sepal_ui.mapping.draw_control import DrawControl from sepal_ui.mapping.layer import EELayer +from sepal_ui.mapping.layer_state_control import LayerStateControl from sepal_ui.mapping.value_inspector import ValueInspector from sepal_ui.message import ms from sepal_ui.scripts import utils as su @@ -55,6 +56,7 @@ class SepalMap(ipl.Map): dc (bool, optional): wether or not the drawing control should be displayed. default to false vinspector (bool, optional): Add value inspector to map, useful to inspect pixel values. default to false gee (bool, optional): wether or not to use the ee binding. If False none of the earthengine display fonctionalities can be used. default to True + statebar (bool): wether or not to display the Statebar in the map kwargs (optional): any parameter from a ipyleaflet.Map. if set, 'ee_initialize' will be overwritten. """ @@ -74,7 +76,18 @@ class SepalMap(ipl.Map): _id = None "str: a unique 6 letters str to identify the map in the DOM" - def __init__(self, basemaps=[], dc=False, vinspector=False, gee=True, **kwargs): + state = None + "sw.StateBar: the statebar to inform the user about tile loading" + + def __init__( + self, + basemaps=[], + dc=False, + vinspector=False, + gee=True, + statebar=False, + **kwargs, + ): # set the default parameters kwargs["center"] = kwargs.pop("center", [0, 0]) @@ -114,6 +127,10 @@ class SepalMap(ipl.Map): self.v_inspector = ValueInspector(self) not vinspector or self.add_control(self.v_inspector) + # specific statebar + self.state = LayerStateControl(self) + not statebar or self.add_control(self.state) + # create a proxy ID to the element # this id should be unique and will be used by mutators to identify this map self._id = "".join(random.choice(string.ascii_lowercase) for i in range(6)) diff --git a/sepal_ui/message/en/layer_control.json b/sepal_ui/message/en/layer_control.json new file mode 100644 index 00000000..2f90d41c --- /dev/null +++ b/sepal_ui/message/en/layer_control.json @@ -0,0 +1,6 @@ +{ + "layer_state": { + "loading": "loading {} layer(s) out of {}", + "complete": "{} layer(s) loaded" + } +} \ No newline at end of file diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py index e143170e..6ad4d5d0 100644 --- a/sepal_ui/sepalwidgets/alert.py +++ b/sepal_ui/sepalwidgets/alert.py @@ -250,7 +250,7 @@ class Alert(v.Alert, SepalWidget): return su.check_input(input_, msg) -class StateBar(v.SystemBar): +class StateBar(v.SystemBar, SepalWidget): """Widget to display quick messages on simple inline status bar
display a loading statebar when a layer is loading in the map ## issue I experienced some issues with the FCDM module as the map is super slow to load (it uses a adaptative buffer, the more you zoom the slower it gets it's a nightmare). The consequence is that the user clicks frantically on the `zoom` `unzoom` btn and the layer never fully loads and they eventually break the app. I've looked into the loading widgets that exists in ipyleaflet and that's not very elegant (from my perspective). ## current implementation I came up with the idea of overwriting the `add_layer` method to add a `StateBar` at the top left corner for every layer and dynamically show them when the tile are reloading. overwritting the `add_layer` method is super versatile as it's the basic function called by all the others (`add_ee_layer`, `addLayer`, `add_raster_layer` ... etc). - user doesn't change anything in the way object are added to the map - each time you add a layer, it adds a statebar writting "loading \<whatever\>" - the statebare is shown whenever the layer is loading (thank you traitlets) ## questions - should we remove them when the layer is removed (overwritting remove_layer as well) ? - should the statebar always be displayed (and instead of changing viz, we could change loading trait) ? - do you think it could be useful in general ? ## demo Here is a gif demo and the the code I used. ![feature_demo](https://user-images.githubusercontent.com/12596392/142245503-4b78f635-9700-468c-9202-fa04a13de4b8.gif) ```python from sepal_ui.mapping import SepalMap from sepal_ui import sepalwidgets as sw from ipyleaflet import WidgetControl import ee ee.Initialize() # create a custom statebar class StateBar(sw.StateBar): def __init__(self, **kwargs): name = kwargs.pop("layer", "layer") kwargs["_metadata"] = {"layer": name} super().__init__(**kwargs) self.msg = f"Loading {name}" self.loading = True def activate(self, change): if change['new']: self.show() else: self.hide() return # define a custom Map class class Map(SepalMap): layer_state_list = [] def add_layer(self, l): # call the original function super().add_layer(l) # add a layer state object state = StateBar(layer=l.name) self.layer_state_list += [state] self.add_control(WidgetControl(widget=state, position='topleft')) # link it to the layer state #layer = next(l for l in self.layers if l.name == name) l.observe(state.activate, "loading") return # create the map and zoom on congo test_map = Map() test_map.zoom = 10 test_map.center = [5.703447982149503, 28.32275390625] # load hansen & al ddataset dataset = ee.Image('UMD/hansen/global_forest_change_2020_v1_8') treeCoverVisParam = { "bands": ['treecover2000'], "min": 0, "max": 100, "palette": ['black', 'green'] } test_map.addLayer(dataset, treeCoverVisParam, 'tree cover') # load the S2 RGB product (SR) def maskS2clouds(image): qa = image.select('QA60'); # Bits 10 and 11 are clouds and cirrus, respectively. cloudBitMask = 1 << 10; cirrusBitMask = 1 << 11; # Both flags should be set to zero, indicating clear conditions. mask = ( qa .bitwiseAnd(cloudBitMask).eq(0) .And(qa.bitwiseAnd(cirrusBitMask).eq(0)) ) return image.updateMask(mask).divide(10000) dataset = ( ee.ImageCollection('COPERNICUS/S2_SR') .filterDate('2020-01-01', '2020-01-30') .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',20)) .map(maskS2clouds) ) visualization = { "min": 0.0, "max": 0.3, "bands": ['B4', 'B3', 'B2'], } test_map.addLayer(dataset.mean(), visualization, 'RGB') # display the map test_map ```
12rambau/sepal_ui
diff --git a/tests/test_LayerStateControl.py b/tests/test_LayerStateControl.py new file mode 100644 index 00000000..ce2aecb2 --- /dev/null +++ b/tests/test_LayerStateControl.py @@ -0,0 +1,84 @@ +from ipyleaflet import RasterLayer +from traitlets import Bool +import ee +import pytest + +from sepal_ui import mapping as sm +from sepal_ui.scripts import utils as su + + +class TestLayerStateControl: + def test_init(self): + + m = sm.SepalMap() + state = sm.LayerStateControl(m) + m.add_control(state) + + assert isinstance(state, sm.LayerStateControl) + assert state.w_state.loading is False + + return + + @su.need_ee + def test_update_nb_layer(self, map_with_layers): + + # create the map and controls + m = map_with_layers + state = next(c for c in m.controls if isinstance(c, sm.LayerStateControl)) + + # TODO I don't know how to check state changes but I can at least check the conclusion + assert state.w_state.msg == "2 layer(s) loaded" + + # remove a layer to update the nb_layer + m.remove_layer(-1) + assert state.w_state.msg == "1 layer(s) loaded" + + return + + def test_update_loading(self, map_with_layers): + + # get the map and control + m = map_with_layers + state = next(c for c in m.controls if isinstance(c, sm.LayerStateControl)) + + # check that the parameter is updated with existing layers + m.layers[-1].loading = True + assert state.nb_loading_layer == 1 + assert state.w_state.msg == "loading 1 layer(s) out of 2" + + # check when this loading layer is removed + m.remove_layer(-1) + assert state.nb_loading_layer == 0 + assert state.w_state.msg == "1 layer(s) loaded" + + return + + @pytest.fixture + def map_with_layers(self, fake_layer): + """create a map with 2 layers and a stateBar""" + + # create the map and controls + m = sm.SepalMap() + state = sm.LayerStateControl(m) + m.add_control(state) + + # add some ee_layer (loading very fast) + # world lights + dataset = ee.ImageCollection("NOAA/DMSP-OLS/CALIBRATED_LIGHTS_V4").filter( + ee.Filter.date("2010-01-01", "2010-12-31") + ) + m.addLayer(dataset, {}, "Nighttime Lights") + + # a fake layer with loading update possibilities + m.add_layer(fake_layer) + + return m + + @pytest.fixture + def fake_layer(self): + """create a layer from a fakelayer class that have only one parameter: the laoding trait""" + + class FakeLayer(RasterLayer): + loading = Bool(False).tag(sync=True) + + return FakeLayer() diff --git a/tests/test_SepalMap.py b/tests/test_SepalMap.py index 51f5a01a..30a0d3eb 100644 --- a/tests/test_SepalMap.py +++ b/tests/test_SepalMap.py @@ -51,6 +51,10 @@ class TestSepalMap: m = sm.SepalMap(vinspector=True) assert m.v_inspector in m.controls + # check that the map start with a statebar + m = sm.SepalMap(statebar=True) + assert m.state in m.controls + # check that a wrong layer raise an error if it's not part of the leaflet basemap list with pytest.raises(Exception): m = sm.SepalMap(["TOTO"]) diff --git a/tests/test_StateBar.py b/tests/test_StateBar.py index 9eb3ab0f..0ed4ed5c 100644 --- a/tests/test_StateBar.py +++ b/tests/test_StateBar.py @@ -7,6 +7,7 @@ class TestStateBar: # minimal state bar state_bar = sw.StateBar() assert len(state_bar.children) == 2 + assert state_bar.viz is True return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 3 }
2.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 fsspec==2025.3.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipyleaflet==0.19.2 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==1.5.2 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-futures==0.9.9 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@4554f35da3fab21c32c35c4bd557ecfdec9c60c5#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 xyzservices==2025.1.0 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - fsspec==2025.3.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==1.5.2 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-futures==0.9.9 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - xyzservices==2025.1.0 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_StateBar.py::TestStateBar::test_init" ]
[ "tests/test_LayerStateControl.py::TestLayerStateControl::test_init", "tests/test_SepalMap.py::TestSepalMap::test_init", "tests/test_SepalMap.py::TestSepalMap::test_set_center", "tests/test_SepalMap.py::TestSepalMap::test_zoom_bounds", "tests/test_SepalMap.py::TestSepalMap::test_add_colorbar", "tests/test_SepalMap.py::TestSepalMap::test_add_ee_layer", "tests/test_SepalMap.py::TestSepalMap::test_get_basemap_list", "tests/test_SepalMap.py::TestSepalMap::test_get_viz_params", "tests/test_SepalMap.py::TestSepalMap::test_add_layer", "tests/test_SepalMap.py::TestSepalMap::test_add_basemap", "tests/test_SepalMap.py::TestSepalMap::test_get_scale", "tests/test_SepalMap.py::TestSepalMap::test_zoom_raster" ]
[ "tests/test_StateBar.py::TestStateBar::test_add_msg" ]
[]
MIT License
null
null
12rambau__sepal_ui-411
179bd8d089275c54e94a7614be7ed03d298ef532
2022-02-28 17:46:40
97371fbaed444727126a2969cd68f856db77221f
diff --git a/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst b/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst index 1a982afb..867227cb 100644 --- a/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst +++ b/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst @@ -8,6 +8,7 @@ sepal\_ui.sepalwidgets.DatePicker .. autosummary:: ~DatePicker.menu + ~DatePicker.disabled .. rubric:: Methods @@ -15,5 +16,8 @@ sepal\_ui.sepalwidgets.DatePicker :nosignatures: ~Datepicker.close_menu + ~DatePicker.disable -.. automethod:: sepal_ui.sepalwidgets.DatePicker.close_menu \ No newline at end of file +.. automethod:: sepal_ui.sepalwidgets.DatePicker.close_menu + +.. automethod:: sepal_ui.sepalwidgets.DatePicker.disable \ No newline at end of file diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 3ad7f1a9..68b81746 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -1,7 +1,7 @@ from pathlib import Path import ipyvuetify as v -from traitlets import link, Int, Any, List, observe, Dict, Unicode +from traitlets import link, Int, Any, List, observe, Dict, Unicode, Bool from ipywidgets import jslink import pandas as pd import ee @@ -40,6 +40,9 @@ class DatePicker(v.Layout, SepalWidget): menu = None "v.Menu: the menu widget to display the datepicker" + disabled = Bool(False).tag(sync=True) + "traitlets.Bool: the disabled status of the Datepicker object" + def __init__(self, label="Date", **kwargs): # create the widgets @@ -93,6 +96,14 @@ class DatePicker(v.Layout, SepalWidget): return + @observe("disabled") + def disable(self, change): + """A method to disabled the appropriate components in the datipkcer object""" + + self.menu.v_slots[0]["children"].disabled = self.disabled + + return + class FileInput(v.Flex, SepalWidget): """
add a disabled trait on the datepicker I'm currently coding it in a module and the process of disabling a datepicker is uterly boring. I think we could add an extra trait to the layout and pilot the enabling and disabling directly from the built-in widget ```python self.w_start = sw.DatePicker(label="start", v_model=None) # disable both the slots (hidden to everyone) and the menu self.w_start.menu.v_slots[0]["children"].disabled = True self.w_start.menu.disabled = True ```
12rambau/sepal_ui
diff --git a/tests/test_DatePicker.py b/tests/test_DatePicker.py index f4c6d40e..e5f5d06f 100644 --- a/tests/test_DatePicker.py +++ b/tests/test_DatePicker.py @@ -35,6 +35,14 @@ class TestDatePicker: return + def test_disable(self, datepicker): + + for boolean in [True, False]: + datepicker.disabled = boolean + assert datepicker.menu.v_slots[0]["children"].disabled == boolean + + return + @pytest.fixture def datepicker(self): """create a default datepicker"""
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
2.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 bqplot==0.12.44 branca==0.4.2 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 colorama==0.4.6 colour==0.1.5 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 EditorConfig==0.17.0 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 ffmpeg-python==0.2.0 filelock==3.18.0 folium==0.13.0 fonttools==4.56.0 fqdn==1.5.1 future==1.0.0 geeadd==1.2.1 geemap==0.8.9 geocoder==1.38.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipyevents==2.0.2 ipyfilechooser==0.6.0 ipykernel==6.29.5 ipyleaflet==0.13.3 ipynb-py-convert==0.4.6 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipytree==0.2.2 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsbeautifier==1.15.4 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 logzero==1.7.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 mss==10.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyCRS==1.0.2 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pyshp==2.3.1 pytest==8.3.5 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 ratelim==0.1.6 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@179bd8d089275c54e94a7614be7ed03d298ef532#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 whitebox==2.3.6 whiteboxgui==2.3.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - bqplot==0.12.44 - branca==0.4.2 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - colorama==0.4.6 - colour==0.1.5 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - editorconfig==0.17.0 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - ffmpeg-python==0.2.0 - filelock==3.18.0 - folium==0.13.0 - fonttools==4.56.0 - fqdn==1.5.1 - future==1.0.0 - geeadd==1.2.1 - geemap==0.8.9 - geocoder==1.38.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipyevents==2.0.2 - ipyfilechooser==0.6.0 - ipykernel==6.29.5 - ipyleaflet==0.13.3 - ipynb-py-convert==0.4.6 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipytree==0.2.2 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsbeautifier==1.15.4 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - logzero==1.7.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - mss==10.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pycrs==1.0.2 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pyshp==2.3.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - ratelim==0.1.6 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - whitebox==2.3.6 - whiteboxgui==2.3.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_DatePicker.py::TestDatePicker::test_disable" ]
[]
[ "tests/test_DatePicker.py::TestDatePicker::test_init", "tests/test_DatePicker.py::TestDatePicker::test_bind" ]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-411
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-411
12rambau__sepal_ui-416
8b76805db051d6d15024bd9ec2d78502cd92132e
2022-03-11 19:47:50
97371fbaed444727126a2969cd68f856db77221f
diff --git a/docs/source/modules/sepal_ui.sepalwidgets.DrawerItem.rst b/docs/source/modules/sepal_ui.sepalwidgets.DrawerItem.rst index a3280cd3..22b87b44 100644 --- a/docs/source/modules/sepal_ui.sepalwidgets.DrawerItem.rst +++ b/docs/source/modules/sepal_ui.sepalwidgets.DrawerItem.rst @@ -7,7 +7,9 @@ sepal\_ui.sepalwidgets.DrawerItem .. autosummary:: - ~DrawerItem.rt + ~DrawerItem.rt + ~DrawerItem.alert + ~DrawerItem.alert_badge .. rubric:: Methods @@ -15,5 +17,11 @@ sepal\_ui.sepalwidgets.DrawerItem :nosignatures: ~DrawerItem.display_tile + ~DrawerItem.add_notif + ~DrawerItem.remove_notif -.. automethod:: sepal_ui.sepalwidgets.DrawerItem.display_tile \ No newline at end of file +.. automethod:: sepal_ui.sepalwidgets.DrawerItem.display_tile + +.. automethod:: sepal_ui.sepalwidgets.DrawerItem.add_notif + +.. automethod:: sepal_ui.sepalwidgets.DrawerItem.remove_notif \ No newline at end of file diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py index a1aff843..2a87de83 100644 --- a/sepal_ui/sepalwidgets/app.py +++ b/sepal_ui/sepalwidgets/app.py @@ -1,3 +1,4 @@ +from traitlets import link, Bool, observe from functools import partial from datetime import datetime @@ -73,12 +74,29 @@ class DrawerItem(v.ListItem, SepalWidget): card (str, optional): the mount_id of tiles in the app href (str, optional): the absolute link to an external web page kwargs (optional): any parameter from a v.ListItem. If set, '_metadata', 'target', 'link' and 'children' will be overwritten. + model (optional): sepalwidget model where is defined the bin_var trait + bind_var (optional): required when model is selected. Trait to link with 'alert' self trait parameter """ rt = None "sw.ResizeTrigger: the trigger to resize maps and other javascript object when jumping from a tile to another" - def __init__(self, title, icon=None, card=None, href=None, **kwargs): + alert = Bool(False).tag(sync=True) + "Bool: trait to control visibility of an alert in the drawer item" + + alert_badge = None + "v.ListItemAction: red circle to display in the drawer" + + def __init__( + self, + title, + icon=None, + card=None, + href=None, + model=None, + bind_var=None, + **kwargs + ): # set the resizetrigger self.rt = js.rt @@ -108,6 +126,45 @@ class DrawerItem(v.ListItem, SepalWidget): # call the constructor super().__init__(**kwargs) + # cannot be set as a class member because it will be shared with all + # the other draweritems. + self.alert_badge = v.ListItemAction( + children=[v.Icon(children=["fas fa-circle"], x_small=True, color="red")] + ) + + if model: + if not bind_var: + raise Exception( + "You have selected a model, you need a trait to bind with drawer." + ) + + link((model, bind_var), (self, "alert")) + + @observe("alert") + def add_notif(self, change): + """Add a notification alert to drawer""" + + if change["new"]: + if self.alert_badge not in self.children: + new_children = self.children[:] + new_children.append(self.alert_badge) + self.children = new_children + else: + self.remove_notif() + + return + + def remove_notif(self): + """Remove notification alert""" + + if self.alert_badge in self.children: + new_children = self.children[:] + new_children.remove(self.alert_badge) + + self.children = new_children + + return + def display_tile(self, tiles): """ Display the apropriate tiles when the item is clicked. @@ -138,6 +195,9 @@ class DrawerItem(v.ListItem, SepalWidget): # change the current item status self.input_value = True + # Remove notification + self.remove_notif() + return self
Interact with navigation drawers Sometimes is useful to pass some data from the module model to the app environment and so far we do not have this implementation. We can add two simple methods to the drawers so they can update their state with icons, badges, and so.
12rambau/sepal_ui
diff --git a/tests/test_DrawerItem.py b/tests/test_DrawerItem.py index ad26c3a2..0e80ffc9 100644 --- a/tests/test_DrawerItem.py +++ b/tests/test_DrawerItem.py @@ -1,3 +1,6 @@ +import pytest +from sepal_ui.model import Model +from traitlets import Bool import ipyvuetify as v from sepal_ui import sepalwidgets as sw @@ -60,3 +63,32 @@ class TestDrawerItem: assert tile.viz is False return + + @pytest.fixture + def model(self): + class TestModel(Model): + app_ready = Bool(False).tag(sync=True) + + return TestModel() + + def test_add_notif(self, model): + + drawer_item = sw.DrawerItem("title", model=model, bind_var="app_ready") + + model.app_ready = True + + assert drawer_item.alert_badge in drawer_item.children + + model.app_ready = False + + assert drawer_item.alert_badge not in drawer_item.children + + def test_remove_notif(self, model): + + drawer_item = sw.DrawerItem("title", model=model, bind_var="app_ready") + + model.app_ready = True + + drawer_item.remove_notif() + + assert drawer_item.alert_badge not in drawer_item.children
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
2.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 bqplot==0.12.44 branca==0.4.2 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 colorama==0.4.6 colour==0.1.5 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 EditorConfig==0.17.0 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 ffmpeg-python==0.2.0 filelock==3.18.0 folium==0.13.0 fonttools==4.56.0 fqdn==1.5.1 future==1.0.0 geeadd==1.2.1 geemap==0.8.9 geocoder==1.38.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipyevents==2.0.2 ipyfilechooser==0.6.0 ipykernel==6.29.5 ipyleaflet==0.13.3 ipynb-py-convert==0.4.6 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipytree==0.2.2 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsbeautifier==1.15.4 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 logzero==1.7.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 mss==10.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyCRS==1.0.2 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pyshp==2.3.1 pytest==8.3.5 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 ratelim==0.1.6 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@8b76805db051d6d15024bd9ec2d78502cd92132e#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 whitebox==2.3.6 whiteboxgui==2.3.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - bqplot==0.12.44 - branca==0.4.2 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - colorama==0.4.6 - colour==0.1.5 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - editorconfig==0.17.0 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - ffmpeg-python==0.2.0 - filelock==3.18.0 - folium==0.13.0 - fonttools==4.56.0 - fqdn==1.5.1 - future==1.0.0 - geeadd==1.2.1 - geemap==0.8.9 - geocoder==1.38.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipyevents==2.0.2 - ipyfilechooser==0.6.0 - ipykernel==6.29.5 - ipyleaflet==0.13.3 - ipynb-py-convert==0.4.6 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipytree==0.2.2 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsbeautifier==1.15.4 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - logzero==1.7.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - mss==10.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pycrs==1.0.2 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pyshp==2.3.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - ratelim==0.1.6 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - whitebox==2.3.6 - whiteboxgui==2.3.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_DrawerItem.py::TestDrawerItem::test_add_notif", "tests/test_DrawerItem.py::TestDrawerItem::test_remove_notif" ]
[]
[ "tests/test_DrawerItem.py::TestDrawerItem::test_init_cards", "tests/test_DrawerItem.py::TestDrawerItem::test_display_tile" ]
[]
MIT License
null
null
12rambau__sepal_ui-418
8b76805db051d6d15024bd9ec2d78502cd92132e
2022-03-14 14:24:04
97371fbaed444727126a2969cd68f856db77221f
diff --git a/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst b/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst index 867227cb..322cca23 100644 --- a/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst +++ b/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst @@ -9,6 +9,7 @@ sepal\_ui.sepalwidgets.DatePicker ~DatePicker.menu ~DatePicker.disabled + ~DatePicker.date_text .. rubric:: Methods @@ -17,7 +18,13 @@ sepal\_ui.sepalwidgets.DatePicker ~Datepicker.close_menu ~DatePicker.disable + ~DatePicker.is_valid_date + ~DatePicker.check_date .. automethod:: sepal_ui.sepalwidgets.DatePicker.close_menu -.. automethod:: sepal_ui.sepalwidgets.DatePicker.disable \ No newline at end of file +.. automethod:: sepal_ui.sepalwidgets.DatePicker.disable + +.. automethod:: sepal_ui.sepalwidgets.DatePicker.check_date + +.. autofunction:: sepal_ui.sepalwidgets.DatePicker.disable \ No newline at end of file diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 7d003229..bf1adf0b 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -1,4 +1,5 @@ from pathlib import Path +from datetime import datetime import ipyvuetify as v from traitlets import link, Int, Any, List, observe, Dict, Unicode, Bool @@ -40,6 +41,9 @@ class DatePicker(v.Layout, SepalWidget): menu = None "v.Menu: the menu widget to display the datepicker" + date_text = None + "v.TextField: the text field of the datepicker widget" + disabled = Bool(False).tag(sync=True) "traitlets.Bool: the disabled status of the Datepicker object" @@ -48,7 +52,7 @@ class DatePicker(v.Layout, SepalWidget): # create the widgets date_picker = v.DatePicker(no_title=True, v_model=None, scrollable=True) - date_text = v.TextField( + self.date_text = v.TextField( v_model=None, label=label, hint="YYYY-MM-DD format", @@ -69,7 +73,7 @@ class DatePicker(v.Layout, SepalWidget): { "name": "activator", "variable": "menuData", - "children": date_text, + "children": self.date_text, } ], ) @@ -84,8 +88,28 @@ class DatePicker(v.Layout, SepalWidget): # call the constructor super().__init__(**kwargs) - jslink((date_picker, "v_model"), (date_text, "v_model")) - jslink((date_picker, "v_model"), (self, "v_model")) + jslink((date_picker, "v_model"), (self.date_text, "v_model")) + jslink((self, "v_model"), (date_picker, "v_model")) + + @observe("v_model") + def check_date(self, change): + """ + A method to check if the value of the set v_model is a correctly formated date + Reset the widget and display an error if it's not the case + """ + + self.date_text.error_messages = None + + # exit immediately if nothing is set + if change["new"] is None: + return + + # change the error status + if not self.is_valid_date(change["new"]): + msg = self.date_text.hint + self.date_text.error_messages = msg + + return @observe("v_model") def close_menu(self, change): @@ -104,6 +128,27 @@ class DatePicker(v.Layout, SepalWidget): return + @staticmethod + def is_valid_date(date): + """ + Check if the date is provided using the date format required for the widget + + Args: + date (str): the date to test in YYYY-MM-DD format + + Return: + (bool): the date to test + """ + + try: + date = datetime.strptime(date, "%Y-%m-%d") + valid = True + + except Exception: + valid = False + + return valid + class FileInput(v.Flex, SepalWidget): """
Can't instantiate a sw.DatePicker with initial v_model Is not possible to instantiate the sepal DatePicker with an initially given date through the `v_model` parameter
12rambau/sepal_ui
diff --git a/tests/test_DatePicker.py b/tests/test_DatePicker.py index e5f5d06f..48993736 100644 --- a/tests/test_DatePicker.py +++ b/tests/test_DatePicker.py @@ -17,6 +17,11 @@ class TestDatePicker: datepicker = sw.DatePicker("toto") assert isinstance(datepicker, sw.DatePicker) + # datepicker with default value + value = "2022-03-14" + datepicker = sw.DatePicker(v_model=value) + assert datepicker.v_model == value + return def test_bind(self, datepicker): @@ -43,6 +48,34 @@ class TestDatePicker: return + def test_is_valid_date(self, datepicker): + + # a nicely shaped date + test = "2022-03-14" + assert datepicker.is_valid_date(test) is True + + # a badly shaped date + test = "2022-50-14" + assert datepicker.is_valid_date(test) is False + + return + + def test_check_date(self, datepicker): + + # manually update the value with a badely shaped date + test = "2022-50-14" + datepicker.v_model = test + assert datepicker.v_model == test + assert datepicker.date_text.error_messages is not None + + # manually update the value with a nicely shaped date + test = "2022-03-14" + datepicker.v_model = test + assert datepicker.v_model == test + assert datepicker.date_text.error_messages is None + + return + @pytest.fixture def datepicker(self): """create a default datepicker"""
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
2.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 bqplot==0.12.44 branca==0.4.2 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 colorama==0.4.6 colour==0.1.5 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 EditorConfig==0.17.0 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 ffmpeg-python==0.2.0 filelock==3.18.0 folium==0.13.0 fonttools==4.56.0 fqdn==1.5.1 future==1.0.0 geeadd==1.2.1 geemap==0.8.9 geocoder==1.38.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipyevents==2.0.2 ipyfilechooser==0.6.0 ipykernel==6.29.5 ipyleaflet==0.13.3 ipynb-py-convert==0.4.6 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipytree==0.2.2 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsbeautifier==1.15.4 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 logzero==1.7.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 mss==10.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyCRS==1.0.2 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pyshp==2.3.1 pytest==8.3.5 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 ratelim==0.1.6 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@8b76805db051d6d15024bd9ec2d78502cd92132e#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 whitebox==2.3.6 whiteboxgui==2.3.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - bqplot==0.12.44 - branca==0.4.2 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - colorama==0.4.6 - colour==0.1.5 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - editorconfig==0.17.0 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - ffmpeg-python==0.2.0 - filelock==3.18.0 - folium==0.13.0 - fonttools==4.56.0 - fqdn==1.5.1 - future==1.0.0 - geeadd==1.2.1 - geemap==0.8.9 - geocoder==1.38.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipyevents==2.0.2 - ipyfilechooser==0.6.0 - ipykernel==6.29.5 - ipyleaflet==0.13.3 - ipynb-py-convert==0.4.6 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipytree==0.2.2 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsbeautifier==1.15.4 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - logzero==1.7.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - mss==10.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pycrs==1.0.2 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pyshp==2.3.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - ratelim==0.1.6 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - whitebox==2.3.6 - whiteboxgui==2.3.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_DatePicker.py::TestDatePicker::test_is_valid_date", "tests/test_DatePicker.py::TestDatePicker::test_check_date" ]
[]
[ "tests/test_DatePicker.py::TestDatePicker::test_init", "tests/test_DatePicker.py::TestDatePicker::test_bind", "tests/test_DatePicker.py::TestDatePicker::test_disable" ]
[]
MIT License
null
null
12rambau__sepal_ui-419
97371fbaed444727126a2969cd68f856db77221f
2022-03-15 11:14:02
97371fbaed444727126a2969cd68f856db77221f
diff --git a/docs/source/modules/sepal_ui.rst b/docs/source/modules/sepal_ui.rst index 366a3fb2..2650327b 100644 --- a/docs/source/modules/sepal_ui.rst +++ b/docs/source/modules/sepal_ui.rst @@ -24,3 +24,11 @@ Content sepal_ui.theme sepal_ui.color sepal_ui.config_file + +.. rubric:: Attributes + +.. autosummary:: + + sepal_ui.get_theme + +.. autofunction:: sepal_ui.get_theme diff --git a/docs/source/modules/sepal_ui.scripts.utils.rst b/docs/source/modules/sepal_ui.scripts.utils.rst index d4a30a14..6c404e8a 100644 --- a/docs/source/modules/sepal_ui.scripts.utils.rst +++ b/docs/source/modules/sepal_ui.scripts.utils.rst @@ -23,6 +23,7 @@ sepal\_ui.scripts.utils switch to_colors set_config_locale + set_config_theme .. autofunction:: sepal_ui.scripts.utils.catch_errors @@ -54,6 +55,8 @@ sepal\_ui.scripts.utils .. autofunction:: sepal_ui.scripts.utils.set_config_locale +.. autofunction:: sepal_ui.scripts.utils.set_config_theme + diff --git a/docs/source/modules/sepal_ui.sepalwidgets.AppBar.rst b/docs/source/modules/sepal_ui.sepalwidgets.AppBar.rst index 3787c444..011eae2b 100644 --- a/docs/source/modules/sepal_ui.sepalwidgets.AppBar.rst +++ b/docs/source/modules/sepal_ui.sepalwidgets.AppBar.rst @@ -10,6 +10,7 @@ sepal\_ui.sepalwidgets.AppBar ~AppBar.toogle_button ~AppBar.title ~AppBar.locale + ~AppBar.theme .. rubric:: Methods diff --git a/docs/source/modules/sepal_ui.sepalwidgets.ThemeSelect.rst b/docs/source/modules/sepal_ui.sepalwidgets.ThemeSelect.rst new file mode 100644 index 00000000..5c4e14d0 --- /dev/null +++ b/docs/source/modules/sepal_ui.sepalwidgets.ThemeSelect.rst @@ -0,0 +1,21 @@ +sepal\_ui.sepalwidgets.ThemeSelect +================================== + +.. autoclass:: sepal_ui.sepalwidgets.ThemeSelect + + .. rubric:: Attributes + + .. autosummary:: + + ~ThemeSelect.THEME_ICONS + ~ThemeSelect.theme + + .. rubric:: Methods + + .. autosummary:: + :nosignatures: + + ~ThemeSelect.toggle_theme + +.. automethod:: sepal_ui.sepalwidgets.ThemeSelect.toggle_theme + \ No newline at end of file diff --git a/docs/source/modules/sepal_ui.sepalwidgets.rst b/docs/source/modules/sepal_ui.sepalwidgets.rst index b1bc9ef1..9d0c6864 100644 --- a/docs/source/modules/sepal_ui.sepalwidgets.rst +++ b/docs/source/modules/sepal_ui.sepalwidgets.rst @@ -33,3 +33,4 @@ sepal\_ui.sepalwidgets sepal_ui.sepalwidgets.Tooltip sepal_ui.sepalwidgets.VectorField sepal_ui.sepalwidgets.LocaleSelect + sepal_ui.sepalwidgets.ThemeSelect diff --git a/sepal_ui/__init__.py b/sepal_ui/__init__.py index 69eccad6..bf79e175 100644 --- a/sepal_ui/__init__.py +++ b/sepal_ui/__init__.py @@ -1,18 +1,49 @@ +from types import SimpleNamespace +from pathlib import Path +from configparser import ConfigParser + +import ipyvuetify as v + +from sepal_ui.frontend import styles + __author__ = """Pierrick Rambaud""" __email__ = "pierrick.rambaud49@gmail.com" __version__ = "2.6.2" -# direct access to colors -from sepal_ui.frontend import styles -import ipyvuetify as v -from types import SimpleNamespace -from pathlib import Path -theme = v.theme.themes.dark if v.theme.dark else v.theme.themes.light +def get_theme(config_file): + """ + get the theme from the config file (default to dark) + + Return: + (str): the theme to use + """ + + # init theme + theme = "dark" + + # read the config file if existing + if config_file.is_file(): + config = ConfigParser() + config.read(config_file) + theme = config.get("sepal-ui", "theme", fallback="dark") + + # set vuetify theme + v.theme.dark = True if theme == "dark" else False + + return theme + + +config_file = Path.home() / ".sepal-ui-config" +"Pathlib.Path: the configuration file generated by sepal-ui based application to save parameters as language or theme" + +theme = getattr(v.theme.themes, get_theme(config_file)) "traitlets: the theme used in sepal" color = SimpleNamespace( - bg=styles.bg_color, + main=theme.main, + darker=theme.darker, + bg=theme.bg_color, primary=theme.primary, accent=theme.accent, secondary=theme.secondary, @@ -20,8 +51,6 @@ color = SimpleNamespace( info=theme.info, warning=theme.warning, error=theme.error, + menu=theme.menu, ) -'SimpleNamespace: the colors of sepal. members are in the following list: "bg, primary, accent, secondary, success, info, warning, error". They will render according to the selected theme.' - -config_file = Path.home() / ".sepal-ui-config" -"Pathlib.Path: the configuration file generated by sepal-ui based application to save parameters as language or theme" +'SimpleNamespace: the colors of sepal. members are in the following list: "main, darker, bg, primary, accent, secondary, success, info, warning, error, menu". They will render according to the selected theme.' diff --git a/sepal_ui/aoi/aoi_model.py b/sepal_ui/aoi/aoi_model.py index d713e7b9..0ecfdd74 100644 --- a/sepal_ui/aoi/aoi_model.py +++ b/sepal_ui/aoi/aoi_model.py @@ -10,6 +10,7 @@ from ipyleaflet import GeoJSON import geemap import ee +from sepal_ui import color from sepal_ui.frontend.styles import AOI_STYLE from sepal_ui.scripts import utils as su from sepal_ui.scripts import gee @@ -626,9 +627,12 @@ class AoiModel(Model): for f in data["features"]: f["properties"]["name"] = self.name + # adapt the style to the theme + style = {**AOI_STYLE, "color": color.success, "fillColor": color.success} + # create a GeoJSON object self.ipygeojson = GeoJSON( - data=data, style=AOI_STYLE, name="aoi", attribution="SEPA(c)" + data=data, style=style, name="aoi", attribution="SEPAL(c)" ) return self.ipygeojson diff --git a/sepal_ui/bin/module_theme b/sepal_ui/bin/module_theme new file mode 100755 index 00000000..8d153333 --- /dev/null +++ b/sepal_ui/bin/module_theme @@ -0,0 +1,55 @@ +#!/usr/bin/python3 + +from colorama import init, Fore, Style + +from sepal_ui.scripts import utils as su + +# init colors for all plateforms +init() + + +def check_theme(theme): + """ + Check if the theme is a legit name + + Return: + (bool) + """ + + themes = ["dark", "light"] + + return theme in themes + + +if __name__ == "__main__": + + # welcome the user + print(Fore.YELLOW) + print("##########################################") + print("# #") + print("# SEPAL MODULE THEMING TOOL #") + print("# #") + print("##########################################") + print(Fore.RESET) + print(f"Welcome in the {Style.BRIGHT}module theming{Style.NORMAL} interface.") + + # select a language + is_theme = False + while is_theme is False: + + theme = input(f"{Fore.CYAN}Provide a theme name: \n{Fore.RESET}") + is_theme = check_theme(theme) + + # display an error if the language does not exist + if is_theme is False: + print( + f'{Fore.RED} The provided theme name ("{theme}") is not a supported theme. {Fore.RESET}' + ) + + # write the new color code in the config file + su.set_config_theme(theme) + + # display information + print( + f'{Fore.GREEN} The provided theme ("{theme}") has been set as default theme for all SEPAL applications.{Fore.RESET}' + ) diff --git a/sepal_ui/frontend/styles.py b/sepal_ui/frontend/styles.py index cf4b2971..a48b3dea 100644 --- a/sepal_ui/frontend/styles.py +++ b/sepal_ui/frontend/styles.py @@ -2,24 +2,28 @@ from traitlets import Unicode from IPython.display import display import ipyvuetify as v -# change vuetify theming -v.theme.dark = True - # set the colors for the dark theme -v.theme.themes.dark.primary = "#B3842E" +v.theme.themes.dark.primary = "#b3842e" v.theme.themes.dark.accent = "#a1458e" v.theme.themes.dark.secondary = "#324a88" -v.theme.themes.dark.success = "#3F802A" -v.theme.themes.dark.info = "#79B1C9" +v.theme.themes.dark.success = "#3f802a" +v.theme.themes.dark.info = "#79b1c9" v.theme.themes.dark.warning = "#b8721d" -v.theme.themes.dark.error = "#A63228" +v.theme.themes.dark.error = "#a63228" -# fixed colors -sepal_main = "#24221F" -sepal_darker = "#1a1a1a" +# fixed colors for drawer and appbar +v.theme.themes.dark.main = "#24221f" +v.theme.themes.light.main = "#2e7d32" +v.theme.themes.dark.darker = "#1a1a1a" +v.theme.themes.light.darker = "#005005" # set the background -bg_color = "#121212" if v.theme.dark else "#fff" +v.theme.themes.dark.bg_color = "#121212" +v.theme.themes.light.bg_color = "#fff" + +# set a specific color for menus +v.theme.themes.dark.menu = "#424242" +v.theme.themes.light.menu = "#fff" class Styles(v.VuetifyTemplate): @@ -49,30 +53,33 @@ class Styles(v.VuetifyTemplate): styles = Styles() display(styles) -COMPONENTS = { - "PROGRESS_BAR": { - "color": "indigo", - } -} - # default styling of the aoi layer AOI_STYLE = { "stroke": True, - "color": v.theme.themes.dark.success, + "color": "grey", "weight": 2, "opacity": 1, "fill": True, - "fillColor": v.theme.themes.dark.success, + "fillColor": "grey", "fillOpacity": 0.4, } +# the colors are set as follow. +# 1 (True): dark theme +# 0 (false): light theme +# This will need to be changed if we want to support more than 2 theme +COMPONENTS = { + "PROGRESS_BAR": { + "color": ["#2196f3", "#3f51b5"], + } +} -_folder = {"color": "amber", "icon": "far fa-folder"} -_table = {"color": "green accent-4", "icon": "far fa-table"} -_vector = {"color": "deep-purple", "icon": "far fa-vector-square"} -_other = {"color": "light-blue", "icon": "far fa-file"} -_parent = {"color": "white", "icon": "far fa-folder-open"} -_image = {"color": "deep-purple", "icon": "far fa-image"} +_folder = {"color": ["#ffca28", "#ffc107"], "icon": "far fa-folder"} +_table = {"color": ["#4caf50", "#00c853"], "icon": "far fa-table"} +_vector = {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-vector-square"} +_other = {"color": ["#00bcd4", "#03a9f4"], "icon": "far fa-file"} +_parent = {"color": ["#424242", "#ffffff"], "icon": "far fa-folder-open"} +_image = {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-image"} ICON_TYPES = { "": _folder, diff --git a/sepal_ui/mapping/mapping.py b/sepal_ui/mapping/mapping.py index ab44e84c..1dae10f3 100644 --- a/sepal_ui/mapping/mapping.py +++ b/sepal_ui/mapping/mapping.py @@ -100,7 +100,10 @@ class SepalMap(geemap.Map): if len(basemaps): [self.add_basemap(basemap) for basemap in set(basemaps)] else: - self.add_basemap("CartoDB.DarkMatter") + default_basemap = ( + "CartoDB.DarkMatter" if v.theme.dark is True else "CartoDB.Positron" + ) + self.add_basemap(default_basemap) # add the base controls self.clear_controls() diff --git a/sepal_ui/message/en/locale.json b/sepal_ui/message/en/locale.json index da5c4efc..c96a4857 100644 --- a/sepal_ui/message/en/locale.json +++ b/sepal_ui/message/en/locale.json @@ -155,7 +155,10 @@ } }, "locale": { - "change": "The locale \"{0}\" will now be used as default language in SEPAL apps. please restart the current application to take this change into account. Note that if \"{0}\" is not avalaible in another application, SEPAL will fallback to the closest possible language", + "change": "The locale \"{0}\" will now be used as default language in SEPAL apps. Please restart the current application to take this change into account. Note that if \"{0}\" is not avalaible in another application, SEPAL will fallback to the closest possible language", "fallback": "The \"{0}\" locale is not available for this application. We will be using \"{1}\" instead. Please report to the maintainer if you want to add \"{0}\" to the suported languages." + }, + "theme": { + "change": "The theme \"{0}\" will be used as default theme in SEPAL apps. Please restart the current application to take this change into account." } } \ No newline at end of file diff --git a/sepal_ui/scripts/utils.py b/sepal_ui/scripts/utils.py index adbce606..2cd55df9 100644 --- a/sepal_ui/scripts/utils.py +++ b/sepal_ui/scripts/utils.py @@ -521,3 +521,31 @@ def set_config_locale(locale): config.write(config_file.open("w")) return + + +@versionadded(version="2.7.0") +def set_config_theme(theme): + """ + Set the provided theme in the sepal-ui config file + + Args: + theme (str): a theme name (currently supporting "dark" and "light") + """ + + config = ConfigParser() + + # read the existing file if available + if config_file.is_file(): + config.read(config_file) + + # set the section if needed + if "sepal-ui" not in config.sections(): + config.add_section("sepal-ui") + + # set the value + config.set("sepal-ui", "theme", theme) + + # save back the file + config.write(config_file.open("w")) + + return diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py index 2d26b7e1..15bcd5f2 100644 --- a/sepal_ui/sepalwidgets/app.py +++ b/sepal_ui/sepalwidgets/app.py @@ -2,20 +2,29 @@ from traitlets import link, Bool, observe from functools import partial from datetime import datetime from pathlib import Path +from itertools import cycle import ipyvuetify as v from deprecated.sphinx import versionadded import pandas as pd from ipywidgets import jsdlink +import sepal_ui from sepal_ui.sepalwidgets.sepalwidget import SepalWidget from sepal_ui import color -from sepal_ui.frontend.styles import sepal_main, sepal_darker from sepal_ui.frontend import js from sepal_ui.scripts import utils as su from sepal_ui.message import ms -__all__ = ["AppBar", "DrawerItem", "NavDrawer", "Footer", "App", "LocaleSelect"] +__all__ = [ + "AppBar", + "DrawerItem", + "NavDrawer", + "Footer", + "App", + "LocaleSelect", + "ThemeSelect", +] class AppBar(v.AppBar, SepalWidget): @@ -37,6 +46,9 @@ class AppBar(v.AppBar, SepalWidget): locale = None "sw.LocaleSelect: the locale selector of all apps" + theme = None + "sw.ThemeSelect: the theme selector of all apps" + def __init__(self, title="SEPAL module", translator=None, **kwargs): self.toggle_button = v.Btn( @@ -47,13 +59,20 @@ class AppBar(v.AppBar, SepalWidget): self.title = v.ToolbarTitle(children=[title]) self.locale = LocaleSelect(translator=translator) + self.theme = ThemeSelect() # set the default parameters - kwargs["color"] = kwargs.pop("color", sepal_main) + kwargs["color"] = kwargs.pop("color", color.main) kwargs["class_"] = kwargs.pop("class_", "white--text") kwargs["dense"] = kwargs.pop("dense", True) kwargs["app"] = True - kwargs["children"] = [self.toggle_button, self.title, v.Spacer(), self.locale] + kwargs["children"] = [ + self.toggle_button, + self.title, + v.Spacer(), + self.locale, + self.theme, + ] super().__init__(**kwargs) @@ -252,7 +271,7 @@ class NavDrawer(v.NavigationDrawer, SepalWidget): # set default parameters kwargs["v_model"] = kwargs.pop("v_model", True) kwargs["app"] = True - kwargs["color"] = kwargs.pop("color", sepal_darker) + kwargs["color"] = kwargs.pop("color", color.darker) kwargs["children"] = children # call the constructor @@ -313,7 +332,7 @@ class Footer(v.Footer, SepalWidget): text = text if text != "" else "SEPAL \u00A9 {}".format(datetime.today().year) # set default parameters - kwargs["color"] = kwargs.pop("color", sepal_main) + kwargs["color"] = kwargs.pop("color", color.main) kwargs["class_"] = kwargs.pop("class_", "white--text") kwargs["app"] = True kwargs["children"] = [text] @@ -414,6 +433,7 @@ class App(v.App, SepalWidget): # add js event self.appBar.locale.observe(self._locale_info, "value") + self.appBar.theme.observe(self._theme_info, "v_model") def show_tile(self, name): """ @@ -442,13 +462,14 @@ class App(v.App, SepalWidget): return self @versionadded(version="2.4.1", reason="New end user interaction method") - def add_banner(self, msg, **kwargs): + def add_banner(self, msg, id_=None, **kwargs): """ Display an alert object on top of the app to communicate development information to end user (release date, known issues, beta version). The alert is dissmisable and prominent Args: msg (str): the message to write in the Alert kwargs: any arguments of the v.Alert constructor. if set, 'children' will be overwritten. + id_ (str, optional): unique banner identificator to avoid multiple aggregations. Return: self @@ -457,16 +478,28 @@ class App(v.App, SepalWidget): kwargs["type"] = kwargs.pop("type", "info") kwargs["border"] = kwargs.pop("border", "left") kwargs["class_"] = kwargs.pop("class_", "mt-5") - kwargs["transition"] = kwargs.pop("transition", "slide-x-transition") + kwargs["transition"] = kwargs.pop("transition", "scroll-x-transition") kwargs["prominent"] = kwargs.pop("prominent", True) kwargs["dismissible"] = kwargs.pop("dismissible", True) kwargs["children"] = [msg] # cannot be overwritten + kwargs["attributes"] = {"id": id_} + kwargs["v_model"] = kwargs.pop("v_model", False) + + # Verify if alert is already in the app. + children = self.content.children.copy() - # create the alert + # remove already existing alert + alert = next((c for c in children if c.attributes.get("id") == id_), False) + alert is False or children.remove(alert) + + # create alert alert = v.Alert(**kwargs) - # add the alert to the app - self.content.children = [alert] + self.content.children.copy() + # add the alert to the app if not already there + self.content.children = [alert] + children + + # Display the alert + alert.v_model = True return self @@ -475,7 +508,16 @@ class App(v.App, SepalWidget): if change["new"] != "": msg = ms.locale.change.format(change["new"]) - self.add_banner(msg, type="success") + self.add_banner(msg, id_="locale") + + return + + def _theme_info(self, change): + """display information about the theme change""" + + if change["new"] != "": + msg = ms.theme.change.format(change["new"]) + self.add_banner(msg, id_="theme") return @@ -535,7 +577,7 @@ class LocaleSelect(v.Menu, SepalWidget): self.language_list = v.List( dense=True, flat=True, - color="grey darken-3", + color=color.menu, v_model=True, max_height="300px", style_="overflow: auto; border-radius: 0 0 0 0;", @@ -600,3 +642,62 @@ class LocaleSelect(v.Menu, SepalWidget): su.set_config_locale(loc.code) return + + +class ThemeSelect(v.Btn, SepalWidget): + """ + A theme selector for sepal-ui based application. + + It displays the currently requested theme (default to dark). + When value is changed, the sepal-ui config file is updated. It is designed to be used in a AppBar component. + + .. versionadded:: 2.7.0 + + Args: + kwargs (dict, optional): any arguments for a Btn object, children and v_model will be override + """ + + THEME_ICONS = {"dark": "fas fa-moon", "light": "fas fa-sun"} + "dict: the dictionnry of icons to use for each theme (used as keys)" + + theme = "dark" + "str: the current theme of the widget (default to dark)" + + def __init__(self, **kwargs): + + # get the current theme name + self.theme = sepal_ui.get_theme(sepal_ui.config_file) + + # set the btn parameters + kwargs["x_small"] = kwargs.pop("x_small", True) + kwargs["fab"] = kwargs.pop("fab", True) + kwargs["class_"] = kwargs.pop("class_", "ml-2") + kwargs["children"] = [v.Icon(children=[self.THEME_ICONS[self.theme]])] + kwargs["v_model"] = self.theme + + # create the btn + super().__init__(**kwargs) + + # add some js events + self.on_event("click", self.toggle_theme) + + def toggle_theme(self, widget, event, data): + """ + toggle the btn icon from dark to light and adapt the configuration file at the same time + """ + # use a cycle to go through the themes + theme_cycle = cycle(self.THEME_ICONS.keys()) + next(t for t in theme_cycle if t == self.theme) + self.theme = next(t for t in theme_cycle) + + # change icon + self.color = "info" + self.children[0].children = [self.THEME_ICONS[self.theme]] + + # change the paramater file + su.set_config_theme(self.theme) + + # trigger other events by changing v_model + self.v_model = self.theme + + return diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index bf1adf0b..365d4f0b 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -9,7 +9,7 @@ import ee import geopandas as gpd from natsort import humansorted - +from sepal_ui import color from sepal_ui.message import ms from sepal_ui.frontend.styles import COMPONENTS, ICON_TYPES from sepal_ui.scripts import utils as su @@ -215,13 +215,13 @@ class FileInput(v.Flex, SepalWidget): self.loading = v.ProgressLinear( indeterminate=False, - background_color="grey darken-3", - color=COMPONENTS["PROGRESS_BAR"]["color"], + background_color=color.menu, + color=COMPONENTS["PROGRESS_BAR"]["color"][v.theme.dark], ) self.file_list = v.List( dense=True, - color="grey darken-3", + color=color.menu, flat=True, v_model=True, max_height="300px", @@ -374,13 +374,13 @@ class FileInput(v.Flex, SepalWidget): if el.is_dir(): icon = ICON_TYPES[""]["icon"] - color = ICON_TYPES[""]["color"] + color = ICON_TYPES[""]["color"][v.theme.dark] elif el.suffix in ICON_TYPES.keys(): icon = ICON_TYPES[el.suffix]["icon"] - color = ICON_TYPES[el.suffix]["color"] + color = ICON_TYPES[el.suffix]["color"][v.theme.dark] else: icon = ICON_TYPES["DEFAULT"]["icon"] - color = ICON_TYPES["DEFAULT"]["color"] + color = ICON_TYPES["DEFAULT"]["color"][v.theme.dark] children = [ v.ListItemAction(children=[v.Icon(color=color, children=[icon])]), @@ -405,7 +405,7 @@ class FileInput(v.Flex, SepalWidget): v.ListItemAction( children=[ v.Icon( - color=ICON_TYPES["PARENT"]["color"], + color=ICON_TYPES["PARENT"]["color"][v.theme.dark], children=[ICON_TYPES["PARENT"]["icon"]], ) ] diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py index 3982aad6..f0a39f77 100644 --- a/sepal_ui/translator/translator.py +++ b/sepal_ui/translator/translator.py @@ -119,7 +119,7 @@ class Translator(SimpleNamespace): if config_file.is_file(): config = ConfigParser() config.read(config_file) - target = config["sepal-ui"]["locale"] + target = config.get("sepal-ui", "locale", fallback="en") else: return ("en", None) diff --git a/setup.py b/setup.py index d7f3d03e..1b207b7e 100644 --- a/setup.py +++ b/setup.py @@ -57,7 +57,7 @@ setup_params = { "pytest", ], "doc": [ - "jupyter-sphinx @ git+git://github.com/jupyter/jupyter-sphinx.git", + "jupyter-sphinx @ git+https://github.com/jupyter/jupyter-sphinx.git", "pydata-sphinx-theme", "sphinx-notfound-page", "Sphinx",
automatically detect the theme used and adapt the frontend accordingly I have seen it on several zoom : it's so cool to display everything in dark but look so wrong when people are actually just developing in there own env in light theme. Several situation that I would like to handle : - voila theme - jupyterLab theme - jupyter notebook theme
12rambau/sepal_ui
diff --git a/tests/test_LocaleSelect.py b/tests/test_LocaleSelect.py index 5da8c6e0..1813b58d 100644 --- a/tests/test_LocaleSelect.py +++ b/tests/test_LocaleSelect.py @@ -6,7 +6,7 @@ from sepal_ui import sepalwidgets as sw from sepal_ui import config_file -class TestBtn: +class TestLocalSelect: def test_init(self, locale_select): # minimal btn diff --git a/tests/test_SepalMap.py b/tests/test_SepalMap.py index 440ce972..43f32238 100644 --- a/tests/test_SepalMap.py +++ b/tests/test_SepalMap.py @@ -53,8 +53,8 @@ class TestSepalMap: m.set_drawing_controls(True) assert isinstance(m.dc, geemap.DrawControl) - assert m.dc.rectangle == {"shapeOptions": {"color": "#79B1C9"}} - assert m.dc.polygon == {"shapeOptions": {"color": "#79B1C9"}} + assert m.dc.rectangle == {"shapeOptions": {"color": "#79b1c9"}} + assert m.dc.polygon == {"shapeOptions": {"color": "#79b1c9"}} assert m.dc.marker == {} assert m.dc.polyline == {} diff --git a/tests/test_ThemeSelect.py b/tests/test_ThemeSelect.py new file mode 100644 index 00000000..0de07d20 --- /dev/null +++ b/tests/test_ThemeSelect.py @@ -0,0 +1,36 @@ +from configparser import ConfigParser + +import pytest + +from sepal_ui import sepalwidgets as sw +from sepal_ui import config_file + + +class TestThemeSelect: + def test_init(self, theme_select): + + # minimal btn + assert isinstance(theme_select, sw.ThemeSelect) + + return + + def test_change_language(self, theme_select): + + # change value + theme_select.fire_event("click", None) + config = ConfigParser() + config.read(config_file) + assert "sepal-ui" in config.sections() + assert config["sepal-ui"]["theme"] == "light" + + return + + @pytest.fixture + def theme_select(self): + """Create a simple theme_select""" + + # destroy any existing config file + if config_file.is_file(): + config_file.unlink() + + return sw.ThemeSelect() diff --git a/tests/test_utils.py b/tests/test_utils.py index a648b462..05136ab4 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -326,3 +326,29 @@ class TestUtils: config_file.unlink() return + + def test_set_config_theme(self): + + # remove any config file that could exist + if config_file.is_file(): + config_file.unlink() + + # create a config_file with a set language + theme = "dark" + su.set_config_theme(theme) + + config = ConfigParser() + config.read(config_file) + assert "sepal-ui" in config.sections() + assert config["sepal-ui"]["theme"] == theme + + # change an existing locale + theme = "light" + su.set_config_theme(theme) + config.read(config_file) + assert config["sepal-ui"]["theme"] == theme + + # destroy the file again + config_file.unlink() + + return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 14 }
2.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "numpy>=1.16.0", "pandas>=1.0.0", "ipyvuetify", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 bqplot==0.12.44 branca==0.4.2 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 colorama==0.4.6 colour==0.1.5 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 EditorConfig==0.17.0 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 ffmpeg-python==0.2.0 filelock==3.18.0 folium==0.13.0 fonttools==4.56.0 fqdn==1.5.1 future==1.0.0 geeadd==1.2.1 geemap==0.8.9 geocoder==1.38.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipyevents==2.0.2 ipyfilechooser==0.6.0 ipykernel==6.29.5 ipyleaflet==0.13.3 ipynb-py-convert==0.4.6 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipytree==0.2.2 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsbeautifier==1.15.4 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 logzero==1.7.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 mss==10.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyCRS==1.0.2 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pyshp==2.3.1 pytest==8.3.5 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 ratelim==0.1.6 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@97371fbaed444727126a2969cd68f856db77221f#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 whitebox==2.3.6 whiteboxgui==2.3.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - bqplot==0.12.44 - branca==0.4.2 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - colorama==0.4.6 - colour==0.1.5 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - editorconfig==0.17.0 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - ffmpeg-python==0.2.0 - filelock==3.18.0 - folium==0.13.0 - fonttools==4.56.0 - fqdn==1.5.1 - future==1.0.0 - geeadd==1.2.1 - geemap==0.8.9 - geocoder==1.38.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipyevents==2.0.2 - ipyfilechooser==0.6.0 - ipykernel==6.29.5 - ipyleaflet==0.13.3 - ipynb-py-convert==0.4.6 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipytree==0.2.2 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsbeautifier==1.15.4 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - logzero==1.7.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - mss==10.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pycrs==1.0.2 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pyshp==2.3.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - ratelim==0.1.6 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - whitebox==2.3.6 - whiteboxgui==2.3.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_ThemeSelect.py::TestThemeSelect::test_init", "tests/test_ThemeSelect.py::TestThemeSelect::test_change_language", "tests/test_utils.py::TestUtils::test_set_config_theme" ]
[ "tests/test_SepalMap.py::TestSepalMap::test_init", "tests/test_SepalMap.py::TestSepalMap::test_set_drawing_controls", "tests/test_SepalMap.py::TestSepalMap::test_remove_last_layer", "tests/test_SepalMap.py::TestSepalMap::test_zoom_bounds", "tests/test_SepalMap.py::TestSepalMap::test_show_dc", "tests/test_SepalMap.py::TestSepalMap::test_change_cursor", "tests/test_SepalMap.py::TestSepalMap::test_add_colorbar", "tests/test_SepalMap.py::TestSepalMap::test_addLayer", "tests/test_SepalMap.py::TestSepalMap::test_get_viz_params", "tests/test_utils.py::TestUtils::test_init_ee" ]
[ "tests/test_LocaleSelect.py::TestLocalSelect::test_init", "tests/test_LocaleSelect.py::TestLocalSelect::test_change_language", "tests/test_SepalMap.py::TestSepalMap::test_get_basemap_list", "tests/test_utils.py::TestUtils::test_hide_component", "tests/test_utils.py::TestUtils::test_show_component", "tests/test_utils.py::TestUtils::test_download_link", "tests/test_utils.py::TestUtils::test_is_absolute", "tests/test_utils.py::TestUtils::test_random_string", "tests/test_utils.py::TestUtils::test_get_file_size", "tests/test_utils.py::TestUtils::test_catch_errors", "tests/test_utils.py::TestUtils::test_loading_button", "tests/test_utils.py::TestUtils::test_to_colors", "tests/test_utils.py::TestUtils::test_switch", "tests/test_utils.py::TestUtils::test_next_string", "tests/test_utils.py::TestUtils::test_set_config_locale" ]
[]
MIT License
null
null
12rambau__sepal_ui-459
a4b3091755a11ef31a3714858007a93b750b6a79
2022-05-04 08:13:02
7eb3f48735e1cfeac75fecf88dd8194c8daea3d3
diff --git a/docs/source/modules/sepal_ui.translator.Translator.rst b/docs/source/modules/sepal_ui.translator.Translator.rst index 60fa976c..642a3ab6 100644 --- a/docs/source/modules/sepal_ui.translator.Translator.rst +++ b/docs/source/modules/sepal_ui.translator.Translator.rst @@ -27,6 +27,7 @@ sepal\_ui.translator.Translator ~Translator.find_target ~Translator.available_locales ~Translator.merge_dict + ~Translator.delete_empty .. automethod:: sepal_ui.translator.Translator.missing_keys @@ -38,6 +39,8 @@ sepal\_ui.translator.Translator .. automethod:: sepal_ui.translator.Translator.merge_dict +.. automethod:: sepal_ui.translator.Translator.delete_empty + .. autofunction:: sepal_ui.translator.Translator.find_target \ No newline at end of file diff --git a/sepal_ui/message/en/locale.json b/sepal_ui/message/en/locale.json index 632249f8..22b77234 100644 --- a/sepal_ui/message/en/locale.json +++ b/sepal_ui/message/en/locale.json @@ -2,11 +2,6 @@ "test_key": "Test key", "status": "Status: {}", "widgets": { - "navdrawer": { - "code": "Source code", - "wiki": "Wiki", - "bug": "Bug report" - }, "asset_select": { "types": { "0": "Raster", diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py index b004b9ee..df1e81d8 100644 --- a/sepal_ui/sepalwidgets/app.py +++ b/sepal_ui/sepalwidgets/app.py @@ -255,19 +255,13 @@ class NavDrawer(v.NavigationDrawer, SepalWidget): code_link = [] if code: - item_code = DrawerItem( - ms.widgets.navdrawer.code, icon="far fa-file-code", href=code - ) + item_code = DrawerItem("Source code", icon="far fa-file-code", href=code) code_link.append(item_code) if wiki: - item_wiki = DrawerItem( - ms.widgets.navdrawer.wiki, icon="fas fa-book-open", href=wiki - ) + item_wiki = DrawerItem("Wiki", icon="fas fa-book-open", href=wiki) code_link.append(item_wiki) if issue: - item_bug = DrawerItem( - ms.widgets.navdrawer.bug, icon="fas fa-bug", href=issue - ) + item_bug = DrawerItem("Bug report", icon="fas fa-bug", href=issue) code_link.append(item_bug) children = [ diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py index f0a39f77..f4fdec47 100644 --- a/sepal_ui/translator/translator.py +++ b/sepal_ui/translator/translator.py @@ -166,7 +166,8 @@ class Translator(SimpleNamespace): Identify numbered dictionnaries embeded in the dict and transform them into lists This function is an helper to prevent deprecation after the introduction of pontoon for translation. - The user is now force to use keys even for numbered lists. SimpleNamespace doesn't support integer indexing so this function will transform back this "numbered" dictionnary (with integer keys) into lists. + The user is now force to use keys even for numbered lists. SimpleNamespace doesn't support integer indexing + so this function will transform back this "numbered" dictionnary (with integer keys) into lists. Args: d (dict): the dictionnary to sanitize @@ -252,7 +253,8 @@ class Translator(SimpleNamespace): """ gather all the .json file in the provided l10n folder as 1 single json dict - the json dict will be sanitysed and the key will be used as if they were coming from 1 single file. be careful with duplication + the json dict will be sanitysed and the key will be used as if they were coming from 1 single file. + be careful with duplication. empty string keys will be removed. Args: folder (pathlib.path) @@ -264,6 +266,29 @@ class Translator(SimpleNamespace): final_json = {} for f in folder.glob("*.json"): - final_json = {**final_json, **cls.sanitize(json.loads(f.read_text()))} + tmp_dict = cls.delete_empty(json.loads(f.read_text())) + final_json = {**final_json, **cls.sanitize(tmp_dict)} return final_json + + @versionadded(version="2.8.1") + @classmethod + def delete_empty(cls, d): + """ + Remove empty strings ("") recursively from the dictionaries. This is to prevent untranslated strings from + Crowdin to be uploaded. The dictionnary must only embed dictionnaries and no lists. + + Args: + d (dict): the dictionnary to sanitize + + Return: + (dict): the sanitized dictionnary + + """ + for k, v in list(d.items()): + if isinstance(v, dict): + cls.delete_empty(v) + elif v == "": + del d[k] + + return d
crowdin untranslated keys are marked as empty string These string are interpreted as "something" by the translator leading to empty strings everywhere in the build-in component. They should be ignored
12rambau/sepal_ui
diff --git a/tests/test_Translator.py b/tests/test_Translator.py index 930a533e..c6d0e85e 100644 --- a/tests/test_Translator.py +++ b/tests/test_Translator.py @@ -49,25 +49,29 @@ class TestTranslator: # a test dict with many embeded numbered list # but also an already existing list test = { - "foo1": {"0": "foo2", "1": "foo3"}, - "foo4": { - "foo5": {"0": "foo6", "1": "foo7"}, - "foo8": "foo9", - }, - "foo10": ["foo11", "foo12"], + "a": {"0": "b", "1": "c"}, + "d": {"e": {"0": "f", "1": "g"}, "h": "i"}, + "j": ["k", "l"], } # the sanitize version of this result = { - "foo1": ["foo2", "foo3"], - "foo4": {"foo5": ["foo6", "foo7"], "foo8": "foo9"}, - "foo10": ["foo11", "foo12"], + "a": ["b", "c"], + "d": {"e": ["f", "g"], "h": "i"}, + "j": ["k", "l"], } assert Translator.sanitize(test) == result return + def test_delete_empty(self): + + test = {"a": "", "b": 1, "c": {"d": ""}, "e": {"f": "", "g": 2}} + result = {"b": 1, "c": {}, "e": {"g": 2}} + + assert Translator.delete_empty(test) == result + def test_missing_keys(self, translation_folder): # check that all keys are in the fr dict
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 4 }
2.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 bqplot==0.12.44 branca==0.4.2 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 colorama==0.4.6 colour==0.1.5 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 EditorConfig==0.17.0 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 ffmpeg-python==0.2.0 filelock==3.18.0 folium==0.13.0 fonttools==4.56.0 fqdn==1.5.1 future==1.0.0 geeadd==1.2.1 geemap==0.8.9 geocoder==1.38.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipyevents==2.0.2 ipyfilechooser==0.6.0 ipykernel==6.29.5 ipyleaflet==0.13.3 ipynb-py-convert==0.4.6 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipytree==0.2.2 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsbeautifier==1.15.4 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 logzero==1.7.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 mss==10.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyCRS==1.0.2 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pyshp==2.3.1 pytest==8.3.5 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 ratelim==0.1.6 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@a4b3091755a11ef31a3714858007a93b750b6a79#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 whitebox==2.3.6 whiteboxgui==2.3.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - bqplot==0.12.44 - branca==0.4.2 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - colorama==0.4.6 - colour==0.1.5 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - editorconfig==0.17.0 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - ffmpeg-python==0.2.0 - filelock==3.18.0 - folium==0.13.0 - fonttools==4.56.0 - fqdn==1.5.1 - future==1.0.0 - geeadd==1.2.1 - geemap==0.8.9 - geocoder==1.38.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipyevents==2.0.2 - ipyfilechooser==0.6.0 - ipykernel==6.29.5 - ipyleaflet==0.13.3 - ipynb-py-convert==0.4.6 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipytree==0.2.2 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsbeautifier==1.15.4 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - logzero==1.7.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - mss==10.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pycrs==1.0.2 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pyshp==2.3.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - ratelim==0.1.6 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - whitebox==2.3.6 - whiteboxgui==2.3.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Translator.py::TestTranslator::test_delete_empty" ]
[]
[ "tests/test_Translator.py::TestTranslator::test_init", "tests/test_Translator.py::TestTranslator::test_search_key", "tests/test_Translator.py::TestTranslator::test_sanitize", "tests/test_Translator.py::TestTranslator::test_missing_keys", "tests/test_Translator.py::TestTranslator::test_find_target", "tests/test_Translator.py::TestTranslator::test_available_locales" ]
[]
MIT License
null
null
12rambau__sepal_ui-501
7eb3f48735e1cfeac75fecf88dd8194c8daea3d3
2022-06-09 11:09:52
7eb3f48735e1cfeac75fecf88dd8194c8daea3d3
diff --git a/docs/source/modules/sepal_ui.translator.Translator.rst b/docs/source/modules/sepal_ui.translator.Translator.rst index 642a3ab6..7f11e39f 100644 --- a/docs/source/modules/sepal_ui.translator.Translator.rst +++ b/docs/source/modules/sepal_ui.translator.Translator.rst @@ -2,19 +2,6 @@ sepal\_ui.translator.Translator =============================== .. autoclass:: sepal_ui.translator.Translator - - .. rubric:: Attributes - - .. autosummary:: - - ~Translator.default_dict - ~Translator.target_dict - ~Translator.default - ~Translator.target - ~Translator.targeted - ~Translator.match - ~Translator.keys - ~Translator.folder .. rubric:: Methods @@ -33,7 +20,7 @@ sepal\_ui.translator.Translator .. automethod:: sepal_ui.translator.Translator.sanitize -.. automethod:: sepal_ui.translator.Translator.search_key +.. autofunction:: sepal_ui.translator.Translator.search_key .. automethod:: sepal_ui.translator.Translator.available_locales diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py index 96c10461..bfd59e3d 100644 --- a/sepal_ui/sepalwidgets/app.py +++ b/sepal_ui/sepalwidgets/app.py @@ -602,7 +602,7 @@ class LocaleSelect(v.Menu, SepalWidget): # extract the language information from the translator # if not set default to english - code = "en" if translator is None else translator.target + code = "en" if translator is None else translator._target loc = self.COUNTRIES[self.COUNTRIES.code == code].squeeze() attr = {**self.ATTR, "src": self.FLAG.format(loc.flag), "alt": loc.name} diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py index f4fdec47..efa29bc9 100644 --- a/sepal_ui/translator/translator.py +++ b/sepal_ui/translator/translator.py @@ -1,21 +1,26 @@ import json -from types import SimpleNamespace from pathlib import Path from collections import abc -from deepdiff import DeepDiff from configparser import ConfigParser -from deprecated.sphinx import versionadded +from deprecated.sphinx import versionadded, deprecated +from box import Box from sepal_ui import config_file -class Translator(SimpleNamespace): +class Translator(Box): """ - The translator is a SimpleNamespace of Simplenamespace. It reads 2 Json files, the first one being the source language (usually English) and the second one the target language. + The translator is a Python Box of boxes. It reads 2 Json files, the first one being the source language (usually English) and the second one the target language. It will replace in the source dictionary every key that exist in both json dictionaries. Following this procedure, every message that is not translated can still be accessed in the source language. To access the dictionary keys, instead of using [], you can simply use key name as in an object ex: translator.first_key.secondary_key. There are no depth limits, just respect the snake_case convention when naming your keys in the .json files. + 5 internal keys are created upon initialization (there name cannot be used as keys in the translation message): + - (str) _default : the default locale of the translator + - (str) _targeted : the initially requested language. Use to display debug information to the user agent + - (str) _target : the target locale of the translator + - (bool) _match : if the target language match the one requested one by user, used to trigger information in appBar + - (str) _folder : the path to the l10n folder Args: json_folder (str | pathlib.Path): The folder where the dictionaries are stored @@ -23,75 +28,60 @@ class Translator(SimpleNamespace): default (str, optional): The language code (IETF BCP 47) of the source lang. default to "en" (it should be the same as the source dictionary) """ - FORBIDDEN_KEYS = [ - "default_dict", - "target_dict", - "in", - "class", - "default", - "target", - "match", - ] - "list(str): list of the forbidden keys, using one of them in a translation dict will throw an error" - - target_dict = {} - "(dict): the target language dictionary" - - default_dict = {} - "dict: the source language dictionary" - - default = None - "str: the default locale of the translator" - - targeted = None - "str: the initially requested language. Use to display debug information to the user agent" - - target = None - "str: the target locale of the translator" - - match = None - "bool: if the target language match the one requested one by user, used to trigger information in appBar" - - keys = None - "all the keys can be acceced as attributes" - - folder = None - "pathlib.Path: the path to the l10n folder" + _protected_keys = [ + "find_target", + "search_key", + "sanitize", + "_update", + "missing_keys", + "available_locales", + "merge_dict", + "delete_empty", + ] + dir(Box) + "keys that cannot be used as var names as they are protected for methods" def __init__(self, json_folder, target=None, default="en"): - # init the simple namespace - super().__init__() + # the name of the 5 variables that cannot be used as init keys + FORBIDDEN_KEYS = ["_folder", "_default", "_target", "_targeted", "_match"] - # force cast to path - self.folder = Path(json_folder) + # init the box with the folder + folder = Path(json_folder) # reading the default dict - self.default = default - self.default_dict = self.merge_dict(self.folder / default) + default_dict = self.merge_dict(folder / default) # create a dictionary in the target language - self.targeted, target = self.find_target(self.folder, target) - self.target = target or default - self.target_dict = self.merge_dict(self.folder / self.target) + targeted, target = self.find_target(folder, target) + target = target or default + target_dict = self.merge_dict(folder / target) # evaluate the matching of requested and obtained values - self.match = self.targeted == self.target + match = targeted == target # create the composite dictionary - ms_dict = self._update(self.default_dict, self.target_dict) + ms_dict = self._update(default_dict, target_dict) # check if forbidden keys are being used - [self.search_key(ms_dict, k) for k in self.FORBIDDEN_KEYS] + # this will raise an error if any + [self.search_key(ms_dict, k) for k in FORBIDDEN_KEYS] - # transform it into a json str + # # unpack the json as a simple namespace ms_json = json.dumps(ms_dict) + ms_boxes = json.loads(ms_json, object_hook=lambda d: Box(**d, frozen_box=True)) - # unpack the json as a simple namespace - ms = json.loads(ms_json, object_hook=lambda d: SimpleNamespace(**d)) + private_keys = { + "_folder": str(folder), + "_default": default, + "_targeted": targeted, + "_target": target, + "_match": match, + } - for k, v in ms.__dict__.items(): - setattr(self, k, getattr(ms, k)) + # the final box is not frozen + # waiting for an answer here: https://github.com/cdgriffith/Box/issues/223 + # it the meantime it's easy to call the translator using a frozen_box argument + super(Box, self).__init__(**private_keys, **ms_boxes) @versionadded(version="2.7.0") @staticmethod @@ -139,8 +129,8 @@ class Translator(SimpleNamespace): return (target, lang) - @classmethod - def search_key(cls, d, key): + @staticmethod + def search_key(d, key): """ Search a specific key in the d dictionary and raise an error if found @@ -149,14 +139,9 @@ class Translator(SimpleNamespace): key (str): the key to look for """ - for k, v in d.items(): - if isinstance(v, abc.Mapping): - cls.search_key(v, key) - else: - if k == key: - raise Exception( - f"You cannot use the key {key} in your translation dictionary" - ) + if key in d: + msg = f"You cannot use the key {key} in your translation dictionary" + raise Exception(msg) return @@ -218,34 +203,19 @@ class Translator(SimpleNamespace): return ms + @deprecated(version="2.9.0", reason="Not needed with automatic translators") def missing_keys(self): - """ - this function is intended for developer use only - print the list of the missing keys in the target dictionnairie - - Return: - (str): the list of missing keys - """ - - # find all the missing keys - try: - ddiff = DeepDiff(self.default_dict, self.target_dict)[ - "dictionary_item_removed" - ] - except Exception: - ddiff = ["All messages are translated"] - - return "\n".join(ddiff) + pass def available_locales(self): """ Return the available locales in the l10n folder Return: - (list): the lilst of str codes + (list): the list of str codes """ - return [f.name for f in self.folder.iterdir() if f.is_dir()] + return [f.name for f in Path(self._folder).glob("[!^._]*") if f.is_dir()] @versionadded(version="2.7.0") @classmethod
use box for the translator ? I discovered this lib while working on the geemap drop. I think it could be super handy for the translator keys and maybe faster. https://github.com/cdgriffith/Box side note: we will need it anyway for the geemap drop
12rambau/sepal_ui
diff --git a/tests/test_Translator.py b/tests/test_Translator.py index c6d0e85e..ff6c46f8 100644 --- a/tests/test_Translator.py +++ b/tests/test_Translator.py @@ -35,9 +35,10 @@ class TestTranslator: def test_search_key(self): - # assert that having a wrong key in the json will raise an error + # assert that having a wrong key at root level + # in the json will raise an error key = "toto" - d = {"a": {"toto": "b"}, "c": "d"} + d = {"toto": {"a": "b"}, "c": "d"} with pytest.raises(Exception): Translator.search_key(d, key) @@ -72,16 +73,6 @@ class TestTranslator: assert Translator.delete_empty(test) == result - def test_missing_keys(self, translation_folder): - - # check that all keys are in the fr dict - translator = Translator(translation_folder, "fr") - assert translator.missing_keys() == "All messages are translated" - - # check that 1 key is missing - translator = Translator(translation_folder, "es") - assert translator.missing_keys() == "root['test_key']" - return def test_find_target(self, translation_folder): @@ -114,6 +105,12 @@ class TestTranslator: for locale in res: assert locale in translator.available_locales() + # Check no hidden and protected files are in locales + locales = translator.available_locales() + assert not all( + [(loc.startswith(".") or loc.startswith("_")) for loc in locales] + ) + return @pytest.fixture(scope="class")
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 3 }
2.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "coverage" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 fsspec==2025.3.2 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipyleaflet==0.19.2 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.19.0 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@7eb3f48735e1cfeac75fecf88dd8194c8daea3d3#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 xyzservices==2025.1.0 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - fsspec==2025.3.2 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.19.0 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - xyzservices==2025.1.0 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Translator.py::TestTranslator::test_search_key" ]
[]
[ "tests/test_Translator.py::TestTranslator::test_init", "tests/test_Translator.py::TestTranslator::test_sanitize", "tests/test_Translator.py::TestTranslator::test_delete_empty", "tests/test_Translator.py::TestTranslator::test_find_target", "tests/test_Translator.py::TestTranslator::test_available_locales" ]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-501
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-501
12rambau__sepal_ui-516
9c319b0c21b8b1ba75173f3f85fd184747c398de
2022-07-03 07:19:07
114063b50ee5b1ccbab680424bb048e11939b870
diff --git a/docs/source/modules/sepal_ui.aoi.AoiModel.rst b/docs/source/modules/sepal_ui.aoi.AoiModel.rst index 0f5b8f1a..ccdcab52 100644 --- a/docs/source/modules/sepal_ui.aoi.AoiModel.rst +++ b/docs/source/modules/sepal_ui.aoi.AoiModel.rst @@ -12,7 +12,6 @@ sepal\_ui.aoi.AoiModel ~AoiModel.NAME ~AoiModel.ISO ~AoiModel.GADM_BASE_URL - ~AoiModel.GADM_ZIP_DIR ~AoiModel.GAUL_ASSET ~AoiModel.ASSET_SUFFIX ~AoiModel.CUSTOM diff --git a/sepal_ui/aoi/aoi_model.py b/sepal_ui/aoi/aoi_model.py index ad2a72fb..40f9b4e6 100644 --- a/sepal_ui/aoi/aoi_model.py +++ b/sepal_ui/aoi/aoi_model.py @@ -61,11 +61,6 @@ class AoiModel(Model): GADM_BASE_URL = "https://biogeo.ucdavis.edu/data/gadm3.6/gpkg/gadm36_{}_gpkg.zip" "str: the base url to download gadm maps" - GADM_ZIP_DIR = Path.home() / "tmp" / "GADM_zip" - "pathlib.Path: the zip dir where we download the zips" - - GADM_ZIP_DIR.mkdir(parents=True, exist_ok=True) - GAUL_ASSET = "FAO/GAUL/2015/level{}" "str: the GAUL asset name" diff --git a/sepal_ui/mapping/sepal_map.py b/sepal_ui/mapping/sepal_map.py index 6a518ccc..6ca115fc 100644 --- a/sepal_ui/mapping/sepal_map.py +++ b/sepal_ui/mapping/sepal_map.py @@ -16,7 +16,7 @@ import random from haversine import haversine import numpy as np import rioxarray -import xarray_leaflet +import xarray_leaflet # noqa: F401 import matplotlib.pyplot as plt from matplotlib import colors as mpc from matplotlib import colorbar @@ -38,11 +38,6 @@ from sepal_ui.mapping.basemaps import basemap_tiles __all__ = ["SepalMap"] -# call x_array leaflet at least once -# flake8 will complain as it's a pluggin (i.e. never called) -# We don't want to ignore testing F401 -xarray_leaflet - class SepalMap(ipl.Map): """ diff --git a/sepal_ui/mapping/value_inspector.py b/sepal_ui/mapping/value_inspector.py index f848018f..783d68ad 100644 --- a/sepal_ui/mapping/value_inspector.py +++ b/sepal_ui/mapping/value_inspector.py @@ -3,7 +3,7 @@ import ee import geopandas as gpd from shapely import geometry as sg import rioxarray -import xarray_leaflet +import xarray_leaflet # noqa: F401 from rasterio.crs import CRS import rasterio as rio import ipyvuetify as v @@ -16,11 +16,6 @@ from sepal_ui.mapping.map_btn import MapBtn from sepal_ui.frontend.styles import COMPONENTS from sepal_ui.message import ms -# call x_array leaflet at least once -# flake8 will complain as it's a pluggin (i.e. never called) -# We don't want to ignore testing F401 -xarray_leaflet - class ValueInspector(WidgetControl): """ diff --git a/sepal_ui/sepalwidgets/tile.py b/sepal_ui/sepalwidgets/tile.py index dec40168..69a92dc0 100644 --- a/sepal_ui/sepalwidgets/tile.py +++ b/sepal_ui/sepalwidgets/tile.py @@ -76,7 +76,7 @@ class Tile(v.Layout, SepalWidget): self._metadata["mount_id"] = "nested_tile" # remove elevation - self.elevation = False + self.children[0].elevation = False # remove title self.set_title()
deprecate zip_dir https://github.com/12rambau/sepal_ui/blob/a9255e7c566aac31ee7f8303e74fb7e8a3d57e5f/sepal_ui/aoi/aoi_model.py#L64 This folder is created on AOI call but is not used anymore as we are using the tmp module to create the tmp directory.
12rambau/sepal_ui
diff --git a/tests/test_Tile.py b/tests/test_Tile.py index aa22d301..de0de97e 100644 --- a/tests/test_Tile.py +++ b/tests/test_Tile.py @@ -81,7 +81,7 @@ class TestTile: assert res == tile assert tile._metadata["mount_id"] == "nested_tile" - assert tile.elevation is False + assert tile.children[0].elevation == 0 assert len(tile.children[0].children) == 1 return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 5 }
2.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 fsspec==2025.3.2 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipyleaflet==0.19.2 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==1.5.2 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-futures==0.9.9 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@9c319b0c21b8b1ba75173f3f85fd184747c398de#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 xyzservices==2025.1.0 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - fsspec==2025.3.2 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==1.5.2 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-futures==0.9.9 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - xyzservices==2025.1.0 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Tile.py::TestTile::test_nest" ]
[]
[ "tests/test_Tile.py::TestTile::test_init", "tests/test_Tile.py::TestTile::test_set_content", "tests/test_Tile.py::TestTile::test_set_title", "tests/test_Tile.py::TestTile::test_hide", "tests/test_Tile.py::TestTile::test_show", "tests/test_Tile.py::TestTile::test_toggle_inputs", "tests/test_Tile.py::TestTile::test_get_id", "tests/test_Tile.py::TestTile::test_tile_about", "tests/test_Tile.py::TestTile::test_tile_disclaimer" ]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-516
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-516
12rambau__sepal_ui-517
9c319b0c21b8b1ba75173f3f85fd184747c398de
2022-07-03 10:05:47
114063b50ee5b1ccbab680424bb048e11939b870
diff --git a/sepal_ui/message/en/utils.json b/sepal_ui/message/en/utils.json new file mode 100644 index 00000000..0282d86c --- /dev/null +++ b/sepal_ui/message/en/utils.json @@ -0,0 +1,7 @@ +{ + "utils": { + "check_input": { + "error": "The value has not been initialized" + } + } +} \ No newline at end of file diff --git a/sepal_ui/scripts/utils.py b/sepal_ui/scripts/utils.py index b062906d..1f37abc2 100644 --- a/sepal_ui/scripts/utils.py +++ b/sepal_ui/scripts/utils.py @@ -17,6 +17,7 @@ from matplotlib import colors as c from deprecated.sphinx import versionadded, deprecated import sepal_ui +from sepal_ui.message import ms from sepal_ui.conf import config_file, config from .warning import SepalWarning @@ -631,3 +632,31 @@ def geojson_to_ee(geo_json, geodesic=False, encoding="utf-8"): raise ValueError("Could not convert the geojson to ee.Geometry()") return + + +def check_input(input_, msg=ms.utils.check_input.error): + """ + Check if the inpupt value is initialized. + If not raise an error, else return True + + Args: + input\_ (any): the input to check + msg (str, optionnal): the message to display if the input is not set + + Return: + (bool): check if the value is initialized + """ + + # by the default the variable is considered valid + init = True + + # check the collection type that are the only one supporting the len method + try: + init = False if len(input_) == 0 else init + except Exception: + init = False if input_ is None else init + + if init is False: + raise ValueError(msg) + + return init diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py index 4fd9c633..55ad3b65 100644 --- a/sepal_ui/sepalwidgets/alert.py +++ b/sepal_ui/sepalwidgets/alert.py @@ -3,11 +3,13 @@ from tqdm.notebook import tqdm from ipywidgets import jslink, Output import ipyvuetify as v from traitlets import Unicode, observe, directional_link, Bool +from deprecated.sphinx import deprecated from sepal_ui.sepalwidgets.sepalwidget import SepalWidget from sepal_ui.scripts.utils import set_type from sepal_ui.frontend.styles import TYPES, color from sepal_ui.message import ms +from sepal_ui.scripts import utils as su __all__ = ["Divider", "Alert", "StateBar", "Banner"] @@ -229,6 +231,7 @@ class Alert(v.Alert, SepalWidget): return self + @deprecated(version="3.0", reason="This method is now part of the utils module") def check_input(self, input_, msg=None): """ Check if the inpupt value is initialized. @@ -241,20 +244,9 @@ class Alert(v.Alert, SepalWidget): Return: (bool): check if the value is initialized """ - if not msg: - msg = "The value has not been initialized" - init = True + msg = msg or ms.utils.check_input.error - # check the collection type that are the only one supporting the len method - try: - init = False if len(input_) == 0 else init - except Exception: - init = False if input_ is None else init - - if init is False: - self.add_msg(msg, "error") - - return init + return su.check_input(input_, msg) class StateBar(v.SystemBar):
refactor check_input to raise error instead of displaying a message? https://github.com/12rambau/sepal_ui/blob/a9255e7c566aac31ee7f8303e74fb7e8a3d57e5f/sepal_ui/sepalwidgets/alert.py#L232 This was initially coded as a message to prevent the execution from stopping when a function was using undefined variables. Along the way we introduced `try ... exept` statements in our functions and now main methods are mostly used with the `loading_button` decorator. I think we could refactor the `check_input` so that it directly raises an error instead writing down a message in the alert. Maybe even better, we deprecate this function and we move `check_input` to `utils` (with the error raising mechanism).
12rambau/sepal_ui
diff --git a/tests/test_Alert.py b/tests/test_Alert.py index 6116cbc7..d125b74e 100644 --- a/tests/test_Alert.py +++ b/tests/test_Alert.py @@ -111,28 +111,22 @@ class TestAlert: alert = sw.Alert() - var_test = None - res = alert.check_input(var_test) - assert res is False - assert alert.viz is True - assert alert.children[0].children[0] == "The value has not been initialized" + with pytest.raises(ValueError, match="The value has not been initialized"): + alert.check_input(None) - res = alert.check_input(var_test, "toto") - assert alert.children[0].children[0] == "toto" + with pytest.raises(ValueError, match="toto"): + alert.check_input(None, "toto") - var_test = 1 - res = alert.check_input(var_test) + res = alert.check_input(1) assert res is True # test lists - var_test = [range(2)] - res = alert.check_input(var_test) + res = alert.check_input([range(2)]) assert res is True # test empty list - var_test = [] - res = alert.check_input(var_test) - assert res is False + with pytest.raises(ValueError): + alert.check_input([]) return diff --git a/tests/test_utils.py b/tests/test_utils.py index 59bda7b8..9f6742cd 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -391,3 +391,24 @@ class TestUtils: su.geojson_to_ee(dict_) return + + def test_check_input(self): + + with pytest.raises(ValueError, match="The value has not been initialized"): + su.check_input(None) + + with pytest.raises(ValueError, match="toto"): + su.check_input(None, "toto") + + res = su.check_input(1) + assert res is True + + # test lists + res = su.check_input([range(2)]) + assert res is True + + # test empty list + with pytest.raises(ValueError): + su.check_input([]) + + return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
2.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 fsspec==2025.3.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==1.5.2 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest==8.3.5 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-futures==0.9.9 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@9c319b0c21b8b1ba75173f3f85fd184747c398de#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 xyzservices==2025.1.0 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - fsspec==2025.3.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==1.5.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pytest==8.3.5 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-futures==0.9.9 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - xyzservices==2025.1.0 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Alert.py::TestAlert::test_check_input", "tests/test_utils.py::TestUtils::test_check_input" ]
[ "tests/test_utils.py::TestUtils::test_init_ee", "tests/test_utils.py::TestUtils::test_geojson_to_ee" ]
[ "tests/test_Alert.py::TestAlert::test_init", "tests/test_Alert.py::TestAlert::test_add_msg", "tests/test_Alert.py::TestAlert::test_add_live_msg", "tests/test_Alert.py::TestAlert::test_append_msg", "tests/test_Alert.py::TestAlert::test_reset", "tests/test_Alert.py::TestAlert::test_rmv_last_msg", "tests/test_Alert.py::TestAlert::test_update_progress", "tests/test_utils.py::TestUtils::test_hide_component", "tests/test_utils.py::TestUtils::test_show_component", "tests/test_utils.py::TestUtils::test_download_link", "tests/test_utils.py::TestUtils::test_random_string", "tests/test_utils.py::TestUtils::test_get_file_size", "tests/test_utils.py::TestUtils::test_catch_errors", "tests/test_utils.py::TestUtils::test_loading_button", "tests/test_utils.py::TestUtils::test_to_colors", "tests/test_utils.py::TestUtils::test_switch", "tests/test_utils.py::TestUtils::test_next_string", "tests/test_utils.py::TestUtils::test_set_config_locale", "tests/test_utils.py::TestUtils::test_set_config_theme", "tests/test_utils.py::TestUtils::test_set_style" ]
[]
MIT License
null
null
12rambau__sepal_ui-518
698d446e33062934d49f9edb91cbe303b73e786f
2022-07-03 10:33:15
114063b50ee5b1ccbab680424bb048e11939b870
diff --git a/sepal_ui/mapping/aoi_control.py b/sepal_ui/mapping/aoi_control.py index 01a6aa48..ae143d2c 100644 --- a/sepal_ui/mapping/aoi_control.py +++ b/sepal_ui/mapping/aoi_control.py @@ -36,7 +36,7 @@ class AoiControl(WidgetControl): kwargs["position"] = kwargs.pop("position", "topright") # create a hoverable btn - btn = MapBtn(logo="fas fa-search-location", v_on="menu.on") + btn = MapBtn(content="fas fa-search-location", v_on="menu.on") slot = {"name": "activator", "variable": "menu", "children": btn} self.aoi_list = sw.ListItemGroup(children=[], v_model="") w_list = sw.List( diff --git a/sepal_ui/mapping/fullscreen_control.py b/sepal_ui/mapping/fullscreen_control.py index 5e23c1d6..2855fa72 100644 --- a/sepal_ui/mapping/fullscreen_control.py +++ b/sepal_ui/mapping/fullscreen_control.py @@ -43,7 +43,7 @@ class FullScreenControl(WidgetControl): self.zoomed = fullscreen # create a btn - self.w_btn = MapBtn(logo=self.ICONS[self.zoomed]) + self.w_btn = MapBtn(self.ICONS[self.zoomed]) # overwrite the widget set in the kwargs (if any) kwargs["widget"] = self.w_btn @@ -88,7 +88,7 @@ class FullScreenControl(WidgetControl): self.zoomed = not self.zoomed # change button icon - self.w_btn.logo.children = [self.ICONS[self.zoomed]] + self.w_btn.children[0].children = [self.ICONS[self.zoomed]] # zoom self.template.send({"method": self.METHODS[self.zoomed], "args": []}) diff --git a/sepal_ui/mapping/map_btn.py b/sepal_ui/mapping/map_btn.py index ab55e1c8..0ea13364 100644 --- a/sepal_ui/mapping/map_btn.py +++ b/sepal_ui/mapping/map_btn.py @@ -7,26 +7,26 @@ from sepal_ui.frontend.styles import map_btn_style class MapBtn(v.Btn, sw.SepalWidget): """ Btn specifically design to be displayed on a map. It matches all the characteristics of - the classic leaflet btn but as they are from ipyvuetify we can use them in combination with Menu to produce on-the-map. The MapBtn is responsive to theme changes. - Tiles. It only accept icon as children as the space is very limited. + the classic leaflet btn but as they are from ipyvuetify we can use them in combination with Menu to produce on-the-map tiles. + The MapBtn is responsive to theme changes. It only accept icon or 3 letters as children as the space is very limited. Args: - logo (str): a fas/mdi fully qualified name + content (str): a fas/mdi fully qualified name or a string name. If a string name is used, only the 3 first letters will be displayed. """ - logo = None - "(sw.Icon): a sw.Icon" - - def __init__(self, logo, **kwargs): + def __init__(self, content, **kwargs): # create the icon - self.logo = sw.Icon(small=True, children=[logo]) + if content.startswith("mdi-") or content.startswith("fas fa-"): + content = sw.Icon(small=True, children=[content]) + else: + content = content[: min(3, len(content))].upper() # some parameters are overloaded to match the map requirements kwargs["color"] = "text-color" kwargs["outlined"] = True kwargs["style_"] = " ".join([f"{k}: {v};" for k, v in map_btn_style.items()]) - kwargs["children"] = [self.logo] + kwargs["children"] = [content] kwargs["icon"] = False super().__init__(**kwargs) diff --git a/sepal_ui/mapping/value_inspector.py b/sepal_ui/mapping/value_inspector.py index ecc52e72..96508ba3 100644 --- a/sepal_ui/mapping/value_inspector.py +++ b/sepal_ui/mapping/value_inspector.py @@ -54,7 +54,7 @@ class ValueInspector(WidgetControl): ) # create a clickable btn - btn = MapBtn(logo="fas fa-crosshairs", v_on="menu.on") + btn = MapBtn("fas fa-crosshairs", v_on="menu.on") slot = {"name": "activator", "variable": "menu", "children": btn} close_btn = sw.Icon(children=["fas fa-times"], small=True) title = sw.Html(tag="h4", children=[ms.v_inspector.title])
add posibility to add text in the map_btn The current implementation of the map_btn only authorize to use logos. It would be nice to let the opportunity to use letters as in the SEPAL main framework (3 letters only in capital)
12rambau/sepal_ui
diff --git a/tests/test_FullScreenControl.py b/tests/test_FullScreenControl.py index 39141edf..148242b8 100644 --- a/tests/test_FullScreenControl.py +++ b/tests/test_FullScreenControl.py @@ -14,7 +14,7 @@ class TestFullScreenControl: assert isinstance(control, sm.FullScreenControl) assert control in map_.controls assert control.zoomed is False - assert "fas fa-expand" in control.w_btn.logo.children + assert "fas fa-expand" in control.w_btn.children[0].children return @@ -29,12 +29,12 @@ class TestFullScreenControl: control.toggle_fullscreen(None, None, None) assert control.zoomed is True - assert "fas fa-compress" in control.w_btn.logo.children + assert "fas fa-compress" in control.w_btn.children[0].children # click again to reset to initial state control.toggle_fullscreen(None, None, None) assert control.zoomed is False - assert "fas fa-expand" in control.w_btn.logo.children + assert "fas fa-expand" in control.w_btn.children[0].children return diff --git a/tests/test_MapBtn.py b/tests/test_MapBtn.py index 0dd605b8..9a9d9c2f 100644 --- a/tests/test_MapBtn.py +++ b/tests/test_MapBtn.py @@ -1,11 +1,29 @@ from sepal_ui import mapping as sm +from sepal_ui import sepalwidgets as sw class TestMapBtn: - def test_map_btn(self): + def test_init(self): + # fas icon map_btn = sm.MapBtn("fas fa-folder") - assert isinstance(map_btn, sm.MapBtn) + assert isinstance(map_btn.children[0], sw.Icon) + assert map_btn.children[0].children[0] == "fas fa-folder" + + # mdi icon + map_btn = sm.MapBtn("mdi-folder") + assert isinstance(map_btn.children[0], sw.Icon) + assert map_btn.children[0].children[0] == "mdi-folder" + + # small text + map_btn = sm.MapBtn("to") + assert isinstance(map_btn.children[0], str) + assert map_btn.children[0] == "TO" + + # long text + map_btn = sm.MapBtn("toto") + assert isinstance(map_btn.children[0], str) + assert map_btn.children[0] == "TOT" return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 4 }
2.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 fsspec==2025.3.2 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipyleaflet==0.19.2 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==1.5.2 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-futures==0.9.9 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@698d446e33062934d49f9edb91cbe303b73e786f#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 xyzservices==2025.1.0 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - fsspec==2025.3.2 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==1.5.2 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-futures==0.9.9 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - xyzservices==2025.1.0 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_MapBtn.py::TestMapBtn::test_init" ]
[ "tests/test_FullScreenControl.py::TestFullScreenControl::test_init", "tests/test_FullScreenControl.py::TestFullScreenControl::test_toggle_fullscreen" ]
[]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-518
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-518
12rambau__sepal_ui-533
7710c4abf8f0dfa916a4933c766ab6203bf3a76e
2022-07-06 07:47:43
114063b50ee5b1ccbab680424bb048e11939b870
diff --git a/sepal_ui/__init__.py b/sepal_ui/__init__.py index 5eab7e53..79ccdf6f 100644 --- a/sepal_ui/__init__.py +++ b/sepal_ui/__init__.py @@ -1,8 +1,11 @@ import ipyvuetify as v from sepal_ui.conf import config, config_file -from sepal_ui.frontend.styles import color, get_theme +from sepal_ui.frontend.styles import SepalColor, get_theme __author__ = """Pierrick Rambaud""" __email__ = "pierrick.rambaud49@gmail.com" __version__ = "2.9.4" + +color = SepalColor() +'color: the colors of sepal. members are in the following list: "main, darker, bg, primary, accent, secondary, success, info, warning, error, menu". They will render according to the selected theme.' diff --git a/sepal_ui/aoi/aoi_model.py b/sepal_ui/aoi/aoi_model.py index 330e4bfd..fb856a77 100644 --- a/sepal_ui/aoi/aoi_model.py +++ b/sepal_ui/aoi/aoi_model.py @@ -10,7 +10,7 @@ from ipyleaflet import GeoJSON from traitlets import Any from sepal_ui import color -from sepal_ui.frontend.styles import AOI_STYLE +from sepal_ui.frontend import styles as ss from sepal_ui.message import ms from sepal_ui.model import Model from sepal_ui.scripts import gee @@ -619,7 +619,8 @@ class AoiModel(Model): f["properties"]["name"] = self.name # adapt the style to the theme - style = {**AOI_STYLE, "color": color.success, "fillColor": color.success} + style = json.loads((ss.JSON_DIR / "aoi.json").read_text()) + style.update(color=color.success, fillColor=color.success) # create a GeoJSON object self.ipygeojson = GeoJSON( diff --git a/sepal_ui/frontend/json/aoi.json b/sepal_ui/frontend/json/aoi.json new file mode 100644 index 00000000..af272ded --- /dev/null +++ b/sepal_ui/frontend/json/aoi.json @@ -0,0 +1,9 @@ +{ + "stroke": true, + "color": "grey", + "weight": 2, + "opacity": 1, + "fill": true, + "fillColor": "grey", + "fillOpacity": 0.4 +} \ No newline at end of file diff --git a/sepal_ui/frontend/json/file_icons.json b/sepal_ui/frontend/json/file_icons.json new file mode 100644 index 00000000..2b140fd1 --- /dev/null +++ b/sepal_ui/frontend/json/file_icons.json @@ -0,0 +1,12 @@ +{ + "": {"color": ["#ffca28", "#ffc107"], "icon": "far fa-folder"}, + ".csv": {"color": ["#4caf50", "#00c853"], "icon": "far fa-table"}, + ".txt": {"color": ["#4caf50", "#00c853"], "icon": "far fa-table"}, + ".tif": {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-image"}, + ".tiff": {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-image"}, + ".vrt": {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-image"}, + ".shp": {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-vector-square"}, + ".geojson": {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-vector-square"}, + "DEFAULT": {"color": ["#00bcd4", "#03a9f4"], "icon": "far fa-file"}, + "PARENT": {"color": ["#424242", "#ffffff"], "icon": "far fa-folder-open"} +} \ No newline at end of file diff --git a/sepal_ui/frontend/json/layer.json b/sepal_ui/frontend/json/layer.json new file mode 100644 index 00000000..9976aff6 --- /dev/null +++ b/sepal_ui/frontend/json/layer.json @@ -0,0 +1,7 @@ +{ + "stroke": true, + "weight": 2, + "opacity": 1, + "fill": true, + "fillOpacity": 0 +} \ No newline at end of file diff --git a/sepal_ui/frontend/json/layer_hover.json b/sepal_ui/frontend/json/layer_hover.json new file mode 100644 index 00000000..c6b7ff45 --- /dev/null +++ b/sepal_ui/frontend/json/layer_hover.json @@ -0,0 +1,7 @@ +{ + "stroke": true, + "weight": 5, + "opacity": 1, + "fill": true, + "fillOpacity": 0 +} \ No newline at end of file diff --git a/sepal_ui/frontend/json/map_btn.json b/sepal_ui/frontend/json/map_btn.json new file mode 100644 index 00000000..79817a81 --- /dev/null +++ b/sepal_ui/frontend/json/map_btn.json @@ -0,0 +1,6 @@ +{ + "padding": "0px", + "min-width": "0px", + "width": "30px", + "height": "30px" +} \ No newline at end of file diff --git a/sepal_ui/frontend/json/progress_bar.json b/sepal_ui/frontend/json/progress_bar.json new file mode 100644 index 00000000..ef7461ef --- /dev/null +++ b/sepal_ui/frontend/json/progress_bar.json @@ -0,0 +1,3 @@ +{ + "color": ["#2196f3", "#3f51b5"] +} \ No newline at end of file diff --git a/sepal_ui/frontend/styles.py b/sepal_ui/frontend/styles.py index 97a03dde..a8bfff93 100644 --- a/sepal_ui/frontend/styles.py +++ b/sepal_ui/frontend/styles.py @@ -8,6 +8,26 @@ from traitlets import Bool, HasTraits, Unicode, observe import sepal_ui.scripts.utils as su from sepal_ui import config +################################################################################ +# access the folders where style information is stored (layers, widgets) +# + +# the colors are set using tables as follow. +# 1 (True): dark theme +# 0 (false): light theme +JSON_DIR = Path(__file__).parent / "json" +"pathlib.Path: the path to the json style folder" + +CSS_DIR = Path(__file__).parent / "css" +"pathlib.Path: the path to the css style folder" + +JS_DIR = Path(__file__).parent / "js" +"pathlib.Path: the path to the js style folder" + +################################################################################ +# define all the colors taht we want to use in the theme +# + DARK_THEME = { "primary": "#b3842e", "accent": "#a1458e", @@ -21,6 +41,7 @@ DARK_THEME = { "bg": "#121212", # Are not traits "menu": "#424242", # Are not traits } +"dict: colors used for the dark theme" LIGHT_THEME = { "primary": v.theme.themes.light.primary, @@ -35,17 +56,19 @@ LIGHT_THEME = { "bg": "#FFFFFF", "menu": "#FFFFFF", } +"dict: colors used for the light theme" +TYPES = ("info", "primary", "secondary", "accent", "error", "success", "warning", "anchor") # fmt: skip +"tuple: the different types defined by ipyvuetify" -if not DARK_THEME.keys() == LIGHT_THEME.keys(): - raise Exception("Both dictionaries has to have the same color names") +################################################################################ +# define classes and method to make the application resonsive +# def get_theme(): """ get theme name from the config file (default to dark) - Args: - Return: (str): the theme to use """ @@ -53,10 +76,11 @@ def get_theme(): class SepalColor(HasTraits, SimpleNamespace): - """Custom simple name space to store and access to the sepal_ui colors and - with a magic method to display theme.""" + """ + Custom simple name space to store and access to the sepal_ui colors and + with a magic method to display theme. + """ - # Initialize with the current theme _dark_theme = Bool(True if get_theme() == "dark" else False).tag(sync=True) "bool: whether to use dark theme or not. By changing this value, the theme value will be stored in the conf file. Is only intended to be accessed in development mode." @@ -117,10 +141,6 @@ class SepalColor(HasTraits, SimpleNamespace): return html -color = SepalColor() -'color: the colors of sepal. members are in the following list: "main, darker, bg, primary, accent, secondary, success, info, warning, error, menu". They will render according to the selected theme.' - - class Styles(v.VuetifyTemplate): """ Fixed styles to fix display issues in the lib: @@ -132,7 +152,7 @@ class Styles(v.VuetifyTemplate): - ensure that tqdm bars are using a transparent background when displayed in an alert """ - css = (Path(__file__).parent / "css/custom.css").read_text() + css = (CSS_DIR / "custom.css").read_text() cdn = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" template = Unicode( f'<style>{css}</style><link rel="stylesheet" href="{cdn}"/>' @@ -142,83 +162,3 @@ class Styles(v.VuetifyTemplate): styles = Styles() display(styles) - -# default styling of the aoi layer -AOI_STYLE = { - "stroke": True, - "color": "grey", - "weight": 2, - "opacity": 1, - "fill": True, - "fillColor": "grey", - "fillOpacity": 0.4, -} - -# the colors are set as follow. -# 1 (True): dark theme -# 0 (false): light theme -# This will need to be changed if we want to support more than 2 theme -COMPONENTS = { - "PROGRESS_BAR": { - "color": ["#2196f3", "#3f51b5"], - } -} - -_folder = {"color": ["#ffca28", "#ffc107"], "icon": "far fa-folder"} -_table = {"color": ["#4caf50", "#00c853"], "icon": "far fa-table"} -_vector = {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-vector-square"} -_other = {"color": ["#00bcd4", "#03a9f4"], "icon": "far fa-file"} -_parent = {"color": ["#424242", "#ffffff"], "icon": "far fa-folder-open"} -_image = {"color": ["#9c27b0", "#673ab7"], "icon": "far fa-image"} - -ICON_TYPES = { - "": _folder, - ".csv": _table, - ".txt": _table, - ".tif": _image, - ".tiff": _image, - ".vrt": _image, - ".shp": _vector, - ".geojson": _vector, - "DEFAULT": _other, - "PARENT": _parent, -} - -TYPES = ( - "info", - "primary", - "secondary", - "accent", - "error", - "success", - "warning", - "anchor", -) - -# Default styles to GeoJSON layers added to a SepalMap. - -layer_style = { - "stroke": True, - "color": color.primary, - "weight": 2, - "opacity": 1, - "fill": True, - "fillOpacity": 0, -} - -layer_hover_style = { - "stroke": True, - "color": color.primary, - "weight": 5, - "opacity": 1, - "fill": True, - "fillOpacity": 0, -} - -map_btn_style = { - "padding": "0px", - "min-width": "0px", - "width": "30px", - "height": "30px", - "background": color.bg, -} diff --git a/sepal_ui/mapping/map_btn.py b/sepal_ui/mapping/map_btn.py index 0ea13364..109f13ee 100644 --- a/sepal_ui/mapping/map_btn.py +++ b/sepal_ui/mapping/map_btn.py @@ -1,7 +1,10 @@ +import json + import ipyvuetify as v +from sepal_ui import color from sepal_ui import sepalwidgets as sw -from sepal_ui.frontend.styles import map_btn_style +from sepal_ui.frontend import styles as ss class MapBtn(v.Btn, sw.SepalWidget): @@ -22,10 +25,14 @@ class MapBtn(v.Btn, sw.SepalWidget): else: content = content[: min(3, len(content))].upper() + # create the style from default + style = json.loads((ss.JSON_DIR / "map_btn.json").read_text()) + style.update(background=color.bg) + # some parameters are overloaded to match the map requirements kwargs["color"] = "text-color" kwargs["outlined"] = True - kwargs["style_"] = " ".join([f"{k}: {v};" for k, v in map_btn_style.items()]) + kwargs["style_"] = " ".join([f"{k}: {v};" for k, v in style.items()]) kwargs["children"] = [content] kwargs["icon"] = False diff --git a/sepal_ui/mapping/sepal_map.py b/sepal_ui/mapping/sepal_map.py index 4ef41d1a..f746a72c 100644 --- a/sepal_ui/mapping/sepal_map.py +++ b/sepal_ui/mapping/sepal_map.py @@ -6,6 +6,7 @@ if "GDAL_DATA" in list(os.environ.keys()): if "PROJ_LIB" in list(os.environ.keys()): del os.environ["PROJ_LIB"] +import json import math import random import string @@ -27,7 +28,8 @@ from matplotlib import colorbar from matplotlib import colors as mpc from rasterio.crs import CRS -import sepal_ui.frontend.styles as styles +from sepal_ui import color +from sepal_ui.frontend import styles as ss from sepal_ui.mapping.basemaps import basemap_tiles from sepal_ui.mapping.draw_control import DrawControl from sepal_ui.mapping.layer import EELayer @@ -775,8 +777,18 @@ class SepalMap(ipl.Map): # apply default coloring for geoJson if isinstance(layer, ipl.GeoJSON): - layer.style = layer.style or styles.layer_style - hover_style = styles.layer_hover_style if hover else layer.hover_style + + # define the default values + default_style = json.loads((ss.JSON_DIR / "layer.json").read_text()) + default_style.update(color=color.primary) + default_hover_style = json.loads( + (ss.JSON_DIR / "layer_hover.json").read_text() + ) + default_hover_style.update(color=color.primary) + + # apply the style depending on the parameters + layer.style = layer.style or default_style + hover_style = default_hover_style if hover else layer.hover_style layer.hover_style = layer.hover_style or hover_style super().add_layer(layer) diff --git a/sepal_ui/mapping/value_inspector.py b/sepal_ui/mapping/value_inspector.py index 96508ba3..8149a078 100644 --- a/sepal_ui/mapping/value_inspector.py +++ b/sepal_ui/mapping/value_inspector.py @@ -1,3 +1,5 @@ +import json + import ee import geopandas as gpd import ipyvuetify as v @@ -10,7 +12,7 @@ from shapely import geometry as sg from sepal_ui import color from sepal_ui import sepalwidgets as sw -from sepal_ui.frontend.styles import COMPONENTS +from sepal_ui.frontend import styles as ss from sepal_ui.mapping.layer import EELayer from sepal_ui.mapping.map_btn import MapBtn from sepal_ui.message import ms @@ -47,10 +49,11 @@ class ValueInspector(WidgetControl): # create a loading to place it on top of the card. It will always be visible # even when the card is scrolled + p_style = json.loads((ss.JSON_DIR / "progress_bar.json").read_text()) self.w_loading = sw.ProgressLinear( indeterminate=False, background_color=color.menu, - color=COMPONENTS["PROGRESS_BAR"]["color"][v.theme.dark], + color=p_style["color"][v.theme.dark], ) # create a clickable btn diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py index 6ad4d5d0..f80b20ef 100644 --- a/sepal_ui/sepalwidgets/alert.py +++ b/sepal_ui/sepalwidgets/alert.py @@ -6,7 +6,8 @@ from ipywidgets import Output, jslink from tqdm.notebook import tqdm from traitlets import Bool, Unicode, directional_link, observe -from sepal_ui.frontend.styles import TYPES, color +from sepal_ui import color +from sepal_ui.frontend.styles import TYPES from sepal_ui.message import ms from sepal_ui.scripts import utils as su from sepal_ui.scripts.utils import set_type diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 38ffef00..438238e1 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -1,3 +1,4 @@ +import json from datetime import datetime from pathlib import Path @@ -10,7 +11,7 @@ from natsort import humansorted from traitlets import Any, Bool, Dict, Int, List, Unicode, link, observe from sepal_ui import color -from sepal_ui.frontend.styles import COMPONENTS, ICON_TYPES +from sepal_ui.frontend import styles as ss from sepal_ui.message import ms from sepal_ui.scripts import gee from sepal_ui.scripts import utils as su @@ -193,6 +194,9 @@ class FileInput(v.Flex, SepalWidget): v_model = Unicode(None, allow_none=True).tag(sync=True) "str: the v_model of the input" + ICON_STYLE = json.loads((ss.JSON_DIR / "file_icons.json").read_text()) + "dict: the style applied to the icons in the file menu" + def __init__( self, extentions=[], @@ -216,10 +220,11 @@ class FileInput(v.Flex, SepalWidget): v_model=None, ) + p_style = json.loads((ss.JSON_DIR / "progress_bar.json").read_text()) self.loading = v.ProgressLinear( indeterminate=False, background_color=color.menu, - color=COMPONENTS["PROGRESS_BAR"]["color"][v.theme.dark], + color=p_style["color"][v.theme.dark], ) self.file_list = v.List( @@ -376,14 +381,14 @@ class FileInput(v.Flex, SepalWidget): for el in list_dir: if el.is_dir(): - icon = ICON_TYPES[""]["icon"] - color = ICON_TYPES[""]["color"][v.theme.dark] - elif el.suffix in ICON_TYPES.keys(): - icon = ICON_TYPES[el.suffix]["icon"] - color = ICON_TYPES[el.suffix]["color"][v.theme.dark] + icon = self.ICON_STYLE[""]["icon"] + color = self.ICON_STYLE[""]["color"][v.theme.dark] + elif el.suffix in self.ICON_STYLE.keys(): + icon = self.ICON_STYLE[el.suffix]["icon"] + color = self.ICON_STYLE[el.suffix]["color"][v.theme.dark] else: - icon = ICON_TYPES["DEFAULT"]["icon"] - color = ICON_TYPES["DEFAULT"]["color"][v.theme.dark] + icon = self.ICON_STYLE["DEFAULT"]["icon"] + color = self.ICON_STYLE["DEFAULT"]["color"][v.theme.dark] children = [ v.ListItemAction(children=[v.Icon(color=color, children=[icon])]), @@ -410,8 +415,8 @@ class FileInput(v.Flex, SepalWidget): v.ListItemAction( children=[ v.Icon( - color=ICON_TYPES["PARENT"]["color"][v.theme.dark], - children=[ICON_TYPES["PARENT"]["icon"]], + color=self.ICON_STYLE["PARENT"]["color"][v.theme.dark], + children=[self.ICON_STYLE["PARENT"]["icon"]], ) ] ),
add TYPES to documentation don't haw to deal with variables yet
12rambau/sepal_ui
diff --git a/tests/test_SepalMap.py b/tests/test_SepalMap.py index 30a0d3eb..438ffa7a 100644 --- a/tests/test_SepalMap.py +++ b/tests/test_SepalMap.py @@ -1,3 +1,4 @@ +import json import math import random from pathlib import Path @@ -7,9 +8,9 @@ import ee import pytest from ipyleaflet import GeoJSON, LocalTileLayer -import sepal_ui.frontend.styles as styles from sepal_ui import get_theme from sepal_ui import mapping as sm +from sepal_ui.frontend import styles as ss # create a seed so that we can check values random.seed(42) @@ -289,8 +290,11 @@ class TestSepalMap: # Assert new_layer = m.layers[-1] - assert new_layer.style == styles.layer_style - assert new_layer.hover_style == styles.layer_hover_style + layer_style = json.loads((ss.JSON_DIR / "layer.json").read_text()) + hover_style = json.loads((ss.JSON_DIR / "layer_hover.json").read_text()) + + assert all([new_layer.style[k] == v for k, v in layer_style.items()]) + assert all([new_layer.hover_style[k] == v for k, v in hover_style.items()]) # Arrange with style layer_style = {"color": "blue"} diff --git a/tests/test_style.py b/tests/test_style.py new file mode 100644 index 00000000..a52c5f5e --- /dev/null +++ b/tests/test_style.py @@ -0,0 +1,19 @@ +from sepal_ui.frontend import styles as ss + + +class TestStyle: + def test_folders(self): + + assert ss.JSON_DIR.is_dir() + assert ss.CSS_DIR.is_dir() + assert ss.JS_DIR.is_dir() + + return + + def test_colors(self): + + # test that colors have the same size and names + assert len(ss.DARK_THEME.keys()) == len(ss.LIGHT_THEME.keys()) + assert all(dc in ss.LIGHT_THEME.keys() for dc in ss.DARK_THEME.keys()) + + return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 8 }
2.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 fsspec==2025.3.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==1.5.2 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest==8.3.5 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-futures==0.9.9 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@7710c4abf8f0dfa916a4933c766ab6203bf3a76e#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 xyzservices==2025.1.0 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - fsspec==2025.3.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==1.5.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pytest==8.3.5 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-futures==0.9.9 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - xyzservices==2025.1.0 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_style.py::TestStyle::test_folders" ]
[ "tests/test_SepalMap.py::TestSepalMap::test_init", "tests/test_SepalMap.py::TestSepalMap::test_set_center", "tests/test_SepalMap.py::TestSepalMap::test_zoom_bounds", "tests/test_SepalMap.py::TestSepalMap::test_add_colorbar", "tests/test_SepalMap.py::TestSepalMap::test_add_ee_layer", "tests/test_SepalMap.py::TestSepalMap::test_get_basemap_list", "tests/test_SepalMap.py::TestSepalMap::test_get_viz_params", "tests/test_SepalMap.py::TestSepalMap::test_add_layer", "tests/test_SepalMap.py::TestSepalMap::test_add_basemap", "tests/test_SepalMap.py::TestSepalMap::test_get_scale", "tests/test_SepalMap.py::TestSepalMap::test_zoom_raster" ]
[ "tests/test_style.py::TestStyle::test_colors" ]
[]
MIT License
null
null
12rambau__sepal_ui-535
6a619361e90ab318463e2094fc9dbcbc85dd2e8f
2022-07-06 13:02:30
114063b50ee5b1ccbab680424bb048e11939b870
diff --git a/sepal_ui/mapping/sepal_map.py b/sepal_ui/mapping/sepal_map.py index 57693e56..e2860daf 100644 --- a/sepal_ui/mapping/sepal_map.py +++ b/sepal_ui/mapping/sepal_map.py @@ -227,8 +227,8 @@ class SepalMap(ipl.Map): # Center map to the centroid of the layer(s) self.center = [(maxy - miny) / 2 + miny, (maxx - minx) / 2 + minx] - # create the tuples for each corner - tl, br, bl, tr = (minx, maxy), (maxx, miny), (minx, miny), (maxx, maxy) + # create the tuples for each corner in (lat/lng) convention + tl, br, bl, tr = (maxy, minx), (miny, maxx), (miny, minx), (maxy, maxx) # find zoom level to display the biggest diagonal (in km) lg, zoom = 40075, 1 # number of displayed km at zoom 1 diff --git a/sepal_ui/message/en/locale.json b/sepal_ui/message/en/locale.json index 5989dee5..b689db70 100644 --- a/sepal_ui/message/en/locale.json +++ b/sepal_ui/message/en/locale.json @@ -37,7 +37,6 @@ "custom": "Custom", "no_access": "It seems like you do not have access to the input asset or it does not exist.", "wrong_type": "The type of the selected asset ({}) does not match authorized asset type ({}).", - "hint": "Select an asset in the list or write a custom asset name. Be careful, you need to have access to this asset to use it", "placeholder": "users/custom_user/custom_asset" }, "load_table": { @@ -65,20 +64,6 @@ "asset": "GEE Asset name", "btn": "Select AOI", "complete": "The AOI has been selected", - "shape_drawn": "A shape has been drawn", - "file_pattern": "aoi_{}", - "no_selection": "No selection method has been picked up", - "no_country": "No Country has been selected", - "asset_already_exist": "The asset was already existing you can continue to use it. It's also available at :{}", - "asset_created": "The asset has been created under the name : {}", - "name_used": "The name was already in used, change it or delete the previous asset in your GEE acount", - "no_asset": "No Asset has been provided", - "check_if_asset": "Check carefully that your string is an assetId", - "not_available": "This function is not yet available", - "no_shape": "No shape has been drawn on the map", - "shp_error": "An error occured with provided .shp file", - "aoi_message": "click on \"selet these inputs\" to validate your AOI", - "geojson_to_ee": "Convert your .csv file into a ee_object", "exception" : { "no_inputs": "Please provide fully qualified inputs before validating your AOI", "no_asset" : "Please select an asset.", @@ -98,7 +83,6 @@ "planet" : { "exception" : { "empty": "Please fill the required field(s).", - "format" : "Please check the format of your inputs.", "invalid" : "Invalid email or password", "nosubs" : "Your credentials do not have any valid planet subscription." }, @@ -143,7 +127,7 @@ "0": "New element", "1": "Modify element" }, - "btn": { + "btn": { "save": { "name": "save", "tooltip": "create new class" diff --git a/sepal_ui/reclassify/table_view.py b/sepal_ui/reclassify/table_view.py index 0f8bf1cd..c3f8a35a 100644 --- a/sepal_ui/reclassify/table_view.py +++ b/sepal_ui/reclassify/table_view.py @@ -212,15 +212,24 @@ class EditDialog(v.Dialog): self.title = v.CardTitle(children=[self.TITLES[0]]) # Action buttons - btn_txt = ms.rec.table.edit_dialog.btn - self.save = sw.Btn(btn_txt.save.name) - save_tool = sw.Tooltip(self.save, btn_txt.save.tooltip, bottom=True) + self.save = sw.Btn(ms.rec.table.edit_dialog.btn.save.name) + save_tool = sw.Tooltip( + self.save, ms.rec.table.edit_dialog.btn.save.tooltip, bottom=True + ) - self.modify = sw.Btn(btn_txt.modify.name).hide() # by default modify is hidden - modify_tool = sw.Tooltip(self.modify, btn_txt.modify.tooltip, bottom=True) + self.modify = sw.Btn( + ms.rec.table.edit_dialog.btn.modify.name + ).hide() # by default modify is hidden + modify_tool = sw.Tooltip( + self.modify, ms.rec.table.edit_dialog.btn.modify.tooltip, bottom=True + ) - self.cancel = sw.Btn(btn_txt.cancel.name, outlined=True, class_="ml-2") - cancel_tool = sw.Tooltip(self.cancel, btn_txt.cancel.tooltip, bottom=True) + self.cancel = sw.Btn( + ms.rec.table.edit_dialog.btn.cancel.name, outlined=True, class_="ml-2" + ) + cancel_tool = sw.Tooltip( + self.cancel, ms.rec.table.edit_dialog.btn.cancel.tooltip, bottom=True + ) actions = v.CardActions(children=[save_tool, modify_tool, cancel_tool]) diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py index 6d869aaa..e143170e 100644 --- a/sepal_ui/sepalwidgets/alert.py +++ b/sepal_ui/sepalwidgets/alert.py @@ -380,8 +380,11 @@ class Banner(v.Snackbar, SepalWidget): Args: nb_banner (int): the number of banners in the queue """ - msg = ms.widgets.banner - txt = msg.close if nb_banner == 0 else msg.next.format(nb_banner) + # do not wrap ms.widget.banner. If you do it won't be recognized by the key-checker of the Translator + if nb_banner == 0: + txt = ms.widgets.banner.close + else: + txt = ms.widgets.banner.next.format(nb_banner) self.btn_close.children = [txt] return diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py index 5cf26320..f3a4b791 100644 --- a/sepal_ui/translator/translator.py +++ b/sepal_ui/translator/translator.py @@ -3,6 +3,7 @@ from collections import abc from configparser import ConfigParser from pathlib import Path +import pandas as pd from box import Box from deprecated.sphinx import deprecated, versionadded @@ -262,3 +263,58 @@ class Translator(Box): del d[k] return d + + @versionadded(version="2.10.0") + def key_use(self, folder, name): + """ + Parse all the files in the folder and check if keys are all used at least once. + Return the unused key names. + + .. warning:: + + Don't forget that there are many ways of calling Translator variables + (getattr, save.cm.xxx in another variable etc...) SO don't forget to check + manually the variables suggested by this method before deleting them + + Args: + folder (pathlib.Path): The application folder using this translator data + name (str): the name use by the translator in this app (usually "cm") + + Return: + (list): the list of unused keys + """ + # cannot set FORBIDDEN_KEY in the Box as it would lock another key + FORBIDDEN_KEYS = ["_folder", "_default", "_target", "_targeted", "_match"] + + # sanitize folder + folder = Path(folder) + + # get all the python files recursively + py_files = [ + f for f in folder.glob("**/*.py") if ".ipynb_checkpoints" not in str(f) + ] + + # get the flat version of all keys + keys = list(set(pd.json_normalize(self).columns) ^ set(FORBIDDEN_KEYS)) + + # init the unused keys list + unused_keys = [] + + for k in keys: + + # by default we consider that the is never used + is_present = False + + # read each python file and search for the pattern of the key + # if it's find change status of the counter and exit the search + for f in py_files: + tmp = f.read_text() + if f"{name}.{k}" in tmp: + is_present = True + break + + # if nothing is find, the value is still False and the key can be + # added to the list + is_present or unused_keys.append(k) + + return unused_keys
create a translator function to check the use of the keys If you are updating many time the same application you may end up removing some or all the existing keys. It complex to visually assess if all the remaining keys in the dict are used. Maybe a parser could be interesting to check all the folder files and validate the keys that are used. Usage will be of course for developer only
12rambau/sepal_ui
diff --git a/tests/test_Translator.py b/tests/test_Translator.py index 7c8e7242..48d34519 100644 --- a/tests/test_Translator.py +++ b/tests/test_Translator.py @@ -6,6 +6,7 @@ from pathlib import Path import pytest from sepal_ui import config_file +from sepal_ui.message import ms from sepal_ui.translator import Translator @@ -121,6 +122,16 @@ class TestTranslator: return + def test_key_use(self): + + # check key usage method and the lib content at the same time + expected = ["test_key"] + lib_folder = Path(__file__).parents[1] + res = ms.key_use(lib_folder, "ms") + assert res == expected + + return + @pytest.fixture(scope="class") def translation_folder(self): """
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 5 }
2.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 fsspec==2025.3.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 haversine==2.9.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipyleaflet==0.19.2 ipyspin==1.0.1 ipython==8.12.3 ipython-genutils==0.2.0 ipyurl==0.1.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==7.8.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyter_server_xarray_leaflet==0.2.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mercantile==1.2.1 mistune==3.1.3 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==1.5.2 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-futures==0.9.9 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@6a619361e90ab318463e2094fc9dbcbc85dd2e8f#egg=sepal_ui shapely==2.0.7 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==3.6.10 wrapt==1.17.2 xarray==2024.7.0 xarray_leaflet==0.2.3 xyzservices==2025.1.0 yarg==0.1.9 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - fsspec==2025.3.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - haversine==2.9.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipyspin==1.0.1 - ipython==8.12.3 - ipython-genutils==0.2.0 - ipyurl==0.1.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==7.8.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyter-server-xarray-leaflet==0.2.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mercantile==1.2.1 - mistune==3.1.3 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==1.5.2 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-futures==0.9.9 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==3.6.10 - wrapt==1.17.2 - xarray==2024.7.0 - xarray-leaflet==0.2.3 - xyzservices==2025.1.0 - yarg==0.1.9 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Translator.py::TestTranslator::test_key_use" ]
[]
[ "tests/test_Translator.py::TestTranslator::test_init", "tests/test_Translator.py::TestTranslator::test_search_key", "tests/test_Translator.py::TestTranslator::test_sanitize", "tests/test_Translator.py::TestTranslator::test_delete_empty", "tests/test_Translator.py::TestTranslator::test_find_target", "tests/test_Translator.py::TestTranslator::test_available_locales" ]
[]
MIT License
null
null
12rambau__sepal_ui-571
412e02ef08df68c256f384081d2c7eaecc09428e
2022-08-11 17:01:29
8c50a7f032daafcbf7cfb6dc16d5d421f02a32e5
diff --git a/.cz.yaml b/.cz.yaml index 05742add..c2d69e89 100644 --- a/.cz.yaml +++ b/.cz.yaml @@ -3,7 +3,7 @@ commitizen: changelog_incremental: true tag_format: v_$major.$minor.$patch$prerelease update_changelog_on_bump: true - version: 2.10.3 + version: 2.10.2 version_files: - setup.py:version - sepal_ui/__init__.py:__version__ diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index ffeb0434..89744741 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -30,10 +30,6 @@ jobs: python -m pip install --upgrade pip pip install --find-links=https://girder.github.io/large_image_wheels --no-cache GDAL - - name: Install localetileserver - run: | - pip install localtileserver - - name: Install dependencies run: pip install .[test] diff --git a/CHANGELOG.md b/CHANGELOG.md index ab8a7927..fb338910 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,3 @@ -## v_2.10.3 (2022-08-10) - -### Fix - -- lazy import localtileserver -- avoid reloading root when fileinput is already none - -### Refactor - -- .. spelling:word-list:: -- reset method -- remove legacy print - ## v_2.10.2 (2022-07-28) ### Fix diff --git a/sepal_ui/__init__.py b/sepal_ui/__init__.py index 0f65dc57..64d44a80 100644 --- a/sepal_ui/__init__.py +++ b/sepal_ui/__init__.py @@ -5,7 +5,7 @@ from sepal_ui.frontend.styles import SepalColor, get_theme __author__ = """Pierrick Rambaud""" __email__ = "pierrick.rambaud49@gmail.com" -__version__ = "2.10.3" +__version__ = "2.10.2" color = SepalColor() 'color: the colors of sepal. members are in the following list: "main, darker, bg, primary, accent, secondary, success, info, warning, error, menu". They will render according to the selected theme.' diff --git a/sepal_ui/mapping/__init__.py b/sepal_ui/mapping/__init__.py index 78835859..b178a82b 100644 --- a/sepal_ui/mapping/__init__.py +++ b/sepal_ui/mapping/__init__.py @@ -3,6 +3,7 @@ from .draw_control import * from .fullscreen_control import * from .layer import * from .layer_state_control import * +from .legend_control import * from .map_btn import * from .menu_control import * from .sepal_map import * diff --git a/sepal_ui/mapping/legend_control.py b/sepal_ui/mapping/legend_control.py new file mode 100644 index 00000000..de367c3c --- /dev/null +++ b/sepal_ui/mapping/legend_control.py @@ -0,0 +1,158 @@ +from ipyleaflet import WidgetControl +from ipywidgets import HTML +from traitlets import Bool, Dict, Unicode, observe + +import sepal_ui.sepalwidgets as sw +from sepal_ui.message import ms +from sepal_ui.scripts import utils as su + + +class LegendControl(WidgetControl): + """ + A custom Legend widget ready to be embed in a map + + This Legend can be control though it's different attributes, changin it's position of course but also the orientation ,the keys and their colors. + + .. versionadded:: 2.10.4 + + Args: + legend_dict (dict): the dictionnary to fill the legend values. cannot be empty. + title (str) title of the legend, if not set a default value in the current language will be used + vertical (bool): the orientation of the legend. default to True + """ + + title = Unicode(None).tag(sync=True) + "Unicode: title of the legend." + + legend_dict = Dict(None).tag(sync=True) + "Dict: dictionary with key as label name and value as color" + + vertical = Bool(None).tag(sync=True) + "Bool: whether to display the legend in a vertical or horizontal way" + + _html_table = None + + _html_title = None + + def __init__( + self, legend_dict={}, title=ms.mapping.legend, vertical=True, **kwargs + ): + + # init traits + self.title = title + self.legend_dict = legend_dict + self.vertical = vertical + + # generate the content based on the init options + self._html_title = sw.Html(tag="h4", children=[f"{self.title}"]) + self._html_table = sw.Html(tag="table", children=[]) + + # create a card inside the widget + # Be sure that the scroll bar will be shown up when legend horizontal + self.legend_card = sw.Card( + attributes={"id": "legend_card"}, + style_="overflow-x:auto; white-space: nowrap;", + max_width=450, + max_height=350, + children=[self._html_title, self._html_table], + ).hide() + + # set some parameters for the actual widget + kwargs["widget"] = self.legend_card + kwargs["position"] = kwargs.pop("position", "bottomright") + + super().__init__(**kwargs) + + self._set_legend(legend_dict) + + def __len__(self): + """returns the number of elements in the legend""" + + return len(self.legend_dict) + + def hide(self): + """Hide control by hiding its content""" + self.legend_card.hide() + + def show(self): + """Show control by displaying its content""" + self.legend_card.show() + + @observe("legend_dict", "vertical") + def _set_legend(self, _): + """Creates/update a legend based on the class legend_dict member""" + + # Do this to avoid crash when called by trait for the first time + if self._html_table is None: + return + + if not self.legend_dict: + self.hide() + return + + self.show() + + if self.vertical: + elements = [ + sw.Html( + tag="tr" if self.vertical else "td", + children=[ + sw.Html(tag="td", children=self.color_box(color)), + label.capitalize(), + ], + ) + for label, color in self.legend_dict.items() + ] + else: + elements = [ + ( + sw.Html( + tag="td", + children=[label.capitalize()], + ), + sw.Html( + tag="td", + children=self.color_box(color), + ), + ) + for label, color in self.legend_dict.items() + ] + # Flat nested list + elements = [e for row in elements for e in row] + + self._html_table.children = elements + + return + + @observe("title") + def _update_title(self, change): + """Trait method to update the title of the legend""" + + # Do this to avoid crash when called by trait + if self._html_title is None: + return + + self._html_title.children = change["new"] + + return + + @staticmethod + def color_box(color, size=35): + """Returns an rectangular SVG html element with the provided color""" + + # Define height and width based on the size + w = size + h = size / 2 + + return [ + HTML( + f""" + <th> + <svg width='{w}' height='{h}'> + <rect width='{w}' height='{h}' style='fill:{su.to_colors(color)}; + stroke-width:1;stroke:rgb(255,255,255)'/> + </svg> + </th> + """ + ) + ] diff --git a/sepal_ui/mapping/sepal_map.py b/sepal_ui/mapping/sepal_map.py index 6d2690ad..004c4360 100644 --- a/sepal_ui/mapping/sepal_map.py +++ b/sepal_ui/mapping/sepal_map.py @@ -33,6 +33,7 @@ from sepal_ui.mapping.basemaps import basemap_tiles from sepal_ui.mapping.draw_control import DrawControl from sepal_ui.mapping.layer import EELayer from sepal_ui.mapping.layer_state_control import LayerStateControl +from sepal_ui.mapping.legend_control import LegendControl from sepal_ui.mapping.value_inspector import ValueInspector from sepal_ui.message import ms from sepal_ui.scripts import utils as su @@ -859,6 +860,28 @@ class SepalMap(ipl.Map): return layer + def add_legend( + self, + title=ms.mapping.legend, + legend_dict={}, + position="bottomright", + vertical=True, + ): + """ + Creates and adds a custom legend as widget control to the map + + Args: + title (str, optional): Title of the legend. Defaults to 'Legend'. + legend_dict (dict): dictionary with key as label name and value as color + """ + + # Define as class member so it can be accessed from outside. + self.legend = LegendControl( + legend_dict, title=title, vertical=vertical, position=position + ) + + return self.add_control(self.legend) + # ########################################################################## # ### overwrite geemap calls ### # ########################################################################## diff --git a/sepal_ui/message/en/locale.json b/sepal_ui/message/en/locale.json index b689db70..247d226f 100644 --- a/sepal_ui/message/en/locale.json +++ b/sepal_ui/message/en/locale.json @@ -78,7 +78,8 @@ } }, "mapping": { - "no_image": "The image file does not exist." + "no_image": "The image file does not exist.", + "legend" : "Legend" }, "planet" : { "exception" : { diff --git a/setup.py b/setup.py index 89750b43..f259be17 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from subprocess import check_call from setuptools import setup from setuptools.command.develop import develop -version = "2.10.3" +version = "2.10.2" DESCRIPTION = "Wrapper for ipyvuetify widgets to unify the display of voila dashboards in SEPAL platform" LONG_DESCRIPTION = open("README.rst").read() @@ -69,6 +69,7 @@ setup_params = { "pyyaml", "dask", "tqdm", + "localtileserver", "jupyter-server-proxy", "matplotlib", "rioxarray",
add_legend feature Now, as we got rid of the geemap library, one important and missing feature is `add_legend`, would be nice to get it back natively.
12rambau/sepal_ui
diff --git a/tests/test_LegendControl.py b/tests/test_LegendControl.py new file mode 100644 index 00000000..142cdce7 --- /dev/null +++ b/tests/test_LegendControl.py @@ -0,0 +1,114 @@ +import re + +from sepal_ui.mapping import LegendControl + + +class TestLegend: + def test_init(self): + + legend_dict = { + "forest": "#b3842e", + "non forest": "#a1458e", + "secondary": "#324a88", + "success": "#3f802a", + "info": "#79b1c9", + "warning": "#b8721d", + } + + # hardcode expected + expected_labels = [ + "Forest", + "Non forest", + "Secondary", + "Success", + "Info", + "Warning", + ] + + legend = LegendControl(legend_dict, title="Legend") + + # Check all the default values + assert legend.title == "Legend" + assert legend._html_title.children[0] == "Legend" + assert legend.legend_dict == legend_dict + + # check all the labels and colors are present in the html + assert all([label in str(legend._html_table) for label in expected_labels]) + assert all([color in str(legend._html_table) for color in legend_dict.values()]) + + # Check the lenght + assert len(legend) == 6 + + return + + def test_set_legend(self): + + legend_dict = { + "forest": "#b3842e", + "info": "#79b1c9", + } + + legend = LegendControl(legend_dict) + + new_legend = { + "forest": "#b3842e", + "non forest": "#3f802a", + } + + # trigger the event + legend.legend_dict = new_legend + + assert legend.legend_dict == new_legend + + # Check that previous labels are not in the new legend + assert "Info" not in str(legend._html_table) + + # check all the new labels are present in the legend + assert all( + [label in str(legend._html_table) for label in ["Forest", "Non forest"]] + ) + + # Act: change the view + + # Check current view + assert legend.vertical is True + + # in the vertical view, there should be at least two rows + assert str(legend._html_table).count("'tr'") == 2 + + legend.vertical = False + assert str(legend._html_table).count("'tr'") == 0 + + return + + def test_update_title(self): + + legend_dict = { + "forest": "#b3842e", + "info": "#79b1c9", + } + + legend = LegendControl(legend_dict) + + legend.title = "leyenda" + + # Check all the default values + assert legend.title == "leyenda" + assert legend._html_title.children[0] == "leyenda" + + return + + def test_color_box(self): + + legend_dict = { + "forest": "#b3842e", + "info": "#79b1c9", + } + legend = LegendControl(legend_dict) + str_box = re.sub("[ ]+", "", str(legend.color_box("blue", 50)[0])) + + assert "fill:#0000ff" in str_box + assert "width='50'" in str_box + assert "'height='25.0'" in str_box + + return diff --git a/tests/test_SepalMap.py b/tests/test_SepalMap.py index 2ba4da45..7c4f1dc4 100644 --- a/tests/test_SepalMap.py +++ b/tests/test_SepalMap.py @@ -11,6 +11,7 @@ from ipyleaflet import GeoJSON from sepal_ui import get_theme from sepal_ui import mapping as sm from sepal_ui.frontend import styles as ss +from sepal_ui.mapping.legend_control import LegendControl # create a seed so that we can check values random.seed(42) @@ -387,6 +388,25 @@ class TestSepalMap: return + def test_add_legend(self, ee_map_with_layers): + + legend_dict = { + "forest": "#b3842e", + "non forest": "#a1458e", + "secondary": "#324a88", + "success": "#3f802a", + "info": "#79b1c9", + "warning": "#b8721d", + } + + ee_map_with_layers.add_legend(legend_dict=legend_dict) + + # just test that is a Legend, the rest is tested by Legend + assert isinstance(ee_map_with_layers.legend, LegendControl) + assert ee_map_with_layers.legend.legend_dict == legend_dict + + return + @pytest.fixture def rgb(self): """add a raster file of the bahamas coming from rasterio test suit"""
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 8 }
2.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "nbmake" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 haversine==2.9.0 httplib2==0.22.0 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbmake==1.5.5 nest-asyncio==1.6.0 nodeenv==1.9.1 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==1.5.2 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest==8.3.5 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-futures==0.9.9 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@412e02ef08df68c256f384081d2c7eaecc09428e#egg=sepal_ui shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==2.1.2 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - haversine==2.9.0 - httplib2==0.22.0 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbmake==1.5.5 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==1.5.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pytest==8.3.5 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-futures==0.9.9 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==2.1.2 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_LegendControl.py::TestLegend::test_init", "tests/test_LegendControl.py::TestLegend::test_set_legend", "tests/test_LegendControl.py::TestLegend::test_update_title", "tests/test_LegendControl.py::TestLegend::test_color_box" ]
[ "tests/test_SepalMap.py::TestSepalMap::test_init", "tests/test_SepalMap.py::TestSepalMap::test_set_center", "tests/test_SepalMap.py::TestSepalMap::test_zoom_bounds", "tests/test_SepalMap.py::TestSepalMap::test_add_raster", "tests/test_SepalMap.py::TestSepalMap::test_add_colorbar", "tests/test_SepalMap.py::TestSepalMap::test_add_ee_layer", "tests/test_SepalMap.py::TestSepalMap::test_get_basemap_list", "tests/test_SepalMap.py::TestSepalMap::test_get_viz_params", "tests/test_SepalMap.py::TestSepalMap::test_add_layer", "tests/test_SepalMap.py::TestSepalMap::test_add_basemap", "tests/test_SepalMap.py::TestSepalMap::test_get_scale", "tests/test_SepalMap.py::TestSepalMap::test_zoom_raster" ]
[]
[]
MIT License
null
null
12rambau__sepal_ui-574
412e02ef08df68c256f384081d2c7eaecc09428e
2022-08-16 14:28:01
8c50a7f032daafcbf7cfb6dc16d5d421f02a32e5
diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py index 1ad14c98..ea647223 100644 --- a/sepal_ui/translator/translator.py +++ b/sepal_ui/translator/translator.py @@ -65,7 +65,7 @@ class Translator(Box): # check if forbidden keys are being used # this will raise an error if any - [self.search_key(ms_dict, k) for k in FORBIDDEN_KEYS] + [self.search_key(ms_dict, k) for k in FORBIDDEN_KEYS + self._protected_keys] # # unpack the json as a simple namespace ms_json = json.dumps(ms_dict) @@ -130,8 +130,7 @@ class Translator(Box): return (target, lang) - @staticmethod - def search_key(d, key): + def search_key(self, d, key): """ Search a specific key in the d dictionary and raise an error if found @@ -144,7 +143,9 @@ class Translator(Box): msg = f"You cannot use the key {key} in your translation dictionary" raise Exception(msg) - return + for k, v in d.items(): + if isinstance(v, dict): + return self.search_key(v, key) @classmethod def sanitize(cls, d):
_protected_keys are not raising error when used in translator `protected_keys` are not raising errors when used in a json translation file. It is also happening with the "`FORBIDDEN_KEYS`" when are used in nested levels. To reproduce... ```Python # set up the appropriate keys for each language keys = { "en": { "find_target": "A key", "test_key": "Test key", "nested" : { "items" : { "_target" : "value" }, }, "merge_dict" : "value" }, "fr": { "a_key": "Une clef", "test_key": "Clef de test" }, "fr-FR": { "a_key": "Une clef", "test_key": "Clef de test" }, "es": { "a_key": "Una llave" }, } # generate the tmp_dir in the test directory tmp_dir = Path(".").parent / "data" / "messages" tmp_dir.mkdir(exist_ok=True, parents=True) # create the translation files for lan, d in keys.items(): folder = tmp_dir / lan folder.mkdir(exist_ok=True) (folder / "locale.json").write_text(json.dumps(d, indent=2)) ``` When the object is being instantiated, there's not any error to alert that the nested key "`_target`" cannot be used, nor the "`find_target`" in the first level. ```Python translator = Translator(tmp_dir, "en") ```
12rambau/sepal_ui
diff --git a/tests/test_Translator.py b/tests/test_Translator.py index 3c3704af..865bcd84 100644 --- a/tests/test_Translator.py +++ b/tests/test_Translator.py @@ -40,17 +40,30 @@ class TestTranslator: assert translator._target == "fr-FR" assert translator._match is True + # Check that is failing when using + return def test_search_key(self): + # generate the tmp_dir in the test directory + tmp_dir = Path(__file__).parent / "data" / "messages" + tmp_dir.mkdir(exist_ok=True, parents=True) + # assert that having a wrong key at root level # in the json will raise an error key = "toto" d = {"toto": {"a": "b"}, "c": "d"} with pytest.raises(Exception): - Translator.search_key(d, key) + Translator(tmp_dir).search_key(d, key) + + # Search when the key is in a deeper nested level + key = "nested_key" + d = {"en": {"level1": {"level2": {"nested_key": "value"}}}} + + with pytest.raises(Exception): + Translator(tmp_dir).search_key(d, key) return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
2.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "nbmake" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 haversine==2.9.0 httplib2==0.22.0 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbmake==1.5.5 nest-asyncio==1.6.0 nodeenv==1.9.1 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==1.5.2 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest==8.3.5 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-futures==0.9.9 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@412e02ef08df68c256f384081d2c7eaecc09428e#egg=sepal_ui shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==2.1.2 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - haversine==2.9.0 - httplib2==0.22.0 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbmake==1.5.5 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==1.5.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pytest==8.3.5 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-futures==0.9.9 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==2.1.2 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Translator.py::TestTranslator::test_search_key" ]
[]
[ "tests/test_Translator.py::TestTranslator::test_init", "tests/test_Translator.py::TestTranslator::test_sanitize", "tests/test_Translator.py::TestTranslator::test_delete_empty", "tests/test_Translator.py::TestTranslator::test_find_target", "tests/test_Translator.py::TestTranslator::test_available_locales", "tests/test_Translator.py::TestTranslator::test_key_use" ]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-574
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-574
12rambau__sepal_ui-601
89f8d87dc4f83bfc2e96a111692ae252e470e8bc
2022-10-13 11:16:16
8a8196e3c7893b7a0aebdb4910e83054f59e0374
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 95fda88a..6293f828 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -6,6 +6,7 @@ import ee import geopandas as gpd import ipyvuetify as v import pandas as pd +from deprecated.sphinx import versionadded from ipywidgets import jslink from natsort import humansorted from traitlets import Any, Bool, Dict, Int, List, Unicode, link, observe @@ -29,13 +30,18 @@ __all__ = [ ] +@versionadded( + version="2.13.0", + reason="Empty v_model will be treated as empty string: :code:`v_model=''`.", +) class DatePicker(v.Layout, SepalWidget): """ Custom input widget to provide a reusable DatePicker. It allows to choose date as a string in the following format YYYY-MM-DD Args: label (str, optional): the label of the datepicker field - kwargs (optional): any parameter from a v.Layout abject. If set, 'children' will be overwritten. + layout_kwargs (dict, optional): any parameter for the wrapper layout + kwargs (optional): any parameter from a v.DatePicker abject. """ @@ -48,13 +54,14 @@ class DatePicker(v.Layout, SepalWidget): disabled = Bool(False).tag(sync=True) "traitlets.Bool: the disabled status of the Datepicker object" - def __init__(self, label="Date", **kwargs): + def __init__(self, label="Date", layout_kwargs={}, **kwargs): + + kwargs["v_model"] = kwargs.get("v_model", "") # create the widgets - date_picker = v.DatePicker(no_title=True, v_model=None, scrollable=True) + self.date_picker = v.DatePicker(no_title=True, scrollable=True, **kwargs) self.date_text = v.TextField( - v_model=None, label=label, hint="YYYY-MM-DD format", persistent_hint=True, @@ -69,7 +76,7 @@ class DatePicker(v.Layout, SepalWidget): offset_y=True, v_model=False, close_on_content_click=False, - children=[date_picker], + children=[self.date_picker], v_slots=[ { "name": "activator", @@ -80,17 +87,18 @@ class DatePicker(v.Layout, SepalWidget): ) # set the default parameter - kwargs["v_model"] = kwargs.pop("v_model", None) - kwargs["row"] = kwargs.pop("row", True) - kwargs["class_"] = kwargs.pop("class_", "pa-5") - kwargs["align_center"] = kwargs.pop("align_center", True) - kwargs["children"] = [v.Flex(xs10=True, children=[self.menu])] + layout_kwargs["row"] = layout_kwargs.get("row", True) + layout_kwargs["class_"] = layout_kwargs.get("class_", "pa-5") + layout_kwargs["align_center"] = layout_kwargs.get("align_center", True) + layout_kwargs["children"] = layout_kwargs.pop( + "children", [v.Flex(xs10=True, children=[self.menu])] + ) # call the constructor - super().__init__(**kwargs) + super().__init__(**layout_kwargs) - jslink((date_picker, "v_model"), (self.date_text, "v_model")) - jslink((self, "v_model"), (date_picker, "v_model")) + link((self.date_picker, "v_model"), (self.date_text, "v_model")) + link((self.date_picker, "v_model"), (self, "v_model")) @observe("v_model") def check_date(self, change): @@ -102,7 +110,7 @@ class DatePicker(v.Layout, SepalWidget): self.date_text.error_messages = None # exit immediately if nothing is set - if change["new"] is None: + if not change["new"]: return # change the error status
Datepicker is not fully customizable As our main `DatePicker` usage is as in its "menu" form, it is not handy to set some use cases: - set a min_, max_ value directly (you have to `datepicker.children.....min_`...) - set a default initial value with `v_model` since it is hardcoded from the beginning - the `jslink` "link" will only work if the change is made from a "js" event, but not if you want to link the values since the initialization.
12rambau/sepal_ui
diff --git a/tests/test_DatePicker.py b/tests/test_DatePicker.py index d206c10b..3ae0b219 100644 --- a/tests/test_DatePicker.py +++ b/tests/test_DatePicker.py @@ -23,6 +23,28 @@ class TestDatePicker: return + def test_kwargs(self): + """test kwargs to both datepicker and layout""" + + date_picker_kwargs = { + "min": "2018-02-14", + "max": "2021-03-14", + } + + layout_kwargs = { + "class_": "pa-0", + "align_center": False, + } + + datepicker = sw.DatePicker( + v_model="", layout_kwargs=layout_kwargs, **date_picker_kwargs + ) + + assert datepicker.date_picker.min == "2018-02-14" + assert datepicker.date_picker.max == "2021-03-14" + assert datepicker.class_ == "pa-0" + assert datepicker.align_center is False + def test_bind(self, datepicker): class Test_io(Model): out = Any(None).tag(sync=True) diff --git a/tests/test_sepalwidgets.py b/tests/test_sepalwidgets.py index 1dd4d004..2c06d37f 100644 --- a/tests/test_sepalwidgets.py +++ b/tests/test_sepalwidgets.py @@ -18,7 +18,7 @@ class TestSepalWidgets: for c in v_classes: - if c in ["Alert", "Tooltip", "Banner"]: + if c in ["Alert", "Tooltip", "Banner", "DatePicker"]: # they are meant to be hidden by default # they are specific sepalwidgets and tested elswhere continue
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 1 }
2.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 anyio==3.7.1 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.2 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 haversine==2.9.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nodeenv==1.9.1 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a2 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest==8.3.5 pytest-cov==6.0.0 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@89f8d87dc4f83bfc2e96a111692ae252e470e8bc#egg=sepal_ui shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==2.1.2 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - anyio==3.7.1 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.2 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - haversine==2.9.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nodeenv==1.9.1 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==2.1.2 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_DatePicker.py::TestDatePicker::test_kwargs" ]
[]
[ "tests/test_DatePicker.py::TestDatePicker::test_init", "tests/test_DatePicker.py::TestDatePicker::test_bind", "tests/test_DatePicker.py::TestDatePicker::test_disable", "tests/test_DatePicker.py::TestDatePicker::test_is_valid_date", "tests/test_DatePicker.py::TestDatePicker::test_check_date", "tests/test_sepalwidgets.py::TestSepalWidgets::test_generated", "tests/test_sepalwidgets.py::TestSepalWidgets::test_html" ]
[]
MIT License
null
null
12rambau__sepal_ui-608
2d5126f5e9521470cbeb5ad374f74046e889f771
2022-11-18 07:51:19
8a8196e3c7893b7a0aebdb4910e83054f59e0374
diff --git a/docs/source/widgets/btn.rst b/docs/source/widgets/btn.rst index 949d5468..91d92967 100644 --- a/docs/source/widgets/btn.rst +++ b/docs/source/widgets/btn.rst @@ -20,8 +20,8 @@ The default color is set to "primary". v.theme.dark = False btn = sw.Btn( - text = "The One btn", - icon = "fas fa-cogs" + msg = "The One btn", + gliph = "fas fa-cogs" ) btn @@ -42,8 +42,8 @@ Btn can be used to launch function on any Javascript event such as "click". v.theme.dark = False btn = sw.Btn( - text = "The One btn", - icon = "fas fa-cogs" + msg = "The One btn", + gliph = "fas fa-cogs" ) btn.on_event('click', lambda *args: print('Hello world!')) diff --git a/sepal_ui/reclassify/reclassify_view.py b/sepal_ui/reclassify/reclassify_view.py index f4d6ca40..18a90455 100644 --- a/sepal_ui/reclassify/reclassify_view.py +++ b/sepal_ui/reclassify/reclassify_view.py @@ -33,8 +33,8 @@ class ImportMatrixDialog(v.Dialog): # create the 3 widgets title = v.CardTitle(children=["Load reclassification matrix"]) self.w_file = sw.FileInput(label="filename", folder=folder) - self.load_btn = sw.Btn("Load") - cancel = sw.Btn("Cancel", outlined=True) + self.load_btn = sw.Btn(msg="Load") + cancel = sw.Btn(msg="Cancel", outlined=True) actions = v.CardActions(children=[cancel, self.load_btn]) # default params @@ -81,8 +81,8 @@ class SaveMatrixDialog(v.Dialog): # create the widgets title = v.CardTitle(children=["Save matrix"]) self.w_file = v.TextField(label="filename", v_model=None) - btn = sw.Btn("Save matrix") - cancel = sw.Btn("Cancel", outlined=True) + btn = sw.Btn(msg="Save matrix") + cancel = sw.Btn(msg="Cancel", outlined=True) actions = v.CardActions(children=[cancel, btn]) self.alert = sw.Alert(children=["Choose a name for the output"]).show() @@ -464,7 +464,7 @@ class ReclassifyView(sw.Card): self.btn_list = [ sw.Btn( - "Custom", + msg="Custom", _metadata={"path": "custom"}, small=True, class_="mr-2", @@ -472,7 +472,7 @@ class ReclassifyView(sw.Card): ) ] + [ sw.Btn( - f"use {name}", + msg=f"use {name}", _metadata={"path": path}, small=True, class_="mr-2", @@ -490,18 +490,20 @@ class ReclassifyView(sw.Card): self.save_dialog = SaveMatrixDialog(folder=out_path) self.import_dialog = ImportMatrixDialog(folder=out_path) self.get_table = sw.Btn( - ms.rec.rec.input.btn, "far fa-table", color="success", small=True + msg=ms.rec.rec.input.btn, gliph="far fa-table", color="success", small=True ) self.import_table = sw.Btn( - "import", - "fas fa-download", + msg="import", + gliph="fas fa-download", color="secondary", small=True, class_="ml-2 mr-2", ) - self.save_table = sw.Btn("save", "fas fa-save", color="secondary", small=True) + self.save_table = sw.Btn( + msg="save", gliph="fas fa-save", color="secondary", small=True + ) self.reclassify_btn = sw.Btn( - ms.rec.rec.btn, "fas fa-chess-board", small=True, disabled=True + msg=ms.rec.rec.btn, gliph="fas fa-chess-board", small=True, disabled=True ) self.toolbar = v.Toolbar( diff --git a/sepal_ui/reclassify/table_view.py b/sepal_ui/reclassify/table_view.py index c3f8a35a..24ac31b5 100644 --- a/sepal_ui/reclassify/table_view.py +++ b/sepal_ui/reclassify/table_view.py @@ -49,19 +49,24 @@ class ClassTable(sw.DataTable): # create the 4 CRUD btn # and set them in the top slot of the table self.edit_btn = sw.Btn( - ms.rec.table.btn.edit, - icon="fas fa-pencil-alt", + msg=ms.rec.table.btn.edit, + gliph="fas fa-pencil-alt", class_="ml-2 mr-2", color="secondary", small=True, ) self.delete_btn = sw.Btn( - ms.rec.table.btn.delete, icon="fas fa-trash-alt", color="error", small=True + msg=ms.rec.table.btn.delete, + gliph="fas fa-trash-alt", + color="error", + small=True, ) self.add_btn = sw.Btn( - ms.rec.table.btn.add, icon="fas fa-plus", color="success", small=True + msg=ms.rec.table.btn.add, gliph="fas fa-plus", color="success", small=True + ) + self.save_btn = sw.Btn( + msg=ms.rec.table.btn.save, gliph="far fa-save", small=True ) - self.save_btn = sw.Btn(ms.rec.table.btn.save, icon="far fa-save", small=True) slot = v.Toolbar( class_="d-flex mb-6", @@ -212,20 +217,19 @@ class EditDialog(v.Dialog): self.title = v.CardTitle(children=[self.TITLES[0]]) # Action buttons - self.save = sw.Btn(ms.rec.table.edit_dialog.btn.save.name) + self.save = sw.Btn(msg=ms.rec.table.edit_dialog.btn.save.name) save_tool = sw.Tooltip( self.save, ms.rec.table.edit_dialog.btn.save.tooltip, bottom=True ) - self.modify = sw.Btn( - ms.rec.table.edit_dialog.btn.modify.name - ).hide() # by default modify is hidden + self.modify = sw.Btn(msg=ms.rec.table.edit_dialog.btn.modify.name) + self.modify.hide() # by default modify is hidden modify_tool = sw.Tooltip( self.modify, ms.rec.table.edit_dialog.btn.modify.tooltip, bottom=True ) self.cancel = sw.Btn( - ms.rec.table.edit_dialog.btn.cancel.name, outlined=True, class_="ml-2" + msg=ms.rec.table.edit_dialog.btn.cancel.name, outlined=True, class_="ml-2" ) cancel_tool = sw.Tooltip( self.cancel, ms.rec.table.edit_dialog.btn.cancel.tooltip, bottom=True @@ -437,7 +441,7 @@ class SaveDialog(v.Dialog): v_model=ms.rec.table.save_dialog.placeholder, ) - self.save = sw.Btn(ms.rec.table.save_dialog.btn.save.name) + self.save = sw.Btn(msg=ms.rec.table.save_dialog.btn.save.name) save = sw.Tooltip( self.save, ms.rec.table.save_dialog.btn.save.tooltip, @@ -446,7 +450,7 @@ class SaveDialog(v.Dialog): ) self.cancel = sw.Btn( - ms.rec.table.save_dialog.btn.cancel.name, outlined=True, class_="ml-2" + msg=ms.rec.table.save_dialog.btn.cancel.name, outlined=True, class_="ml-2" ) cancel = sw.Tooltip( self.cancel, ms.rec.table.save_dialog.btn.cancel.tooltip, bottom=True @@ -600,8 +604,8 @@ class TableView(sw.Card): folder=self.class_path, ) self.btn = sw.Btn( - ms.rec.table.classif.btn, - icon="far fa-table", + msg=ms.rec.table.classif.btn, + gliph="far fa-table", color="success", outlined=True, ) diff --git a/sepal_ui/sepalwidgets/btn.py b/sepal_ui/sepalwidgets/btn.py index c6437d86..137622fa 100644 --- a/sepal_ui/sepalwidgets/btn.py +++ b/sepal_ui/sepalwidgets/btn.py @@ -1,6 +1,9 @@ +import warnings from pathlib import Path import ipyvuetify as v +from deprecated.sphinx import deprecated +from traitlets import Unicode, observe from sepal_ui.scripts import utils as su from sepal_ui.sepalwidgets.sepalwidget import SepalWidget @@ -14,27 +17,83 @@ class Btn(v.Btn, SepalWidget): the color will be defaulted to 'primary' and can be changed afterward according to your need Args: + msg (str, optional): the text to display in the btn + gliph (str, optional): the full name of any mdi/fa icon text (str, optional): the text to display in the btn icon (str, optional): the full name of any mdi/fa icon kwargs (dict, optional): any parameters from v.Btn. if set, 'children' will be overwritten. + + .. deprecated:: 2.13 + ``text`` and ``icon`` will be replaced by ``msg`` and ``gliph`` to avoid duplicating ipyvuetify trait. """ v_icon = None "v.Icon: the icon in the btn" - def __init__(self, text="Click", icon="", **kwargs): + gliph = Unicode("").tag(sync=True) + "traitlet.Unicode: the name of the icon" + + msg = Unicode("").tag(sync=True) + "traitlet.Unicode: the text of the btn" + + def __init__(self, msg="Click", gliph="", **kwargs): + + # deprecation in 2.13 of text and icon + # as they already exist in the ipyvuetify Btn traits (as booleans) + if "text" in kwargs: + if isinstance(kwargs["text"], str): + msg = kwargs.pop("text") + warnings.warn( + '"text" is deprecated, please use "msg" instead', DeprecationWarning + ) + if "icon" in kwargs: + if isinstance(kwargs["icon"], str): + gliph = kwargs.pop("icon") + warnings.warn( + '"icon" is deprecated, please use "gliph" instead', + DeprecationWarning, + ) # create the default v_icon self.v_icon = v.Icon(left=True, children=[""]) - self.set_icon(icon) # set the default parameters kwargs["color"] = kwargs.pop("color", "primary") - kwargs["children"] = [self.v_icon, text] + kwargs["children"] = [self.v_icon, self.msg] # call the constructor super().__init__(**kwargs) + self.gliph = gliph + self.msg = msg + + @observe("gliph") + def _set_gliph(self, change): + """ + Set a new icon. If the icon is set to "", then it's hidden + """ + new_gliph = change["new"] + self.v_icon.children = [new_gliph] + + # hide the component to avoid the right padding + if not new_gliph: + su.hide_component(self.v_icon) + else: + su.show_component(self.v_icon) + + return self + + @observe("msg") + def _set_text(self, change): + """ + Set the text of the btn + """ + + self.children = [self.v_icon, change["new"]] + + return self + + @deprecated(version="2.14", reason="Replace by the private _set_gliph") def set_icon(self, icon=""): """ set a new icon. If the icon is set to "", then it's hidden. @@ -45,13 +104,7 @@ class Btn(v.Btn, SepalWidget): Return: self """ - self.v_icon.children = [icon] - - if not icon: - su.hide_component(self.v_icon) - else: - su.show_component(self.v_icon) - + self.gliph = icon return self def toggle_loading(self): diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 5a9507ad..1bb0e850 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -256,7 +256,7 @@ class FileInput(v.Flex, SepalWidget): "name": "activator", "variable": "x", "children": Btn( - icon="fas fa-search", v_model=False, v_on="x.on", text=label + gliph="fas fa-search", v_model=False, v_on="x.on", msg=label ), } ],
create a function to set the text of the btn dynamically icon and text should be editable dynamically https://github.com/12rambau/sepal_ui/blob/8af255ec0d1cb3ad4dd74d021ad140fafef756f6/sepal_ui/sepalwidgets/btn.py#L38
12rambau/sepal_ui
diff --git a/tests/test_Btn.py b/tests/test_Btn.py index 407c0e3b..058cb775 100644 --- a/tests/test_Btn.py +++ b/tests/test_Btn.py @@ -50,6 +50,47 @@ class TestBtn: return + def test_set_gliph(self, btn): + + # new gliph + gliph = "fas fa-folder" + btn.gliph = gliph + + assert isinstance(btn.v_icon, v.Icon) + assert btn.v_icon.children[0] == gliph + + # change existing icon + gliph = "fas fa-file" + btn.gliph = gliph + assert btn.v_icon.children[0] == gliph + + # remove all gliph + gliph = "" + btn.gliph = gliph + assert "d-none" in btn.v_icon.class_ + + # assert deprecation + with pytest.deprecated_call(): + sw.Btn(icon="fas fa-folder") + + return + + def test_test_msg(self, btn): + + # test the initial text + assert btn.children[1] == "Click" + + # update msg + msg = "New message" + btn.msg = msg + assert btn.children[1] == msg + + # test deprecation notice + with pytest.deprecated_call(): + sw.Btn(text="Deprecation") + + return + @pytest.fixture def btn(self): """Create a simple btn"""
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 5 }
2.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "nbmake" ], "pre_install": [ "apt-get update", "apt-get install -y gcc", "pip install --find-links=https://girder.github.io/large_image_wheels --no-cache GDAL", "pip install localtileserver" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 aniso8601==10.0.0 annotated-types==0.7.0 anyio==3.7.1 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 blinker==1.9.0 branca==0.8.1 cachelib==0.13.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 color-operations==0.2.0 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 Flask==3.1.0 Flask-Caching==2.3.1 flask-cors==5.0.1 flask-restx==1.3.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 GDAL==3.11.0 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 haversine==2.9.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 itsdangerous==2.2.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 localtileserver==0.10.6 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 morecantile==6.2.0 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbmake==1.5.5 nest-asyncio==1.6.0 nodeenv==1.9.1 numexpr==2.10.2 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a2 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 pydantic==2.11.1 pydantic_core==2.33.0 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pystac==1.10.1 pytest==8.3.5 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rio-cogeo==5.4.1 rio-tiler==7.5.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 scooby==0.10.0 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@2d5126f5e9521470cbeb5ad374f74046e889f771#egg=sepal_ui server-thread==0.3.0 shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==2.1.2 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - aniso8601==10.0.0 - annotated-types==0.7.0 - anyio==3.7.1 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - blinker==1.9.0 - branca==0.8.1 - cachelib==0.13.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - color-operations==0.2.0 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - flask==3.1.0 - flask-caching==2.3.1 - flask-cors==5.0.1 - flask-restx==1.3.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - gdal==3.11.0 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - haversine==2.9.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - itsdangerous==2.2.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - localtileserver==0.10.6 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - morecantile==6.2.0 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbmake==1.5.5 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - numexpr==2.10.2 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pystac==1.10.1 - pytest==8.3.5 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rio-cogeo==5.4.1 - rio-tiler==7.5.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - scooby==0.10.0 - send2trash==1.8.3 - server-thread==0.3.0 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==2.1.2 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Btn.py::TestBtn::test_set_gliph", "tests/test_Btn.py::TestBtn::test_test_msg" ]
[]
[ "tests/test_Btn.py::TestBtn::test_init", "tests/test_Btn.py::TestBtn::test_set_icon", "tests/test_Btn.py::TestBtn::test_toggle_loading" ]
[]
MIT License
null
null
12rambau__sepal_ui-644
8a8196e3c7893b7a0aebdb4910e83054f59e0374
2022-11-29 14:42:21
8a8196e3c7893b7a0aebdb4910e83054f59e0374
diff --git a/sepal_ui/sepalwidgets/btn.py b/sepal_ui/sepalwidgets/btn.py index 137622fa..105f6160 100644 --- a/sepal_ui/sepalwidgets/btn.py +++ b/sepal_ui/sepalwidgets/btn.py @@ -25,6 +25,9 @@ class Btn(v.Btn, SepalWidget): .. deprecated:: 2.13 ``text`` and ``icon`` will be replaced by ``msg`` and ``gliph`` to avoid duplicating ipyvuetify trait. + + .. deprecated:: 2.14 + Btn is not using a default ``msg`` anymor`. """ v_icon = None @@ -36,7 +39,7 @@ class Btn(v.Btn, SepalWidget): msg = Unicode("").tag(sync=True) "traitlet.Unicode: the text of the btn" - def __init__(self, msg="Click", gliph="", **kwargs): + def __init__(self, msg="", gliph="", **kwargs): # deprecation in 2.13 of text and icon # as they already exist in the ipyvuetify Btn traits (as booleans) @@ -55,7 +58,7 @@ class Btn(v.Btn, SepalWidget): ) # create the default v_icon - self.v_icon = v.Icon(left=True, children=[""]) + self.v_icon = v.Icon(children=[""]) # set the default parameters kwargs["color"] = kwargs.pop("color", "primary") @@ -89,6 +92,7 @@ class Btn(v.Btn, SepalWidget): Set the text of the btn """ + self.v_icon.left = bool(change["new"]) self.children = [self.v_icon, change["new"]] return self
sepal_ui.Btn does't work as expected I want to create a simple Icon button, to do so: ```python sw.Btn(icon=True, gliph ="mdi-plus") ``` Doing this, without "msg" parameter will add the default text to the button which is "click", I think is worthless having that value. So if I want to remove the default text, I would expect doing this: ```python sw.Btn(children = [""], icon=True, gliph ="mdi-plus") # or sw.Btn(msg= ""] icon=True, gliph ="mdi-plus") ``` Which leads the icon aligned to the left and not centered (as it is using a empyt string as message).
12rambau/sepal_ui
diff --git a/tests/test_Btn.py b/tests/test_Btn.py index fcaed760..4e3cb9b5 100644 --- a/tests/test_Btn.py +++ b/tests/test_Btn.py @@ -11,7 +11,7 @@ class TestBtn: btn = sw.Btn() assert btn.color == "primary" assert btn.v_icon.children[0] == "" - assert btn.children[1] == "Click" + assert btn.children[1] == "" # extensive btn btn = sw.Btn("toto", "fas fa-folder") @@ -42,12 +42,18 @@ class TestBtn: assert isinstance(btn.v_icon, v.Icon) assert btn.v_icon.children[0] == gliph + assert btn.v_icon.left is True # change existing icon gliph = "fas fa-file" btn.gliph = gliph assert btn.v_icon.children[0] == gliph + # display only the gliph + btn.msg = "" + assert btn.children[1] == "" + assert btn.v_icon.left is False + # remove all gliph gliph = "" btn.gliph = gliph @@ -79,4 +85,4 @@ class TestBtn: def btn(self): """Create a simple btn""" - return sw.Btn() + return sw.Btn("Click")
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
2.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc", "pip install --find-links=https://girder.github.io/large_image_wheels --no-cache GDAL", "pip install localtileserver" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 aniso8601==10.0.0 annotated-types==0.7.0 anyio==3.7.1 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 blinker==1.9.0 branca==0.8.1 cachelib==0.13.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 color-operations==0.2.0 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 execnet==2.1.1 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 Flask==3.1.0 Flask-Caching==2.3.1 flask-cors==5.0.1 flask-restx==1.3.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 GDAL==3.11.0 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 haversine==2.9.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 itsdangerous==2.2.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 localtileserver==0.10.6 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 morecantile==6.2.0 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nodeenv==1.9.1 numexpr==2.10.2 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a2 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 pydantic==2.11.1 pydantic_core==2.33.0 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pystac==1.10.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rio-cogeo==5.4.1 rio-tiler==7.5.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 scooby==0.10.0 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@8a8196e3c7893b7a0aebdb4910e83054f59e0374#egg=sepal_ui server-thread==0.3.0 shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==2.1.2 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - aniso8601==10.0.0 - annotated-types==0.7.0 - anyio==3.7.1 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - blinker==1.9.0 - branca==0.8.1 - cachelib==0.13.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - color-operations==0.2.0 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - execnet==2.1.1 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - flask==3.1.0 - flask-caching==2.3.1 - flask-cors==5.0.1 - flask-restx==1.3.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - gdal==3.11.0 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - haversine==2.9.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - itsdangerous==2.2.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - localtileserver==0.10.6 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - morecantile==6.2.0 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nodeenv==1.9.1 - numexpr==2.10.2 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a2 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pystac==1.10.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rio-cogeo==5.4.1 - rio-tiler==7.5.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - scooby==0.10.0 - send2trash==1.8.3 - server-thread==0.3.0 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==2.1.2 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Btn.py::TestBtn::test_init", "tests/test_Btn.py::TestBtn::test_set_gliph" ]
[]
[ "tests/test_Btn.py::TestBtn::test_toggle_loading", "tests/test_Btn.py::TestBtn::test_set_msg" ]
[]
MIT License
null
null
12rambau__sepal_ui-646
8a8196e3c7893b7a0aebdb4910e83054f59e0374
2022-11-29 22:27:29
8a8196e3c7893b7a0aebdb4910e83054f59e0374
diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py index 68e3f115..de6d4abb 100644 --- a/sepal_ui/sepalwidgets/alert.py +++ b/sepal_ui/sepalwidgets/alert.py @@ -94,9 +94,10 @@ class Alert(v.Alert, SepalWidget): self.show() # cast the progress to float + total = tqdm_args.get("total", 1) progress = float(progress) - if not (0 <= progress <= 1): - raise ValueError(f"progress should be in [0, 1], {progress} given") + if not (0 <= progress <= total): + raise ValueError(f"progress should be in [0, {total}], {progress} given") # Prevent adding multiple times if self.progress_output not in self.children: @@ -107,7 +108,7 @@ class Alert(v.Alert, SepalWidget): "bar_format", "{l_bar}{bar}{n_fmt}/{total_fmt}" ) tqdm_args["dynamic_ncols"] = tqdm_args.pop("dynamic_ncols", tqdm_args) - tqdm_args["total"] = tqdm_args.pop("total", 100) + tqdm_args["total"] = tqdm_args.pop("total", 1) tqdm_args["desc"] = tqdm_args.pop("desc", msg) tqdm_args["colour"] = tqdm_args.pop("tqdm_args", getattr(color, self.type)) @@ -120,7 +121,7 @@ class Alert(v.Alert, SepalWidget): # Initialize bar self.progress_bar.update(0) - self.progress_bar.update(progress * 100 - self.progress_bar.n) + self.progress_bar.update(progress - self.progress_bar.n) if progress == 1: self.progress_bar.close()
allow other values for progress Now that we are supporting tqdm it should be possible to support progress values that are not between 0 and 1. https://github.com/12rambau/sepal_ui/blob/c15a83dc6c92d076e6932afab4e4b2987585894b/sepal_ui/sepalwidgets/alert.py#L98
12rambau/sepal_ui
diff --git a/tests/test_Alert.py b/tests/test_Alert.py index af360930..52c6931c 100644 --- a/tests/test_Alert.py +++ b/tests/test_Alert.py @@ -153,11 +153,18 @@ class TestAlert: # test a random update alert.update_progress(0.5) - assert alert.progress_bar.n == 50 + assert alert.progress_bar.n == 0.5 assert alert.viz is True # show that a value > 1 raise an error with pytest.raises(ValueError): + alert.reset() alert.update_progress(1.5) + # check that if total is set value can be more than 1 + alert.reset() + alert.update_progress(50, total=100) + assert alert.progress_bar.n == 50 + assert alert.viz is True + return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
2.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-sugar" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 anyio==3.7.1 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 comm==0.2.2 contourpy==1.3.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 decorator==5.2.1 deepdiff==8.4.2 defusedxml==0.7.1 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 haversine==2.9.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nodeenv==1.9.1 numpy==2.0.2 orderly-set==5.3.0 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a2 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work pytest-sugar==1.0.0 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@8a8196e3c7893b7a0aebdb4910e83054f59e0374#egg=sepal_ui shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==3.0.0 terminado==0.18.1 tinycss2==1.4.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==2.1.2 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - anyio==3.7.1 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - comm==0.2.2 - contourpy==1.3.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - decorator==5.2.1 - deepdiff==8.4.2 - defusedxml==0.7.1 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - haversine==2.9.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nodeenv==1.9.1 - numpy==2.0.2 - orderly-set==5.3.0 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a2 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pytest-sugar==1.0.0 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==3.0.0 - terminado==0.18.1 - tinycss2==1.4.0 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==2.1.2 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_Alert.py::TestAlert::test_update_progress" ]
[]
[ "tests/test_Alert.py::TestAlert::test_init", "tests/test_Alert.py::TestAlert::test_add_msg", "tests/test_Alert.py::TestAlert::test_add_live_msg", "tests/test_Alert.py::TestAlert::test_append_msg", "tests/test_Alert.py::TestAlert::test_reset", "tests/test_Alert.py::TestAlert::test_rmv_last_msg" ]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-646
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-646
12rambau__sepal_ui-685
549667ffe968ab4d631766a96024819b0fabff00
2023-01-05 11:57:10
6b3f6e8c9f7c3e1dd7a20378153e0129f34c88e9
diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index 88dda404..e29b052d 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -60,15 +60,7 @@ jobs: - name: Check that there are no unexpected Sphinx warnings if: matrix.python-version == '3.8' - shell: python - run: | - from pathlib import Path - text = Path("warnings.txt").read_text().strip() - print("\n=== Sphinx Warnings ===\n\n" + text) # Print just for reference so we can look at the logs - warnings = [ii for ii in text.split("\n")] - expected = ["transition", "CHANGELOG.md", "modules.rst", "target"] - unexpected = [ii for ii in text.split("\n") if all(i not in ii for i in expected)] - assert len(unexpected) == 0 + run: python tests/check_warnings.py - name: test with pytest run: pytest --color=yes --cov --cov-report=xml tests diff --git a/docs/source/tutorials/add-tile.rst b/docs/source/tutorials/add-tile.rst index 91524bc2..f63948a3 100644 --- a/docs/source/tutorials/add-tile.rst +++ b/docs/source/tutorials/add-tile.rst @@ -15,6 +15,7 @@ the tile cod is the following : import ipyvuetify as v from component.message import ms from sepal_ui.scripts import utils as su + from sepal_ui.scripts import decorator as sd class MyTile(sw.Tile): @@ -45,7 +46,7 @@ the tile cod is the following : # now that the Tile is created we can link it to a specific function self.btn.on_event('click', self._on_run) - @su.loading_button(debug=False) + @sd.loading_button(debug=False) def _on_run(self, widget, data, event): time.sleep(5) diff --git a/docs/source/tutorials/decorator.rst b/docs/source/tutorials/decorator.rst index 79f8e5c1..632068e0 100644 --- a/docs/source/tutorials/decorator.rst +++ b/docs/source/tutorials/decorator.rst @@ -82,6 +82,7 @@ Let's import the required modules. All the decorators are stored in the utils mo import ipyvuetify as v import sepal_ui.sepalwidgets as sw import sepal_ui.scripts.utils as su + import sepal_ui.scripts.decorator as sd Now, create a custom tile with all the elements that we will require to be displayed in our interface, as well as the events that we want to trigger. @@ -125,19 +126,19 @@ It's time to use the decorators in the class methods. For this example, we will .. code-block:: python - @su.loading_button() - @su.switch('loading', 'disabled', on_widgets=['w_select']) + @sd.loading_button() + @sd.switch('loading', 'disabled', on_widgets=['w_select']) def get_items_event(self): """request GEE items""" self.children = self.request_items() - @su.switch('loading', 'disabled') + @sd.switch('loading', 'disabled') def on_card_event(self): sleep(2) - @su.need_ee + @sd.need_ee def request_items(self): """Connect to gee and request the root assets id's""" diff --git a/noxfile.py b/noxfile.py index 76b3ac6b..14582d70 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,7 +27,10 @@ def docs(session): "docs/source/modules", "./sepal_ui", ) - session.run("sphinx-build", "-v", "-b", "html", "docs/source", "build") + session.run( + "sphinx-build", "-v", "-b", "html", "docs/source", "build", "-w", "warnings.txt" + ) + session.run("python", "tests/check_warnings.py") @nox.session(name="docs-live", reuse_venv=False) diff --git a/sepal_ui/aoi/aoi_model.py b/sepal_ui/aoi/aoi_model.py index 582abd49..28e00c8a 100644 --- a/sepal_ui/aoi/aoi_model.py +++ b/sepal_ui/aoi/aoi_model.py @@ -8,12 +8,10 @@ import ee import geopandas as gpd import pandas as pd import traitlets as t -from deprecated.sphinx import deprecated from ipyleaflet import GeoJSON from typing_extensions import Self from sepal_ui import color -from sepal_ui import sepalwidgets as sw from sepal_ui.frontend import styles as ss from sepal_ui.message import ms from sepal_ui.model import Model @@ -142,13 +140,8 @@ class AoiModel(Model): ipygeojson: Optional[GeoJSON] = None "The representation of the AOI as a ipyleaflet layer" - @deprecated( - version="2.11.3", - reason=":code:`alert` positional argument will be removed. Successfull output messages has to be created in AoiView.", - ) def __init__( self, - alert: Optional[sw.Alert] = None, gee: bool = True, vector: Optional[Union[str, Path]] = None, asset: Optional[Union[str, Path]] = None, diff --git a/sepal_ui/frontend/js/jupyter_clip.js b/sepal_ui/frontend/js/jupyter_clip.js new file mode 100644 index 00000000..02605b66 --- /dev/null +++ b/sepal_ui/frontend/js/jupyter_clip.js @@ -0,0 +1,7 @@ +var tempInput = document.createElement("input"); +tempInput.value = _txt; +document.body.appendChild(tempInput); +tempInput.focus(); +tempInput.select(); +document.execCommand("copy"); +document.body.removeChild(tempInput); diff --git a/sepal_ui/message/en/password_field.json b/sepal_ui/message/en/password_field.json new file mode 100644 index 00000000..2f182d19 --- /dev/null +++ b/sepal_ui/message/en/password_field.json @@ -0,0 +1,5 @@ +{ + "password_field": { + "label": "Password" + } +} diff --git a/sepal_ui/reclassify/parameters.py b/sepal_ui/reclassify/parameters.py index bb214e6f..36e36c83 100644 --- a/sepal_ui/reclassify/parameters.py +++ b/sepal_ui/reclassify/parameters.py @@ -2,13 +2,13 @@ from sepal_ui.message import ms __all__ = ["MATRIX_NAMES", "TABLE_NAMES", "NO_VALUE", "SCHEMA"] -MATRIX_NAMES = ["src", "dst"] -TABLE_NAMES = ["code", "desc", "color"] +MATRIX_NAMES: list = ["src", "dst"] +TABLE_NAMES: list = ["code", "desc", "color"] # Set a value for missing reclassifications -NO_VALUE = 999 +NO_VALUE: int = 999 -SCHEMA = { +SCHEMA: dict = { "id": [ms.rec.table.schema.id, "number"], "code": [ms.rec.table.schema.code, "number"], "desc": [ms.rec.table.schema.description, "string"], diff --git a/sepal_ui/reclassify/reclassify_model.py b/sepal_ui/reclassify/reclassify_model.py index bebf3baa..a3a15ff2 100644 --- a/sepal_ui/reclassify/reclassify_model.py +++ b/sepal_ui/reclassify/reclassify_model.py @@ -1,15 +1,18 @@ from pathlib import Path +from typing import Any, Optional, Union import ee import geopandas as gpd import numpy as np import pandas as pd import rasterio as rio +import traitlets as t from matplotlib.colors import to_rgba from natsort import natsorted from rasterio.windows import from_bounds -from traitlets import Any, Bool, Dict, Int +from typing_extensions import Self +from sepal_ui import aoi from sepal_ui.message import ms from sepal_ui.model import Model from sepal_ui.scripts import decorator as sd @@ -23,91 +26,89 @@ __all__ = ["ReclassifyModel"] class ReclassifyModel(Model): - # inputs - # should be unicode but we need to handle when nothing is set (None) - band = Any(None).tag(sync=True) - "str|int: the band name or number to use for the reclassification if raster type. Use property name if vector type" + band: t.Any = t.Any(None).tag(sync=True) + "the band name or number to use for the reclassification if raster type. Use property name if vector type" - src_local = Any(None).tag(sync=True) - "str: the source file to reclassify (from a local path) only used if :code:`gee=False`" + src_local: t.Any = t.Any(None).tag(sync=True) + "the source file to reclassify (from a local path) only used if :code:`gee=False`" - src_gee = Any(None).tag(sync=True) - "str: AssetId of the used input asset for reclassification. Only used if :code:`gee=True`" + src_gee: t.Unicode = t.Unicode(None, allow_none=True).tag(sync=True) + "AssetId of the used input asset for reclassification. Only used if :code:`gee=True`" - dst_class_file = Any(None).tag(sync=True) - "str: the destination file for reclassify matrix" + dst_class_file: t.Any = t.Any(None).tag(sync=True) + "the destination file for reclassify matrix" - dst_dir = Any(None).tag(sync=True) - "str: the dir used to store the output" + dst_dir: Union[Path, str] = "" + "the dir used to store the output" - gee = Bool(False).tag(sync=True) - "bool: either to use the gee backend or not" + gee: t.Bool = t.Bool(False).tag(sync=True) + "either to use the gee backend or not" - aoi_model = None - "aoi.AoiModel: AOI model object to get an area of interest if one is selected" + aoi_model: Optional[aoi.AoiModel] = None + "AOI model object to get an area of interest if one is selected" - folder = None - "str: the init GEE asset folder where the asset selector should start looking (debugging purpose)" + folder: str = "" + "the init GEE asset folder where the asset selector should start looking (debugging purpose)" - enforce_aoi = None - "bool: either or not an aoi should be set to allow the reclassification" + enforce_aoi: bool = False + "either or not an aoi should be set to allow the reclassification" # data manipulation - matrix = Dict({}).tag(sync=True) - "dict: the transfer matrix between the input and the output using the following format: {old_value: new_value, ...}" + matrix: t.Dict = t.Dict({}).tag(sync=True) + "the transfer matrix between the input and the output using the following format: {old_value: new_value, ...}" # outputs - input_type = Bool(False).tag(sync=True) # 1 raster, 0 vector - "bool: the input type, 1 for raster and 0 for vector" + input_type: t.Bool = t.Bool(False).tag(sync=True) # 1 raster, 0 vector + "the input type, 1 for raster and 0 for vector" - src_class = Dict({}).tag(sync=True) - "dict: the source classes using the following columns: {code: (desc, color)}" + src_class: t.Dict = t.Dict({}).tag(sync=True) + "the source classes using the following columns: {code: (desc, color)}" - dst_class = Dict({}).tag(sync=True) - "dict: the destination classes using the following columns: {code: (desc, color)}" + dst_class: t.Dict = t.Dict({}).tag(sync=True) + "the destination classes using the following columns: {code: (desc, color)}" - dst_local = Any(None).tag(sync=True) - "str: the output file. default to :code:`dst_dir/f'{src_local.stem}_reclass.{src_local.suffix}'`" + dst_local: t.Unicode = t.Unicode(None, allow_none=True).tag(sync=True) + "the output file. default to :code:`dst_dir/f'{src_local.stem}_reclass.{src_local.suffix}'`" - dst_gee = Any(None).tag(sync=True) - "str: the output assetId. default to :code:`dst_dir/f'{src_gee.stem}_reclass'`" + dst_gee: t.Unicode = t.Unicode(None, allow_none=True).tag(sync=True) + "the output assetId. default to :code:`dst_dir/f'{src_gee.stem}_reclass'`" # Create a state var, to determine if an asset has been remaped - remaped = Int(False).tag(sync=True) - "int: state var updated each time an input is remapped" + remaped: t.Int = t.Int(0).tag(sync=True) + "state var updated each time an input is remapped" - save = False - "bool: either or not the relcassified dataset need to be saved" + save: bool = False + "either or not the relcassified dataset need to be saved" - dst_local_memory = None - "Any: the local output of the reclassification" + dst_local_memory: Any = None + "the local output of the reclassification" - dst_gee_memory = None - "Any: the gee output of the reclassification" + dst_gee_memory: Any = None + "the gee output of the reclassification" - table_created = Bool(False).tag(sync=True) - "bool: either or not a table have been created" + table_created: t.Bool = t.Bool(False).tag(sync=True) + "either or not a table have been created" def __init__( self, - gee=False, - dst_dir=Path.home(), - aoi_model=None, - folder="", - save=True, - enforce_aoi=False, + gee: bool = False, + dst_dir: Union[Path, str] = Path.home(), + aoi_model: Optional[aoi.AoiModel] = None, + folder: str = "", + save: bool = True, + enforce_aoi: bool = False, **kwargs, - ): + ) -> None: """ Reclassification model to store information about the current reclassification and share them within your app. save all the input and output of the reclassification + the the matrix to move from one to another. It is embeding 2 backends, one based on GEE that will use assets as in/out and another based on python that will use local files as in/out. The model can handle both vector and raster data, the format and name of the output will be determined from the the input format/name. The developer will still have the possiblity to choose where to save the outputs (folder name). Args: - gee (bool): either or not to set :code:`gee` to True - dst_dir (str): the destination forlder for outputs - folder(str, optional): the init GEE asset folder where the asset selector should start looking (debugging purpose) - aoi_model (aoi.AoiModel, optional): the aoi model to link to the reclassify workflow - enforce_aoi (bool, optional): either or not an aoi should be set to allow the reclassification + gee: either or not to set :code:`gee` to True + dst_dir: the destination forlder for outputs + folder: the init GEE asset folder where the asset selector should start looking (debugging purpose) + aoi_model: the aoi model to link to the reclassify workflow + enforce_aoi: either or not an aoi should be set to allow the reclassification """ # init the model @@ -143,16 +144,12 @@ class ReclassifyModel(Model): # set if the model need to save by default self.save = save - def get_classes(self): + def get_classes(self) -> dict: """ Extract the classes from the class file. The class file need to be compatible with the reclassify tool i.e. a table file with 3 headerless columns using the following format: 'code', 'desc', 'color'. Color need to be set in hexadecimal to be read else black will be used. - Args: - file (pathlike object): the pathlib object of the class file - Return: - (dict): the dict of the classes using following format: - {code: (name, color)} + the dict of the classes using following format: {code: (name, color)} """ file = self.dst_class_file @@ -176,12 +173,12 @@ class ReclassifyModel(Model): # create a dict out of it return class_list - def get_type(self): + def get_type(self) -> bool: """ Guess the type of the input and set the input type attribute for the model (vector or raster) Return: - (bool): the type of input (1 for raster, 0 for vector) + the type of input (1 for raster, 0 for vector) """ if self.gee: @@ -210,7 +207,7 @@ class ReclassifyModel(Model): raise AttributeError(f"Unrecognized file format: {input_path.suffix}") return self.input_type - def get_bands(self): + def get_bands(self) -> list: """ Use the input_type to extract all the bands/properties from the input @@ -255,8 +252,13 @@ class ReclassifyModel(Model): # remember to use self as a parameter return natsorted(band_func[self.gee][self.input_type]()) - def get_aoi(self): - """Validate and get feature collection from aoi_model""" + def get_aoi(self) -> Union[gpd.GeoDataFrame, ee.ComputedObject]: + """ + Validate and get feature collection from aoi_model + + Returns: + the saved AOI in the appropriate format + """ # by default it's none aoi = None @@ -279,14 +281,13 @@ class ReclassifyModel(Model): return aoi - def unique(self): + def unique(self) -> dict: """ Retreive all the existing class from the specified band/property according to the input_type. The data will be saved in self.src_class with no_name and black as a color. Return: - (Dict): the unique class value found in the specified band/property - and there color/name defaulted to none and black + the unique class value found in the specified band/property and there color/name defaulted to none and black """ if not self.band: @@ -359,12 +360,9 @@ class ReclassifyModel(Model): return self.src_class - def reclassify(self): + def reclassify(self) -> Self: """ Reclassify the input according to the provided matrix. For vector file type reclassifying correspond to add an extra column at the end, for raster the initial class band will be replaced by the new class, the oher being kept unmodified. vizualization colors will be set for both local (QGIS compatible) and assets (SEPAL vizualization compatible). - - Return: - self """ if not self.matrix: @@ -586,12 +584,12 @@ class ReclassifyModel(Model): return "Asset successfully reclassified." - def set_dst_gee(self): + def set_dst_gee(self) -> str: """ Creates a unique and consecutive asset name based on the source Return: - (str) the destination folder + the destination folder """ # create the asset_id diff --git a/sepal_ui/reclassify/reclassify_tile.py b/sepal_ui/reclassify/reclassify_tile.py index 48adc351..4d6ac680 100644 --- a/sepal_ui/reclassify/reclassify_tile.py +++ b/sepal_ui/reclassify/reclassify_tile.py @@ -1,48 +1,53 @@ from pathlib import Path +from typing import Optional, Union import ipyvuetify as v from traitlets import link -from sepal_ui import reclassify as rec +from sepal_ui import aoi from sepal_ui import sepalwidgets as sw from sepal_ui.message import ms +from .reclassify_model import ReclassifyModel +from .reclassify_view import ReclassifyView +from .table_view import TableView + __all__ = ["ReclassifyTile"] class ReclassifyTile(sw.Tile): - result_dir = None - "pathlib.Path: Directory to store the outputs (rasters, and csv_files)." + result_dir: Union[Path, str] = "" + "Directory to store the outputs (rasters, and csv_files)." - model = None - "ReclassifyModel: the reclassify model to use with these inputs" + model: Optional[ReclassifyModel] = None + "the reclassify model to use with these inputs" - reclassify_view = None - "ReclassifyView: a fully qualified ReclassifyView object" + reclassify_view: Optional[ReclassifyView] = None + "a fully qualified ReclassifyView object" - table_view = None - "TableView: a fully qualified TableView object" + table_view: Optional[TableView] = None + "a fully qualified TableView object" def __init__( self, - results_dir=Path.home() / "downloads", - gee=True, - dst_class=None, - default_class={}, - aoi_model=None, - folder="", + results_dir: Union[Path, str] = Path.home() / "downloads", + gee: bool = True, + dst_class: Union[Path, str] = "", + default_class: dict = {}, + aoi_model: Optional[aoi.AoiModel] = None, + folder: str = "", **kwargs - ): + ) -> None: """ All in one tile to reclassify GEE assets or local raster and create custom classifications Args: - results_dir (str|pathlike object): Directory to store the outputs (rasters, and csv_files). default to ~/downloads - gee (bool): Use GEE variant, to reclassify assets or local input. default True - dst_class (str|pathlib.Path, optional): the file to be used as destination classification. for app that require specific code system the file can be set prior and the user won't have the oportunity to change it - default_class (dict|optional): the default classification system to use, need to point to existing sytem: {name: absolute_path} - folder(str, optional): the init GEE asset folder where the asset selector should start looking (debugging purpose) + results_dir: Directory to store the outputs (rasters, and csv_files). default to ~/downloads + gee: Use GEE variant, to reclassify assets or local input. default True + dst_class: the file to be used as destination classification. for app that require specific code system the file can be set prior and the user won't have the oportunity to change it + default_class: the default classification system to use, need to point to existing sytem: {name: absolute_path} + folder: the init GEE asset folder where the asset selector should start looking (debugging purpose) """ # output directory @@ -50,12 +55,12 @@ class ReclassifyTile(sw.Tile): self.aoi_model = aoi_model # create the model - self.model = rec.ReclassifyModel( + self.model = ReclassifyModel( dst_dir=self.results_dir, gee=gee, aoi_model=self.aoi_model, folder=folder ) # set the tabs elements - self.reclassify_view = rec.ReclassifyView( + self.reclassify_view = ReclassifyView( self.model, out_path=self.results_dir, gee=gee, @@ -65,7 +70,7 @@ class ReclassifyTile(sw.Tile): folder=folder, ).nest_tile() - self.table_view = rec.TableView(out_path=self.results_dir).nest_tile() + self.table_view = TableView(out_path=self.results_dir).nest_tile() # create the tab tiles = [self.reclassify_view, self.table_view] diff --git a/sepal_ui/reclassify/reclassify_view.py b/sepal_ui/reclassify/reclassify_view.py index 5d8b1daf..5a7ec6bd 100644 --- a/sepal_ui/reclassify/reclassify_view.py +++ b/sepal_ui/reclassify/reclassify_view.py @@ -1,10 +1,13 @@ from pathlib import Path +from typing import Optional, Union import ipyvuetify as v import pandas as pd from traitlets import Unicode +from typing_extensions import Self import sepal_ui.sepalwidgets as sw +from sepal_ui import aoi from sepal_ui.message import ms from sepal_ui.scripts import decorator as sd from sepal_ui.scripts import utils as su @@ -17,15 +20,15 @@ __all__ = ["ReclassifyView"] class ImportMatrixDialog(v.Dialog): - file = Unicode("").tag(sync=True) + file: Unicode = Unicode("").tag(sync=True) "the file to use" - def __init__(self, folder, **kwargs): + def __init__(self, folder: Union[str, Path], **kwargs) -> None: """ Dialog to select the file to use and fill the matrix Args: - folder (pathlike object): the path to the saved classifications + folder: the path to the saved classifications """ # create the 3 widgets @@ -48,14 +51,14 @@ class ImportMatrixDialog(v.Dialog): # js behaviour cancel.on_event("click", self._cancel) - def _cancel(self, widget, event, data): + def _cancel(self, *args) -> Self: """exit and do nothing""" self.value = False return self - def show(self): + def show(self) -> Self: self.value = True @@ -63,14 +66,13 @@ class ImportMatrixDialog(v.Dialog): class SaveMatrixDialog(v.Dialog): - """ - Dialog to setup the name of the output matrix file - - Args: - folder (pathlike object): the path to the save folder. default to ~/ - """ + def __init__(self, folder: Union[Path, str] = Path.home(), **kwargs) -> None: + """ + Dialog to setup the name of the output matrix file - def __init__(self, folder=Path.home(), **kwargs): + Args: + folder: the path to the save folder. default to ~/ + """ # save the matrix self._matrix = {} @@ -102,7 +104,7 @@ class SaveMatrixDialog(v.Dialog): self.w_file.on_event("blur", self._sanitize) self.w_file.observe(self._store_info, "v_model") - def _store_info(self, change): + def _store_info(self, change: dict) -> None: """Display where will be the file written""" new_val = change["new"] @@ -115,7 +117,9 @@ class SaveMatrixDialog(v.Dialog): self.alert.add_msg(msg) - def _cancel(self, widget, event, data): + return + + def _cancel(self, *args) -> Self: """do nothing and exit""" self.w_file.v_model = None @@ -123,7 +127,7 @@ class SaveMatrixDialog(v.Dialog): return self - def _save(self, widget, event, data): + def _save(self, *args) -> Self: """save the matrix in a specified file""" file = self.folder / f"{su.normalize_str(self.w_file.v_model)}.csv" @@ -137,8 +141,10 @@ class SaveMatrixDialog(v.Dialog): return self - def show(self, matrix): - """show the dialog and set the matrix values""" + def show(self, matrix: dict) -> Self: + """ + show the dialog and set the matrix values + """ self._matrix = matrix @@ -149,8 +155,10 @@ class SaveMatrixDialog(v.Dialog): return self - def _sanitize(self, widget, event, data): - """sanitize the used name when saving""" + def _sanitize(self, *args) -> Self: + """ + sanitize the used name when saving + """ if not self.w_file.v_model: return self @@ -161,15 +169,14 @@ class SaveMatrixDialog(v.Dialog): class ClassSelect(sw.Select): - """ - Custom widget to pick the value of a original class in the new classification system - - Args: - new_codes(dict): the dict of the new codes to use as items {code: (name, color)} - code (int): the orginal code of the class - """ + def __init__(self, new_codes: dict, old_code: int, **kwargs) -> None: + """ + Custom widget to pick the value of a original class in the new classification system - def __init__(self, new_codes, old_code, **kwargs): + Args: + new_codes: the dict of the new codes to use as items {code: (name, color)} + code: the orginal code of the class + """ # set default parameters self.items = [ @@ -188,25 +195,28 @@ class ClassSelect(sw.Select): class ReclassifyTable(sw.SimpleTable): - """ - Table to store the reclassifying information. - 2 columns are integrated, the new class value and the values in the original input - One can select multiple class to be reclassify in the new classification - Args: - model (ReclassifyModel): model embeding the traitlet dict to store the reclassifying matrix. keys: class value in dst, values: list of values in src. - dst_classes (dict|optional): a dictionnary that represent the classes of new the new classification table as {class_code: (class_name, class_color)}. class_code must be ints and class_name str. - src_classes (dict|optional): the list of existing values within the input file {class_code: (class_name, class_color)} + HEADERS: list = ms.rec.rec.headers + "name of the column header [from, to]" - Attributes: - HEADER (list): name of the column header (from, to) - model (ReclassifyModel): the reclassifyModel object to manipulate the - input file and save parameters - """ + model: Optional[ReclassifyModel] = None + "the reclassifyModel object to manipulate the input file and save parameters" - HEADERS = ms.rec.rec.headers + def __init__( + self, + model: ReclassifyModel, + dst_classes: dict = {}, + src_classes: dict = {}, + **kwargs, + ) -> None: + """ + Table to store the reclassifying information. 2 columns are integrated, the new class value and the values in the original input. One can select multiple class to be reclassify in the new classification - def __init__(self, model, dst_classes={}, src_classes={}, **kwargs): + Args: + model (ReclassifyModel): model embeding the traitlet dict to store the reclassifying matrix. keys: class value in dst, values: list of values in src. + dst_classes (dict|optional): a dictionnary that represent the classes of new the new classification table as {class_code: (class_name, class_color)}. class_code must be ints and class_name str. + src_classes (dict|optional): the list of existing values within the input file {class_code: (class_name, class_color)} + """ # default parameters self.dense = True @@ -226,13 +236,13 @@ class ReclassifyTable(sw.SimpleTable): ] self.set_table(dst_classes, src_classes) - def set_table(self, dst_classes, src_classes): + def set_table(self, dst_classes: dict, src_classes: dict) -> Self: """ Rebuild the table content based on the new_classes and codes provided Args: - dst_classes (dict|optional): a dictionnary that represent the classes of new the new classification table as {class_code: (class_name, class_color)}. class_code must be ints and class_name str. - src_classes (dict|optional): the list of existing values within the input file {class_code: (class_name, class_color)} + dst_classes: a dictionnary that represent the classes of new the new classification table as {class_code: (class_name, class_color)}. class_code must be ints and class_name str. + src_classes: the list of existing values within the input file {class_code: (class_name, class_color)} Return: self @@ -282,8 +292,10 @@ class ReclassifyTable(sw.SimpleTable): return self - def _update_matrix_values(self, change): - """Update the appropriate matrix value when a Combo select change""" + def _update_matrix_values(self, change: dict) -> Self: + """ + Update the appropriate matrix value when a Combo select change + """ # get the code of the class in the src classification code = change["owner"]._metadata["class"] @@ -295,24 +307,6 @@ class ReclassifyTable(sw.SimpleTable): class ReclassifyView(sw.Card): - """ - Stand-alone Card object allowing the user to reclassify a input file. the input can be of any type (vector or raster) and from any source (local or GEE). - The user need to provide a destination classification file (table) in the following format : 3 headless columns: 'code', 'desc', 'color'. Once all the old class have been attributed to their new class the file can be exported in the source format to local memory or GEE. the output is also savec in memory for further use in the app. It can be used as a tile in a sepal_ui app. The id\\_ of the tile is set to "reclassify_tile" - - Args: - model (ReclassifyModel): the reclassify model to manipulate the - classification dataset. default to a new one - class_path (str,optional): Folder path containing already existing - classes. Default to ~/ - out_path (str,optional): the folder to save the created classifications. - default to ~/downloads - gee (bool): either or not to set :code:`gee` to True. default to False - dst_class (str|pathlib.Path, optional): the file to be used as destination classification. for app that require specific code system the file can be set prior and the user won't have the oportunity to change it - default_class (dict|optional): the default classification system to use, need to point to existing sytem: {name: absolute_path} - folder(str, optional): the init GEE asset folder where the asset selector should start looking (debugging purpose) - save (bool, optional): Whether to write/export the result or not. - enforce_aoi (bool, optional): either or not an aoi should be set to allow the reclassification - """ MAX_CLASS = 20 "int: the number of line in the table to trigger the display of an extra toolbar and alert" @@ -355,18 +349,33 @@ class ReclassifyView(sw.Card): def __init__( self, - model=None, - class_path=Path.home(), - out_path=Path.home() / "downloads", - gee=False, - dst_class=None, - default_class={}, - aoi_model=None, - save=True, - folder="", - enforce_aoi=False, + model: Optional[ReclassifyModel] = None, + class_path: Union[str, Path] = Path.home(), + out_path: Union[str, Path] = Path.home() / "downloads", + gee: bool = False, + dst_class: Union[str, Path] = "", + default_class: dict = {}, + aoi_model: Optional[aoi.AoiModel] = None, + save: bool = True, + folder: Union[str, Path] = "", + enforce_aoi: bool = False, **kwargs, - ): + ) -> None: + """ + Stand-alone Card object allowing the user to reclassify a input file. the input can be of any type (vector or raster) and from any source (local or GEE). + The user need to provide a destination classification file (table) in the following format : 3 headless columns: 'code', 'desc', 'color'. Once all the old class have been attributed to their new class the file can be exported in the source format to local memory or GEE. the output is also savec in memory for further use in the app. It can be used as a tile in a sepal_ui app. The id\\_ of the tile is set to "reclassify_tile" + + Args: + model: the reclassify model to manipulate the classification dataset. default to a new one + class_path: Folder path containing already existing classes. Default to ~/ + out_path: the folder to save the created classifications. default to ~/downloads + gee: either or not to set :code:`gee` to True. default to False + dst_class: the file to be used as destination classification. for app that require specific code system the file can be set prior and the user won't have the oportunity to change it + default_class: the default classification system to use, need to point to existing sytem: {name: absolute_path} + folder: the init GEE asset folder where the asset selector should start looking (debugging purpose) + save: Whether to write/export the result or not. + enforce_aoi: either or not an aoi should be set to allow the reclassification + """ # create metadata to make it compatible with the framwork app system self._metadata = {"mount_id": "reclassify_tile"} @@ -581,8 +590,10 @@ class ReclassifyView(sw.Card): self.reclassify_btn.on_event("click", self.reclassify) [btn.on_event("click", self._set_dst_class_file) for btn in self.btn_list] - def _set_dst_class_file(self, widget, event, data): - """Set the destination classification according to the one selected with btn. alter the widgets properties to reflect this change""" + def _set_dst_class_file(self, widget: v.VuetifyWidget, *args) -> Self: + """ + Set the destination classification according to the one selected with btn. alter the widgets properties to reflect this change + """ # get the filename filename = widget._metadata["path"] @@ -599,12 +610,9 @@ class ReclassifyView(sw.Card): return self - def load_matrix_content(self, widget, event, data): + def load_matrix_content(self, widget: v.VuetifyWidget, *args) -> Self: """ Load the content of the file in the matrix. The table need to be already set to perform this operation - - Return: - self """ self.import_dialog.value = False file = self.import_dialog.w_file.v_model @@ -656,13 +664,10 @@ class ReclassifyView(sw.Card): return self - def reclassify(self, widget, event, data): + def reclassify(self, *args) -> Self: """ Reclassify the input and store it in the appropriate format. The input is not saved locally to avoid memory overload. - - Return: - self """ # create the output file @@ -674,8 +679,10 @@ class ReclassifyView(sw.Card): return self @sd.switch("loading", "disabled", on_widgets=["w_code"]) - def _update_band(self, change): - """Update the band possibility to the available bands/properties of the input""" + def _update_band(self, *args) -> Self: + """ + Update the band possibility to the available bands/properties of the input + """ # guess the file type and save it in the model self.model.get_type() @@ -687,13 +694,10 @@ class ReclassifyView(sw.Card): @sd.switch("disabled", on_widgets=["reclassify_btn"], targets=[False]) @sd.switch("table_created", on_widgets=["model"], targets=[True]) - def get_reclassify_table(self, widget, event, data): + def get_reclassify_table(self, *args) -> Self: """ Display a reclassify table which will lead the user to select a local code 'from user' to a target code based on a classes file - - Return: - self """ # get the destination classes @@ -716,14 +720,11 @@ class ReclassifyView(sw.Card): return self - def nest_tile(self): + def nest_tile(self) -> Self: """ Prepare the view to be used as a nested component in a tile. the elevation will be set to 0 and the title remove from children. The mount_id will also be changed to nested - - Return: - self """ # remove id diff --git a/sepal_ui/reclassify/table_view.py b/sepal_ui/reclassify/table_view.py index ea708156..d8272b13 100644 --- a/sepal_ui/reclassify/table_view.py +++ b/sepal_ui/reclassify/table_view.py @@ -1,10 +1,12 @@ from colorsys import rgb_to_hls, rgb_to_hsv from pathlib import Path +from typing import Optional, Union import ipyvuetify as v import pandas as pd from matplotlib.colors import to_rgb from traitlets import Int +from typing_extensions import Self from sepal_ui import sepalwidgets as sw from sepal_ui.message import ms @@ -19,22 +21,14 @@ class ClassTable(sw.DataTable): SCHEMA = param.SCHEMA - def __init__(self, out_path=Path.home() / "downloads", **kwargs): + def __init__( + self, out_path: Union[str, Path] = Path.home() / "downloads", **kwargs + ) -> None: """ Custom data table to modify, display and save classification. From this interface, a user can modify a classification starting from a scratch or by loading a classification file. the display datatable allow all the CRUD fonctionality (create, read, update, delete). - Attributes: - SCHEMA (const list): the schema of the classification: ['id', 'code', 'description', 'color'] - out_path (pathlib.Path): the output folder to save the created classifications - save_dialog (v.Dialog): the Dialog to save the classification (select name and format) - edit_dialog (v.Dialog): the dialog to edit/create a noew line in the data-table. The user will provide: the code, the description and the color (with a color selector) - edit_icon (v.Icon): the btn to open the edit_dialog (a line need to be selected in the table) - delete_icon (v.icon): the btn to delete a selected line in the table - add_icon (v.Icon): the btn to add a new line in the table - save_icon (v.Icon): the btn to open the save_dialog and save the current classification table - Args: - out_path (str|optional): output path where table will be saved, default to ~/downloads/ + out_path: output path where table will be saved, default to ~/downloads/ """ # save the output path @@ -110,15 +104,12 @@ class ClassTable(sw.DataTable): self.add_btn.on_event("click", self._add_event) self.save_btn.on_event("click", self._save_event) - def populate_table(self, items_file=None): + def populate_table(self, items_file: Union[Path, str] = "") -> Self: """ Populate table. It will fill the table with the item contained in the items_file parameter. If no file is provided the table is reset. Args: items (Path object|optional): file containing classes and description - - Return: - self """ # If there is not any file passed as an argument, populate and empy table @@ -151,7 +142,7 @@ class ClassTable(sw.DataTable): return self - def _save_event(self, widget, event, data): + def _save_event(self, *args) -> None: """open the save dialog to save the current table in a specific formatted table""" if not self.items: @@ -161,7 +152,7 @@ class ClassTable(sw.DataTable): return - def _edit_event(self, widget, event, data): + def _edit_event(self, *args) -> None: """Open the edit dialog and fill it with current line information""" if not self.v_model: @@ -171,14 +162,14 @@ class ClassTable(sw.DataTable): return - def _add_event(self, widget, event, data): + def _add_event(self, *args) -> None: """Open the edit dialog to create a new line to the table""" self.edit_dialog.update() return - def _remove_event(self, widget, event, data): + def _remove_event(self, *args) -> None: """Remove current selection (self.v_model) element from table""" if not self.v_model: @@ -196,21 +187,12 @@ class EditDialog(v.Dialog): TITLES = ms.rec.table.edit_dialog.titles - def __init__(self, table, **kwargs): + def __init__(self, table: ClassTable, **kwargs) -> None: """ Dialog to modify/create new elements from the ClassTable data_table Args: - table (ClassTable, v.DataTable): Table linked with dialog - - Attributes: - TITLES (list): the list of potential header (translated at the start of the application) - table (classTable): the classTable associated with the dialog - title (v.CardTitle): the title of the card ('modify' or 'new') - save (sw.Btn): the btn to validate the new line and save it in the datatable - modify (sw.Btn): the btn to validate the edited line and save it in the datatable - cancel (sw.Btn): the btn to close the dialog without saving anything - widgets (list): the list of widget to control the new element state (id, code, description, color) in this order. + table: Table linked with dialog """ # custom attributes @@ -274,15 +256,12 @@ class EditDialog(v.Dialog): self.modify.on_event("click", self._modify) self.cancel.on_event("click", self._cancel) - def update(self, data=[None, None, None, None]): + def update(self, data: list = [None, None, None, None]) -> Self: """ upadte the dialog with the provided information and activate it Args: - data (list): the text value of the selected line (id, code, description, color). default to 4 None (new line) - - Return: - self + data: the text value of the selected line (id, code, description, color). default to 4 None (new line) """ # change the title accodring to the presence of data @@ -341,7 +320,7 @@ class EditDialog(v.Dialog): return self - def _modify(self, widget, event, data): + def _modify(self, *args) -> None: """Modify elements in the data_table and close the dialog""" # modify a local copy of the items @@ -375,7 +354,7 @@ class EditDialog(v.Dialog): return - def _save(self, widget, event, data): + def _save(self, *args) -> None: """Add elements to the table and close the dialog""" # modify a local copy of the items @@ -397,7 +376,7 @@ class EditDialog(v.Dialog): return - def _cancel(self, widget, event, data): + def _cancel(self, *args) -> None: """Close dialog and do nothing""" self.v_model = False @@ -407,24 +386,16 @@ class EditDialog(v.Dialog): class SaveDialog(v.Dialog): - reload = Int().tag(sync=True) + reload = Int(0).tag(sync=True) + "a traitlet to inform the rest of the app that saving is complete" - def __init__(self, table, out_path, **kwargs): + def __init__(self, table: ClassTable, out_path: Union[str, Path], **kwargs) -> None: """ Dialog to save as .csv file the content of a ClassTable data table Args: - table (ClassTable): Table linked with dialog - out_path (str): Folder path to store table content - - Attributes: - reload (Int): a traitlet to inform the rest of the app that saving is complete - table (ClassTable): Table linked with dialog - out_path (str): Folder path to store table content - w_file_name (v.TextField): the filename to use in out_path - save (sw.Btn): save btn to launch the saving of the table data in the out_path using the filename provided in the widget - cancel (sw.Btn): btn to close the dialog and do nothing - alert (sw.Alert): an alert to display evolution of the saving process (errors) + table: Table linked with dialog + out_path: Folder path to store table content """ # gather the table and saving params @@ -481,7 +452,7 @@ class SaveDialog(v.Dialog): self.w_file_name.on_event("blur", self._normalize_name) self.w_file_name.observe(self._store_info, "v_model") - def _store_info(self, change): + def _store_info(self, change: dict) -> None: """Display where will be the file written""" new_val = change["new"] @@ -494,12 +465,11 @@ class SaveDialog(v.Dialog): self.alert.add_msg(msg) - def show(self): + return + + def show(self) -> Self: """ display the dialog and write down the text in the alert - - Return: - self """ self.v_model = True @@ -510,7 +480,7 @@ class SaveDialog(v.Dialog): return self - def _normalize_name(self, widget, event, data): + def _normalize_name(self, widget: v.VuetifyWidget, *args) -> None: """Replace the name with it's normalized version""" # normalized the name @@ -518,7 +488,7 @@ class SaveDialog(v.Dialog): return - def _save(self, widget, event, data): + def _save(self, *args) -> None: """Write current table on a text file""" # set the file name @@ -537,7 +507,7 @@ class SaveDialog(v.Dialog): return - def _cancel(self, widget, event, data): + def _cancel(self, *args) -> None: """hide the widget and do nothing""" self.v_model = False @@ -547,36 +517,39 @@ class SaveDialog(v.Dialog): class TableView(sw.Card): - title = None + title: Optional[v.CardTitle] = None "v.CardTitle: the title of the card" - class_path = None + class_path: str = "" "str: Folder path containing already existing classes" - out_path = None + out_path: str = "" "str: the folder to save the created classifications" - w_class_file = None + w_class_file: Optional[sw.FileInput] = None "sw.FileInput: the file input of the existing classification system" - w_class_table = None + w_class_table: Optional[ClassTable] = None "ClassTable: the classtable (CRUD) to manage the editing of the classification" - btn = None + btn: Optional[sw.Btn] = None "sw.Btn: the btn to start loading file data into the table" - alert = None + alert: Optional[sw.Alert] = None "sw.Alert: the alert to display loading information (error and success)" def __init__( - self, class_path=Path.home(), out_path=Path.home() / "downloads", **kwargs + self, + class_path: Union[str, Path] = Path.home(), + out_path: Union[str, Path] = Path.home() / "downloads", + **kwargs, ): """ Stand-alone Card object allowing the user to build custom class table. The user can start from an existing table or start from scratch. It gives the oportunity to change: the value, the class name and the color. It can be used as a tile in a sepal_ui app. The id\\_ of the tile is set to "classification_tile" Args: - class_path (str|optional): Folder path containing already existing classes. Default to ~/ - out_path (str|optional): the folder to save the created classifications. default to ~/downloads + class_path: Folder path containing already existing classes. Default to ~/ + out_path: the folder to save the created classifications. default to ~/downloads """ # create metadata to make it compatible with the framwork app system @@ -642,12 +615,9 @@ class TableView(sw.Card): self.btn.on_event("click", self.get_class_table) @sd.loading_button(debug=True) - def get_class_table(self, widget, event, data): + def get_class_table(self, *args) -> Self: """ Display class table widget in view - - Return: - self """ # load the existing file into the table @@ -655,14 +625,11 @@ class TableView(sw.Card): return self - def nest_tile(self): + def nest_tile(self) -> Self: """ Prepare the view to be used as a nested component in a tile. the elevation will be set to 0 and the title remove from children. The mount_id will also be changed to nested - - Return: - self """ # remove id diff --git a/sepal_ui/scripts/gee.py b/sepal_ui/scripts/gee.py index f9258000..a3aa17ad 100644 --- a/sepal_ui/scripts/gee.py +++ b/sepal_ui/scripts/gee.py @@ -6,10 +6,10 @@ import ee import ipyvuetify as v from sepal_ui.message import ms -from sepal_ui.scripts import utils as su +from sepal_ui.scripts import decorator as sd -@su.need_ee +@sd.need_ee def wait_for_completion(task_descripsion: str, widget_alert: v.Alert = None) -> str: """ Wait until the selected process is finished. Display some output information @@ -45,7 +45,7 @@ def wait_for_completion(task_descripsion: str, widget_alert: v.Alert = None) -> return state -@su.need_ee +@sd.need_ee def is_task(task_descripsion: str) -> ee.batch.Task: """ Search for the described task in the user Task list return None if nothing is found @@ -66,7 +66,7 @@ def is_task(task_descripsion: str) -> ee.batch.Task: return current_task -@su.need_ee +@sd.need_ee def is_running(task_descripsion: str) -> ee.batch.Task: """ Search for the described task in the user Task list return None if nothing is currently running @@ -86,7 +86,7 @@ def is_running(task_descripsion: str) -> ee.batch.Task: return current_task -@su.need_ee +@sd.need_ee def get_assets(folder: Union[str, Path] = "", asset_list: List[str] = []) -> List[str]: """ Get all the assets from the parameter folder. every nested asset will be displayed. @@ -113,7 +113,7 @@ def get_assets(folder: Union[str, Path] = "", asset_list: List[str] = []) -> Lis return asset_list -@su.need_ee +@sd.need_ee def is_asset(asset_name: str, folder: Union[str, Path] = "") -> bool: """ Check if the asset already exist in the user asset folder diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 40c56a97..74c5f2b3 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -17,6 +17,7 @@ from typing_extensions import Self from sepal_ui import color from sepal_ui.frontend import styles as ss from sepal_ui.message import ms +from sepal_ui.scripts import decorator as sd from sepal_ui.scripts import gee from sepal_ui.scripts import utils as su from sepal_ui.sepalwidgets.btn import Btn @@ -364,7 +365,7 @@ class FileInput(v.Flex, SepalWidget): return self - @su.switch("indeterminate", on_widgets=["loading"]) + @sd.switch("indeterminate", on_widgets=["loading"]) def _change_folder(self) -> None: """ Change the target folder @@ -563,7 +564,7 @@ class LoadTableField(v.Col, SepalWidget): return - @su.switch("loading", on_widgets=["IdSelect", "LngSelect", "LatSelect"]) + @sd.switch("loading", on_widgets=["IdSelect", "LngSelect", "LatSelect"]) def _on_file_input_change(self, change: dict) -> Self: """ Update the select content when the fileinput v_model is changing @@ -672,7 +673,7 @@ class AssetSelect(v.Combobox, SepalWidget): types: t.List = t.List().tag(sync=True) "The list of types accepted by the asset selector. names need to be valide TYPES and changing this value will trigger the reload of the asset items." - @su.need_ee + @sd.need_ee def __init__( self, folder: Union[str, Path] = "", @@ -725,7 +726,7 @@ class AssetSelect(v.Combobox, SepalWidget): self.on_event("click:prepend", self._get_items) self.observe(self._get_items, "default_asset") - @su.switch("loading") + @sd.switch("loading") def _validate(self, change: dict) -> None: """ Validate the selected asset. Throw an error message if is not accesible or not in the type list. @@ -754,7 +755,7 @@ class AssetSelect(v.Combobox, SepalWidget): return - @su.switch("loading", "disabled") + @sd.switch("loading", "disabled") def _get_items(self, *args) -> Self: # init the item list @@ -819,11 +820,11 @@ class PasswordField(v.TextField, SepalWidget): """ # default behavior - kwargs["label"] = kwargs.pop("label", "Password") + kwargs["label"] = kwargs.pop("label", ms.password_field.label) kwargs["class_"] = kwargs.pop("class_", "mr-2") kwargs["v_model"] = kwargs.pop("v_model", "") kwargs["type"] = "password" - kwargs["append_icon"] = kwargs.pop("append_icon", "mdi-eye-off") + kwargs["append_icon"] = kwargs.pop("append_icon", "fa-solid fa-eye-slash") # init the widget with the remaining kwargs super().__init__(**kwargs) @@ -838,10 +839,10 @@ class PasswordField(v.TextField, SepalWidget): if self.type == "text": self.type = "password" - self.append_icon = "mdi-eye-off" + self.append_icon = "fa-solid fa-eye-slash" else: self.type = "text" - self.append_icon = "mdi-eye" + self.append_icon = "fa-solid fa-eye" return @@ -875,8 +876,10 @@ class NumberField(v.TextField, SepalWidget): # set default params kwargs["type"] = "number" - kwargs["append_outer_icon"] = kwargs.pop("append_outer_icon", "mdi-plus") - kwargs["prepend_icon"] = kwargs.pop("prepend_icon", "mdi-minus") + kwargs["append_outer_icon"] = kwargs.pop( + "append_outer_icon", "fa-solid fa-plus" + ) + kwargs["prepend_icon"] = kwargs.pop("prepend_icon", "fa-solid fa-minus") kwargs["v_model"] = kwargs.pop("v_model", 0) kwargs["readonly"] = kwargs.pop("readonly", True) @@ -998,7 +1001,7 @@ class VectorField(v.Col, SepalWidget): return self - @su.switch("loading", on_widgets=["w_column", "w_value"]) + @sd.switch("loading", on_widgets=["w_column", "w_value"]) def _update_file(self, change: dict) -> Self: """update the file name, the v_model and reset the other widgets""" @@ -1034,7 +1037,7 @@ class VectorField(v.Col, SepalWidget): return self - @su.switch("loading", on_widgets=["w_value"]) + @sd.switch("loading", on_widgets=["w_value"]) def _update_column(self, change: dict) -> Self: """Update the column name and empty the value list""" diff --git a/sepal_ui/sepalwidgets/widget.py b/sepal_ui/sepalwidgets/widget.py index 0c1d9551..1f332be8 100644 --- a/sepal_ui/sepalwidgets/widget.py +++ b/sepal_ui/sepalwidgets/widget.py @@ -1,3 +1,4 @@ +from pathlib import Path from typing import Optional, Union import ipyvuetify as v @@ -81,22 +82,11 @@ class CopyToClip(v.VuetifyTemplate): self.components = {"mytf": self.tf} # template with js behaviour - self.template = """ - <mytf/> - <script> - {methods: { - jupyter_clip(_txt) { - var tempInput = document.createElement("input"); - tempInput.value = _txt; - document.body.appendChild(tempInput); - tempInput.focus(); - tempInput.select(); - document.execCommand("copy"); - document.body.removeChild(tempInput); - } - }} - </script> - """ + js_dir = Path(__file__).parents[1] / "frontend/js" + clip = (js_dir / "jupyter_clip.js").read_text() + self.template = ( + "<mytf/>" "<script>{methods: {jupyter_clip(_txt) {%s}}}</script>" % clip + ) super().__init__()
NumberField is not using fontawesome icons
12rambau/sepal_ui
diff --git a/tests/check_warnings.py b/tests/check_warnings.py new file mode 100644 index 00000000..af336d96 --- /dev/null +++ b/tests/check_warnings.py @@ -0,0 +1,56 @@ +import sys +from pathlib import Path + + +def check_warnings(file): + """ + Check the list of warnings produced by the GitHub CI tests + raise errors if there are unexpected ones and/or if some are missing + + Args: + file (pathlib.Path): the path to the generated warning.txt file from + the CI build + + Return: + 0 if the warnings are all there + 1 if some warning are not registered or unexpected + """ + + # print some log + print("\n=== Sphinx Warnings test ===\n") + + # find the file where all the known warnings are stored + warning_file = Path(__file__).parent / "data" / "warning_list.txt" + + test_warnings = file.read_text().strip().split("\n") + ref_warnings = warning_file.read_text().strip().split("\n") + + print( + f'Checking build warnings in file: "{file}" and comparing to expected ' + f'warnings defined in "{warning_file}"\n\n' + ) + + # find all the missing warnings + missing_warnings = [] + for wa in ref_warnings: + index = [i for i, twa in enumerate(test_warnings) if wa in twa] + if len(index) == 0: + missing_warnings += [wa] + print(f"Warning was not raised: {wa}\n") + else: + test_warnings.pop(index[0]) + + # the remaining one are unexpected + for twa in test_warnings: + print(f"Unexpected warning: {twa}\n") + + return len(missing_warnings) != 0 or len(test_warnings) != 0 + + +if __name__ == "__main__": + + # cast the file to path and resolve to an absolute one + file = Path.cwd() / "warnings.txt" + + # execute the test + sys.exit(check_warnings(file)) diff --git a/tests/data/warning_list.txt b/tests/data/warning_list.txt new file mode 100644 index 00000000..c4c475f8 --- /dev/null +++ b/tests/data/warning_list.txt @@ -0,0 +1,3 @@ +ERROR: Unknown target name: "type". +ERROR: Document or section may not begin with a transition. +WARNING: document isn't included in any toctree \ No newline at end of file diff --git a/tests/test_AoiModel.py b/tests/test_AoiModel.py index f240e543..cba391be 100644 --- a/tests/test_AoiModel.py +++ b/tests/test_AoiModel.py @@ -9,36 +9,36 @@ from sepal_ui import aoi class TestAoiModel: - def test_init_no_ee(self, alert, fake_vector): + def test_init_no_ee(self, fake_vector): # default init - aoi_model = aoi.AoiModel(alert, gee=False) + aoi_model = aoi.AoiModel(gee=False) assert isinstance(aoi_model, aoi.AoiModel) assert aoi_model.gee is False # with a default vector - aoi_model = aoi.AoiModel(alert, vector=fake_vector, gee=False) + aoi_model = aoi.AoiModel(vector=fake_vector, gee=False) assert aoi_model.name == "gadm36_VAT_0" # test with a non ee admin admin = "VAT" # GADM Vatican city - aoi_model = aoi.AoiModel(alert, gee=False, admin=admin) + aoi_model = aoi.AoiModel(gee=False, admin=admin) assert aoi_model.name == "VAT" return @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") - def test_init_ee(alert, gee_dir): + def test_init_ee(self, gee_dir): # default init - aoi_model = aoi.AoiModel(alert, folder=gee_dir) + aoi_model = aoi.AoiModel(folder=gee_dir) assert isinstance(aoi_model, aoi.AoiModel) assert aoi_model.gee is True # with default assetId asset_id = str(gee_dir / "feature_collection") - aoi_model = aoi.AoiModel(alert, asset=asset_id, folder=gee_dir) + aoi_model = aoi.AoiModel(asset=asset_id, folder=gee_dir) assert aoi_model.asset_name == asset_id assert aoi_model.default_asset == asset_id @@ -48,23 +48,23 @@ class TestAoiModel: # check that wrongly defined asset_name raise errors with pytest.raises(Exception): - aoi_model = aoi.AoiModel(alert, folder=gee_dir) + aoi_model = aoi.AoiModel(folder=gee_dir) aoi_model._from_asset({"pathname": None}) with pytest.raises(Exception): - aoi_model = aoi.AoiModel(alert, folder=gee_dir) + aoi_model = aoi.AoiModel(folder=gee_dir) asset = {"pathname": asset_id, "column": "data", "value": None} aoi_model._from_asset(asset) # it should be the same with a different name - aoi_model = aoi.AoiModel(alert, folder=gee_dir) + aoi_model = aoi.AoiModel(folder=gee_dir) asset = {"pathname": asset_id, "column": "data", "value": 0} aoi_model._from_asset(asset) assert aoi_model.name == "feature_collection_data_0" # with a default admin admin = "110" # GAUL Vatican city - aoi_model = aoi.AoiModel(alert, admin=admin, folder=gee_dir) + aoi_model = aoi.AoiModel(admin=admin, folder=gee_dir) assert aoi_model.name == "VAT" return @@ -121,7 +121,7 @@ class TestAoiModel: return - def test_clear_attributes(self, alert, aoi_model_outputs, aoi_model_traits): + def test_clear_attributes(self, aoi_model_outputs, aoi_model_traits): aoi_model = aoi.AoiModel(gee=False) @@ -151,7 +151,7 @@ class TestAoiModel: assert all([is_none(out) for out in aoi_model_outputs]) # check that default are saved - aoi_model = aoi.AoiModel(alert, admin="VAT", gee=False) # GADM for Vatican + aoi_model = aoi.AoiModel(admin="VAT", gee=False) # GADM for Vatican # insert dummy parameter [set_trait(trait) for trait in aoi_model_traits] @@ -192,9 +192,9 @@ class TestAoiModel: return - def test_set_object(self, alert): + def test_set_object(self): - aoi_model = aoi.AoiModel(alert, gee=False) + aoi_model = aoi.AoiModel(gee=False) # test that no method returns an error with pytest.raises(Exception): @@ -202,9 +202,9 @@ class TestAoiModel: return - def test_from_admin(self, alert, gee_dir): + def test_from_admin(self, gee_dir): - aoi_model = aoi.AoiModel(alert, folder=gee_dir) + aoi_model = aoi.AoiModel(folder=gee_dir) # with fake number with pytest.raises(Exception): @@ -217,9 +217,9 @@ class TestAoiModel: return @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") - def test_from_point(self, alert, fake_points, gee_dir): + def test_from_point(self, fake_points, gee_dir): - aoi_model = aoi.AoiModel(alert, folder=gee_dir, gee=False) + aoi_model = aoi.AoiModel(folder=gee_dir, gee=False) # uncomplete json points = { @@ -244,9 +244,9 @@ class TestAoiModel: return @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") - def test_from_vector(self, alert, gee_dir, fake_vector): + def test_from_vector(self, gee_dir, fake_vector): - aoi_model = aoi.AoiModel(alert, folder=gee_dir, gee=False) + aoi_model = aoi.AoiModel(folder=gee_dir, gee=False) # with no pathname with pytest.raises(Exception): @@ -270,9 +270,9 @@ class TestAoiModel: return @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") - def test_from_geo_json(self, alert, gee_dir, square): + def test_from_geo_json(self, gee_dir, square): - aoi_model = aoi.AoiModel(alert, folder=gee_dir, gee=False) + aoi_model = aoi.AoiModel(folder=gee_dir, gee=False) # no points with pytest.raises(Exception): @@ -286,11 +286,11 @@ class TestAoiModel: return @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") - def test_from_asset(self, alert, gee_dir): + def test_from_asset(self, gee_dir): # init parameters asset_id = str(gee_dir / "feature_collection") - aoi_model = aoi.AoiModel(alert, folder=gee_dir) + aoi_model = aoi.AoiModel(folder=gee_dir) # no asset name with pytest.raises(Exception): @@ -381,12 +381,12 @@ class TestAoiModel: return @pytest.fixture - def test_model(self, alert, gee_dir): + def test_model(self, gee_dir): """ Create a test AoiModel based on GEE using Vatican """ admin = "110" # vatican city (smalest adm0 feature) - return aoi.AoiModel(alert, admin=admin, folder=gee_dir) + return aoi.AoiModel(admin=admin, folder=gee_dir) @pytest.fixture(scope="class") def aoi_model_traits(self): diff --git a/tests/test_PasswordField.py b/tests/test_PasswordField.py index 5d930a63..d4ff8855 100644 --- a/tests/test_PasswordField.py +++ b/tests/test_PasswordField.py @@ -16,12 +16,12 @@ class TestPasswordField: # change the viz once password._toggle_pwd(None, None, None) assert password.type == "text" - assert password.append_icon == "mdi-eye" + assert password.append_icon == "fa-solid fa-eye" # change it a second time password._toggle_pwd(None, None, None) assert password.type == "password" - assert password.append_icon == "mdi-eye-off" + assert password.append_icon == "fa-solid fa-eye-slash" return diff --git a/tests/test_ReclassifyView.py b/tests/test_ReclassifyView.py index ad7124bc..84ad221e 100644 --- a/tests/test_ReclassifyView.py +++ b/tests/test_ReclassifyView.py @@ -11,7 +11,7 @@ from sepal_ui.reclassify import ReclassifyModel, ReclassifyView class TestReclassifyView: @pytest.mark.skipif(not ee.data._credentials, reason="GEE is not set") - def test_init_exception(alert, gee_dir): + def test_init_exception(self, gee_dir): """Test exceptions""" aoi_model = aoi.AoiModel(gee=False) @@ -146,10 +146,10 @@ class TestReclassifyView: return @pytest.fixture - def view_local(self, tmp_dir, class_file, alert): + def view_local(self, tmp_dir, class_file): """return a local reclassify view""" - aoi_model = aoi.AoiModel(alert, gee=False) + aoi_model = aoi.AoiModel(gee=False) return ReclassifyView( aoi_model=aoi_model, @@ -160,10 +160,10 @@ class TestReclassifyView: ) @pytest.fixture - def view_gee(self, tmp_dir, class_file, gee_dir, alert): + def view_gee(self, tmp_dir, class_file, gee_dir): """return a gee reclassify view""" - aoi_model = aoi.AoiModel(alert, gee=True, folder=str(gee_dir)) + aoi_model = aoi.AoiModel(gee=True, folder=str(gee_dir)) return ReclassifyView( aoi_model=aoi_model,
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 13 }
2.13
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-sugar", "pytest-icdiff", "pytest-cov", "pytest-deadfixtures", "Flake8-pyproject", "nox", "nbmake" ], "pre_install": [ "apt-get update", "apt-get install -y gcc", "pip install --find-links=https://girder.github.io/large_image_wheels --no-cache GDAL", "pip install localtileserver" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 aniso8601==10.0.0 annotated-types==0.7.0 anyio==3.7.1 argcomplete==3.5.3 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 blinker==1.9.0 branca==0.8.1 cachelib==0.13.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 color-operations==0.2.0 colorama==0.4.6 colorlog==6.9.0 comm==0.2.2 commitizen==4.4.1 contourpy==1.3.0 coverage==7.8.0 cryptography==44.0.2 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decli==0.6.2 decorator==5.2.1 defusedxml==0.7.1 dependency-groups==1.3.0 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 flake8==7.2.0 Flake8-pyproject==1.2.3 Flask==3.1.0 Flask-Caching==2.3.1 flask-cors==5.0.1 flask-restx==1.3.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 GDAL==3.11.0 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 icdiff==2.0.7 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 itsdangerous==2.2.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 localtileserver==0.10.6 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mccabe==0.7.0 mistune==3.1.3 morecantile==6.2.0 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbmake==1.5.5 nest-asyncio==1.6.0 nodeenv==1.9.1 nox==2025.2.9 numexpr==2.10.2 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a6 platformdirs==4.3.7 pluggy==1.5.0 pprintpp==0.4.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycodestyle==2.13.0 pycparser==2.22 pydantic==2.11.1 pydantic_core==2.33.0 pyflakes==3.3.2 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pystac==1.10.1 pytest==8.3.5 pytest-cov==6.0.0 pytest-deadfixtures==2.2.1 pytest-icdiff==0.9 pytest-sugar==1.0.0 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rio-cogeo==5.4.1 rio-tiler==7.5.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 scooby==0.10.0 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@549667ffe968ab4d631766a96024819b0fabff00#egg=sepal_ui server-thread==0.3.0 shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==2.5.0 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tomlkit==0.13.2 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==3.1.3 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - aniso8601==10.0.0 - annotated-types==0.7.0 - anyio==3.7.1 - argcomplete==3.5.3 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - blinker==1.9.0 - branca==0.8.1 - cachelib==0.13.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - color-operations==0.2.0 - colorama==0.4.6 - colorlog==6.9.0 - comm==0.2.2 - commitizen==4.4.1 - contourpy==1.3.0 - coverage==7.8.0 - cryptography==44.0.2 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decli==0.6.2 - decorator==5.2.1 - defusedxml==0.7.1 - dependency-groups==1.3.0 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - flake8==7.2.0 - flake8-pyproject==1.2.3 - flask==3.1.0 - flask-caching==2.3.1 - flask-cors==5.0.1 - flask-restx==1.3.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - gdal==3.11.0 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - icdiff==2.0.7 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - itsdangerous==2.2.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - localtileserver==0.10.6 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mccabe==0.7.0 - mistune==3.1.3 - morecantile==6.2.0 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbmake==1.5.5 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - nox==2025.2.9 - numexpr==2.10.2 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a6 - platformdirs==4.3.7 - pluggy==1.5.0 - pprintpp==0.4.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycodestyle==2.13.0 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pyflakes==3.3.2 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pystac==1.10.1 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-deadfixtures==2.2.1 - pytest-icdiff==0.9 - pytest-sugar==1.0.0 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rio-cogeo==5.4.1 - rio-tiler==7.5.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - scooby==0.10.0 - send2trash==1.8.3 - sepal-ui==2.13.0 - server-thread==0.3.0 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==2.5.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tomlkit==0.13.2 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==3.1.3 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_PasswordField.py::TestPasswordField::test_toogle_viz" ]
[ "tests/test_AoiModel.py::TestAoiModel::test_clear_attributes" ]
[ "tests/test_AoiModel.py::TestAoiModel::test_set_object", "tests/test_PasswordField.py::TestPasswordField::test_init", "tests/test_ReclassifyView.py::TestReclassifyView::test_init_local", "tests/test_ReclassifyView.py::TestReclassifyView::test_set_dst_class_file" ]
[]
MIT License
null
null
12rambau__sepal_ui-747
a683a7665a9710acd5ca939308e18539e92014b7
2023-02-08 10:00:39
22c831cffe193cb87de2720b655ebd069e585f45
diff --git a/sepal_ui/sepalwidgets/sepalwidget.py b/sepal_ui/sepalwidgets/sepalwidget.py index 40826809..00cbe015 100644 --- a/sepal_ui/sepalwidgets/sepalwidget.py +++ b/sepal_ui/sepalwidgets/sepalwidget.py @@ -177,11 +177,11 @@ class SepalWidget(v.VuetifyWidget): is_klass = isinstance(w, klass) is_val = w.attributes.get(attr, "niet") == value if attr and value else True - # asumption: searched element won't be nested inside one another if is_klass and is_val: elements.append(w) - else: - elements = self.get_children(w, klass, attr, value, id_, elements) + + # always search for nested elements + elements = self.get_children(w, klass, attr, value, id_, elements) return elements
make get_children recursively again previous implementation used recursion to find all children within the widget that matches with the query, now it returns only first level of matching children, could we make it reclusively again?
12rambau/sepal_ui
diff --git a/tests/test_SepalWidget.py b/tests/test_SepalWidget.py index 3abd719f..22699d69 100644 --- a/tests/test_SepalWidget.py +++ b/tests/test_SepalWidget.py @@ -108,24 +108,23 @@ class TestSepalWidget: assert len(res) == 0 # search for specific attributes in any class - # one alert that could match is ignored because the parent card is identified - # earlier, that's a feature res = test_card.get_children(attr="id", value=3) - assert len(res) == 6 + assert len(res) == 7 assert isinstance(res[0], sw.Alert) assert isinstance(res[1], sw.Alert) assert isinstance(res[2], sw.Alert) assert isinstance(res[3], sw.Card) assert isinstance(res[4], sw.Alert) - assert isinstance(res[5], sw.Btn) + assert isinstance(res[5], sw.Alert) + assert isinstance(res[6], sw.Btn) - # missing value (all children will match so nested are ignored) + # missing value (all children will match including icons) res = test_card.get_children(attr="id") - assert len(res) == 10 + assert len(res) == 40 - # missing attr (all children will match so nested are ignored) + # missing attr (all children will match including icons) res = test_card.get_children(value=5) - assert len(res) == 10 + assert len(res) == 40 # no match search attr res = test_card.get_children(attr="toto", value="toto")
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
2.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-sugar", "pytest-icdiff", "pytest-cov", "pytest-deadfixtures", "Flake8-pyproject", "nox", "nbmake" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 anyio==3.7.1 argcomplete==3.5.3 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 colorlog==6.9.0 comm==0.2.2 commitizen==4.4.1 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decli==0.6.2 decorator==5.2.1 defusedxml==0.7.1 dependency-groups==1.3.0 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 flake8==7.2.0 Flake8-pyproject==1.2.3 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 icdiff==2.0.7 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mccabe==0.7.0 mistune==3.1.3 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbmake==1.5.5 nest-asyncio==1.6.0 nodeenv==1.9.1 nox==2025.2.9 numpy==2.0.2 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a6 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pprintpp==0.4.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycodestyle==2.13.0 pycparser==2.22 pyflakes==3.3.2 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 pytest-deadfixtures==2.2.1 pytest-icdiff==0.9 pytest-sugar==1.0.0 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@a683a7665a9710acd5ca939308e18539e92014b7#egg=sepal_ui shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==2.5.0 terminado==0.18.1 tinycss2==1.4.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tomlkit==0.13.2 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - anyio==3.7.1 - argcomplete==3.5.3 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - colorlog==6.9.0 - comm==0.2.2 - commitizen==4.4.1 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decli==0.6.2 - decorator==5.2.1 - defusedxml==0.7.1 - dependency-groups==1.3.0 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - flake8==7.2.0 - flake8-pyproject==1.2.3 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - icdiff==2.0.7 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mccabe==0.7.0 - mistune==3.1.3 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbmake==1.5.5 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - nox==2025.2.9 - numpy==2.0.2 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a6 - platformdirs==4.3.7 - pprintpp==0.4.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycodestyle==2.13.0 - pycparser==2.22 - pyflakes==3.3.2 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pytest-cov==6.0.0 - pytest-deadfixtures==2.2.1 - pytest-icdiff==0.9 - pytest-sugar==1.0.0 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - sepal-ui==2.15.0 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==2.5.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomlkit==0.13.2 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_SepalWidget.py::TestSepalWidget::test_get_children" ]
[]
[ "tests/test_SepalWidget.py::TestSepalWidget::test_init", "tests/test_SepalWidget.py::TestSepalWidget::test_set_viz", "tests/test_SepalWidget.py::TestSepalWidget::test_show", "tests/test_SepalWidget.py::TestSepalWidget::test_hide", "tests/test_SepalWidget.py::TestSepalWidget::test_toggle_viz", "tests/test_SepalWidget.py::TestSepalWidget::test_reset", "tests/test_SepalWidget.py::TestSepalWidget::test_set_children", "tests/test_SepalWidget.py::TestSepalWidget::test_set_children_error" ]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-747
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-747
12rambau__sepal_ui-758
27a18eba37bec8ef1cabfa6bcc4022164ebc4c3b
2023-02-13 16:42:43
22c831cffe193cb87de2720b655ebd069e585f45
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 04e69553..0cb7a9bf 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -156,6 +156,12 @@ class DatePicker(v.Layout, SepalWidget): return + def today(self) -> Self: + """Update the date to the current day.""" + self.v_model = datetime.today().strftime("%Y-%m-%d") + + return self + @staticmethod def is_valid_date(date: str) -> bool: """
add a today() method for the datepicker It's something I do a lot, setting up the datepicker to today as: ```python from sepal_ui import sepawidgets as sw from datetime import datetime dp = sw.Datepicker() # do stulff and as a fallback do dp.v_model = datetime.today().strftime("%Y-%m-%d") ``` Instead I would love to have something like: ```python dp.today() ``` what do you think ?
12rambau/sepal_ui
diff --git a/tests/test_DatePicker.py b/tests/test_DatePicker.py index 02ee81c1..cfa47475 100644 --- a/tests/test_DatePicker.py +++ b/tests/test_DatePicker.py @@ -1,3 +1,5 @@ +from datetime import datetime + import pytest from traitlets import Any @@ -96,6 +98,16 @@ class TestDatePicker: return + def test_today(self, datepicker) -> None: + """check that the date is updated to today""" + + res = datepicker.today() + + assert res == datepicker + assert res.v_model == datetime.today().strftime("%Y-%m-%d") + + return + @pytest.fixture def datepicker(self): """create a default datepicker."""
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
2.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-sugar", "pytest-icdiff", "pytest-cov", "pytest-deadfixtures", "Flake8-pyproject", "nbmake" ], "pre_install": [ "apt-get update", "apt-get install -y gcc", "pip install --find-links=https://girder.github.io/large_image_wheels --no-cache GDAL", "pip install localtileserver" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 aniso8601==10.0.0 annotated-types==0.7.0 anyio==3.7.1 argcomplete==3.5.3 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 blinker==1.9.0 branca==0.8.1 cachelib==0.13.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 color-operations==0.2.0 colorama==0.4.6 colorlog==6.9.0 comm==0.2.2 commitizen==4.4.1 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decli==0.6.2 decorator==5.2.1 defusedxml==0.7.1 dependency-groups==1.3.0 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 flake8==7.2.0 Flake8-pyproject==1.2.3 Flask==3.1.0 Flask-Caching==2.3.1 flask-cors==5.0.1 flask-restx==1.3.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 GDAL==3.11.0 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 icdiff==2.0.7 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 itsdangerous==2.2.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 localtileserver==0.10.6 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mccabe==0.7.0 mistune==3.1.3 morecantile==6.2.0 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbmake==1.5.5 nest-asyncio==1.6.0 nodeenv==1.9.1 nox==2025.2.9 numexpr==2.10.2 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a6 platformdirs==4.3.7 pluggy==1.5.0 pprintpp==0.4.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycodestyle==2.13.0 pycparser==2.22 pydantic==2.11.1 pydantic_core==2.33.0 pyflakes==3.3.1 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pystac==1.10.1 pytest==8.3.5 pytest-cov==6.0.0 pytest-deadfixtures==2.2.1 pytest-icdiff==0.9 pytest-sugar==1.0.0 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rio-cogeo==5.4.1 rio-tiler==7.5.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 scooby==0.10.0 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@27a18eba37bec8ef1cabfa6bcc4022164ebc4c3b#egg=sepal_ui server-thread==0.3.0 shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==2.5.0 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tomlkit==0.13.2 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==3.1.3 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - aniso8601==10.0.0 - annotated-types==0.7.0 - anyio==3.7.1 - argcomplete==3.5.3 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - blinker==1.9.0 - branca==0.8.1 - cachelib==0.13.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - color-operations==0.2.0 - colorama==0.4.6 - colorlog==6.9.0 - comm==0.2.2 - commitizen==4.4.1 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decli==0.6.2 - decorator==5.2.1 - defusedxml==0.7.1 - dependency-groups==1.3.0 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - flake8==7.2.0 - flake8-pyproject==1.2.3 - flask==3.1.0 - flask-caching==2.3.1 - flask-cors==5.0.1 - flask-restx==1.3.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - gdal==3.11.0 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - icdiff==2.0.7 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - itsdangerous==2.2.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - localtileserver==0.10.6 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mccabe==0.7.0 - mistune==3.1.3 - morecantile==6.2.0 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbmake==1.5.5 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - nox==2025.2.9 - numexpr==2.10.2 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a6 - platformdirs==4.3.7 - pluggy==1.5.0 - pprintpp==0.4.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycodestyle==2.13.0 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pyflakes==3.3.1 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pystac==1.10.1 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-deadfixtures==2.2.1 - pytest-icdiff==0.9 - pytest-sugar==1.0.0 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rio-cogeo==5.4.1 - rio-tiler==7.5.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - scooby==0.10.0 - send2trash==1.8.3 - sepal-ui==2.15.1 - server-thread==0.3.0 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==2.5.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tomlkit==0.13.2 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==3.1.3 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_DatePicker.py::TestDatePicker::test_today" ]
[]
[ "tests/test_DatePicker.py::TestDatePicker::test_init", "tests/test_DatePicker.py::TestDatePicker::test_kwargs", "tests/test_DatePicker.py::TestDatePicker::test_bind", "tests/test_DatePicker.py::TestDatePicker::test_disable", "tests/test_DatePicker.py::TestDatePicker::test_is_valid_date", "tests/test_DatePicker.py::TestDatePicker::test_check_date" ]
[]
MIT License
null
null
12rambau__sepal_ui-774
2576446debe3544f3edeb208c76f671ffc0c8650
2023-03-01 15:49:43
22c831cffe193cb87de2720b655ebd069e585f45
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 04e69553..cd561bb5 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -205,6 +205,9 @@ class FileInput(v.Flex, SepalWidget): clear: Optional[v.Btn] = None "clear btn to remove everything and set back to the ini folder" + root: t.Unicode = t.Unicode("").tag(sync=True) + "the root folder from which you cannot go higher in the tree." + v_model: t.Unicode = t.Unicode(None, allow_none=True).tag(sync=True) "the v_model of the input" @@ -218,6 +221,7 @@ class FileInput(v.Flex, SepalWidget): label: str = ms.widgets.fileinput.label, v_model: Union[str, None] = "", clearable: bool = False, + root: Union[str, Path] = "", **kwargs, ) -> None: """ @@ -229,10 +233,12 @@ class FileInput(v.Flex, SepalWidget): label: the label of the input v_model: the default value clearable: wether or not to make the widget clearable. default to False + root: the root folder from which you cannot go higher in the tree. kwargs: any parameter from a v.Flex abject. If set, 'children' will be overwritten. """ self.extentions = extentions self.folder = Path(folder) + self.root = str(root) if isinstance(root, Path) else root self.selected_file = v.TextField( readonly=True, @@ -441,7 +447,10 @@ class FileInput(v.Flex, SepalWidget): folder_list = humansorted(folder_list, key=lambda x: x.value) file_list = humansorted(file_list, key=lambda x: x.value) + folder_list.extend(file_list) + # add the parent item if root is set and is not reached yet + # if root is not set then we always display it parent_item = v.ListItem( value=str(folder.parent), children=[ @@ -458,9 +467,11 @@ class FileInput(v.Flex, SepalWidget): ), ], ) - - folder_list.extend(file_list) - folder_list.insert(0, parent_item) + root_folder = Path(self.root) + if self.root == "": + folder_list.insert(0, parent_item) + elif root_folder in folder.parents: + folder_list.insert(0, parent_item) return folder_list diff --git a/sepal_ui/sepalwidgets/sepalwidget.py b/sepal_ui/sepalwidgets/sepalwidget.py index 79428748..d9d10451 100644 --- a/sepal_ui/sepalwidgets/sepalwidget.py +++ b/sepal_ui/sepalwidgets/sepalwidget.py @@ -13,7 +13,7 @@ Example: """ import warnings -from typing import Optional, Union +from typing import List, Optional, Union import ipyvuetify as v import traitlets as t @@ -125,7 +125,7 @@ class SepalWidget(v.VuetifyWidget): value: str = "", id_: str = "", elements: Optional[list] = None, - ) -> list: + ) -> List[v.VuetifyWidget]: r""" Recursively search for every element matching the specifications.
Restrict maximum parent level from InputFile I have some apps where I’m interested on only search up to certain level, i.e., module_downloads, and I think that in the most of them, the user doesn’t need to go upper from sepal_user, once they start clicking, they could easily get lost over multiple folders. what if we implement a parameter called: max_depth? We could use int values to this parameter, what do you think?
12rambau/sepal_ui
diff --git a/tests/conftest.py b/tests/conftest.py index f8b2c217..bac6feee 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ import uuid from itertools import product from pathlib import Path +from typing import Optional import ee import geopandas as gpd @@ -20,7 +21,7 @@ except Exception: @pytest.fixture(scope="session") -def root_dir(): +def root_dir() -> Path: """ Path to the root dir of the librairy. """ @@ -28,7 +29,7 @@ def root_dir(): @pytest.fixture(scope="session") -def tmp_dir(): +def tmp_dir() -> Path: """ Creates a temporary local directory to store data. """ @@ -39,7 +40,7 @@ def tmp_dir(): @pytest.fixture(scope="session") -def _hash(): +def _hash() -> str: """ Create a hash for each test instance. """ @@ -47,7 +48,7 @@ def _hash(): @pytest.fixture(scope="session") -def gee_dir(_hash): +def gee_dir(_hash: str) -> Optional[Path]: """ Create a test dir based on earthengine initialization populate it with fake super small assets: @@ -131,6 +132,6 @@ def gee_dir(_hash): @pytest.fixture -def alert(): +def alert() -> sw.Alert: """return a dummy alert that can be used everywhere to display informations.""" return sw.Alert() diff --git a/tests/test_FileInput.py b/tests/test_FileInput.py index 6fbba7a8..089f519b 100644 --- a/tests/test_FileInput.py +++ b/tests/test_FileInput.py @@ -1,3 +1,7 @@ +from pathlib import Path +from typing import List + +import ipyvuetify as v import pytest from traitlets import Any @@ -119,20 +123,32 @@ class TestFileInput: return + def test_root(self, file_input: sw.FileInput, root_dir: Path) -> None: + """Add a root folder to a file_input and check that you can't go higher""" + + # set the root to the current folder and reload + file_input.root = str(root_dir) + file_input._on_reload() + first_title_item = file_input.get_children(klass=v.ListItemTitle)[0] + + assert ".. /" not in first_title_item.children[0] + + return + @pytest.fixture - def file_input(self, root_dir): + def file_input(self, root_dir: Path) -> sw.FileInput: """create a default file_input in the root_dir.""" return sw.FileInput(folder=root_dir) @pytest.fixture - def readme(self, root_dir): + def readme(self, root_dir: Path) -> Path: """return the readme file path.""" return root_dir / "README.rst" @staticmethod - def get_names(widget): + def get_names(file_input: sw.FileInput) -> List[str]: """get the list name of a fileinput object.""" - item_list = widget.file_list.children[0].children + item_list = file_input.file_list.children[0].children def get_name(item): return item.children[1].children[0].children[0]
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 2 }
2.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-sugar pytest-icdiff pytest-deadfixtures Flake8-pyproject nbmake", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc", "pip install --find-links=https://girder.github.io/large_image_wheels --no-cache GDAL", "pip install localtileserver" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 aniso8601==10.0.0 annotated-types==0.7.0 anyio==3.7.1 argcomplete==3.5.3 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-timeout==5.0.1 attrs==25.3.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 blinker==1.9.0 branca==0.8.1 cachelib==0.13.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 color-operations==0.2.0 colorama==0.4.6 colorlog==6.9.0 comm==0.2.2 commitizen==4.4.1 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decli==0.6.2 decorator==5.2.1 defusedxml==0.7.1 dependency-groups==1.3.0 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 flake8==7.2.0 Flake8-pyproject==1.2.3 Flask==3.1.0 Flask-Caching==2.3.1 flask-cors==5.0.1 flask-restx==1.3.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.2 GDAL==3.11.0 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 icdiff==2.0.7 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 itsdangerous==2.2.0 jedi==0.19.2 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab_pygments==0.3.0 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 localtileserver==0.10.6 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mccabe==0.7.0 mistune==3.1.3 morecantile==6.2.0 multidict==6.2.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbmake==1.5.5 nest-asyncio==1.6.0 nodeenv==1.9.1 nox==2025.2.9 numexpr==2.10.2 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a6 platformdirs==4.3.7 pluggy==1.5.0 pprintpp==0.4.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycodestyle==2.13.0 pycparser==2.22 pydantic==2.11.1 pydantic_core==2.33.0 pyflakes==3.3.2 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pystac==1.10.1 pytest==8.3.5 pytest-cov==6.0.0 pytest-deadfixtures==2.2.1 pytest-icdiff==0.9 pytest-sugar==1.0.0 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rio-cogeo==5.4.1 rio-tiler==7.5.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 scooby==0.10.0 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@2576446debe3544f3edeb208c76f671ffc0c8650#egg=sepal_ui server-thread==0.3.0 shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==2.5.0 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tomlkit==0.13.2 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.29.3 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 Werkzeug==3.1.3 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - aniso8601==10.0.0 - annotated-types==0.7.0 - anyio==3.7.1 - argcomplete==3.5.3 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-timeout==5.0.1 - attrs==25.3.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - blinker==1.9.0 - branca==0.8.1 - cachelib==0.13.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - color-operations==0.2.0 - colorama==0.4.6 - colorlog==6.9.0 - comm==0.2.2 - commitizen==4.4.1 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decli==0.6.2 - decorator==5.2.1 - defusedxml==0.7.1 - dependency-groups==1.3.0 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - flake8==7.2.0 - flake8-pyproject==1.2.3 - flask==3.1.0 - flask-caching==2.3.1 - flask-cors==5.0.1 - flask-restx==1.3.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.2 - gdal==3.11.0 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - icdiff==2.0.7 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - itsdangerous==2.2.0 - jedi==0.19.2 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab-pygments==0.3.0 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - localtileserver==0.10.6 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mccabe==0.7.0 - mistune==3.1.3 - morecantile==6.2.0 - multidict==6.2.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbmake==1.5.5 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - nox==2025.2.9 - numexpr==2.10.2 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a6 - platformdirs==4.3.7 - pluggy==1.5.0 - pprintpp==0.4.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycodestyle==2.13.0 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pyflakes==3.3.2 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pystac==1.10.1 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-deadfixtures==2.2.1 - pytest-icdiff==0.9 - pytest-sugar==1.0.0 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rio-cogeo==5.4.1 - rio-tiler==7.5.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - scooby==0.10.0 - send2trash==1.8.3 - sepal-ui==2.15.2 - server-thread==0.3.0 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==2.5.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tomlkit==0.13.2 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.29.3 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - werkzeug==3.1.3 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_FileInput.py::TestFileInput::test_root" ]
[]
[ "tests/test_FileInput.py::TestFileInput::test_init", "tests/test_FileInput.py::TestFileInput::test_bind", "tests/test_FileInput.py::TestFileInput::test_on_file_select", "tests/test_FileInput.py::TestFileInput::test_on_reload", "tests/test_FileInput.py::TestFileInput::test_reset", "tests/test_FileInput.py::TestFileInput::test_select_file" ]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-774
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-774
12rambau__sepal_ui-807
1c183817ccae604484ad04729288e7beb3451a64
2023-04-03 20:51:14
b91b2a2c45b4fa80a7a0c699df978ebc46682260
diff --git a/docs/source/conf.py b/docs/source/conf.py index 07f6d872..13defac5 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -52,6 +52,7 @@ extensions = [ "sphinx.ext.napoleon", "sphinx.ext.autosummary", "sphinx.ext.viewcode", + "sphinx.ext.todo", "sphinx_favicon", "notfound.extension", "sphinxcontrib.autoprogram", @@ -155,3 +156,6 @@ html_css_files = ["css/custom.css", "css/icon.css"] autosummary_generate = True autoclass_content = "both" autodoc_typehints = "description" + +# -- Options for TODO ---------------------------------------------------------- +todo_include_todos = True diff --git a/sepal_ui/mapping/__init__.py b/sepal_ui/mapping/__init__.py index b668ab60..32e56a39 100644 --- a/sepal_ui/mapping/__init__.py +++ b/sepal_ui/mapping/__init__.py @@ -24,6 +24,7 @@ from .layer_state_control import * from .layers_control import * from .legend_control import * from .map_btn import * +from .marker_cluster import * from .menu_control import * from .sepal_map import * from .zoom_control import * diff --git a/sepal_ui/mapping/layers_control.py b/sepal_ui/mapping/layers_control.py index 87550f91..a4efdec3 100644 --- a/sepal_ui/mapping/layers_control.py +++ b/sepal_ui/mapping/layers_control.py @@ -191,6 +191,9 @@ class LayersControl(MenuControl): self.menu.open_on_hover = True self.menu.close_delay = 200 + # set the ize according to the content + self.set_size(None, None, None, None) + # update the table at instance creation self.update_table({}) diff --git a/sepal_ui/mapping/marker_cluster.py b/sepal_ui/mapping/marker_cluster.py new file mode 100644 index 00000000..2eb7978f --- /dev/null +++ b/sepal_ui/mapping/marker_cluster.py @@ -0,0 +1,20 @@ +"""Custom implementation of the marker cluster to hide it at once.""" + +from ipyleaflet import MarkerCluster +from traitlets import Bool, observe + + +class MarkerCluster(MarkerCluster): + """Overwrite the MarkerCluster to hide all the underlying cluster at once. + + .. todo:: + remove when https://github.com/jupyter-widgets/ipyleaflet/issues/1108 is solved + """ + + visible = Bool(True).tag(sync=True) + + @observe("visible") + def toggle_markers(self, change): + """change the marker value according to the cluster viz.""" + for marker in self.markers: + marker.visible = self.visible
create a custom marker cluster that can be hidden currently the marker cluster cannot be hidden, only the underlying markers can. I twould be good if it was possible to hide all the underlying markers at once by changin the visible trait of the marker_cluster itself
12rambau/sepal_ui
diff --git a/tests/test_mapping/test_MarkerCluster.py b/tests/test_mapping/test_MarkerCluster.py new file mode 100644 index 00000000..532eee9f --- /dev/null +++ b/tests/test_mapping/test_MarkerCluster.py @@ -0,0 +1,22 @@ +"""Test the MarkerCluster control.""" +from ipyleaflet import Marker + +from sepal_ui import mapping as sm + + +def test_init() -> None: + """Init a MarkerCluster.""" + marker_cluster = sm.MarkerCluster() + assert isinstance(marker_cluster, sm.MarkerCluster) + + return + + +def test_visible() -> None: + """Hide MarkerCluster.""" + markers = [Marker(location=(0, 0)) for _ in range(3)] + marker_cluster = sm.MarkerCluster(markers=markers) + + # check that the visibility trait is linked + marker_cluster.visible = False + assert all(m.visible is False for m in markers)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 3 }
2.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 anyio==3.7.1 argcomplete==3.5.3 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 async-timeout==5.0.1 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 colorlog==6.9.0 comm==0.2.2 commitizen==4.4.1 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decli==0.6.2 decorator==5.2.1 defusedxml==0.7.1 dependency-groups==1.3.0 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.2 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab==4.0.13 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 multidict==6.2.0 mypy==1.15.0 mypy-extensions==1.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.0.8 notebook_shim==0.2.4 nox==2025.2.9 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a6 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest==8.3.5 pytest-cov==6.0.0 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@1c183817ccae604484ad04729288e7beb3451a64#egg=sepal_ui shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==2.5.0 terminado==0.18.1 tinycss2==1.4.0 toml==0.10.2 tomli==2.2.1 tomlkit==0.13.2 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 Unidecode==1.3.8 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - anyio==3.7.1 - argcomplete==3.5.3 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - async-timeout==5.0.1 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - colorlog==6.9.0 - comm==0.2.2 - commitizen==4.4.1 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decli==0.6.2 - decorator==5.2.1 - defusedxml==0.7.1 - dependency-groups==1.3.0 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.2 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.0.13 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - multidict==6.2.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.0.8 - notebook-shim==0.2.4 - nox==2025.2.9 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a6 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - sepal-ui==2.16.1 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==2.5.0 - terminado==0.18.1 - tinycss2==1.4.0 - toml==0.10.2 - tomli==2.2.1 - tomlkit==0.13.2 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - unidecode==1.3.8 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_mapping/test_MarkerCluster.py::test_init", "tests/test_mapping/test_MarkerCluster.py::test_visible" ]
[]
[]
[]
MIT License
null
null
12rambau__sepal_ui-814
6d825ae167f96ad2e7b76b96ca07de562f74dcf0
2023-04-11 07:43:35
b91b2a2c45b4fa80a7a0c699df978ebc46682260
diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py index 19718f51..8dafab92 100644 --- a/sepal_ui/sepalwidgets/alert.py +++ b/sepal_ui/sepalwidgets/alert.py @@ -108,14 +108,17 @@ class Alert(v.Alert, SepalWidget): Args: progress: the progress status in float msg: The message to use before the progress bar - tqdm_args (optional): any arguments supported by a tqdm progress bar + tqdm_args (optional): any arguments supported by a tqdm progress bar, they will only be taken into account after a call to ``self.reset()``. """ # show the alert self.show() - # cast the progress to float - total = tqdm_args.get("total", 1) + # cast the progress to float and perform sanity checks progress = float(progress) + if self.progress_output not in self.children: + total = tqdm_args.get("total", 1) + else: + total = self.progress_bar.total if not (0 <= progress <= total): raise ValueError(f"progress should be in [0, {total}], {progress} given")
avoid to force developer to set total each time I should be able to init the progress of an Alert first and then simply update the progress. as in: ```python from sepal_ui import sepalwidgets as sw alert = sw.Alert() # init alert.update_progress(0, "toto", total=10) # loop for i in range(10): alert.update_progress(i) ``` in the current implemetnation, total need to be set in every calls
12rambau/sepal_ui
diff --git a/tests/test_sepalwidgets/test_Alert.py b/tests/test_sepalwidgets/test_Alert.py index 3f8de9a4..cac14ebb 100644 --- a/tests/test_sepalwidgets/test_Alert.py +++ b/tests/test_sepalwidgets/test_Alert.py @@ -175,7 +175,8 @@ def test_update_progress() -> None: # check that if total is set value can be more than 1 alert.reset() - alert.update_progress(50, total=100) + alert.update_progress(0, total=100) + alert.update_progress(50) assert alert.progress_bar.n == 50 assert alert.viz is True
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
2.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 anyascii==0.3.2 anyio==3.7.1 argcomplete==3.5.3 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 async-timeout==5.0.1 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 branca==0.8.1 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 colorama==0.4.6 colorlog==6.9.0 comm==0.2.2 commitizen==4.4.1 contourpy==1.3.0 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decli==0.6.2 decorator==5.2.1 defusedxml==0.7.1 dependency-groups==1.3.0 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.1 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.12.0 httpcore==0.15.0 httplib2==0.22.0 httpx==0.23.0 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab==4.0.13 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 multidict==6.2.0 mypy==1.15.0 mypy-extensions==1.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.0.8 notebook_shim==0.2.4 nox==2025.2.9 numpy==2.0.2 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.0a6 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pytest @ file:///croot/pytest_1738938843180/work python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986==1.5.0 rfc3986-validator==0.1.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@6d825ae167f96ad2e7b76b96ca07de562f74dcf0#egg=sepal_ui shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==2.5.0 terminado==0.18.1 tinycss2==1.4.0 toml==0.10.2 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tomlkit==0.13.2 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 virtualenv==20.29.3 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - anyascii==0.3.2 - anyio==3.7.1 - argcomplete==3.5.3 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - async-timeout==5.0.1 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - branca==0.8.1 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - colorama==0.4.6 - colorlog==6.9.0 - comm==0.2.2 - commitizen==4.4.1 - contourpy==1.3.0 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decli==0.6.2 - decorator==5.2.1 - defusedxml==0.7.1 - dependency-groups==1.3.0 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.1 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.12.0 - httpcore==0.15.0 - httplib2==0.22.0 - httpx==0.23.0 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.0.13 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - multidict==6.2.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.0.8 - notebook-shim==0.2.4 - nox==2025.2.9 - numpy==2.0.2 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.0a6 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986==1.5.0 - rfc3986-validator==0.1.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - send2trash==1.8.3 - sepal-ui==2.16.2 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==2.5.0 - terminado==0.18.1 - tinycss2==1.4.0 - toml==0.10.2 - tomlkit==0.13.2 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - virtualenv==20.29.3 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_sepalwidgets/test_Alert.py::test_update_progress" ]
[]
[ "tests/test_sepalwidgets/test_Alert.py::test_init", "tests/test_sepalwidgets/test_Alert.py::test_add_msg", "tests/test_sepalwidgets/test_Alert.py::test_add_live_msg", "tests/test_sepalwidgets/test_Alert.py::test_append_msg", "tests/test_sepalwidgets/test_Alert.py::test_reset", "tests/test_sepalwidgets/test_Alert.py::test_rmv_last_msg" ]
[]
MIT License
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-814
swerebench/sweb.eval.x86_64.12rambau_1776_sepal_ui-814
12rambau__sepal_ui-856
999deb0011f05d3e7ff94e04b517ac2919e38a59
2023-08-03 07:55:32
b91b2a2c45b4fa80a7a0c699df978ebc46682260
diff --git a/sepal_ui/message/en/decorator.json b/sepal_ui/message/en/decorator.json new file mode 100644 index 00000000..80b1422a --- /dev/null +++ b/sepal_ui/message/en/decorator.json @@ -0,0 +1,6 @@ +{ + "decorator": { + "no_alert": "You should provide the `alert` argument as parent does not have one", + "no_button": "You should provide the `button` argument as parent does not have one" + } +} diff --git a/sepal_ui/scripts/decorator.py b/sepal_ui/scripts/decorator.py index b28e59e3..eb0e228d 100644 --- a/sepal_ui/scripts/decorator.py +++ b/sepal_ui/scripts/decorator.py @@ -13,13 +13,15 @@ import warnings from functools import wraps from itertools import product from pathlib import Path -from typing import Any, Callable, List, Union +from typing import Any, Callable, List, Optional import ee import httplib2 import ipyvuetify as v from deprecated.sphinx import versionadded +from sepal_ui.message import ms + # from sepal_ui.scripts.utils import init_ee from sepal_ui.scripts.warning import SepalWarning @@ -60,14 +62,14 @@ def init_ee() -> None: @versionadded(version="3.0", reason="moved from utils to a dedicated module") -def catch_errors(alert: v.Alert, debug: bool = False) -> Any: +def catch_errors(alert: Optional[v.Alert] = None, debug: bool = False) -> Any: """Decorator to execute try/except sentence and catch errors in the alert message. If debug is True then the error is raised anyway. Args: - alert (sw.Alert): Alert to display errors - debug (bool): Whether to raise the error or not, default to false + alert: Alert to display errors + debug: Whether to raise the error or not, default to false Returns: The return statement of the decorated method @@ -75,12 +77,20 @@ def catch_errors(alert: v.Alert, debug: bool = False) -> Any: def decorator_alert_error(func): @wraps(func) - def wrapper_alert_error(*args, **kwargs): + def wrapper_alert_error(self, *args, **kwargs): + + # Change name of variable to assign it again in this scope + # check if alert exist in the parent object if alert is not set manually + assert hasattr(self, "alert") or alert, ms.decorator.no_alert + alert_ = self.alert if not alert else alert + alert_.reset() + + # try to execute the method value = None try: - value = func(*args, **kwargs) + value = func(self, *args, **kwargs) except Exception as e: - alert.add_msg(f"{e}", type_="error") + alert_.add_msg(f"{e}", type_="error") if debug: raise e return value @@ -119,8 +129,8 @@ def need_ee(func: Callable) -> Any: @versionadded(version="3.0", reason="moved from utils to a dedicated module") def loading_button( - alert: Union[v.Alert, None] = None, - button: Union[v.Btn, None] = None, + alert: Optional[v.Alert] = None, + button: Optional[v.Btn] = None, debug: bool = False, ) -> Any: """Decorator to execute try/except sentence and toggle loading button object. @@ -142,6 +152,9 @@ def loading_button( # set btn and alert # Change name of variable to assign it again in this scope + # check if they exist in the parent object if alert is not set manually + assert hasattr(self, "alert") or alert, ms.decorator.no_alert + assert hasattr(self, "btn") or button, ms.decorator.no_button button_ = self.btn if not button else button alert_ = self.alert if not alert else alert @@ -186,7 +199,7 @@ def loading_button( [custom_showwarning(w) for w in w_list] except Exception as e: - alert_.add_msg(f"{e}", "error") + alert_.add_msg(f"{e}", type_="error") if debug: button_.toggle_loading() # Stop loading button if there is an error raise e diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py index b3f3056d..9c70a732 100644 --- a/sepal_ui/sepalwidgets/alert.py +++ b/sepal_ui/sepalwidgets/alert.py @@ -229,6 +229,7 @@ class Alert(v.Alert, SepalWidget): """Empty the messages and hide it.""" self.children = [""] self.hide() + self.type = set_type("info") return self diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py index f9b09496..59f9f397 100644 --- a/sepal_ui/sepalwidgets/app.py +++ b/sepal_ui/sepalwidgets/app.py @@ -14,7 +14,7 @@ Example: from datetime import datetime from itertools import cycle from pathlib import Path -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional import ipyvuetify as v import pandas as pd @@ -248,7 +248,7 @@ class AppBar(v.AppBar, SepalWidget): def __init__( self, title: str = "SEPAL module", - translator: Union[None, Translator] = None, + translator: Optional[Translator] = None, **kwargs, ) -> None: """Custom AppBar widget with the provided title using the sepal color framework. @@ -316,7 +316,7 @@ class DrawerItem(v.ListItem, SepalWidget): icon: str = "", card: str = "", href: str = "", - model: Union[Model, None] = None, + model: Optional[Model] = None, bind_var: str = "", **kwargs, ) -> None: diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py index 9b7ddc2d..51638b69 100644 --- a/sepal_ui/sepalwidgets/inputs.py +++ b/sepal_ui/sepalwidgets/inputs.py @@ -220,7 +220,7 @@ class FileInput(v.Flex, SepalWidget): extensions: List[str] = [], folder: Union[str, Path] = Path.home(), label: str = ms.widgets.fileinput.label, - v_model: Union[str, None] = "", + v_model: str = "", clearable: bool = False, root: Union[str, Path] = "", **kwargs, diff --git a/sepal_ui/sepalwidgets/sepalwidget.py b/sepal_ui/sepalwidgets/sepalwidget.py index 68ac405f..3d7d7273 100644 --- a/sepal_ui/sepalwidgets/sepalwidget.py +++ b/sepal_ui/sepalwidgets/sepalwidget.py @@ -12,13 +12,13 @@ Example: """ import warnings -from typing import List, Optional, Union +from typing import List, Optional, Type, Union import ipyvuetify as v import traitlets as t from deprecated.sphinx import versionadded from traitlets import observe -from typing_extensions import Self, Type +from typing_extensions import Self __all__ = ["SepalWidget", "Tooltip"] diff --git a/sepal_ui/sepalwidgets/tile.py b/sepal_ui/sepalwidgets/tile.py index a70a4e52..97a6aeb9 100644 --- a/sepal_ui/sepalwidgets/tile.py +++ b/sepal_ui/sepalwidgets/tile.py @@ -41,8 +41,8 @@ class Tile(v.Layout, SepalWidget): id_: str, title: str, inputs: list = [""], - btn: Union[v.Btn, None] = None, - alert: Union[v.Alert, None] = None, + btn: Optional[v.Btn] = None, + alert: Optional[v.Alert] = None, **kwargs, ) -> None: """Custom Layout widget for the sepal UI framework. diff --git a/sepal_ui/sepalwidgets/widget.py b/sepal_ui/sepalwidgets/widget.py index affbd822..52fa1d2c 100644 --- a/sepal_ui/sepalwidgets/widget.py +++ b/sepal_ui/sepalwidgets/widget.py @@ -11,7 +11,7 @@ Example: """ from pathlib import Path -from typing import Optional, Union +from typing import Optional import ipyvuetify as v import traitlets as t @@ -124,7 +124,7 @@ class StateIcon(Tooltip): def __init__( self, - model: Union[None, Model] = None, + model: Optional[Model] = None, model_trait: str = "", states: dict = {}, **kwargs,
Use Optional instead of Union[None, ...] Now that we don't support 3.7 any more, we should drop `typing_extentions` and stop using the Union[none, ...] pattern. 2 option are possible: 1. `none|...` 2. `Optional[...]` I personnaly prefer 2.
12rambau/sepal_ui
diff --git a/tests/test_planetapi/test_PlanetModel.py b/tests/test_planetapi/test_PlanetModel.py index c343f5e3..37da73da 100644 --- a/tests/test_planetapi/test_PlanetModel.py +++ b/tests/test_planetapi/test_PlanetModel.py @@ -1,12 +1,11 @@ """Test the planet PlanetModel model.""" import os -from typing import Union +from typing import Any, Union import planet import pytest from pytest import FixtureRequest -from typing_extensions import Any from sepal_ui.planetapi import PlanetModel diff --git a/tests/test_scripts/test_decorator.py b/tests/test_scripts/test_decorator.py index 356a7b66..f400c4b8 100644 --- a/tests/test_scripts/test_decorator.py +++ b/tests/test_scripts/test_decorator.py @@ -22,22 +22,38 @@ def test_init_ee() -> None: def test_catch_errors() -> None: """Check the catch error decorator.""" + # create an external alert to test the wiring + alert = sw.Alert() + # create a fake object that uses the decorator class Obj: def __init__(self): self.alert = sw.Alert() self.btn = sw.Btn() - self.func1 = sd.catch_errors(alert=self.alert)(self.func) - self.func2 = sd.catch_errors(alert=self.alert, debug=True)(self.func) + @sd.catch_errors() + def func0(self, *args): + return 1 / 0 - def func(self, *args): + @sd.catch_errors(alert=alert) + def func1(self, *args): + return 1 / 0 + + @sd.catch_errors(debug=True) + def func2(self, *args): return 1 / 0 obj = Obj() - obj.func1() + # should return an alert error in the the self alert widget + obj.func0() assert obj.alert.type == "error" + + # should return an alert in the external alert widget + obj.func1() + assert alert.type == "error" + + # should raise an error with pytest.raises(Exception): obj.func2() @@ -83,8 +99,8 @@ def test_loading_button() -> None: obj.alert.reset() with pytest.raises(Exception): obj.fun2(obj.btn, None, None) - assert obj.btn.disabled is False - assert obj.alert.type == "error" + assert obj.btn.disabled is False + assert obj.alert.type == "error" # should only display the sepal warning obj.alert.reset() @@ -98,13 +114,13 @@ def test_loading_button() -> None: obj.alert.reset() with warnings.catch_warnings(record=True) as w_list: obj.func4(obj.btn, None, None) - assert obj.btn.disabled is False - assert obj.alert.type == "warning" - assert "sepal" in obj.alert.children[1].children[0] - assert "toto" not in obj.alert.children[1].children[0] - msg_list = [w.message.args[0] for w in w_list] - assert any("sepal" in s for s in msg_list) - assert any("toto" in s for s in msg_list) + assert obj.btn.disabled is False + assert obj.alert.type == "warning" + assert "sepal" in obj.alert.children[1].children[0] + assert "toto" not in obj.alert.children[1].children[0] + msg_list = [w.message.args[0] for w in w_list] + assert any("sepal" in s for s in msg_list) + assert any("toto" in s for s in msg_list) return diff --git a/tests/test_sepalwidgets/test_Alert.py b/tests/test_sepalwidgets/test_Alert.py index cac14ebb..171a152f 100644 --- a/tests/test_sepalwidgets/test_Alert.py +++ b/tests/test_sepalwidgets/test_Alert.py @@ -125,6 +125,7 @@ def test_reset() -> None: assert alert.viz is False assert len(alert.children) == 1 assert alert.children[0] == "" + assert alert.type == "info" return
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 7 }
2.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 aniso8601==10.0.0 annotated-types==0.7.0 anyascii==0.3.2 anyio==4.9.0 argcomplete==3.5.3 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 async-timeout==5.0.1 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 blinker==1.9.0 branca==0.8.1 cachelib==0.13.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 color-operations==0.2.0 colorama==0.4.6 colorlog==6.9.0 comm==0.2.2 commitizen==4.4.1 contourpy==1.3.0 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decli==0.6.2 decorator==5.2.1 defusedxml==0.7.1 dependency-groups==1.3.0 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 Flask==3.1.0 Flask-Caching==2.3.1 flask-cors==5.0.1 flask-restx==1.3.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.2 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 itsdangerous==2.2.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 localtileserver==0.10.6 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mistune==3.1.3 morecantile==6.2.0 multidict==6.2.0 mypy==1.15.0 mypy-extensions==1.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 nox==2025.2.9 numexpr==2.10.2 numpy==2.0.2 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.19.0 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 pydantic==2.11.1 pydantic_core==2.33.0 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pystac==1.10.1 pytest @ file:///croot/pytest_1738938843180/work python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rio-cogeo==5.4.1 rio-tiler==7.5.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 scooby==0.10.0 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@999deb0011f05d3e7ff94e04b517ac2919e38a59#egg=sepal_ui server-thread==0.3.0 shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==2.5.0 terminado==0.18.1 tinycss2==1.4.0 toml==0.10.2 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tomlkit==0.13.2 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 uritemplate==4.1.1 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.29.3 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 Werkzeug==3.1.3 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - aniso8601==10.0.0 - annotated-types==0.7.0 - anyascii==0.3.2 - anyio==4.9.0 - argcomplete==3.5.3 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - async-timeout==5.0.1 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - blinker==1.9.0 - branca==0.8.1 - cachelib==0.13.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - color-operations==0.2.0 - colorama==0.4.6 - colorlog==6.9.0 - comm==0.2.2 - commitizen==4.4.1 - contourpy==1.3.0 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decli==0.6.2 - decorator==5.2.1 - defusedxml==0.7.1 - dependency-groups==1.3.0 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - flask==3.1.0 - flask-caching==2.3.1 - flask-cors==5.0.1 - flask-restx==1.3.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.2 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - itsdangerous==2.2.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - localtileserver==0.10.6 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mistune==3.1.3 - morecantile==6.2.0 - multidict==6.2.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - nox==2025.2.9 - numexpr==2.10.2 - numpy==2.0.2 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.19.0 - platformdirs==4.3.7 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pystac==1.10.1 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rio-cogeo==5.4.1 - rio-tiler==7.5.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - scooby==0.10.0 - send2trash==1.8.3 - sepal-ui==2.16.4 - server-thread==0.3.0 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==2.5.0 - terminado==0.18.1 - tinycss2==1.4.0 - toml==0.10.2 - tomlkit==0.13.2 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - uri-template==1.3.0 - uritemplate==4.1.1 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.29.3 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - werkzeug==3.1.3 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_scripts/test_decorator.py::test_catch_errors" ]
[]
[ "tests/test_scripts/test_decorator.py::test_loading_button", "tests/test_scripts/test_decorator.py::test_switch", "tests/test_sepalwidgets/test_Alert.py::test_init", "tests/test_sepalwidgets/test_Alert.py::test_add_msg", "tests/test_sepalwidgets/test_Alert.py::test_add_live_msg", "tests/test_sepalwidgets/test_Alert.py::test_append_msg", "tests/test_sepalwidgets/test_Alert.py::test_reset", "tests/test_sepalwidgets/test_Alert.py::test_rmv_last_msg", "tests/test_sepalwidgets/test_Alert.py::test_update_progress" ]
[]
MIT License
null
null
12rambau__sepal_ui-896
b91b2a2c45b4fa80a7a0c699df978ebc46682260
2023-10-07 12:43:59
b91b2a2c45b4fa80a7a0c699df978ebc46682260
diff --git a/sepal_ui/message/en/locale.json b/sepal_ui/message/en/locale.json index abdea912..b65a232d 100644 --- a/sepal_ui/message/en/locale.json +++ b/sepal_ui/message/en/locale.json @@ -85,14 +85,17 @@ "exception": { "empty": "Please fill the required field(s).", "invalid": "Invalid email or password", - "nosubs": "Your credentials do not have any valid planet subscription." + "nosubs": "Your credentials do not have any valid planet subscription.", + "no_secret_file": "The credentials file does not exist, use a different login method." }, "widget": { "username": "Planet username", "password": "Planet password", "apikey": "Planet API key", + "store": "Remember credentials file in the session.", "method": { "label": "Login method", + "from_file": "From saved credentials", "credentials": "Credentials", "api_key": "Planet API key" } diff --git a/sepal_ui/planetapi/planet_model.py b/sepal_ui/planetapi/planet_model.py index 7aee2ed4..c3939499 100644 --- a/sepal_ui/planetapi/planet_model.py +++ b/sepal_ui/planetapi/planet_model.py @@ -6,8 +6,8 @@ from typing import Dict, List, Optional, Union import nest_asyncio import planet.data_filter as filters -import requests import traitlets as t +from deprecated.sphinx import deprecated from planet import DataClient from planet.auth import Auth from planet.exceptions import NoPermission @@ -21,7 +21,6 @@ nest_asyncio.apply() class PlanetModel(Model): - SUBS_URL: str = ( "https://api.planet.com/auth/v1/experimental/public/my/subscriptions" ) @@ -56,11 +55,18 @@ class PlanetModel(Model): if credentials: self.init_session(credentials) - def init_session(self, credentials: Union[str, List[str]]) -> None: + @deprecated( + version="3.0", + reason="credentials member is deprecated, use self.auth._key instead", + ) + def init_session( + self, credentials: Union[str, List[str]], write_secrets: bool = False + ) -> None: """Initialize planet client with api key or credentials. It will handle errors. Args: - credentials: planet API key or username and password pair of planet explorer. + credentials: planet API key, username and password pair or a secrets planet.json file. + write_secrets: either to write the credentials in the secret file or not. Defaults to True. """ if isinstance(credentials, str): credentials = [credentials] @@ -70,13 +76,21 @@ class PlanetModel(Model): if len(credentials) == 2: self.auth = Auth.from_login(*credentials) + + # Check if the str is a path to a secret file + elif len(credentials) == 1 and credentials[0].endswith(".json"): + self.auth = Auth.from_file(credentials[0]) + else: self.auth = Auth.from_key(credentials[0]) - self.credentials = credentials + self.credentials = self.auth._key self.session = Session(auth=self.auth) self._is_active() + if self.active and write_secrets: + self.auth.store() + return def _is_active(self) -> None: @@ -213,10 +227,11 @@ class PlanetModel(Model): "quad_download": true } """ - url = "https://api.planet.com/basemaps/v1/mosaics?api_key={}" - res = requests.get(url.format(self.credentials[0])) + mosaics_url = "https://api.planet.com/basemaps/v1/mosaics" + request = self.session.request("GET", mosaics_url) + response = asyncio.run(request) - return res.json().get("mosaics", []) + return response.json().get("mosaics", []) def get_quad(self, mosaic: dict, quad_id: str) -> dict: """Get a quad response for a specific mosaic and quad. @@ -245,10 +260,13 @@ class PlanetModel(Model): "percent_covered": 100 } """ - url = "https://api.planet.com/basemaps/v1/mosaics/{}/quads/{}?api_key={}" - res = requests.get(url.format(mosaic["id"], quad_id, self.credentials[0])) + quads_url = "https://api.planet.com/basemaps/v1/mosaics/{}/quads/{}" + quads_url = quads_url.format(mosaic["id"], quad_id) + + request = self.session.request("GET", quads_url) + response = asyncio.run(request) - return res.json() or {} + return response.json() or {} @staticmethod def search_status(d: dict) -> List[Dict[str, bool]]: diff --git a/sepal_ui/planetapi/planet_view.py b/sepal_ui/planetapi/planet_view.py index 1de11832..72f3d771 100644 --- a/sepal_ui/planetapi/planet_view.py +++ b/sepal_ui/planetapi/planet_view.py @@ -1,5 +1,6 @@ """The ``Card`` widget to use in application to interface with Planet.""" +from pathlib import Path from typing import Optional import ipyvuetify as v @@ -12,7 +13,6 @@ from sepal_ui.scripts.decorator import loading_button class PlanetView(sw.Layout): - planet_model: Optional[PlanetModel] = None "Backend model to manipulate interface actions" @@ -47,7 +47,7 @@ class PlanetView(sw.Layout): ): """Stand-alone interface to capture planet lab credentials. - It also validate its subscription and connect to the client stored in the model. + It also validate its subscription and connect to the client from_file in the model. Args: btn (sw.Btn, optional): Button to trigger the validation process in the associated model. @@ -67,18 +67,27 @@ class PlanetView(sw.Layout): ) self.w_password = sw.PasswordField(label=ms.planet.widget.password) self.w_key = sw.PasswordField(label=ms.planet.widget.apikey, v_model="").hide() + self.w_secret_file = sw.TextField( + label=ms.planet.widget.store, + v_model=str(Path.home() / ".planet.json"), + readonly=True, + class_="mr-2", + ).hide() self.w_info_view = InfoView(model=self.planet_model) self.w_method = v.Select( label=ms.planet.widget.method.label, class_="mr-2", - v_model="credentials", + v_model="", items=[ + {"value": "from_file", "text": ms.planet.widget.method.from_file}, {"value": "credentials", "text": ms.planet.widget.method.credentials}, {"value": "api_key", "text": ms.planet.widget.method.api_key}, ], ) + self.w_store = sw.Checkbox(label=ms.planet.widget.store, v_model=True) + w_validation = v.Flex( style_="flex-grow: 0 !important;", children=[self.btn], @@ -87,17 +96,22 @@ class PlanetView(sw.Layout): self.children = [ self.w_method, sw.Layout( + attributes={"id": "planet_credentials"}, class_="align-center", children=[ self.w_username, self.w_password, self.w_key, + self.w_secret_file, ], ), + self.w_store, ] if not btn: - self.children[-1].set_children(w_validation, "last") + self.get_children(attr="id", value="planet_credentials")[0].set_children( + w_validation, "last" + ) # Set it here to avoid displacements when using button self.set_children(self.w_info_view, "last") @@ -108,36 +122,82 @@ class PlanetView(sw.Layout): self.w_method.observe(self._swap_inputs, "v_model") self.btn.on_event("click", self.validate) + self.set_initial_method() + + def validate_secret_file(self) -> None: + """Validate the secret file path.""" + if not Path(self.w_secret_file.v_model).exists(): + self.w_secret_file.error_messages = [ms.planet.exception.no_secret_file] + return False + + self.w_secret_file.error_messages = [] + return True + + def set_initial_method(self) -> None: + """Set the initial method to connect to planet lab.""" + self.w_method.v_model = ( + "from_file" if self.validate_secret_file() else "credentials" + ) + def reset(self) -> None: """Empty credentials fields and restart activation mode.""" - self.w_username.v_model = None - self.w_password.v_model = None - self.w_key.v_model = None + self.w_username.v_model = "" + self.w_password.v_model = "" + self.w_key.v_model = "" self.planet_model.__init__() return def _swap_inputs(self, change: dict) -> None: - """Swap between credentials and api key inputs.""" + """Swap between credentials and api key inputs. + + Args: + change.new: values of from_file, credentials, api_key + """ self.alert.reset() self.reset() - self.w_username.toggle_viz() - self.w_password.toggle_viz() - self.w_key.toggle_viz() + # small detail, but validate the file every time the method is changed + self.validate_secret_file() + + if change["new"] == "credentials": + self.w_username.show() + self.w_password.show() + self.w_secret_file.hide() + self.w_store.show() + self.w_key.hide() + + elif change["new"] == "api_key": + self.w_username.hide() + self.w_password.hide() + self.w_secret_file.hide() + self.w_store.show() + self.w_key.show() + else: + self.w_username.hide() + self.w_password.hide() + self.w_key.hide() + self.w_store.hide() + self.w_secret_file.show() return - @loading_button(debug=True) + @loading_button() def validate(self, *args) -> None: """Initialize planet client and validate if is active.""" self.planet_model.__init__() if self.w_method.v_model == "credentials": credentials = [self.w_username.v_model, self.w_password.v_model] + + elif self.w_method.v_model == "api_key": + credentials = self.w_key.v_model + else: - credentials = [self.w_key.v_model] + if not self.validate_secret_file(): + raise Exception(ms.planet.exception.no_secret_file) + credentials = self.w_secret_file.v_model - self.planet_model.init_session(credentials) + self.planet_model.init_session(credentials, write_secrets=self.w_store.v_model) return
get_mosaics from planet api fails `get_mosaics` --and probably-- `get_quads` fails when the authentication process is done `from_login`... test has been passed because we are only testing the initialization of the `Planet` `from_key` but not to get elements from it
12rambau/sepal_ui
diff --git a/tests/test_planetapi/test_PlanetModel.py b/tests/test_planetapi/test_PlanetModel.py index 68450a05..3741c62f 100644 --- a/tests/test_planetapi/test_PlanetModel.py +++ b/tests/test_planetapi/test_PlanetModel.py @@ -1,6 +1,7 @@ """Test the planet PlanetModel model.""" import os +from pathlib import Path from typing import Any, Union import planet @@ -42,7 +43,7 @@ def test_init(planet_key: str, cred: list) -> None: @pytest.mark.skipif("PLANET_API_KEY" not in os.environ, reason="requires Planet") @pytest.mark.parametrize("credentials", ["planet_key", "cred"]) def test_init_client(credentials: Any, request: FixtureRequest) -> None: - """Check init the client with 2 methods. + """Check init the client with 3 methods. Args: credentials: any credentials as set in the parameters @@ -53,16 +54,66 @@ def test_init_client(credentials: Any, request: FixtureRequest) -> None: planet_model.init_session(request.getfixturevalue(credentials)) assert planet_model.active is True - # check the content of cred - # I use a proxy to avoid exposing the credentials in the logs - cred = request.getfixturevalue(credentials) - cred = [cred] if isinstance(cred, str) else cred - is_same = planet_model.credentials == cred - assert is_same is True, "The credentials are not corresponding" + assert ( + planet_model.auth._key == planet_model.credentials + ), "The credentials are not corresponding" with pytest.raises(Exception): planet_model.init_session("wrongkey") + with pytest.raises(Exception): + planet_model.init_session(["wrongkey", "credentials"]) + + return + + +@pytest.mark.skipif("PLANET_API_KEY" not in os.environ, reason="requires Planet") +def test_init_with_file(planet_key) -> None: + """Check init the session from a file.""" + planet_secret_file = Path.home() / ".planet.json" + existing = False + + # This test will overwrite and remove the file, let's backup it + if planet_secret_file.exists(): + existing = True + planet_secret_file.rename(planet_secret_file.with_suffix(".json.bak")) + + # Create a file with the credentials + planet_model = PlanetModel() + # We assume that the credentials are valid + planet_model.init_session(planet_key, write_secrets=True) + + assert planet_secret_file.exists() + + # test init with the file + planet_model = PlanetModel() + planet_model.init_session(str(planet_secret_file)) + + assert planet_model.active is True + + # Check that wrong credentials won't save the secrets file + + # remove the file + planet_secret_file.unlink() + + planet_model = PlanetModel() + + with pytest.raises(Exception): + planet_model.init_session("wrong_key", write_secrets=True) + + assert not planet_secret_file.exists() + + # Check no save with good credentials + + planet_model = PlanetModel() + planet_model.init_session(planet_key, write_secrets=False) + + assert not planet_secret_file.exists() + + # restore the file + if existing: + planet_secret_file.with_suffix(".json.bak").rename(planet_secret_file) + return diff --git a/tests/test_planetapi/test_PlanetView.py b/tests/test_planetapi/test_PlanetView.py index c700fe3f..1d0b39cc 100644 --- a/tests/test_planetapi/test_PlanetView.py +++ b/tests/test_planetapi/test_PlanetView.py @@ -2,11 +2,13 @@ import json import os +from pathlib import Path import pytest from sepal_ui import sepalwidgets as sw -from sepal_ui.planetapi import PlanetView +from sepal_ui.message import ms +from sepal_ui.planetapi import PlanetModel, PlanetView @pytest.mark.skipif("PLANET_API_KEY" not in os.environ, reason="requires Planet") @@ -40,16 +42,27 @@ def test_reset() -> None: # reset the view planet_view.reset() - assert planet_view.w_username.v_model is None - assert planet_view.w_password.v_model is None - assert planet_view.w_key.v_model is None + assert planet_view.w_username.v_model == "" + assert planet_view.w_password.v_model == "" + assert planet_view.w_key.v_model == "" # use a default method - default_method = "credentials" - assert planet_view.w_method.v_model == default_method - assert planet_view.w_username.viz is True - assert planet_view.w_password.viz is True - assert planet_view.w_key.viz is False + # Default method will be from_file if the secrets file exists + default_method = ( + "from_file" if (Path.home() / ".planet.json").exists() else "credentials" + ) + if default_method == "credentials": + assert planet_view.w_method.v_model == default_method + assert planet_view.w_username.viz is True + assert planet_view.w_password.viz is True + assert planet_view.w_key.viz is False + assert planet_view.w_secret_file.viz is False + else: + assert planet_view.w_method.v_model == default_method + assert planet_view.w_username.viz is False + assert planet_view.w_password.viz is False + assert planet_view.w_key.viz is False + assert planet_view.w_secret_file.viz is True # change the method planet_view.w_method.v_model = "api_key" @@ -57,6 +70,7 @@ def test_reset() -> None: assert planet_view.w_username.viz is False assert planet_view.w_password.viz is False assert planet_view.w_key.viz is True + assert planet_view.w_secret_file.viz is False return @@ -83,3 +97,66 @@ def test_validate() -> None: assert planet_view.planet_model.active is True return + + +@pytest.mark.skipif("PLANET_API_KEY" not in os.environ, reason="requires Planet") +def test_validate_secret_file(planet_key) -> None: + """Test validation view method of the secret file.""" + # Arrange + planet_secret_file = Path.home() / ".planet.json" + + # Test with existing file + # Create a secrets file + planet_model = PlanetModel() + planet_model.init_session(planet_key, write_secrets=True) + + planet_view = PlanetView() + planet_view.validate_secret_file() + + assert planet_view.w_secret_file.error_messages == [] + + # Also validate with the event + planet_view.btn.fire_event("click", None) + + # Test with non-existing file + + # Create a backup of the file + planet_secret_file.rename(planet_secret_file.with_suffix(".json.bak")) + + planet_view.validate_secret_file() + + assert planet_view.w_secret_file.error_messages == [ + ms.planet.exception.no_secret_file + ] + + # Restore the file + planet_secret_file.with_suffix(".json.bak").rename(planet_secret_file) + + +def test_validate_event() -> None: + """Test validation button event.""" + # Arrange + planet_secret_file = Path.home() / ".planet.json" + exists = False + + # if the file exists, rename it + if planet_secret_file.exists(): + exists = True + planet_secret_file.rename(planet_secret_file.with_suffix(".json.bak")) + + # Arrange + planet_view = PlanetView() + + planet_view.w_method.v_model = "from_file" + + # Act + planet_view.btn.fire_event("click", None) + + # Assert + assert planet_view.alert.children[0].children == [ + ms.planet.exception.no_secret_file + ] + + # Restore if there was a file + if exists: + planet_secret_file.with_suffix(".json.bak").rename(planet_secret_file)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 3 }
2.16
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-sugar", "pytest-icdiff", "pytest-cov", "pytest-deadfixtures", "Flake8-pyproject", "nbmake", "pytest-regressions" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
affine==2.4.0 aiohappyeyeballs==2.6.1 aiohttp==3.11.14 aiosignal==1.3.2 aniso8601==10.0.0 annotated-types==0.7.0 anyascii==0.3.2 anyio==4.9.0 argcomplete==3.5.3 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 async-timeout==5.0.1 attrs==25.3.0 babel==2.17.0 backcall==0.2.0 beautifulsoup4==4.13.3 bleach==6.2.0 blinker==1.9.0 branca==0.8.1 cachelib==0.13.0 cachetools==5.5.2 cattrs==24.1.3 certifi==2025.1.31 cffi==1.17.1 cfgv==3.4.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 cloudpickle==3.1.1 color-operations==0.2.0 colorama==0.4.6 colorlog==6.9.0 comm==0.2.2 commitizen==4.4.1 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 dask==2024.8.0 debugpy==1.8.13 decli==0.6.2 decorator==5.2.1 defusedxml==0.7.1 dependency-groups==1.3.0 Deprecated==1.2.18 distlib==0.3.9 docopt==0.6.2 earthengine-api==1.5.8 exceptiongroup==1.2.2 executing==2.2.0 fastjsonschema==2.21.1 filelock==3.18.0 flake8==7.2.0 Flake8-pyproject==1.2.3 Flask==3.1.0 Flask-Caching==2.3.1 flask-cors==5.0.1 flask-restx==1.3.0 fonttools==4.56.0 fqdn==1.5.1 frozenlist==1.5.0 fsspec==2025.3.2 geojson==3.2.0 geopandas==1.0.1 google-api-core==2.24.2 google-api-python-client==2.166.0 google-auth==2.38.0 google-auth-httplib2==0.2.0 google-cloud-core==2.4.3 google-cloud-storage==3.1.0 google-crc32c==1.7.1 google-resumable-media==2.7.2 googleapis-common-protos==1.69.2 h11==0.14.0 httpcore==1.0.7 httplib2==0.22.0 httpx==0.28.1 icdiff==2.0.7 identify==2.6.9 idna==3.10 importlib_metadata==8.6.1 importlib_resources==6.5.2 iniconfig==2.1.0 ipykernel==6.29.5 ipyleaflet==0.19.2 ipython==8.12.3 ipyvue==1.11.2 ipyvuetify==1.11.1 ipywidgets==8.1.5 isoduration==20.11.0 itsdangerous==2.2.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-leaflet==0.19.2 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_proxy==4.4.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 kiwisolver==1.4.7 localtileserver==0.10.6 locket==1.0.0 Markdown==3.7 MarkupSafe==3.0.2 matplotlib==3.9.4 matplotlib-inline==0.1.7 mccabe==0.7.0 mistune==3.1.3 morecantile==6.2.0 multidict==6.2.0 mypy==1.15.0 mypy-extensions==1.0.0 natsort==8.4.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nbmake==1.5.5 nest-asyncio==1.6.0 nodeenv==1.9.1 notebook==7.3.3 notebook_shim==0.2.4 nox==2025.2.9 numexpr==2.10.2 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 partd==1.4.2 pexpect==4.9.0 pickleshare==0.7.5 pillow==11.1.0 pipreqs==0.5.0 planet==2.19.0 platformdirs==4.3.7 pluggy==1.5.0 pprintpp==0.4.0 pre_commit==4.2.0 prometheus_client==0.21.1 prompt_toolkit==3.0.50 propcache==0.3.1 proto-plus==1.26.1 protobuf==6.30.2 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pyarrow==19.0.1 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycodestyle==2.13.0 pycparser==2.22 pydantic==2.11.1 pydantic_core==2.33.0 pyflakes==3.3.2 pygadm==0.5.3 pygaul==0.3.4 Pygments==2.19.1 PyJWT==2.10.1 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.6.1 pystac==1.10.1 pytest==8.3.5 pytest-cov==6.0.0 pytest-datadir==1.6.1 pytest-deadfixtures==2.2.1 pytest-icdiff==0.9 pytest-regressions==2.7.0 pytest-sugar==1.0.0 python-box==7.3.2 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 questionary==2.1.0 rasterio==1.4.3 referencing==0.36.2 requests==2.32.3 requests-cache==1.2.1 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rio-cogeo==5.4.1 rio-tiler==7.5.1 rioxarray==0.15.0 rpds-py==0.24.0 rsa==4.9 scooby==0.10.0 Send2Trash==1.8.3 -e git+https://github.com/12rambau/sepal_ui.git@b91b2a2c45b4fa80a7a0c699df978ebc46682260#egg=sepal_ui server-thread==0.3.0 shapely==2.0.7 simpervisor==1.0.0 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 termcolor==2.5.0 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tomlkit==0.13.2 toolz==1.0.0 tornado==6.4.2 tqdm==4.67.1 traitlets==5.14.3 traittypes==0.2.1 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 uritemplate==4.1.1 url-normalize==2.2.0 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.30.0 voila==0.5.8 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 websockets==15.0.1 Werkzeug==3.1.3 widgetsnbextension==4.0.13 wrapt==1.17.2 xarray==2024.7.0 xyzservices==2025.1.0 yarg==0.1.9 yarl==1.18.3 zipp==3.21.0
name: sepal_ui channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - affine==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.11.14 - aiosignal==1.3.2 - aniso8601==10.0.0 - annotated-types==0.7.0 - anyascii==0.3.2 - anyio==4.9.0 - argcomplete==3.5.3 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - async-timeout==5.0.1 - attrs==25.3.0 - babel==2.17.0 - backcall==0.2.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - blinker==1.9.0 - branca==0.8.1 - cachelib==0.13.0 - cachetools==5.5.2 - cattrs==24.1.3 - certifi==2025.1.31 - cffi==1.17.1 - cfgv==3.4.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - cloudpickle==3.1.1 - color-operations==0.2.0 - colorama==0.4.6 - colorlog==6.9.0 - comm==0.2.2 - commitizen==4.4.1 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - dask==2024.8.0 - debugpy==1.8.13 - decli==0.6.2 - decorator==5.2.1 - defusedxml==0.7.1 - dependency-groups==1.3.0 - deprecated==1.2.18 - distlib==0.3.9 - docopt==0.6.2 - earthengine-api==1.5.8 - exceptiongroup==1.2.2 - executing==2.2.0 - fastjsonschema==2.21.1 - filelock==3.18.0 - flake8==7.2.0 - flake8-pyproject==1.2.3 - flask==3.1.0 - flask-caching==2.3.1 - flask-cors==5.0.1 - flask-restx==1.3.0 - fonttools==4.56.0 - fqdn==1.5.1 - frozenlist==1.5.0 - fsspec==2025.3.2 - geojson==3.2.0 - geopandas==1.0.1 - google-api-core==2.24.2 - google-api-python-client==2.166.0 - google-auth==2.38.0 - google-auth-httplib2==0.2.0 - google-cloud-core==2.4.3 - google-cloud-storage==3.1.0 - google-crc32c==1.7.1 - google-resumable-media==2.7.2 - googleapis-common-protos==1.69.2 - h11==0.14.0 - httpcore==1.0.7 - httplib2==0.22.0 - httpx==0.28.1 - icdiff==2.0.7 - identify==2.6.9 - idna==3.10 - importlib-metadata==8.6.1 - importlib-resources==6.5.2 - iniconfig==2.1.0 - ipykernel==6.29.5 - ipyleaflet==0.19.2 - ipython==8.12.3 - ipyvue==1.11.2 - ipyvuetify==1.11.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - itsdangerous==2.2.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-leaflet==0.19.2 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-proxy==4.4.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - kiwisolver==1.4.7 - localtileserver==0.10.6 - locket==1.0.0 - markdown==3.7 - markupsafe==3.0.2 - matplotlib==3.9.4 - matplotlib-inline==0.1.7 - mccabe==0.7.0 - mistune==3.1.3 - morecantile==6.2.0 - multidict==6.2.0 - mypy==1.15.0 - mypy-extensions==1.0.0 - natsort==8.4.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nbmake==1.5.5 - nest-asyncio==1.6.0 - nodeenv==1.9.1 - notebook==7.3.3 - notebook-shim==0.2.4 - nox==2025.2.9 - numexpr==2.10.2 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - partd==1.4.2 - pexpect==4.9.0 - pickleshare==0.7.5 - pillow==11.1.0 - pipreqs==0.5.0 - planet==2.19.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pprintpp==0.4.0 - pre-commit==4.2.0 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - propcache==0.3.1 - proto-plus==1.26.1 - protobuf==6.30.2 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pyarrow==19.0.1 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycodestyle==2.13.0 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pyflakes==3.3.2 - pygadm==0.5.3 - pygaul==0.3.4 - pygments==2.19.1 - pyjwt==2.10.1 - pyogrio==0.10.0 - pyparsing==3.2.3 - pyproj==3.6.1 - pystac==1.10.1 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-datadir==1.6.1 - pytest-deadfixtures==2.2.1 - pytest-icdiff==0.9 - pytest-regressions==2.7.0 - pytest-sugar==1.0.0 - python-box==7.3.2 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - questionary==2.1.0 - rasterio==1.4.3 - referencing==0.36.2 - requests==2.32.3 - requests-cache==1.2.1 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rio-cogeo==5.4.1 - rio-tiler==7.5.1 - rioxarray==0.15.0 - rpds-py==0.24.0 - rsa==4.9 - scooby==0.10.0 - send2trash==1.8.3 - sepal-ui==2.16.4 - server-thread==0.3.0 - shapely==2.0.7 - simpervisor==1.0.0 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - termcolor==2.5.0 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tomlkit==0.13.2 - toolz==1.0.0 - tornado==6.4.2 - tqdm==4.67.1 - traitlets==5.14.3 - traittypes==0.2.1 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - tzdata==2025.2 - uri-template==1.3.0 - uritemplate==4.1.1 - url-normalize==2.2.0 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.30.0 - voila==0.5.8 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - websockets==15.0.1 - werkzeug==3.1.3 - widgetsnbextension==4.0.13 - wrapt==1.17.2 - xarray==2024.7.0 - xyzservices==2025.1.0 - yarg==0.1.9 - yarl==1.18.3 - zipp==3.21.0 prefix: /opt/conda/envs/sepal_ui
[ "tests/test_planetapi/test_PlanetView.py::test_validate_event" ]
[]
[]
[]
MIT License
null
null
139bercy__pypel-78
92fc416b197c73156d83579d2e439698d171e09d
2021-09-08 14:40:05
92fc416b197c73156d83579d2e439698d171e09d
diff --git a/Makefile b/Makefile index b31b86f..7619a79 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ -.PHONY: report local_elastic +.PHONY: report test_cli report: - pytest --cov=. --html=tests/reports/report.html --cov-report html -W error tests/ + pytest --cov=. --html=tests/reports/report.html --cov-report html -W error tests/ -vv ci: pytest --cov=. -W error tests/ diff --git a/README.md b/README.md index cac0a61..66e0eeb 100644 --- a/README.md +++ b/README.md @@ -19,19 +19,32 @@ PYPEL (PYthon Pipeline into ELasticsearch) is a customizable ETL (Extract / Tran - What if my usecase slightly differs from that ? The Extract/Transform/Load parts are separated, and you can modify each one independantly to fit your usecase. -## API descrption -All functionalities are available through the pypel.Process class: +## API summary +All functionalities are available through the pypel.processes.Process class: - - instantiate your Process : `process = pypel.Process()` + - instantiate your Process : `process = pypel.processes.Process()` - extract data : `df = process.extract(file_path)` - transform data : `df = process.transform(df)` - load data : `process.load(df, es_indice, es_instance)` es_indice is the elasticsearch indice you wanna load into, es_instance is an elasticsearch connection : `es = elasticserach.Elasticsearch(ip, ...)` - for conveniance, a wrap-up function exists that bundles all 3 operations in one : `process.process(file_path, es_indice, es_instance)` -The Process constructor takes optional Extractor, Transformer & Loader arguments. These must derive from their pypel-class. +The Process constructor takes optional Extractor, Transformer & Loader arguments. These must derive from their BaseClass. + +4 subpackages are made accessible for customization : + - extractors are located in `pypel.extractors` + - transformers in `pypel.transformers` + - loaders in `pypel.loaders` + - processes in `pypel.processes` + +For options, detailed usage and/or functionalities please refer to the docstrings. + +### In-depth API usage +All custom extractors, transformers and loaders MUST be derived from their respective BaseClass, e.g `BaseTransformer` + +The `Process` class exists for conveniance only. Complex use-cases can (and probably should) ignore it completely, but +the cli currently only instanciates & executes `Process`es. -For options, detailed usage and/or functionalities please refer to the documentation ### Loading from the command line Pypel allows generating & loading from the command line by executing `pypel/main.py`. @@ -44,7 +57,8 @@ For a `--config-file` example, see `pypel/conf_template.json`. Only json config files are currently supported. ## Tests -Move to the project's root directory `pypel` then run `make`. This generates html reports for easier reading. +Move to the project's root directory `pypel` then run `make`. This generates html reports for easier reading, located +at: `./tests/reports/report.html` & `./tests/reports/coverage/index.html` for coverage details. To try loading from a config file, start a local elasticsearch then run `make test_cli`. The test is successful if the recipe executed without failure AND the indices `pypel_bulk_MM_DD`, `pypel_bulk_2_MM_DD`, `pypel_change_indice_MM_DD` diff --git a/conf_template.json b/conf_template.json index 57b75a9..33c05a7 100644 --- a/conf_template.json +++ b/conf_template.json @@ -2,14 +2,15 @@ "Processes": [ { "name": "EXAMPLE", - "Extractor": { - "name": "pypel.Extractor" + "Extractors": { + "name": "pypel.extractors.Extractor" }, - "Transformers": { - "name": "pypel.Transformer" - }, - "Loader": { - "name": "pypel.Loader", + "Transformers": [ + { + "name": "pypel.transformers.Transformer" + }], + "Loaders": { + "name": "pypel.loaders.Loader", "backup": false, "name_export": null, "dont_append_date": false, @@ -19,19 +20,19 @@ }, { "name": "ANOTHER_EXAMPLE", - "Extractor": { - "name": "pypel.Extractor" + "Extractors": { + "name": "pypel.extractors.Extractor" }, "Transformers": [ { - "name": "pypel.Transformer" + "name": "pypel.transformers.Transformer" }, { - "name":"pypel.ColumnStripperTransformer" + "name":"pypel.transformers.ColumnStripperTransformer" } ], "Loader": { - "name": "pypel.Loader" + "name": "pypel.transformers.Loader" }, "indice": "pypel_bulk_2" } diff --git a/pypel/processes/ProcessFactory.py b/pypel/ProcessFactory.py similarity index 98% rename from pypel/processes/ProcessFactory.py rename to pypel/ProcessFactory.py index 6dbc942..e010243 100644 --- a/pypel/processes/ProcessFactory.py +++ b/pypel/ProcessFactory.py @@ -1,5 +1,5 @@ import importlib -from pypel.processes.Process import Process +from pypel.processes import Process from typing import Optional, Dict, TypedDict, Union, List from elasticsearch import Elasticsearch diff --git a/pypel/__init__.py b/pypel/__init__.py index 3e6764a..a6fa67c 100644 --- a/pypel/__init__.py +++ b/pypel/__init__.py @@ -1,16 +1,15 @@ -from pypel.processes.Process import Process -from pypel.processes.ProcessFactory import ProcessFactory -from pypel.transformers.Transformer import Transformer, BaseTransformer, ColumnStripperTransformer -from pypel.loaders.Loader import Loader, BaseLoader -from pypel.extractors.Extractor import Extractor +import pypel.processes as processes +from pypel.ProcessFactory import ProcessFactory +import pypel.transformers as transformers +import pypel.loaders as loaders +import pypel.extractors as extractors from pypel.main import process_from_config from pypel.utils.elk.init_index import * from pypel.utils.elk.clean_index import * from pypel._config.config import set_config, get_config -__all__ = ["Process", "ProcessFactory", "process_from_config", "init_index", "clean_index", "BaseTransformer", "Loader", - "Transformer", "Extractor", "logger", "set_config", "get_config", "BaseTransformer", - "ColumnStripperTransformer"] +__all__ = ["processes", "ProcessFactory", "process_from_config", "init_index", "clean_index", "extractors", + "loaders", "logger", "set_config", "get_config"] import logging diff --git a/pypel/extractors/Extractor.py b/pypel/extractors/Extractor.py deleted file mode 100644 index 6b59768..0000000 --- a/pypel/extractors/Extractor.py +++ /dev/null @@ -1,86 +0,0 @@ -import pandas as pd -import re -import openpyxl -from pypel.utils.utils import arrayer -import warnings -import logging -from pypel._config.config import get_config -from typing import Dict, Optional, List, Union - -logger = logging.getLogger(__name__) -logger.setLevel(getattr(logging, get_config()["LOGS_LEVEL"])) - - -class Extractor: - """ - Encapsulates all the extracting, getting data logic. - """ - - def extract(self, file_path: Union[str, bytes], - converters: Optional[Dict[str, type]] = None, - dates: Optional[List[str]] = False, - sheet_name: Union[None, int, str, List[Union[int, str]]] = 0, - skiprows: Optional[int] = None, **kwargs): - """ - Read the passed file and return it as a dataframe. - Uses many pandas parameters defined at Extractor instanciation. - - :param file_path: absolute path to the file - :param converters: - cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) - :param dates: this is equivalent to pandas' `parse_dates` in - [read_excel](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) - :param sheet_name: - cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) - :param skiprows: - cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) - :param kwargs: additional pandas args - :return: pandas.Dataframe object - """ - if file_path.endswith(".csv"): - if get_config()["LOGS"]: - with open(file_path) as file: - row_count = sum(1 for row in file) - file_name = re.findall(r"(?<=/)[^/]*$", file_path)[0] - logger.debug(f"{row_count} rows (including header)" - f"detected in the csv {file_name}") - return pd.read_csv(file_path, - converters=converters, - parse_dates=dates, - **kwargs) - elif file_path.endswith(".xlsx"): - if get_config()["LOGS"]: - wb = openpyxl.load_workbook(filename=file_path) - if sheet_name != 0: - sheet = wb[sheet_name] - else: - sheet = wb[wb.sheetnames[0]] - sheet_name = sheet.title - excel_rows = sheet.max_row - try: - file_name = re.findall(r"(?<=/)[.\s\w_-]+$", file_path)[0] - except IndexError: - warnings.warn(f"Could not get file name from file path :" - f"{file_path}") - file_name = "ERROR" - logger.debug(f"{excel_rows} rows in the excel sheet \'{sheet_name}\' from file \'{file_name}\'") - if skiprows is not None: - skiprows = arrayer(skiprows) - return pd.read_excel(io=file_path, - skiprows=skiprows, - sheet_name=sheet_name, - converters=converters, - **kwargs) - elif file_path.endswith(".xls"): - if get_config()["LOGS"]: - logger.debug(f"Targeting file \'{file_path}\'") - if skiprows is not None: - skiprows = arrayer(skiprows) - return pd.read_excel(io=file_path, - skiprows=skiprows, - sheet_name=sheet_name, - converters=converters, - engine="xlrd", - **kwargs) - else: - raise ValueError("File has unsupported file extension") diff --git a/pypel/extractors/Extractors.py b/pypel/extractors/Extractors.py new file mode 100644 index 0000000..a87a530 --- /dev/null +++ b/pypel/extractors/Extractors.py @@ -0,0 +1,203 @@ +import abc +import pandas as pd +import re +import openpyxl +from pypel.utils.utils import arrayer +import warnings +import logging +from pypel._config.config import get_config +from typing import Dict, Optional, List, Union, Any + +logger = logging.getLogger(__name__) +logger.setLevel(getattr(logging, get_config()["LOGS_LEVEL"])) + + +class BaseExtractor: + @abc.abstractmethod + def extract(self, *args, **kwargs) -> Any: + """This method must be implemented""" + + +class Extractor(BaseExtractor): + """ + Encapsulates all the extracting, getting data logic. + """ + def extract(self, file_path: Union[str, bytes], + converters: Optional[Dict[str, type]] = None, + dates: Optional[List[str]] = False, + sheet_name: Union[None, int, str, List[Union[int, str]]] = 0, + skiprows: Optional[int] = None, **kwargs) -> pd.DataFrame: + """ + Read the passed file and return it as a dataframe. + Uses many pandas parameters defined at Extractor instanciation. + + :param file_path: absolute path to the file + :param converters: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param dates: this is equivalent to pandas' `parse_dates` in + [read_excel](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param sheet_name: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param skiprows: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param kwargs: additional pandas args + :return: pandas.Dataframe object + """ + if file_path.endswith(".csv"): + if get_config()["LOGS"]: + with open(file_path) as file: + row_count = sum(1 for row in file) + file_name = re.findall(r"(?<=/)[^/]*$", file_path)[0] + logger.debug(f"{row_count} rows (including header)" + f"detected in the csv {file_name}") + return pd.read_csv(file_path, + converters=converters, + parse_dates=dates, + **kwargs) + elif file_path.endswith(".xlsx"): + if get_config()["LOGS"]: + wb = openpyxl.load_workbook(filename=file_path) + if sheet_name != 0: + sheet = wb[sheet_name] + else: + sheet = wb[wb.sheetnames[0]] + sheet_name = sheet.title + excel_rows = sheet.max_row + try: + file_name = re.findall(r"(?<=/)[.\s\w_-]+$", file_path)[0] + except IndexError: + warnings.warn(f"Could not get file name from file path :" + f"{file_path}") + file_name = "ERROR" + logger.debug(f"{excel_rows} rows in the excel sheet \'{sheet_name}\' from file \'{file_name}\'") + if skiprows is not None: + skiprows = arrayer(skiprows) + return pd.read_excel(io=file_path, + skiprows=skiprows, + sheet_name=sheet_name, + converters=converters, + **kwargs) + elif file_path.endswith(".xls"): + if get_config()["LOGS"]: + logger.debug(f"Targeting file \'{file_path}\'") + if skiprows is not None: + skiprows = arrayer(skiprows) + return pd.read_excel(io=file_path, + skiprows=skiprows, + sheet_name=sheet_name, + converters=converters, + engine="xlrd", + **kwargs) + else: + raise ValueError("File has unsupported file extension") + + +class CSVExtractor(BaseExtractor): + def extract(self, file_path: Union[str, bytes], + converters: Optional[Dict[str, type]] = None, + dates: Optional[List[str]] = False, + skiprows: Optional[int] = None, **kwargs) -> pd.DataFrame: + """ + Read the passed file and return it as a dataframe. + Uses many pandas parameters defined at Extractor instanciation. + + :param file_path: absolute path to the file + :param converters: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param dates: this is equivalent to pandas' `parse_dates` in + [read_excel](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param skiprows: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param kwargs: additional pandas args + :return: pandas.Dataframe object + """ + if get_config()["LOGS"]: + with open(file_path) as file: + row_count = sum(1 for row in file) + file_name = re.findall(r"(?<=/)[^/]*$", file_path)[0] + logger.debug(f"{row_count} rows (including header)" + f"detected in the csv {file_name}") + return pd.read_csv(file_path, + converters=converters, + parse_dates=dates, + **kwargs) + + +class XLSExtractor(BaseExtractor): + def extract(self, file_path: Union[str, bytes], + converters: Optional[Dict[str, type]] = None, + dates: Optional[List[str]] = False, + sheet_name: Union[None, int, str, List[Union[int, str]]] = 0, + skiprows: Optional[int] = None, **kwargs) -> pd.DataFrame: + """ + Read the passed file and return it as a dataframe. + Uses many pandas parameters defined at Extractor instanciation. + + :param file_path: absolute path to the file + :param converters: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param dates: this is equivalent to pandas' `parse_dates` in + [read_excel](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param sheet_name: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param skiprows: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param kwargs: additional pandas args + :return: pandas.Dataframe object + """ + if get_config()["LOGS"]: + logger.debug(f"Targeting file \'{file_path}\'") + if skiprows is not None: + skiprows = arrayer(skiprows) + return pd.read_excel(io=file_path, + skiprows=skiprows, + sheet_name=sheet_name, + converters=converters, + engine="xlrd", + **kwargs) + + +class XLSXExtractor(BaseExtractor): + def extract(self, file_path: Union[str, bytes], + converters: Optional[Dict[str, type]] = None, + dates: Optional[List[str]] = False, + sheet_name: Union[None, int, str, List[Union[int, str]]] = 0, + skiprows: Optional[int] = None, **kwargs) -> pd.DataFrame: + """ + Read the passed file and return it as a dataframe. + Uses many pandas parameters defined at Extractor instanciation. + + :param file_path: absolute path to the file + :param converters: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param dates: this is equivalent to pandas' `parse_dates` in + [read_excel](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param sheet_name: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param skiprows: + cf [pandas' doc](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html) + :param kwargs: additional pandas args + :return: pandas.Dataframe object + """ + if get_config()["LOGS"]: + wb = openpyxl.load_workbook(filename=file_path) + if sheet_name != 0: + sheet = wb[sheet_name] + else: + sheet = wb[wb.sheetnames[0]] + sheet_name = sheet.title + excel_rows = sheet.max_row + try: + file_name = re.findall(r"(?<=/)[.\s\w_-]+$", file_path)[0] + except IndexError: + warnings.warn(f"Could not get file name from file path :" + f"{file_path}") + file_name = "ERROR" + logger.debug(f"{excel_rows} rows in the excel sheet \'{sheet_name}\' from file \'{file_name}\'") + if skiprows is not None: + skiprows = arrayer(skiprows) + return pd.read_excel(io=file_path, + skiprows=skiprows, + sheet_name=sheet_name, + converters=converters, + **kwargs) diff --git a/pypel/extractors/__init__.py b/pypel/extractors/__init__.py new file mode 100644 index 0000000..cf1e9d1 --- /dev/null +++ b/pypel/extractors/__init__.py @@ -0,0 +1,4 @@ +from .Extractors import BaseExtractor, Extractor, XLSExtractor, XLSXExtractor, CSVExtractor + + +__all__ = ["BaseExtractor", "Extractor", "XLSExtractor", "XLSXExtractor", "CSVExtractor"] diff --git a/pypel/loaders/Loader.py b/pypel/loaders/Loaders.py similarity index 96% rename from pypel/loaders/Loader.py rename to pypel/loaders/Loaders.py index a4bddea..1fe646e 100644 --- a/pypel/loaders/Loader.py +++ b/pypel/loaders/Loaders.py @@ -18,18 +18,13 @@ class Action(TypedDict): _source: Any -class BaseLoader(abc.ABC): +class BaseLoader: """Dummy class that all Loaders should inherit from.""" @abc.abstractmethod - def load(self, *args, **kwargs): + def load(self, *args, **kwargs) -> Any: """This method must be implemented""" -class EmptyLoader(BaseLoader): - def load(self, *args, **kwargs): - """This loader does nothing.""" - - class Loader(BaseLoader): """ Encapsulates all the loading logic. @@ -46,7 +41,7 @@ class Loader(BaseLoader): path_to_export_folder: Union[None, str, bytes, os.PathLike] = None, backup: bool = False, name_export: Optional[str] = None, - dont_append_date: bool = False): + dont_append_date: bool = False) -> None: if backup: if path_to_export_folder is None: raise ValueError("No export folder passed but backup set to true !") @@ -155,7 +150,7 @@ class CSVWriter(BaseLoader): """ Loader that saves the dataframe in a csv file """ - def load(self, dataframe: pd.DataFrame, path: os.PathLike, **kwargs): + def load(self, dataframe: pd.DataFrame, path: os.PathLike, **kwargs) -> None: """ Saves `dataframe` into the csv `path` diff --git a/pypel/loaders/__init__.py b/pypel/loaders/__init__.py new file mode 100644 index 0000000..a4d1925 --- /dev/null +++ b/pypel/loaders/__init__.py @@ -0,0 +1,4 @@ +from .Loaders import BaseLoader, Loader, CSVWriter + + +__all__ = ["BaseLoader", "Loader", "CSVWriter"] diff --git a/pypel/main.py b/pypel/main.py index 242e271..9d1d273 100644 --- a/pypel/main.py +++ b/pypel/main.py @@ -1,15 +1,15 @@ import json import os import pathlib -import warnings +import sys import elasticsearch import argparse import ssl -from pypel.processes.ProcessFactory import ProcessFactory +from pypel.ProcessFactory import ProcessFactory # import pypel.utils.elk.clean_index as clean_index # import pypel.utils.elk.init_index as init_index import logging.handlers -from typing import List, Dict, TypedDict, Union +from typing import List, Dict, TypedDict, Union, Optional logger = logging.getLogger(__name__) @@ -26,14 +26,14 @@ class ProcessConfig(ProcessConfigMandatory): class Config(TypedDict): - Process: List[ProcessConfig] + Processes: List[ProcessConfig] def select_process_from_config(es_: elasticsearch.Elasticsearch, processes: Config, process: str, - files: pathlib.Path, - indice: Union[None, str]): + files: Union[pathlib.Path, str], + indice: Optional[str]): """ Given a pair of configurations (global & process configuration `conf`and mapping configuration `mappings`), load all processes related to `process`, or all of them if `process` is omitted in to the Elasticsearch @@ -49,18 +49,23 @@ def select_process_from_config(es_: elasticsearch.Elasticsearch, if processes is None: raise ValueError("key 'Processes' not found in the passed config, no idea what to do.") else: - assert isinstance(processes, list) + try: + assert isinstance(processes, list) + except AssertionError as e_: + raise ValueError("Processes is not a list, please encapsulate Processes inside a list even if you only " + "have a single Process") from e_ if process == "all": for proc in processes: process_from_config(es_, proc, files, indice) else: - if process in [conf["name"] for conf in processes]: - process_from_config(es_, [conf for conf in processes if conf["name"] == process][0], files, indice) + if process in [conf.get("name") for conf in processes]: + process_from_config(es_, [conf for conf in processes if conf.get("name") == process][0], files, indice) else: raise ValueError(f"process {process} not found in the configuration file !") -def process_from_config(es_, process, files, indice): +def process_from_config(es_: elasticsearch.Elasticsearch, process: ProcessConfig, files: Union[pathlib.Path, str], + indice: Optional[str]): """ Instantiate the process from its passed configuration, and execute it on passed file or directory @@ -71,31 +76,34 @@ def process_from_config(es_, process, files, indice): :return: None """ if indice: - _indice = indice + indice_ = indice else: - _indice = process["indice"] + indice_ = process["indice"] processor = ProcessFactory().create_process(process, es_) if os.path.isdir(files): file_paths = [os.path.join(files, f_).__str__() for f_ in os.listdir(files)] - bulk_op = {indice: file_paths} + bulk_op = {indice_: file_paths} processor.bulk(bulk_op) + elif os.path.isfile(files): + processor.process(files, indice_, es_) else: - processor.process(files, _indice, es_) + raise FileNotFoundError(f"Could not find file {files}") -def get_args(): +def get_args(args_): """Return the process concerned - in case it's specified at the command line.""" parser = argparse.ArgumentParser(description='Process the type of Process') + parser.add_argument("-f", "--source-path", type=str, help="path to the file or directory to load from", + required=True) parser.add_argument("-c", "--config-file", default="./conf/config.json", type=str, help="get the path to the config file to load from") - parser.add_argument("-f", "--source-path", type=str, help="path to the file or directory to load from") # TODO: should that be a pypel functionnality ? # parser.add_argument("-c", "--clean", default=False, type=str, help="should elasticsearch indices be cleared") # parser.add_argument("-m", "--mapping", default="./conf/index_mappings.json", type=pathlib.Path, # help="path to the elasticsearch indices's mappings") parser.add_argument("-p", "--process", default="all", help="specify the process(es) to execute") parser.add_argument("-i", "--indice", default=None, help="specify the indice to load into") - return parser.parse_args() + return parser.parse_args(args_) def get_es_instance(conf): @@ -122,7 +130,7 @@ def get_es_instance(conf): if __name__ == "__main__": # pragma: no cover - args = get_args() + args = get_args(sys.argv[1:]) for arg in args.__dict__: logger.debug(arg, args.__getattribute__(arg)) path_to_conf = os.path.join(os.getcwd(), args.config_file) @@ -144,5 +152,5 @@ if __name__ == "__main__": # pragma: no cover clean_index.clean_index(mappings, es_index_client) init_index.init_index(mappings, es_index_client) """ - logger.debug(config["Processes"]) - select_process_from_config(es, config["Processes"], args.process, args.source_path, args.indice) + logger.debug(config.get("Processes")) + select_process_from_config(es, config.get("Processes"), args.process, args.source_path, args.indice) diff --git a/pypel/processes/Process.py b/pypel/processes/Processes.py similarity index 88% rename from pypel/processes/Process.py rename to pypel/processes/Processes.py index 1c6e38c..0dec29e 100644 --- a/pypel/processes/Process.py +++ b/pypel/processes/Processes.py @@ -1,7 +1,7 @@ import os -from pypel.extractors.Extractor import Extractor -from pypel.transformers.Transformer import Transformer, BaseTransformer -from pypel.loaders.Loader import Loader, BaseLoader +from pypel.extractors.Extractors import BaseExtractor, CSVExtractor +from pypel.transformers.Transformers import Transformer, BaseTransformer +from pypel.loaders.Loaders import Loader, BaseLoader from elasticsearch import Elasticsearch import warnings from typing import Dict, List, Union, Optional @@ -14,14 +14,14 @@ class Process: Parameters ---------- - :param extractor: pypel.Extractor + :param extractor: Optional[pypel.extractors.Extractor] instance or class to use for extracting data. MUST be derived from pypel.Extractor - :param transformer: pypel.Transformer + :param transformer: Union[pypel.BaseTransformer, type, List[pypel.transformers.BaseTransformers], None] instance, class or list of instances to use for transforming data. MUST be derived from pypel.Transformer, for lists, all elements of the list must inherit from pypel.Transformer. if list-like, will be for-in looped on, so mind the order. - :param loader: pypel.Loader + :param loader: Union[pypel.loaders.BaseLoader, type, None] class to use for loading data. MUST be derived from pypel.Loader Examples @@ -29,24 +29,24 @@ class Process: Instanciate the default Process >>> import pypel - >>> my_process = Process() + >>> my_process = pypel.processes.Process() Instanciate a Process with a custom Extractor (same logic applies for custom Transformers/Loaders) - >>> class MyExtractor(pypel.Extractor): + >>> class MyExtractor(pypel.extractors.Extractor): ... pass >>> my_extractor_instance = MyExtractor() - >>> my_process2 = pypel.Process(extractor=my_extractor_instance) + >>> my_process2 = pypel.processes.Process(extractor=my_extractor_instance) """ def __init__(self, - extractor: Extractor = None, - transformer: Union[Transformer, type, List[Transformer]] = None, + extractor: Optional[BaseExtractor] = None, + transformer: Union[BaseTransformer, type, List[BaseTransformer], None] = None, loader: Union[Loader, type, None] = None): - self.extractor = extractor if extractor is not None else Extractor() + self.extractor = extractor if extractor is not None else CSVExtractor() self.transformer = transformer if transformer is not None else Transformer self.loader = loader if loader is not None else Loader try: - assert isinstance(self.extractor, Extractor) + assert isinstance(self.extractor, BaseExtractor) except AssertionError as e: raise ValueError("Bad extractor") from e try: @@ -163,7 +163,7 @@ class Process: ======= Example - >>> process = Process(Extractor(), Transformer(), Loader()) + >>> process = Process(CSVExtractor(), Transformer(), Loader()) >>> myconf = {"covid_stats.csv": "covid", "relance.xls": "relance", "obscure_name.xlsx": "id7654"} >>> process.bulk(myconf) Equivalent to @@ -182,7 +182,7 @@ class Process: except AssertionError: err = "" if not self.__transformer_is_instanced: - err = f"Transformer" + err = "Transformer" if not self.__loader_is_instanced: if err: err = f"{err}, Loader" diff --git a/pypel/processes/__init__.py b/pypel/processes/__init__.py new file mode 100644 index 0000000..ed7b6e1 --- /dev/null +++ b/pypel/processes/__init__.py @@ -0,0 +1,4 @@ +from .Processes import Process + + +__all__ = ["Process"] diff --git a/pypel/transformers/Transformer.py b/pypel/transformers/Transformers.py similarity index 92% rename from pypel/transformers/Transformer.py rename to pypel/transformers/Transformers.py index 05bc127..257d356 100644 --- a/pypel/transformers/Transformer.py +++ b/pypel/transformers/Transformers.py @@ -1,16 +1,16 @@ import os -from pypel.extractors.Extractor import Extractor +from pypel.extractors.Extractors import Extractor import warnings from typing import List, Dict, Optional, Any, Union -from pandas import DataFrame, to_datetime +from pandas import DataFrame, to_datetime, NA import abc -class BaseTransformer(abc.ABC): +class BaseTransformer: """Dummy class that all Transformers must inherit from.""" @abc.abstractmethod - def transform(self, *args, **kwargs) -> DataFrame: + def transform(self, *args, **kwargs) -> Any: """This method must be implemented""" @@ -160,28 +160,28 @@ class Transformer(BaseTransformer): class ColumnStripperTransformer(BaseTransformer): """Strips column names, removing trailing and leading whitespaces.""" - def transform(self, df: DataFrame): - return df.columns.astype(str).str.strip() + def transform(self, df: DataFrame) -> DataFrame: + return df.rename(columns=str.strip) class ColumnReplacerTransformer(BaseTransformer): """Allows replacing column names.""" - def transform(self, df: DataFrame, column_replace_dict: Dict[str, str]): - return df.columns.to_series().replace(column_replace_dict, regex=True) + def transform(self, df: DataFrame, column_replace_dict: Dict[str, str]) -> DataFrame: + return df.rename(columns=column_replace_dict) -class ColumnCapitaliser(BaseTransformer): +class ColumnCapitaliserTransformer(BaseTransformer): """Capitalizes column names.""" - def transform(self, df: DataFrame): - return df.columns.to_series().astype(str).str.capitalize() + def transform(self, df: DataFrame) -> DataFrame: + return df.rename(columns=str.capitalize) -class ColumnContenStripper(BaseTransformer): +class ColumnContenStripperTransformer(BaseTransformer): """Strips/trims the contents of a column. Said column(s) must contain only str values.""" - def transform(self, df: DataFrame, columns_to_strip: List[str]): + def transform(self, df: DataFrame, columns_to_strip: List[str]) -> DataFrame: df_ = df.copy() for column in columns_to_strip: try: @@ -196,25 +196,25 @@ class ColumnContenStripper(BaseTransformer): class ContentReplacerTransformer(BaseTransformer): """Allows replacing contents of a column""" - def transform(self, df: DataFrame, replace_dict: Dict[Any, Any]): + def transform(self, df: DataFrame, replace_dict: Dict[Any, Any]) -> DataFrame: return df.replace(replace_dict, regex=True) class NullValuesReplacerTransformer(BaseTransformer): """Replaces NaNs, NaTs or similar values by None, because None is understood by elasticsearc where nans arent.""" - def transform(self, df: DataFrame): + def transform(self, df: DataFrame) -> DataFrame: """ We use x != x because we want to check for both NaN & NaT at the same time, also any value that do pass this check should probably be taken care of anyway. """ - return df.applymap(lambda x: None if x != x else x) + return df.applymap(lambda x: None if x is NA or x != x else x) class DateFormatterTransformer(BaseTransformer): """Allows changing the date format of specific datetime columns""" - def transform(self, df: DataFrame, date_columns: List[str], date_format="%Y-%m-%d"): + def transform(self, df: DataFrame, date_columns: List[str], date_format="%Y-%m-%d") -> DataFrame: """ :param df: the dataframe to modify :param date_columns: the columns containing the datetime values to modify @@ -226,7 +226,7 @@ class DateFormatterTransformer(BaseTransformer): try: df_[col] = df_[col].dt.strftime(date_format) except AttributeError as e: - raise ValueError(f"Column {col} has non-datetime values, the columns to format must be datetimes." + raise ValueError(f"Column {col} has non-datetime values, the columns to format must be datetimes. " f"Please parse beforehands.") from e return df_ @@ -234,7 +234,7 @@ class DateFormatterTransformer(BaseTransformer): class DateParserTransformer(BaseTransformer): """Converts passed columns' values to datetime objects. Date parsing is prefered at extraction.""" - def transform(self, df: DataFrame, date_columns: List[str], date_format: str = "%Y-%m-%d"): + def transform(self, df: DataFrame, date_columns: List[str], date_format: str = "%Y-%m-%d") -> DataFrame: """ :param df: the dataframe containing the columns to parse diff --git a/pypel/transformers/__init__.py b/pypel/transformers/__init__.py new file mode 100644 index 0000000..fc98144 --- /dev/null +++ b/pypel/transformers/__init__.py @@ -0,0 +1,8 @@ +from .Transformers import (BaseTransformer, Transformer, ColumnStripperTransformer, ColumnReplacerTransformer, + ContentReplacerTransformer, ColumnCapitaliserTransformer, ColumnContenStripperTransformer, + NullValuesReplacerTransformer, DateParserTransformer, DateFormatterTransformer, + MergerTransformer) + +__all__ = ["BaseTransformer", "Transformer", "ColumnReplacerTransformer", "ColumnCapitaliserTransformer", + "ColumnStripperTransformer", "ColumnContenStripperTransformer", "ContentReplacerTransformer", + "NullValuesReplacerTransformer", "DateFormatterTransformer", "DateParserTransformer", "MergerTransformer"] diff --git a/requirements-dev.txt b/requirements-dev.txt index 8d0a49f..e810536 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -7,3 +7,4 @@ xlrd>=2.0.0 pytest pytest-cov pytest-html +pytest-mock diff --git a/setup.py b/setup.py index 0161bc1..8c048b6 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from setuptools import setup, find_packages setup(name='pypel', - version='0.7.1', + version='0.9.0', description="Python Pipeline into Elasticsearch", packages=find_packages(exclude=('tests', 'docs', "docker", "Doc"), where="."), author="Quentin Dimarellis",
Add tests for all Loaders & Transformers Transformers implemented in #71 are not test covered. Neither is the CSVWriter loader.
139bercy/pypel
diff --git a/tests/__init__.py b/tests/__init__.py index faa4ca5..9c5125e 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,1 +1,2 @@ -# obligé de la rajouter si on veut tester avec la commande "pytest" sinon il irra chercher les import dans le dossier d'instalation de pytest \ No newline at end of file +# obligé de la rajouter si on veut tester avec la commande "pytest" +# sinon il ira chercher les import dans le dossier d'instalation de pytest diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py new file mode 100644 index 0000000..324e744 --- /dev/null +++ b/tests/integration/test_cli.py @@ -0,0 +1,209 @@ +import elasticsearch +import pytest +import pypel.processes +import ssl +import os +from pypel.main import get_args, select_process_from_config, process_from_config, get_es_instance + + +@pytest.fixture +def process_config(): + return { + "Extractors": { + "name": "pypel.extractors.Extractor" + }, + "Transformers": [{ + "name": "pypel.transformers.Transformer" + }], + "Loaders": { + "name": "pypel.loaders.Loader", + }, + "indice": "my_indice" + } + + +@pytest.fixture +def processes_config(): + return [{ + "name": "EXAMPLE", + "Extractors": { + "name": "pypel.extractors.Extractor" + }, + "Transformers": [ + { + "name": "pypel.transformers.ColumnStripperTransformer" + } + ], + "Loaders": { + "name": "pypel.loaders.Loader" + }, + "indice": "pypel_bulk" + }, + { + "name": "ANOTHER_EXAMPLE", + "Extractors": { + "name": "pypel.extractors.Extractor" + }, + "Transformers": [{ + "name": "pypel.transformers.Transformer" + }], + "Loaders": { + "name": "pypel.loaders.Loader" + }, + "indice": "pypel_bulk_2" + }] + + +def mock_ssl_context(cafile): + return {"name": cafile} + + +class TestGetArgs: + def test_raises_if_file_not_specified(self): + with pytest.raises(SystemExit): + get_args([]) + + def test_process(self): + key = "process" + expected = "MyProcess" + actual = get_args(["-p", "MyProcess", "-f", "/f"]).__getattribute__(key) + assert expected == actual + + def test_indice(self): + key = "indice" + expected = "my_indice" + actual = get_args(["-i", "my_indice", "-f", "/f"]).__getattribute__(key) + assert expected == actual + + def test_source_path(self): + key = "source_path" + expected = "/home/user/data.csv" + actual = get_args(["-f", "/home/user/data.csv"]).__getattribute__(key) + assert expected == actual + + def test_config_file(self): + key = "config_file" + expected = "/home/user/pypel/config_template.json" + actual = get_args(["-c", "/home/user/pypel/config_template.json", "-f", "/f"]).__getattribute__(key) + assert expected == actual + + def test_defaults(self): + expected = { + "source_path": "/home/user/data.csv", + "config_file": "./conf/config.json", + "process": "all", + "indice": None} + actual = get_args(["-f", "/home/user/data.csv"]) + for key in actual.__dict__: + assert actual.__getattribute__(key) == expected[key] + + def test_all_params(self): + expected = { + "source_path": "/file", + "config_file": "/home/user/pypel_conf.json", + "process": "MYPROCESS", + "indice": "indice"} + actual = get_args(["-f", "/file", "-i", "indice", "-c", "/home/user/pypel_conf.json", "-p", "MYPROCESS"]) + for key in actual.__dict__: + assert actual.__getattribute__(key) == expected[key] + + +class TestGetESInstance: + def test_no_authentication(self, monkeypatch): + def assert_es_instanciation_called_with(hosts, http_auth, use_ssl=False, scheme=None, port=8080, + ssl_context=None): + assert hosts == "localhost" + assert http_auth is None + monkeypatch.setattr(elasticsearch, "Elasticsearch", assert_es_instanciation_called_with) + get_es_instance({}) + + def test_authentication_no_cafile(self, monkeypatch): + def assert_es_instanciation_called_with(hosts, http_auth, use_ssl=False, scheme=None, port=8080, + ssl_context=None): + assert hosts == "localhost" + assert http_auth == ("user", "my_pwd") + + monkeypatch.setattr(elasticsearch, "Elasticsearch", assert_es_instanciation_called_with) + get_es_instance({"user": "user", "pwd": "my_pwd"}) + + def test_cafile(self, monkeypatch): + def assert_es_instanciation_called_with(hosts, http_auth, use_ssl=False, scheme=None, port=8080, + ssl_context=None): + assert hosts == "1.12.4.2" + assert http_auth == ("elastic", "changeme") + assert use_ssl is True + assert scheme == "https" + assert port == 8080 + assert ssl_context == {"name": "fake_cafile_content"} + + monkeypatch.setattr(elasticsearch, "Elasticsearch", assert_es_instanciation_called_with) + monkeypatch.setattr(ssl, "create_default_context", mock_ssl_context) + get_es_instance({"user": "elastic", "pwd": "changeme", "host": "1.12.4.2", "scheme": "https", "port": 8080, + "cafile": "fake_cafile_content"}) + + +class TestProcessFromConfig: + def test_raises_if_non_existant_file(self, process_config, es_instance): + with pytest.raises(FileNotFoundError, match="Could not find file /i_do_not_exist"): + process_from_config(es_instance, process_config, "/i_do_not_exist", None) + + def test_single_file(self, monkeypatch, process_config, es_instance): + def process_assert_called_with(_, file_path, indice, instance): + assert file_path == "./tests/fake_data/test_init_df.csv" + assert indice == "my_indice" + assert instance is es_instance + + monkeypatch.setattr(pypel.processes.Process, "process", process_assert_called_with) + process_from_config(es_instance, process_config, "./tests/fake_data/test_init_df.csv", None) + + def test_with_cl_indice(self, monkeypatch, process_config, es_instance): + def process_assert_called_with(_, file_path, indice, instance): + assert file_path == "./tests/fake_data/test_init_df.csv" + assert indice == "indice" + assert instance is es_instance + + monkeypatch.setattr(pypel.processes.Process, "process", process_assert_called_with) + process_from_config(es_instance, process_config, "./tests/fake_data/test_init_df.csv", "indice") + + def test_directory(self, monkeypatch, process_config, es_instance): + def bulk_assert_called_with(_, dic): + assert dic == { + "my_indice": [os.path.join("./tests/fake_data/", file) for file in os.listdir("./tests/fake_data/")]} + + monkeypatch.setattr(pypel.processes.Process, "bulk", bulk_assert_called_with) + process_from_config(es_instance, process_config, "./tests/fake_data/", None) + + +class TestSelectProcessFromConfig: + def test_raises_if_processes_not_found(self, es_instance): + with pytest.raises(ValueError, match="key 'Processes' not found in the passed config, no idea what to do."): + select_process_from_config(es_instance, None, None, None, None) + + def test_raises_if_processes_not_a_list(self, es_instance): + with pytest.raises(ValueError, + match="Processes is not a list, please encapsulate Processes inside a list even if you only " + "have a single Process"): + select_process_from_config(es_instance, {}, None, None, None) + + def test_raises_if_process_not_in_processes(self, es_instance, processes_config): + with pytest.raises(ValueError, match="process DOESNOTEXIST not found in the configuration file !"): + select_process_from_config(es_instance, processes_config, "DOESNOTEXIST", "/file", None) + + def test_single_process(self, es_instance, monkeypatch, processes_config): + def process_from_conf_assert_called_with(es, proc, file, indice): + assert es == es_instance + assert proc == processes_config[0] + assert file == "/file" + assert indice is None + + monkeypatch.setattr(pypel.main, "process_from_config", process_from_conf_assert_called_with) + select_process_from_config(es_instance, processes_config, "EXAMPLE", "/file", None) + + def test_multiple_processes(self, es_instance, mocker, processes_config): + mocker.patch('pypel.main.process_from_config') + select_process_from_config(es_instance, processes_config, "all", "/file", None) + assert pypel.main.process_from_config.call_count == 2 + # TODO: fix the assert_has_calls logic + # calls = [call(es_instance, proc, "/files", None) for proc in processes_config] + # print("mock_calls", pypel.main.process_from_config.mock_calls) + # pypel.main.process_from_config.assert_has_calls(calls) diff --git a/tests/integration/test_factory.py b/tests/integration/test_factory.py index 2e2ec4a..9bd0734 100644 --- a/tests/integration/test_factory.py +++ b/tests/integration/test_factory.py @@ -9,24 +9,24 @@ def factory(): class TestFactory: def test_factory_defaults_when_empty_config(self, factory, es_instance): - expected = pypel.Process() + expected = pypel.processes.Process() obtained = factory.create_process({}, es_instance=es_instance) assert isinstance(obtained, type(expected)) def test_factory_instantiates_non_default_transformers(self, factory, es_instance): - expected = pypel.Process(transformer=pypel.transformers.Transformer.ColumnStripperTransformer) - obtained = factory.create_process({"Extractors": {"name": "pypel.Extractor"}, - "Transformers": {"name": "pypel.ColumnStripperTransformer"}, - "Loaders": {"name": "pypel.Loader"}}, es_instance=es_instance) + expected = pypel.processes.Process(transformer=pypel.transformers.Transformer) + obtained = factory.create_process({"Extractors": {"name": "pypel.extractors.Extractor"}, + "Transformers": {"name": "pypel.transformers.Transformer"}, + "Loaders": {"name": "pypel.loaders.Loader"}}, es_instance=es_instance) assert isinstance(obtained, type(expected)) def test_factory_instanciates_list_of_transformers(self, factory, es_instance): - expected = pypel.Process(transformer=[pypel.transformers.Transformer.ColumnStripperTransformer(), - pypel.Transformer()]) - obtained = factory.create_process({"Extractors": {"name": "pypel.Extractor"}, - "Transformers": [{"name": "pypel.ColumnStripperTransformer"}, - {"name": "pypel.Transformer"}], - "Loaders": {"name": "pypel.Loader"}}, es_instance=es_instance) + expected = pypel.processes.Process(transformer=[pypel.transformers.ColumnStripperTransformer(), + pypel.transformers.ColumnCapitaliserTransformer()]) + obtained = factory.create_process({"Extractors": {"name": "pypel.extractors.Extractor"}, + "Transformers": [{"name": "pypel.transformers.ColumnStripperTransformer"}, + {"name": "pypel.transformers.Transformer"}], + "Loaders": {"name": "pypel.loaders.Loader"}}, es_instance=es_instance) assert isinstance(obtained, type(expected)) def test_raises_if_class_not_found(self, factory, es_instance): diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py index 397cbd1..85d20c8 100644 --- a/tests/integration/test_integration.py +++ b/tests/integration/test_integration.py @@ -8,14 +8,14 @@ import numpy from tests.unit.test_Loader import LoaderTest, Elasticsearch -class TransformerForTesting(pypel.Transformer): +class TransformerForTesting(pypel.transformers.Transformer): def _format_na(self, df: pd.DataFrame) -> pd.DataFrame: return df.where(df.notnull(), 0).astype(int) @pytest.fixture def ep(): - return pypel.Process() + return pypel.processes.Process(extractor=pypel.extractors.Extractor()) def mockreturn_extract(self, dummy): @@ -36,7 +36,7 @@ def mockreturn_extract(self, dummy): "DATE_DECISION": [dt.datetime.strptime("2019/05/12", "%Y/%m/%d")], "CODE_COMMUNE_ETABLISSEMENT": ['75112'], "STATUT": ["decidé"] - } + } df = pd.DataFrame(d) return df @@ -57,13 +57,13 @@ def mockreturn_extract_no_date(self): "CODE_COMMUNE_ETABLISSEMENT": ['75112'], "Statut": ["decidé"], "ShouldBeNone": numpy.NaN - } + } test_df = pd.DataFrame(test) return test_df def test_integration_extract_transform_no_date(ep, params, monkeypatch): - monkeypatch.setattr(pypel.Process, "extract", mockreturn_extract_no_date) + monkeypatch.setattr(pypel.processes.Process, "extract", mockreturn_extract_no_date) expected = { "PROJET": ["nom du projet"], "ENTREPRISE": ["MINISTERE DE L'ECONOMIE DES FINANCES ET DE LA RELANCE"], @@ -79,20 +79,18 @@ def test_integration_extract_transform_no_date(ep, params, monkeypatch): "CODE_COMMUNE_ETABLISSEMENT": ['75112'], "STATUT": ["decidé"], "SHOULDBENONE": None - } + } df = ep.extract() with pytest.warns(UserWarning): obtained = ep.transform(df, - column_replace={ - "é": "e", - " ": "_"}, - strip=["DEPARTEMENT"]) + column_replace={"é": "e", " ": "_"}, + strip=["DEPARTEMENT"]) expected_df = pd.DataFrame(expected) assert_frame_equal(expected_df, obtained, check_names=True) def test_integration_exctract_transform(ep, params, monkeypatch): - monkeypatch.setattr(pypel.Process, "extract", mockreturn_extract) + monkeypatch.setattr(pypel.processes.Process, "extract", mockreturn_extract) expected = { "PROJET": ["nom du projet"], "ENTREPRISE": ["MINISTERE DE L'ECONOMIE DES FINANCES ET DE LA RELANCE"], @@ -110,12 +108,10 @@ def test_integration_exctract_transform(ep, params, monkeypatch): "DATE_DECISION": ["2019-05-12"], "CODE_COMMUNE_ETABLISSEMENT": ['75112'], "STATUT": ["decidé"] - } + } df = ep.extract("") obtained = ep.transform(df, - column_replace={ - "é": "e", - " ": "_"}, + column_replace={"é": "e", " ": "_"}, date_format="%Y-%m-%d", date_columns=["DATE_DEPOT_PROJET", "DATE_DEBUT_INSTRUCTION", "DATE_DECISION"]) expected_df = pd.DataFrame(expected) @@ -217,12 +213,13 @@ def test_multiple_transformers(ep): testing_df = pd.DataFrame({"0": [numpy.NaN]}) expected_df = pd.DataFrame({"0": [0]}) with pytest.warns(UserWarning): - obtained_df = pypel.Process(transformer=[pypel.Transformer(), TransformerForTesting()]).transform(testing_df) + obtained_df = pypel.processes.Process( + transformer=[pypel.transformers.Transformer(), TransformerForTesting()]).transform(testing_df) assert_frame_equal(expected_df, obtained_df, check_names=True) def test_process_method(): path_csv = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.csv") - process = pypel.Process(loader=LoaderTest(Elasticsearch())) + process = pypel.processes.Process(loader=LoaderTest(Elasticsearch())) with pytest.warns(UserWarning): process.process(path_csv, "indice") diff --git a/tests/unit/test_Loader.py b/tests/unit/test_Loader.py index 3bcd6b0..1805f88 100644 --- a/tests/unit/test_Loader.py +++ b/tests/unit/test_Loader.py @@ -1,6 +1,7 @@ +import os import tempfile import pytest -import pypel +import pypel.loaders.Loaders as loader from pandas import DataFrame @@ -8,7 +9,7 @@ class Elasticsearch: pass -class LoaderTest(pypel.Loader): +class LoaderTest(loader.Loader): def _bulk_into_elastic(self, actions: list, indice: str): pass @@ -34,8 +35,8 @@ class TestLoader: [9, 9, 9, 9, 9]], columns=["0", "1", "2", "3", "4"]) with tempfile.TemporaryDirectory() as path: - loader = LoaderTest(Elasticsearch(), backup=True, path_to_export_folder=path) - loader.load(df, "indice") + loader_ = LoaderTest(Elasticsearch(), backup=True, path_to_export_folder=path) + loader_.load(df, "indice") def test_loading_no_export(self): df = DataFrame(data=[[6, 6, 6, 6, 6], @@ -43,8 +44,8 @@ class TestLoader: [8, 8, 8, 8, 8], [9, 9, 9, 9, 9]], columns=["0", "1", "2", "3", "4"]) - loader = LoaderTest(Elasticsearch()) - loader.load(df, "indice") + loader_ = LoaderTest(Elasticsearch()) + loader_.load(df, "indice") def test_loading_export_named_file(self): df = DataFrame(data=[[6, 6, 6, 6, 6], @@ -53,29 +54,43 @@ class TestLoader: [9, 9, 9, 9, 9]], columns=["0", "1", "2", "3", "4"]) with tempfile.TemporaryDirectory() as path: - loader = LoaderTest(Elasticsearch(), backup=True, path_to_export_folder=path, name_export="name") - loader.load(df, "indice") + loader_ = LoaderTest(Elasticsearch(), backup=True, path_to_export_folder=path, name_export="name") + loader_.load(df, "indice") def test_bad_folder_crashes(self): with pytest.raises(ValueError): - pypel.Loader(Elasticsearch(), path_to_export_folder="/this_folder_does_not_exist", backup=True) + loader.Loader(Elasticsearch(), path_to_export_folder="/this_folder_does_not_exist", backup=True) def test_no_folder_crashes(self): with pytest.raises(ValueError): - pypel.Loader(Elasticsearch(), backup=True) + loader.Loader(Elasticsearch(), backup=True) def test_good_folder(self): - pypel.Loader(Elasticsearch(), path_to_export_folder="/", backup=True) + loader.Loader(Elasticsearch(), path_to_export_folder="/", backup=True) def test_no_backup(self): - pypel.Loader(Elasticsearch()) + loader.Loader(Elasticsearch()) def test_bulk_into_elastic(self, monkeypatch): - monkeypatch.setattr(pypel.loaders.Loader.elasticsearch.helpers, "streaming_bulk", mock_streaming_bulk_no_error) - pypel.Loader(Elasticsearch())._bulk_into_elastic([], "indice") + monkeypatch.setattr(loader.elasticsearch.helpers, "streaming_bulk", mock_streaming_bulk_no_error) + loader.Loader(Elasticsearch())._bulk_into_elastic([], "indice") def test_bulk_into_elastic_warns_on_error(self, monkeypatch): - monkeypatch.setattr(pypel.loaders.Loader.elasticsearch.helpers, "streaming_bulk", + monkeypatch.setattr(loader.elasticsearch.helpers, "streaming_bulk", mock_streaming_bulk_some_errors) with pytest.warns(UserWarning): - pypel.Loader(Elasticsearch())._bulk_into_elastic([], "indice") + loader.Loader(Elasticsearch())._bulk_into_elastic([], "indice") + + +class TestCSVWriter: + def test_asserts_writes_csv(self): + df = DataFrame(data=[[6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], + columns=["0", "1", "2", "3", "4"]) + with tempfile.TemporaryDirectory() as path: + loader_ = loader.CSVWriter() + file_name = "tmpcsv.csv" + loader_.load(df, path + f"/{file_name}") + assert file_name in os.listdir(path) diff --git a/tests/unit/test_extractor.py b/tests/unit/test_extractor.py index edc9cc4..6a1f3e5 100644 --- a/tests/unit/test_extractor.py +++ b/tests/unit/test_extractor.py @@ -1,5 +1,5 @@ import pytest -from pypel import Extractor +from pypel.extractors import Extractor, CSVExtractor, XLSExtractor, XLSXExtractor import pandas as pd from pandas.testing import assert_frame_equal import os @@ -10,6 +10,21 @@ def ex(): return Extractor() +@pytest.fixture +def csv(): + return CSVExtractor() + + +@pytest.fixture +def xls(): + return XLSExtractor() + + +@pytest.fixture +def xlsx(): + return XLSXExtractor() + + class TestExtractor: def test_raises_if_unsupported_file_extension(self, ex): with pytest.raises(ValueError): @@ -124,3 +139,123 @@ class TestExtractor: [9, 9, 9, 9, 9]], columns=["a", "b", "c", "d", "e"]) df = ex.extract(path_xls) assert_frame_equal(expected_xls, df) + + +class TestCSVExtractor: + def test_extract_csv(self, csv): + path_csv = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.csv") + expected_csv = pd.DataFrame(data=[[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5], + [6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], columns=["a", "b", "c", "d", "e"]) + df = csv.extract(path_csv) + assert_frame_equal(expected_csv, df) + + def test_extract_csv_no_logging(self, csv, disable_logs): + path_csv = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.csv") + expected_csv = pd.DataFrame(data=[[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5], + [6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], columns=["a", "b", "c", "d", "e"]) + df = csv.extract(path_csv) + assert_frame_equal(expected_csv, df) + + +class TestXLSXExtractor: + def test_extract_xlsx(self, xlsx): + path = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.xlsx") + expected_default = pd.DataFrame(data=[[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5], + [6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], columns=["a", "b", "c", "d", "e"]) + df = xlsx.extract(path) + assert_frame_equal(expected_default, df) + + def test_extract_xlsx_no_logging(self, xlsx, disable_logs): + path = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.xlsx") + expected_default = pd.DataFrame(data=[[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5], + [6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], columns=["a", "b", "c", "d", "e"]) + df = xlsx.extract(path) + assert_frame_equal(expected_default, df) + + def test_extract_xlsx_skiprows(self, xlsx): + path = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.xlsx") + expected_skip_5 = pd.DataFrame(data=[[6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], + columns=[0, 1, 2, 3, 4]) + df = xlsx.extract(path, skiprows=5, header=None) + assert_frame_equal(expected_skip_5, df) + + def test_extract_xlsx_sheetname(self, xlsx): + path = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.xlsx") + expected_sheetname = pd.DataFrame(data=[[9]], columns=["a"]) + obtained_sheetname = xlsx.extract(path, sheet_name="TEST") + assert_frame_equal(expected_sheetname, obtained_sheetname) + + def test_raises_if_badly_named_file(self, xlsx): + with pytest.warns(UserWarning): + xlsx.extract(os.path.join(os.getcwd(), "tests", "fake_data", "test_bad_filename$.xlsx")) + + +class TestXLSExtractor: + def test_extract_xls(self, xls): + path_xls = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.xls") + expected_xls = pd.DataFrame(data=[[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5], + [6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], columns=["a", "b", "c", "d", "e"]) + df = xls.extract(path_xls) + assert_frame_equal(expected_xls, df) + + def test_extract_skiprows_xls(self, xls): + path_xls = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.xls") + expected_xls = pd.DataFrame(data=[[5, 5, 5, 5, 5], + [6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], columns=[0, 1, 2, 3, 4]) + df = xls.extract(path_xls, skiprows=4, header=None) + assert_frame_equal(expected_xls, df) + + def test_init_datafram_xls_no_logging(self, xls, disable_logs): + path_xls = os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.xls") + expected_xls = pd.DataFrame(data=[[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5], + [6, 6, 6, 6, 6], + [7, 7, 7, 7, 7], + [8, 8, 8, 8, 8], + [9, 9, 9, 9, 9]], columns=["a", "b", "c", "d", "e"]) + df = xls.extract(path_xls) + assert_frame_equal(expected_xls, df) diff --git a/tests/unit/test_process.py b/tests/unit/test_process.py index 2f88d75..e809431 100644 --- a/tests/unit/test_process.py +++ b/tests/unit/test_process.py @@ -4,7 +4,7 @@ import elasticsearch from tests.unit.test_Loader import Elasticsearch, LoaderTest -class Extractor2(pypel.Extractor): +class Extractor2(pypel.extractors.Extractor): pass @@ -19,64 +19,64 @@ def assert_process_called_with_indice1_to_file1(_, file, indice): class TestProcessInstanciation: def test_default_instanciates(self): - pypel.Process() + pypel.processes.Process() def test_bad_type_args_fails(self): with pytest.raises(ValueError): - pypel.Process(extractor="") # noqa + pypel.processes.Process(extractor="") with pytest.raises(ValueError): - pypel.Process(transformer="") + pypel.processes.Process(transformer="") with pytest.raises(ValueError): - pypel.Process(loader="") # noqa + pypel.processes.Process(loader="") with pytest.raises(ValueError): - pypel.Process(extractor=[]) # noqa + pypel.processes.Process(extractor=[]) def test_instance_from_bad_class_fails(self): with pytest.raises(ValueError): - pypel.Process(extractor=FakeExtractor()) # noqa + pypel.processes.Process(extractor=FakeExtractor()) def test_good_args_instanciates(self): - pypel.Process(extractor=Extractor2()) + pypel.processes.Process(extractor=Extractor2()) def test_list_of_transformers_instanciates(self): - pypel.Process(transformer=[pypel.Transformer(), pypel.Transformer()]) + pypel.processes.Process(transformer=[pypel.transformers.Transformer(), pypel.transformers.Transformer()]) def test_list_of_uninstanced_transformers_fails(self): with pytest.raises(ValueError): - pypel.Process(transformer=[pypel.Transformer, pypel.Transformer]) + pypel.processes.Process(transformer=[pypel.transformers.Transformer, pypel.transformers.Transformer]) def test_list_of_wrong_type_fails(self): with pytest.raises(ValueError): - pypel.Process(transformer=[0, 0]) + pypel.processes.Process(transformer=[0, 0]) class TestProcessMethods: def test_transform_instanced_no_args(self, df): - process = pypel.Process(transformer=pypel.Transformer(date_format="", date_columns=[])) + process = pypel.processes.Process(transformer=pypel.transformers.Transformer(date_format="", date_columns=[])) process.transform(df) def test_transform_multiple_transformers_extra_args(self, df): - process = pypel.Process(transformer=[pypel.Transformer(date_format="", date_columns=[]), - pypel.Transformer(date_format="", date_columns=[])]) + process = pypel.processes.Process(transformer=[pypel.transformers.Transformer(date_format="", date_columns=[]), + pypel.transformers.Transformer(date_format="", date_columns=[])]) with pytest.warns(UserWarning): process.transform(df, "extra_argument") def test_load_class_loader_fails_if_no_valid_es_instance_is_passed(self, df): - process = pypel.Process(loader=pypel.Loader) + process = pypel.processes.Process(loader=pypel.loaders.Loader) with pytest.raises(AssertionError): process.load(df, "indice", Elasticsearch()) def test_load_class_loader_passes_if_valid_es_instance_is_passed(self, df): - process = pypel.Process(loader=LoaderTest) + process = pypel.processes.Process(loader=LoaderTest) process.load(df, "indice", elasticsearch.Elasticsearch()) def test_load_instanced_loader_extra_args_warns(self, df): - process = pypel.Process(loader=LoaderTest(Elasticsearch())) + process = pypel.processes.Process(loader=LoaderTest(Elasticsearch())) with pytest.warns(UserWarning): process.load(df, "indice", "extra_arg", extrakeyword="yes") def test_load_instanced_does_not_warn(self, df): - process = pypel.Process(loader=LoaderTest(Elasticsearch())) + process = pypel.processes.Process(loader=LoaderTest(Elasticsearch())) process.load(df, "indice") def test_bulk_with_indice_to_list_format(self, monkeypatch): @@ -85,14 +85,16 @@ class TestProcessMethods: def mock_process_for_multiple_bulk(_, file, indice): processed_dic[file] = indice - monkeypatch.setattr(pypel.Process, "process", mock_process_for_multiple_bulk) - process = pypel.Process(transformer=pypel.Transformer(), loader=pypel.Loader(Elasticsearch())) + monkeypatch.setattr(pypel.processes.Process, "process", mock_process_for_multiple_bulk) + process = pypel.processes.Process(transformer=pypel.transformers.Transformer(), + loader=pypel.loaders.Loader(Elasticsearch())) process.bulk({"indice": ["file1", "file2"]}) assert processed_dic == {"file1": "indice", "file2": "indice"} def test_single_bulk_with_file_indice_format(self, monkeypatch): - process = pypel.Process(transformer=pypel.Transformer(), loader=pypel.Loader(Elasticsearch())) - monkeypatch.setattr(pypel.Process, "process", assert_process_called_with_indice1_to_file1) + process = pypel.processes.Process(transformer=pypel.transformers.Transformer(), + loader=pypel.loaders.Loader(Elasticsearch())) + monkeypatch.setattr(pypel.processes.Process, "process", assert_process_called_with_indice1_to_file1) process.bulk({"file1": "indice1"}) def test_multiple_bulk_with_file_indice_format(self, monkeypatch): @@ -101,7 +103,8 @@ class TestProcessMethods: def mock_process_for_multiple_bulk(_, file, indice): processed_dic[file] = indice - process = pypel.Process(transformer=pypel.Transformer(), loader=pypel.Loader(Elasticsearch())) - monkeypatch.setattr(pypel.Process, "process", mock_process_for_multiple_bulk) + process = pypel.processes.Process(transformer=pypel.transformers.Transformer(), + loader=pypel.loaders.Loader(Elasticsearch())) + monkeypatch.setattr(pypel.processes.Process, "process", mock_process_for_multiple_bulk) process.bulk({"file1": "indice1", "file2": "indice2", "file3": "indice3"}) assert processed_dic == {"file1": "indice1", "file2": "indice2", "file3": "indice3"} diff --git a/tests/unit/test_transformer.py b/tests/unit/test_transformer.py index b6d699c..0045447 100644 --- a/tests/unit/test_transformer.py +++ b/tests/unit/test_transformer.py @@ -1,7 +1,12 @@ import pytest -from pypel import Transformer, Extractor +from pypel.transformers import (Transformer, ColumnStripperTransformer, ColumnReplacerTransformer, + ContentReplacerTransformer, ColumnCapitaliserTransformer, + ColumnContenStripperTransformer, MergerTransformer, + NullValuesReplacerTransformer, DateParserTransformer, DateFormatterTransformer) +from pypel.extractors import Extractor import os -from pandas import DataFrame +from pandas import DataFrame, NA, NaT, to_datetime +from numpy import nan from pandas.testing import assert_frame_equal @@ -10,10 +15,15 @@ def transformer(): return Transformer() +@pytest.fixture +def merger(): + return MergerTransformer() + + class RefExtractor(Extractor): - def extract(self, *args, **kwargs): + def extract(self, *args, **kwargs) -> DataFrame: return DataFrame({ - "0": [0, 1, 2]}) + "0": [0, 1, 2]}) class TestTransformer: @@ -50,6 +60,83 @@ class TestTransformer: def test_merge_ref_with_default_extractor(self, transformer): df = Extractor().extract(os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.csv")) - transformer.merge_referential(df, - os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.csv")) + expected = df.copy() + actual = transformer.merge_referential(df, os.path.join(os.getcwd(), "tests", "fake_data", "test_init_df.csv")) + assert_frame_equal(expected, actual) + + +class TestAtomicTransformers: + def test_column_stripper(self): + tr = ColumnStripperTransformer() + expected = DataFrame(data=[[0]], columns=["bad_column_name"]) + actual = tr.transform(DataFrame(data=[[0]], columns=[" bad_column_name "])) + assert_frame_equal(expected, actual) + + def test_column_replacer(self): + tr = ColumnReplacerTransformer() + expected = DataFrame(data=[[0]], columns=["replaced"]) + actual = tr.transform(DataFrame(data=[[0]], columns=["original"]), column_replace_dict={ + "original": "replaced"}) + assert_frame_equal(expected, actual) + + def test_content_replacer(self): + tr = ContentReplacerTransformer() + expected = DataFrame(data=[["replaced"]], columns=[0]) + actual = tr.transform(DataFrame(data=[["original"]], columns=[0]), replace_dict={ + "original": "replaced"}) + assert_frame_equal(expected, actual) + + def test_column_capitaliser(self): + tr = ColumnCapitaliserTransformer() + expected = DataFrame(data=[[0]], columns=["Capitalized"]) + actual = tr.transform(DataFrame(data=[[0]], columns=["capitalized"])) + assert_frame_equal(expected, actual) + + def test_null_values_replacer(self): + tr = NullValuesReplacerTransformer() + expected = DataFrame(data=[[None], [None], [None]], columns=[0]) + actual = tr.transform(DataFrame(data=[[NA], [NaT], [nan]], columns=[0])) + assert_frame_equal(expected, actual) + + def test_date_parser(self): + tr = DateParserTransformer() + expected = DataFrame(data=[[to_datetime("13-01-1970")]], columns=["to_parse"]) + actual = tr.transform(DataFrame(data=[["13 01 1970"]], columns=["to_parse"]), ["to_parse"], "%d %m %Y") + assert_frame_equal(expected, actual) + + def test_date_formatter(self): + tr = DateFormatterTransformer() + expected = DataFrame(data=[["1970-01-22"]], columns=["to_format"]) + actual = tr.transform(DataFrame(data=[[to_datetime("22 01 1970")]], columns=["to_format"]), ["to_format"]) + assert_frame_equal(expected, actual) + + def test_date_formatter_raises_if_non_datetimes_in_column(self): + with pytest.raises(ValueError, match="Column to_format has non-datetime values, the columns to format must " + "be datetimes. Please parse beforehands."): + tr = DateFormatterTransformer() + tr.transform(DataFrame(data=[["22 01 1970"]], columns=["to_format"]), ["to_format"]) + + +class TestColumnContentStripper: + def test_column_content_stripping(self): + tr = ColumnContenStripperTransformer() + expected = DataFrame(data=[["stripped"]], columns=["to_strip"]) + actual = tr.transform(DataFrame(data=[[" stripped "]], columns=["to_strip"]), columns_to_strip=["to_strip"]) + assert_frame_equal(expected, actual) + + def test_warns_if_column_not_in_df(self): + with pytest.warns(UserWarning, match="No such column not_in_df in passed dataframe"): + tr = ColumnContenStripperTransformer() + tr.transform(DataFrame(data=[[" stripped "]], columns=["to_strip"]), columns_to_strip=["not_in_df"]) + + def test_warns_if_column_not_strings(self): + with pytest.warns(UserWarning, match="Column not_str is not of type `str`, cannot strip."): + tr = ColumnContenStripperTransformer() + tr.transform(DataFrame(data=[[0]], columns=["not_str"]), columns_to_strip=["not_str"]) + +class TestMerger: + def test_merge_with_self(self, df, merger): + expected = df.copy() + actual = merger.transform(df, mergekey="0", ref=df) + assert_frame_equal(expected, actual) diff --git a/tests/unit/test_unit_process.py b/tests/unit/test_unit_process.py index cf8c763..39fb63d 100644 --- a/tests/unit/test_unit_process.py +++ b/tests/unit/test_unit_process.py @@ -1,5 +1,8 @@ import pytest -from pypel import Extractor, Transformer, Loader, Process +from pypel.extractors import Extractor +from pypel.loaders import Loader +from pypel.transformers import Transformer +from pypel.processes import Process from pandas import DataFrame
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_removed_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 11 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.8", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 elastic-transport==8.17.1 elasticsearch==8.17.2 et_xmlfile==2.0.0 exceptiongroup==1.2.2 iniconfig==2.1.0 numpy==1.19.5 openpyxl==3.1.5 packaging==24.2 pandas==1.2.5 pluggy==1.5.0 -e git+https://github.com/139bercy/pypel.git@92fc416b197c73156d83579d2e439698d171e09d#egg=pypel pytest==8.3.5 pytest-mock==3.14.0 python-dateutil==2.9.0.post0 pytz==2025.2 six==1.17.0 tomli==2.2.1 Unidecode==1.3.8 urllib3==2.2.3 xlrd==2.0.1
name: pypel channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=24.2=py38h06a4308_0 - python=3.8.20=he870216_0 - readline=8.2=h5eee18b_0 - setuptools=75.1.0=py38h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.44.0=py38h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - elastic-transport==8.17.1 - elasticsearch==8.17.2 - et-xmlfile==2.0.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - numpy==1.19.5 - openpyxl==3.1.5 - packaging==24.2 - pandas==1.2.5 - pluggy==1.5.0 - pytest==8.3.5 - pytest-mock==3.14.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - six==1.17.0 - tomli==2.2.1 - unidecode==1.3.8 - urllib3==2.2.3 - xlrd==2.0.1 prefix: /opt/conda/envs/pypel
[ "tests/integration/test_cli.py::TestGetArgs::test_raises_if_file_not_specified", "tests/integration/test_cli.py::TestGetArgs::test_process", "tests/integration/test_cli.py::TestGetArgs::test_indice", "tests/integration/test_cli.py::TestGetArgs::test_source_path", "tests/integration/test_cli.py::TestGetArgs::test_config_file", "tests/integration/test_cli.py::TestGetArgs::test_defaults", "tests/integration/test_cli.py::TestGetArgs::test_all_params", "tests/integration/test_cli.py::TestGetESInstance::test_no_authentication", "tests/integration/test_cli.py::TestGetESInstance::test_authentication_no_cafile", "tests/integration/test_cli.py::TestGetESInstance::test_cafile", "tests/integration/test_cli.py::TestProcessFromConfig::test_raises_if_non_existant_file", "tests/integration/test_cli.py::TestProcessFromConfig::test_single_file", "tests/integration/test_cli.py::TestProcessFromConfig::test_with_cl_indice", "tests/integration/test_cli.py::TestProcessFromConfig::test_directory", "tests/integration/test_cli.py::TestSelectProcessFromConfig::test_raises_if_processes_not_found", "tests/integration/test_cli.py::TestSelectProcessFromConfig::test_raises_if_processes_not_a_list", "tests/integration/test_cli.py::TestSelectProcessFromConfig::test_raises_if_process_not_in_processes", "tests/integration/test_cli.py::TestSelectProcessFromConfig::test_single_process", "tests/integration/test_cli.py::TestSelectProcessFromConfig::test_multiple_processes", "tests/integration/test_factory.py::TestFactory::test_factory_defaults_when_empty_config", "tests/integration/test_factory.py::TestFactory::test_factory_instantiates_non_default_transformers", "tests/integration/test_factory.py::TestFactory::test_factory_instanciates_list_of_transformers", "tests/integration/test_factory.py::TestFactory::test_raises_if_class_not_found", "tests/integration/test_integration.py::test_integration_extract_transform_no_date", "tests/integration/test_integration.py::test_integration_exctract_transform", "tests/integration/test_integration.py::test_init_dataframe_excel", "tests/integration/test_integration.py::test_init_dataframe_excel_skiprows", "tests/integration/test_integration.py::test_init_dataframe_excel_sheetname", "tests/integration/test_integration.py::test_init_dataframe_excel_csv", "tests/integration/test_integration.py::test_init_bad_filename", "tests/integration/test_integration.py::test_init_bad_filename_excel", "tests/integration/test_integration.py::test_multiple_transformers", "tests/integration/test_integration.py::test_process_method", "tests/unit/test_Loader.py::TestLoader::test_loading_export_csv", "tests/unit/test_Loader.py::TestLoader::test_loading_no_export", "tests/unit/test_Loader.py::TestLoader::test_loading_export_named_file", "tests/unit/test_Loader.py::TestLoader::test_bad_folder_crashes", "tests/unit/test_Loader.py::TestLoader::test_no_folder_crashes", "tests/unit/test_Loader.py::TestLoader::test_good_folder", "tests/unit/test_Loader.py::TestLoader::test_no_backup", "tests/unit/test_Loader.py::TestLoader::test_bulk_into_elastic", "tests/unit/test_Loader.py::TestLoader::test_bulk_into_elastic_warns_on_error", "tests/unit/test_Loader.py::TestCSVWriter::test_asserts_writes_csv", "tests/unit/test_extractor.py::TestExtractor::test_raises_if_unsupported_file_extension", "tests/unit/test_extractor.py::TestExtractor::test_extract_excel", "tests/unit/test_extractor.py::TestExtractor::test_extract_excel_no_logging", "tests/unit/test_extractor.py::TestExtractor::test_extract_excel_skiprows", "tests/unit/test_extractor.py::TestExtractor::test_extract_excel_sheetname", "tests/unit/test_extractor.py::TestExtractor::test_extract_excel_csv", "tests/unit/test_extractor.py::TestExtractor::test_extract_excel_csv_no_logging", "tests/unit/test_extractor.py::TestExtractor::test_extract_xls", "tests/unit/test_extractor.py::TestExtractor::test_extract_skiprows_xls", "tests/unit/test_extractor.py::TestExtractor::test_init_datafram_xls_no_logging", "tests/unit/test_extractor.py::TestCSVExtractor::test_extract_csv", "tests/unit/test_extractor.py::TestCSVExtractor::test_extract_csv_no_logging", "tests/unit/test_extractor.py::TestXLSXExtractor::test_extract_xlsx", "tests/unit/test_extractor.py::TestXLSXExtractor::test_extract_xlsx_no_logging", "tests/unit/test_extractor.py::TestXLSXExtractor::test_extract_xlsx_skiprows", "tests/unit/test_extractor.py::TestXLSXExtractor::test_extract_xlsx_sheetname", "tests/unit/test_extractor.py::TestXLSXExtractor::test_raises_if_badly_named_file", "tests/unit/test_extractor.py::TestXLSExtractor::test_extract_xls", "tests/unit/test_extractor.py::TestXLSExtractor::test_extract_skiprows_xls", "tests/unit/test_extractor.py::TestXLSExtractor::test_init_datafram_xls_no_logging", "tests/unit/test_process.py::TestProcessInstanciation::test_default_instanciates", "tests/unit/test_process.py::TestProcessInstanciation::test_bad_type_args_fails", "tests/unit/test_process.py::TestProcessInstanciation::test_instance_from_bad_class_fails", "tests/unit/test_process.py::TestProcessInstanciation::test_good_args_instanciates", "tests/unit/test_process.py::TestProcessInstanciation::test_list_of_transformers_instanciates", "tests/unit/test_process.py::TestProcessInstanciation::test_list_of_uninstanced_transformers_fails", "tests/unit/test_process.py::TestProcessInstanciation::test_list_of_wrong_type_fails", "tests/unit/test_process.py::TestProcessMethods::test_transform_instanced_no_args", "tests/unit/test_process.py::TestProcessMethods::test_transform_multiple_transformers_extra_args", "tests/unit/test_process.py::TestProcessMethods::test_load_class_loader_fails_if_no_valid_es_instance_is_passed", "tests/unit/test_process.py::TestProcessMethods::test_load_instanced_loader_extra_args_warns", "tests/unit/test_process.py::TestProcessMethods::test_load_instanced_does_not_warn", "tests/unit/test_process.py::TestProcessMethods::test_bulk_with_indice_to_list_format", "tests/unit/test_process.py::TestProcessMethods::test_single_bulk_with_file_indice_format", "tests/unit/test_process.py::TestProcessMethods::test_multiple_bulk_with_file_indice_format", "tests/unit/test_transformer.py::TestTransformer::test_format_str_columns_warns_if_column_missing", "tests/unit/test_transformer.py::TestTransformer::test_format_dates_warns_if_date_format_omitted", "tests/unit/test_transformer.py::TestTransformer::test_format_dates_warns_if_columns_omitted", "tests/unit/test_transformer.py::TestTransformer::test_merge_referential_passing_dataframe", "tests/unit/test_transformer.py::TestTransformer::test_merge_ref_passing_instanced_extractor", "tests/unit/test_transformer.py::TestTransformer::test_merge_ref_crashes_if_extractor_param_not_a_valid_extractor_instance", "tests/unit/test_transformer.py::TestTransformer::test_merge_ref_crashes_if_ref_is_not_path_nor_str", "tests/unit/test_transformer.py::TestTransformer::test_merge_ref_with_default_extractor", "tests/unit/test_transformer.py::TestAtomicTransformers::test_column_stripper", "tests/unit/test_transformer.py::TestAtomicTransformers::test_column_replacer", "tests/unit/test_transformer.py::TestAtomicTransformers::test_content_replacer", "tests/unit/test_transformer.py::TestAtomicTransformers::test_column_capitaliser", "tests/unit/test_transformer.py::TestAtomicTransformers::test_null_values_replacer", "tests/unit/test_transformer.py::TestAtomicTransformers::test_date_parser", "tests/unit/test_transformer.py::TestAtomicTransformers::test_date_formatter", "tests/unit/test_transformer.py::TestAtomicTransformers::test_date_formatter_raises_if_non_datetimes_in_column", "tests/unit/test_transformer.py::TestColumnContentStripper::test_column_content_stripping", "tests/unit/test_transformer.py::TestColumnContentStripper::test_warns_if_column_not_in_df", "tests/unit/test_transformer.py::TestColumnContentStripper::test_warns_if_column_not_strings", "tests/unit/test_transformer.py::TestMerger::test_merge_with_self", "tests/unit/test_unit_process.py::TestWarnings::test_instanced_transformer_warns_if_addition_params_are_passed", "tests/unit/test_unit_process.py::TestWarnings::test_instanced_loader_warns_if_addition_params_are_passed", "tests/unit/test_unit_process.py::TestParameters::test_extractor_calls_init_dataframe_with_extract_parameters", "tests/unit/test_unit_process.py::TestBulk::test_bulk_crashes_if_transformer_not_instanced", "tests/unit/test_unit_process.py::TestBulk::test_bulk_crashes_if_loader_not_instanced", "tests/unit/test_unit_process.py::TestBulk::test_bulk_crashes_if_both_not_instanced" ]
[ "tests/unit/test_process.py::TestProcessMethods::test_load_class_loader_passes_if_valid_es_instance_is_passed" ]
[]
[]
null
null
null
15five__scim2-filter-parser-13
3ed1858b492542d0bc9b9e9ab9547641595e28c1
2020-07-30 14:25:04
c794bf3e50e3cb71bdcf919feb43d11912907dd2
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 12a5d4f..178f172 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,10 @@ CHANGE LOG ========== +0.3.5 +----- +- Update the sql.Transpiler to collect namedtuples rather than tuples for attr paths + 0.3.4 ----- - Update tox.ini and clean up linting errors diff --git a/setup.py b/setup.py index bbf57bf..bd16f70 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ def long_description(): setup( name='scim2-filter-parser', - version='0.3.4', + version='0.3.5', description='A customizable parser/transpiler for SCIM2.0 filters', url='https://github.com/15five/scim2-filter-parser', maintainer='Paul Logston', diff --git a/src/scim2_filter_parser/transpilers/sql.py b/src/scim2_filter_parser/transpilers/sql.py index 6254f1e..2107758 100644 --- a/src/scim2_filter_parser/transpilers/sql.py +++ b/src/scim2_filter_parser/transpilers/sql.py @@ -4,9 +4,12 @@ clause based on a SCIM filter. """ import ast import string +import collections from .. import ast as scim2ast +AttrPath = collections.namedtuple('AttrPath', ['attr_name', 'sub_attr', 'uri']) + class Transpiler(ast.NodeTransformer): """ @@ -145,7 +148,7 @@ class Transpiler(ast.NodeTransformer): # Convert attr_name to another value based on map. # Otherwise, return None. - attr_path_tuple = (attr_name_value, sub_attr_value, uri_value) + attr_path_tuple = AttrPath(attr_name_value, sub_attr_value, uri_value) self.attr_paths.append(attr_path_tuple) return self.attr_map.get(attr_path_tuple)
Return NamedTuple rather than tuple. It would be nice to return a NamedTuple instead of a tuple here: https://github.com/15five/scim2-filter-parser/blob/7ddc216f8c3dd1cdb2152944187e8f7f5ee07be2/src/scim2_filter_parser/transpilers/sql.py#L148 This way parts of each path could be accessed by name rather than by index in the tuple.
15five/scim2-filter-parser
diff --git a/tests/test_transpiler.py b/tests/test_transpiler.py index b8e1bb4..280c2d3 100644 --- a/tests/test_transpiler.py +++ b/tests/test_transpiler.py @@ -36,6 +36,16 @@ class RFCExamples(TestCase): self.assertEqual(expected_sql, sql, query) self.assertEqual(expected_params, params, query) + def test_attr_paths_are_created(self): + query = 'userName eq "bjensen"' + tokens = self.lexer.tokenize(query) + ast = self.parser.parse(tokens) + self.transpiler.transpile(ast) + + self.assertEqual(len(self.transpiler.attr_paths), 1) + for path in self.transpiler.attr_paths: + self.assertTrue(isinstance(path, transpile_sql.AttrPath)) + def test_username_eq(self): query = 'userName eq "bjensen"' sql = "username = {a}"
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.7", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asgiref==3.7.2 attrs @ file:///croot/attrs_1668696182826/work certifi @ file:///croot/certifi_1671487769961/work/certifi Django==3.2.25 flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1671697413597/work pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pytest==7.1.2 pytz==2025.2 -e git+https://github.com/15five/scim2-filter-parser.git@3ed1858b492542d0bc9b9e9ab9547641595e28c1#egg=scim2_filter_parser sly==0.3 sqlparse==0.4.4 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typing_extensions @ file:///croot/typing_extensions_1669924550328/work zipp @ file:///croot/zipp_1672387121353/work
name: scim2-filter-parser channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=22.1.0=py37h06a4308_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - flit-core=3.6.0=pyhd3eb1b0_0 - importlib-metadata=4.11.3=py37h06a4308_0 - importlib_metadata=4.11.3=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=22.0=py37h06a4308_0 - pip=22.3.1=py37h06a4308_0 - pluggy=1.0.0=py37h06a4308_1 - py=1.11.0=pyhd3eb1b0_0 - pytest=7.1.2=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py37h06a4308_0 - typing_extensions=4.4.0=py37h06a4308_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.11.0=py37h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - asgiref==3.7.2 - django==3.2.25 - pytz==2025.2 - sly==0.3 - sqlparse==0.4.4 prefix: /opt/conda/envs/scim2-filter-parser
[ "tests/test_transpiler.py::RFCExamples::test_attr_paths_are_created" ]
[]
[ "tests/test_transpiler.py::RFCExamples::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians", "tests/test_transpiler.py::RFCExamples::test_family_name_contains", "tests/test_transpiler.py::RFCExamples::test_meta_last_modified_ge", "tests/test_transpiler.py::RFCExamples::test_meta_last_modified_gt", "tests/test_transpiler.py::RFCExamples::test_meta_last_modified_le", "tests/test_transpiler.py::RFCExamples::test_meta_last_modified_lt", "tests/test_transpiler.py::RFCExamples::test_schema_username_startswith", "tests/test_transpiler.py::RFCExamples::test_schemas_eq", "tests/test_transpiler.py::RFCExamples::test_title_has_value", "tests/test_transpiler.py::RFCExamples::test_title_has_value_and_user_type_eq", "tests/test_transpiler.py::RFCExamples::test_title_has_value_or_user_type_eq", "tests/test_transpiler.py::RFCExamples::test_user_type_eq_and_email_contains_or_email_contains", "tests/test_transpiler.py::RFCExamples::test_user_type_eq_and_not_email_type_eq", "tests/test_transpiler.py::RFCExamples::test_user_type_eq_and_not_email_type_eq_work_and_value_contains", "tests/test_transpiler.py::RFCExamples::test_user_type_ne_and_not_email_contains_or_email_contains", "tests/test_transpiler.py::RFCExamples::test_username_eq", "tests/test_transpiler.py::RFCExamples::test_username_startswith", "tests/test_transpiler.py::UndefinedAttributes::test_email_type_eq_primary_value_eq_uuid_1", "tests/test_transpiler.py::UndefinedAttributes::test_email_type_eq_primary_value_eq_uuid_2", "tests/test_transpiler.py::UndefinedAttributes::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_1", "tests/test_transpiler.py::UndefinedAttributes::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_2", "tests/test_transpiler.py::UndefinedAttributes::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_3", "tests/test_transpiler.py::UndefinedAttributes::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_4", "tests/test_transpiler.py::UndefinedAttributes::test_schemas_eq", "tests/test_transpiler.py::UndefinedAttributes::test_title_has_value_and_user_type_eq_1", "tests/test_transpiler.py::UndefinedAttributes::test_title_has_value_and_user_type_eq_2", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_email_contains_or_email_contains", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_1", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_2", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_work_and_value_contains_1", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_work_and_value_contains_2", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_work_and_value_contains_3", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_ne_and_not_email_contains_or_email_contains", "tests/test_transpiler.py::UndefinedAttributes::test_username_eq", "tests/test_transpiler.py::AzureQueries::test_email_type_eq_primary_value_eq_uuid", "tests/test_transpiler.py::AzureQueries::test_external_id_from_azure", "tests/test_transpiler.py::AzureQueries::test_parse_simple_email_filter_with_uuid", "tests/test_transpiler.py::CommandLine::test_command_line" ]
[]
MIT License
swerebench/sweb.eval.x86_64.15five_1776_scim2-filter-parser-13
swerebench/sweb.eval.x86_64.15five_1776_scim2-filter-parser-13
15five__scim2-filter-parser-20
08de23c5626556a37beced764a22a2fa7021989b
2020-10-18 03:21:13
c794bf3e50e3cb71bdcf919feb43d11912907dd2
diff --git a/src/scim2_filter_parser/parser.py b/src/scim2_filter_parser/parser.py index 516f65d..12c693e 100644 --- a/src/scim2_filter_parser/parser.py +++ b/src/scim2_filter_parser/parser.py @@ -110,9 +110,8 @@ class SCIMParser(Parser): # which takes precedence over "or" # 3. Attribute operators precedence = ( - ('nonassoc', OR), # noqa F821 - ('nonassoc', AND), # noqa F821 - ('nonassoc', NOT), # noqa F821 + ('left', OR, AND), # noqa F821 + ('right', NOT), # noqa F821 ) # FILTER = attrExp / logExp / valuePath / *1"not" "(" FILTER ")"
Issue when using multiple "or" or "and" Hi, I am facing an issue, where the query having two or more "and" or more than two "or" is failing. Have a look at examples below: - 1)```"displayName co \"username\" or nickName co \"username\" or userName co \"username\""``` ```"displayName co \"username\" and nickName co \"username\" and userName co \"username\""``` the two queries fails giving , ```scim2_filter_parser.parser.SCIMParserError: Parsing error at: Token(type='OR', value='or', lineno=1, index=52)``` notice above queries are having either only "or" or "and". 2)```"displayName co \"username\" and nickName co \"username\" or userName co \"username\""``` but this query works.
15five/scim2-filter-parser
diff --git a/tests/test_parser.py b/tests/test_parser.py index 4ff562c..19aa198 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -47,6 +47,24 @@ class BuggyQueries(TestCase): with self.assertRaises(parser.SCIMParserError): self.parser.parse(token_stream) + def test_g17_1_log_exp_order(self): + query = 'displayName co "username" or nickName co "username" or userName co "username"' + + tokens = self.lexer.tokenize(query) + self.parser.parse(tokens) # Should not raise error + + def test_g17_2_log_exp_order(self): + query = 'displayName co "username" and nickName co "username" and userName co "username"' + + tokens = self.lexer.tokenize(query) + self.parser.parse(tokens) # Should not raise error + + def test_g17_3_log_exp_order(self): + query = 'displayName co "username" and nickName co "username" or userName co "username"' + + tokens = self.lexer.tokenize(query) + self.parser.parse(tokens) # Should not raise error + class CommandLine(TestCase): def setUp(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[django-query]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.7", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 asgiref==3.7.2 Babel==2.14.0 certifi @ file:///croot/certifi_1671487769961/work/certifi charset-normalizer==3.4.1 Django==3.2.25 docutils==0.19 exceptiongroup==1.2.2 idna==3.10 imagesize==1.4.1 importlib-metadata==6.7.0 iniconfig==2.0.0 Jinja2==3.1.6 MarkupSafe==2.1.5 packaging==24.0 pluggy==1.2.0 Pygments==2.17.2 pytest==7.4.4 pytz==2025.2 requests==2.31.0 -e git+https://github.com/15five/scim2-filter-parser.git@08de23c5626556a37beced764a22a2fa7021989b#egg=scim2_filter_parser sly==0.4 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 sqlparse==0.4.4 tomli==2.0.1 typing_extensions==4.7.1 urllib3==2.0.7 zipp==3.15.0
name: scim2-filter-parser channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - asgiref==3.7.2 - babel==2.14.0 - charset-normalizer==3.4.1 - django==3.2.25 - docutils==0.19 - exceptiongroup==1.2.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - jinja2==3.1.6 - markupsafe==2.1.5 - packaging==24.0 - pluggy==1.2.0 - pygments==2.17.2 - pytest==7.4.4 - pytz==2025.2 - requests==2.31.0 - sly==0.4 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlparse==0.4.4 - tomli==2.0.1 - typing-extensions==4.7.1 - urllib3==2.0.7 - zipp==3.15.0 prefix: /opt/conda/envs/scim2-filter-parser
[ "tests/test_parser.py::BuggyQueries::test_g17_1_log_exp_order", "tests/test_parser.py::BuggyQueries::test_g17_2_log_exp_order" ]
[]
[ "tests/test_parser.py::RegressionTestQueries::test_command_line", "tests/test_parser.py::BuggyQueries::test_g17_3_log_exp_order", "tests/test_parser.py::BuggyQueries::test_no_quotes_around_comp_value", "tests/test_parser.py::CommandLine::test_command_line" ]
[]
MIT License
swerebench/sweb.eval.x86_64.15five_1776_scim2-filter-parser-20
swerebench/sweb.eval.x86_64.15five_1776_scim2-filter-parser-20
15five__scim2-filter-parser-31
c794bf3e50e3cb71bdcf919feb43d11912907dd2
2022-07-09 01:20:42
c794bf3e50e3cb71bdcf919feb43d11912907dd2
logston: Hey @powellc, if you have the time, can you give this a rigorous review? It changes core logic in a pretty large way. I'd like to make sure my assumptions are sound and my changes are worth the costs. andersk: When converting a string to a `LIKE` or `ILIKE` pattern, it’s necessary to escape `%`, `_`, and `\` as `\%`, `\_`, and `\\`. This doesn’t seem to do that. ```console $ python3 -m scim2_filter_parser.transpilers.sql \ 'userType eq "a%b_c\\d" and userName co "a%b_c\\d"' SQL: (usertype = {a}) AND (username ILIKE {b}) PARAMS: {'a': 'a%b_c\\\\d', 'b': '%a%b_c\\\\d%'} ``` Expected: ```console SQL: (usertype = {a}) AND (username ILIKE {b}) PARAMS: {'a': 'a%b_c\\d', 'b': '%a\\%b\\_c\\\\d%'} ``` This may be a separate bug, but this will increase its impact by transpiling more queries to `ILIKE`. andersk: Oh…I guess there’s also a question of which databases this needs to be compatible with? `ILIKE` works in PostgreSQL but not MySQL or SQLite. logston: Right, good points. As anticipated, this is trickier than this quick patch lets on. Another solution that was suggested was to uppercase strings before comparison. eg. `UPPER`. I'll need to check if that's available in all major SQL engines.
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 14f28e6..35eb5c5 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,5 +1,12 @@ CHANGE LOG ========== +0.4.0 +----- +- Update userName to be case insensitive. #31 + +BREAKING CHANGE: This allows queries that did not match rows before to +match rows now! + 0.3.9 ----- diff --git a/setup.py b/setup.py index fa62e03..c46c582 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ def long_description(): setup( name='scim2-filter-parser', - version='0.3.9', + version='0.4.0', description='A customizable parser/transpiler for SCIM2.0 filters', url='https://github.com/15five/scim2-filter-parser', maintainer='Paul Logston', diff --git a/src/scim2_filter_parser/ast.py b/src/scim2_filter_parser/ast.py index b019f01..28de65e 100644 --- a/src/scim2_filter_parser/ast.py +++ b/src/scim2_filter_parser/ast.py @@ -95,6 +95,12 @@ class AttrPath(AST): sub_attr : (SubAttr, type(None)) # noqa: E203 uri : (str, type(None)) # noqa: E203 + @property + def case_insensitive(self): + # userName is always case-insensitive + # https://datatracker.ietf.org/doc/html/rfc7643#section-4.1.1 + return self.attr_name == 'userName' + class CompValue(AST): value : str # noqa: E203 @@ -105,6 +111,10 @@ class AttrExpr(AST): attr_path : AttrPath # noqa: E203 comp_value : CompValue # noqa: E203 + @property + def case_insensitive(self): + return self.attr_path.case_insensitive + # The following classes for visiting and rewriting the AST are taken # from Python's ast module. It's really easy to make mistakes when diff --git a/src/scim2_filter_parser/transpilers/django_q_object.py b/src/scim2_filter_parser/transpilers/django_q_object.py index def4633..5ef90b2 100644 --- a/src/scim2_filter_parser/transpilers/django_q_object.py +++ b/src/scim2_filter_parser/transpilers/django_q_object.py @@ -139,13 +139,13 @@ class Transpiler(ast.NodeTransformer): partial = partial.replace(".", "__") if full and partial: # Specific to Azure - op, value = self.visit_AttrExprValue(node.value, node.comp_value) + op, value = self.visit_AttrExprValue(node) key = partial + "__" + op return full & Q(**{key: value}) elif full: return full elif partial: - op, value = self.visit_AttrExprValue(node.value, node.comp_value) + op, value = self.visit_AttrExprValue(node) key = partial + "__" + op return Q(**{key: value}) else: @@ -159,20 +159,20 @@ class Transpiler(ast.NodeTransformer): return None if "." in attr: attr = attr.replace(".", "__") - op, value = self.visit_AttrExprValue(node.value, node.comp_value) + op, value = self.visit_AttrExprValue(node) key = attr + "__" + op query = Q(**{key: value}) if node.value == "ne": query = ~query return query - def visit_AttrExprValue(self, node_value, node_comp_value): - op = self.lookup_op(node_value) + def visit_AttrExprValue(self, node): + op = self.lookup_op(node.value) - if node_comp_value: + if node.comp_value: # There is a comp_value, so visit node and build SQL. # prep item_id to be a str replacement placeholder - value = self.visit(node_comp_value) + value = self.visit(node.comp_value) else: value = None diff --git a/src/scim2_filter_parser/transpilers/sql.py b/src/scim2_filter_parser/transpilers/sql.py index 0c3fba4..7128edb 100644 --- a/src/scim2_filter_parser/transpilers/sql.py +++ b/src/scim2_filter_parser/transpilers/sql.py @@ -112,28 +112,38 @@ class Transpiler(ast.NodeTransformer): if isinstance(node.attr_path.attr_name, scim2ast.Filter): full, partial = self.visit_PartialAttrExpr(node.attr_path.attr_name) if full and partial: - value = self.visit_AttrExprValue(node.value, node.comp_value) + value = self.visit_AttrExprValue(node) return f'({full} AND {partial} {value})' elif full: return full elif partial: - value = self.visit_AttrExprValue(node.value, node.comp_value) + value = self.visit_AttrExprValue(node) return f'{partial} {value}' else: return None else: + # Case-insensitivity only needs to be checked in this branch + # because userName is currently the only attribute that can be case + # insensitive and userName can not be a nested part of a complex query (eg. + # emails.type in emails[type eq "Primary"]...). + # https://datatracker.ietf.org/doc/html/rfc7643#section-4.1.1 attr = self.visit(node.attr_path) if attr is None: return None - value = self.visit_AttrExprValue(node.value, node.comp_value) + + value = self.visit_AttrExprValue(node) + + if node.case_insensitive: + return f'UPPER({attr}) {value}' + return f'{attr} {value}' - def visit_AttrExprValue(self, node_value, node_comp_value): - op_sql = self.lookup_op(node_value) + def visit_AttrExprValue(self, node): + op_sql = self.lookup_op(node.value) item_id = self.get_next_id() - if not node_comp_value: + if not node.comp_value: self.params[item_id] = None return op_sql @@ -142,15 +152,19 @@ class Transpiler(ast.NodeTransformer): # prep item_id to be a str replacement placeholder item_id_placeholder = '{' + item_id + '}' - if 'LIKE' == op_sql: + if node.value.lower() in self.matching_op_by_scim_op.keys(): # Add appropriate % signs to values in LIKE clause - prefix, suffix = self.lookup_like_matching(node_value) - value = prefix + self.visit(node_comp_value) + suffix + prefix, suffix = self.lookup_like_matching(node.value) + value = prefix + self.visit(node.comp_value) + suffix + else: - value = self.visit(node_comp_value) + value = self.visit(node.comp_value) self.params[item_id] = value + if node.case_insensitive: + return f'{op_sql} UPPER({item_id_placeholder})' + return f'{op_sql} {item_id_placeholder}' def visit_AttrPath(self, node):
userName attribute should be case-insensitive, per the RFC From https://github.com/15five/django-scim2/issues/76 > See https://datatracker.ietf.org/doc/html/rfc7643#section-4.1.1: (userName) > This attribute is REQUIRED and is case insensitive. > Currently this case-insensitive behavior is not implemented and the filter lookups are case-sensitive.
15five/scim2-filter-parser
diff --git a/tests/test_query.py b/tests/test_query.py index ee4161d..7cd9595 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -16,6 +16,7 @@ class RFCExamples(unittest.TestCase): username TEXT, first_name TEXT, last_name TEXT, + nickname TEXT, title TEXT, update_ts DATETIME, user_type TEXT @@ -24,17 +25,17 @@ class RFCExamples(unittest.TestCase): INSERT_USERS = ''' INSERT INTO users - (id, username, first_name, last_name, title, update_ts, user_type) + (id, username, first_name, last_name, nickname, title, update_ts, user_type) VALUES - (1, 'bjensen', 'Brie', 'Jensen', NULL, NULL, NULL), - (2, 'momalley', 'Mike', 'O''Malley', NULL, NULL, NULL), - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', NULL, 'Employee'), - (4, 'crobertson', 'Carly', 'Robertson', NULL, NULL, 'Intern'), - - (5, 'gt', 'Gina', 'Taylor', NULL, '2012-05-13T04:42:34Z', NULL), - (6, 'ge', 'Greg', 'Edgar', NULL, '2011-05-13T04:42:34Z', NULL), - (7, 'lt', 'Lisa', 'Ting', NULL, '2010-05-13T04:42:34Z', NULL), - (8, 'le', 'Linda', 'Euler', NULL, '2011-05-13T04:42:34Z', NULL) + (1, 'bjensen', 'Brie', 'Jensen', 'BB', NULL, NULL, NULL), + (2, 'momalley', 'Mike', 'O''Malley', NULL, NULL, NULL, NULL), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', NULL, 'Employee'), + (4, 'crobertson', 'Carly', 'Robertson', NULL, NULL, NULL, 'Intern'), + + (5, 'gt', 'Gina', 'Taylor', NULL, NULL, '2012-05-13T04:42:34Z', NULL), + (6, 'ge', 'Greg', 'Edgar', NULL, NULL, '2011-05-13T04:42:34Z', NULL), + (7, 'lt', 'Lisa', 'Ting', NULL, NULL, '2010-05-13T04:42:34Z', NULL), + (8, 'le', 'Linda', 'Euler', NULL, NULL, '2011-05-13T04:42:34Z', NULL) ''' CREATE_TABLE_EMAILS = ''' @@ -95,6 +96,7 @@ class RFCExamples(unittest.TestCase): # attr_name, sub_attr, uri: table name ('title', None, None): 'users.title', ('userName', None, None): 'users.username', + ('nickName', None, None): 'users.nickname', ('userType', None, None): 'users.user_type', ('name', 'familyName', None): 'users.last_name', ('meta', 'lastModified', None): 'users.update_ts', @@ -105,6 +107,7 @@ class RFCExamples(unittest.TestCase): ('ims', 'type', None): 'ims.type', ('schemas', None, None): 'schemas.text', ('userName', None, 'urn:ietf:params:scim:schemas:core:2.0:User'): 'username', + ('nickName', None, 'urn:ietf:params:scim:schemas:core:2.0:User'): 'nickname', } JOINS = ( @@ -133,120 +136,120 @@ class RFCExamples(unittest.TestCase): self.assertEqual(expected_rows, results) - def test_username_eq(self): - query = 'userName eq "bjensen"' + def test_nickname_eq(self): + query = 'nickName eq "BB"' expected_rows = [ - (1, 'bjensen', 'Brie', 'Jensen', None, None, None) + (1, 'bjensen', 'Brie', 'Jensen', 'BB', None, None, None) ] self.assertRows(query, expected_rows) def test_family_name_contains(self): query = '''name.familyName co "O'Malley"''' expected_rows = [ - (2, 'momalley', 'Mike', "O'Malley", None, None, None), + (2, 'momalley', 'Mike', "O'Malley", None, None, None, None), ] self.assertRows(query, expected_rows) - def test_username_startswith(self): - query = 'userName sw "J"' + def test_nickname_startswith(self): + query = 'nickName sw "J"' expected_rows = [ - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), ] self.assertRows(query, expected_rows) def test_schema_username_startswith(self): - query = 'urn:ietf:params:scim:schemas:core:2.0:User:userName sw "J"' + query = 'urn:ietf:params:scim:schemas:core:2.0:User:nickName sw "J"' expected_rows = [ - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), ] self.assertRows(query, expected_rows) def test_title_has_value(self): query = 'title pr' expected_rows = [ - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), ] self.assertRows(query, expected_rows) def test_meta_last_modified_gt(self): query = 'meta.lastModified gt "2011-05-13T04:42:34Z"' expected_rows = [ - (5, 'gt', 'Gina', 'Taylor', None, '2012-05-13T04:42:34Z', None), + (5, 'gt', 'Gina', 'Taylor', None, None, '2012-05-13T04:42:34Z', None), ] self.assertRows(query, expected_rows) def test_meta_last_modified_ge(self): query = 'meta.lastModified ge "2011-05-13T04:42:34Z"' expected_rows = [ - (5, 'gt', 'Gina', 'Taylor', None, '2012-05-13T04:42:34Z', None), - (6, 'ge', 'Greg', 'Edgar', None, '2011-05-13T04:42:34Z', None), - (8, 'le', 'Linda', 'Euler', None, '2011-05-13T04:42:34Z', None) + (5, 'gt', 'Gina', 'Taylor', None, None, '2012-05-13T04:42:34Z', None), + (6, 'ge', 'Greg', 'Edgar', None, None, '2011-05-13T04:42:34Z', None), + (8, 'le', 'Linda', 'Euler', None, None, '2011-05-13T04:42:34Z', None) ] self.assertRows(query, expected_rows) def test_meta_last_modified_lt(self): query = 'meta.lastModified lt "2011-05-13T04:42:34Z"' expected_rows = [ - (7, 'lt', 'Lisa', 'Ting', None, '2010-05-13T04:42:34Z', None), + (7, 'lt', 'Lisa', 'Ting', None, None, '2010-05-13T04:42:34Z', None), ] self.assertRows(query, expected_rows) def test_meta_last_modified_le(self): query = 'meta.lastModified le "2011-05-13T04:42:34Z"' expected_rows = [ - (6, 'ge', 'Greg', 'Edgar', None, '2011-05-13T04:42:34Z', None), - (7, 'lt', 'Lisa', 'Ting', None, '2010-05-13T04:42:34Z', None), - (8, 'le', 'Linda', 'Euler', None, '2011-05-13T04:42:34Z', None) + (6, 'ge', 'Greg', 'Edgar', None, None, '2011-05-13T04:42:34Z', None), + (7, 'lt', 'Lisa', 'Ting', None, None, '2010-05-13T04:42:34Z', None), + (8, 'le', 'Linda', 'Euler', None, None, '2011-05-13T04:42:34Z', None) ] self.assertRows(query, expected_rows) def test_title_has_value_and_user_type_eq(self): query = 'title pr and userType eq "Employee"' expected_rows = [ - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), ] self.assertRows(query, expected_rows) def test_title_has_value_or_user_type_eq(self): query = 'title pr or userType eq "Intern"' expected_rows = [ - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), - (4, 'crobertson', 'Carly', 'Robertson', None, None, 'Intern'), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), + (4, 'crobertson', 'Carly', 'Robertson', None, None, None, 'Intern'), ] self.assertRows(query, expected_rows) def test_schemas_eq(self): query = 'schemas eq "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"' expected_rows = [ - (4, 'crobertson', 'Carly', 'Robertson', None, None, 'Intern'), + (4, 'crobertson', 'Carly', 'Robertson', None, None, None, 'Intern'), ] self.assertRows(query, expected_rows) def test_user_type_eq_and_email_contains_or_email_contains(self): query = 'userType eq "Employee" and (emails co "example.com" or emails.value co "example.org")' expected_rows = [ - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), ] self.assertRows(query, expected_rows) def test_user_type_ne_and_not_email_contains_or_email_contains(self): query = 'userType ne "Employee" and not (emails co "example.com" or emails.value co "example.org")' expected_rows = [ - (4, 'crobertson', 'Carly', 'Robertson', None, None, 'Intern'), + (4, 'crobertson', 'Carly', 'Robertson', None, None, None, 'Intern'), ] self.assertRows(query, expected_rows) def test_user_type_eq_and_not_email_type_eq(self): query = 'userType eq "Employee" and (emails.type eq "work")' expected_rows = [ - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), ] self.assertRows(query, expected_rows) def test_user_type_eq_and_not_email_type_eq_work_and_value_contains(self): query = 'userType eq "Employee" and emails[type eq "work" and value co "@example.com"]' expected_rows = [ - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), ] self.assertRows(query, expected_rows) @@ -254,8 +257,8 @@ class RFCExamples(unittest.TestCase): query = ('emails[type eq "work" and value co "@example.com"] or ' 'ims[type eq "xmpp" and value co "@foo.com"]') expected_rows = [ - (1, 'bjensen', 'Brie', 'Jensen', None, None, None), - (3, 'Jacob', 'Jacob', 'Jingleheimer', 'Friend', None, 'Employee'), + (1, 'bjensen', 'Brie', 'Jensen', 'BB', None, None, None), + (3, 'Jacob', 'Jacob', 'Jingleheimer', 'JJ', 'Friend', None, 'Employee'), ] self.assertRows(query, expected_rows) @@ -441,7 +444,7 @@ class CommandLine(unittest.TestCase): ' FROM users', ' LEFT JOIN emails ON emails.user_id = users.id', ' LEFT JOIN schemas ON schemas.user_id = users.id', - ' WHERE username = bjensen;' + ' WHERE UPPER(username) = UPPER(bjensen);' ] self.assertEqual(result, expected) diff --git a/tests/test_transpiler.py b/tests/test_transpiler.py index 2198cde..dfaf562 100644 --- a/tests/test_transpiler.py +++ b/tests/test_transpiler.py @@ -6,52 +6,72 @@ from scim2_filter_parser.lexer import SCIMLexer from scim2_filter_parser.parser import SCIMParser import scim2_filter_parser.transpilers.sql as transpile_sql +class SetupHelper(TestCase): + attr_map = None -class RFCExamples(TestCase): + def setUp(self): + self.lexer = SCIMLexer() + self.parser = SCIMParser() + + def assertSQL(self, query, expected_sql, expected_params, attr_map=None): + tokens = self.lexer.tokenize(query) + ast = self.parser.parse(tokens) + + if attr_map is None: + attr_map = self.attr_map + + transpiler = transpile_sql.Transpiler(attr_map) + + sql, params = transpiler.transpile(ast) + + self.assertEqual(expected_sql, sql, query) + self.assertEqual(expected_params, params, query) + + +class RFCExamples(SetupHelper, TestCase): attr_map = { ('name', 'familyName', None): 'name.familyname', ('emails', None, None): 'emails', ('emails', 'type', None): 'emails.type', ('emails', 'value', None): 'emails.value', ('userName', None, None): 'username', + ('nickName', None, None): 'nickname', ('title', None, None): 'title', ('userType', None, None): 'usertype', ('schemas', None, None): 'schemas', ('userName', None, 'urn:ietf:params:scim:schemas:core:2.0:User'): 'username', + ('nickName', None, 'urn:ietf:params:scim:schemas:core:2.0:User'): 'nickname', ('meta', 'lastModified', None): 'meta.lastmodified', ('ims', 'type', None): 'ims.type', ('ims', 'value', None): 'ims.value', } - def setUp(self): - self.lexer = SCIMLexer() - self.parser = SCIMParser() - self.transpiler = transpile_sql.Transpiler(self.attr_map) - - def assertSQL(self, query, expected_sql, expected_params): - tokens = self.lexer.tokenize(query) - ast = self.parser.parse(tokens) - sql, params = self.transpiler.transpile(ast) - - self.assertEqual(expected_sql, sql, query) - self.assertEqual(expected_params, params, query) - def test_attr_paths_are_created(self): query = 'userName eq "bjensen"' tokens = self.lexer.tokenize(query) ast = self.parser.parse(tokens) - self.transpiler.transpile(ast) - self.assertEqual(len(self.transpiler.attr_paths), 1) - for path in self.transpiler.attr_paths: + transpiler = transpile_sql.Transpiler(self.attr_map) + transpiler.transpile(ast) + + self.assertEqual(len(transpiler.attr_paths), 1) + for path in transpiler.attr_paths: self.assertTrue(isinstance(path, transpile_sql.AttrPath)) + # userName is always case-insensitive + # https://datatracker.ietf.org/doc/html/rfc7643#section-4.1.1 def test_username_eq(self): query = 'userName eq "bjensen"' - sql = "username = {a}" + sql = "UPPER(username) = UPPER({a})" params = {'a': 'bjensen'} self.assertSQL(query, sql, params) + def test_nickname_eq(self): + query = 'nickName eq "Bob"' + sql = "nickname = {a}" + params = {'a': 'Bob'} + self.assertSQL(query, sql, params) + def test_family_name_contains(self): query = '''name.familyName co "O'Malley"''' sql = "name.familyname LIKE {a}" @@ -60,13 +80,25 @@ class RFCExamples(TestCase): def test_username_startswith(self): query = 'userName sw "J"' - sql = "username LIKE {a}" + sql = "UPPER(username) LIKE UPPER({a})" + params = {'a': 'J%'} + self.assertSQL(query, sql, params) + + def test_nickname_startswith(self): + query = 'nickName sw "J"' + sql = "nickname LIKE {a}" params = {'a': 'J%'} self.assertSQL(query, sql, params) def test_schema_username_startswith(self): query = 'urn:ietf:params:scim:schemas:core:2.0:User:userName sw "J"' - sql = "username LIKE {a}" + sql = "UPPER(username) LIKE UPPER({a})" + params = {'a': 'J%'} + self.assertSQL(query, sql, params) + + def test_schema_nickname_startswith(self): + query = 'urn:ietf:params:scim:schemas:core:2.0:User:nickName sw "J"' + sql = "nickname LIKE {a}" params = {'a': 'J%'} self.assertSQL(query, sql, params) @@ -149,27 +181,35 @@ class RFCExamples(TestCase): params = {'a': 'work', 'b': '%@example.com%', 'c': 'xmpp', 'd': '%@foo.com%'} self.assertSQL(query, sql, params) + def test_username_with_more_complex_query(self): + query = ( + 'emails[type eq "work" and value co "@example.com"] or ' + 'ims[type eq "xmpp" and value co "@foo.com"] or ' + 'userName eq "bjensen"' + ) + sql = ( + '(((emails.type = {a}) AND (emails.value LIKE {b})) OR ' + '((ims.type = {c}) AND (ims.value LIKE {d}))) OR ' + '(UPPER(username) = UPPER({e}))' + ) + params = { + 'a': 'work', + 'b': '%@example.com%', + 'c': 'xmpp', + 'd': '%@foo.com%', + 'e': 'bjensen', + } + self.assertSQL(query, sql, params) -class UndefinedAttributes(TestCase): - - def setUp(self): - self.lexer = SCIMLexer() - self.parser = SCIMParser() - - def assertSQL(self, query, attr_map, expected_sql, expected_params): - tokens = self.lexer.tokenize(query) - ast = self.parser.parse(tokens) - sql, params = transpile_sql.Transpiler(attr_map).transpile(ast) - self.assertEqual(expected_sql, sql, query) - self.assertEqual(expected_params, params, query) +class UndefinedAttributes(SetupHelper, TestCase): def test_username_eq(self): query = 'userName eq "bjensen"' sql = None params = {} attr_map = {} - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_title_has_value_and_user_type_eq_1(self): query = 'title pr and userType eq "Employee"' @@ -178,7 +218,7 @@ class UndefinedAttributes(TestCase): attr_map = { ('title', None, None): 'title', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_title_has_value_and_user_type_eq_2(self): query = 'title pr and userType eq "Employee"' @@ -187,14 +227,14 @@ class UndefinedAttributes(TestCase): attr_map = { ('userType', None, None): 'usertype', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_schemas_eq(self): query = 'schemas eq "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"' sql = None params = {} attr_map = {} - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_user_type_eq_and_email_contains_or_email_contains(self): query = 'userType eq "Employee" and (emails co "example.com" or emails.value co "example.org")' @@ -205,7 +245,7 @@ class UndefinedAttributes(TestCase): ('emails', None, None): 'emails', ('emails', 'value', None): 'emails.value', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_user_type_ne_and_not_email_contains_or_email_contains(self): query = 'userType ne "Employee" and not (emails co "example.com" or emails.value co "example.org")' @@ -216,7 +256,7 @@ class UndefinedAttributes(TestCase): ('emails', None, None): 'emails', ('emails', 'value', None): 'emails.value', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_user_type_eq_and_not_email_type_eq_1(self): query = 'userType eq "Employee" and (emails.type eq "work")' @@ -225,7 +265,7 @@ class UndefinedAttributes(TestCase): attr_map = { ('userType', None, None): 'usertype', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_user_type_eq_and_not_email_type_eq_2(self): query = 'userType eq "Employee" and (emails.type eq "work")' @@ -234,7 +274,7 @@ class UndefinedAttributes(TestCase): attr_map = { ('emails', 'type', None): 'emails.type', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_user_type_eq_and_not_email_type_eq_work_and_value_contains_1(self): query = 'userType eq "Employee" and emails[type eq "work" and value co "@example.com"]' @@ -243,7 +283,7 @@ class UndefinedAttributes(TestCase): attr_map = { ('userType', None, None): 'usertype', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_user_type_eq_and_not_email_type_eq_work_and_value_contains_2(self): query = 'userType eq "Employee" and emails[type eq "work" and value co "@example.com"]' @@ -252,7 +292,7 @@ class UndefinedAttributes(TestCase): attr_map = { ('emails', 'type', None): 'emails.type', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_user_type_eq_and_not_email_type_eq_work_and_value_contains_3(self): query = 'userType eq "Employee" and emails[type eq "work" and value co "@example.com"]' @@ -262,7 +302,7 @@ class UndefinedAttributes(TestCase): ('emails', 'type', None): 'emails.type', ('emails', 'value', None): 'emails.value', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_1(self): query = ('emails[type eq "work" and value co "@example.com"] or ' @@ -273,7 +313,7 @@ class UndefinedAttributes(TestCase): ('emails', 'value', None): 'emails.value', ('ims', 'type', None): 'ims.type', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_2(self): query = ('emails[type eq "work" and value co "@example.com"] or ' @@ -285,7 +325,7 @@ class UndefinedAttributes(TestCase): ('ims', 'type', None): 'ims.type', ('ims', 'value', None): 'ims.value', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_3(self): query = ('emails[type eq "work" and value co "@example.com"] or ' @@ -297,7 +337,7 @@ class UndefinedAttributes(TestCase): ('emails', 'type', None): 'emails.type', ('ims', 'type', None): 'ims.type', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_4(self): query = ('emails[type eq "work" and value co "@example.com"] or ' @@ -308,7 +348,7 @@ class UndefinedAttributes(TestCase): ('emails', 'type', None): 'emails.type', ('ims', 'value', None): 'ims.value', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_email_type_eq_primary_value_eq_uuid_1(self): query = 'emails[type eq "Primary"].value eq "001750ca-8202-47cd-b553-c63f4f245940"' @@ -317,7 +357,7 @@ class UndefinedAttributes(TestCase): attr_map = { ('emails', 'value', None): 'emails.value', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) def test_email_type_eq_primary_value_eq_uuid_2(self): query = 'emails[type eq "Primary"].value eq "001750ca-8202-47cd-b553-c63f4f245940"' @@ -326,29 +366,16 @@ class UndefinedAttributes(TestCase): attr_map = { ('emails', 'type', None): 'emails.type', } - self.assertSQL(query, attr_map, sql, params) + self.assertSQL(query, sql, params, attr_map) -class AzureQueries(TestCase): +class AzureQueries(SetupHelper, TestCase): attr_map = { ('emails', 'type', None): 'emails.type', ('emails', 'value', None): 'emails.value', ('externalId', None, None): 'externalid', } - def setUp(self): - self.lexer = SCIMLexer() - self.parser = SCIMParser() - self.transpiler = transpile_sql.Transpiler(self.attr_map) - - def assertSQL(self, query, expected_sql, expected_params): - tokens = self.lexer.tokenize(query) - ast = self.parser.parse(tokens) - sql, params = self.transpiler.transpile(ast) - - self.assertEqual(expected_sql, sql, query) - self.assertEqual(expected_params, params, query) - def test_email_type_eq_primary_value_eq_uuid(self): query = 'emails[type eq "Primary"].value eq "001750ca-8202-47cd-b553-c63f4f245940"' sql = "(emails.type = {a} AND emails.value = {b})" @@ -368,24 +395,11 @@ class AzureQueries(TestCase): self.assertSQL(query, sql, params) -class GitHubBugsQueries(TestCase): +class GitHubBugsQueries(SetupHelper, TestCase): attr_map = { ('emails', 'type', None): 'emails.type', } - def setUp(self): - self.lexer = SCIMLexer() - self.parser = SCIMParser() - self.transpiler = transpile_sql.Transpiler(self.attr_map) - - def assertSQL(self, query, expected_sql, expected_params): - tokens = self.lexer.tokenize(query) - ast = self.parser.parse(tokens) - sql, params = self.transpiler.transpile(ast) - - self.assertEqual(expected_sql, sql, query) - self.assertEqual(expected_params, params, query) - def test_g15_ne_op(self): query = 'emails[type ne "work"]' sql = "emails.type != {a}" @@ -405,7 +419,7 @@ class CommandLine(TestCase): transpile_sql.main(['userName eq "bjensen"']) result = self.test_stdout.getvalue().strip().split('\n') expected = [ - 'SQL: username = {a}', + 'SQL: UPPER(username) = UPPER({a})', "PARAMS: {'a': 'bjensen'}" ] self.assertEqual(result, expected)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 5 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[django-query]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.7", "reqs_path": [ "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 asgiref==3.7.2 Babel==2.14.0 certifi @ file:///croot/certifi_1671487769961/work/certifi charset-normalizer==3.4.1 Django==3.2.25 docutils==0.19 exceptiongroup==1.2.2 idna==3.10 imagesize==1.4.1 importlib-metadata==6.7.0 iniconfig==2.0.0 Jinja2==3.1.6 MarkupSafe==2.1.5 packaging==24.0 pluggy==1.2.0 Pygments==2.17.2 pytest==7.4.4 pytz==2025.2 requests==2.31.0 -e git+https://github.com/15five/scim2-filter-parser.git@c794bf3e50e3cb71bdcf919feb43d11912907dd2#egg=scim2_filter_parser sly==0.4 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 sqlparse==0.4.4 tomli==2.0.1 typing_extensions==4.7.1 urllib3==2.0.7 zipp==3.15.0
name: scim2-filter-parser channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - asgiref==3.7.2 - babel==2.14.0 - charset-normalizer==3.4.1 - django==3.2.25 - docutils==0.19 - exceptiongroup==1.2.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - jinja2==3.1.6 - markupsafe==2.1.5 - packaging==24.0 - pluggy==1.2.0 - pygments==2.17.2 - pytest==7.4.4 - pytz==2025.2 - requests==2.31.0 - sly==0.4 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlparse==0.4.4 - tomli==2.0.1 - typing-extensions==4.7.1 - urllib3==2.0.7 - zipp==3.15.0 prefix: /opt/conda/envs/scim2-filter-parser
[ "tests/test_query.py::CommandLine::test_command_line", "tests/test_transpiler.py::RFCExamples::test_schema_username_startswith", "tests/test_transpiler.py::RFCExamples::test_username_eq", "tests/test_transpiler.py::RFCExamples::test_username_startswith", "tests/test_transpiler.py::RFCExamples::test_username_with_more_complex_query", "tests/test_transpiler.py::CommandLine::test_command_line" ]
[]
[ "tests/test_query.py::RFCExamples::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians", "tests/test_query.py::RFCExamples::test_family_name_contains", "tests/test_query.py::RFCExamples::test_meta_last_modified_ge", "tests/test_query.py::RFCExamples::test_meta_last_modified_gt", "tests/test_query.py::RFCExamples::test_meta_last_modified_le", "tests/test_query.py::RFCExamples::test_meta_last_modified_lt", "tests/test_query.py::RFCExamples::test_nickname_eq", "tests/test_query.py::RFCExamples::test_nickname_startswith", "tests/test_query.py::RFCExamples::test_schema_username_startswith", "tests/test_query.py::RFCExamples::test_schemas_eq", "tests/test_query.py::RFCExamples::test_title_has_value", "tests/test_query.py::RFCExamples::test_title_has_value_and_user_type_eq", "tests/test_query.py::RFCExamples::test_title_has_value_or_user_type_eq", "tests/test_query.py::RFCExamples::test_user_type_eq_and_email_contains_or_email_contains", "tests/test_query.py::RFCExamples::test_user_type_eq_and_not_email_type_eq", "tests/test_query.py::RFCExamples::test_user_type_eq_and_not_email_type_eq_work_and_value_contains", "tests/test_query.py::RFCExamples::test_user_type_ne_and_not_email_contains_or_email_contains", "tests/test_query.py::AzureQueries::test_email_type_eq_primary_value_eq_uuid", "tests/test_query.py::AzureQueries::test_external_id_from_azure", "tests/test_query.py::AzureQueries::test_parse_simple_email_filter_with_uuid", "tests/test_query.py::GeneralQueries::test_ensure_distinct_rows_fetched", "tests/test_transpiler.py::RFCExamples::test_attr_paths_are_created", "tests/test_transpiler.py::RFCExamples::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians", "tests/test_transpiler.py::RFCExamples::test_family_name_contains", "tests/test_transpiler.py::RFCExamples::test_meta_last_modified_ge", "tests/test_transpiler.py::RFCExamples::test_meta_last_modified_gt", "tests/test_transpiler.py::RFCExamples::test_meta_last_modified_le", "tests/test_transpiler.py::RFCExamples::test_meta_last_modified_lt", "tests/test_transpiler.py::RFCExamples::test_nickname_eq", "tests/test_transpiler.py::RFCExamples::test_nickname_startswith", "tests/test_transpiler.py::RFCExamples::test_schema_nickname_startswith", "tests/test_transpiler.py::RFCExamples::test_schemas_eq", "tests/test_transpiler.py::RFCExamples::test_title_has_value", "tests/test_transpiler.py::RFCExamples::test_title_has_value_and_user_type_eq", "tests/test_transpiler.py::RFCExamples::test_title_has_value_or_user_type_eq", "tests/test_transpiler.py::RFCExamples::test_user_type_eq_and_email_contains_or_email_contains", "tests/test_transpiler.py::RFCExamples::test_user_type_eq_and_not_email_type_eq", "tests/test_transpiler.py::RFCExamples::test_user_type_eq_and_not_email_type_eq_work_and_value_contains", "tests/test_transpiler.py::RFCExamples::test_user_type_ne_and_not_email_contains_or_email_contains", "tests/test_transpiler.py::UndefinedAttributes::test_email_type_eq_primary_value_eq_uuid_1", "tests/test_transpiler.py::UndefinedAttributes::test_email_type_eq_primary_value_eq_uuid_2", "tests/test_transpiler.py::UndefinedAttributes::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_1", "tests/test_transpiler.py::UndefinedAttributes::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_2", "tests/test_transpiler.py::UndefinedAttributes::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_3", "tests/test_transpiler.py::UndefinedAttributes::test_emails_type_eq_work_value_contians_or_ims_type_eq_and_value_contians_4", "tests/test_transpiler.py::UndefinedAttributes::test_schemas_eq", "tests/test_transpiler.py::UndefinedAttributes::test_title_has_value_and_user_type_eq_1", "tests/test_transpiler.py::UndefinedAttributes::test_title_has_value_and_user_type_eq_2", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_email_contains_or_email_contains", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_1", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_2", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_work_and_value_contains_1", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_work_and_value_contains_2", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_eq_and_not_email_type_eq_work_and_value_contains_3", "tests/test_transpiler.py::UndefinedAttributes::test_user_type_ne_and_not_email_contains_or_email_contains", "tests/test_transpiler.py::UndefinedAttributes::test_username_eq", "tests/test_transpiler.py::AzureQueries::test_email_type_eq_primary_value_eq_uuid", "tests/test_transpiler.py::AzureQueries::test_external_id_from_azure", "tests/test_transpiler.py::AzureQueries::test_parse_simple_email_filter_with_uuid", "tests/test_transpiler.py::GitHubBugsQueries::test_g15_ne_op" ]
[]
MIT License
null
null
20c__ctl-3
879af37647e61767a1ede59ffd353e4cfd27cd6f
2019-10-08 09:23:56
879af37647e61767a1ede59ffd353e4cfd27cd6f
diff --git a/src/ctl/plugins/pypi.py b/src/ctl/plugins/pypi.py index 5d979af..a6117af 100644 --- a/src/ctl/plugins/pypi.py +++ b/src/ctl/plugins/pypi.py @@ -32,7 +32,7 @@ class PyPIPluginConfig(release.ReleasePluginConfig): config_file = confu.schema.Str(help="path to pypi config file (e.g. ~/.pypirc)") # PyPI repository name, needs to exist in your pypi config file - repository = confu.schema.Str( + pypi_repository = confu.schema.Str( help="PyPI repository name - needs to exist " "in your pypi config file", default="pypi", ) @@ -55,16 +55,16 @@ class PyPIPlugin(release.ReleasePlugin): @property def dist_path(self): - return os.path.join(self.target.checkout_path, "dist", "*") + return os.path.join(self.repository.checkout_path, "dist", "*") def prepare(self): super(PyPIPlugin, self).prepare() self.shell = True - self.repository = self.get_config("repository") + self.pypi_repository = self.get_config("pypi_repository") self.pypirc_path = os.path.expanduser(self.config.get("config_file")) self.twine_settings = Settings( config_file=self.pypirc_path, - repository_name=self.repository, + repository_name=self.pypi_repository, sign=self.get_config("sign"), identity=self.get_config("identity"), sign_with=self.get_config("sign_with"), diff --git a/src/ctl/plugins/release.py b/src/ctl/plugins/release.py index bcfa1ce..dcae2f4 100644 --- a/src/ctl/plugins/release.py +++ b/src/ctl/plugins/release.py @@ -18,8 +18,8 @@ import ctl.plugins.git class ReleasePluginConfig(confu.schema.Schema): - target = confu.schema.Str( - help="target for release - should be a path " + repository = confu.schema.Str( + help="repository target for release - should be a path " "to a python package or the name of a " "repository type plugin", cli=False, @@ -46,16 +46,16 @@ class ReleasePlugin(command.CommandPlugin): "version", nargs=1, type=str, - help="release version - if target is managed by git, " + help="release version - if repository is managed by git, " "checkout this branch/tag", ) group.add_argument( - "target", + "repository", nargs="?", type=str, - default=plugin_config.get("target"), - help=ReleasePluginConfig().target.help, + default=plugin_config.get("repository"), + help=ReleasePluginConfig().repository.help, ) sub = parser.add_subparsers(title="Operation", dest="op") @@ -74,7 +74,7 @@ class ReleasePlugin(command.CommandPlugin): return { "group": group, - "confu_target": op_release_parser, + "confu_repository": op_release_parser, "op_release_parser": op_release_parser, "op_validate_parser": op_validate_parser, } @@ -84,48 +84,48 @@ class ReleasePlugin(command.CommandPlugin): self.prepare() self.shell = True - self.set_target(self.get_config("target")) + self.set_repository(self.get_config("repository")) self.dry_run = kwargs.get("dry") self.version = kwargs.get("version")[0] - self.orig_branch = self.target.branch + self.orig_branch = self.repository.branch if self.dry_run: self.log.info("Doing dry run...") - self.log.info("Release target: {}".format(self.target)) + self.log.info("Release repository: {}".format(self.repository)) try: - self.target.checkout(self.version) + self.repository.checkout(self.version) op = self.get_op(kwargs.get("op")) op(**kwargs) finally: - self.target.checkout(self.orig_branch) + self.repository.checkout(self.orig_branch) - def set_target(self, target): - if not target: - raise ValueError("No target specified") + def set_repository(self, repository): + if not repository: + raise ValueError("No repository specified") try: - self.target = self.other_plugin(target) - if not isinstance(self.target, ctl.plugins.repository.RepositoryPlugin): + self.repository = self.other_plugin(repository) + if not isinstance(self.repository, ctl.plugins.repository.RepositoryPlugin): raise TypeError( "The plugin with the name `{}` is not a " "repository type plugin and cannot be used " - "as a target".format(target) + "as a repository".format(repository) ) except KeyError: - self.target = os.path.abspath(target) - if not os.path.exists(self.target): + self.repository = os.path.abspath(repository) + if not os.path.exists(self.repository): raise IOError( "Target is neither a configured repository " "plugin nor a valid file path: " - "{}".format(self.target) + "{}".format(self.repository) ) - self.target = ctl.plugins.git.temporary_plugin( - self.ctl, "{}__tmp_repo".format(self.plugin_name), self.target + self.repository = ctl.plugins.git.temporary_plugin( + self.ctl, "{}__tmp_repo".format(self.plugin_name), self.repository ) - self.cwd = self.target.checkout_path + self.cwd = self.repository.checkout_path @expose("ctl.{plugin_name}.release") def release(self, **kwargs):
PyPI plugin: `target` config attribute should be `repository` This is so it's in line with the version plugin, which currently uses `repository` to specify the target repository The pypi plugin currently uses `repository` to specify which PyPI repository to use, this should change to `pypi_repository` as well. Should do this before tagging 1.0.0 since it's a config schema change
20c/ctl
diff --git a/tests/test_plugin_pypi.py b/tests/test_plugin_pypi.py index 20315ad..19813e2 100644 --- a/tests/test_plugin_pypi.py +++ b/tests/test_plugin_pypi.py @@ -53,35 +53,35 @@ def test_init(): -def test_set_target_git_path(tmpdir, ctlr): +def test_set_repository_git_path(tmpdir, ctlr): """ - Test setting build target: existing git repo via filepath + Test setting build repository: existing git repo via filepath """ plugin, git_plugin = instantiate(tmpdir, ctlr) - plugin.set_target(git_plugin.checkout_path) + plugin.set_repository(git_plugin.checkout_path) assert plugin.dist_path == os.path.join(git_plugin.checkout_path, "dist", "*") -def test_set_target_git_plugin(tmpdir, ctlr): +def test_set_repository_git_plugin(tmpdir, ctlr): """ - Test setting build target: existing git plugin + Test setting build repository: existing git plugin """ plugin, git_plugin = instantiate(tmpdir, ctlr) - plugin.set_target(git_plugin.plugin_name) + plugin.set_repository(git_plugin.plugin_name) assert plugin.dist_path == os.path.join(git_plugin.checkout_path, "dist", "*") -def test_set_target_error(tmpdir, ctlr): +def test_set_repository_error(tmpdir, ctlr): """ - Test setting invalid build target + Test setting invalid build repository """ plugin, git_plugin = instantiate(tmpdir, ctlr) @@ -89,17 +89,17 @@ def test_set_target_error(tmpdir, ctlr): # non existing path / plugin name with pytest.raises(IOError): - plugin.set_target("invalid target") + plugin.set_repository("invalid repository") # invalid plugin type with pytest.raises(TypeError): - plugin.set_target("test_pypi") + plugin.set_repository("test_pypi") - # no target + # no repository with pytest.raises(ValueError): - plugin.set_target(None) + plugin.set_repository(None) def test_build_dist(tmpdir, ctlr): @@ -110,7 +110,7 @@ def test_build_dist(tmpdir, ctlr): plugin, git_plugin = instantiate(tmpdir, ctlr) plugin.prepare() - plugin.set_target(git_plugin.plugin_name) + plugin.set_repository(git_plugin.plugin_name) plugin._build_dist() assert os.path.exists(os.path.join(git_plugin.checkout_path, @@ -126,7 +126,7 @@ def test_validate_dist(tmpdir, ctlr): plugin, git_plugin = instantiate(tmpdir, ctlr) plugin.prepare() - plugin.set_target(git_plugin.plugin_name) + plugin.set_repository(git_plugin.plugin_name) plugin._build_dist() plugin._validate_dist()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "codecov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "Ctl/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 cfu==1.5.0 charset-normalizer==2.0.12 click==8.0.4 codecov==2.1.13 coverage==6.2 -e git+https://github.com/20c/ctl.git@879af37647e61767a1ede59ffd353e4cfd27cd6f#egg=ctl future==0.18.3 git-url-parse==1.2.2 grainy==1.8.1 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 munge==0.6.0 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 pluginmgr==0.6.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: ctl channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - cfu==1.5.0 - charset-normalizer==2.0.12 - click==8.0.4 - codecov==2.1.13 - coverage==6.2 - future==0.18.3 - git-url-parse==1.2.2 - grainy==1.8.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - munge==0.6.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - pluginmgr==0.6.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/ctl
[ "tests/test_plugin_pypi.py::test_set_repository_git_path[standard]", "tests/test_plugin_pypi.py::test_set_repository_git_plugin[standard]", "tests/test_plugin_pypi.py::test_set_repository_error[standard]" ]
[ "tests/test_plugin_pypi.py::test_build_dist[standard]", "tests/test_plugin_pypi.py::test_validate_dist[standard]" ]
[ "tests/test_plugin_pypi.py::test_init" ]
[]
Apache License 2.0
swerebench/sweb.eval.x86_64.20c_1776_ctl-3
swerebench/sweb.eval.x86_64.20c_1776_ctl-3
20c__ctl-7
be7f350f8f2d92918922d82fce0266fcd72decd2
2019-10-21 11:05:40
be7f350f8f2d92918922d82fce0266fcd72decd2
diff --git a/Ctl/Pipfile b/Ctl/Pipfile index 0c7a304..1bd6308 100644 --- a/Ctl/Pipfile +++ b/Ctl/Pipfile @@ -14,7 +14,7 @@ tmpl = "==0.3.0" [packages] munge = "<1,>=0.4" -cfu = ">=1.2.0,<2" +cfu = ">=1.3.0,<2" grainy = ">=1.4.0,<2" git-url-parse = ">=1.1.0,<2" pluginmgr = ">=0.6" diff --git a/Ctl/requirements.txt b/Ctl/requirements.txt index b3582c5..0037aaa 100644 --- a/Ctl/requirements.txt +++ b/Ctl/requirements.txt @@ -1,5 +1,5 @@ munge >=0.4, <1 -cfu >= 1.2.0, < 2 +cfu >= 1.3.0, < 2 grainy >= 1.4.0, <2 git-url-parse >= 1.1.0, <2 pluginmgr >= 0.6 diff --git a/src/ctl/__init__.py b/src/ctl/__init__.py index eb4a635..b9616df 100644 --- a/src/ctl/__init__.py +++ b/src/ctl/__init__.py @@ -4,6 +4,7 @@ import os from pkg_resources import get_distribution import confu.config +import confu.exceptions import grainy.core import copy import logging @@ -279,11 +280,14 @@ class Ctl(object): # def set_config_dir(self): def __init__(self, ctx=None, config_dir=None, full_init=True): - self.init_context(ctx=ctx, config_dir=config_dir) + self.init_context(ctx=ctx, config_dir=config_dir) self.init_logging() - self.init_permissions() + if self.config.errors: + return self.log_config_issues() + + self.init_permissions() self.expose_plugin_vars() if full_init: @@ -330,8 +334,10 @@ class Ctl(object): Apply python logging config and create `log` and `usage_log` properties """ + # allow setting up python logging from ctl config set_pylogger_config(self.ctx.config.get_nested("ctl", "log")) + # instantiate logger self.log = Log("ctl") self.usage_log = Log("usage") diff --git a/src/ctl/plugins/tmp b/src/ctl/plugins/tmp new file mode 100644 index 0000000..41bd689 --- /dev/null +++ b/src/ctl/plugins/tmp @@ -0,0 +1,57 @@ +plugins: + + # plugin that controls the repo we want to install from + - type: git + name: git_fullctl + config: + repo_url: git@git.20c.com:fullctl/www.fullctl.com + + + # copy files + - type: copy + name: copy_fullctl + config: + src: {{tmp}}/git@git.20c.com:fullctl/www.fullctl.com + dest: {{tmp}}/builds/www.fullctl.com/{{tag}} + walk_dirs: + - {{src}}/fullctl/website + - {{src}}/fullctl/ixportal + + + # template files + - type: template + name: template_fullctl + config: + src: {{tmp}}/git@git.20c.com:fullctl/www.fullctl.com + dest: {{tmp}}/builds/www.fullctl.com/{{tag}}/fullctl + walk_dirs: + - {{src}}Ctl/fullctl/templates + vars: + - {{src}}/Ctl/fullctl/{{env}}.yaml + + + # rsync + - type: rsync + name: rsync_fullctl + config: + gateways: + beta: + - host: 127.0.0.1 + user: fullctl + + # run installation sequence + - type: chain + name: facsimile + config: + chains: + beta: + # stage `git` - checks out the tag passed in the cli + - git_fullctl checkout {{tag}} + # stage `copy` - copy project files + - copy_fullctl beta {{tag}} + # stage `template` - build template files + - template_fullctl beta {{tag}} + # stage `rsync` + - rsync_fullctl beta {{tmp}}/builds/www.fullctl.com/{{tag}} + + diff --git a/src/ctl/util/versioning.py b/src/ctl/util/versioning.py index 22bdb09..23e1390 100644 --- a/src/ctl/util/versioning.py +++ b/src/ctl/util/versioning.py @@ -1,5 +1,4 @@ def version_tuple(version): - print("VERSION", version) """ Returns a tuple from version string """ return tuple(version.split(".")) @@ -9,27 +8,35 @@ def version_string(version): return ".".join(["{}".format(v) for v in version]) -def validate_semantic(version): +def validate_semantic(version, pad=0): if not isinstance(version, (list, tuple)): version = version_tuple(version) - try: - major, minor, patch, dev = version - except ValueError: - major, minor, patch = version + parts = len(version) + + if parts < 1: + raise ValueError("Semantic version needs to contain at least a major version") + if parts > 4: + raise ValueError("Semantic version can not contain more than 4 parts") + + if parts < pad: + version = tuple(list(version) + [0 for i in range(0, pad - parts)]) return tuple([int(n) for n in version]) def bump_semantic(version, segment): - version = list(validate_semantic(version)) if segment == "major": + version = list(validate_semantic(version)) return (version[0] + 1, 0, 0) elif segment == "minor": + version = list(validate_semantic(version, pad=2)) return (version[0], version[1] + 1, 0) elif segment == "patch": + version = list(validate_semantic(version, pad=3)) return (version[0], version[1], version[2] + 1) elif segment == "dev": + version = list(validate_semantic(version, pad=4)) try: return (version[0], version[1], version[2], version[3] + 1) except IndexError:
Better error handling for config errors outside of `plugins` Example: having a schema error in `permissions` exits ctl with traceback that's not very telling as to what is failing reproduce: ``` permissions: namespace: ctl permission: crud ```
20c/ctl
diff --git a/tests/test_plugin_version.py b/tests/test_plugin_version.py index 6745c78..4b9617a 100644 --- a/tests/test_plugin_version.py +++ b/tests/test_plugin_version.py @@ -138,6 +138,30 @@ def test_bump(tmpdir, ctlr): plugin.bump(version="invalid", repo="dummy_repo"