Skip to content

Instantly share code, notes, and snippets.

@nwatab
Last active February 18, 2022 14:44
Show Gist options
  • Save nwatab/e139272963f1bd659fcd532a35c59978 to your computer and use it in GitHub Desktop.
Save nwatab/e139272963f1bd659fcd532a35c59978 to your computer and use it in GitHub Desktop.
SupportersColabJune1
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
@app.route('/users/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
if __name__ == '__main__':
app.run()
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/users')
@app.route('/users/<int:id>')
def users(id=None):
print(id)
users = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Charlie'}]
if id is None:
return jsonify(users)
elif isinstance(id, int) and 1 <= id <= 3:
return jsonify({'id': id, 'name': users[id-1]['name']})
else:
return jsonify({})
if __name__ == '__main__':
app.run()
import os
from flask import Flask, request, redirect, url_for, jsonify
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'uploaded'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return jsonify(filename=filename,
type=filename.rsplit('.', 1)[1].lower())
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
if __name__ == '__main__':
app.run()
import os
from flask import Flask, request, redirect, url_for, jsonify, Response
from werkzeug.utils import secure_filename
from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
from keras.preprocessing import image
import numpy as np
from PIL import Image
import io
app = Flask(__name__)
model = None
def load_model():
global model
model = VGG16(weights='imagenet', include_top=True)
@app.route('/', methods=['GET', 'POST'])
def upload_file():
response = {'success': False}
if request.method == 'POST':
if request.files.get('file'):
img_requested = request.files['file'].read()
img = Image.open(io.BytesIO(img_requested))
if img.mode != 'RGB':
img = img.convert('RGB')
img = img.resize((224, 224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
inputs = preprocess_input(img)
preds = model.predict(inputs)
results = decode_predictions(preds)
response['predictions'] = []
for (imagenetID, label, prob) in results[0]:
row = {'label': label, 'probability': float(prob)}
response['predictions'].append(row)
response['success'] = True
return jsonify(response)
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
if __name__ == '__main__':
load_model()
# no-thread: https://github.com/keras-team/keras/issues/2397#issuecomment-377914683
# avoid model.predict runs before model initiated
app.run(threaded=False)
from keras.applications.vgg16 import VGG16
model = VGG16(weights='imagenet', include_top=True)
print(model.summary())
from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
from keras.preprocessing import image
import numpy as np
img_path = 'cat.jpg' # change to your file
model = VGG16(weights='imagenet', include_top=True)
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
pred = model.predict(x)
label = decode_predictions(pred)
print(label)
absl-py==0.2.1
astor==0.6.2
bleach==1.5.0
click==6.7
Flask==1.0.2
gast==0.2.0
grpcio==1.12.0
h5py==2.7.1
html5lib==0.9999999
itsdangerous==0.24
Jinja2==2.10
Keras==2.1.6
Markdown==2.6.11
MarkupSafe==1.0
numpy==1.14.3
Pillow==5.1.0
protobuf==3.5.2.post1
PyYAML==3.12
scipy==1.1.0
six==1.11.0
tensorboard==1.8.0
tensorflow==1.8.0
termcolor==1.1.0
Werkzeug==0.14.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment