Suraj-Yadav commited on
Commit
494f436
·
verified ·
1 Parent(s): 15e7d4b

Uploading food not food text classifier demo app

Browse files
README.md CHANGED
@@ -1,12 +0,0 @@
1
- ---
2
- title: Food Not Food Text Classifier App
3
- emoji: 📉
4
- colorFrom: yellow
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 4.44.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
__pycache__/constants.cpython-310.pyc ADDED
Binary file (317 Bytes). View file
 
__pycache__/utility.cpython-310.pyc ADDED
Binary file (2.6 kB). View file
 
app.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from demos.food_not_food_text_classifier.app_utility import gradio_food_classifier
4
+
5
+ description = """
6
+ A text classifier to determine if a sentence is about food or not food.
7
+
8
+ Fine-tuned from [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) on a [small dataset of food and not food text](https://huggingface.co/datasets/mrdbourke/learn_hf_food_not_food_image_captions).
9
+
10
+ See [source code](https://github.com/mrdbourke/learn-huggingface/blob/main/notebooks/hugging_face_text_classification_tutorial.ipynb).
11
+ """
12
+
13
+ demo = gr.Interface(fn=gradio_food_classifier,
14
+ inputs="text",
15
+ outputs=gr.Label(num_top_classes=2),
16
+ title="🍗🚫🥑 Food or Not Food Text Classifier App",
17
+ description=description,
18
+ examples=[["I whipped up a fresh batch of code, but it seems to have a syntax error."],
19
+ ["A delicious photo of a plate of scrambled eggs, bacon and toast."]])
20
+
21
+
22
+ if __name__ == "__main__":
23
+ demo.launch()
app_utility.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Union,Dict
3
+ from transformers import pipeline
4
+ from constants import HUGGINGFACE_MODEL_PATH
5
+
6
+
7
+ def set_device() -> torch.device:
8
+ """
9
+ Set the device to the best available option: CUDA (if available), MPS (if available on Mac),
10
+ or CPU as a fallback. Provides a robust selection mechanism for production environments.
11
+
12
+ Returns:
13
+ torch.device: The best available device for computation.
14
+ """
15
+ if torch.cuda.is_available():
16
+ return torch.device("cuda")
17
+ elif torch.backends.mps.is_available() and torch.backends.mps.is_built():
18
+ return torch.device("mps")
19
+ else:
20
+ return torch.device("cpu")
21
+
22
+
23
+ def food_not_food_classifier(
24
+ text: Union[str, list],
25
+ model_path: str,
26
+ batch_size: int = 32,
27
+ device: str = None,
28
+ get_classifier:bool = False
29
+ ) -> Dict[str, float]:
30
+ """
31
+ Classifies whether the given text is related to food or not, returning a dictionary of labels and their scores.
32
+
33
+ Args:
34
+ text (Union[str, list]): The input text or list of texts to classify.
35
+ model_path (str): The path to the Hugging Face model for classification.
36
+ batch_size (int): The batch size for processing. Default is 32.
37
+ device (str): The device to run inference on (e.g., 'cuda', 'cpu'). Default is None (auto-detect best available).
38
+
39
+ Returns:
40
+ Dict[str, float]: A dictionary where the keys are the labels and the values are the classification scores.
41
+ """
42
+
43
+ if device is None:
44
+ device = set_device()
45
+
46
+ classifier = pipeline(
47
+ task="text-classification",
48
+ model=model_path,
49
+ batch_size=batch_size,
50
+ device=device,
51
+ top_k=None # Keep all predictions
52
+ )
53
+
54
+ if get_classifier:
55
+ return classifier
56
+ else:
57
+
58
+ results = classifier(text) # [[{'label': 'food', 'score': 0.9500328898429871}, {'label': 'not_food', 'score': 0.04996709153056145}]]
59
+
60
+ output_dict = {}
61
+ for output in results[0]:
62
+ output_dict[output['label']] = output['score']
63
+
64
+ return output_dict
65
+
66
+
67
+ def gradio_food_classifier(text: str) -> dict:
68
+ """
69
+ A wrapper function for Gradio to classify text using the classify_food_text function.
70
+
71
+ Args:
72
+ text (str): The input text to classify.
73
+
74
+ Returns:
75
+ dict: Classification results as a dictionary of label and score.
76
+ """
77
+ classifier = food_not_food_classifier(text=text,
78
+ model_path=HUGGINGFACE_MODEL_PATH,
79
+ get_classifier=True)
80
+
81
+ results = classifier(text)
82
+
83
+ output_dict = {}
84
+ for output in results[0]:
85
+ output_dict[output['label']] = output['score']
86
+
87
+ return output_dict
constants.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ HUGGINGFACE_MODEL_PATH = "Suraj-Yadav/learn_hf_food_not_food_text_classifier-distilbert-base-uncased"
2
+
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ torch
3
+ transformers