Spaces:
Sleeping
Sleeping
rdsarjito
commited on
Commit
·
9de5935
1
Parent(s):
314c91a
5 commit
Browse files- app.py +138 -156
- model_loader.py +0 -58
- requirements.txt +5 -9
app.py
CHANGED
@@ -2,79 +2,24 @@ import streamlit as st
|
|
2 |
import torch
|
3 |
import torch.nn as nn
|
4 |
import re
|
5 |
-
from transformers import AutoTokenizer
|
6 |
-
import numpy as np
|
7 |
import os
|
|
|
8 |
|
9 |
-
# Set page
|
10 |
st.set_page_config(
|
11 |
-
page_title="Allergen
|
12 |
-
page_icon="
|
13 |
layout="wide"
|
14 |
)
|
15 |
|
16 |
-
# Define styling
|
17 |
-
st.markdown("""
|
18 |
-
<style>
|
19 |
-
.main-header {
|
20 |
-
font-size: 2.5rem;
|
21 |
-
color: #1E88E5;
|
22 |
-
text-align: center;
|
23 |
-
}
|
24 |
-
.sub-header {
|
25 |
-
font-size: 1.5rem;
|
26 |
-
color: #424242;
|
27 |
-
margin-bottom: 1rem;
|
28 |
-
}
|
29 |
-
.result-positive {
|
30 |
-
font-size: 1.2rem;
|
31 |
-
color: #D32F2F;
|
32 |
-
font-weight: bold;
|
33 |
-
}
|
34 |
-
.result-negative {
|
35 |
-
font-size: 1.2rem;
|
36 |
-
color: #388E3C;
|
37 |
-
font-weight: bold;
|
38 |
-
}
|
39 |
-
.footer {
|
40 |
-
text-align: center;
|
41 |
-
color: #616161;
|
42 |
-
margin-top: 2rem;
|
43 |
-
}
|
44 |
-
</style>
|
45 |
-
""", unsafe_allow_html=True)
|
46 |
-
|
47 |
-
# App title and description
|
48 |
-
st.markdown("<h1 class='main-header'>Allergen Detector</h1>", unsafe_allow_html=True)
|
49 |
-
st.markdown("<p class='sub-header'>Detect common allergens in your recipe ingredients</p>", unsafe_allow_html=True)
|
50 |
-
|
51 |
# Set device
|
52 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
53 |
|
54 |
-
#
|
55 |
target_columns = ['susu', 'kacang', 'telur', 'makanan_laut', 'gandum']
|
56 |
-
allergen_display_names = {
|
57 |
-
'susu': 'Milk (Susu)',
|
58 |
-
'kacang': 'Nuts (Kacang)',
|
59 |
-
'telur': 'Eggs (Telur)',
|
60 |
-
'makanan_laut': 'Seafood (Makanan Laut)',
|
61 |
-
'gandum': 'Wheat (Gandum)'
|
62 |
-
}
|
63 |
-
|
64 |
-
# Define model for multilabel classification
|
65 |
-
class MultilabelBertClassifier(nn.Module):
|
66 |
-
def __init__(self, model_name, num_labels):
|
67 |
-
super(MultilabelBertClassifier, self).__init__()
|
68 |
-
self.bert = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=num_labels)
|
69 |
-
# Replace the classification head with our own for multilabel
|
70 |
-
self.bert.classifier = nn.Linear(self.bert.config.hidden_size, num_labels)
|
71 |
-
|
72 |
-
def forward(self, input_ids, attention_mask):
|
73 |
-
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
|
74 |
-
return outputs.logits
|
75 |
|
76 |
# Clean text function
|
77 |
-
@st.cache_data
|
78 |
def clean_text(text):
|
79 |
# Convert dashes to spaces for better tokenization
|
80 |
text = text.replace('--', ' ')
|
@@ -87,38 +32,51 @@ def clean_text(text):
|
|
87 |
text = text.lower()
|
88 |
return text
|
89 |
|
90 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
@st.cache_resource
|
92 |
def load_model():
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
if
|
106 |
-
checkpoint = torch.load(model_path, map_location=device)
|
107 |
model.load_state_dict(checkpoint['model_state_dict'])
|
108 |
else:
|
109 |
-
|
110 |
|
111 |
model.to(device)
|
112 |
model.eval()
|
113 |
-
|
114 |
return model, tokenizer
|
115 |
-
|
116 |
-
st.error(
|
117 |
-
return None,
|
118 |
|
119 |
# Function to predict allergens
|
120 |
def predict_allergens(model, tokenizer, ingredients_text, max_length=128):
|
121 |
-
if not model
|
122 |
return {}
|
123 |
|
124 |
# Clean the text
|
@@ -140,103 +98,127 @@ def predict_allergens(model, tokenizer, ingredients_text, max_length=128):
|
|
140 |
with torch.no_grad():
|
141 |
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
|
142 |
predictions = torch.sigmoid(outputs)
|
143 |
-
|
144 |
-
binary_predictions = (probabilities > 0.5).astype(bool)
|
145 |
-
|
146 |
-
result = {
|
147 |
-
'binary': {},
|
148 |
-
'probabilities': {}
|
149 |
-
}
|
150 |
|
|
|
151 |
for i, target in enumerate(target_columns):
|
152 |
-
result[
|
153 |
-
result['probabilities'][target] = float(probabilities[i])
|
154 |
|
155 |
return result
|
156 |
|
157 |
-
#
|
158 |
def main():
|
159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
model, tokenizer = load_model()
|
161 |
|
162 |
# Input area
|
163 |
-
st.
|
164 |
-
ingredients = st.text_area(
|
165 |
-
"Paste your recipe ingredients here:",
|
166 |
-
height=200,
|
167 |
-
placeholder="Example: 1 bungkus Lontong homemade, 2 butir Telur ayam, 2 kotak kecil Tahu coklat..."
|
168 |
-
)
|
169 |
-
|
170 |
-
# Sample recipe option
|
171 |
-
use_sample = st.checkbox("Use sample recipe")
|
172 |
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
st.
|
177 |
|
178 |
-
#
|
179 |
-
|
|
|
|
|
|
|
|
|
180 |
|
181 |
-
#
|
182 |
-
if
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
|
|
|
|
|
|
|
|
|
|
189 |
|
190 |
-
#
|
191 |
col1, col2 = st.columns(2)
|
192 |
|
193 |
with col1:
|
194 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
|
196 |
-
|
197 |
-
|
198 |
-
for allergen, present in results['binary'].items():
|
199 |
-
if present:
|
200 |
-
st.markdown(f"<p class='result-positive'>✓ {allergen_display_names[allergen]}</p>", unsafe_allow_html=True)
|
201 |
-
else:
|
202 |
-
st.markdown("<p class='result-negative'>No allergens detected</p>", unsafe_allow_html=True)
|
203 |
|
204 |
with col2:
|
205 |
-
st.
|
206 |
-
for allergen,
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
|
|
|
|
|
|
|
|
|
|
212 |
|
213 |
-
#
|
214 |
-
st.
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
st.success("This recipe appears to be free from the common allergens we can detect.")
|
220 |
-
|
221 |
-
st.info("Note: This analysis is based on an AI model and may not be 100% accurate. Always verify allergen information from trusted sources if you have dietary restrictions.")
|
222 |
-
|
223 |
-
# Information section
|
224 |
-
with st.expander("About This App"):
|
225 |
st.write("""
|
226 |
-
|
|
|
|
|
|
|
227 |
|
228 |
-
The model
|
229 |
-
- Milk (Susu)
|
230 |
-
- Nuts (Kacang)
|
231 |
-
- Eggs (Telur)
|
232 |
-
- Seafood (Makanan Laut)
|
233 |
-
- Wheat (Gandum)
|
234 |
-
|
235 |
-
The accuracy of detection depends on how clearly the ingredients are described. The model has been trained on Indonesian recipe data.
|
236 |
""")
|
237 |
-
|
238 |
-
# Footer
|
239 |
-
st.markdown("<p class='footer'>Developed with ❤️ using Streamlit and PyTorch</p>", unsafe_allow_html=True)
|
240 |
|
241 |
if __name__ == "__main__":
|
242 |
main()
|
|
|
2 |
import torch
|
3 |
import torch.nn as nn
|
4 |
import re
|
5 |
+
from transformers import AutoTokenizer
|
|
|
6 |
import os
|
7 |
+
import numpy as np
|
8 |
|
9 |
+
# Set page config
|
10 |
st.set_page_config(
|
11 |
+
page_title="Allergen Detection App",
|
12 |
+
page_icon="🍲",
|
13 |
layout="wide"
|
14 |
)
|
15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
# Set device
|
17 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
18 |
|
19 |
+
# Define target columns (allergens)
|
20 |
target_columns = ['susu', 'kacang', 'telur', 'makanan_laut', 'gandum']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
# Clean text function
|
|
|
23 |
def clean_text(text):
|
24 |
# Convert dashes to spaces for better tokenization
|
25 |
text = text.replace('--', ' ')
|
|
|
32 |
text = text.lower()
|
33 |
return text
|
34 |
|
35 |
+
# Define model for multilabel classification
|
36 |
+
class MultilabelBertClassifier(nn.Module):
|
37 |
+
def __init__(self, model_name, num_labels):
|
38 |
+
super(MultilabelBertClassifier, self).__init__()
|
39 |
+
# Replace with a simpler initialization for inference only
|
40 |
+
from transformers import AutoConfig, AutoModel
|
41 |
+
self.config = AutoConfig.from_pretrained(model_name)
|
42 |
+
self.bert = AutoModel.from_pretrained(model_name)
|
43 |
+
self.classifier = nn.Linear(self.config.hidden_size, num_labels)
|
44 |
+
|
45 |
+
def forward(self, input_ids, attention_mask):
|
46 |
+
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
|
47 |
+
pooled_output = outputs.last_hidden_state[:, 0, :] # Use [CLS] token
|
48 |
+
return self.classifier(pooled_output)
|
49 |
+
|
50 |
+
# Load model function
|
51 |
@st.cache_resource
|
52 |
def load_model():
|
53 |
+
# Load tokenizer
|
54 |
+
tokenizer = AutoTokenizer.from_pretrained('indobenchmark/indobert-base-p2')
|
55 |
+
|
56 |
+
# Initialize model
|
57 |
+
model = MultilabelBertClassifier('indobenchmark/indobert-base-p1', len(target_columns))
|
58 |
+
|
59 |
+
# Check if model exists
|
60 |
+
model_path = "model/alergen_model.pt"
|
61 |
+
|
62 |
+
if os.path.exists(model_path):
|
63 |
+
# Load model weights
|
64 |
+
checkpoint = torch.load(model_path, map_location=device)
|
65 |
+
if 'model_state_dict' in checkpoint:
|
|
|
66 |
model.load_state_dict(checkpoint['model_state_dict'])
|
67 |
else:
|
68 |
+
model.load_state_dict(checkpoint)
|
69 |
|
70 |
model.to(device)
|
71 |
model.eval()
|
|
|
72 |
return model, tokenizer
|
73 |
+
else:
|
74 |
+
st.error("Model file not found. Please upload the model file.")
|
75 |
+
return None, tokenizer
|
76 |
|
77 |
# Function to predict allergens
|
78 |
def predict_allergens(model, tokenizer, ingredients_text, max_length=128):
|
79 |
+
if not model:
|
80 |
return {}
|
81 |
|
82 |
# Clean the text
|
|
|
98 |
with torch.no_grad():
|
99 |
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
|
100 |
predictions = torch.sigmoid(outputs)
|
101 |
+
predictions = (predictions > 0.5).float().cpu().numpy()[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
+
result = {}
|
104 |
for i, target in enumerate(target_columns):
|
105 |
+
result[target] = bool(predictions[i])
|
|
|
106 |
|
107 |
return result
|
108 |
|
109 |
+
# UI components
|
110 |
def main():
|
111 |
+
st.title("🍲 Allergen Detection in Indonesian Recipes")
|
112 |
+
st.write("This app predicts common allergens in your recipe based on ingredients.")
|
113 |
+
|
114 |
+
# Sidebar for model upload
|
115 |
+
with st.sidebar:
|
116 |
+
st.header("Model Settings")
|
117 |
+
uploaded_model = st.file_uploader("Upload model file (model/alergen_model.pt)", type=["pt"])
|
118 |
+
|
119 |
+
if uploaded_model:
|
120 |
+
# Save uploaded model
|
121 |
+
with open("model/alergen_model.pt", "wb") as f:
|
122 |
+
f.write(uploaded_model.getbuffer())
|
123 |
+
st.success("Model uploaded successfully!")
|
124 |
+
|
125 |
+
st.markdown("---")
|
126 |
+
st.write("Allergen Categories:")
|
127 |
+
for allergen in target_columns:
|
128 |
+
if allergen == 'susu':
|
129 |
+
st.write("- Susu (Milk)")
|
130 |
+
elif allergen == 'kacang':
|
131 |
+
st.write("- Kacang (Nuts)")
|
132 |
+
elif allergen == 'telur':
|
133 |
+
st.write("- Telur (Eggs)")
|
134 |
+
elif allergen == 'makanan_laut':
|
135 |
+
st.write("- Makanan Laut (Seafood)")
|
136 |
+
elif allergen == 'gandum':
|
137 |
+
st.write("- Gandum (Wheat/Gluten)")
|
138 |
+
|
139 |
+
# Load model
|
140 |
model, tokenizer = load_model()
|
141 |
|
142 |
# Input area
|
143 |
+
st.header("Recipe Ingredients")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
144 |
|
145 |
+
# Example button
|
146 |
+
if st.button("Load Example"):
|
147 |
+
example_text = "1 bungkus Lontong homemade 2 butir Telur ayam 2 kotak kecil Tahu coklat 4 butir kecil Kentang 2 buah Tomat merah 1 buah Ketimun lalap 4 lembar Selada keriting 2 lembar Kol putih 2 porsi Saus kacang homemade 4 buah Kerupuk udang goreng Secukupnya emping goreng 2 sdt Bawang goreng Secukupnya Kecap manis (bila suka)"
|
148 |
+
st.session_state.ingredients = example_text
|
149 |
|
150 |
+
# Text input
|
151 |
+
ingredients_text = st.text_area(
|
152 |
+
"Enter recipe ingredients (in Indonesian):",
|
153 |
+
height=150,
|
154 |
+
key="ingredients"
|
155 |
+
)
|
156 |
|
157 |
+
# Predict button
|
158 |
+
if st.button("Detect Allergens"):
|
159 |
+
if ingredients_text.strip() == "":
|
160 |
+
st.warning("Please enter ingredients first.")
|
161 |
+
elif model is None:
|
162 |
+
st.error("Please upload the model file first.")
|
163 |
+
else:
|
164 |
+
with st.spinner("Analyzing ingredients..."):
|
165 |
+
# Make prediction
|
166 |
+
allergens = predict_allergens(model, tokenizer, ingredients_text)
|
167 |
+
|
168 |
+
# Display results
|
169 |
+
st.header("Results")
|
170 |
|
171 |
+
# Create columns for results
|
172 |
col1, col2 = st.columns(2)
|
173 |
|
174 |
with col1:
|
175 |
+
st.subheader("Detected Allergens:")
|
176 |
+
has_allergens = False
|
177 |
+
for allergen, present in allergens.items():
|
178 |
+
if present:
|
179 |
+
has_allergens = True
|
180 |
+
if allergen == 'susu':
|
181 |
+
st.warning("🥛 Susu (Milk)")
|
182 |
+
elif allergen == 'kacang':
|
183 |
+
st.warning("🥜 Kacang (Nuts)")
|
184 |
+
elif allergen == 'telur':
|
185 |
+
st.warning("🥚 Telur (Eggs)")
|
186 |
+
elif allergen == 'makanan_laut':
|
187 |
+
st.warning("🦐 Makanan Laut (Seafood)")
|
188 |
+
elif allergen == 'gandum':
|
189 |
+
st.warning("🌾 Gandum (Wheat/Gluten)")
|
190 |
|
191 |
+
if not has_allergens:
|
192 |
+
st.success("✅ No allergens detected!")
|
|
|
|
|
|
|
|
|
|
|
193 |
|
194 |
with col2:
|
195 |
+
st.subheader("All Categories:")
|
196 |
+
for allergen, present in allergens.items():
|
197 |
+
if allergen == 'susu':
|
198 |
+
st.write("🥛 Susu (Milk): " + ("Detected ⚠️" if present else "Not detected ✓"))
|
199 |
+
elif allergen == 'kacang':
|
200 |
+
st.write("🥜 Kacang (Nuts): " + ("Detected ⚠️" if present else "Not detected ✓"))
|
201 |
+
elif allergen == 'telur':
|
202 |
+
st.write("🥚 Telur (Eggs): " + ("Detected ⚠️" if present else "Not detected ✓"))
|
203 |
+
elif allergen == 'makanan_laut':
|
204 |
+
st.write("🦐 Makanan Laut (Seafood): " + ("Detected ⚠️" if present else "Not detected ✓"))
|
205 |
+
elif allergen == 'gandum':
|
206 |
+
st.write("🌾 Gandum (Wheat/Gluten): " + ("Detected ⚠️" if present else "Not detected ✓"))
|
207 |
|
208 |
+
# Show cleaned text
|
209 |
+
with st.expander("Processed Text"):
|
210 |
+
st.code(clean_text(ingredients_text))
|
211 |
+
|
212 |
+
# Instructions and information
|
213 |
+
with st.expander("How to Use"):
|
|
|
|
|
|
|
|
|
|
|
|
|
214 |
st.write("""
|
215 |
+
1. First, upload the trained model file (`model/alergen_model.pt`) using the sidebar uploader
|
216 |
+
2. Enter your recipe ingredients in the text box (in Indonesian)
|
217 |
+
3. Click the "Detect Allergens" button to analyze the recipe
|
218 |
+
4. View the results showing which allergens are present in your recipe
|
219 |
|
220 |
+
The model detects five common allergen categories: milk, nuts, eggs, seafood, and wheat/gluten.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
221 |
""")
|
|
|
|
|
|
|
222 |
|
223 |
if __name__ == "__main__":
|
224 |
main()
|
model_loader.py
DELETED
@@ -1,58 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
from transformers import AutoModelForSequenceClassification
|
4 |
-
|
5 |
-
# Define target columns
|
6 |
-
target_columns = ['susu', 'kacang', 'telur', 'makanan_laut', 'gandum']
|
7 |
-
|
8 |
-
# Define model class - same as in your original code
|
9 |
-
class MultilabelBertClassifier(nn.Module):
|
10 |
-
def __init__(self, model_name, num_labels):
|
11 |
-
super(MultilabelBertClassifier, self).__init__()
|
12 |
-
self.bert = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=num_labels)
|
13 |
-
# Replace the classification head with our own for multilabel
|
14 |
-
self.bert.classifier = nn.Linear(self.bert.config.hidden_size, num_labels)
|
15 |
-
|
16 |
-
def forward(self, input_ids, attention_mask):
|
17 |
-
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
|
18 |
-
return outputs.logits
|
19 |
-
|
20 |
-
# Function to load the saved model
|
21 |
-
def load_saved_model(model_path, device='cpu'):
|
22 |
-
"""
|
23 |
-
Load the saved allergen detection model
|
24 |
-
|
25 |
-
Args:
|
26 |
-
model_path (str): Path to the saved model file
|
27 |
-
device (str): Device to load the model onto ('cpu' or 'cuda')
|
28 |
-
|
29 |
-
Returns:
|
30 |
-
model: The loaded model
|
31 |
-
"""
|
32 |
-
try:
|
33 |
-
# Create model instance
|
34 |
-
model = MultilabelBertClassifier('indobenchmark/indobert-base-p1', len(target_columns))
|
35 |
-
|
36 |
-
# Load saved weights
|
37 |
-
checkpoint = torch.load(model_path, map_location=device)
|
38 |
-
|
39 |
-
# Check if model was saved using DataParallel
|
40 |
-
if 'module.' in list(checkpoint['model_state_dict'].keys())[0]:
|
41 |
-
# Create new OrderedDict without 'module.' prefix
|
42 |
-
from collections import OrderedDict
|
43 |
-
new_state_dict = OrderedDict()
|
44 |
-
for k, v in checkpoint['model_state_dict'].items():
|
45 |
-
name = k[7:] if k.startswith('module.') else k
|
46 |
-
new_state_dict[name] = v
|
47 |
-
model.load_state_dict(new_state_dict)
|
48 |
-
else:
|
49 |
-
model.load_state_dict(checkpoint['model_state_dict'])
|
50 |
-
|
51 |
-
# Move model to device and set to evaluation mode
|
52 |
-
model.to(device)
|
53 |
-
model.eval()
|
54 |
-
|
55 |
-
return model
|
56 |
-
except Exception as e:
|
57 |
-
print(f"Error loading model: {str(e)}")
|
58 |
-
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -1,9 +1,5 @@
|
|
1 |
-
streamlit
|
2 |
-
torch
|
3 |
-
transformers
|
4 |
-
numpy
|
5 |
-
|
6 |
-
scikit-learn==1.3.0
|
7 |
-
regex==2023.8.8
|
8 |
-
tqdm==4.66.1
|
9 |
-
matplotlib==3.7.2
|
|
|
1 |
+
streamlit>=1.25.0
|
2 |
+
torch>=2.0.0
|
3 |
+
transformers>=4.30.0
|
4 |
+
numpy>=1.22.0
|
5 |
+
protobuf>=3.20.0
|
|
|
|
|
|
|
|