import streamlit as st
import pickle as pkl
from PIL import Image
from sklearn.neighbors import NearestNeighbors
from tensorflow.keras.models import load_model
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.preprocessing import image
import os
from numpy.linalg import norm
import numpy as np
# Load necessary files and model
filenames = pkl.load(open('filenames2.pkl', 'rb'))
Image_features = pkl.load(open('Images_features2.pkl', 'rb'))
neighbors = NearestNeighbors(n_neighbors=6, algorithm='brute', metric='euclidean')
neighbors.fit(Image_features)
model = load_model('model.h5')
# Feature extraction function
def extract_features_from_images(image_path, model):
img = image.load_img(image_path, target_size=(224, 224))
img_array = image.img_to_array(img)
img_expand_dim = np.expand_dims(img_array, axis=0)
img_preprocess = preprocess_input(img_expand_dim)
result = model.predict(img_preprocess).flatten()
norm_result = result / norm(result)
return norm_result
# Custom CSS for background and title
st.markdown(
"""
""",
unsafe_allow_html=True,
)
# Streamlit UI
st.markdown('
Fashion Deep Learning Classification 👗
', unsafe_allow_html=True)
st.write('Upload a clothing image, and the model recommends similar products.')
file = st.file_uploader('Upload an Image', type=['jpg', 'jpeg', 'png'])
if file is not None:
# Display uploaded image with reduced size
img = Image.open(file)
st.image(img, caption='Uploaded Image', width=200)
# Extract features from the uploaded image
input_image = extract_features_from_images(file, model)
# Get recommendations
distance, indices = neighbors.kneighbors([input_image])
st.subheader("Recommended Products:")
# Display recommendations in a grid layout
cols = st.columns(3) # 3 images per row
base_dir = os.path.dirname(__file__) # Get the directory of the current script
images_dir = os.path.join(base_dir, "images") # Construct the images folder path
for i, idx in enumerate(indices[0]):
st.write(i,idx)
product_filename = filenames[idx]
st.write(product_filename)
product_path = os.path.join(images_dir, product_filename)
st.write(product_path)
product_image = Image.open(product_path)
# Assign columns dynamically
with cols[i % 3]:
st.image(product_image, caption=f"Product {i + 1}", use_column_width=True)