-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
test_components.py
2893 lines (2579 loc) 路 98.7 KB
/
test_components.py
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Tests for all of the components defined in components.py. Tests are divided into two types:
1. test_component_functions() are unit tests that check essential functions of a component, the functions that are checked are documented in the docstring.
2. test_in_interface() are functional tests that check a component's functionalities inside an Interface. Please do not use Interface.launch() in this file, as it slow downs the tests.
"""
import filecmp
import json
import os
import pathlib # noqa: F401
import shutil
import tempfile
from copy import deepcopy
from difflib import SequenceMatcher
from pathlib import Path
from unittest.mock import MagicMock, patch
import numpy as np
import pandas as pd
import PIL
import pytest
import vega_datasets
from gradio_client import media_data
from gradio_client import utils as client_utils
from scipy.io import wavfile
import gradio as gr
from gradio import processing_utils, utils
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
class TestComponent:
def test_component_functions(self):
"""
component
"""
assert isinstance(gr.components.component("textarea"), gr.templates.TextArea)
def test_raise_warnings():
for c_type, component in zip(
["inputs", "outputs"], [gr.inputs.Textbox, gr.outputs.Label]
):
with pytest.warns(UserWarning, match=f"Usage of gradio.{c_type}"):
component()
class TestTextbox:
def test_component_functions(self):
"""
Preprocess, postprocess, serialize, tokenize, get_config
"""
text_input = gr.Textbox()
assert text_input.preprocess("Hello World!") == "Hello World!"
assert text_input.postprocess("Hello World!") == "Hello World!"
assert text_input.postprocess(None) is None
assert text_input.postprocess("Ali") == "Ali"
assert text_input.postprocess(2) == "2"
assert text_input.postprocess(2.14) == "2.14"
assert text_input.serialize("Hello World!", True) == "Hello World!"
assert text_input.tokenize("Hello World! Gradio speaking.") == (
["Hello", "World!", "Gradio", "speaking."],
[
"World! Gradio speaking.",
"Hello Gradio speaking.",
"Hello World! speaking.",
"Hello World! Gradio",
],
None,
)
text_input.interpretation_replacement = "unknown"
assert text_input.tokenize("Hello World! Gradio speaking.") == (
["Hello", "World!", "Gradio", "speaking."],
[
"unknown World! Gradio speaking.",
"Hello unknown Gradio speaking.",
"Hello World! unknown speaking.",
"Hello World! Gradio unknown",
],
None,
)
assert text_input.get_config() == {
"lines": 1,
"max_lines": 20,
"placeholder": None,
"value": "",
"name": "textbox",
"show_copy_button": False,
"show_label": True,
"type": "text",
"label": None,
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"interactive": None,
"root_url": None,
}
@pytest.mark.asyncio
async def test_in_interface_as_input(self):
"""
Interface, process, interpret,
"""
iface = gr.Interface(lambda x: x[::-1], "textbox", "textbox")
assert iface("Hello") == "olleH"
iface = gr.Interface(
lambda sentence: max([len(word) for word in sentence.split()]),
gr.Textbox(),
"number",
interpretation="default",
)
scores = await iface.interpret(
["Return the length of the longest word in this sentence"]
)
assert scores[0]["interpretation"] == [
("Return", 0.0),
(" ", 0),
("the", 0.0),
(" ", 0),
("length", 0.0),
(" ", 0),
("of", 0.0),
(" ", 0),
("the", 0.0),
(" ", 0),
("longest", 0.0),
(" ", 0),
("word", 0.0),
(" ", 0),
("in", 0.0),
(" ", 0),
("this", 0.0),
(" ", 0),
("sentence", 1.0),
(" ", 0),
]
def test_in_interface_as_output(self):
"""
Interface, process
"""
iface = gr.Interface(lambda x: x[-1], "textbox", gr.Textbox())
assert iface("Hello") == "o"
iface = gr.Interface(lambda x: x / 2, "number", gr.Textbox())
assert iface(10) == "5.0"
def test_static(self):
"""
postprocess
"""
component = gr.Textbox("abc")
assert component.get_config().get("value") == "abc"
def test_override_template(self):
"""
override template
"""
component = gr.TextArea(value="abc")
assert component.get_config().get("value") == "abc"
assert component.get_config().get("lines") == 7
component = gr.TextArea(value="abc", lines=4)
assert component.get_config().get("value") == "abc"
assert component.get_config().get("lines") == 4
def test_faulty_type(self):
with pytest.raises(
ValueError, match='`type` must be one of "text", "password", or "email".'
):
gr.Textbox(type="boo")
def test_max_lines(self):
assert gr.Textbox(type="password").get_config().get("max_lines") == 1
assert gr.Textbox(type="email").get_config().get("max_lines") == 1
assert gr.Textbox(type="text").get_config().get("max_lines") == 20
assert gr.Textbox().get_config().get("max_lines") == 20
class TestNumber:
def test_component_functions(self):
"""
Preprocess, postprocess, serialize, set_interpret_parameters, get_interpretation_neighbors, get_config
"""
numeric_input = gr.Number(elem_id="num", elem_classes="first")
assert numeric_input.preprocess(3) == 3.0
assert numeric_input.preprocess(None) is None
assert numeric_input.postprocess(3) == 3
assert numeric_input.postprocess(3) == 3.0
assert numeric_input.postprocess(2.14) == 2.14
assert numeric_input.postprocess(None) is None
assert numeric_input.serialize(3, True) == 3
numeric_input.set_interpret_parameters(steps=3, delta=1, delta_type="absolute")
assert numeric_input.get_interpretation_neighbors(1) == (
[-2.0, -1.0, 0.0, 2.0, 3.0, 4.0],
{},
)
numeric_input.set_interpret_parameters(steps=3, delta=1, delta_type="percent")
assert numeric_input.get_interpretation_neighbors(1) == (
[0.97, 0.98, 0.99, 1.01, 1.02, 1.03],
{},
)
assert numeric_input.get_config() == {
"value": None,
"name": "number",
"show_label": True,
"label": None,
"minimum": None,
"maximum": None,
"container": True,
"min_width": 160,
"scale": None,
"elem_id": "num",
"elem_classes": ["first"],
"visible": True,
"interactive": None,
"root_url": None,
}
def test_component_functions_integer(self):
"""
Preprocess, postprocess, serialize, set_interpret_parameters, get_interpretation_neighbors, get_template_context
"""
numeric_input = gr.Number(precision=0, value=42)
assert numeric_input.preprocess(3) == 3
assert numeric_input.preprocess(None) is None
assert numeric_input.postprocess(3) == 3
assert numeric_input.postprocess(3) == 3
assert numeric_input.postprocess(2.85) == 3
assert numeric_input.postprocess(None) is None
assert numeric_input.serialize(3, True) == 3
numeric_input.set_interpret_parameters(steps=3, delta=1, delta_type="absolute")
assert numeric_input.get_interpretation_neighbors(1) == (
[-2.0, -1.0, 0.0, 2.0, 3.0, 4.0],
{},
)
numeric_input.set_interpret_parameters(steps=3, delta=1, delta_type="percent")
assert numeric_input.get_interpretation_neighbors(100) == (
[97.0, 98.0, 99.0, 101.0, 102.0, 103.0],
{},
)
with pytest.raises(ValueError) as error:
numeric_input.get_interpretation_neighbors(1)
assert error.msg == "Cannot generate valid set of neighbors"
numeric_input.set_interpret_parameters(
steps=3, delta=1.24, delta_type="absolute"
)
with pytest.raises(ValueError) as error:
numeric_input.get_interpretation_neighbors(4)
assert error.msg == "Cannot generate valid set of neighbors"
assert numeric_input.get_config() == {
"value": 42,
"name": "number",
"show_label": True,
"label": None,
"minimum": None,
"maximum": None,
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"interactive": None,
"root_url": None,
}
def test_component_functions_precision(self):
"""
Preprocess, postprocess, serialize, set_interpret_parameters, get_interpretation_neighbors, get_template_context
"""
numeric_input = gr.Number(precision=2, value=42.3428)
assert numeric_input.preprocess(3.231241) == 3.23
assert numeric_input.preprocess(None) is None
assert numeric_input.postprocess(-42.1241) == -42.12
assert numeric_input.postprocess(5.6784) == 5.68
assert numeric_input.postprocess(2.1421) == 2.14
assert numeric_input.postprocess(None) is None
@pytest.mark.asyncio
async def test_in_interface_as_input(self):
"""
Interface, process, interpret
"""
iface = gr.Interface(lambda x: x**2, "number", "textbox")
assert iface(2) == "4.0"
iface = gr.Interface(
lambda x: x**2, "number", "number", interpretation="default"
)
scores = (await iface.interpret([2]))[0]["interpretation"]
assert scores == [
(1.94, -0.23640000000000017),
(1.96, -0.15840000000000032),
(1.98, -0.07960000000000012),
(2, None),
(2.02, 0.08040000000000003),
(2.04, 0.16159999999999997),
(2.06, 0.24359999999999982),
]
@pytest.mark.asyncio
async def test_precision_0_in_interface(self):
"""
Interface, process, interpret
"""
iface = gr.Interface(lambda x: x**2, gr.Number(precision=0), "textbox")
assert iface(2) == "4"
iface = gr.Interface(
lambda x: x**2, "number", gr.Number(precision=0), interpretation="default"
)
# Output gets rounded to 4 for all input so no change
scores = (await iface.interpret([2]))[0]["interpretation"]
assert scores == [
(1.94, 0.0),
(1.96, 0.0),
(1.98, 0.0),
(2, None),
(2.02, 0.0),
(2.04, 0.0),
(2.06, 0.0),
]
@pytest.mark.asyncio
async def test_in_interface_as_output(self):
"""
Interface, process, interpret
"""
iface = gr.Interface(lambda x: int(x) ** 2, "textbox", "number")
assert iface(2) == 4.0
iface = gr.Interface(
lambda x: x**2, "number", "number", interpretation="default"
)
scores = (await iface.interpret([2]))[0]["interpretation"]
assert scores == [
(1.94, -0.23640000000000017),
(1.96, -0.15840000000000032),
(1.98, -0.07960000000000012),
(2, None),
(2.02, 0.08040000000000003),
(2.04, 0.16159999999999997),
(2.06, 0.24359999999999982),
]
def test_static(self):
"""
postprocess
"""
component = gr.Number()
assert component.get_config().get("value") is None
component = gr.Number(3)
assert component.get_config().get("value") == 3.0
class TestSlider:
def test_component_functions(self):
"""
Preprocess, postprocess, serialize, get_config
"""
slider_input = gr.Slider()
assert slider_input.preprocess(3.0) == 3.0
assert slider_input.postprocess(3) == 3
assert slider_input.postprocess(3) == 3
assert slider_input.postprocess(None) == 0
assert slider_input.serialize(3, True) == 3
slider_input = gr.Slider(10, 20, value=15, step=1, label="Slide Your Input")
assert slider_input.get_config() == {
"minimum": 10,
"maximum": 20,
"step": 1,
"value": 15,
"name": "slider",
"show_label": True,
"label": "Slide Your Input",
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"interactive": None,
"root_url": None,
}
@pytest.mark.asyncio
async def test_in_interface(self):
""" "
Interface, process, interpret
"""
iface = gr.Interface(lambda x: x**2, "slider", "textbox")
assert iface(2) == "4"
iface = gr.Interface(
lambda x: x**2, "slider", "number", interpretation="default"
)
scores = (await iface.interpret([2]))[0]["interpretation"]
assert scores == [
-4.0,
200.08163265306123,
812.3265306122449,
1832.7346938775513,
3261.3061224489797,
5098.040816326531,
7342.938775510205,
9996.0,
]
def test_static(self):
"""
postprocess
"""
component = gr.Slider(0, 100, 5)
assert component.get_config().get("value") == 5
component = gr.Slider(0, 100, None)
assert component.get_config().get("value") == 0
@patch("gradio.Slider.get_random_value", return_value=7)
def test_slider_get_random_value_on_load(self, mock_get_random_value):
slider = gr.Slider(minimum=-5, maximum=10, randomize=True)
assert slider.value == 7
assert slider.load_event_to_attach[0]() == 7
assert slider.load_event_to_attach[1] is None
@patch("random.randint", return_value=3)
def test_slider_rounds_when_using_default_randomizer(self, mock_randint):
slider = gr.Slider(minimum=0, maximum=1, randomize=True, step=0.1)
# If get_random_value didn't round, this test would fail
# because 0.30000000000000004 != 0.3
assert slider.get_random_value() == 0.3
mock_randint.assert_called()
class TestCheckbox:
def test_component_functions(self):
"""
Preprocess, postprocess, serialize, get_config
"""
bool_input = gr.Checkbox()
assert bool_input.preprocess(True)
assert bool_input.postprocess(True)
assert bool_input.postprocess(True)
assert bool_input.serialize(True, True)
bool_input = gr.Checkbox(value=True, label="Check Your Input")
assert bool_input.get_config() == {
"value": True,
"name": "checkbox",
"show_label": True,
"label": "Check Your Input",
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"interactive": None,
"root_url": None,
}
@pytest.mark.asyncio
async def test_in_interface(self):
"""
Interface, process, interpret
"""
iface = gr.Interface(lambda x: 1 if x else 0, "checkbox", "number")
assert iface(True) == 1
iface = gr.Interface(
lambda x: 1 if x else 0, "checkbox", "number", interpretation="default"
)
scores = (await iface.interpret([False]))[0]["interpretation"]
assert scores == (None, 1.0)
scores = (await iface.interpret([True]))[0]["interpretation"]
assert scores == (-1.0, None)
class TestCheckboxGroup:
def test_component_functions(self):
"""
Preprocess, postprocess, serialize, get_config
"""
checkboxes_input = gr.CheckboxGroup(["a", "b", "c"])
assert checkboxes_input.preprocess(["a", "c"]) == ["a", "c"]
assert checkboxes_input.postprocess(["a", "c"]) == ["a", "c"]
assert checkboxes_input.serialize(["a", "c"], True) == ["a", "c"]
checkboxes_input = gr.CheckboxGroup(
value=["a", "c"],
choices=["a", "b", "c"],
label="Check Your Inputs",
)
assert checkboxes_input.get_config() == {
"choices": ["a", "b", "c"],
"value": ["a", "c"],
"name": "checkboxgroup",
"show_label": True,
"label": "Check Your Inputs",
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"interactive": None,
"root_url": None,
}
with pytest.raises(ValueError):
gr.CheckboxGroup(["a"], type="unknown")
cbox = gr.CheckboxGroup(choices=["a", "b"], value="c")
assert cbox.get_config()["value"] == ["c"]
assert cbox.postprocess("a") == ["a"]
def test_in_interface(self):
"""
Interface, process
"""
checkboxes_input = gr.CheckboxGroup(["a", "b", "c"])
iface = gr.Interface(lambda x: "|".join(x), checkboxes_input, "textbox")
assert iface(["a", "c"]) == "a|c"
assert iface([]) == ""
_ = gr.CheckboxGroup(["a", "b", "c"], type="index")
class TestRadio:
def test_component_functions(self):
"""
Preprocess, postprocess, serialize, get_config
"""
radio_input = gr.Radio(["a", "b", "c"])
assert radio_input.preprocess("c") == "c"
assert radio_input.postprocess("a") == "a"
assert radio_input.serialize("a", True) == "a"
radio_input = gr.Radio(
choices=["a", "b", "c"], default="a", label="Pick Your One Input"
)
assert radio_input.get_config() == {
"choices": ["a", "b", "c"],
"value": None,
"name": "radio",
"show_label": True,
"label": "Pick Your One Input",
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"interactive": None,
"root_url": None,
}
with pytest.raises(ValueError):
gr.Radio(["a", "b"], type="unknown")
@pytest.mark.asyncio
async def test_in_interface(self):
"""
Interface, process, interpret
"""
radio_input = gr.Radio(["a", "b", "c"])
iface = gr.Interface(lambda x: 2 * x, radio_input, "textbox")
assert iface("c") == "cc"
radio_input = gr.Radio(["a", "b", "c"], type="index")
iface = gr.Interface(
lambda x: 2 * x, radio_input, "number", interpretation="default"
)
assert iface("c") == 4
scores = (await iface.interpret(["b"]))[0]["interpretation"]
assert scores == [-2.0, None, 2.0]
class TestDropdown:
def test_component_functions(self):
"""
Preprocess, postprocess, serialize, get_config
"""
dropdown_input = gr.Dropdown(["a", "b", "c"], multiselect=True)
assert dropdown_input.preprocess("a") == "a"
assert dropdown_input.postprocess("a") == "a"
dropdown_input_multiselect = gr.Dropdown(["a", "b", "c"])
assert dropdown_input_multiselect.preprocess(["a", "c"]) == ["a", "c"]
assert dropdown_input_multiselect.postprocess(["a", "c"]) == ["a", "c"]
assert dropdown_input_multiselect.serialize(["a", "c"], True) == ["a", "c"]
dropdown_input_multiselect = gr.Dropdown(
value=["a", "c"],
choices=["a", "b", "c"],
label="Select Your Inputs",
multiselect=True,
max_choices=2,
)
assert dropdown_input_multiselect.get_config() == {
"allow_custom_value": False,
"choices": ["a", "b", "c"],
"value": ["a", "c"],
"name": "dropdown",
"show_label": True,
"label": "Select Your Inputs",
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"interactive": None,
"root_url": None,
"multiselect": True,
"max_choices": 2,
}
with pytest.raises(ValueError):
gr.Dropdown(["a"], type="unknown")
dropdown = gr.Dropdown(choices=["a", "b"], value="c")
assert dropdown.get_config()["value"] == "c"
assert dropdown.postprocess("a") == "a"
def test_in_interface(self):
"""
Interface, process
"""
checkboxes_input = gr.CheckboxGroup(["a", "b", "c"])
iface = gr.Interface(lambda x: "|".join(x), checkboxes_input, "textbox")
assert iface(["a", "c"]) == "a|c"
assert iface([]) == ""
_ = gr.CheckboxGroup(["a", "b", "c"], type="index")
class TestImage:
def test_component_functions(self):
"""
Preprocess, postprocess, serialize, get_config, _segment_by_slic
type: pil, file, filepath, numpy
"""
img = deepcopy(media_data.BASE64_IMAGE)
image_input = gr.Image()
assert image_input.preprocess(img).shape == (68, 61, 3)
image_input = gr.Image(shape=(25, 25), image_mode="L")
assert image_input.preprocess(img).shape == (25, 25)
image_input = gr.Image(shape=(30, 10), type="pil")
assert image_input.preprocess(img).size == (30, 10)
assert image_input.postprocess("test/test_files/bus.png") == img
assert image_input.serialize("test/test_files/bus.png") == img
image_input = gr.Image(type="filepath")
image_temp_filepath = image_input.preprocess(img)
assert image_temp_filepath in image_input.temp_files
image_input = gr.Image(
source="upload", tool="editor", type="pil", label="Upload Your Image"
)
assert image_input.get_config() == {
"brush_radius": None,
"image_mode": "RGB",
"shape": None,
"source": "upload",
"tool": "editor",
"name": "image",
"streaming": False,
"show_label": True,
"label": "Upload Your Image",
"container": True,
"min_width": 160,
"scale": None,
"height": None,
"width": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"value": None,
"interactive": None,
"root_url": None,
"mirror_webcam": True,
"selectable": False,
}
assert image_input.preprocess(None) is None
image_input = gr.Image(invert_colors=True)
assert image_input.preprocess(img) is not None
image_input.preprocess(img)
file_image = gr.Image(type="filepath")
assert isinstance(file_image.preprocess(img), str)
with pytest.raises(ValueError):
gr.Image(type="unknown")
image_input.shape = (30, 10)
assert image_input._segment_by_slic(img) is not None
# Output functionalities
y_img = gr.processing_utils.decode_base64_to_image(
deepcopy(media_data.BASE64_IMAGE)
)
image_output = gr.Image()
assert image_output.postprocess(y_img).startswith(
"data:image/png;base64,iVBORw0KGgoAAA"
)
assert image_output.postprocess(np.array(y_img)).startswith(
"data:image/png;base64,iVBORw0KGgoAAA"
)
with pytest.raises(ValueError):
image_output.postprocess([1, 2, 3])
image_output = gr.Image(type="numpy")
assert image_output.postprocess(y_img).startswith("data:image/png;base64,")
@pytest.mark.flaky
def test_serialize_url(self):
img = "https://gradio.app/assets/img/header-image.jpg"
expected = client_utils.encode_url_or_file_to_base64(img)
assert gr.Image().serialize(img) == expected
def test_in_interface_as_input(self):
"""
Interface, process, interpret
type: file
interpretation: default, shap,
"""
img = "test/test_files/bus.png"
image_input = gr.Image()
iface = gr.Interface(
lambda x: PIL.Image.open(x).rotate(90, expand=True),
gr.Image(shape=(30, 10), type="filepath"),
"image",
)
output = iface(img)
assert PIL.Image.open(output).size == (10, 30)
iface = gr.Interface(
lambda x: np.sum(x), image_input, "number", interpretation="default"
)
def test_in_interface_as_output(self):
"""
Interface, process
"""
def generate_noise(height, width):
return np.random.randint(0, 256, (height, width, 3))
iface = gr.Interface(generate_noise, ["slider", "slider"], "image")
assert iface(10, 20).endswith(".png")
def test_static(self):
"""
postprocess
"""
component = gr.Image("test/test_files/bus.png")
assert component.get_config().get("value") == media_data.BASE64_IMAGE
component = gr.Image(None)
assert component.get_config().get("value") is None
class TestPlot:
@pytest.mark.asyncio
async def test_in_interface_as_output(self):
"""
Interface, process
"""
def plot(num):
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(num), range(num))
return fig
iface = gr.Interface(plot, "slider", "plot")
with utils.MatplotlibBackendMananger():
output = await iface.process_api(fn_index=0, inputs=[10], state={})
assert output["data"][0]["type"] == "matplotlib"
assert output["data"][0]["plot"].startswith("data:image/png;base64")
def test_static(self):
"""
postprocess
"""
with utils.MatplotlibBackendMananger():
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1, 2, 3], [1, 2, 3])
component = gr.Plot(fig)
assert component.get_config().get("value") is not None
component = gr.Plot(None)
assert component.get_config().get("value") is None
def test_postprocess_altair(self):
import altair as alt
from vega_datasets import data
cars = data.cars()
chart = (
alt.Chart(cars)
.mark_point()
.encode(
x="Horsepower",
y="Miles_per_Gallon",
color="Origin",
)
)
out = gr.Plot().postprocess(chart)
assert isinstance(out["plot"], str)
assert out["plot"] == chart.to_json()
class TestAudio:
def test_component_functions(self):
"""
Preprocess, postprocess serialize, get_config, deserialize
type: filepath, numpy, file
"""
x_wav = deepcopy(media_data.BASE64_AUDIO)
audio_input = gr.Audio()
output1 = audio_input.preprocess(x_wav)
assert output1[0] == 8000
assert output1[1].shape == (8046,)
x_wav["is_file"] = True
audio_input = gr.Audio(type="filepath")
output1 = audio_input.preprocess(x_wav)
assert Path(output1).name == "audio_sample-0-100.wav"
assert filecmp.cmp(
"test/test_files/audio_sample.wav",
audio_input.serialize("test/test_files/audio_sample.wav")["name"],
)
audio_input = gr.Audio(label="Upload Your Audio")
assert audio_input.get_config() == {
"autoplay": False,
"source": "upload",
"name": "audio",
"streaming": False,
"show_label": True,
"label": "Upload Your Audio",
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"value": None,
"interactive": None,
"root_url": None,
}
assert audio_input.preprocess(None) is None
x_wav["is_example"] = True
x_wav["crop_min"], x_wav["crop_max"] = 1, 4
output2 = audio_input.preprocess(x_wav)
assert output2 is not None
assert output1 != output2
audio_input = gr.Audio(type="filepath")
assert isinstance(audio_input.preprocess(x_wav), str)
with pytest.raises(ValueError):
gr.Audio(type="unknown")
# Confirm Audio can be instantiated with a numpy array
gr.Audio((100, np.random.random(size=(1000, 2))), label="Play your audio")
# Output functionalities
y_audio = client_utils.decode_base64_to_file(
deepcopy(media_data.BASE64_AUDIO)["data"]
)
audio_output = gr.Audio(type="filepath")
assert filecmp.cmp(y_audio.name, audio_output.postprocess(y_audio.name)["name"])
assert audio_output.get_config() == {
"autoplay": False,
"name": "audio",
"streaming": False,
"show_label": True,
"label": None,
"source": "upload",
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"value": None,
"interactive": None,
"root_url": None,
}
assert audio_output.deserialize(
{
"name": None,
"data": deepcopy(media_data.BASE64_AUDIO)["data"],
"is_file": False,
}
).endswith(".wav")
output1 = audio_output.postprocess(y_audio.name)
output2 = audio_output.postprocess(y_audio.name)
assert output1 == output2
def test_serialize(self):
audio_input = gr.Audio()
serialized_input = audio_input.serialize("test/test_files/audio_sample.wav")
assert serialized_input["data"] == media_data.BASE64_AUDIO["data"]
assert os.path.basename(serialized_input["name"]) == "audio_sample.wav"
assert serialized_input["orig_name"] == "audio_sample.wav"
assert not serialized_input["is_file"]
def test_tokenize(self):
"""
Tokenize, get_masked_inputs
"""
x_wav = deepcopy(media_data.BASE64_AUDIO)
audio_input = gr.Audio()
tokens, _, _ = audio_input.tokenize(x_wav)
assert len(tokens) == audio_input.interpretation_segments
x_new = audio_input.get_masked_inputs(tokens, [[1] * len(tokens)])[0]
similarity = SequenceMatcher(a=x_wav["data"], b=x_new).ratio()
assert similarity > 0.9
def test_in_interface(self):
def reverse_audio(audio):
sr, data = audio
return (sr, np.flipud(data))
iface = gr.Interface(reverse_audio, "audio", "audio")
reversed_file = iface("test/test_files/audio_sample.wav")
reversed_reversed_file = iface(reversed_file)
reversed_reversed_data = client_utils.encode_url_or_file_to_base64(
reversed_reversed_file
)
similarity = SequenceMatcher(
a=reversed_reversed_data, b=media_data.BASE64_AUDIO["data"]
).ratio()
assert similarity > 0.99
def test_in_interface_as_output(self):
"""
Interface, process
"""
def generate_noise(duration):
return 48000, np.random.randint(-256, 256, (duration, 3)).astype(np.int16)
iface = gr.Interface(generate_noise, "slider", "audio")
assert iface(100).endswith(".wav")
def test_audio_preprocess_can_be_read_by_scipy(self):
x_wav = deepcopy(media_data.BASE64_MICROPHONE)
audio_input = gr.Audio(type="filepath")
output = audio_input.preprocess(x_wav)
wavfile.read(output)
def test_prepost_process_to_mp3(self):
x_wav = deepcopy(media_data.BASE64_MICROPHONE)
audio_input = gr.Audio(type="filepath", format="mp3")
output = audio_input.preprocess(x_wav)
assert output.endswith("mp3")
output = audio_input.postprocess(
(48000, np.random.randint(-256, 256, (5, 3)).astype(np.int16))
)
assert output["name"].endswith("mp3")
class TestFile:
def test_component_functions(self):
"""
Preprocess, serialize, get_config, value
"""
x_file = deepcopy(media_data.BASE64_FILE)
file_input = gr.File()
output = file_input.preprocess(x_file)
assert isinstance(output, tempfile._TemporaryFileWrapper)
serialized = file_input.serialize("test/test_files/sample_file.pdf")
assert filecmp.cmp(
serialized["name"],
"test/test_files/sample_file.pdf",
)
assert serialized["orig_name"] == "sample_file.pdf"
assert output.orig_name == "test/test_files/sample_file.pdf"
x_file["is_file"] = True
input1 = file_input.preprocess(x_file)
input2 = file_input.preprocess(x_file)
assert input1.name == input2.name
assert Path(input1.name).name == "sample_file.pdf"
file_input = gr.File(label="Upload Your File")
assert file_input.get_config() == {
"file_count": "single",
"file_types": None,
"name": "file",
"show_label": True,
"label": "Upload Your File",
"container": True,
"min_width": 160,
"scale": None,
"elem_id": None,
"elem_classes": None,
"visible": True,
"value": None,
"interactive": None,
"root_url": None,
"selectable": False,
}
assert file_input.preprocess(None) is None