ESMATUGBA commited on
Commit
cff90be
·
verified ·
1 Parent(s): 45958a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -94
app.py CHANGED
@@ -1,94 +1,107 @@
1
- import streamlit as st
2
- import tensorflow as tf
3
- from tensorflow.keras.applications import VGG16
4
- from tensorflow.keras.models import Sequential
5
- from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout
6
- from PIL import Image
7
- import numpy as np
8
-
9
- # --- SAYFA AYARLARI ---
10
- st.set_page_config(page_title="Bird Identifier / Kuş Tanımlayıcı", layout="wide", page_icon="🐦")
11
-
12
- # --- MODEL YÜKLEME (TİTREMEYİ ÖNLEYEN ÖNBELLEK) ---
13
- @st.cache_resource
14
- def load_bird_model():
15
- # Model mimarisini kur
16
- base_model = VGG16(weights=None, include_top=False, input_shape=(128, 128, 3))
17
- model = Sequential([
18
- base_model,
19
- GlobalAveragePooling2D(),
20
- Dense(256, activation='relu'),
21
- Dropout(0.6),
22
- Dense(25, activation='softmax')
23
- ])
24
- # Ağırlıkları yükle (Dosya adının aynı olduğundan emin ol)
25
- model.load_weights("bird_weights.weights.h5")
26
- return model
27
-
28
- # Uygulama başladığında modeli bir kez yükle ve hafızada tut
29
- model = load_bird_model()
30
-
31
- # --- KUŞ TÜRLERİ LİSTESİ ---
32
- class_names = [
33
- 'Alexandrine Parakeet', 'Asian Green Bee-Eater', 'Baya Weaver', 'Black Drongo',
34
- 'Black-Crowned Night Heron', 'Blue-Throated Barbet', 'Brown-Headed Barbet',
35
- 'Cattle Egret', 'Common Kingfisher', 'Common Myna', 'Common Rosefinch',
36
- 'Common Tailorbird', 'Coppersmith Barbet', 'Grey Heron', 'Hoopoe',
37
- 'Indian Peafowl', 'Indian Roller', 'Indian Silverbill', 'Jungle Babbler',
38
- 'Little Egret', 'Pied Kingfisher', 'Purple Sunbird', 'Red-Wattled Lapwing',
39
- 'Slaty-Headed Parakeet', 'White-Throated Kingfisher'
40
- ]
41
-
42
- # --- YAN PANEL (SIDEBAR) ---
43
- with st.sidebar:
44
- st.title("Settings / Ayarlar ⚙️")
45
- st.divider()
46
- st.subheader("Recognized Species / Tanınan Türler 🐦")
47
- # Türleri alfabetik listele
48
- for name in sorted(class_names):
49
- st.write(f"• {name}")
50
-
51
- # --- ANA EKRAN ---
52
- st.title("Bird Species Classifier / Kuş Türü Sınıflandırıcı 🐦")
53
- st.write("Identify 25 types of Indian birds / 25 farklı Hint kuş türünü tanımlayın.")
54
- st.divider()
55
-
56
- # Ekranı ikiye böl
57
- col1, col2 = st.columns([1, 1])
58
-
59
- with col1:
60
- st.subheader("Upload Image / Resim Yükle 📤")
61
- uploaded_file = st.file_uploader("Choose a file / Dosya seçin...", type=["jpg", "jpeg", "png"])
62
-
63
- if uploaded_file is not None:
64
- image = Image.open(uploaded_file)
65
- st.image(image, caption="Uploaded Image / Yüklenen Resim", use_container_width=True)
66
-
67
- with col2:
68
- st.subheader("Analysis Results / Analiz Sonuçları 🔍")
69
-
70
- if uploaded_file is not None:
71
- if st.button("Predict / Tahmin Et"):
72
- with st.spinner("Analyzing... / Analiz ediliyor..."):
73
- # Görüntü hazırlama
74
- img = image.resize((128, 128))
75
- img_array = np.array(img).astype('float32') / 255.0
76
- img_array = np.expand_dims(img_array, axis=0)
77
-
78
- # Tahmin yap
79
- preds = model.predict(img_array)
80
- class_idx = np.argmax(preds[0])
81
- confidence = np.max(preds[0]) * 100
82
-
83
- # Sonuç gösterimi
84
- st.success(f"**Result / Sonuç:** {class_names[class_idx]}")
85
- st.write(f"**Confidence / Güven:** %{confidence:.2f}")
86
- st.progress(int(confidence))
87
-
88
- # Başarı kutlaması
89
- st.balloons()
90
- else:
91
- st.info("Please upload a bird photo to start. / Başlamak için lütfen bir kuş fotoğrafı yükleyin.")
92
-
93
- st.divider()
94
- st.caption("Deep Learning Project / Derin Öğrenme Projesi - 2024")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import tensorflow as tf
3
+ from tensorflow.keras.applications import VGG16
4
+ from tensorflow.keras.models import Sequential
5
+ from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout
6
+ from PIL import Image
7
+ import numpy as np
8
+ import os
9
+
10
+ # --- SAYFA AYARLARI ---
11
+ st.set_page_config(page_title="Bird Identifier / Kuş Tanımlayıcı", layout="wide", page_icon="🐦")
12
+
13
+ # --- MODEL YÜKLEME (TİTREMEYİ VE TEKRAR YÜKLEMEYİ ÖNLER) ---
14
+ @st.cache_resource
15
+ def load_bird_model():
16
+ # Modelin yanındaki dosyayı bulmak için tam yol tespiti
17
+ current_dir = os.path.dirname(os.path.abspath(__file__))
18
+ weights_path = os.path.join(current_dir, "bird_weights.weights.h5")
19
+
20
+ # Model Mimarisi (Kaggle'daki model2 ile birebir aynı olmalı)
21
+ base_model = VGG16(weights=None, include_top=False, input_shape=(128, 128, 3))
22
+ model = Sequential([
23
+ base_model,
24
+ GlobalAveragePooling2D(),
25
+ Dense(256, activation='relu'),
26
+ Dropout(0.6),
27
+ Dense(25, activation='softmax')
28
+ ])
29
+
30
+ # Ağırlıkları yükle
31
+ if os.path.exists(weights_path):
32
+ model.load_weights(weights_path)
33
+ else:
34
+ # Eğer dosya ana dizindeyse doğrudan ismen yüklemeyi dene
35
+ model.load_weights("bird_weights.weights.h5")
36
+
37
+ return model
38
+
39
+ # Uygulama başladığında modeli yükle (Cache sayesinde titreme yapmaz)
40
+ try:
41
+ model = load_bird_model()
42
+ except Exception as e:
43
+ st.error(f"Model yüklenirken bir hata oluştu / Error loading model: {e}")
44
+
45
+ # --- KUŞ TÜRLERİ LİSTESİ ---
46
+ class_names = [
47
+ 'Alexandrine Parakeet', 'Asian Green Bee-Eater', 'Baya Weaver', 'Black Drongo',
48
+ 'Black-Crowned Night Heron', 'Blue-Throated Barbet', 'Brown-Headed Barbet',
49
+ 'Cattle Egret', 'Common Kingfisher', 'Common Myna', 'Common Rosefinch',
50
+ 'Common Tailorbird', 'Coppersmith Barbet', 'Grey Heron', 'Hoopoe',
51
+ 'Indian Peafowl', 'Indian Roller', 'Indian Silverbill', 'Jungle Babbler',
52
+ 'Little Egret', 'Pied Kingfisher', 'Purple Sunbird', 'Red-Wattled Lapwing',
53
+ 'Slaty-Headed Parakeet', 'White-Throated Kingfisher'
54
+ ]
55
+
56
+ # --- YAN PANEL (SIDEBAR) ---
57
+ with st.sidebar:
58
+ st.title("Settings / Ayarlar ⚙️")
59
+ st.divider()
60
+ st.subheader("Recognized Species / Tanınan Türler 🐦")
61
+ for name in sorted(class_names):
62
+ st.write(f"• {name}")
63
+
64
+ # --- ANA EKRAN (GÖRSEL DÜZEN) ---
65
+ st.title("Bird Species Classifier / Kuş Türü Sınıflandırıcı 🐦")
66
+ st.write("Identify 25 Indian bird species / 25 farklı Hint kuş türünü tanımlayın.")
67
+ st.divider()
68
+
69
+ col1, col2 = st.columns([1, 1])
70
+
71
+ with col1:
72
+ st.subheader("Upload Image / Resim Yükle 📤")
73
+ uploaded_file = st.file_uploader("Choose a bird photo / Bir kuş fotoğrafı seçin...", type=["jpg", "jpeg", "png"])
74
+
75
+ if uploaded_file is not None:
76
+ image = Image.open(uploaded_file)
77
+ st.image(image, caption="Uploaded Image / Yüklenen Resim", use_container_width=True)
78
+
79
+ with col2:
80
+ st.subheader("Analysis Results / Analiz Sonuçları 🔍")
81
+
82
+ if uploaded_file is not None:
83
+ # Tahmin butonu
84
+ if st.button("Predict / Tahmin Et"):
85
+ with st.spinner("Analyzing... / Analiz ediliyor..."):
86
+ # Görüntü Ön İşleme
87
+ img = image.resize((128, 128))
88
+ img_array = np.array(img).astype('float32') / 255.0
89
+ img_array = np.expand_dims(img_array, axis=0)
90
+
91
+ # Tahmin
92
+ preds = model.predict(img_array)
93
+ class_idx = np.argmax(preds[0])
94
+ confidence = np.max(preds[0]) * 100
95
+
96
+ # Sonuçların Yazdırılması
97
+ st.success(f"**Result / Sonuç:** {class_names[class_idx]}")
98
+ st.write(f"**Confidence / Güven:** %{confidence:.2f}")
99
+ st.progress(int(confidence))
100
+
101
+ # Kutlama (Balonlar)
102
+ st.balloons()
103
+ else:
104
+ st.info("Waiting for an image to analyze... / Analiz için resim bekleniyor...")
105
+
106
+ st.divider()
107
+ st.caption("Developed with TensorFlow & Streamlit | Indian Bird Dataset Project")