Skip to content

Commit

Permalink
refactor: extend the length of the black lines to 100 chars (#916)
Browse files Browse the repository at this point in the history
  • Loading branch information
12rambau authored May 10, 2024
2 parents 2d0174c + 9601dea commit 9cb21d3
Show file tree
Hide file tree
Showing 42 changed files with 120 additions and 357 deletions.
6 changes: 2 additions & 4 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
def lint(session):
"""Apply the pre-commits."""
session.install("pre-commit")
session.run("pre-commit", "run", "--a", *session.posargs)
session.run("pre-commit", "run", "--all-files", *session.posargs)


@nox.session(reuse_venv=True)
Expand Down Expand Up @@ -56,9 +56,7 @@ def docs(session):
# build the api doc files
templates = "docs/source/_templates/apidoc"
modules = "docs/source/modules"
session.run(
"sphinx-apidoc", f"--templatedir={templates}", "-o", modules, "sepal_ui"
)
session.run("sphinx-apidoc", f"--templatedir={templates}", "-o", modules, "sepal_ui")

# build the documentation
source = "docs/source"
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,6 @@ using = "PEP631:test;dev;doc"

[tool.codespell]
skip = 'CHANGELOG.md,sepal_ui/message/**/*.json,sepal_ui/data/gaul_iso.json'

[tool.black]
line-length = 100
32 changes: 8 additions & 24 deletions sepal_ui/aoi/aoi_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,7 @@ def __init__(
self.gee = gee
if gee:
su.init_ee()
self.folder = (
str(folder) or f"projects/{ee.data._cloud_api_user_project}/assets/"
)
self.folder = str(folder) or f"projects/{ee.data._cloud_api_user_project}/assets/"

# set default values
self.set_default(vector, admin, asset)
Expand All @@ -177,22 +175,16 @@ def set_default(
# save the default values
self.default_vector = vector
self.default_asset = self.asset_name = str(asset) if asset else None
self.asset_json = (
{"pathname": asset, "column": "ALL", "value": None} if asset else None
)
self.asset_json = {"pathname": asset, "column": "ALL", "value": None} if asset else None
self.default_admin = self.admin = admin

# cast the vector to json
self.vector_json = (
{"pathname": str(vector), "column": "ALL", "value": None}
if vector
else None
{"pathname": str(vector), "column": "ALL", "value": None} if vector else None
)

# cast the asset to json
self.asset_json = (
{"pathname": asset, "column": "ALL", "value": None} if asset else None
)
self.asset_json = {"pathname": asset, "column": "ALL", "value": None} if asset else None

# set the default gdf if possible
if self.vector_json is not None:
Expand Down Expand Up @@ -285,9 +277,7 @@ def _from_points(self, point_json: dict) -> Self:
self.gdf = gpd.GeoDataFrame(
df,
crs="EPSG:4326",
geometry=gpd.points_from_xy(
df[point_json["lng_column"]], df[point_json["lat_column"]]
),
geometry=gpd.points_from_xy(df[point_json["lng_column"]], df[point_json["lat_column"]]),
)

# set the name
Expand Down Expand Up @@ -449,9 +439,7 @@ def get_columns(self) -> List[str]:
if self.gee:
aoi_ee = ee.Feature(self.feature_collection.first())
columns = aoi_ee.propertyNames().getInfo()
list_ = [
col for col in columns if col not in ["system:index", "Shape_Area"]
]
list_ = [col for col in columns if col not in ["system:index", "Shape_Area"]]
else:
list_ = list(set(["geometry"]) ^ set(self.gdf.columns.to_list()))

Expand All @@ -478,9 +466,7 @@ def get_fields(self, column: str) -> List[str]:

return sorted(list_)

def get_selected(
self, column: str, field: str
) -> Union[ee.Feature, gpd.GeoDataFrame]:
def get_selected(self, column: str, field: str) -> Union[ee.Feature, gpd.GeoDataFrame]:
"""Select an ee object based on selected column and field.
Args:
Expand All @@ -494,9 +480,7 @@ def get_selected(
raise Exception(ms.aoi_sel.exception.no_gdf)

if self.gee:
selected_feature = self.feature_collection.filterMetadata(
column, "equals", field
)
selected_feature = self.feature_collection.filterMetadata(column, "equals", field)
else:
selected_feature = self.gdf[self.gdf[column] == field]

Expand Down
24 changes: 6 additions & 18 deletions sepal_ui/aoi/aoi_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,9 @@ def __init__(
if methods == "ALL":
self.methods = select_methods
elif methods == "ADMIN":
self.methods = {
k: v for k, v in select_methods.items() if v["type"] == ADMIN
}
self.methods = {k: v for k, v in select_methods.items() if v["type"] == ADMIN}
elif methods == "CUSTOM":
self.methods = {
k: v for k, v in select_methods.items() if v["type"] == CUSTOM
}
self.methods = {k: v for k, v in select_methods.items() if v["type"] == CUSTOM}
elif type(methods) == list:
if any(m[0] == "-" for m in methods) != all(m[0] == "-" for m in methods):
raise Exception("You mixed adding and removing, punk")
Expand All @@ -65,9 +61,7 @@ def __init__(
to_remove = [method[1:] for method in methods]

# Rewrite the methods instead of mutate the class methods
self.methods = {
k: v for k, v in select_methods.items() if k not in to_remove
}
self.methods = {k: v for k, v in select_methods.items() if k not in to_remove}

else:
self.methods = {k: select_methods[k] for k in methods}
Expand Down Expand Up @@ -104,9 +98,7 @@ class AdminField(sw.Select):
parent: Optional[sw.Select] = None
"The parent adminfield object"

def __init__(
self, level: int, parent: Optional[sw.Select] = None, gee: bool = True
) -> None:
def __init__(self, level: int, parent: Optional[sw.Select] = None, gee: bool = True) -> None:
"""An admin level selector.
It is binded to ee (GAUL 2015) or not (GADM). Allows to select administrative codes taking into account the administrative parent code and displaying humanly readable administrative names.
Expand All @@ -124,9 +116,7 @@ def __init__(
self.parent = parent

# init an empty widget
super().__init__(
v_model=None, items=[], clearable=True, label=ms.aoi_sel.adm[level]
)
super().__init__(v_model=None, items=[], clearable=True, label=ms.aoi_sel.adm[level])

# add js behaviour
self.parent is None or self.parent.observe(self._update, "v_model")
Expand Down Expand Up @@ -333,9 +323,7 @@ def __init__(
self.btn = sw.Btn(msg=ms.aoi_sel.btn)

# create the widget
self.children = (
[self.w_method] + [*self.components.values()] + [self.btn, self.alert]
)
self.children = [self.w_method] + [*self.components.values()] + [self.btn, self.alert]

super().__init__(**kwargs)

Expand Down
14 changes: 3 additions & 11 deletions sepal_ui/bin/activate_venv.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,7 @@ def main() -> None:
test_venv_path = Path.home() / "module-venv"
if test_venv_path.exists():
test_envs = pd.DataFrame(
list(
[f"test {el.name}", str(el)]
for el in test_venv_path.glob("[!.]*")
if el.is_dir()
)
list([f"test {el.name}", str(el)] for el in test_venv_path.glob("[!.]*") if el.is_dir())
)
venvs = pd.concat([venvs, test_envs])
venvs = venvs.reset_index(drop=True)
Expand All @@ -59,9 +55,7 @@ def main() -> None:
while not valid:

selection = int(
input(
f"{Fore.CYAN} Select the venv number you want to activate: \n{Fore.RESET}"
)
input(f"{Fore.CYAN} Select the venv number you want to activate: \n{Fore.RESET}")
)

if selection not in venvs.index.unique():
Expand All @@ -84,9 +78,7 @@ def main() -> None:
# The following lines won't be executed because the previous subprocess kill the kernel

# Confirm that we are in the new env
result = subprocess.run(
["echo", "$VIRTUAL_ENV"], shell=True, stdout=subprocess.PIPE
)
result = subprocess.run(["echo", "$VIRTUAL_ENV"], shell=True, stdout=subprocess.PIPE)

print(f"The current env is: {result.stdout!r}")

Expand Down
16 changes: 4 additions & 12 deletions sepal_ui/bin/module_deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ def write_reqs(file: Union[str, Path]) -> None:

# add the custom libs
tmp_file = Path.cwd() / "req_tmp.txt"
subprocess.run(
["pipreqs", "--savepath", str(tmp_file), str(Path.cwd())], cwd=Path.cwd()
)
subprocess.run(["pipreqs", "--savepath", str(tmp_file), str(Path.cwd())], cwd=Path.cwd())

# add the libs in the final file
with file.open("a") as dst:
Expand Down Expand Up @@ -79,9 +77,7 @@ def clean_dulpicate(file: Union[str, Path]) -> None:
for line in text[idx:]:
if any(lib in line for lib in libs):
lib = next(lb for lb in libs if lb in line)
print(
f"Removing {Style.BRIGHT}{lib}{Style.NORMAL} from reqs, duplicated from default."
)
print(f"Removing {Style.BRIGHT}{lib}{Style.NORMAL} from reqs, duplicated from default.")
continue
final_text.append(line)

Expand Down Expand Up @@ -113,9 +109,7 @@ def clean_troubleshouting(file: Union[str, Path]) -> None:
# gdal and osgeo are part of pygdal
# we use a specific version of earthengine in SEPAl, let's stick to it
if "ee" in line:
print(
f"Removing {Style.BRIGHT}ee{Style.NORMAL} from reqs, included in sepal_ui."
)
print(f"Removing {Style.BRIGHT}ee{Style.NORMAL} from reqs, included in sepal_ui.")
continue
elif any(lib in line for lib in ["osgeo"]):
print(f"Removing {Style.BRIGHT}'osgeo'{Style.NORMAL} as part of gdal")
Expand Down Expand Up @@ -144,9 +138,7 @@ def freeze_sepal_ui(file: Union[str, Path]) -> None:
text = file.read_text().split("\n")

# search for the sepal_ui line
idx, _ = next(
(i, il) for i, il in enumerate(text) if "#" not in il and "sepal_ui" in il
)
idx, _ = next((i, il) for i, il in enumerate(text) if "#" not in il and "sepal_ui" in il)

text[idx] = f"sepal_ui=={sepal_ui.__version__}"

Expand Down
8 changes: 2 additions & 6 deletions sepal_ui/bin/module_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
parser = argparse.ArgumentParser(description=__doc__, usage="module_factory")


def set_default_readme(
folder: Path, module_name: str, description: str, url: str
) -> None:
def set_default_readme(folder: Path, module_name: str, description: str, url: str) -> None:
"""Write a default README.md file and overwrite the existing one.
Args:
Expand Down Expand Up @@ -194,9 +192,7 @@ def main() -> None:
subprocess.run(["cp", "-r", str(template_dir), str(folder)], cwd=Path.cwd())

# replace the placeholders
url = github_url.replace(".git", "").replace(
"git@github.com:", "https://github.com/"
)
url = github_url.replace(".git", "").replace("git@github.com:", "https://github.com/")

set_default_readme(folder, module_name, description, url)
set_default_about(folder, description)
Expand Down
3 changes: 1 addition & 2 deletions sepal_ui/frontend/resize_trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ class ResizeTrigger(v.VuetifyTemplate):
# load the js file
js = (Path(__file__).parent / "js/jupyter_resize.js").read_text()
template = Unicode(
"<script class='sepal-ui-script'>{methods: {jupyter_resize(){%s}}}</script>"
% js
"<script class='sepal-ui-script'>{methods: {jupyter_resize(){%s}}}</script>" % js
).tag(sync=True)
"Unicode: the javascript script to manually trigger the resize event"

Expand Down
8 changes: 2 additions & 6 deletions sepal_ui/mapping/aoi_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ def __init__(self, m: Map, **kwargs) -> None:
self.menu.cole_on_content_click = True

# set the size of the card to 0 so that the list controls the widget display
self.set_size(
min_width="200px", max_width="200px", min_height=None, max_height="300px"
)
self.set_size(min_width="200px", max_width="200px", min_height=None, max_height="300px")

# add js behaviours
self.menu.v_slots[0]["children"].on_event("click", self.click_btn)
Expand All @@ -74,9 +72,7 @@ def click_btn(self, *args) -> None:
return

@sd.need_ee
def add_aoi(
self, name: str, item: Union[sg.base.BaseGeometry, ee.ComputedObject]
) -> None:
def add_aoi(self, name: str, item: Union[sg.base.BaseGeometry, ee.ComputedObject]) -> None:
"""Add an AOI to the list and refresh the list displayed. the AOI will be composed of a name and the bounds of the provided item.
Args:
Expand Down
4 changes: 1 addition & 3 deletions sepal_ui/mapping/fullscreen_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ class FullScreenControl(WidgetControl):
template: Optional[v.VuetifyTemplate] = None
"Embeds the 2 javascripts methods to change the rendering of the map"

def __init__(
self, m: Map, fullscreen: bool = False, fullapp: bool = False, **kwargs
) -> None:
def __init__(self, m: Map, fullscreen: bool = False, fullapp: bool = False, **kwargs) -> None:
"""A custom Fullscreen Button ready to be embed in a map object.
This button will force the display of the map in fullscreen mode. It should be used instead of the built-in ipyleaflet FullscreenControl if your map is embedding ipyvuetify widgets. I tends to solve the issue raised here: https://github.com/widgetti/ipyvuetify/issues/141. The idea is to fake the fullscreen display by forcing the map container to extend to the full extend of the screen without using a z-index superior to the ipyvuetify overlay.
Expand Down
19 changes: 5 additions & 14 deletions sepal_ui/mapping/inspector_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,7 @@ def read_data(self, **kwargs) -> None:
elif isinstance(lyr, Marker):
continue
else:
data = {
ms.inspector_control.info.header: ms.inspector_control.info.text
}
data = {ms.inspector_control.info.header: ms.inspector_control.info.text}

items.append(
{
Expand Down Expand Up @@ -218,9 +216,7 @@ def _from_eelayer(self, ee_obj: ee.ComputedObject, coords: Sequence[float]) -> d
).getInfo()

else:
raise ValueError(
f'the layer object is a "{type(ee_obj)}" which is not accepted.'
)
raise ValueError(f'the layer object is a "{type(ee_obj)}" which is not accepted.')

return pixel_values

Expand Down Expand Up @@ -280,22 +276,17 @@ def _from_raster(self, raster: Union[str, Path], coords: Sequence[float]) -> dic
window = rio.windows.from_bounds(*bounds, transform=da.rio.transform())
da_filtered = da.rio.isel_window(window)
means = da_filtered.mean(axis=(1, 2)).to_numpy()
pixel_values = {
ms.inspector_control.band.format(i + 1): v for i, v in enumerate(means)
}
pixel_values = {ms.inspector_control.band.format(i + 1): v for i, v in enumerate(means)}

# if the point is out of the image display None
else:
pixel_values = {
ms.inspector_control.band.format(i + 1): None
for i in range(da.rio.count)
ms.inspector_control.band.format(i + 1): None for i in range(da.rio.count)
}

return pixel_values


@deprecated(
version="2.15.1", reason="ValueInspector class is now renamed InspectorControl"
)
@deprecated(version="2.15.1", reason="ValueInspector class is now renamed InspectorControl")
class ValueInspector(InspectorControl):
pass
9 changes: 2 additions & 7 deletions sepal_ui/mapping/layers_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,7 @@ def __init__(self, m: Map, **kwargs) -> None:
# set the kwargs parameters
kwargs.setdefault("position", "topright")
super().__init__(
icon_content="fa-solid fa-layer-group",
card_content=self.tile,
m=m,
**kwargs
icon_content="fa-solid fa-layer-group", card_content=self.tile, m=m, **kwargs
)

# customize the menu to make it look more like a layercontrol
Expand Down Expand Up @@ -226,9 +223,7 @@ def update_table(self, change: dict) -> None:
# the error raised if you delete the last one is a feature
bases = [lyr for lyr in self.m.layers if lyr.base is True]
base_rows = []
current = next(
(lyr for lyr in bases if lyr.visible is True), SimpleNamespace(name=None)
)
current = next((lyr for lyr in bases if lyr.visible is True), SimpleNamespace(name=None))
if len(bases) > 0:
head = [HeaderRow(ms.layer_control.basemap.header)]
empy_cell = sw.Html(tag="td", children=[" "], attributes={"colspan": 3})
Expand Down
Loading

0 comments on commit 9cb21d3

Please sign in to comment.