File size: 12,565 Bytes
0ad74ed |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
import inspect
import random
import time
import gradio as gr
import pytest
from pydub import AudioSegment
def pytest_configure(config):
config.addinivalue_line(
"markers", "flaky: mark test as flaky. Failure will not cause te"
)
@pytest.fixture
def calculator_demo():
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
return num1 / num2
demo = gr.Interface(
calculator,
["number", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"],
"number",
examples=[
[5, "add", 3],
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
],
)
return demo
@pytest.fixture
def calculator_demo_with_defaults():
def calculator(num1, operation=None, num2=100):
if operation is None or operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
return num1 / num2
demo = gr.Interface(
calculator,
[
gr.Number(value=10),
gr.Radio(["add", "subtract", "multiply", "divide"]),
gr.Number(),
],
"number",
examples=[
[5, "add", 3],
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
],
)
return demo
@pytest.fixture
def state_demo():
state = gr.State(delete_callback=lambda x: print("STATE DELETED"))
demo = gr.Interface(
lambda x, y: (x, y),
["textbox", state],
["textbox", state],
)
return demo
@pytest.fixture
def increment_demo():
with gr.Blocks() as demo:
btn1 = gr.Button("Increment")
btn2 = gr.Button("Increment")
btn3 = gr.Button("Increment")
numb = gr.Number()
state = gr.State(0)
btn1.click(
lambda x: (x + 1, x + 1),
state,
[state, numb],
api_name="increment_with_queue",
)
btn2.click(
lambda x: (x + 1, x + 1),
state,
[state, numb],
queue=False,
api_name="increment_without_queue",
)
btn3.click(
lambda x: (x + 1, x + 1),
state,
[state, numb],
api_name=False,
)
return demo
@pytest.fixture
def progress_demo():
def my_function(x, progress=gr.Progress()):
progress(0, desc="Starting...")
for _ in progress.tqdm(range(20)):
time.sleep(0.1)
return x
return gr.Interface(my_function, gr.Textbox(), gr.Textbox())
@pytest.fixture
def yield_demo():
def spell(x):
for i in range(len(x)):
time.sleep(0.5)
yield x[:i]
return gr.Interface(spell, "textbox", "textbox")
@pytest.fixture
def cancel_from_client_demo():
def iteration():
for i in range(20):
print(f"i: {i}")
yield i
time.sleep(0.5)
def long_process():
time.sleep(10)
print("DONE!")
return 10
with gr.Blocks() as demo:
num = gr.Number()
btn = gr.Button(value="Iterate")
btn.click(iteration, None, num, api_name="iterate")
btn2 = gr.Button(value="Long Process")
btn2.click(long_process, None, num, api_name="long")
return demo
@pytest.fixture
def sentiment_classification_demo():
def classifier(text): # noqa: ARG001
time.sleep(1)
return {label: random.random() for label in ["POSITIVE", "NEGATIVE", "NEUTRAL"]}
def sleep_for_test():
time.sleep(10)
return 2
with gr.Blocks(theme="gstaff/xkcd") as demo:
with gr.Row():
with gr.Column():
input_text = gr.Textbox(label="Input Text")
with gr.Row():
classify = gr.Button("Classify Sentiment")
with gr.Column():
label = gr.Label(label="Predicted Sentiment")
number = gr.Number()
btn = gr.Button("Sleep then print")
classify.click(classifier, input_text, label, api_name="classify")
btn.click(sleep_for_test, None, number, api_name="sleep")
return demo
@pytest.fixture
def count_generator_demo():
def count(n):
for i in range(int(n)):
time.sleep(0.5)
yield i
def show(n):
return str(list(range(int(n))))
with gr.Blocks() as demo:
with gr.Column():
num = gr.Number(value=10)
with gr.Row():
count_btn = gr.Button("Count")
list_btn = gr.Button("List")
with gr.Column():
out = gr.Textbox()
count_btn.click(count, num, out)
list_btn.click(show, num, out)
return demo
@pytest.fixture
def count_generator_no_api():
def count(n):
for i in range(int(n)):
time.sleep(0.5)
yield i
def show(n):
return str(list(range(int(n))))
with gr.Blocks() as demo:
with gr.Column():
num = gr.Number(value=10)
with gr.Row():
count_btn = gr.Button("Count")
list_btn = gr.Button("List")
with gr.Column():
out = gr.Textbox()
count_btn.click(count, num, out, api_name=False)
list_btn.click(show, num, out, api_name=False)
return demo
@pytest.fixture
def count_generator_demo_exception():
def count(n):
for i in range(int(n)):
time.sleep(0.01)
if i == 5:
raise ValueError("Oh no!")
yield i
def show(n):
return str(list(range(int(n))))
with gr.Blocks() as demo:
with gr.Column():
num = gr.Number(value=10)
with gr.Row():
count_btn = gr.Button("Count")
with gr.Column():
out = gr.Textbox()
count_btn.click(count, num, out, api_name="count")
return demo
@pytest.fixture
def file_io_demo():
demo = gr.Interface(
lambda _: print("foox"),
[gr.File(file_count="multiple"), "file"],
[gr.File(file_count="multiple"), "file"],
)
return demo
@pytest.fixture
def stateful_chatbot():
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.Button("Clear")
st = gr.State([1, 2, 3])
def respond(message, st, chat_history):
assert st[0] == 1 and st[1] == 2 and st[2] == 3
bot_message = "I love you"
chat_history.append((message, bot_message))
return "", chat_history
msg.submit(respond, [msg, st, chatbot], [msg, chatbot], api_name="submit")
clear.click(lambda: None, None, chatbot, queue=False)
return demo
@pytest.fixture
def hello_world_with_group():
with gr.Blocks() as demo:
name = gr.Textbox(label="name")
output = gr.Textbox(label="greeting")
greet = gr.Button("Greet")
show_group = gr.Button("Show group")
with gr.Group(visible=False) as group:
gr.Textbox("Hello!")
def greeting(name):
return f"Hello {name}", gr.Group(visible=True)
greet.click(
greeting, inputs=[name], outputs=[output, group], api_name="greeting"
)
show_group.click(
lambda: gr.Group(visible=False), None, group, api_name="show_group"
)
return demo
@pytest.fixture
def hello_world_with_state_and_accordion():
with gr.Blocks() as demo:
with gr.Row():
name = gr.Textbox(label="name")
output = gr.Textbox(label="greeting")
num = gr.Number(label="count")
with gr.Row():
n_counts = gr.State(value=0)
greet = gr.Button("Greet")
open_acc = gr.Button("Open acc")
close_acc = gr.Button("Close acc")
with gr.Accordion(label="Extra stuff", open=False) as accordion:
gr.Textbox("Hello!")
def greeting(name, state):
state += 1
return state, f"Hello {name}", state, gr.Accordion(open=False)
greet.click(
greeting,
inputs=[name, n_counts],
outputs=[n_counts, output, num, accordion],
api_name="greeting",
)
open_acc.click(
lambda state: (state + 1, state + 1, gr.Accordion(open=True)),
[n_counts],
[n_counts, num, accordion],
api_name="open",
)
close_acc.click(
lambda state: (state + 1, state + 1, gr.Accordion(open=False)),
[n_counts],
[n_counts, num, accordion],
api_name="close",
)
return demo
@pytest.fixture
def stream_audio():
import pathlib
import tempfile
def _stream_audio(audio_file):
audio = AudioSegment.from_mp3(audio_file)
i = 0
chunk_size = 3000
while chunk_size * i < len(audio):
chunk = audio[chunk_size * i : chunk_size * (i + 1)]
i += 1
if chunk:
file = str(pathlib.Path(tempfile.gettempdir()) / f"{i}.wav")
chunk.export(file, format="wav")
yield file
return gr.Interface(
fn=_stream_audio,
inputs=gr.Audio(type="filepath", label="Audio file to stream"),
outputs=gr.Audio(autoplay=True, streaming=True),
)
@pytest.fixture
def video_component():
return gr.Interface(fn=lambda x: x, inputs=gr.Video(), outputs=gr.Video())
@pytest.fixture
def all_components():
classes_to_check = gr.components.Component.__subclasses__()
subclasses = []
while classes_to_check:
subclass = classes_to_check.pop()
children = subclass.__subclasses__()
if children:
classes_to_check.extend(children)
if (
"value" in inspect.signature(subclass).parameters
and subclass != gr.components.Component
and not getattr(subclass, "is_template", False)
):
subclasses.append(subclass)
return subclasses
@pytest.fixture(autouse=True)
def gradio_temp_dir(monkeypatch, tmp_path):
"""tmp_path is unique to each test function.
It will be cleared automatically according to pytest docs: https://docs.pytest.org/en/6.2.x/reference.html#tmp-path
"""
monkeypatch.setenv("GRADIO_TEMP_DIR", str(tmp_path))
return tmp_path
@pytest.fixture
def long_response_with_info():
def long_response(_):
gr.Info("Beginning long response")
time.sleep(17)
gr.Info("Done!")
return "\ta\nb" * 90000
return gr.Interface(
long_response,
None,
gr.Textbox(label="Output"),
)
@pytest.fixture
def many_endpoint_demo():
with gr.Blocks() as demo:
def noop(x):
return x
n_elements = 1000
for _ in range(n_elements):
msg2 = gr.Textbox()
msg2.submit(noop, msg2, msg2)
butn2 = gr.Button()
butn2.click(noop, msg2, msg2)
return demo
@pytest.fixture
def max_file_size_demo():
with gr.Blocks() as demo:
file_1b = gr.File()
upload_status = gr.Textbox()
file_1b.upload(
lambda x: "Upload successful", file_1b, upload_status, api_name="upload_1b"
)
return demo
@pytest.fixture
def chatbot_message_format():
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox()
def respond(message, chat_history: list):
bot_message = random.choice(
["How are you?", "I love you", "I'm very hungry"]
)
chat_history.extend(
[
{"role": "user", "content": message},
{"role": "assistant", "content": bot_message},
]
)
return "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot], api_name="chat")
return demo
|