Skip to content

Commit

Permalink
switch from black to ruff formatter (#6543)
Browse files Browse the repository at this point in the history
* migrate from black to ruff

* fix script and dependencies

* applying ruff

* add changeset

* add changeset

* address ruff feedback

* replace linter

* fixed typing

* fix typing

---------

Co-authored-by: Abubakar Abid <[email protected]>
Co-authored-by: gradio-pr-bot <[email protected]>
  • Loading branch information
3 people authored Dec 6, 2023
1 parent 5d5ab8c commit 8a70e83
Show file tree
Hide file tree
Showing 38 changed files with 120 additions and 124 deletions.
6 changes: 6 additions & 0 deletions .changeset/wise-feet-fold.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"gradio": patch
"gradio_client": patch
---

feat:switch from black to ruff formatter
5 changes: 4 additions & 1 deletion client/python/gradio_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -780,7 +780,10 @@ def deploy_discord(
)
if is_private:
huggingface_hub.add_space_secret(
space_id, "HF_TOKEN", hf_token, token=hf_token # type: ignore
space_id,
"HF_TOKEN",
hf_token, # type: ignore
token=hf_token,
)

url = f"https://huggingface.co/spaces/{space_id}"
Expand Down
2 changes: 1 addition & 1 deletion client/python/gradio_client/documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]:
del parameters[param_name]
if param.default != inspect.Parameter.empty:
default = param.default
if type(default) == str:
if isinstance(default, str):
default = '"' + default + '"'
if default.__class__.__module__ != "builtins":
default = f"{default.__class__.__name__}()"
Expand Down
4 changes: 2 additions & 2 deletions client/python/scripts/format.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

cd "$(dirname ${0})/.."

echo "Formatting the client library.. Our style follows the Black code style."
echo "Formatting the client library.. Our style follows the ruff code style."
python -m ruff --fix .
python -m black .
python -m ruff format .

