This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
152 lines (114 loc) · 3.63 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# -*- coding: utf-8 -*-
"""
An app to make inferences from geofignet.
"""
from io import BytesIO, StringIO
import uuid
import base64
import urllib
import requests
from PIL import Image
from flask import Flask
from flask import make_response, send_file
from flask import request, jsonify, render_template, flash
import numpy as np
import torch
from torchvision import models
import geofignet as gfn
CLASS_NAMES = ['blockdiagram',
'chronostrat',
'corephoto',
'correlation',
'equation',
'fieldnote',
'fmilog',
'geologicmap',
'outcrop',
'photomicrograph',
'regionalsection',
'rosediagram',
'seismic',
'semicrograph',
'stereonet',
'structuremap',
'synthetic',
'table',
'ternary',
'welllog',
]
# Instantiate a vanilla ResNet and adjust its shape.
model = models.resnet18()
model.fc = torch.nn.Linear(model.fc.in_features, len(CLASS_NAMES))
# Load the geofignet weights.
device = torch.device("cpu")
model = torch.load('data/geofignet.pt', map_location=device)
# Evaluate it before inference.
_ = model.eval()
# Error handling
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
app = Flask(__name__)
# Routes and handlers
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/api', methods=["GET", "POST"])
def api():
if request.method == "GET":
if not request.args:
return render_template('api.html')
reqs = [{'image': request.args.get('image')}]
else:
reqs = request.json.get('requests')
if len(reqs) > 10:
return "Number of images exceeded maximum of 10."
result = {'job_uuid': uuid.uuid1()}
result['n_requests'] = len(reqs)
result['results'] = []
for req in reqs:
if req['image'].startswith('http'):
r = requests.get(req['image'])
img = Image.open(BytesIO(r.content)).convert('RGB')
else:
img = Image.open(BytesIO(base64.b64decode(req['image']))).convert('RGB')
probs = gfn.infer(model, img)
prob = max(probs)
clas = CLASS_NAMES[np.argmax(probs)]
this = {'top_class': clas}
this['top_prob'] = prob
this['classes'] = CLASS_NAMES
this['probabilities'] = probs
result['results'].append(this)
return jsonify(result)
@app.route('/infer', methods=["GET"])
def infer():
url = urllib.parse.unquote(request.args.get('image'))
if not url:
flash("You must provide the URL of an image.")
return render_template('index.html')
# Get image.
r = requests.get(url)
img = Image.open(BytesIO(r.content))
probs = gfn.infer(model, img)
prob = format(max(probs), "0.3f")
clas = CLASS_NAMES[np.argmax(probs)]
plot = gfn.plot(probs, CLASS_NAMES)
return render_template('index.html', clas=clas, prob=prob, url=url, plot=plot)
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/')
def main():
return render_template('index.html')