Deployment4: MLApps deployment on Huggingface Space

Deploying model and application with huggingface space, aiking and fastai

Open In Colab

Compatibility Block

Check Platform

Platform & Environment Configuration

Imports

Public Imports

import os
from fastdownload import download_url
import pathlib
import warnings
warnings.filterwarnings("ignore")
import requests
from huggingface_hub import from_pretrained_fastai
from fastai.vision.all import *
import streamlit as st
from streamlit_jupyter import StreamlitPatcher, tqdm

Private Imports

Loading Learner

We have already trained our model in previous notebook. We now quickly review steps to verify the model.

uname = "rahuketu86"
dsname = "PandemicSafety"
url = "https://zealmaker.com/curations/courses/fastai_dl1/02d_deployment"
model_root = f"Model-{dsname}"
model_repo = f"{uname}/{model_root}"; model_repo
learn = from_pretrained_fastai(model_repo)
space_root = f"Space-{dsname}"
space_repo = f"{uname}/{space_root}"; space_repo
'rahuketu86/Space-PandemicSafety'

Gradio App

Generate some examples

example_url = "https://datasette.zealmaker.com/PandemicSafety.json?p2=180&p0=1&sql=select%20image%20from%20cleaned_v1%20where%20rowid%20in%20(%3Ap0%2C%20%3Ap1%2C%20%3Ap2)%20order%20by%20rowid%20limit%20101&p1=2"
urls = requests.get(example_url).json()['rows']
example_files = L(urls).itemgot(0).map(lambda url: download_url(url)); example_files
107.42% [57344/53384 00:00<00:00]
101.44% [114688/113056 00:00<00:00]
114.17% [40960/35875 00:00<00:00]
(#3) [Path('close-up-face-pretty-woman-walking-city-wearing-leather-jacket-concept-positive-emotions-urban-look-young-female-person-113846433.jpg'),Path('black-white-urban-city-warehouse-street-alleyway-road-path-man-male-guy-dude-mid-s-age-face-portrait-outdoors-season-graffiti-134283772.jpg'),Path('covid-19-indoor-spaces.jpg')]
examples = list(get_image_files(".").map(lambda e : str(e))); examples
['black-white-urban-city-warehouse-street-alleyway-road-path-man-male-guy-dude-mid-s-age-face-portrait-outdoors-season-graffiti-134283772.jpg',
 'close-up-face-pretty-woman-walking-city-wearing-leather-jacket-concept-positive-emotions-urban-look-young-female-person-113846433.jpg',
 'covid-19-indoor-spaces.jpg',
 'xkcd.png']
examples = [ e for e in examples if e in example_files.map(lambda e: e.name)]; examples
['black-white-urban-city-warehouse-street-alleyway-road-path-man-male-guy-dude-mid-s-age-face-portrait-outdoors-season-graffiti-134283772.jpg',
 'close-up-face-pretty-woman-walking-city-wearing-leather-jacket-concept-positive-emotions-urban-look-young-female-person-113846433.jpg',
 'covid-19-indoor-spaces.jpg']
labels = learn.dls.vocab
def predict(img):
    img = PILImage.create(img)
    pred, pred_idx, probs = learn.predict(img)
    return dict(zip(labels, map(float, probs)))
article="<p style='text-align: center'><a href='https://zealmaker.com/curations/courses/fastai_dl1/02d_deployment' target='_blank'>zealmaker.com</a></p>"
demo = gr.Interface(fn=predict, 
                    inputs=gr.inputs.Image(shape=(512, 512)), 
                    outputs=gr.outputs.Label(num_top_classes=2),
                    title = dsname,
                    article=article,
                    interpretation='default',
                    examples = examples,
                    enable_queue=True
                   );demo
demo.launch()
Running on local URL:  http://127.0.0.1:7861

To create a public link, set `share=True` in `launch()`.
huggingface_hub[fastai]
gradio
scikit-image
Writing requirements.txt
import nbdev; nbdev.export.nb_export("02d_deployment.ipynb", lib_path=".")
from huggingface_hub import create_repo, HfApi, notebook_login
notebook_login()
create_repo(space_repo, repo_type='space', space_sdk='gradio', exist_ok=True)
RepoUrl('https://huggingface.co/spaces/rahuketu86/Space-PandemicSafety', endpoint='https://huggingface.co', repo_type='space', repo_id='rahuketu86/Space-PandemicSafety')
files_to_upload=examples+['requirements.txt', 'app.py']; files_to_upload
['black-white-urban-city-warehouse-street-alleyway-road-path-man-male-guy-dude-mid-s-age-face-portrait-outdoors-season-graffiti-134283772.jpg',
 'close-up-face-pretty-woman-walking-city-wearing-leather-jacket-concept-positive-emotions-urban-look-young-female-person-113846433.jpg',
 'covid-19-indoor-spaces.jpg',
 'requirements.txt',
 'app.py']
api = HfApi()
for fname in files_to_upload:
    api.upload_file(path_or_fileobj=fname, path_in_repo=fname, repo_id=space_repo, repo_type='space')
L(files_to_upload).map(lambda e: Path(e).unlink())
(#5) [None,None,None,None,None]