nutripath commited on
Commit
5e4dd9c
·
1 Parent(s): 4c2ba57

initial nutrition ml api

Browse files
Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user ./requirements.txt requirements.txt
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ COPY --chown=user . /app
13
+
14
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import pandas as pd
4
+ import torch
5
+ import matplotlib.pyplot as plt
6
+ from sklearn.preprocessing import LabelEncoder, StandardScaler
7
+ from sklearn.model_selection import train_test_split
8
+
9
+ from model.preprocessing import load_dataset, get_features, encode_labels, scale_features
10
+ from model.nlp import compute_tfidf
11
+ from model.train import train_model
12
+ from model.recommender import compute_similarity, recommend
13
+
14
+ st.set_page_config(page_title="Nutrition AI", page_icon="🥗", layout="wide")
15
+
16
+ # ── Cache model să nu se antreneze la fiecare interacțiune ──
17
+ @st.cache_resource
18
+ def load_and_train():
19
+ df = load_dataset("dataset/food_dataset.csv")
20
+ features, target = get_features(df)
21
+ target_encoded, le = encode_labels(target)
22
+
23
+ tfidf_matrix, vectorizer = compute_tfidf(df['food_description'])
24
+ X_numeric = features.values
25
+ X_text = tfidf_matrix.toarray()
26
+ X = np.hstack((X_numeric, X_text))
27
+
28
+ X_train, X_test, y_train, y_test = train_test_split(
29
+ X, target_encoded, test_size=0.2, random_state=42
30
+ )
31
+ X_train_num, X_test_num = train_test_split(
32
+ X_numeric, test_size=0.2, random_state=42
33
+ )
34
+
35
+ X_train_s, X_test_s = scale_features(X_train, X_test)
36
+
37
+ model, train_loss, val_loss, train_acc, val_acc = train_model(
38
+ X_train_s, y_train, X_test_s, y_test, epochs=100
39
+ )
40
+
41
+ similarity_matrix = compute_similarity(X_train_num)
42
+ df_train = df.iloc[:len(X_train_num)].reset_index(drop=True)
43
+
44
+ scaler = StandardScaler()
45
+ scaler.fit(X_train)
46
+
47
+ return model, le, scaler, similarity_matrix, df_train, train_loss, val_loss, train_acc, val_acc, X_train_num
48
+
49
+ # ── UI ──────────────────────────────────────────────────────
50
+ st.title("🥗 Nutrition AI — Food Analyzer")
51
+ st.markdown("Introdu valorile nutriționale ale unui aliment și primești **clasificarea calorică** și **recomandări similare**.")
52
+
53
+ with st.spinner("⏳ Se antrenează modelul... (doar prima dată)"):
54
+ model, le, scaler, similarity_matrix, df_train, train_loss, val_loss, train_acc, val_acc, X_train_num = load_and_train()
55
+
56
+ st.success("✅ Model antrenat!")
57
+
58
+ # ── Tabs ────────────────────────────────────────────────────
59
+ tab1, tab2, tab3 = st.tabs(["🔍 Analiză aliment", "📊 Grafice training", "📋 Despre proiect"])
60
+
61
+ # ════════════════════════════════════════════════════════════
62
+ # TAB 1 — Predicție + Recomandări
63
+ # ════════════════════════════════════════════════════════════
64
+ with tab1:
65
+ st.subheader("Introdu datele nutriționale")
66
+
67
+ col1, col2 = st.columns(2)
68
+
69
+ with col1:
70
+ protein = st.slider("Proteine (g)", 0.0, 100.0, 25.0, step=0.5)
71
+ carbs = st.slider("Carbohidrați (g)", 0.0, 200.0, 50.0, step=0.5)
72
+ fat = st.slider("Grăsimi (g)", 0.0, 100.0, 15.0, step=0.5)
73
+
74
+ with col2:
75
+ fiber = st.slider("Fibre (g)", 0.0, 50.0, 5.0, step=0.5)
76
+ sugar = st.slider("Zahăr (g)", 0.0, 100.0, 10.0, step=0.5)
77
+ calories_display = protein * 4 + carbs * 4 + fat * 9
78
+ st.metric("🔥 Calorii estimate", f"{calories_display:.0f} kcal")
79
+
80
+ if st.button("🚀 Analizează", use_container_width=True):
81
+
82
+ # Descriere sintetică pentru TF-IDF
83
+ description = f"protein {protein} carbs {carbs} fat {fat} fiber {fiber} sugar {sugar}"
84
+
85
+ # Input numeric
86
+ input_numeric = np.array([[protein, carbs, fat, fiber, sugar]])
87
+
88
+ # Construim X identic ca la training (numeric only pentru input simplu)
89
+ from sklearn.feature_extraction.text import TfidfVectorizer
90
+ tfidf_matrix_full, _ = compute_tfidf(
91
+ pd.concat([df_train['food_description'], pd.Series([description])], ignore_index=True)
92
+ )
93
+ input_text = tfidf_matrix_full[-1].toarray()
94
+
95
+ # Padding dacă dimensiunea diferă
96
+ X_numeric_train_size = X_train_num.shape[1] if hasattr(X_train_num, 'shape') else 5
97
+ input_combined = np.hstack((input_numeric, input_text))
98
+
99
+ # Scale
100
+ if input_combined.shape[1] != scaler.n_features_in_:
101
+ # fallback — folosim doar numeric + zeros pentru text
102
+ input_combined = np.zeros((1, scaler.n_features_in_))
103
+ input_combined[0, :5] = [protein, carbs, fat, fiber, sugar]
104
+
105
+ input_scaled = scaler.transform(input_combined)
106
+ input_tensor = torch.tensor(input_scaled, dtype=torch.float32)
107
+
108
+ model.eval()
109
+ with torch.no_grad():
110
+ output = model(input_tensor)
111
+ pred_class = torch.argmax(output, dim=1).item()
112
+ probs = torch.softmax(output, dim=1).numpy()[0]
113
+
114
+ class_name = le.inverse_transform([pred_class])[0]
115
+
116
+ # Rezultat
117
+ st.divider()
118
+ col_r1, col_r2 = st.columns(2)
119
+
120
+ with col_r1:
121
+ st.subheader("📌 Clasificare calorică")
122
+ if class_name == "low":
123
+ st.success(f"### 🟢 {class_name.upper()}")
124
+ st.write("Aliment cu conținut caloric **scăzut**. Potrivit pentru diete hipocalorice.")
125
+ elif class_name == "medium":
126
+ st.warning(f"### 🟡 {class_name.upper()}")
127
+ st.write("Aliment cu conținut caloric **mediu**. Echilibrat pentru majoritatea dietelor.")
128
+ else:
129
+ st.error(f"### 🔴 {class_name.upper()}")
130
+ st.write("Aliment cu conținut caloric **ridicat**. Consumați cu moderație.")
131
+
132
+ # Probabilități
133
+ st.write("**Probabilități per clasă:**")
134
+ for i, cls in enumerate(le.classes_):
135
+ st.progress(float(probs[i]), text=f"{cls}: {probs[i]*100:.1f}%")
136
+
137
+ with col_r2:
138
+ st.subheader("💡 Feedback nutrițional")
139
+ feedbacks = []
140
+ if protein >= 20:
141
+ feedbacks.append("✅ Bogat în **proteine**")
142
+ if fiber >= 5:
143
+ feedbacks.append("✅ Sursă bună de **fibre**")
144
+ if sugar > 20:
145
+ feedbacks.append("⚠️ Conținut ridicat de **zahăr**")
146
+ if fat > 30:
147
+ feedbacks.append("⚠️ Conținut ridicat de **grăsimi**")
148
+ if carbs < 20:
149
+ feedbacks.append("✅ **Low-carb**")
150
+ if calories_display < 200:
151
+ feedbacks.append("✅ Foarte **puține calorii**")
152
+ if not feedbacks:
153
+ feedbacks.append("ℹ️ Profil nutrițional echilibrat")
154
+
155
+ for f in feedbacks:
156
+ st.markdown(f)
157
+
158
+ # Recomandări
159
+ st.divider()
160
+ st.subheader("🔁 Alimente similare (Cosine Similarity)")
161
+
162
+ sim_input = input_numeric
163
+ all_vecs = np.vstack([X_train_num, sim_input])
164
+ from sklearn.metrics.pairwise import cosine_similarity
165
+ sims = cosine_similarity(sim_input, X_train_num)[0]
166
+ top_indices = np.argsort(sims)[::-1][:5]
167
+
168
+ rec_cols = st.columns(5)
169
+ for idx, col in zip(top_indices, rec_cols):
170
+ row = df_train.iloc[idx]
171
+ with col:
172
+ st.metric(
173
+ label=f"Similarity: {sims[idx]:.3f}",
174
+ value=row['calorie_class'].upper(),
175
+ delta=f"{row['calories']} kcal"
176
+ )
177
+ st.caption(f"P: {row['protein_g']}g | C: {row['carbs_g']}g | F: {row['fat_g']}g")
178
+
179
+ # ════════════════════════════════════════════════════════════
180
+ # TAB 2 — Grafice
181
+ # ════════════════════════════════════════════════════════════
182
+ with tab2:
183
+ st.subheader("📉 Training vs Validation Loss")
184
+ fig1, ax1 = plt.subplots(figsize=(10, 4))
185
+ ax1.plot(train_loss, label='Train Loss', color='steelblue')
186
+ ax1.plot(val_loss, label='Val Loss', color='orange')
187
+ ax1.set_xlabel("Epoch")
188
+ ax1.set_ylabel("Loss")
189
+ ax1.legend()
190
+ ax1.grid(True, alpha=0.3)
191
+ st.pyplot(fig1)
192
+
193
+ st.subheader("📈 Training vs Validation Accuracy")
194
+ fig2, ax2 = plt.subplots(figsize=(10, 4))
195
+ ax2.plot(train_acc, label='Train Accuracy', color='steelblue')
196
+ ax2.plot(val_acc, label='Val Accuracy', color='orange')
197
+ ax2.set_xlabel("Epoch")
198
+ ax2.set_ylabel("Accuracy")
199
+ ax2.legend()
200
+ ax2.grid(True, alpha=0.3)
201
+ st.pyplot(fig2)
202
+
203
+ # ════════════════════════════════════════════════════════════
204
+ # TAB 3 — Despre proiect
205
+ # ════════════════════════════════════════════════════════════
206
+ with tab3:
207
+ st.subheader("🧠 Arhitectura sistemului")
208
+ st.markdown("""
209
+ Proiectul combină **3 tehnici AI**:
210
+
211
+ **1. NLP — TF-IDF**
212
+ - Descrierea nutrițională este transformată într-un vector numeric
213
+ - Permite modelului să înțeleagă pattern-uri textuale
214
+
215
+ **2. Deep Learning — MLP**
216
+ - Rețea neuronală cu 4 straturi (128 → 64 → 32 → 3)
217
+ - Antrenată cu CrossEntropyLoss + class weights
218
+ - Optimizer: Adam | Learning rate: 0.001 | Epoci: 100
219
+
220
+ **3. Recommender System — Cosine Similarity**
221
+ - Compară vectorii nutriționali între alimente
222
+ - Returnează Top 5 alimente cu profil similar
223
+ """)
224
+
225
+ st.subheader("📦 Tehnologii")
226
+ st.markdown("""
227
+ `PyTorch` · `Scikit-learn` · `Pandas` · `Matplotlib` · `Streamlit`
228
+ """)
model/__init__.py ADDED
File without changes
model/food_dataset.csv ADDED
The diff for this file is too large to render. See raw diff
 
