Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_path_exists(self):
out = outputs.Label()
path = outputs.BASE_OUTPUT_INTERFACE_TEMPLATE_PATH.format(out.get_name())
self.assertTrue(os.path.exists(os.path.join(PACKAGE_NAME, path)))
def test_output_interface_is_instance(self):
out = gradio.outputs.Label(show_confidences=False)
io = Interface(inputs='SketCHPad', outputs=out, model=lambda x: x, model_type='function')
self.assertEqual(io.output_interface, out)
def test_input_output_mapping(self):
io = Interface(inputs='SketCHPad', outputs='textBOX', model=lambda x: x, model_type='function')
self.assertIsInstance(io.input_interface, gradio.inputs.Sketchpad)
self.assertIsInstance(io.output_interface, gradio.outputs.Textbox)
def postprocessing(pred):
if pred[0][0] > 0.5:
return json.dumps({"label": "Positive review"})
else:
return json.dumps({"label": "Negative review"})
textbox = gradio.inputs.Textbox(preprocessing_fn=preprocessing,
sample_inputs=[
"A wonderful little production. The filming technique is very unassuming- very old-time-BBC fashion and gives a comforting, and sometimes discomforting, sense of realism to the entire piece. The actors are extremely well chosen- Michael Sheen not only has got all the polari but he has all the voices down pat too! You can truly see the seamless editing guided by the references to Williams' diary entries, not only is it well worth the watching but it is a terrificly written and performed piece. A masterful production about one of the great master's of comedy and his life. The realism really comes home with the little things: the fantasy of the guard which, rather than use the traditional 'dream' techniques remains solid then disappears.",
"This was a very brief episode that appeared in one of the Night Gallery show back in 1971. The episode starred Sue Lyon (of Lolita movie fame) and Joseph Campanella who play a baby sitter and a vampire, respectively. The vampire hires a baby sitter to watch his child (which appears to be some kind of werewolf or monster) while he goes out at night for blood. I don't know what purpose it was to make such an abbreviated episode that lasted just 5 minutes. They should just have expanded the earlier episode by those same 5 minutes and skipped this one. A total wasted effort.",
"No one expects the Star Trek movies to be high art, but the fans do expect a movie that is as good as some of the best episodes. Unfortunately, this movie had a muddled, implausible plot that just left me cringing - this is by far the worst of the nine (so far) movies. Even the chance to watch the well known characters interact in another movie can't save this movie - including the goofy scenes with Kirk, Spock and McCoy at Yosemite.I would say this movie is not worth a rental, and hardly worth watching, however for the True Fan who needs to see all the movies, renting this movie is about the only way you'll see it - even the cable channels avoid this movie.",
"This movie started out cringe-worthy--but it was meant to, with an overbearing mother, a witch of a rival, and a hesitant beauty queen constantly coming in second. There was some goofy overacting, and a few implausible plot points (She comes in second in EVERY single competition? ALL of them?) Unfortunately, the movie suffers horribly from it's need to, well, be a TV movie. Rather than end at the ending of the movie, an amusing twist in which the killer is (semi-plausibly) revealed, the movie continues for another twenty minutes, just to make sure that justice is done. Of course, now that the killer is revealed, she suddenly undergoes a complete personality shift--her character gets completely rewritten, because the writers don't need to keep her identity secret any more. The cheese completely sinks what otherwise could have been a passably amusing movie.",
"I thought this movie did a down right good job. It wasn't as creative or original as the first, but who was expecting it to be. It was a whole lotta fun. the more i think about it the more i like it, and when it comes out on DVD I'm going to pay the money for it very proudly, every last cent. Sharon Stone is great, she always is, even if her movie is horrible(Catwoman), but this movie isn't, this is one of those movies that will be underrated for its lifetime, and it will probably become a classic in like 20 yrs. Don't wait for it to be a classic, watch it now and enjoy it. Don't expect a masterpiece, or something thats gripping and soul touching, just allow yourself to get out of your life and get yourself involved in theirs.All in all, this movie is entertaining and i recommend people who haven't seen it see it.",
"I rented this movie, but I wasn't too sure what to expect of it. I was very glad to find that it's about the best Brazilian movie I've ever seen. The story is rather odd and simple, and above all, extremely original. We have Antonio, who is a young man living in Nordestina, a town in the middle of nowhere in the north east of Brazil, and who is deeply in love with Karina. The main conflict between the two is that, while Antonio loves his little town and has no wish to leave it, Karina wants to see the world and resents the place. As a prove of his love for her, he decides to go out himself and bring the world to her. He'll put Nordestina in the map, as he says. And the way he does it is unbelievable. This is a good movie; might be a bit stagy for some people due to its different editing job, but I think that it's also that that improves the story. It's just fun, and it makes you feel good."])
label = gradio.outputs.Label(postprocessing_fn=postprocessing)
io = gradio.Interface(inputs=textbox, outputs=label, model_type="keras", model=model, always_flag=True)
httpd, path_to_local_server, share_url = io.launch(share=True, inbrowser=True)
print("URL for IMDB model interface: ", share_url)
for i in range(start_idx + 1, 500):
heat_map.extend([normalized_saliency[i]] * len(words[counter]))
heat_map.append(0) # zero saliency value assigned to the spaces between words
counter += 1
return np.array(heat_map)
textbox = gradio.inputs.Textbox(preprocessing_fn=preprocessing,
sample_inputs=[
"A wonderful little production. The filming technique is very unassuming- very old-time-BBC fashion and gives a comforting, and sometimes discomforting, sense of realism to the entire piece. The actors are extremely well chosen- Michael Sheen not only has got all the polari but he has all the voices down pat too! You can truly see the seamless editing guided by the references to Williams' diary entries, not only is it well worth the watching but it is a terrificly written and performed piece. A masterful production about one of the great master's of comedy and his life. The realism really comes home with the little things: the fantasy of the guard which, rather than use the traditional 'dream' techniques remains solid then disappears.",
"This was a very brief episode that appeared in one of the Night Gallery show back in 1971. The episode starred Sue Lyon (of Lolita movie fame) and Joseph Campanella who play a baby sitter and a vampire, respectively. The vampire hires a baby sitter to watch his child (which appears to be some kind of werewolf or monster) while he goes out at night for blood. I don't know what purpose it was to make such an abbreviated episode that lasted just 5 minutes. They should just have expanded the earlier episode by those same 5 minutes and skipped this one. A total wasted effort.",
"No one expects the Star Trek movies to be high art, but the fans do expect a movie that is as good as some of the best episodes. Unfortunately, this movie had a muddled, implausible plot that just left me cringing - this is by far the worst of the nine (so far) movies. Even the chance to watch the well known characters interact in another movie can't save this movie - including the goofy scenes with Kirk, Spock and McCoy at Yosemite.I would say this movie is not worth a rental, and hardly worth watching, however for the True Fan who needs to see all the movies, renting this movie is about the only way you'll see it - even the cable channels avoid this movie.",
"This movie started out cringe-worthy--but it was meant to, with an overbearing mother, a witch of a rival, and a hesitant beauty queen constantly coming in second. There was some goofy overacting, and a few implausible plot points (She comes in second in EVERY single competition? ALL of them?) Unfortunately, the movie suffers horribly from it's need to, well, be a TV movie. Rather than end at the ending of the movie, an amusing twist in which the killer is (semi-plausibly) revealed, the movie continues for another twenty minutes, just to make sure that justice is done. Of course, now that the killer is revealed, she suddenly undergoes a complete personality shift--her character gets completely rewritten, because the writers don't need to keep her identity secret any more. The cheese completely sinks what otherwise could have been a passably amusing movie.",
"I thought this movie did a down right good job. It wasn't as creative or original as the first, but who was expecting it to be. It was a whole lotta fun. the more i think about it the more i like it, and when it comes out on DVD I'm going to pay the money for it very proudly, every last cent. Sharon Stone is great, she always is, even if her movie is horrible(Catwoman), but this movie isn't, this is one of those movies that will be underrated for its lifetime, and it will probably become a classic in like 20 yrs. Don't wait for it to be a classic, watch it now and enjoy it. Don't expect a masterpiece, or something thats gripping and soul touching, just allow yourself to get out of your life and get yourself involved in theirs.All in all, this movie is entertaining and i recommend people who haven't seen it see it.",
"I rented this movie, but I wasn't too sure what to expect of it. I was very glad to find that it's about the best Brazilian movie I've ever seen. The story is rather odd and simple, and above all, extremely original. We have Antonio, who is a young man living in Nordestina, a town in the middle of nowhere in the north east of Brazil, and who is deeply in love with Karina. The main conflict between the two is that, while Antonio loves his little town and has no wish to leave it, Karina wants to see the world and resents the place. As a prove of his love for her, he decides to go out himself and bring the world to her. He'll put Nordestina in the map, as he says. And the way he does it is unbelievable. This is a good movie; might be a bit stagy for some people due to its different editing job, but I think that it's also that that improves the story. It's just fun, and it makes you feel good."])
label = gradio.outputs.Label(postprocessing_fn=postprocessing)
io = gradio.Interface(inputs=textbox, outputs=label, model_type="keras", model=model, saliency=saliency, always_flag=True)
httpd, path_to_local_server, share_url = io.launch(share=True, inbrowser=True, inline=False)
print("URL for IMDB model interface: ", share_url)
# Move association file to root of temporary directory.
copyfile(os.path.join(temp_dir, ASSOCIATION_PATH_IN_STATIC),
os.path.join(temp_dir, ASSOCIATION_PATH_IN_ROOT))
render_template_with_tags(
os.path.join(
temp_dir,
inputs.BASE_INPUT_INTERFACE_JS_PATH.format(input_interface.get_name()),
),
input_interface.get_js_context(),
)
render_template_with_tags(
os.path.join(
temp_dir,
outputs.BASE_OUTPUT_INTERFACE_JS_PATH.format(output_interface.get_name()),
),
output_interface.get_js_context(),
)
output = output.argmax()
input_tensors = [model.inputs[0], K.learning_phase()]
saliency_input = model.layers[0].input
saliency_output = model.layers[-1].output[:, output]
gradients = model.optimizer.get_gradients(saliency_output, saliency_input)
compute_gradients = K.function(inputs=input_tensors, outputs=gradients)
saliency_graph = compute_gradients(processed_input.reshape(-1, 784))
normalized_saliency = (abs(saliency_graph[0]) - abs(saliency_graph[0]).min()) / \
(abs(saliency_graph[0]).max() - abs(saliency_graph[0]).min())
return normalized_saliency.reshape(28, 28)
model = get_trained_model(n=50000)
sketchpad = gradio.inputs.Sketchpad(flatten=True, sample_inputs=x_test[:10])
label = gradio.outputs.Label(show_confidences=False)
io = gradio.Interface(inputs=sketchpad, outputs=label, model=model, model_type="keras", saliency=saliency, always_flag=True)
httpd, path_to_local_server, share_url = io.launch(inline=True, share=True, inbrowser=True)
print("URL for MNIST model interface with saliency:", share_url)
provided.
:param preprocessing_fns: an optional function that overrides the preprocessing function of the input interface.
:param postprocessing_fns: an optional function that overrides the postprocessing fn of the output interface.
:param saliency: an optional function that takes the model and the processed input and returns a 2-d array
"""
if isinstance(inputs, str):
self.input_interface = gradio.inputs.registry[inputs.lower()](
preprocessing_fns
)
elif isinstance(inputs, gradio.inputs.AbstractInput):
self.input_interface = inputs
else:
raise ValueError("Input interface must be of type `str` or `AbstractInput`")
if isinstance(outputs, str):
self.output_interface = gradio.outputs.registry[outputs.lower()](
postprocessing_fns
)
elif isinstance(outputs, gradio.outputs.AbstractOutput):
self.output_interface = outputs
else:
raise ValueError(
"Output interface must be of type `str` or `AbstractOutput`"
)
self.model_obj = model
if model_type is None:
model_type = self._infer_model_type(model)
if verbose:
print(
"Model type not explicitly identified, inferred to be: {}".format(
self.VALID_MODEL_TYPES[model_type]
)
provided.
:param preprocessing_fns: an optional function that overrides the preprocessing function of the input interface.
:param postprocessing_fns: an optional function that overrides the postprocessing fn of the output interface.
:param saliency: an optional function that takes the model and the processed input and returns a 2-d array
"""
if isinstance(inputs, str):
self.input_interface = gradio.inputs.registry[inputs.lower()](
preprocessing_fns
)
elif isinstance(inputs, gradio.inputs.AbstractInput):
self.input_interface = inputs
else:
raise ValueError("Input interface must be of type `str` or `AbstractInput`")
if isinstance(outputs, str):
self.output_interface = gradio.outputs.registry[outputs.lower()](
postprocessing_fns
)
elif isinstance(outputs, gradio.outputs.AbstractOutput):
self.output_interface = outputs
else:
raise ValueError(
"Output interface must be of type `str` or `AbstractOutput`"
)
self.model_obj = model
if model_type is None:
model_type = self._infer_model_type(model)
if verbose:
print(
"Model type not explicitly identified, inferred to be: {}".format(
self.VALID_MODEL_TYPES[model_type]
)