File size: 1,914 Bytes
2579dcf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# 1. Import the required packages
import torch
import gradio as gr
from typing import Dict
from transformers import pipeline
# 2. Define our function to use with our model.
def food_not_food_classifier(text: str) -> Dict[str, float]:
# 2. Setup food not food text classifier
food_not_food_classifier_pipeline = pipeline(task="text-classification",
model="mrdbourke/learn_hf_food_not_food_text_classifier-distilbert-base-uncased",
batch_size=32,
device="cuda" if torch.cuda.is_available() else "cpu",
top_k=None) # top_k=None => return all possible labels
# 3. Get the outputs from our pipeline
outputs = food_not_food_classifier_pipeline(text)[0]
# 4. Format output for Gradio
output_dict = {}
for item in outputs:
output_dict[item["label"]] = item["score"]
return output_dict
# 3. Create a Gradio interface
description = """
A text classifier to determine if a sentence is about food or not food.
Fine-tuned from [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) a [dataset of LLM generated food/not_food image captions](https://huggingface.co/datasets/mrdbourke/learn_hf_food_not_food_image_captions).
See [source code](https://github.com/mrdbourke/learn-huggingface/blob/main/notebooks/hugging_face_text_classification_tutorial.ipynb).
"""
demo = gr.Interface(
fn=food_not_food_classifier,
inputs="text",
outputs=gr.Label(num_top_classes=2),
title="ππ«π₯ Food or Not Food Text Classifier",
description=description,
examples=[["I whipped up a fresh batch of code, but it to seems to have a syntax error"],
["A plate of pancakes and strawberry icing"]]
)
# 4. Launch the interface
if __name__ == "__main__":
demo.launch()
|