Spaces:
Running
Running
rdsarjito
commited on
Commit
·
314c91a
1
Parent(s):
e88e274
4 commit
Browse files- app.py +204 -40
- model_loader.py +58 -0
- requirements.txt +9 -9
app.py
CHANGED
@@ -1,38 +1,84 @@
|
|
1 |
import streamlit as st
|
2 |
import torch
|
3 |
import torch.nn as nn
|
4 |
-
import numpy as np
|
5 |
-
import pandas as pd
|
6 |
import re
|
7 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
#
|
10 |
-
MODEL_PATH = 'model/alergen_model.pt'
|
11 |
-
MODEL_NAME = 'indobenchmark/indobert-base-p1'
|
12 |
-
TARGET_COLUMNS = ['susu', 'kacang', 'telur', 'makanan_laut', 'gandum']
|
13 |
-
MAX_LEN = 128
|
14 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
15 |
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
|
|
18 |
class MultilabelBertClassifier(nn.Module):
|
19 |
def __init__(self, model_name, num_labels):
|
20 |
super(MultilabelBertClassifier, self).__init__()
|
21 |
self.bert = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=num_labels)
|
|
|
22 |
self.bert.classifier = nn.Linear(self.bert.config.hidden_size, num_labels)
|
23 |
|
24 |
def forward(self, input_ids, attention_mask):
|
25 |
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
|
26 |
return outputs.logits
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
model.to(device)
|
31 |
-
model.eval()
|
32 |
-
|
33 |
-
# Fungsi preprocessing
|
34 |
def clean_text(text):
|
|
|
35 |
text = text.replace('--', ' ')
|
|
|
36 |
text = re.sub(r"http\S+", "", text)
|
37 |
text = re.sub('\n', ' ', text)
|
38 |
text = re.sub("[^a-zA-Z0-9\s]", " ", text)
|
@@ -41,38 +87,156 @@ def clean_text(text):
|
|
41 |
text = text.lower()
|
42 |
return text
|
43 |
|
44 |
-
#
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
encoding = tokenizer.encode_plus(
|
48 |
-
|
49 |
add_special_tokens=True,
|
50 |
-
max_length=
|
|
|
51 |
return_tensors='pt',
|
52 |
-
padding='max_length'
|
53 |
-
truncation=True
|
54 |
)
|
|
|
55 |
input_ids = encoding['input_ids'].to(device)
|
56 |
attention_mask = encoding['attention_mask'].to(device)
|
57 |
-
|
58 |
with torch.no_grad():
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
-
#
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
-
if
|
71 |
-
|
72 |
-
st.warning("Silakan masukkan bahan makanan terlebih dahulu.")
|
73 |
-
else:
|
74 |
-
with st.spinner("Memproses..."):
|
75 |
-
predictions = predict(user_input)
|
76 |
-
st.subheader("📊 Hasil Prediksi:")
|
77 |
-
for allergen, score in predictions.items():
|
78 |
-
st.write(f"- **{allergen}**: {'✅ Terdeteksi' if score > 0.5 else '❌ Tidak terdeteksi'} (Probabilitas: {score:.2f})")
|
|
|
1 |
import streamlit as st
|
2 |
import torch
|
3 |
import torch.nn as nn
|
|
|
|
|
4 |
import re
|
5 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
6 |
+
import numpy as np
|
7 |
+
import os
|
8 |
+
|
9 |
+
# Set page configuration
|
10 |
+
st.set_page_config(
|
11 |
+
page_title="Allergen Detector",
|
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 |
+
# Target columns (allergen types)
|
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('--', ' ')
|
81 |
+
# Basic cleaning
|
82 |
text = re.sub(r"http\S+", "", text)
|
83 |
text = re.sub('\n', ' ', text)
|
84 |
text = re.sub("[^a-zA-Z0-9\s]", " ", text)
|
|
|
87 |
text = text.lower()
|
88 |
return text
|
89 |
|
90 |
+
# Function to load model
|
91 |
+
@st.cache_resource
|
92 |
+
def load_model():
|
93 |
+
try:
|
94 |
+
# Initialize tokenizer
|
95 |
+
tokenizer = AutoTokenizer.from_pretrained('indobenchmark/indobert-base-p2')
|
96 |
+
|
97 |
+
# Initialize model
|
98 |
+
model = MultilabelBertClassifier('indobenchmark/indobert-base-p1', len(target_columns))
|
99 |
+
|
100 |
+
# Load the trained model
|
101 |
+
# In a real deployment, you would use the saved model file
|
102 |
+
# For demo purposes, we'll assume the model file is in the same directory
|
103 |
+
model_path = "model/alergen_model.pt"
|
104 |
+
|
105 |
+
if os.path.exists(model_path):
|
106 |
+
checkpoint = torch.load(model_path, map_location=device)
|
107 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
108 |
+
else:
|
109 |
+
st.error("Model file not found. Please make sure 'alergen_model.pt' is in the same directory.")
|
110 |
+
|
111 |
+
model.to(device)
|
112 |
+
model.eval()
|
113 |
+
|
114 |
+
return model, tokenizer
|
115 |
+
except Exception as e:
|
116 |
+
st.error(f"Error loading model: {str(e)}")
|
117 |
+
return None, None
|
118 |
+
|
119 |
+
# Function to predict allergens
|
120 |
+
def predict_allergens(model, tokenizer, ingredients_text, max_length=128):
|
121 |
+
if not model or not tokenizer:
|
122 |
+
return {}
|
123 |
+
|
124 |
+
# Clean the text
|
125 |
+
cleaned_text = clean_text(ingredients_text)
|
126 |
+
|
127 |
+
# Tokenize
|
128 |
encoding = tokenizer.encode_plus(
|
129 |
+
cleaned_text,
|
130 |
add_special_tokens=True,
|
131 |
+
max_length=max_length,
|
132 |
+
truncation=True,
|
133 |
return_tensors='pt',
|
134 |
+
padding='max_length'
|
|
|
135 |
)
|
136 |
+
|
137 |
input_ids = encoding['input_ids'].to(device)
|
138 |
attention_mask = encoding['attention_mask'].to(device)
|
139 |
+
|
140 |
with torch.no_grad():
|
141 |
+
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
|
142 |
+
predictions = torch.sigmoid(outputs)
|
143 |
+
probabilities = predictions.cpu().numpy()[0]
|
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['binary'][target] = bool(binary_predictions[i])
|
153 |
+
result['probabilities'][target] = float(probabilities[i])
|
154 |
+
|
155 |
+
return result
|
156 |
|
157 |
+
# Main app
|
158 |
+
def main():
|
159 |
+
# Load model and tokenizer
|
160 |
+
model, tokenizer = load_model()
|
161 |
+
|
162 |
+
# Input area
|
163 |
+
st.markdown("### Enter Recipe Ingredients")
|
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 |
+
if use_sample:
|
174 |
+
sample_recipe = "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)"
|
175 |
+
ingredients = sample_recipe
|
176 |
+
st.text_area("Sample recipe:", value=sample_recipe, height=150, disabled=True)
|
177 |
+
|
178 |
+
# Analyze button
|
179 |
+
analyze_button = st.button("Analyze Ingredients")
|
180 |
+
|
181 |
+
# Results section
|
182 |
+
if analyze_button and ingredients:
|
183 |
+
with st.spinner("Analyzing ingredients..."):
|
184 |
+
# Make prediction
|
185 |
+
results = predict_allergens(model, tokenizer, ingredients)
|
186 |
+
|
187 |
+
if results:
|
188 |
+
st.markdown("### Analysis Results")
|
189 |
+
|
190 |
+
# Display results in columns
|
191 |
+
col1, col2 = st.columns(2)
|
192 |
+
|
193 |
+
with col1:
|
194 |
+
st.markdown("#### Detected Allergens:")
|
195 |
+
|
196 |
+
# Check if any allergens were detected
|
197 |
+
if any(results['binary'].values()):
|
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.markdown("#### Confidence Scores:")
|
206 |
+
for allergen, probability in results['probabilities'].items():
|
207 |
+
# Create a progress bar for each allergen
|
208 |
+
st.write(f"{allergen_display_names[allergen]}")
|
209 |
+
st.progress(probability)
|
210 |
+
st.write(f"{probability:.2%}")
|
211 |
+
st.write("")
|
212 |
+
|
213 |
+
# Display a summary
|
214 |
+
st.markdown("### Summary")
|
215 |
+
detected = [allergen_display_names[a] for a, p in results['binary'].items() if p]
|
216 |
+
if detected:
|
217 |
+
st.warning(f"This recipe contains the following allergens: {', '.join(detected)}")
|
218 |
+
else:
|
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 |
+
This allergen detector uses a fine-tuned IndoBERT model to identify common allergens in recipe ingredients.
|
227 |
+
|
228 |
+
The model can detect the following allergens:
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model_loader.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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,9 @@
|
|
1 |
-
streamlit
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
scikit-learn
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
1 |
+
streamlit==1.30.0
|
2 |
+
torch==2.0.1
|
3 |
+
transformers==4.35.2
|
4 |
+
numpy==1.24.3
|
5 |
+
pandas==2.0.3
|
6 |
+
scikit-learn==1.3.0
|
7 |
+
regex==2023.8.8
|
8 |
+
tqdm==4.66.1
|
9 |
+
matplotlib==3.7.2
|