from fastai.vision.all import * import gradio as gr import pathlib import os import platform # The below is for testing your app.py on a Windows laptop e.g. Visual Studio Code print(platform.system()) if platform.system() == 'Windows': # NotImplementedError: cannot instantiate 'PosixPath' on your system # workaround for Windows where path seperator is '/'. Linux is '\'. posix_backup = pathlib.PosixPath # remember the original path thingy try: pathlib.PosixPath = pathlib.WindowsPath # change to Windows path = Path() # get current path in your runtime environment e.g. laptop, Colab, HuggingFace, Kaggle learn = load_learner(path/'export.pkl') finally: # when program is finished, switch back to original path thingy pathlib.PosixPath = posix_backup else: # Darwin aka MacOS, Linux, etc... path = Path() learn = load_learner(path/'export.pkl') # Not needed, since we don't return a dict below # same as bear_types = ['grizzly','black','teddy'] # bear_types = learn.dls.vocab # categories = bear_types def classify_image(img): pred,idx,probs = learn.predict(img) prob = float(probs[idx]) * 100 return f"This is a {pred}.\n Confidence Level : {prob:.4f}%" # return dict(zip(categories, map(float,probs))) # not really needed here # Define example images # These must be local images in your repository. # URLs to images don't seem to work well ? # Image source: Wikipedia examples = ['images/chicken.jpg', 'images/dog.jpg', 'images/fish.jpg'] # Define input component for image upload image_input = gr.Image() # Define output component for displaying text text_output = gr.Textbox(type="text", label="Output") # Define Gradio Interface iface = gr.Interface( fn=classify_image, # the function we defined above inputs=image_input, outputs=text_output, # live=True means you click on any element # and all other elements update immediately. # Therefore, there is no Submit button needed anymore. # Works fine, but may break Clear button, # since there is no image uploaded yet to predict -> Error # AssertionError: Expected an input # live=False will give you a Submit button. live=True, examples=examples ) # Run the interface # To create a public link, set `share=True` in `launch()`. # iface.launch(share=True) # Note: share is for notebooks # When deploying to HuggingFace leave it out, or else -> Error ? iface.launch() # Use CTRL-C to stop server in Visual Studio Code # ^CKeyboard interruption in main thread... closing server. # Killing tunnel 127.0.0.1:7860 <> https://6479f1bbea54b008f.gradio.live