CoolFace
Apppublic

eMulayim/Flower_Classification_by_Computer_Vision

sourceHugging Facemitupdated 8mo agoView on Hugging Face
0likes
streamlit_app.py124 linesDownload Raw Back to src
1import streamlit as st2import tensorflow as tf3from PIL import Image, ImageOps4import numpy as np5import os6 7# --------------------------------------------------------------------------8# 1. AYARLAR VE SAYFA DÜZENİ9# --------------------------------------------------------------------------10st.set_page_config(11    page_title="Flower Classification Project",12    page_icon="🌸",13    layout="centered"14)15 16st.title("🌸 Flower Type Classification")17st.markdown("""18This project is developed using Deep Learning methods.19It predicts whether the uploaded flower image is a **Daisy, Dandelion, Rose, Sunflower, or Tulip**.20""")21 22# --------------------------------------------------------------------------23# 2. KERAS UYUMLULUK SINIFLARI (ÖNEMLİ: EN ÜSTTE TANIMLANMALI)24# Hugging Face (TF 2.x) ve Eğitim Ortamı (Keras 3) farkını çözer.25# --------------------------------------------------------------------------26class FixedDense(tf.keras.layers.Dense):27    def __init__(self, *args, **kwargs):28        # 'quantization_config' parametresi gelirse sil, yoksa hata verir29        if 'quantization_config' in kwargs:30            kwargs.pop('quantization_config')31        super().__init__(*args, **kwargs)32 33class FixedDropout(tf.keras.layers.Dropout):34    def __init__(self, *args, **kwargs):35        if 'quantization_config' in kwargs:36            kwargs.pop('quantization_config')37        super().__init__(*args, **kwargs)38 39# --------------------------------------------------------------------------40# 3. DİNAMİK MODEL YÜKLEME (SRC KLASÖRÜNE ENDEKSLİ)41# --------------------------------------------------------------------------42@st.cache_resource43def load_model():44    # Bu scriptin (streamlit_app.py) tam dosya yolunu bul45    script_path = os.path.abspath(__file__)46    47    # Bu scriptin içinde bulunduğu klasörü bul (Yani 'src' klasörü)48    script_dir = os.path.dirname(script_path)49    50    # Modeli script ile AYNI klasörde ara51    model_path = os.path.join(script_dir, 'DL_trained_model.h5')52    53    # Hata ayıklama için yolu yazdır (Gerekirse comment'i açın)54    # st.write(f"Model aranıyor: {model_path}")55 56    if not os.path.exists(model_path):57        st.error(f"🚨 Model file not found at: {model_path}")58        st.warning("Please ensure 'DL_trained_model.h5' is in the same folder as 'streamlit_app.py'.")59        return None60 61    try:62        # Modeli özel katmanları tanıtarak yükle63        model = tf.keras.models.load_model(64            model_path, 65            custom_objects={'Dense': FixedDense, 'Dropout': FixedDropout},66            compile=False 67        )68        return model69    except Exception as e:70        st.error(f"🚨 Error loading model: {e}")71        return None72 73# Modeli Yükle74model = load_model()75 76# --------------------------------------------------------------------------77# 4. TAHMİN VE ARAYÜZ MANTIĞI78# --------------------------------------------------------------------------79class_names = ['Daisy', 'Dandelion', 'Rose', 'Sunflower', 'Tulip']80 81st.header("Upload an Image")82file = st.file_uploader("Please upload a flower photo (jpg, png, jpeg)", type=["jpg", "png", "jpeg"])83 84def import_and_predict(image_data, model):85    # Modeli eğittiğiniz boyuta getir (180x180)86    size = (180, 180)87    image = ImageOps.fit(image_data, size, Image.Resampling.LANCZOS)88    img = np.asarray(image)89    90    # Boyut ekle (Batch dimension): (180, 180, 3) -> (1, 180, 180, 3)91    img_reshape = img[np.newaxis, ...]92    93    prediction = model.predict(img_reshape)94    return prediction95 96if file is not None:97    # Resmi Göster98    image = Image.open(file)99    # Yeni Streamlit sürümü için 'use_container_width' kullanıyoruz100    st.image(image, caption="Uploaded Image", use_container_width=True)101    102    if model is not None:103        if st.button("Predict"):104            with st.spinner('Model is predicting...'):105                try:106                    predictions = import_and_predict(image, model)107                    score = tf.nn.softmax(predictions[0])108                    109                    predicted_class_idx = np.argmax(score)110                    confidence = 100 * np.max(score)111                    predicted_class = class_names[predicted_class_idx]112                    113                    st.success(f"Prediction: **{predicted_class}**")114                    st.info(f"Confidence Score: **%{confidence:.2f}**")115                    116                    st.subheader("Probability Distribution")117                    # Grafik çiz118                    probs = {name: float(s) for name, s in zip(class_names, score)}119                    st.bar_chart(probs)120                    121                except Exception as e:122                    st.error(f"An error occurred during prediction: {e}")123    else:124        st.error("Model could not be loaded, please check the logs.")