|
|
|
|
|
|
|
|
|
|
|
__all__ = ['install', 'learn', 'categories', 'classify_image', 'classify_image_url', 'image', 'label', 'examples', 'intf', 'intf_text_url']
|
|
|
|
|
|
|
|
|
|
|
|
import subprocess
|
|
import sys
|
|
|
|
def install(package):
|
|
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
|
|
|
|
install("fastai")
|
|
|
|
|
|
|
|
from fastai.vision.all import *
|
|
|
|
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
learn = load_learner('model - 712 images 3 epochs.pkl')
|
|
|
|
categories = ('amateur', 'stock')
|
|
|
|
|
|
|
|
|
|
def classify_image(img):
|
|
tens = tensor(img)
|
|
pred,idx,probs = learn.predict(tens)
|
|
return dict(zip(categories, map(float,probs)))
|
|
|
|
from fastdownload import download_url
|
|
import os
|
|
|
|
def classify_image_url(url_text):
|
|
try:
|
|
dest = 'temp.jpg'
|
|
download_url(url_text, dest, show_progress=False)
|
|
im = Image.open(dest)
|
|
img = im.to_thumb(256,256)
|
|
|
|
os.remove(dest)
|
|
return classify_image(img)
|
|
except:
|
|
|
|
return { categories[0]: 0.0, categories[1]: 0.0 }
|
|
|
|
|
|
def classify_image_url_debug(url_text):
|
|
try:
|
|
dest = 'temp.jpg'
|
|
download_url(url_text, dest, show_progress=False)
|
|
im = Image.open(dest)
|
|
img = im.to_thumb(256,256)
|
|
|
|
os.remove(dest)
|
|
temp = classify_image(img)
|
|
return "Success: " + str(temp)
|
|
except Exception as ex:
|
|
|
|
|
|
error = f"{type(ex).__name__} was raised: {ex}"
|
|
return error;
|
|
|
|
|
|
|
|
|
|
image = gr.inputs.Image(shape=(192, 192))
|
|
label = gr.outputs.Label()
|
|
examples = ['stock.jpg', 'stock2.jpg', 'stock-easy.jpg', 'stock-easy2.jpg', 'combine-stock.jpg', 'washing-machine-stock.jpg', 'glasses-amateur.jpg', 'amateur.jpg', 'amateur2.jpg', 'amateur-easy.jpg', 'amateur-easy2.jpg', 'unsure.jpg']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
desc = "Rudimentary image classifier just to experiment with fast.ai. See [https://www.kaggle.com/code/zachwormgoor/stock-photo-recognizer](https://www.kaggle.com/code/zachwormgoor/stock-photo-recognizer) ";
|
|
|
|
intf = gr.Interface(fn=classify_image, description=desc, inputs=image, outputs=label, examples=examples)
|
|
|
|
|
|
|
|
intf_text_url = gr.Interface(fn=classify_image_url, description=desc, inputs="text", outputs=gr.outputs.Label())
|
|
intf_text_url_debug = gr.Interface(fn=classify_image_url_debug, description=desc, inputs="text", outputs="text")
|
|
|
|
|
|
gr.Markdown("Stock vs amateur photo recognizer. Very rudimentary, just an experiment to try out fast.ai, no refinement. See: https://www.kaggle.com/code/zachwormgoor/stock-photo-recognizer")
|
|
|
|
|
|
gr.TabbedInterface( [intf, intf_text_url, intf_text_url_debug], ["Image file upload", "Image URL", "Image URL debug" ] ).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|