rdsarjito commited on
Commit
9de5935
·
1 Parent(s): 314c91a
Files changed (3) hide show
  1. app.py +138 -156
  2. model_loader.py +0 -58
  3. 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, 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('--', ' ')
@@ -87,38 +32,51 @@ def clean_text(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
@@ -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
- 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()
 
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==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
 
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