Update app.py
Browse files
app.py
CHANGED
@@ -9,6 +9,50 @@ import matplotlib.pyplot as plt
|
|
9 |
import numpy as np
|
10 |
import gradio as gr
|
11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
image_size = 224
|
14 |
dynamic_size = False
|
@@ -171,4 +215,4 @@ def inference(img):
|
|
171 |
|
172 |
return line
|
173 |
|
174 |
-
gr.Interface(inference,"
|
|
|
9 |
import numpy as np
|
10 |
import gradio as gr
|
11 |
|
12 |
+
#@title Helper functions for loading image (hidden)
|
13 |
+
|
14 |
+
original_image_cache = {}
|
15 |
+
|
16 |
+
def preprocess_image(image):
|
17 |
+
image = np.array(image)
|
18 |
+
# reshape into shape [batch_size, height, width, num_channels]
|
19 |
+
img_reshaped = tf.reshape(image, [1, image.shape[0], image.shape[1], image.shape[2]])
|
20 |
+
# Use `convert_image_dtype` to convert to floats in the [0,1] range.
|
21 |
+
image = tf.image.convert_image_dtype(img_reshaped, tf.float32)
|
22 |
+
return image
|
23 |
+
|
24 |
+
def load_image_from_url(img_url):
|
25 |
+
"""Returns an image with shape [1, height, width, num_channels]."""
|
26 |
+
user_agent = {'User-agent': 'Colab Sample (https://tensorflow.org)'}
|
27 |
+
response = requests.get(img_url, headers=user_agent)
|
28 |
+
image = Image.open(BytesIO(response.content))
|
29 |
+
image = preprocess_image(image)
|
30 |
+
return image
|
31 |
+
|
32 |
+
def load_image(image_url, image_size=256, dynamic_size=False, max_dynamic_size=512):
|
33 |
+
"""Loads and preprocesses images."""
|
34 |
+
# Cache image file locally.
|
35 |
+
if image_url in original_image_cache:
|
36 |
+
img = original_image_cache[image_url]
|
37 |
+
elif image_url.startswith('https://'):
|
38 |
+
img = load_image_from_url(image_url)
|
39 |
+
else:
|
40 |
+
fd = tf.io.gfile.GFile(image_url, 'rb')
|
41 |
+
img = preprocess_image(Image.open(fd))
|
42 |
+
original_image_cache[image_url] = img
|
43 |
+
# Load and convert to float32 numpy array, add batch dimension, and normalize to range [0, 1].
|
44 |
+
img_raw = img
|
45 |
+
if tf.reduce_max(img) > 1.0:
|
46 |
+
img = img / 255.
|
47 |
+
if len(img.shape) == 3:
|
48 |
+
img = tf.stack([img, img, img], axis=-1)
|
49 |
+
if not dynamic_size:
|
50 |
+
img = tf.image.resize_with_pad(img, image_size, image_size)
|
51 |
+
elif img.shape[1] > max_dynamic_size or img.shape[2] > max_dynamic_size:
|
52 |
+
img = tf.image.resize_with_pad(img, max_dynamic_size, max_dynamic_size)
|
53 |
+
return img, img_raw
|
54 |
+
|
55 |
+
|
56 |
|
57 |
image_size = 224
|
58 |
dynamic_size = False
|
|
|
215 |
|
216 |
return line
|
217 |
|
218 |
+
gr.Interface(inference,gr.inputs.Image(type="filepath"),"text").launch()
|