berkeruveyik commited on
Commit
2c0573e
·
verified ·
1 Parent(s): 55c9ec5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -51
app.py CHANGED
@@ -3,65 +3,65 @@ import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
5
 
6
- # Model'i yükle
7
- print("Model yükleniyor...")
8
  model = tf.keras.models.load_model('finetuned_food_270.keras')
9
- print("Model başarıyla yüklendi!")
10
 
11
- # Sınıf isimlerini yükle
12
  with open('labels.txt', 'r', encoding='utf-8') as f:
13
  class_names = [line.strip() for line in f.readlines()]
14
- print(f"{len(class_names)} sınıf yüklendi")
15
 
16
- # --- 1. DÜZELTME: GÖRÜNTÜ BOYUTU ---
17
- # Modeli eğittiğiniz boyutu buraya girin
18
  IMG_SIZE = (224, 224)
19
 
20
  def preprocess_image(image):
21
- """Resmi model için hazırla"""
22
 
23
- # PIL Image'a çevir ve RGB yap
24
  if isinstance(image, np.ndarray):
25
  img = Image.fromarray(image)
26
  else:
27
  img = image
28
 
29
- # RGB'ye çevir (grayscale olabilir)
30
  img = img.convert('RGB')
31
 
32
- # Resize (Eğitimde kullandığınız boyuta)
33
  img = img.resize(IMG_SIZE)
34
 
35
- # Numpy array'e çevir (dtype=float32 olmalı)
36
  img_array = np.array(img, dtype=np.float32)
37
 
38
- # Batch dimension ekle
39
  img_array = np.expand_dims(img_array, axis=0)
40
 
41
- # --- 2. DÜZELTME: V2 ÖN İŞLEME ---
42
- # EfficientNetV2 (B2) bu V1 ön işleme fonksiyonunu KULLANMAZ.
43
- # Bu satırı SİLİN veya YORUM SATIRI yapın:
44
  # img_array = tf.keras.applications.efficientnet.preprocess_input(img_array)
45
 
46
- # Modeliniz V2 olduğu için [0, 255] aralığında girdi bekler (şu anki hali).
47
  return img_array
48
 
49
  def predict(image):
50
- """Yemek tahmin fonksiyonu"""
51
  try:
52
- # Görüntüyü işle
53
  processed_image = preprocess_image(image)
54
 
55
- # Tahmin yap
56
  predictions = model.predict(processed_image, verbose=0)
57
 
58
- # Softmax çıktısını al (ilk batch)
59
  predictions = predictions[0]
60
 
61
- # Top 5 tahmini bul
62
  top_indices = np.argsort(predictions)[-5:][::-1]
63
 
64
- # Sonuçları hazırla
65
  results = {}
66
  for idx in top_indices:
67
  label = class_names[idx]
@@ -70,53 +70,77 @@ def predict(image):
70
 
71
  return results
72
  except Exception as e:
73
- print(f"Hata: {e}")
74
- return {"Hata": str(e)}
75
 
76
- # --- Gradio Arayüzü (Değişiklik yok) ---
77
  with gr.Blocks(title="Food 270 Classifier") as demo:
78
- # ... (Arayüz kodunuzun kalanı aynı kalabilir) ...
79
  gr.Markdown("""
80
- # 🍽️ Food 270 Yemek Sınıflandırıcı
81
- **270 farklı yemek türünü tanıyabilen yapay zeka modeli**
82
- 📸 Bir yemek fotoğrafı yükleyin ve hangi yemek olduğunu tahmin ettirin!
83
  """)
 
 
84
  with gr.Row():
 
85
  with gr.Column(scale=1):
86
- input_image = gr.Image(label="Yemek Fotoğrafı", type="numpy")
 
 
87
  with gr.Row():
88
- clear_btn = gr.Button("🗑️ Temizle", variant="secondary")
89
- submit_btn = gr.Button("🔍 Tahmin Et", variant="primary")
 
 
90
  with gr.Column(scale=1):
91
- output = gr.Label(label="Tahmin Sonuçları", num_top_classes=5, show_label=True)
 
 
92
  gr.Markdown("""
93
- ### 📊 Sonuç Açıklaması
94
- - **En yüksek skor** en olası yemek türüdür
95
- - Skorlar **0-1 arası** güven seviyesini gösterir
96
- - **Top 5** en olası tahmin gösterilir
97
  """)
 
 
98
  with gr.Row():
99
  gr.Markdown("""
100
- ### 💡 İpuçları
101
- - Net ve iyi ışıklandırılmış fotoğraflar daha iyi sonuç verir
102
- - Yemeğin tam görünmesi tahmini iyileştirir
103
- - Tek bir yemek türü içeren fotoğraflar idealdir
104
  """)
 
 
105
  gr.Markdown("""
106
  ---
107
- ### 🤖 Model Bilgileri
108
  - **Model**: EfficientNetV2B2 (Fine-tuned)
109
  - **Dataset**: Food 270
110
- - **Sınıf Sayısı**: 270 farklı yemek
111
- - **Eğitim Boyutu**: 224x224
112
- *Geliştirici: Berker Üveyik*
113
  """)
114
- submit_btn.click(fn=predict, inputs=input_image, outputs=output)
115
- clear_btn.click(lambda: (None, None), inputs=None, outputs=[input_image, output])
 
 
 
 
 
 
 
 
 
 
 
