| import streamlit as st |
| import pickle |
| import numpy as np |
| from PIL import Image |
| import tensorflow as tf |
| from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input |
| from tensorflow.keras.preprocessing import image |
| from tensorflow.keras.layers import GlobalMaxPool2D |
| from sklearn.neighbors import NearestNeighbors |
| from numpy.linalg import norm |
| import os |
| import zipfile |
|
|
| |
| st.title("Moda Ürün Öneri Sistemi") |
|
|
| BASE_DIR = "/app/src" |
|
|
| |
| if not os.path.exists(f"{BASE_DIR}/images"): |
| os.makedirs(f"{BASE_DIR}/images", exist_ok=True) |
|
|
| with zipfile.ZipFile(f"{BASE_DIR}/images.zip", "r") as zip_ref: |
| zip_ref.extractall(f"{BASE_DIR}/images") |
|
|
| |
| features = pickle.load(open(f"{BASE_DIR}/Images_features.pkl", "rb")) |
| filenames = pickle.load(open(f"{BASE_DIR}/filenames.pkl", "rb")) |
|
|
|
|
| |
| base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(224, 224, 3)) |
|
|
| base_model.trainable = False |
|
|
| model = tf.keras.Sequential([base_model, GlobalMaxPool2D()]) |
|
|
| |
| def save_uploaded_file(uploaded_file): |
| try: |
| with open(os.path.join("uploads", uploaded_file.name), "wb") as f: |
| f.write(uploaded_file.getbuffer()) |
| return 1 |
| except: |
| return 0 |
| |
| |
| def feature_extraction(img_path, model): |
| img = image.load_img(img_path, target_size=(224, 224)) |
| img_array = image.img_to_array(img) |
| expanded_img = np.expand_dims(img_array, axis=0) |
| preprocessed_img = preprocess_input(expanded_img) |
| result = model.predict(preprocessed_img).flatten() |
| normalized_result = result / norm(result) |
|
|
| return normalized_result |
|
|
| |
| def recommend(features, feature_list): |
| neighbors = NearestNeighbors(n_neighbors=6,algorithm="brute",metric="euclidean") |
|
|
| neighbors.fit(feature_list) |
|
|
| distances, indices = neighbors.kneighbors([features]) |
|
|
| return indices |
|
|
| |
| if not os.path.exists("uploads"): |
| os.makedirs("uploads") |
|
|
|
|
| |
| uploaded_file = st.file_uploader("Bir ürün görseli yükleyin",type=["jpg", "jpeg", "png"]) |
|
|
|
|
| |
| if uploaded_file is not None: |
| if save_uploaded_file(uploaded_file): |
|
|
| display_image = Image.open(uploaded_file) |
|
|
| st.image(display_image, caption="Yüklenen Görsel", width=300) |
|
|
| input_features = feature_extraction( |
| os.path.join("uploads", uploaded_file.name), |
| model |
| ) |
|
|
| indices = recommend(input_features, features) |
|
|
| st.subheader("Benzer Ürün Önerileri") |
|
|
| cols = st.columns(5) |
|
|
| for i, col in enumerate(cols): |
| with col: |
| img_path = os.path.join(BASE_DIR, filenames[indices[0][i + 1]]) |
| |
| if os.path.exists(img_path): |
| st.image(img_path) |
| else: |
| st.warning(f"Görsel bulunamadı: {img_path}") |