vinay-jose commited on
Commit
2d998c0
·
verified ·
1 Parent(s): 675c11a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -0
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fasthtml.common import *
2
+ from fasthtml.components import *
3
+ from fastai.vision.all import *
4
+ from PIL import Image
5
+ import io
6
+
7
+ app, rt = fast_app()
8
+ learn = load_learner("model.pkl")
9
+
10
+ def classify_image(img):
11
+ char,idx,probs = learn.predict(img)
12
+ im = Image.open(img).to_thumb(256,256)
13
+ name = " ".join([s.capitalize() for s in (char).split("_")])
14
+ return name, idx, probs
15
+
16
+ @rt('/')
17
+ def index():
18
+ return Titled("Chair vs Lamp Classifier",
19
+ Div(
20
+ H2("Example Images"),
21
+ Div(
22
+ Img(src="chair1.jpg", hx_trigger="click", hx_get="/classify", hx_target="#result"),
23
+ Img(src="chair2.jpg", hx_trigger="click", hx_get="/classify", hx_target="#result"),
24
+ Img(src="lamp1.jpg", hx_trigger="click", hx_get="/classify", hx_target="#result"),
25
+ Img(src="lamp2.jpg", hx_trigger="click", hx_get="/classify", hx_target="#result"),
26
+ cls="flex flex-wrap justify-center gap-4"
27
+ ),
28
+ H2("Upload an Image"),
29
+ Button("Upload Image", hx_post="/upload", hx_target="#result"),
30
+ Div(id="result")
31
+ )
32
+ )
33
+
34
+ @rt('/classify')
35
+ def classify(img_file: UploadFile):
36
+ img_bytes = img_file.files['image'].read()
37
+ img = Image.open(io.BytesIO(img_bytes))
38
+
39
+ name, idx, probs = classify_image(img)
40
+ return Div(Div(f"This is {name}."),
41
+ Div(f"Probability it's {name}: {probs[idx]:.4f}"))
42
+
43
+ @rt('/upload', methods=['POST'])
44
+ def upload(img_file: UploadFile):
45
+ img_bytes = img_file.files['image'].read()
46
+ img = Image.open(io.BytesIO(img_bytes))
47
+
48
+ name, idx, probs = classify_image(img)
49
+ return Div(Div(f"This is {name}."),
50
+ Div(f"Probability it's {name}: {probs[idx]:.4f}"))
51
+
52
+ serve()