Raise warning when trying to cache examples but not all inputs have examples (#2279)

* Add error message + test

* Undo changes to fake_gan

* Raise warning message instead

* Fix typo in warning message

* Remove unused import

* Address comments
This commit is contained in:
Freddy Boulton 2022-09-20 09:48:52 -05:00 committed by GitHub
parent 6c33eed976
commit b8fc551807
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 74 additions and 1 deletions

View File

@ -2,7 +2,6 @@
# python demo/fake_gan/run.py
import os
import random
import time
import gradio as gr

View File

@ -187,6 +187,20 @@ class Examples:
[ex for (ex, keep) in zip(example, input_has_examples) if keep]
for example in self.processed_examples
]
if cache_examples:
for ex in non_none_examples:
if (
len([sample for sample in ex if sample is not None])
!= self.inputs_with_examples
):
warnings.warn(
"Examples are being cached but not all input components have "
"example values. This may result in an exception being thrown by "
"your function. If you do get an error while caching examples, make "
"sure all of your inputs have example values for all of your examples "
"or you provide default values for those particular parameters in your function."
)
break
self.dataset = Dataset(
components=inputs_with_examples,

View File

@ -1,4 +1,5 @@
import os
from unittest.mock import patch
import pytest
@ -89,3 +90,62 @@ class TestProcessExamples:
prediction = await io.examples_handler.load_from_cache(1)
io.close()
assert prediction[0] == "Hello Dunya"
def test_raise_helpful_error_message_if_providing_partial_examples(tmp_path):
def foo(a, b):
return a + b
with patch("gradio.examples.CACHED_FOLDER", tmp_path):
with pytest.warns(
UserWarning,
match="^Examples are being cached but not all input components have",
):
with pytest.raises(Exception):
gr.Interface(
foo,
inputs=["text", "text"],
outputs=["text"],
examples=[["foo"], ["bar"]],
cache_examples=True,
)
with pytest.warns(
UserWarning,
match="^Examples are being cached but not all input components have",
):
with pytest.raises(Exception):
gr.Interface(
foo,
inputs=["text", "text"],
outputs=["text"],
examples=[["foo", "bar"], ["bar", None]],
cache_examples=True,
)
def foo_no_exception(a, b=2):
return a * b
gr.Interface(
foo_no_exception,
inputs=["text", "number"],
outputs=["text"],
examples=[["foo"], ["bar"]],
cache_examples=True,
)
def many_missing(a, b, c):
return a * b
with pytest.warns(
UserWarning,
match="^Examples are being cached but not all input components have",
):
with pytest.raises(Exception):
gr.Interface(
many_missing,
inputs=["text", "number", "number"],
outputs=["text"],
examples=[["foo", None, None], ["bar", 2, 3]],
cache_examples=True,
)