Skip to content

Commit

Permalink
Reverts the revert that dropped changes from 2 PRs (#7495)
Browse files Browse the repository at this point in the history
* Revert "Revert "changes""

This reverts commit 0324353.

* patch
  • Loading branch information
abidlabs authored Feb 21, 2024
1 parent 254c7dc commit ddd4d3e
Show file tree
Hide file tree
Showing 37 changed files with 150 additions and 77 deletions.
6 changes: 6 additions & 0 deletions .changeset/dirty-carrots-care.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"gradio": patch
"gradio_client": patch
---

feat:Enable Ruff S101
6 changes: 6 additions & 0 deletions .changeset/spicy-zebras-lay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@gradio/dataframe": patch
"gradio": patch
---

fix:ensure Dataframe headers are aligned with content when scrolling
3 changes: 2 additions & 1 deletion client/python/gradio_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,8 @@ def _download_file(
file_name = utils.decode_base64_to_file(x, dir=save_dir).name
elif isinstance(x, dict):
filepath = x.get("path")
assert filepath is not None, f"The 'path' field is missing in {x}"
if not filepath:
raise ValueError(f"The 'path' field is missing in {x}")
file_name = utils.download_file(
root_url + "file=" + filepath,
hf_token=hf_token,
Expand Down
11 changes: 7 additions & 4 deletions client/python/gradio_client/documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,12 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]:
if "args" in parameter_doc["doc"]:
parameter_doc["args"] = True
parameter_docs.append(parameter_doc)
assert (
len(parameters) == 0
), f"Documentation format for {fn.__name__} documents nonexistent parameters: {', '.join(parameters.keys())}. Valid parameters: {', '.join(signature.parameters.keys())}"
if parameters:
raise ValueError(
f"Documentation format for {fn.__name__} documents "
f"nonexistent parameters: {', '.join(parameters.keys())}. "
f"Valid parameters: {', '.join(signature.parameters.keys())}"
)
if len(returns) == 0:
return_docs = {}
elif len(returns) == 1:
Expand Down Expand Up @@ -337,7 +340,7 @@ def generate_documentation():
inherited_fn["description"] = extract_instance_attr_doc(
cls, inherited_fn["name"]
)
except (ValueError, AssertionError):
except ValueError:
pass
documentation[mode][i]["fns"].append(inherited_fn)
return documentation
5 changes: 4 additions & 1 deletion client/python/gradio_client/serializing.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,10 @@ def _deserialize_single(
else:
file_name = utils.create_tmp_copy_of_file(filepath, dir=save_dir)
elif x.get("is_stream"):
assert x["name"] and root_url and save_dir
if not (x["name"] and root_url and save_dir):
raise ValueError(
"name and root_url and save_dir must all be present"
)
if not self.stream or self.stream_name != x["name"]:
self.stream = self._setup_stream(
root_url + "stream/" + x["name"], hf_token=hf_token
Expand Down
6 changes: 4 additions & 2 deletions client/python/gradio_client/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,8 @@ async def get_pred_from_sse_v0(
except asyncio.CancelledError:
pass

assert len(done) == 1
if len(done) != 1:
raise ValueError(f"Did not expect {len(done)} tasks to be done.")
for task in done:
return task.result()

Expand Down Expand Up @@ -407,7 +408,8 @@ async def get_pred_from_sse_v1_v2(
except asyncio.CancelledError:
pass

assert len(done) == 1
if len(done) != 1:
raise ValueError(f"Did not expect {len(done)} tasks to be done.")
for task in done:
exception = task.exception()
if exception:
Expand Down
4 changes: 2 additions & 2 deletions client/python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ include = [
[tool.ruff]
extend = "../../pyproject.toml"

[tool.ruff.isort]
[tool.ruff.lint.isort]
known-first-party = [
"gradio_client"
]

[tool.pytest.ini_options]
GRADIO_ANALYTICS_ENABLED = "False"
HF_HUB_DISABLE_TELEMETRY = "1"
HF_HUB_DISABLE_TELEMETRY = "1"
2 changes: 1 addition & 1 deletion client/python/test/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pytest-asyncio
pytest==7.1.2
ruff==0.1.13
ruff==0.2.2
pyright==1.1.327
gradio
pydub==0.25.1
9 changes: 6 additions & 3 deletions gradio/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,8 @@ def __init__(

def get_component(self, id: int) -> Component | BlockContext:
comp = self.blocks[id]
assert isinstance(comp, (components.Component, BlockContext)), f"{comp}"
if not isinstance(comp, (components.Component, BlockContext)):
raise TypeError(f"Block with id {id} is not a Component or BlockContext")
return comp

@property
Expand Down Expand Up @@ -2379,7 +2380,8 @@ def get_api_info(self):
continue
label = component["props"].get("label", f"parameter_{i}")
comp = self.get_component(component["id"])
assert isinstance(comp, components.Component)
if not isinstance(comp, components.Component):
raise TypeError(f"{comp!r} is not a Component")
info = component["api_info"]
example = comp.example_inputs()
python_type = client_utils.json_schema_to_python_type(info)
Expand Down Expand Up @@ -2409,7 +2411,8 @@ def get_api_info(self):
continue
label = component["props"].get("label", f"value_{o}")
comp = self.get_component(component["id"])
assert isinstance(comp, components.Component)
if not isinstance(comp, components.Component):
raise TypeError(f"{comp!r} is not a Component")
info = component["api_info"]
example = comp.example_inputs()
python_type = client_utils.json_schema_to_python_type(info)
Expand Down
5 changes: 4 additions & 1 deletion gradio/chat_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,10 @@ def __init__(
textbox.container = False
textbox.show_label = False
textbox_ = textbox.render()
assert isinstance(textbox_, Textbox)
if not isinstance(textbox_, Textbox):
raise TypeError(
f"Expected a gr.Textbox, but got {type(textbox_)}"
)
self.textbox = textbox_
else:
self.textbox = Textbox(
Expand Down
4 changes: 3 additions & 1 deletion gradio/cli/commands/components/_create_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,9 @@ def find_template_in_list(template, list_to_search):
"Please pass in a valid component name via the --template option. It must match the name of the python class."
)

if not module:
raise ValueError("Module not found")

readme_contents = textwrap.dedent(
"""
# {package_name}
Expand Down Expand Up @@ -381,7 +384,6 @@ def find_template_in_list(template, list_to_search):

p = Path(inspect.getfile(gradio)).parent
python_file = backend / f"{name.lower()}.py"
assert module is not None

shutil.copy(
str(p / module / component.python_file_name),
Expand Down
3 changes: 2 additions & 1 deletion gradio/cli/commands/components/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,8 @@ def _publish(
except Exception:
latest_release = None

assert demo_dir
if not demo_dir:
raise ValueError("demo_dir must be set")
demo_path = resolve_demo(demo_dir)

if prefer_local or not latest_release:
Expand Down
8 changes: 5 additions & 3 deletions gradio/component_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ def extract_class_source_code(
for node in ast.walk(class_ast):
if isinstance(node, ast.ClassDef) and node.name == class_name:
segment = ast.get_source_segment(code, node)
assert segment
if not segment:
raise ValueError("segment not found")
return segment, node.lineno
return None, None

Expand All @@ -92,8 +93,9 @@ def create_or_modify_pyi(

current_impl, lineno = extract_class_source_code(source_code, class_name)

assert current_impl
assert lineno
if not (current_impl and lineno):
raise ValueError("Couldn't find class source code")

new_interface = create_pyi(current_impl, events)

pyi_file = source_file.with_suffix(".pyi")
Expand Down
4 changes: 3 additions & 1 deletion gradio/components/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,9 @@ def preprocess(
if payload is None:
return payload

assert payload.path
if not payload.path:
raise ValueError("payload path missing")

# Need a unique name for the file to avoid re-using the same audio file if
# a user submits the same audio file twice
temp_file_path = Path(payload.path)
Expand Down
8 changes: 6 additions & 2 deletions gradio/components/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,8 @@ def component(cls_name: str, render: bool) -> Component:
obj = utils.component_or_layout_class(cls_name)(render=render)
if isinstance(obj, BlockContext):
raise ValueError(f"Invalid component: {obj.__class__}")
assert isinstance(obj, Component)
if not isinstance(obj, Component):
raise TypeError(f"Expected a Component instance, but got {obj.__class__}")
return obj


Expand Down Expand Up @@ -363,5 +364,8 @@ def get_component_instance(
component_obj.render()
elif unrender and component_obj.is_rendered:
component_obj.unrender()
assert isinstance(component_obj, Component)
if not isinstance(component_obj, Component):
raise TypeError(
f"Expected a Component instance, but got {component_obj.__class__}"
)
return component_obj
7 changes: 4 additions & 3 deletions gradio/components/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,10 @@ def __init__(
]

# Narrow type to Component
assert all(
isinstance(c, Component) for c in self._components
), "All components in a `Dataset` must be subclasses of `Component`"
if not all(isinstance(c, Component) for c in self._components):
raise TypeError(
"All components in a `Dataset` must be subclasses of `Component`"
)
self._components = [c for c in self._components if isinstance(c, Component)]
self.proxy_url = proxy_url
for component in self._components:
Expand Down
3 changes: 2 additions & 1 deletion gradio/components/dropdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ def preprocess(
if payload is None:
return None
elif self.multiselect:
assert isinstance(payload, list)
if not isinstance(payload, list):
raise TypeError("Multiselect dropdown payload must be a list")
return [
choice_values.index(choice) if choice in choice_values else None
for choice in payload
Expand Down
6 changes: 4 additions & 2 deletions gradio/components/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,8 @@ def preprocess(self, payload: VideoData | None) -> str | None:
"""
if payload is None:
return None
assert payload.video.path
if not payload.video.path:
raise ValueError("Payload path missing")
file_name = Path(payload.video.path)
uploaded_format = file_name.suffix.replace(".", "")
needs_formatting = self.format is not None and uploaded_format != self.format
Expand Down Expand Up @@ -257,7 +258,8 @@ def postprocess(

else:
raise Exception(f"Cannot process type as video: {type(value)}")
assert processed_files[0]
if not processed_files[0]:
raise ValueError("Video data missing")
return VideoData(video=processed_files[0], subtitles=processed_files[1])

def _format_video(self, video: str | Path | None) -> FileData | None:
Expand Down
9 changes: 5 additions & 4 deletions gradio/data_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,9 @@ class LogMessage(BaseModel):

class GradioBaseModel(ABC):
def copy_to_dir(self, dir: str | pathlib.Path) -> GradioDataModel:
assert isinstance(self, (BaseModel, RootModel))
if isinstance(dir, str):
dir = pathlib.Path(dir)
if not isinstance(self, (BaseModel, RootModel)):
raise TypeError("must be used in a Pydantic model")
dir = pathlib.Path(dir)

# TODO: Making sure path is unique should be done in caller
def unique_copy(obj: dict):
Expand Down Expand Up @@ -204,7 +204,8 @@ def _copy_to_dir(self, dir: str) -> FileData:
pathlib.Path(dir).mkdir(exist_ok=True)
new_obj = dict(self)

assert self.path
if not self.path:
raise ValueError("Source file path is not set")
new_name = shutil.copy(self.path, dir)
new_obj["path"] = new_name
return self.__class__(**new_obj)
Expand Down
5 changes: 4 additions & 1 deletion gradio/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,10 @@ def from_spaces_blocks(space: str, hf_token: str | None) -> Blocks:
# Use end_to_end_fn here to properly upload/download all files
predict_fns = []
for fn_index, endpoint in enumerate(client.endpoints):
assert isinstance(endpoint, Endpoint)
if not isinstance(endpoint, Endpoint):
raise TypeError(
f"Expected endpoint to be an Endpoint, but got {type(endpoint)}"
)
helper = client.new_helper(fn_index)
if endpoint.backend_fn:
predict_fns.append(endpoint.make_end_to_end_fn(helper))
Expand Down
5 changes: 3 additions & 2 deletions gradio/external_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,9 @@ def tabular_wrapper(client: InferenceClient, pipeline: str):
# automatically loaded when using the tabular_classification and tabular_regression methods.
# See: https://github.com/huggingface/huggingface_hub/issues/2015
def tabular_inner(data):
assert pipeline in ["tabular_classification", "tabular_regression"]
assert client.model is not None
if pipeline not in ("tabular_classification", "tabular_regression"):
raise TypeError(f"pipeline type {pipeline!r} not supported")
assert client.model # noqa: S101
if pipeline == "tabular_classification":
return client.tabular_classification(data, model=client.model)
else:
Expand Down
8 changes: 5 additions & 3 deletions gradio/flagging.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,9 +421,11 @@ def _deserialize_components(
# Add deserialized object to row
features[label] = {"dtype": "string", "_type": "Value"}
try:
assert Path(deserialized).exists()
row.append(str(Path(deserialized).relative_to(self.dataset_dir)))
except (AssertionError, TypeError, ValueError):
deserialized_path = Path(deserialized)
if not deserialized_path.exists():
raise FileNotFoundError(f"File {deserialized} not found")
row.append(str(deserialized_path.relative_to(self.dataset_dir)))
except (FileNotFoundError, TypeError, ValueError):
deserialized = "" if deserialized is None else str(deserialized)
row.append(deserialized)

Expand Down
18 changes: 10 additions & 8 deletions gradio/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,8 @@ async def get_final_item(*args):
batch=self.batch,
)

assert self.outputs is not None
if self.outputs is None:
raise ValueError("self.outputs is missing")
cache_logger.setup(self.outputs, self.cached_folder)
for example_id, _ in enumerate(self.examples):
print(f"Caching example {example_id + 1}/{len(self.examples)}")
Expand Down Expand Up @@ -405,7 +406,8 @@ def load_from_cache(self, example_id: int) -> list[Any]:
examples = list(csv.reader(cache))
example = examples[example_id + 1] # +1 to adjust for header
output = []
assert self.outputs is not None
if self.outputs is None:
raise ValueError("self.outputs is missing")
for component, value in zip(self.outputs, example):
value_to_use = value
try:
Expand All @@ -417,9 +419,10 @@ def load_from_cache(self, example_id: int) -> list[Any]:
component, components.File
):
value_to_use = value_as_dict
assert utils.is_update(value_as_dict)
if not utils.is_update(value_as_dict):
raise TypeError("value wasn't an update") # caught below
output.append(value_as_dict)
except (ValueError, TypeError, SyntaxError, AssertionError):
except (ValueError, TypeError, SyntaxError):
output.append(component.read_from_flag(value_to_use))
return output

Expand Down Expand Up @@ -784,9 +787,7 @@ def special_args(

# Inject user token
elif type_hint in (Optional[oauth.OAuthToken], oauth.OAuthToken):
oauth_info = (
session["oauth_info"] if "oauth_info" in session else None
)
oauth_info = session.get("oauth_info", None)
oauth_token = (
oauth.OAuthToken(
token=oauth_info["access_token"],
Expand Down Expand Up @@ -912,7 +913,8 @@ def hex_to_rgb(hex_str):
return [int(hex_str[i : i + 2], 16) for i in range(1, 6, 2)]

def get_color_gradient(c1, c2, n):
assert n > 1
if n < 1:
raise ValueError("Must have at least one stop in gradient")
c1_rgb = np.array(hex_to_rgb(c1)) / 255
c2_rgb = np.array(hex_to_rgb(c2)) / 255
mix_pcts = [x / (n - 1) for x in range(n)]
Expand Down
Loading

0 comments on commit ddd4d3e

Please sign in to comment.