ESMATUGBA commited on
Commit
035b41f
·
verified ·
1 Parent(s): dff9189

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -95
app.py CHANGED
@@ -1,96 +1,103 @@
1
-
2
- import streamlit as st
3
- import tensorflow as tf
4
- from PIL import Image
5
- import numpy as np
6
- import os
7
-
8
- # --- SAYFA AYARLARI / PAGE CONFIG ---
9
- st.set_page_config(page_title="Fruit & Veg Classifier", layout="wide", page_icon="🍎")
10
-
11
- # --- MODEL YÜKLEME / LOAD MODEL ---
12
- @st.cache_resource
13
- def load_my_model():
14
- # Model dosya adının 'cnn_model.h5' olduğundan emin olun
15
- model_path = "cnn_model.h5"
16
- model = tf.keras.models.load_model(model_path)
17
- return model
18
-
19
- try:
20
- model = load_my_model()
21
- except Exception as e:
22
- st.error(f"Model dosyası bulunamadı! / Model file not found!: {e}")
23
-
24
- # --- SINIF İSİMLERİ / CLASS NAMES ---
25
- # Veri setindeki klasör sırasına göre burayı güncelleyin
26
- class_names = [
27
- 'Apple', 'Banana', 'Beetroot', 'Bell Pepper', 'Cabbage', 'Capsicum',
28
- 'Carrot', 'Cauliflower', 'Chilli Pepper', 'Corn', 'Cucumber', 'Eggplant',
29
- 'Garlic', 'Ginger', 'Grapes', 'Jalepeno', 'Kiwi', 'Lemon', 'Lettuce',
30
- 'Mango', 'Onion', 'Orange', 'Paprika', 'Pear', 'Peas', 'Pineapple',
31
- 'Pomegranate', 'Potato', 'Raddish', 'Soy Beans', 'Spinach', 'Sweetcorn',
32
- 'Sweetpotato', 'Tomato', 'Turnip', 'Watermelon'
33
- ]
34
-
35
- # --- ARAYÜZ / UI ---
36
- st.title("🍎 Fruit & Veg Classifier / Meyve ve Sebze Sınıflandırıcı")
37
- st.write("Identify your produce using Deep Learning / Derin Öğrenme ile ürünlerinizi tanımlayın.")
38
- st.divider()
39
-
40
- # Yan Panel / Sidebar
41
- with st.sidebar:
42
- st.header("Project Info / Proje Bilgisi")
43
- st.info("""
44
- **EN:** This model uses a custom 5-layer CNN architecture trained on fruit and vegetable images.
45
- \n**TR:** Bu model, meyve ve sebze görüntüleri üzerinde eğitilmiş 5 katmanlı özel bir CNN mimarisi kullanır.
46
- """)
47
- st.subheader("Species / Türler")
48
- st.write(", ".join(class_names))
49
-
50
- # Ana İçerik / Main Content
51
- col1, col2 = st.columns([1, 1])
52
-
53
- with col1:
54
- st.subheader("Upload / Yükle 📤")
55
- uploaded_file = st.file_uploader("Choose a photo / Bir fotoğraf seçin...", type=["jpg", "jpeg", "png"])
56
-
57
- if uploaded_file is not None:
58
- image = Image.open(uploaded_file)
59
- st.image(image, caption="Uploaded Image / Yüklenen Resim", use_container_width=True)
60
-
61
- with col2:
62
- st.subheader("Result / Sonuç 🔍")
63
-
64
- if uploaded_file is not None:
65
- if st.button("Predict / Tahmin Et"):
66
- with st.spinner("Processing... / İşleniyor..."):
67
- # Ön İşleme / Preprocessing (Modelin eğitildiği boyuta göre: 128x128)
68
- img = image.resize((128, 128))
69
- img_array = np.array(img)
70
-
71
- # Eğer model 0-1 arası normalizasyon istiyorsa:
72
- if img_array.max() > 1:
73
- img_array = img_array.astype('float32') / 255.0
74
-
75
- img_array = np.expand_dims(img_array, axis=0)
76
-
77
- # Tahmin / Prediction
78
- predictions = model.predict(img_array)
79
- score = np.max(predictions[0]) * 100
80
- class_idx = np.argmax(predictions[0])
81
- result = class_names[class_idx]
82
-
83
- # Sonuç Ekranı / Result Display
84
- st.success(f"### {result}")
85
- st.write(f"**Confidence / Güven:** %{score:.2f}")
86
-
87
- # İlerleme Çubuğu / Progress Bar
88
- st.progress(int(score))
89
-
90
- # Kutlama / Celebration
91
- st.balloons()
92
- else:
93
- st.write("Please upload an image to see the result. / Sonucu görmek için lütfen bir resim yükleyin.")
94
-
95
- st.divider()
 
 
 
 
 
 
 
96
  st.caption("Deep Learning Course Project / Derin Öğrenme Kurs Projesi")
 
