Label component now accepts file paths to .json files (#2083)

* added label support for file paths

* formatting
This commit is contained in:
Abubakar Abid 2022-08-25 15:26:27 -07:00 committed by GitHub
parent 4a1321ce8a
commit adf52d2dad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 10 additions and 1 deletions

View File

@ -2753,7 +2753,7 @@ class Label(Changeable, IOComponent, JSONSerializable):
"""
Displays a classification label, along with confidence scores of top categories, if provided.
Preprocessing: this component does *not* accept input.
Postprocessing: expects a {Dict[str, float]} of classes and confidences, or {str} with just the class or an {int}/{float} for regression outputs.
Postprocessing: expects a {Dict[str, float]} of classes and confidences, or {str} with just the class or an {int}/{float} for regression outputs, or a {str} path to a .json file containing a json dictionary in the structure produced by Label.postprocess().
Demos: main_note, titanic_survival
Guides: Gradio_and_ONNX_on_Hugging_Face, image_classification_in_pytorch, image_classification_in_tensorflow, image_classification_with_vision_transformers, building_a_pictionary_app
@ -2808,6 +2808,8 @@ class Label(Changeable, IOComponent, JSONSerializable):
"""
if y is None or y == {}:
return None
if isinstance(y, str) and y.endswith(".json") and os.path.exists(y):
return self.serialize(y)
if isinstance(y, (str, numbers.Number)):
return {"label": str(y)}
if isinstance(y, dict):

View File

@ -1289,6 +1289,7 @@ class TestLabel(unittest.TestCase):
)
label_output = gr.Label(num_top_classes=2)
label = label_output.postprocess(y)
self.assertDictEqual(
label,
{
@ -1302,6 +1303,11 @@ class TestLabel(unittest.TestCase):
with self.assertRaises(ValueError):
label_output.postprocess([1, 2, 3])
test_file_dir = pathlib.Path(pathlib.Path(__file__).parent, "test_files")
path = str(pathlib.Path(test_file_dir, "test_label_json.json"))
label = label_output.postprocess(path)
self.assertEqual(label["label"], "web site")
self.assertEqual(
label_output.get_config(),
{

View File

@ -0,0 +1 @@
{"label": "web site", "confidences": [{"label": "web site", "confidence": 0.6625185608863831}, {"label": "envelope", "confidence": 0.02277352288365364}, {"label": "menu", "confidence": 0.012591145932674408}, {"label": "monitor", "confidence": 0.012062293477356434}, {"label": "washer", "confidence": 0.008587697520852089}]}