Victoria Oberascher commited on
Commit
0d4201c
·
1 Parent(s): aba632c

update app

Browse files
Files changed (1) hide show
  1. app.py +133 -0
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import evaluate
2
+ import json
3
+ import os
4
+ import re
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ module = evaluate.load("SEA-AI/horizon-metrics")
9
+
10
+ REGEX_YAML_BLOCK = re.compile(r"---[\n\r]+([\S\s]*?)[\n\r]+---[\n\r]")
11
+
12
+
13
+ def infer_gradio_input_types(feature_types):
14
+ """
15
+ Maps metric feature types to input types for gradio Dataframes:
16
+ - float/int -> numbers
17
+ - string -> strings
18
+ - any other -> json
19
+ Note that json is not a native gradio type but will be treated as string that
20
+ is then parsed as a json.
21
+ """
22
+ input_types = []
23
+ for feature_type in feature_types:
24
+ input_type = "json"
25
+ if isinstance(feature_type, Value):
26
+ if feature_type.dtype.startswith(
27
+ "int") or feature_type.dtype.startswith("float"):
28
+ input_type = "number"
29
+ elif feature_type.dtype == "string":
30
+ input_type = "str"
31
+ input_types.append(input_type)
32
+ return input_types
33
+
34
+
35
+ def json_to_string_type(input_types):
36
+ """Maps json input type to str."""
37
+ return ["str" if i == "json" else i for i in input_types]
38
+
39
+
40
+ def parse_readme(filepath):
41
+ """Parses a repositories README and removes"""
42
+ if not os.path.exists(filepath):
43
+ return "No README.md found."
44
+ with open(filepath, "r") as f:
45
+ text = f.read()
46
+ match = REGEX_YAML_BLOCK.search(text)
47
+ if match:
48
+ text = text[match.end():]
49
+ return text
50
+
51
+
52
+ def parse_gradio_data(data, input_types):
53
+ """Parses data from gradio Dataframe for use in metric."""
54
+ metric_inputs = {}
55
+ data.replace("", np.nan, inplace=True)
56
+ data.dropna(inplace=True)
57
+ for feature_name, input_type in zip(data, input_types):
58
+ if input_type == "json":
59
+ metric_inputs[feature_name] = [
60
+ json.loads(d) for d in data[feature_name].to_list()
61
+ ]
62
+ elif input_type == "str":
63
+ metric_inputs[feature_name] = [
64
+ d.strip('"') for d in data[feature_name].to_list()
65
+ ]
66
+ else:
67
+ metric_inputs[feature_name] = data[feature_name]
68
+ return metric_inputs
69
+
70
+
71
+ def parse_test_cases(test_cases, feature_names, input_types):
72
+ """
73
+ Parses test cases to be used in gradio Dataframe. Note that an apostrophe is added
74
+ to strings to follow the format in json.
75
+ """
76
+ if len(test_cases) == 0:
77
+ return None
78
+ examples = []
79
+ for test_case in test_cases:
80
+ parsed_cases = []
81
+ for feat, input_type in zip(feature_names, input_types):
82
+ if input_type == "json":
83
+ parsed_cases.append(
84
+ [str(element) for element in test_case[feat]])
85
+ elif input_type == "str":
86
+ parsed_cases.append(
87
+ ['"' + element + '"' for element in test_case[feat]])
88
+ else:
89
+ parsed_cases.append(test_case[feat])
90
+ examples.append([list(i) for i in zip(*parsed_cases)])
91
+ return examples
92
+
93
+
94
+ def launch_gradio_widget(metric):
95
+ """Launches `metric` widget with Gradio."""
96
+
97
+ try:
98
+ import gradio as gr
99
+ except ImportError as error:
100
+ print(
101
+ "To create a metric widget with Gradio make sure gradio is installed."
102
+ )
103
+ raise error
104
+
105
+ local_path = Path(sys.path[0])
106
+ # if there are several input types, use first as default.
107
+ if isinstance(metric.features, list):
108
+ (feature_names, feature_types) = zip(*metric.features[0].items())
109
+ else:
110
+ (feature_names, feature_types) = zip(*metric.features.items())
111
+ gradio_input_types = infer_gradio_input_types(feature_types)
112
+
113
+ def compute(data):
114
+ return metric.compute(**parse_gradio_data(data, gradio_input_types))
115
+
116
+ iface = gr.Interface(
117
+ fn=compute,
118
+ inputs=[
119
+ gr.inputs.Textbox(lines=5, label="Predictions"),
120
+ gr.inputs.Textbox(lines=5, label="Ground Truth")
121
+ ],
122
+ outputs=gr.outputs.Textbox(label=metric.name),
123
+ description=
124
+ (metric.info.description +
125
+ "\nIf this is a text-based metric, make sure to wrap you input in double quotes."
126
+ " Alternatively you can use a JSON-formatted list as input."),
127
+ title=f"Metric: {metric.name}",
128
+ article=parse_readme(local_path / "README.md"),
129
+ # TODO: load test cases and use them to populate examples
130
+ # examples=[parse_test_cases(test_cases, feature_names, gradio_input_types)]
131
+ )
132
+
133
+ iface.launch()