Skip to content

Commit 3f19210

Browse files
dustalovgradio-pr-botfreddyaboultonabidlabs
authored
Declare exports in __all__ for type checking (#10238)
* Declare exports * add changeset * type fixes * more type fixes * add changeset * notebooks * changes --------- Co-authored-by: gradio-pr-bot <[email protected]> Co-authored-by: Freddy Boulton <[email protected]> Co-authored-by: Abubakar Abid <[email protected]>
1 parent f0cf3b7 commit 3f19210

File tree

14 files changed

+144
-23
lines changed

14 files changed

+144
-23
lines changed

.changeset/young-geckos-brake.md

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"gradio": patch
3+
"gradio_client": patch
4+
---
5+
6+
fix:Declare exports in __all__ for type checking

client/python/gradio_client/client.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1356,8 +1356,8 @@ def _upload_file(self, f: dict, data_index: int) -> dict[str, str]:
13561356
f"File {file_path} exceeds the maximum file size of {max_file_size} bytes "
13571357
f"set in {component_config.get('label', '') + ''} component."
13581358
)
1359-
with open(file_path, "rb") as f:
1360-
files = [("files", (orig_name.name, f))]
1359+
with open(file_path, "rb") as f_:
1360+
files = [("files", (orig_name.name, f_))]
13611361
r = httpx.post(
13621362
self.client.upload_url,
13631363
headers=self.client.headers,

demo/agent_chatbot/run.ipynb

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: agent_chatbot"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio transformers>=4.47.0"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from dataclasses import asdict\n", "from transformers import Tool, ReactCodeAgent # type: ignore\n", "from transformers.agents import stream_to_gradio, HfApiEngine # type: ignore\n", "\n", "# Import tool from Hub\n", "image_generation_tool = Tool.from_space(\n", " space_id=\"black-forest-labs/FLUX.1-schnell\",\n", " name=\"image_generator\",\n", " description=\"Generates an image following your prompt. Returns a PIL Image.\",\n", " api_name=\"/infer\",\n", ")\n", "\n", "llm_engine = HfApiEngine(\"Qwen/Qwen2.5-Coder-32B-Instruct\")\n", "# Initialize the agent with both tools and engine\n", "agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine)\n", "\n", "\n", "def interact_with_agent(prompt, history):\n", " messages = []\n", " yield messages\n", " for msg in stream_to_gradio(agent, prompt):\n", " messages.append(asdict(msg))\n", " yield messages\n", " yield messages\n", "\n", "\n", "demo = gr.ChatInterface(\n", " interact_with_agent,\n", " chatbot= gr.Chatbot(\n", " label=\"Agent\",\n", " type=\"messages\",\n", " avatar_images=(\n", " None,\n", " \"https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png\",\n", " ),\n", " ),\n", " examples=[\n", " [\"Generate an image of an astronaut riding an alligator\"],\n", " [\"I am writing a children's book for my daughter. Can you help me with some illustrations?\"],\n", " ],\n", " type=\"messages\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
1+
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: agent_chatbot"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio transformers>=4.47.0"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "from dataclasses import asdict\n", "from transformers import Tool, ReactCodeAgent # type: ignore\n", "from transformers.agents import stream_to_gradio, HfApiEngine # type: ignore\n", "\n", "# Import tool from Hub\n", "image_generation_tool = Tool.from_space( # type: ignore\n", " space_id=\"black-forest-labs/FLUX.1-schnell\",\n", " name=\"image_generator\",\n", " description=\"Generates an image following your prompt. Returns a PIL Image.\",\n", " api_name=\"/infer\",\n", ")\n", "\n", "llm_engine = HfApiEngine(\"Qwen/Qwen2.5-Coder-32B-Instruct\")\n", "# Initialize the agent with both tools and engine\n", "agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine)\n", "\n", "\n", "def interact_with_agent(prompt, history):\n", " messages = []\n", " yield messages\n", " for msg in stream_to_gradio(agent, prompt):\n", " messages.append(asdict(msg)) # type: ignore\n", " yield messages\n", " yield messages\n", "\n", "\n", "demo = gr.ChatInterface(\n", " interact_with_agent,\n", " chatbot= gr.Chatbot(\n", " label=\"Agent\",\n", " type=\"messages\",\n", " avatar_images=(\n", " None,\n", " \"https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png\",\n", " ),\n", " ),\n", " examples=[\n", " [\"Generate an image of an astronaut riding an alligator\"],\n", " [\"I am writing a children's book for my daughter. Can you help me with some illustrations?\"],\n", " ],\n", " type=\"messages\",\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}

demo/agent_chatbot/run.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from transformers.agents import stream_to_gradio, HfApiEngine # type: ignore
55

66
# Import tool from Hub
7-
image_generation_tool = Tool.from_space(
7+
image_generation_tool = Tool.from_space( # type: ignore
88
space_id="black-forest-labs/FLUX.1-schnell",
99
name="image_generator",
1010
description="Generates an image following your prompt. Returns a PIL Image.",
@@ -20,7 +20,7 @@ def interact_with_agent(prompt, history):
2020
messages = []
2121
yield messages
2222
for msg in stream_to_gradio(agent, prompt):
23-
messages.append(asdict(msg))
23+
messages.append(asdict(msg)) # type: ignore
2424
yield messages
2525
yield messages
2626

gradio/__init__.py

+118
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,121 @@
119119
from gradio.ipython_ext import load_ipython_extension
120120

121121
__version__ = get_package_version()
122+
123+
__all__ = [
124+
"Accordion",
125+
"AnnotatedImage",
126+
"Annotatedimage",
127+
"Audio",
128+
"BarPlot",
129+
"Blocks",
130+
"BrowserState",
131+
"Brush",
132+
"Button",
133+
"CSVLogger",
134+
"ChatInterface",
135+
"ChatMessage",
136+
"Chatbot",
137+
"Checkbox",
138+
"CheckboxGroup",
139+
"Checkboxgroup",
140+
"ClearButton",
141+
"Code",
142+
"ColorPicker",
143+
"Column",
144+
"CopyData",
145+
"DataFrame",
146+
"Dataframe",
147+
"Dataset",
148+
"DateTime",
149+
"DeletedFileData",
150+
"DownloadButton",
151+
"DownloadData",
152+
"Dropdown",
153+
"DuplicateButton",
154+
"EditData",
155+
"Eraser",
156+
"Error",
157+
"EventData",
158+
"Examples",
159+
"File",
160+
"FileData",
161+
"FileExplorer",
162+
"FileSize",
163+
"Files",
164+
"FlaggingCallback",
165+
"Gallery",
166+
"Group",
167+
"HTML",
168+
"Highlight",
169+
"HighlightedText",
170+
"Highlightedtext",
171+
"IS_WASM",
172+
"Image",
173+
"ImageEditor",
174+
"ImageMask",
175+
"Info",
176+
"Interface",
177+
"JSON",
178+
"Json",
179+
"KeyUpData",
180+
"Label",
181+
"LikeData",
182+
"LinePlot",
183+
"List",
184+
"LoginButton",
185+
"Markdown",
186+
"Matrix",
187+
"MessageDict",
188+
"Mic",
189+
"Microphone",
190+
"Model3D",
191+
"MultimodalTextbox",
192+
"NO_RELOAD",
193+
"Number",
194+
"Numpy",
195+
"OAuthProfile",
196+
"OAuthToken",
197+
"Paint",
198+
"ParamViewer",
199+
"PlayableVideo",
200+
"Plot",
201+
"Progress",
202+
"Radio",
203+
"Request",
204+
"RetryData",
205+
"Row",
206+
"ScatterPlot",
207+
"SelectData",
208+
"SimpleCSVLogger",
209+
"Sketchpad",
210+
"Slider",
211+
"State",
212+
"Tab",
213+
"TabItem",
214+
"TabbedInterface",
215+
"Tabs",
216+
"Text",
217+
"TextArea",
218+
"Textbox",
219+
"Theme",
220+
"Timer",
221+
"UndoData",
222+
"UploadButton",
223+
"Video",
224+
"Warning",
225+
"WaveformOptions",
226+
"__version__",
227+
"close_all",
228+
"deploy",
229+
"get_package_version",
230+
"load",
231+
"load_chat",
232+
"load_ipython_extension",
233+
"mount_gradio_app",
234+
"on",
235+
"render",
236+
"set_static_paths",
237+
"skip",
238+
"update",
239+
]

gradio/blocks.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -1475,10 +1475,7 @@ def is_callable(self, fn_index: int = 0) -> bool:
14751475
return False
14761476
if any(block.stateful for block in dependency.inputs):
14771477
return False
1478-
if any(block.stateful for block in dependency.outputs):
1479-
return False
1480-
1481-
return True
1478+
return not any(block.stateful for block in dependency.outputs)
14821479

14831480
def __call__(self, *inputs, fn_index: int = 0, api_name: str | None = None):
14841481
"""

gradio/cli/commands/components/_docs_utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def get_param_name(param):
7171

7272
def format_none(value):
7373
"""Formats None and NonType values."""
74-
if value is None or value is type(None) or value == "None" or value == "NoneType":
74+
if value is None or value is type(None) or value in ("None", "NoneType"):
7575
return "None"
7676
return value
7777

gradio/components/native_plot.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,10 @@ def __init__(
147147
every=every,
148148
inputs=inputs,
149149
)
150-
for key, val in kwargs.items():
151-
if key == "color_legend_title":
150+
for key_, val in kwargs.items():
151+
if key_ == "color_legend_title":
152152
self.color_title = val
153-
if key in [
153+
if key_ in [
154154
"stroke_dash",
155155
"overlay_point",
156156
"x_label_angle",
@@ -161,7 +161,7 @@ def __init__(
161161
"width",
162162
]:
163163
warnings.warn(
164-
f"Argument '{key}' has been deprecated.", DeprecationWarning
164+
f"Argument '{key_}' has been deprecated.", DeprecationWarning
165165
)
166166

167167
def get_block_name(self) -> str:

gradio/components/video.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ def postprocess(
276276
"""
277277
if self.streaming:
278278
return value # type: ignore
279-
if value is None or value == [None, None] or value == (None, None):
279+
if value is None or value in ([None, None], (None, None)):
280280
return None
281281
if isinstance(value, (str, Path)):
282282
processed_files = (self._format_video(value), None)

gradio/external.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,7 @@ def load_chat(
615615
[{"role": "system", "content": system_message}] if system_message else []
616616
)
617617

618-
def open_api(message: str, history: list | None) -> str:
618+
def open_api(message: str, history: list | None) -> str | None:
619619
history = history or start_message
620620
if len(history) > 0 and isinstance(history[0], (list, tuple)):
621621
history = ChatInterface._tuples_to_messages(history)
@@ -641,7 +641,8 @@ def open_api_stream(
641641
)
642642
response = ""
643643
for chunk in stream:
644-
response += chunk.choices[0].delta.content
645-
yield response
644+
if chunk.choices[0].delta.content is not None:
645+
response += chunk.choices[0].delta.content
646+
yield response
646647

647648
return ChatInterface(open_api_stream if streaming else open_api, type="messages")

gradio/themes/base.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,7 @@ def to_dict(self):
126126
if (
127127
not prop.startswith("_")
128128
or prop.startswith("_font")
129-
or prop == "_stylesheets"
130-
or prop == "name"
129+
or prop in ("_stylesheets", "name")
131130
) and isinstance(getattr(self, prop), (list, str)):
132131
schema["theme"][prop] = getattr(self, prop)
133132
return schema

gradio/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1244,7 +1244,7 @@ def compare_objects(obj1, obj2, path=None):
12441244
if obj1 == obj2:
12451245
return edits
12461246

1247-
if type(obj1) != type(obj2):
1247+
if type(obj1) is not type(obj2):
12481248
edits.append(("replace", path, obj2))
12491249
return edits
12501250

test/components/test_gallery.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -126,5 +126,5 @@ def test_gallery_format(self):
126126
output = gallery.postprocess(
127127
[np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)]
128128
)
129-
if type(output.root[0]) == GalleryImage:
129+
if isinstance(output.root[0], GalleryImage):
130130
assert output.root[0].image.path.endswith(".jpeg")

test/test_utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ class GenericObject:
304304
for x in test_objs:
305305
hints = get_type_hints(x)
306306
assert len(hints) == 1
307-
assert hints["s"] == str
307+
assert hints["s"] is str
308308

309309
assert len(get_type_hints(GenericObject())) == 0
310310

0 commit comments

Comments
 (0)