116
 
117
- # Uygulamayı başlat
118
  if __name__ == "__main__":
119
  demo.launch(
120
- share=False,
121
- debug=False
122
  )
 
3
  import numpy as np
4
  from PIL import Image
5
 
6
+ # Load the model
7
+ print("Loading model...")
8
  model = tf.keras.models.load_model('finetuned_food_270.keras')
9
+ print("Model loaded successfully!")
10
 
11
+ # Load the class names
12
  with open('labels.txt', 'r', encoding='utf-8') as f:
13
  class_names = [line.strip() for line in f.readlines()]
14
+ print(f"{len(class_names)} classes loaded")
15
 
16
+ # --- 1. ADJUSTMENT: IMAGE SIZE ---
17
+ # Enter the size you trained the model with
18
  IMG_SIZE = (224, 224)
19
 
20
  def preprocess_image(image):
21
+ """Prepare the image for the model"""
22
 
23
+ # Convert to PIL Image and ensure RGB
24
  if isinstance(image, np.ndarray):
25
  img = Image.fromarray(image)
26
  else:
27
  img = image
28
 
29
+ # Convert to RGB (in case it's grayscale)
30
  img = img.convert('RGB')
31
 
32
+ # Resize (to the size used during training)
33
  img = img.resize(IMG_SIZE)
34
 
35
+ # Convert to Numpy array (should be dtype=float32)
36
  img_array = np.array(img, dtype=np.float32)
37
 
38
+ # Add batch dimension
39
  img_array = np.expand_dims(img_array, axis=0)
40
 
41
+ # --- 2. ADJUSTMENT: V2 PREPROCESSING ---
42
+ # EfficientNetV2 (B2) does NOT use this V1 preprocessing function.
43
+ # DELETE or COMMENT OUT this line:
44
  # img_array = tf.keras.applications.efficientnet.preprocess_input(img_array)
45
 
46
+ # Since your model is V2, it expects input in the [0, 255] range (which it is now).
47
  return img_array
48
 
49
  def predict(image):
50
+ """Food prediction function"""
51
  try:
52
+ # Process the image
53
  processed_image = preprocess_image(image)
54
 
55
+ # Make a prediction
56
  predictions = model.predict(processed_image, verbose=0)
57
 
58
+ # Get the softmax output (first batch)
59
  predictions = predictions[0]
60
 
61
+ # Find top 5 predictions
62
  top_indices = np.argsort(predictions)[-5:][::-1]
63
 
64
+ # Prepare the results
65
  results = {}
66
  for idx in top_indices:
67
  label = class_names[idx]
 
70
 
71
  return results
72
  except Exception as e:
73
+ print(f"Error: {e}")
74
+ return {"Error": str(e)}
75
 
76
+ # --- Gradio Interface ---
77
  with gr.Blocks(title="Food 270 Classifier") as demo:
78
+ # Title and description
79
  gr.Markdown("""
80
+ # 🍽️ Food 270 Classifier
81
+ **An AI model that can recognize 270 different types of food**
82
+ 📸 Upload a photo of food and let it guess what it is!
83
  """)
84
+
85
+ # Main row
86
  with gr.Row():
87
+ # Left column - Input
88
  with gr.Column(scale=1):
89
+ input_image = gr.Image(label="Food Photo", type="numpy")
90
+
91
+ # Buttons
92
  with gr.Row():
93
+ clear_btn = gr.Button("🗑️ Clear", variant="secondary")
94
+ submit_btn = gr.Button("🔍 Predict", variant="primary")
95
+
96
+ # Right column - Output
97
  with gr.Column(scale=1):
98
+ output = gr.Label(label="Prediction Results", num_top_classes=5, show_label=True)
99
+
100
+ # Additional info
101
  gr.Markdown("""
102
+ ### 📊 Result Explanation
103
+ - The **highest score** is the most likely food type
104
+ - Scores represent the confidence level **between 0-1**
105
+ - The **Top 5** most likely predictions are shown
106
  """)
107
+
108
+ # Bottom section - Tips and info
109
  with gr.Row():
110
  gr.Markdown("""
111
+ ### 💡 Tips
112
+ - Clear and well-lit photos give better results
113
+ - A full view of the food improves the prediction
114
+ - Photos containing a single type of food are ideal
115
  """)
116
+
117
+ # Model info
118
  gr.Markdown("""
119
  ---
120
+ ### 🤖 Model Information
121
  - **Model**: EfficientNetV2B2 (Fine-tuned)
122
  - **Dataset**: Food 270
123
+ - **Number of Classes**: 270 different foods
124
+ - **Training Size**: 224x224
125
+ *Developer: Berker Üveyik*
126
  """)
127
+
128
+ # Event handlers
129
+ submit_btn.click(
130
+ fn=predict,
131
+ inputs=input_image,
132
+ outputs=output
133
+ )
134
+
135
+ clear_btn.click(
136
+ lambda: (None, None),
137
+ inputs=None,
138
+ outputs=[input_image, output]
139
+ )
140
 
141
+ # Launch the application
142
  if __name__ == "__main__":
143
  demo.launch(
144
+ share=False, # Should be False on Spaces
145
+ debug=False # Should be False in production
146
  )