Skip to content

Commit

Permalink
Fix pylint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
giswqs committed Sep 11, 2024
1 parent 99dbb95 commit a97892a
Show file tree
Hide file tree
Showing 12 changed files with 77 additions and 413 deletions.
41 changes: 20 additions & 21 deletions leafmap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,25 @@ def view_vector(
"""Visualize a vector dataset on the map.
Args:
vector (Union[str, GeoDataFrame]): The file path or URL to the vector data, or a GeoDataFrame.
zoom_to_layer (bool, optional): Flag to zoom to the added layer. Defaults to True.
pickable (bool, optional): Flag to enable picking on the added layer. Defaults to True.
color_column (Optional[str], optional): The column to be used for color encoding. Defaults to None.
color_map (Optional[Union[str, Dict]], optional): The color map to use for color encoding. It can be a string or a dictionary. Defaults to None.
color_scheme (Optional[str], optional): The color scheme to use for color encoding. Defaults to "Quantiles".
Name of a choropleth classification scheme (requires mapclassify).
A mapclassify.MapClassifier object will be used
under the hood. Supported are all schemes provided by mapclassify (e.g.
'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled',
'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced',
'JenksCaspallSampled', 'MaxP', 'MaximumBreaks',
'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean',
'UserDefined'). Arguments can be passed in classification_kwds.
color_k (Optional[int], optional): The number of classes to use for color encoding. Defaults to 5.
color_args (dict, optional): Additional keyword arguments that will be passed to assign_continuous_colors(). Defaults to {}.
open_args (dict, optional): Additional keyword arguments that will be passed to geopandas.read_file(). Defaults to {}.
map_args (dict, optional): Additional keyword arguments that will be passed to lonboard.Map. Defaults to {}.
**kwargs: Additional keyword arguments that will be passed to lonboard.Layer.from_geopandas()
vector (Union[str, GeoDataFrame]): The file path or URL to the vector data, or a GeoDataFrame.
zoom_to_layer (bool, optional): Flag to zoom to the added layer. Defaults to True.
pickable (bool, optional): Flag to enable picking on the added layer. Defaults to True.
color_column (Optional[str], optional): The column to be used for color encoding. Defaults to None.
color_map (Optional[Union[str, Dict]], optional): The color map to use for color encoding. It can be a string or a dictionary. Defaults to None.
color_scheme (Optional[str], optional): The color scheme to use for color encoding. Defaults to "Quantiles".
Name of a choropleth classification scheme (requires mapclassify).
A mapclassify.MapClassifier object will be used
under the hood. Supported are all schemes provided by mapclassify (e.g.
'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled',
'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced',
'JenksCaspallSampled', 'MaxP', 'MaximumBreaks',
'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean',
'UserDefined'). Arguments can be passed in classification_kwds.
color_k (Optional[int], optional): The number of classes to use for color encoding. Defaults to 5.
color_args (dict, optional): Additional keyword arguments that will be passed to assign_continuous_colors(). Defaults to {}.
open_args (dict, optional): Additional keyword arguments that will be passed to geopandas.read_file(). Defaults to {}.
map_args (dict, optional): Additional keyword arguments that will be passed to lonboard.Map. Defaults to {}.
**kwargs: Additional keyword arguments that will be passed to lonboard.Layer.from_geopandas()
Returns:
lonboard.Map: A lonboard Map object.
Expand Down Expand Up @@ -95,8 +95,7 @@ def view_pmtiles(
map_args={},
**kwargs,
):
"""
Visualize PMTiles the map.
"""Visualize PMTiles the map.
Args:
url (str): The URL of the PMTiles file.
Expand Down
14 changes: 8 additions & 6 deletions leafmap/basemaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,12 +317,12 @@ def xyz_to_leaflet():

# Add custom tiles.
for tile_type, tile_dict in custom_tiles.items():
for tile_provider, tile_info in tile_dict.items():
for _, tile_info in tile_dict.items():
tile_info["type"] = tile_type
leaflet_dict[tile_info["name"]] = tile_info

# Add xyzservices.provider tiles.
for tile_provider, tile_info in get_xyz_dict().items():
for _, tile_info in get_xyz_dict().items():
if tile_info["name"] in ignore_list:
continue
tile_info["url"] = tile_info.build_url()
Expand Down Expand Up @@ -490,17 +490,19 @@ def xyz_to_bokeh():
return bokeh_dict


def search_qms(keywords, limit=10):
def search_qms(keywords, limit=10, timeout=600):
"""Search qms files for keywords. Reference: https://github.com/geopandas/xyzservices/issues/65
Args:
keywords (str): Keywords to search for.
limit (int): Number of results to return.
"""
QMS_API = "https://qms.nextgis.com/api/v1/geoservices"

services = requests.get(
f"{QMS_API}/?search={keywords}&type=tms&epsg=3857&limit={str(limit)}"
f"{QMS_API}/?search={keywords}&type=tms&epsg=3857&limit={str(limit)}",
timeout=timeout,
)
services = services.json()
if services["count"] == 0:
Expand All @@ -511,9 +513,9 @@ def search_qms(keywords, limit=10):
return services["results"][:limit]


def get_qms(service_id):
def get_qms(service_id, timeout=60):
QMS_API = "https://qms.nextgis.com/api/v1/geoservices"
service_details = requests.get(f"{QMS_API}/{service_id}")
service_details = requests.get(f"{QMS_API}/{service_id}", timeout=timeout)
return service_details.json()


Expand Down
4 changes: 2 additions & 2 deletions leafmap/bokehmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from bokeh.io import output_notebook
from .basemaps import xyz_to_bokeh
from .common import *
from typing import Optional, List, Sequence, Tuple, Dict
from typing import Optional, List, Dict

os.environ["OUTPUT_NOTEBOOK"] = "False"
basemaps = Box(xyz_to_bokeh(), frozen_box=True)
Expand Down Expand Up @@ -477,7 +477,7 @@ def to_streamlit(
use_container_width (bool, optional): A flag indicating whether to use the full width of the container. Defaults to True.
**kwargs: Arbitrary keyword arguments for bokeh.plotting.show().
"""
import streamlit as st
import streamlit as st # pylint: disable=E0401

self.figure.width = width
self.figure.height = height
Expand Down
168 changes: 25 additions & 143 deletions leafmap/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,33 +667,6 @@ def safe_extract(
print("Data downloaded to: {}".format(final_path))


def download_from_gdrive(gfile_url, file_name, out_dir=".", unzip=True, verbose=True):
"""Download a file shared via Google Drive
(e.g., https://drive.google.com/file/d/18SUo_HcDGltuWYZs1s7PpOmOq_FvFn04/view?usp=sharing)
Args:
gfile_url (str): The Google Drive shared file URL
file_name (str): The output file name to use.
out_dir (str, optional): The output directory. Defaults to '.'.
unzip (bool, optional): Whether to unzip the output file if it is a zip file. Defaults to True.
verbose (bool, optional): Whether to display or not the output of the function
"""
try:
from google_drive_downloader import GoogleDriveDownloader as gdd
except ImportError:
raise ImportError(
'Please install googledrivedownloader using "pip install googledrivedownloader"'
)

file_id = gfile_url.split("/")[5]
if verbose:
print("Google Drive file id: {}".format(file_id))

out_dir = check_dir(out_dir)
dest_path = os.path.join(out_dir, file_name)
gdd.download_file_from_google_drive(file_id, dest_path, True, unzip)


def create_download_link(filename, title="Click here to download: "):
"""Downloads a file from voila. Adopted from https://github.com/voila-dashboards/voila/issues/578
Expand Down Expand Up @@ -1813,7 +1786,7 @@ def get_api_key(name: Optional[str] = None, key: Optional[str] = None) -> Option
return key
elif name is not None:
if _in_colab_shell():
from google.colab import userdata
from google.colab import userdata # pylint: disable=E0611

try:
return userdata.get(name)
Expand Down Expand Up @@ -3278,8 +3251,8 @@ def html_to_streamlit(
"""

try:
import streamlit as st
import streamlit.components.v1 as components
import streamlit as st # pylint: disable=E0401
import streamlit.components.v1 as components # pylint: disable=E0401

if isinstance(html, str):
temp_path = None
Expand Down Expand Up @@ -5518,40 +5491,6 @@ def add_crs(filename, epsg):
src.crs = crs


def html_to_streamlit(
filename, width=None, height=None, scrolling=False, replace_dict={}
):
"""Renders an HTML file as a Streamlit component.
Args:
filename (str): The filename of the HTML file.
width (int, optional): Width of the map. Defaults to None.
height (int, optional): Height of the map. Defaults to 600.
scrolling (bool, optional): Whether to allow the map to scroll. Defaults to False.
replace_dict (dict, optional): A dictionary of strings to replace in the HTML file. Defaults to {}.
Raises:
ValueError: If the filename does not exist.
Returns:
streamlit.components: components.html object.
"""

import streamlit.components.v1 as components

if not os.path.exists(filename):
raise ValueError("filename must exist.")

f = open(filename, "r")

html = f.read()

for key, value in replace_dict.items():
html = html.replace(key, value)

f.close()
return components.html(html, width=width, height=height, scrolling=scrolling)


class The_national_map_USGS:
"""
The national map is a collection of topological datasets, maintained by the USGS.
Expand Down Expand Up @@ -6796,7 +6735,7 @@ async def download_file_lite(url, output=None, binary=False, overwrite=False, **
overwrite (bool, optional): Whether to overwrite the file if it exists. Defaults to False.
"""
import sys
import pyodide
import pyodide # pylint: disable=E0401

if "pyodide" not in sys.modules:
raise ValueError("Pyodide is not available.")
Expand Down Expand Up @@ -8261,7 +8200,7 @@ def arc_active_map():
arcpy.Map: The active map in ArcGIS Pro.
"""
if is_arcpy():
import arcpy
import arcpy # pylint: disable=E0401

aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
Expand All @@ -8277,7 +8216,7 @@ def arc_active_view():
arcpy.MapView: The active view in ArcGIS Pro.
"""
if is_arcpy():
import arcpy
import arcpy # pylint: disable=E0401

aprx = arcpy.mp.ArcGISProject("CURRENT")
view = aprx.activeView
Expand Down Expand Up @@ -8318,7 +8257,7 @@ def arc_zoom_to_extent(xmin, ymin, xmax, ymax):
ymax (float): The maximum y value of the extent.
"""
if is_arcpy():
import arcpy
import arcpy # pylint: disable=E0401

view = arc_active_view()
if view is not None:
Expand Down Expand Up @@ -9164,8 +9103,12 @@ def transform_bbox_coords(bbox, src_crs, dst_crs, **kwargs):
"""
x1, y1, x2, y2 = bbox

x1, y1 = transform_coords(x1, y1, src_crs, dst_crs, **kwargs)
x2, y2 = transform_coords(x2, y2, src_crs, dst_crs, **kwargs)
x1, y1 = transform_coords(
x1, y1, src_crs, dst_crs, **kwargs
) # pylint: disable=E0633
x2, y2 = transform_coords(
x2, y2, src_crs, dst_crs, **kwargs
) # pylint: disable=E0633

return [x1, y1, x2, y2]

Expand Down Expand Up @@ -9209,7 +9152,9 @@ def coords_to_xy(
width = src.width
height = src.height
if coord_crs != src.crs:
xs, ys = transform_coords(xs, ys, coord_crs, src.crs, **kwargs)
xs, ys = transform_coords(
xs, ys, coord_crs, src.crs, **kwargs
) # pylint: disable=E0633
rows, cols = rasterio.transform.rowcol(src.transform, xs, ys, **kwargs)
result = [[col, row] for col, row in zip(cols, rows)]

Expand Down Expand Up @@ -9830,26 +9775,6 @@ def pillow_local_file_to_base64(image: Image.Image, temp_dir: str):
display(HTML(htmlcode))


def display_html(filename, width="100%", height="600px", **kwargs):
"""Show an HTML file in a Jupyter notebook.
Args:
filename (str): The path to the HTML file.
width (str, optional): The width of the HTML file. Defaults to "100%".
height (str, optional): The height of the HTML file. Defaults to "600px".
Returns:
IFrame: An IFrame object.
"""

from IPython.display import IFrame

if not os.path.exists(filename):
raise Exception(f"File {filename} does not exist")

return IFrame(filename, width=width, height=height, **kwargs)


def get_nhd_basins(
feature_ids,
fsource="nwissite",
Expand Down Expand Up @@ -12800,14 +12725,20 @@ def gedi_subset(
"""

try:
import harmony
import harmony # pylint: disable=E0401
except ImportError:
install_package("harmony-py")

import requests as re
import geopandas as gpd
from datetime import datetime
from harmony import BBox, Client, Collection, Environment, Request
from harmony import (
BBox,
Client,
Collection,
Environment,
Request,
) # pylint: disable=E0401

if out_dir is None:
out_dir = os.getcwd()
Expand Down Expand Up @@ -13426,7 +13357,7 @@ def convert_coordinates(x, y, source_crs, target_crs="epsg:4326"):
transformer = pyproj.Transformer.from_crs(source_crs, target_crs, always_xy=True)

# Perform the transformation
lon, lat = transformer.transform(x, y)
lon, lat = transformer.transform(x, y) # pylint: disable=E0633

# Return the converted coordinates
return lon, lat
Expand Down Expand Up @@ -13823,55 +13754,6 @@ def github_get_release_id_by_tag(username, repository, tag_name, access_token=No
return None


def github_upload_asset_to_release(
username, repository, release_id, asset_path, access_token=None
):
"""
Uploads an asset to a GitHub release.
Args:
username (str): GitHub username or organization name.
repository (str): Name of the GitHub repository.
release_id (int): ID of the release to upload the asset to.
asset_path (str): Path to the asset file.
access_token (str): Personal access token for authentication.
Returns:
dict: The response JSON from the GitHub API if the upload is successful.
None: If the upload fails.
"""
if access_token is None:
access_token = get_api_key("GITHUB_API_TOKEN")
# GitHub API URL for uploading release assets
url = f"https://uploads.github.com/repos/{username}/{repository}/releases/{release_id}/assets"

# Extract the filename from the asset path
asset_name = os.path.basename(asset_path)

# Set the headers for the upload request
headers = {
"Authorization": f"token {access_token}",
"Content-Type": "application/octet-stream",
}

# Set the parameters for the upload request
params = {"name": asset_name}

# Open the asset file in binary mode
with open(asset_path, "rb") as asset_file:
# Make the request to upload the asset
response = requests.post(url, headers=headers, params=params, data=asset_file)

# Check if the request was successful
if response.status_code == 201:
print(f"Successfully uploaded asset: {asset_name}")
return response.json()
else:
print(f"Error: Unable to upload asset (Status code: {response.status_code})")
print(response.json())
return None


def github_get_release_assets(username, repository, release_id, access_token=None):
"""
Fetches the assets for a given release.
Expand Down
Loading

0 comments on commit a97892a

Please sign in to comment.