mirror of
https://github.com/gradio-app/gradio.git
synced 2024-12-21 02:19:59 +08:00
Merge pull request #15 from gradio-app/aliabd/python-backwards-compatability
python backwards compatability
This commit is contained in:
commit
681ff9d0a4
@ -32,7 +32,7 @@ def launch_interface(args):
|
||||
pass
|
||||
|
||||
def service_shutdown(signum, frame):
|
||||
print('Shutting server down due to signal %d' % signum)
|
||||
print('Shutting server down due to signal {}'.format(signum))
|
||||
httpd.shutdown()
|
||||
raise ServiceExit
|
||||
|
||||
|
@ -114,8 +114,8 @@ class Sketchpad(AbstractInput):
|
||||
|
||||
im = preprocessing_utils.decode_base64_to_image(msg)
|
||||
timestamp = time.time()*1000
|
||||
filename = f'input_{timestamp}.png'
|
||||
im.save(f'{dir}/{filename}', 'PNG')
|
||||
filename = 'input_{}.png'.format(timestamp)
|
||||
im.save('{}/{}'.format(dir, filename), 'PNG')
|
||||
return filename
|
||||
|
||||
def get_sample_inputs(self):
|
||||
@ -160,8 +160,8 @@ class Webcam(AbstractInput):
|
||||
inp = msg['data']['input']
|
||||
im = preprocessing_utils.decode_base64_to_image(inp)
|
||||
timestamp = time.time()*1000
|
||||
filename = f'input_{timestamp}.png'
|
||||
im.save(f'{dir}/{filename}', 'PNG')
|
||||
filename = 'input_{}.png'.format(timestamp)
|
||||
im.save('{}/{}'.format(dir, filename), 'PNG')
|
||||
return filename
|
||||
|
||||
|
||||
@ -187,8 +187,8 @@ class Textbox(AbstractInput):
|
||||
Default rebuild method for text saves it .txt file
|
||||
"""
|
||||
timestamp = time.time()*1000
|
||||
filename = f'input_{timestamp}'
|
||||
with open(f'{dir}/{filename}.txt','w') as f:
|
||||
filename = 'input_{}'.format(timestamp)
|
||||
with open('{}/{}.txt'.format(dir, filename),'w') as f:
|
||||
f.write(msg)
|
||||
return filename
|
||||
|
||||
@ -241,8 +241,8 @@ class ImageIn(AbstractInput):
|
||||
"""
|
||||
im = preprocessing_utils.decode_base64_to_image(msg)
|
||||
timestamp = time.time()*1000
|
||||
filename = f'input_{timestamp}.png'
|
||||
im.save(f'{dir}/{filename}', 'PNG')
|
||||
filename = 'input_{}.png'.format(timestamp)
|
||||
im.save('{}/{}'.format(dir, filename), 'PNG')
|
||||
return filename
|
||||
|
||||
# TODO(abidlabs): clean this up
|
||||
@ -250,8 +250,8 @@ class ImageIn(AbstractInput):
|
||||
"""
|
||||
"""
|
||||
timestamp = time.time()*1000
|
||||
filename = f'input_{timestamp}.png'
|
||||
img.save(f'{dir}/{filename}', 'PNG')
|
||||
filename = 'input_{}.png'.format(timestamp)
|
||||
img.save('{}/{}'.format(dir, filename), 'PNG')
|
||||
return filename
|
||||
|
||||
|
||||
|
@ -95,7 +95,7 @@ class Interface:
|
||||
for m, msg in enumerate(validation_inputs):
|
||||
if self.verbose:
|
||||
print(
|
||||
f"Validating samples: {m+1}/{n} ["
|
||||
"Validating samples: {}/{} [".format(m+1, n)
|
||||
+ "=" * (m + 1)
|
||||
+ "." * (n - m - 1)
|
||||
+ "]",
|
||||
@ -174,9 +174,10 @@ class Interface:
|
||||
current_pkg_version = pkg_resources.require("gradio")[0].version
|
||||
latest_pkg_version = requests.get(url=PKG_VERSION_URL).json()["version"]
|
||||
if StrictVersion(latest_pkg_version) > StrictVersion(current_pkg_version):
|
||||
print(f"IMPORTANT: You are using gradio version {current_pkg_version}, "
|
||||
f"however version {latest_pkg_version} "
|
||||
f"is available, please upgrade.")
|
||||
print("IMPORTANT: You are using gradio version {}, "
|
||||
"however version {} "
|
||||
"is available, please upgrade.".format(
|
||||
current_pkg_version, latest_pkg_version))
|
||||
print('--------')
|
||||
except: # TODO(abidlabs): don't catch all exceptions
|
||||
pass
|
||||
|
@ -172,8 +172,75 @@ def serve_files_in_background(interface, port, directory_to_serve=None):
|
||||
f.write(json.dumps(output))
|
||||
f.write("\n")
|
||||
|
||||
#TODO(abidlabs): clean this up
|
||||
elif self.path == "/api/auto/rotation":
|
||||
from gradio import validation_data, preprocessing_utils
|
||||
import numpy as np
|
||||
|
||||
self._set_headers()
|
||||
data_string = self.rfile.read(int(self.headers["Content-Length"]))
|
||||
msg = json.loads(data_string)
|
||||
img_orig = preprocessing_utils.decode_base64_to_image(msg["data"])
|
||||
img_orig = img_orig.convert('RGB')
|
||||
img_orig = img_orig.resize((224, 224))
|
||||
|
||||
flag_dir = os.path.join(directory_to_serve, FLAGGING_DIRECTORY)
|
||||
os.makedirs(flag_dir, exist_ok=True)
|
||||
|
||||
for deg in range(-180, 180+45, 45):
|
||||
img = img_orig.rotate(deg)
|
||||
img_array = np.array(img) / 127.5 - 1
|
||||
prediction = interface.predict(np.expand_dims(img_array, axis=0))
|
||||
processed_output = interface.output_interface.postprocess(prediction)
|
||||
output = {'input': interface.input_interface.save_to_file(flag_dir, img),
|
||||
'output': interface.output_interface.rebuild_flagged(
|
||||
flag_dir, {'data': {'output': processed_output}}),
|
||||
'message': 'rotation by {} degrees'.format(
|
||||
deg)}
|
||||
|
||||
with open(os.path.join(flag_dir, FLAGGING_FILENAME), 'a+') as f:
|
||||
f.write(json.dumps(output))
|
||||
f.write("\n")
|
||||
|
||||
# Prepare return json dictionary.
|
||||
self.wfile.write(json.dumps({}).encode())
|
||||
|
||||
elif self.path == "/api/auto/lighting":
|
||||
from gradio import validation_data, preprocessing_utils
|
||||
import numpy as np
|
||||
from PIL import ImageEnhance
|
||||
|
||||
self._set_headers()
|
||||
data_string = self.rfile.read(int(self.headers["Content-Length"]))
|
||||
msg = json.loads(data_string)
|
||||
img_orig = preprocessing_utils.decode_base64_to_image(msg["data"])
|
||||
img_orig = img_orig.convert('RGB')
|
||||
img_orig = img_orig.resize((224, 224))
|
||||
enhancer = ImageEnhance.Brightness(img_orig)
|
||||
|
||||
flag_dir = os.path.join(directory_to_serve, FLAGGING_DIRECTORY)
|
||||
os.makedirs(flag_dir, exist_ok=True)
|
||||
|
||||
for i in range(9):
|
||||
img = enhancer.enhance(i/4)
|
||||
img_array = np.array(img) / 127.5 - 1
|
||||
prediction = interface.predict(np.expand_dims(img_array, axis=0))
|
||||
processed_output = interface.output_interface.postprocess(prediction)
|
||||
output = {'input': interface.input_interface.save_to_file(flag_dir, img),
|
||||
'output': interface.output_interface.rebuild_flagged(
|
||||
flag_dir, {'data': {'output': processed_output}}),
|
||||
'message': 'brighting adjustment by a factor '
|
||||
'of {}'.format(i)}
|
||||
|
||||
with open(os.path.join(flag_dir, FLAGGING_FILENAME), 'a+') as f:
|
||||
f.write(json.dumps(output))
|
||||
f.write("\n")
|
||||
|
||||
# Prepare return json dictionary.
|
||||
self.wfile.write(json.dumps({}).encode())
|
||||
|
||||
else:
|
||||
self.send_error(404, 'Path not found: %s' % self.path)
|
||||
self.send_error(404, 'Path not found: {}'.format(self.path))
|
||||
|
||||
class HTTPServer(BaseHTTPServer):
|
||||
"""The main server, you pass in base_path which is the path you want to serve requests from"""
|
||||
|
@ -124,8 +124,9 @@ class Image(AbstractOutput):
|
||||
"""
|
||||
im = preprocessing_utils.decode_base64_to_image(msg)
|
||||
timestamp = datetime.datetime.now()
|
||||
filename = f'output_{timestamp.strftime("%Y-%m-%d-%H-%M-%S")}.png'
|
||||
im.save(f'{dir}/{filename}', 'PNG')
|
||||
filename = 'output_{}.png'.format(timestamp.
|
||||
strftime("%Y-%m-%d-%H-%M-%S"))
|
||||
im.save('{}/{}'.format(dir, filename), 'PNG')
|
||||
return filename
|
||||
|
||||
|
||||
|
@ -19,12 +19,13 @@ def handler(chan, host, port):
|
||||
try:
|
||||
sock.connect((host, port))
|
||||
except Exception as e:
|
||||
verbose("Forwarding request to %s:%d failed: %r" % (host, port, e))
|
||||
verbose("Forwarding request to {}:{} failed: {}".format(host, port, e))
|
||||
return
|
||||
|
||||
verbose(
|
||||
"Connected! Tunnel open %r -> %r -> %r"
|
||||
% (chan.origin_addr, chan.getpeername(), (host, port))
|
||||
"Connected! Tunnel open {} -> {} -> {}".format(chan.origin_addr,
|
||||
chan.getpeername(),
|
||||
(host, port))
|
||||
)
|
||||
while True:
|
||||
r, w, x = select.select([sock, chan], [], [])
|
||||
@ -40,7 +41,7 @@ def handler(chan, host, port):
|
||||
sock.send(data)
|
||||
chan.close()
|
||||
sock.close()
|
||||
verbose("Tunnel closed from %r" % (chan.origin_addr,))
|
||||
verbose("Tunnel closed from {}".format(chan.origin_addr,))
|
||||
|
||||
|
||||
def reverse_forward_tunnel(server_port, remote_host, remote_port, transport):
|
||||
@ -65,7 +66,8 @@ def create_tunnel(payload, local_server, local_server_port):
|
||||
client.set_missing_host_key_policy(paramiko.WarningPolicy())
|
||||
|
||||
verbose(
|
||||
"Connecting to ssh host %s:%d ..." % (payload["host"], int(payload["port"]))
|
||||
"Connecting to ssh host {}:{} ...".format(payload["host"], int(payload[
|
||||
"port"]))
|
||||
)
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
@ -78,14 +80,16 @@ def create_tunnel(payload, local_server, local_server_port):
|
||||
)
|
||||
except Exception as e:
|
||||
print(
|
||||
"*** Failed to connect to %s:%d: %r"
|
||||
% (payload["host"], int(payload["port"]), e)
|
||||
"*** Failed to connect to {}:{}: {}}".format(payload["host"],
|
||||
int(payload["port"]), e)
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
verbose(
|
||||
"Now forwarding remote port %d to %s:%d ..."
|
||||
% (int(payload["remote_port"]), local_server, local_server_port)
|
||||
"Now forwarding remote port {} to {}:{} ...".format(int(payload[
|
||||
"remote_port"]),
|
||||
local_server,
|
||||
local_server_port)
|
||||
)
|
||||
|
||||
thread = threading.Thread(
|
||||
|
BIN
screenshots/.image_interface.png.icloud
Normal file
BIN
screenshots/.image_interface.png.icloud
Normal file
Binary file not shown.
BIN
web/img/.cheetah-clean.png.icloud
Normal file
BIN
web/img/.cheetah-clean.png.icloud
Normal file
Binary file not shown.
Loading…
Reference in New Issue
Block a user