echo "Type checking the client library with pyright"
python -m pyright gradio_client/*.py
2 changes: 1 addition & 1 deletion client/python/scripts/lint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ cd "$(dirname ${0})/.."

echo "Linting..."
python -m ruff test gradio_client
python -m black --check test gradio_client
python -m ruff format --check test gradio_client

echo "Type checking the client library with pyright"
python -m pyright gradio_client/*.py
3 changes: 1 addition & 2 deletions client/python/test/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
black==23.3.0
pytest-asyncio
pytest==7.1.2
ruff==0.0.264
ruff==0.1.7
pyright==1.1.327
gradio
pydub==0.25.1
2 changes: 1 addition & 1 deletion client/python/test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def test_strip_invalid_filename_characters(orig_filename, new_filename):

class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
return super().__call__(*args, **kwargs)


@pytest.mark.asyncio
Expand Down
10 changes: 7 additions & 3 deletions gradio/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1311,7 +1311,7 @@ def validate_outputs(self, fn_index: int, predictions: Any | list[Any]):

dep_outputs = dependency["outputs"]

if type(predictions) is not list and type(predictions) is not tuple:
if not isinstance(predictions, (list, tuple)):
predictions = [predictions]

if len(predictions) < len(dep_outputs):
Expand Down Expand Up @@ -1349,7 +1349,7 @@ def postprocess_data(
dependency = self.dependencies[fn_index]
batch = dependency["batch"]

if type(predictions) is dict and len(predictions) > 0:
if isinstance(predictions, dict) and len(predictions) > 0:
predictions = convert_component_dict_to_list(
dependency["outputs"], predictions
)
Expand Down Expand Up @@ -1418,7 +1418,11 @@ def postprocess_data(
f"{block.__class__} Component with id {output_id} not a valid output component."
)
prediction_value = block.postprocess(prediction_value)
outputs_cached = processing_utils.move_files_to_cache(prediction_value, block, postprocess=True) # type: ignore
outputs_cached = processing_utils.move_files_to_cache(
prediction_value,
block, # type: ignore
postprocess=True,
)
output.append(outputs_cached)

return output
Expand Down
3 changes: 2 additions & 1 deletion gradio/chat_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ def __init__(
if not isinstance(additional_inputs, list):
additional_inputs = [additional_inputs]
self.additional_inputs = [
get_component_instance(i) for i in additional_inputs # type: ignore
get_component_instance(i)
for i in additional_inputs # type: ignore
]
else:
self.additional_inputs = []
Expand Down
4 changes: 3 additions & 1 deletion gradio/cli/commands/components/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ def _build(
pyproject_toml = parse((path / "pyproject.toml").read_text())
if bump_version:
pyproject_toml = parse((path / "pyproject.toml").read_text())
version = semantic_version.Version(pyproject_toml["project"]["version"]).next_patch() # type: ignore
version = semantic_version.Version(
pyproject_toml["project"]["version"] # type: ignore
).next_patch()
live.update(
f":1234: Using version [bold][magenta]{version}[/][/]. "
"Set [bold][magenta]--no-bump-version[/][/] to use the version in pyproject.toml file."
Expand Down
4 changes: 3 additions & 1 deletion gradio/cli/commands/components/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ def _create(
print(
f":snake: Using requires-python of [bold][magenta]{requires_python}[/][/]"
)
pyproject_toml["project"]["requires-python"] = requires_python or ">=3.8" # type: ignore
pyproject_toml["project"]["requires-python"] = ( # type: ignore
requires_python or ">=3.8"
)

keywords = []
print(
Expand Down
3 changes: 1 addition & 2 deletions gradio/cli/commands/components/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ def _dev(
typer.Argument(
help="The path to the app. By default, looks for demo/app.py in the current directory."
),
] = Path("demo")
/ "app.py",
] = Path("demo") / "app.py",
component_directory: Annotated[
Path,
typer.Option(
Expand Down
3 changes: 1 addition & 2 deletions gradio/cli/commands/components/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ def _publish(
dist_dir: Annotated[
Path,
Argument(help=f"Path to the wheel directory. Default is {Path('.') / 'dist'}"),
] = Path(".")
/ "dist",
] = Path(".") / "dist",
bump_version: Annotated[
bool, Option(help="Whether to bump the version number.")
] = True,
Expand Down
2 changes: 1 addition & 1 deletion gradio/components/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ def __extract_metadata(df: Styler) -> dict[str, list[list]]:
def __process_counts(count, default=3) -> tuple[int, str]:
if count is None:
return (default, "dynamic")
if type(count) == int or type(count) == float:
if isinstance(count, (int, float)):
return (int(count), "dynamic")
else:
return count
Expand Down
11 changes: 9 additions & 2 deletions gradio/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,9 +415,16 @@ def inner(*args, **kwargs):
if Context.root_block is None:
raise Exception("Cannot call on() outside of a gradio.Blocks context.")
if triggers is None:
triggers = [EventListenerMethod(input, "change") for input in inputs] if inputs is not None else [] # type: ignore
triggers = (
[EventListenerMethod(input, "change") for input in inputs]
if inputs is not None
else []
) # type: ignore
else:
triggers = [EventListenerMethod(t.__self__ if t.has_trigger else None, t.event_name) for t in triggers] # type: ignore
triggers = [
EventListenerMethod(t.__self__ if t.has_trigger else None, t.event_name)
for t in triggers
] # type: ignore
dep, dep_index = Context.root_block.set_event_trigger(
triggers,
fn,
Expand Down
14 changes: 10 additions & 4 deletions gradio/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,14 @@ def from_model(model_name: str, hf_token: str | None, alias: str | None, **kwarg
"postprocess": lambda r: r.json()["text"],
},
"conversational": {
"inputs": [components.Textbox(render=False), components.State(render=False)], # type: ignore
"outputs": [components.Chatbot(render=False), components.State(render=False)], # type: ignore
"inputs": [
components.Textbox(render=False),
components.State(render=False),
], # type: ignore
"outputs": [
components.Chatbot(render=False),
components.State(render=False),
], # type: ignore
"preprocess": chatbot_preprocess,
"postprocess": chatbot_postprocess,
},
Expand Down Expand Up @@ -570,8 +576,8 @@ def fn(*data):
len(config["outputs"]) == 1
): # if the fn is supposed to return a single value, pop it
output = output[0]
if len(config["outputs"]) == 1 and isinstance(
output, list
if (
len(config["outputs"]) == 1 and isinstance(output, list)
): # Needed to support Output.Image() returning bounding boxes as well (TODO: handle different versions of gradio since they have slightly different APIs)
output = output[0]
return output
Expand Down
2 changes: 1 addition & 1 deletion gradio/external_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def get_tabular_examples(model_name: str) -> Dict[str, List[float]]:


def cols_to_rows(
example_data: Dict[str, List[float]]
example_data: Dict[str, List[float]],
) -> Tuple[List[str], List[List[float]]]:
headers = list(example_data.keys())
n_rows = max(len(example_data[header] or []) for header in headers)
Expand Down
4 changes: 1 addition & 3 deletions gradio/flagging.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,9 +439,7 @@ def _deserialize_components(
if deserialized:
path_in_repo = str( # returned filepath is absolute, we want it relative to compute URL
Path(deserialized).relative_to(self.dataset_dir)
).replace(
"\\", "/"
)
).replace("\\", "/")
row.append(
huggingface_hub.hf_hub_url(
repo_id=self.dataset_id,
Expand Down
3 changes: 1 addition & 2 deletions gradio/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,8 +756,7 @@ def special_args(
if inputs is not None:
inputs.insert(i, request)
elif (
type_hint == Optional[oauth.OAuthProfile]
or type_hint == oauth.OAuthProfile
type_hint == Optional[oauth.OAuthProfile] or type_hint == oauth.OAuthProfile
# Note: "OAuthProfile | None" is equals to Optional[OAuthProfile] in Python
# => it is automatically handled as well by the above condition
# (adding explicit "OAuthProfile | None" would break in Python3.9)
Expand Down
14 changes: 11 additions & 3 deletions gradio/image_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,18 @@ def format_image(
elif type == "filepath":
try:
path = processing_utils.save_pil_to_cache(
im, cache_dir=cache_dir, name=name, format=fmt or format # type: ignore
im,
cache_dir=cache_dir,
name=name,
format=fmt or format, # type: ignore
)
# Catch error if format is not supported by PIL
except (KeyError, ValueError):
path = processing_utils.save_pil_to_cache(
im, cache_dir=cache_dir, name=name, format="png" # type: ignore
im,
cache_dir=cache_dir,
name=name,
format="png", # type: ignore
)
return path
else:
Expand All @@ -54,7 +60,9 @@ def save_image(y: np.ndarray | _Image.Image | str | Path, cache_dir: str):
fmt = y.format
try:
path = processing_utils.save_pil_to_cache(
y, cache_dir=cache_dir, format=fmt # type: ignore
y,
cache_dir=cache_dir,
format=fmt, # type: ignore
)
# Catch error if format is not supported by PIL
except (KeyError, ValueError):
Expand Down
13 changes: 7 additions & 6 deletions gradio/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,12 @@ def __init__(
self.cache_examples = False

self.input_components = [
get_component_instance(i, unrender=True) for i in inputs # type: ignore
get_component_instance(i, unrender=True)
for i in inputs # type: ignore
]
self.output_components = [
get_component_instance(o, unrender=True) for o in outputs # type: ignore
get_component_instance(o, unrender=True)
for o in outputs # type: ignore
]

for component in self.input_components + self.output_components:
Expand Down Expand Up @@ -355,7 +357,8 @@ def __init__(
pass
else:
self.flagging_callback.setup(
self.input_components + self.output_components, self.flagging_dir # type: ignore
self.input_components + self.output_components,
self.flagging_dir, # type: ignore
)

# Render the Gradio UI
Expand Down Expand Up @@ -649,9 +652,7 @@ def attach_clear_events(
clear_btn.click(
None,
[],
(
[input_component_column] if input_component_column else []
), # type: ignore
([input_component_column] if input_component_column else []), # type: ignore
js=f"""() => {json.dumps(
[{'variant': None, 'visible': True, '__type__': 'update'}]
Expand Down
3 changes: 2 additions & 1 deletion gradio/pipelines.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ def load_from_pipeline(pipeline: pipelines.base.Pipeline) -> dict:
"postprocess": lambda r: {i["answer"]: i["score"] for i in r},
}
elif hasattr(transformers, "ImageToTextPipeline") and isinstance(
pipeline, pipelines.image_to_text.ImageToTextPipeline # type: ignore
pipeline,
pipelines.image_to_text.ImageToTextPipeline, # type: ignore
):
pipeline_info = {
"inputs": components.Image(
Expand Down
8 changes: 6 additions & 2 deletions gradio/processing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,9 @@ def _scale(a, n, m, copy=True):
image_out = np.multiply(image, imax_out, dtype=computation_type) # type: ignore
else:
image_out = np.multiply(
image, (imax_out - imin_out) / 2, dtype=computation_type # type: ignore
image,
(imax_out - imin_out) / 2, # type: ignore
dtype=computation_type,
)
image_out -= 1.0 / 2.0
np.rint(image_out, out=image_out)
Expand All @@ -607,7 +609,9 @@ def _scale(a, n, m, copy=True):
np.clip(image_out, 0, imax_out, out=image_out) # type: ignore
else:
image_out = np.multiply(
image, (imax_out - imin_out + 1.0) / 2.0, dtype=computation_type # type: ignore
image,
(imax_out - imin_out + 1.0) / 2.0, # type: ignore
dtype=computation_type,
)
np.floor(image_out, out=image_out)
np.clip(image_out, imin_out, imax_out, out=image_out) # type: ignore
Expand Down
6 changes: 4 additions & 2 deletions gradio/route_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,9 @@ def on_part_data(self, data: bytes, start: int, end: int) -> None:
message_bytes = data[start:end]
if self.upload_progress is not None:
self.upload_progress.update(
self.upload_id, self._current_part.file.filename, message_bytes # type: ignore
self.upload_id, # type: ignore
self._current_part.file.filename, # type: ignore
message_bytes,
)
if self._current_part.file is None:
self._current_part.data += message_bytes
Expand Down Expand Up @@ -463,7 +465,7 @@ async def parse(self) -> FormData:
# Parse the Content-Type header to get the multipart boundary.
_, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if type(charset) == bytes:
if isinstance(charset, bytes):
charset = charset.decode("latin-1")
self._charset = charset
try:
Expand Down
3 changes: 1 addition & 2 deletions gradio/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,7 @@ def __init__(
self,
value: str | tuple[int, np.ndarray] | Callable | None = None,
*,
sources: list[Literal["upload", "microphone"]]
| None = ["microphone"], # noqa: B006
sources: list[Literal["upload", "microphone"]] | None = ["microphone"], # noqa: B006
type: Literal["numpy", "filepath"] = "numpy",
label: str | None = None,
show_label: bool = True,
Expand Down
8 changes: 2 additions & 6 deletions gradio/themes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,17 +328,13 @@ def __init__(
text_size: sizes.Size | str = sizes.text_md,
spacing_size: sizes.Size | str = sizes.spacing_md,
radius_size: sizes.Size | str = sizes.radius_md,
font: fonts.Font
| str
| Iterable[fonts.Font | str] = (
font: fonts.Font | str | Iterable[fonts.Font | str] = (
fonts.GoogleFont("Source Sans Pro"),
"ui-sans-serif",
"system-ui",
"sans-serif",
),
font_mono: fonts.Font
| str
| Iterable[fonts.Font | str] = (
font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
fonts.GoogleFont("IBM Plex Mono"),
"ui-monospace",
"Consolas",
Expand Down
Loading

0 comments on commit 8a70e83

Please sign in to comment.