How to Build and Deploy a Deep-Learning Multi-Classifier Web App (Part 2)
Create a local neural network Gradio App
machinelearning
ai
Author
Tony Phung
Published
January 25, 2024
This post shows how to create a Gradio App (app.py) and run it locally in a browser. This app should:
Allow users to upload an image
Make a Prediction of the breed of dog or cat
Provide a Probability on the predictions of available breeds (dataset used only has 37 different breeds)
This post is part of a series:
Part 1: Create Learner (.pkl file)
Part 2: Create Gradio application file (app.py)
Part 3: Upload to HuggingFace account
Part 2: Create Gradio application file (app.py)
1. Import Gradio and Fast AI libraries
from fastai.vision.allimport*import gradio as gr
c:\Users\tonyp\miniconda3\envs\fastai\Lib\site-packages\torchvision\io\image.py:13: UserWarning: Failed to load image Python extension: '[WinError 127] The specified procedure could not be found'If you don't plan on using image functionality from `torchvision.io`, you can ignore this warning. Otherwise, there might be something wrong with your environment. Did you have `libjpeg` or `libpng` installed before building `torchvision` from source?
warn(
2. Import Learner (.pkl file)
Recall, this file was created and exported in Part 1
If you’re running on a Linux, you shouldn’t have any import issues.
If you’re running a Windows PC, you’ll likely to experience an error.
pets_learner = load_learner('pets_learner.pkl')
---------------------------------------------------------------------------NotImplementedError Traceback (most recent call last)
Cell In[4], line 1----> 1 pets_learner =load_learner('pets_learner.pkl')
File c:\Users\tonyp\miniconda3\envs\fastai\Lib\site-packages\fastai\learner.py:446, in load_learner(fname, cpu, pickle_module) 444 distrib_barrier()
445 map_loc ='cpu'if cpu else default_device()
--> 446try: res =torch.load(fname,map_location=map_loc,pickle_module=pickle_module) 447exceptAttributeErroras e:
448 e.args = [f"Custom classes or functions exported with your `Learner` not available in namespace.\Re-declare/import before loading:\n\t{e.args[0]}"]
File c:\Users\tonyp\miniconda3\envs\fastai\Lib\site-packages\torch\serialization.py:1014, in load(f, map_location, pickle_module, weights_only, mmap, **pickle_load_args) 1012exceptRuntimeErroras e:
1013raise pickle.UnpicklingError(UNSAFE_MESSAGE +str(e)) fromNone-> 1014return_load(opened_zipfile, 1015map_location, 1016pickle_module, 1017overall_storage=overall_storage, 1018**pickle_load_args) 1019if mmap:
1020raiseRuntimeError("mmap can only be used with files saved with ",
1021"`torch.save(_use_new_zipfile_serialization=True), " 1022"please torch.save your checkpoint with this option in order to use mmap.")
File c:\Users\tonyp\miniconda3\envs\fastai\Lib\site-packages\torch\serialization.py:1422, in _load(zip_file, map_location, pickle_module, pickle_file, overall_storage, **pickle_load_args) 1420 unpickler = UnpicklerWrapper(data_file, **pickle_load_args)
1421 unpickler.persistent_load = persistent_load
-> 1422 result =unpickler.load() 1424 torch._utils._validate_loaded_sparse_tensors()
1425 torch._C._log_api_usage_metadata(
1426"torch.load.metadata", {"serialization_id": zip_file.serialization_id()}
1427 )
File c:\Users\tonyp\miniconda3\envs\fastai\Lib\pathlib.py:873, in Path.__new__(cls, *args, **kwargs) 871self=cls._from_parts(args)
872ifnotself._flavour.is_supported:
--> 873raiseNotImplementedError("cannot instantiate %r on your system" 874% (cls.__name__,))
875returnselfNotImplementedError: cannot instantiate 'PosixPath' on your system
I found a solution here.
Not too sure why this happens, probably linux vs windows compatibility, forward vs backlashes probably?
Import the pathlib library below and run the code below to fix the paths:
Note:
- This fix is only required during the testing phase of our Gradio App.
- This testing phase is defined as being able to run the Gradio App locally.
- When we Upload to HuggingFace Spaces, this code fix is not required (because HF is run on Linux, hence no Posix issues, from my understanding)
# only run to import pkl in windows when youre doing testing in windows | when run in hus | its run via dock images ie linux ie no problemsimport pathlib # temp = pathlib.PosixPathpathlib.PosixPath = pathlib.WindowsPath
Use predict() to make prediction on the uploaded local image. The results will have 3 items:
1. The prediction of the breed.
2. Index of the Tensor (in point 3.)
3. A Tensor of length 37. Why the odd number?
- These are the probabilities of each unique breeds in our data!
- Recall in Part 1, we determined the different categories by using a custom labelling function
res = pets_learner.predict(pet1)res
c:\Users\tonyp\miniconda3\envs\fastai\Lib\site-packages\fastai\torch_core.py:263: UserWarning: 'has_mps' is deprecated, please use 'torch.backends.mps.is_built()'
return getattr(torch, 'has_mps', False)
# get index of predctionidx = res[1]# store list of probalities of our predctionprobabilities = res[2]# get breed and probability of our predictioncategories[idx],probabilities[idx]