1
+
2
+ import streamlit as st
3
+ import tensorflow as tf
4
+ from PIL import Image
5
+ import numpy as np
6
+ import os
7
+
8
+ # --- SAYFA AYARLARI / PAGE CONFIG ---
9
+ st.set_page_config(page_title="Fruit & Veg Classifier", layout="wide", page_icon="🍎")
10
+
11
+ # --- MODEL YÜKLEME / LOAD MODEL (Titremeyi önlemek için önbellekleme) ---
12
+ @st.cache_resource
13
+ def load_my_model():
14
+ model_path = "cnn_model.h5"
15
+ # Eğer model .keras formatındaysa ismi ona göre güncelleyin
16
+ if not os.path.exists(model_path):
17
+ return None
18
+ model = tf.keras.models.load_model(model_path)
19
+ return model
20
+
21
+ model = load_my_model()
22
+
23
+ # --- SINIF İSİMLERİ (İngilizce - Türkçe) / CLASS NAMES ---
24
+ # Veri setindeki orijinal (klasör) isimleri solda, Türkçe karşılıkları sağdadır
25
+ class_translations = {
26
+ 'Apple': 'Elma', 'Banana': 'Muz', 'Beetroot': 'Pancar', 'Bell Pepper': 'Dolmalık Biber',
27
+ 'Cabbage': 'Lahana', 'Capsicum': 'Yeşil Biber', 'Carrot': 'Havuç', 'Cauliflower': 'Karnabahar',
28
+ 'Chilli Pepper': 'Acı Biber', 'Corn': 'Mısır', 'Cucumber': 'Salatalık', 'Eggplant': 'Patlıcan',
29
+ 'Garlic': 'Sarımsak', 'Ginger': 'Zencefil', 'Grapes': 'Üzüm', 'Jalepeno': 'Jalapeno Biberi',
30
+ 'Kiwi': 'Kivi', 'Lemon': 'Limon', 'Lettuce': 'Marul', 'Mango': 'Mango',
31
+ 'Onion': 'Soğan', 'Orange': 'Portakal', 'Paprika': 'Kırmızı Toz Biber', 'Pear': 'Armut',
32
+ 'Peas': 'Bezelye', 'Pineapple': 'Ananas', 'Pomegranate': 'Nar', 'Potato': 'Patates',
33
+ 'Raddish': 'Turp', 'Soy Beans': 'Soya Fasulyesi', 'Spinach': 'Ispanak', 'Sweetcorn': 'Tatlı Mısır',
34
+ 'Sweetpotato': 'Tatlı Patates', 'Tomato': 'Domates', 'Turnip': 'Şalgam', 'Watermelon': 'Karpuz'
35
+ }
36
+
37
+ # Orijinal klasör isimleri listesi (Tahmin için)
38
+ class_names = list(class_translations.keys())
39
+
40
+ # --- ARAYÜZ / UI ---
41
+ st.title("🍎 Fruit & Veg Classifier / Meyve ve Sebze Sınıflandırıcı")
42
+ st.write("Identify your produce / Ürünlerinizi tanımlayın.")
43
+ st.divider()
44
+
45
+ # --- YAN PANEL / SIDEBAR (Türkçe İsimler Eklendi) ---
46
+ with st.sidebar:
47
+ st.header("Project Info / Proje Bilgisi")
48
+ st.info("Custom 5-Layer CNN / Özel 5 Katmanlı CNN")
49
+
50
+ st.subheader("Species List / Tür Listesi")
51
+ # Türleri yan yana İngilizce / Türkçe olarak listeler
52
+ for eng, tr in class_translations.items():
53
+ st.write(f"• {eng} / {tr}")
54
+
55
+ # --- ANA İÇERİK / MAIN CONTENT ---
56
+ if model is None:
57
+ st.error("Model file 'cnn_model.h5' not found! / 'cnn_model.h5' dosyası bulunamadı!")
58
+ else:
59
+ col1, col2 = st.columns([1, 1])
60
+
61
+ with col1:
62
+ st.subheader("Upload / Yükle 📤")
63
+ uploaded_file = st.file_uploader("Choose a photo / Fotoğraf seçin...", type=["jpg", "jpeg", "png"])
64
+
65
+ if uploaded_file is not None:
66
+ image = Image.open(uploaded_file)
67
+ st.image(image, caption="Uploaded Image / Yüklenen Resim", use_container_width=True)
68
+
69
+ with col2:
70
+ st.subheader("Result / Sonuç 🔍")
71
+
72
+ if uploaded_file is not None:
73
+ # Butona basıldığında titreme yapmaması için tüm işlemler bu bloğun içinde kalmalı
74
+ if st.button("Predict / Tahmin Et"):
75
+ with st.spinner("Processing... / İşleniyor..."):
76
+ # Görüntü İşleme
77
+ img = image.resize((128, 128))
78
+ img_array = np.array(img).astype('float32')
79
+
80
+ # Normalizasyon
81
+ if img_array.max() > 1:
82
+ img_array /= 255.0
83
+
84
+ img_array = np.expand_dims(img_array, axis=0)
85
+
86
+ # Tahmin
87
+ predictions = model.predict(img_array, verbose=0)
88
+ score = np.max(predictions[0]) * 100
89
+ class_idx = np.argmax(predictions[0])
90
+
91
+ eng_res = class_names[class_idx]
92
+ tr_res = class_translations[eng_res]
93
+
94
+ # Sonuç Ekranı
95
+ st.success(f"### Result / Sonuç: {eng_res} / {tr_res}")
96
+ st.write(f"**Confidence / Güven:** %{score:.2f}")
97
+ st.progress(int(score))
98
+ st.balloons()
99
+ else:
100
+ st.info("Waiting for image... / Resim bekleniyor...")
101
+
102
+ st.divider()
103
  st.caption("Deep Learning Course Project / Derin Öğrenme Kurs Projesi")