model/model.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ class FoodMLP(nn.Module):
5
+
6
+ def __init__(self, input_size, num_classes=3):
7
+ super(FoodMLP, self).__init__()
8
+
9
+ self.layers = nn.Sequential(
10
+ nn.Linear(input_size, 128),
11
+ nn.ReLU(),
12
+ nn.Dropout(0.3),
13
+
14
+ nn.Linear(128, 64),
15
+ nn.ReLU(),
16
+ nn.Dropout(0.3),
17
+
18
+ nn.Linear(64, 32),
19
+ nn.ReLU(),
20
+
21
+ nn.Linear(32, num_classes)
22
+ )
23
+
24
+ def forward(self, x):
25
+ return self.layers(x)
model/nlp.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from sklearn.feature_extraction.text import TfidfVectorizer
2
+
3
+ def compute_tfidf(food_descriptions):
4
+ vectorizer = TfidfVectorizer()
5
+ tfidf_matrix = vectorizer.fit_transform(food_descriptions)
6
+ return tfidf_matrix, vectorizer
model/preprocessing.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from sklearn.preprocessing import LabelEncoder, StandardScaler
3
+
4
+ def load_dataset(path):
5
+ df = pd.read_csv(path)
6
+ df = df.dropna()
7
+ df['food_description'] = df.apply(
8
+ lambda row: f"protein {row['protein_g']} carbs {row['carbs_g']} fat {row['fat_g']} fiber {row['fiber_g']} sugar {row['sugar_g']}",
9
+ axis=1
10
+ )
11
+ return df
12
+
13
+ def get_features(df):
14
+ features = df[['protein_g', 'carbs_g', 'fat_g', 'fiber_g', 'sugar_g']]
15
+ target = df['calorie_class']
16
+ return features, target
17
+
18
+ def encode_labels(target):
19
+ le = LabelEncoder()
20
+ encoded = le.fit_transform(target)
21
+ return encoded, le
22
+
23
+ def scale_features(X_train, X_test):
24
+ scaler = StandardScaler()
25
+ X_train_scaled = scaler.fit_transform(X_train)
26
+ X_test_scaled = scaler.transform(X_test)
27
+ return X_train_scaled, X_test_scaled
model/recommender.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.metrics.pairwise import cosine_similarity
2
+
3
+ def compute_similarity(matrix):
4
+ return cosine_similarity(matrix)
5
+
6
+ def recommend(food_index, similarity_matrix, df, top_k=5):
7
+ scores = list(enumerate(similarity_matrix[food_index]))
8
+ scores = sorted(scores, key=lambda x: x[1], reverse=True)
9
+ scores = scores[1:top_k + 1]
10
+
11
+ results = []
12
+ for i, score in scores:
13
+ row = df.iloc[i]
14
+ results.append({
15
+ 'index': i,
16
+ 'score': round(score, 4),
17
+ 'calories': row['calories'],
18
+ 'protein': row['protein_g'],
19
+ 'carbs': row['carbs_g'],
20
+ 'fat': row['fat_g'],
21
+ 'class': row['calorie_class']
22
+ })
23
+ return results
model/train.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from model import FoodMLP
4
+ from collections import Counter
5
+
6
+ def train_model(X_train, y_train, X_test, y_test, epochs=100):
7
+ input_size = X_train.shape[1]
8
+ model = FoodMLP(input_size)
9
+
10
+ counts = Counter(y_train)
11
+ total = len(y_train)
12
+ weights = [total / counts[i] for i in range(3)]
13
+ class_weights = torch.tensor(weights, dtype=torch.float32)
14
+
15
+ criterion = nn.CrossEntropyLoss(weight=class_weights) # ← FIX aici
16
+ optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
17
+
18
+ X_train_t = torch.tensor(X_train, dtype=torch.float32)
19
+ y_train_t = torch.tensor(y_train, dtype=torch.long)
20
+ X_test_t = torch.tensor(X_test, dtype=torch.float32)
21
+ y_test_t = torch.tensor(y_test, dtype=torch.long)
22
+
23
+ train_loss_history = []
24
+ val_loss_history = []
25
+ train_acc_history = []
26
+ val_acc_history = []
27
+
28
+ for epoch in range(epochs):
29
+ model.train()
30
+ optimizer.zero_grad()
31
+ outputs = model(X_train_t)
32
+ loss = criterion(outputs, y_train_t)
33
+ loss.backward()
34
+ optimizer.step()
35
+
36
+ train_loss_history.append(loss.item())
37
+
38
+ train_preds = torch.argmax(outputs, dim=1)
39
+ train_acc = (train_preds == y_train_t).float().mean().item()
40
+ train_acc_history.append(train_acc)
41
+
42
+ model.eval()
43
+ with torch.no_grad():
44
+ val_outputs = model(X_test_t)
45
+ val_loss = criterion(val_outputs, y_test_t)
46
+ val_loss_history.append(val_loss.item())
47
+
48
+ val_preds = torch.argmax(val_outputs, dim=1)
49
+ val_acc = (val_preds == y_test_t).float().mean().item()
50
+ val_acc_history.append(val_acc)
51
+
52
+ print(f"Epoch {epoch+1}/{epochs} | Train Loss: {loss.item():.4f} | Val Loss: {val_loss.item():.4f} | Train Acc: {train_acc:.4f} | Val Acc: {val_acc:.4f}")
53
+
54
+ return model, train_loss_history, val_loss_history, train_acc_history, val_acc_history
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ flask
2
+ pandas
3
+ scikit-learn
4
+ torch
5
+ numpy