Skip to content

Commit

Permalink
Format backend with latest ruff (#10470)
Browse files Browse the repository at this point in the history
* format

* add changeset

* more ruff

* changes

* update

---------

Co-authored-by: gradio-pr-bot <[email protected]>
  • Loading branch information
abidlabs and gradio-pr-bot authored Jan 30, 2025
1 parent ef66fe5 commit 3465fdb
Show file tree
Hide file tree
Showing 16 changed files with 62 additions and 50 deletions.
6 changes: 6 additions & 0 deletions .changeset/dirty-ads-yell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"gradio": minor
"gradio_client": minor
---

feat:Format backend with latest `ruff`
4 changes: 2 additions & 2 deletions client/python/gradio_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,7 @@ def _render_endpoints_info(
default_value = info.get("parameter_default")
default_value = utils.traverse(
default_value,
lambda x: f"handle_file(\"{x['url']}\")",
lambda x: f'handle_file("{x["url"]}")',
utils.is_file_obj_with_meta,
)
default_info = (
Expand Down Expand Up @@ -996,7 +996,7 @@ def deploy_discord(
space_id = huggingface_hub.get_full_repo_name(to_id, token=hf_token)
else:
if self.space_id:
space_id = f'{self.space_id.split("/")[1]}-gradio-discord-bot'
space_id = f"{self.space_id.split('/')[1]}-gradio-discord-bot"
else:
space_id = f"gradio-discord-bot-{secrets.token_hex(4)}"
space_id = huggingface_hub.get_full_repo_name(space_id, token=hf_token)
Expand Down
4 changes: 2 additions & 2 deletions client/python/gradio_client/documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,13 +336,13 @@ def generate_documentation():
classes_inherit_documentation[cls] = cls_documentation["fns"]
for mode, class_list in classes_to_document.items():
for i, (cls, _) in enumerate(class_list):
for super_class in classes_inherit_documentation:
for super_class, fns in classes_inherit_documentation.items():
if (
inspect.isclass(cls)
and issubclass(cls, super_class)
and cls != super_class
):
for inherited_fn in classes_inherit_documentation[super_class]:
for inherited_fn in fns:
inherited_fn = dict(inherited_fn)
try:
inherited_fn["description"] = extract_instance_attr_doc(
Expand Down
3 changes: 1 addition & 2 deletions gradio/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2826,8 +2826,7 @@ def integrate(
)
else:
print(
"The WandB integration requires you to "
"`launch(share=True)` first."
"The WandB integration requires you to `launch(share=True)` first."
)
if mlflow is not None:
analytics_integration = "MLFlow"
Expand Down
38 changes: 22 additions & 16 deletions gradio/cli/commands/components/_docs_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,17 +689,21 @@ def render_class_docs(exports, docs):
### Initialization
\"\"\", elem_classes=["md-custom"], header_links=True)
gr.ParamViewer(value=_docs["{class_name}"]["members"]["__init__"], linkify={list(linkify.keys())})
gr.ParamViewer(value=_docs["{class_name}"]["members"]["__init__"], linkify={
list(linkify.keys())
})
{render_class_events(docs[class_name].get("events", None), class_name)}
{make_user_fn(
class_name,
user_fn_input_type,
user_fn_input_description,
user_fn_output_type,
user_fn_output_description,
)}
{
make_user_fn(
class_name,
user_fn_input_type,
user_fn_input_description,
user_fn_output_type,
user_fn_output_description,
)
}
"""
return docs_classes

Expand Down Expand Up @@ -752,7 +756,7 @@ def render_param_table(params):
</td>
<td align="left"><code>{param["default"]}</code></td>
<td align="left">{param['description']}</td>
<td align="left">{param["description"]}</td>
</tr>
"""
return table + "</tbody></table>"
Expand Down Expand Up @@ -783,12 +787,14 @@ def render_class_docs_markdown(exports, docs):
{render_class_events_markdown(docs[class_name].get("events", None))}
{make_user_fn_markdown(
user_fn_input_type,
user_fn_input_description,
user_fn_output_type,
user_fn_output_description,
)}
{
make_user_fn_markdown(
user_fn_input_type,
user_fn_input_description,
user_fn_output_type,
user_fn_output_description,
)
}
"""
return docs_classes

Expand Down Expand Up @@ -873,7 +879,7 @@ def make_space(
{docs_classes}
{render_additional_interfaces(docs["__meta__"]["additional_interfaces"])}
demo.load(None, js=r\"\"\"{make_js(get_deep(docs, ["__meta__", "additional_interfaces"]),get_deep( docs, ["__meta__", "user_fn_refs"]))}
demo.load(None, js=r\"\"\"{make_js(get_deep(docs, ["__meta__", "additional_interfaces"]), get_deep(docs, ["__meta__", "user_fn_refs"]))}
\"\"\")
demo.launch()
Expand Down
2 changes: 1 addition & 1 deletion gradio/components/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ async def combine_stream(
command = [
"ffmpeg",
"-i",
f'concat:{"|".join(ts_files)}',
f"concat:{'|'.join(ts_files)}",
"-y",
"-safe",
"0",
Expand Down
2 changes: 1 addition & 1 deletion gradio/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ def custom_post_binary(data):
elif p == "zero-shot-classification":
inputs = [
components.Textbox(label="Input"),
components.Textbox(label="Possible class names (" "comma-separated)"),
components.Textbox(label="Possible class names (comma-separated)"),
components.Checkbox(label="Allow multiple true classes"),
]
outputs = components.Label(label="Classification")
Expand Down
20 changes: 10 additions & 10 deletions gradio/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -809,18 +809,18 @@ def attach_clear_events(
None,
[],
([input_component_column] if input_component_column else []), # type: ignore
js=f"""() => {json.dumps(
[{'variant': None, 'visible': True, '__type__': 'update'}]
js=f"""() => {
json.dumps(
[{"variant": None, "visible": True, "__type__": "update"}]
if self.interface_type
in [
InterfaceTypes.STANDARD,
InterfaceTypes.INPUT_ONLY,
InterfaceTypes.UNIFIED,
]
in [
InterfaceTypes.STANDARD,
InterfaceTypes.INPUT_ONLY,
InterfaceTypes.UNIFIED,
]
else []
)}
)
}
""",
)

Expand Down
2 changes: 1 addition & 1 deletion gradio/processing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,7 @@ def _add_root_url(file_dict: dict):
file_dict["url"] = file_dict["url"][len(previous_root_url) :]
elif client_utils.is_http_url_like(file_dict["url"]):
return file_dict
file_dict["url"] = f'{root_url}{file_dict["url"]}'
file_dict["url"] = f"{root_url}{file_dict['url']}"
return file_dict

return client_utils.traverse(data, _add_root_url, client_utils.is_file_obj_with_url)
Expand Down
2 changes: 1 addition & 1 deletion gradio/route_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ def on_headers_finished(self) -> None:
)
except KeyError as e:
raise MultiPartException(
'The Content-Disposition header field "name" must be ' "provided."
'The Content-Disposition header field "name" must be provided.'
) from e
if b"filename" in options:
self._current_files += 1
Expand Down
8 changes: 4 additions & 4 deletions gradio/themes/builder_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,9 @@ def get_doc_theme_var_groups():
for variable in flat_variables:
if variable.endswith("_dark"):
continue
for style_type in variable_suggestions:
for style_type, suggestions in variable_suggestions.items():
if style_type in variable:
variable_suggestions[style_type].append("*" + variable)
suggestions.append("*" + variable)
break

variable_suggestions["fill"], variable_suggestions["color"] = (
Expand Down Expand Up @@ -676,7 +676,7 @@ def generate_theme_code(
for var_name in core_var_names:
if var_name in specific_core_diffs:
cls, vals = specific_core_diffs[var_name]
core_diffs_code += f""" {var_name}=gr.themes.{cls.__name__}({', '.join(f'''{k}="{v}"''' for k, v in vals.items())}),\n"""
core_diffs_code += f""" {var_name}=gr.themes.{cls.__name__}({", ".join(f'''{k}="{v}"''' for k, v in vals.items())}),\n"""
elif var_name in core_diffs:
var_val = core_diffs[var_name]
if var_name.endswith("_size"):
Expand Down Expand Up @@ -706,7 +706,7 @@ def generate_theme_code(
vars_diff_code = ""
if len(var_diffs) > 0:
vars_diff_code = f""".set(
{(',' + newline + " ").join([f"{k}='{v}'" for k, v in var_diffs.items()])}
{("," + newline + " ").join([f"{k}='{v}'" for k, v in var_diffs.items()])}
)"""

output = f"""
Expand Down
2 changes: 1 addition & 1 deletion gradio/themes/utils/fonts.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def __init__(self, name: str, weights: Iterable[int] = (400, 600)):
self.weights = weights

def stylesheet(self) -> dict:
url = f'https://fonts.googleapis.com/css2?family={self.name.replace(" ", "+")}:wght@{";".join(str(weight) for weight in self.weights)}&display=swap'
url = f"https://fonts.googleapis.com/css2?family={self.name.replace(' ', '+')}:wght@{';'.join(str(weight) for weight in self.weights)}&display=swap"
return {"url": url, "css": None}


Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ ignore = [
"PLR2004", # magic numbers
"PLW2901", # `for` loop variable overwritten by assignment target
"SIM105", # contextlib.suppress (has a performance cost)
"SIM115", # contextlib.suppress (has a performance cost)
"SIM117", # multiple nested with blocks (doesn't look good with gr.Row etc)
"UP006", # use `list` instead of `List` for type annotations (fails for 3.8)
"UP007", # use X | Y for type annotations (TODO: can be enabled once Pydantic plays nice with them)
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pydantic>=2.0
python-multipart>=0.0.18 # required for fastapi forms.
pydub
pyyaml>=5.0,<7.0
ruff>=0.2.2; sys.platform != 'emscripten'
ruff>=0.9.3; sys.platform != 'emscripten' # needed here for custom component docs generation
safehttpx>=0.1.6,<0.2.0
semantic_version~=2.0
starlette>=0.40.0,<1.0; sys.platform != 'emscripten'
Expand Down
2 changes: 1 addition & 1 deletion scripts/lint_backend.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@

cd "$(dirname ${0})/.."
python -c "import gradio"
python -m ruff gradio test client
python -m ruff check gradio test client
python -m ruff format --check gradio test client
14 changes: 7 additions & 7 deletions test/test_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1160,16 +1160,16 @@ class TestShowAPI:
@patch.object(wasm_utils, "IS_WASM", True)
def test_show_api_false_when_is_wasm_true(self):
interface = Interface(lambda x: x, "text", "text", examples=[["hannah"]])
assert (
interface.show_api is False
), "show_api should be False when IS_WASM is True"
assert interface.show_api is False, (
"show_api should be False when IS_WASM is True"
)

@patch.object(wasm_utils, "IS_WASM", False)
def test_show_api_true_when_is_wasm_false(self):
interface = Interface(lambda x: x, "text", "text", examples=[["hannah"]])
assert (
interface.show_api is True
), "show_api should be True when IS_WASM is False"
assert interface.show_api is True, (
"show_api should be True when IS_WASM is False"
)


def test_component_server_endpoints(connect):
Expand Down Expand Up @@ -1344,7 +1344,7 @@ def fn_1(x):
def fn_2(x):
for i in range(len(x)):
time.sleep(0.5)
yield f"Hello, {x[:i+1]}!"
yield f"Hello, {x[: i + 1]}!"
if len(x) < 3:
raise ValueError("Small input")

Expand Down

0 comments on commit 3465fdb

Please sign in to comment.