DasariHarshitha commited on
Commit
f030920
ยท
verified ยท
1 Parent(s): 326e33e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -101
app.py CHANGED
@@ -1,101 +1,65 @@
1
- import streamlit as st
2
- import os
3
- from PIL import Image
4
- import numpy as np
5
- from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array
6
- from tensorflow.keras.models import Sequential
7
- from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
8
- from tensorflow.keras.utils import to_categorical
9
- from tensorflow.keras.optimizers import Adam
10
- from sklearn.preprocessing import LabelEncoder
11
- from sklearn.model_selection import train_test_split
12
-
13
- # Page config
14
- st.set_page_config(page_title="Animal Classifier DL", layout="centered")
15
-
16
- st.title("๐Ÿง  Animal Classifier (Deep Learning)")
17
- st.markdown("Train from folders like `Animals/cat`, `Animals/dog`, etc. and predict uploaded images.")
18
-
19
- IMAGE_SIZE = (128, 128)
20
- DATA_DIR = "Animals" # Folder with subfolders
21
-
22
- # ๐Ÿ” Load dataset and preprocess
23
- @st.cache_data
24
- def load_dataset():
25
- X = []
26
- y = []
27
-
28
- for label in os.listdir(DATA_DIR):
29
- folder = os.path.join(DATA_DIR, label)
30
- if os.path.isdir(folder):
31
- for file in os.listdir(folder):
32
- if file.lower().endswith(('.png', '.jpg', '.jpeg')):
33
- try:
34
- path = os.path.join(folder, file)
35
- img = Image.open(path).convert("RGB").resize(IMAGE_SIZE)
36
- arr = img_to_array(img) / 255.0
37
- X.append(arr)
38
- y.append(label)
39
- except Exception as e:
40
- print(f"โš ๏ธ Skipped {file}: {e}")
41
- return np.array(X), np.array(y)
42
-
43
- X, y = load_dataset()
44
-
45
- # Stop if no data
46
- if len(X) == 0:
47
- st.error("โŒ No images found in 'Animals' folder.")
48
- st.stop()
49
-
50
- # Encode labels
51
- le = LabelEncoder()
52
- y_encoded = le.fit_transform(y)
53
- y_cat = to_categorical(y_encoded)
54
-
55
- # ๐Ÿง  Train/test split
56
- X_train, X_test, y_train, y_test = train_test_split(X, y_cat, test_size=0.2, random_state=42)
57
-
58
- # ๐Ÿง  Build model
59
- @st.cache_resource
60
- def build_model():
61
- model = Sequential([
62
- Conv2D(32, (3, 3), activation='relu', input_shape=(*IMAGE_SIZE, 3)),
63
- MaxPooling2D(2, 2),
64
- Conv2D(64, (3, 3), activation='relu'),
65
- MaxPooling2D(2, 2),
66
- Flatten(),
67
- Dense(128, activation='relu'),
68
- Dropout(0.3),
69
- Dense(len(np.unique(y_encoded)), activation='softmax')
70
- ])
71
- model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
72
- return model
73
-
74
- model = build_model()
75
-
76
- # ๐Ÿ‘จโ€๐Ÿซ Train the model
77
- with st.spinner("Training model..."):
78
- model.fit(X_train, y_train, epochs=5, batch_size=32, validation_split=0.1, verbose=0)
79
-
80
- st.success("โœ… Model trained!")
81
-
82
- # ๐Ÿ“ค Upload images for prediction
83
- uploaded_files = st.file_uploader("Upload animal images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
84
-
85
- if uploaded_files:
86
- st.markdown("### Predictions")
87
- cols = st.columns(len(uploaded_files[:3]))
88
-
89
- for i, file in enumerate(uploaded_files[:3]):
90
- with cols[i]:
91
- img = Image.open(file).convert("RGB")
92
- st.image(img, caption="Uploaded", use_container_width=True)
93
-
94
- img_resized = img.resize(IMAGE_SIZE)
95
- arr = img_to_array(img_resized) / 255.0
96
- arr = np.expand_dims(arr, axis=0)
97
-
98
- pred = model.predict(arr, verbose=0)[0]
99
- top_idx = np.argmax(pred)
100
- label = le.inverse_transform([top_idx])[0]
101
- st.success(f"๐Ÿ” Prediction: **{label.capitalize()}**")
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ from tensorflow.keras.models import load_model
4
+ from tensorflow.keras.preprocessing.image import img_to_array
5
+ from PIL import Image
6
+
7
+ # ๐Ÿ”ง Configure Streamlit
8
+ st.set_page_config(
9
+ page_title="Animal Classifier",
10
+ layout="centered",
11
+ initial_sidebar_state="auto"
12
+ )
13
+
14
+ # ๐Ÿ“ฆ Load model and class labels
15
+ @st.cache_resource
16
+ def load_model_once():
17
+ return load_model("animal_model.keras")
18
+
19
+ @st.cache_data
20
+ def load_labels():
21
+ return np.load("class_labels.npy", allow_pickle=True).item()
22
+
23
+ model = load_model_once()
24
+ class_indices = load_labels()
25
+ class_labels = list(class_indices.keys())
26
+
27
+ # ๐Ÿท App Title
28
+ st.title("๐Ÿพ Animal Image Classifier")
29
+ st.markdown("Upload up to **3 images** and get predictions")
30
+
31
+ # ๐Ÿ“ค Upload Images
32
+ uploaded_files = st.file_uploader(
33
+ "Upload animal images",
34
+ type=["jpg", "jpeg", "png"],
35
+ accept_multiple_files=True
36
+ )
37
+
38
+ if uploaded_files:
39
+ # Limit to 3 images for clarity
40
+ uploaded_files = uploaded_files[:3]
41
+ cols = st.columns(len(uploaded_files))
42
+
43
+ for idx, uploaded_file in enumerate(uploaded_files):
44
+ with cols[idx]:
45
+ st.markdown(f"### Image {idx+1}")
46
+
47
+ # ๐Ÿ–ผ๏ธ Load & visually shrink image
48
+ image = Image.open(uploaded_file).convert("RGB")
49
+ preview = image.copy()
50
+ preview.thumbnail((150, 150))
51
+ st.image(preview, caption="Preview", use_container_width=True)
52
+
53
+ # ๐Ÿงช Preprocess image for prediction
54
+ resized = image.resize((128, 128))
55
+ img_array = img_to_array(resized) / 255.0
56
+ img_array = np.expand_dims(img_array, axis=0)
57
+
58
+ # ๐Ÿ”ฎ Model Prediction
59
+ preds = model.predict(img_array)[0]
60
+ top_indices = preds.argsort()[-3:][::-1]
61
+ top_labels = [class_labels[i] for i in top_indices]
62
+ top_scores = [preds[i] for i in top_indices]
63
+
64
+ # โœ… Display Top Prediction
65
+ st.success(f"**๐Ÿ”ฎPrediction:** {top_labels[0].capitalize()}")