CoolFace
Apppublic

Nikhil0702/Gender_Classification_Using_Hybrid_Approach

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py121 linesDownload Raw Back to root
1import os2import pickle3import cv24import numpy as np5import streamlit as st6import matplotlib.pyplot as plt7from tensorflow.keras.models import load_model8 9# ---------------- SETTINGS ----------------10BASE_DIR = "Main_py"11 12# ---------------- FILE CHECK ----------------13def check_file(filename):14    path = os.path.join(BASE_DIR, filename)15    if not os.path.exists(path):16        st.error(f"โŒ File '{filename}' not found in '{BASE_DIR}'")17        st.stop()18    return path19 20# ---------------- LOAD MODELS ----------------21@st.cache_resource22def load_all_models():23    extractor = load_model(check_file("feature_extractor.keras"))24    with open(check_file("svm_model.pkl"), "rb") as f:25        svm = pickle.load(f)26    with open(check_file("rf_model.pkl"), "rb") as f:27        rf = pickle.load(f)28    with open(check_file("xgb_model.pkl"), "rb") as f:29        xgb = pickle.load(f)30    return extractor, svm, rf, xgb31 32feature_extractor, svm_model, rf_model, xgb_model = load_all_models()33 34# Face detector for rejecting non-face inputs35face_cascade = cv2.CascadeClassifier(36    cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'37)38 39# ---------------- PREDICTION FUNCTION ----------------40def predict_single_image(uploaded_file):41    # Reset file pointer and read bytes42    uploaded_file.seek(0)43    file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)44    img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)45 46    if img is None:47        # Could not decode image48        blank = np.zeros((300, 300, 3), dtype=np.uint8)49        return None, blank, 0.050 51    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)52    img_display = cv2.resize(img_rgb, (300, 300), interpolation=cv2.INTER_AREA)53 54    # --- Face detection ---55    gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)56    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)57 58    if len(faces) == 0:59        return None, img_display, 0.0  # Reject if no face detected60 61    # --- Preprocess for model ---62    img_model = cv2.resize(img_rgb, (128, 128))63    img_model = cv2.cvtColor(img_model, cv2.COLOR_RGB2GRAY) / 255.064    img_model = np.expand_dims(img_model, axis=-1)  # (128, 128, 1)65    img_model = np.expand_dims(img_model, axis=0)   # (1, 128, 128, 1)66 67    # --- Extract features ---68    feature_vector = feature_extractor.predict(img_model)69    feature_vector = feature_vector.reshape(1, -1)70 71    # --- Get probabilities from models ---72    def safe_proba(model):73        try:74            return model.predict_proba(feature_vector)[0]75        except:76            pred = model.predict(feature_vector)[0]77            return [1.0 - pred, pred] if pred in [0, 1] else [0.5, 0.5]78 79    prob_svm = safe_proba(svm_model)80    prob_rf = safe_proba(rf_model)81    prob_xgb = safe_proba(xgb_model)82 83    # Average probabilities84    avg_probs = np.mean([prob_svm, prob_rf, prob_xgb], axis=0)85    confidence = float(np.max(avg_probs))86    predicted_class = int(np.argmax(avg_probs))87    gender_final = "Male" if predicted_class == 1 else "Female"88 89    # --- Reject if too low confidence ---90    if confidence < 0.70:91        return None, img_display, confidence92 93    return gender_final, img_display, confidence94 95# ---------------- STREAMLIT UI ----------------96st.set_page_config(page_title="Gender Classification App", page_icon="๐Ÿ‘ค")97 98st.title("๐Ÿ‘ค Gender Classification (Hybrid DL + ML)")99st.write("Only predicts for **clear human male/female faces** โ€” others will be rejected but still shown.")100 101uploaded_file = st.file_uploader("๐Ÿ“ค Upload an image", type=["jpg", "jpeg", "png"])102 103if uploaded_file is not None:104    if st.button("๐Ÿ” Predict Gender"):105        gender, img_display, conf = predict_single_image(uploaded_file)106 107        fig, ax = plt.subplots()108        ax.imshow(img_display)109        ax.axis("off")110 111        if gender is None:112            msg = "โŒ This is not detected as a picture of a man or woman."113            ax.set_title(msg, fontsize=10, color="red")114            st.pyplot(fig)115            st.warning(msg)116        else:117            color = "blue" if gender == "Male" else "green"118            ax.set_title(f"{gender} ({conf*100:.1f}% confident)", fontsize=12, color=color)119            st.pyplot(fig)120            st.success(f"โœ… Predicted Gender: {gender} โ€” {conf*100:.1f}% confidence")121