MSK34's picture
Update src/streamlit_app.py
addd3b0 verified
Raw
History Blame Contribute Delete
3.21 kB
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
# Sayfa başlığını ayarlıyoruz
st.title("Moda Ürün Öneri Sistemi")
BASE_DIR = "/app/src"
# images.zip dosyasını açıyoruz
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")
# Feature ve dosya yollarını yüklüyoruz
features = pickle.load(open(f"{BASE_DIR}/Images_features.pkl", "rb"))
filenames = pickle.load(open(f"{BASE_DIR}/filenames.pkl", "rb"))
# ResNet50 modelini yüklüyoruz
base_model = ResNet50(weights="imagenet", include_top=False, input_shape=(224, 224, 3))
base_model.trainable = False
model = tf.keras.Sequential([base_model, GlobalMaxPool2D()])
# Yüklenen resmi kaydetmek için fonksiyon yazıyoruz
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
# Yüklenen resmi vektöre çeviriyoruz
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
# En benzer ürünleri bulan fonksiyonu yazıyoruz
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
# Upload klasörü yoksa oluşturuyoruz
if not os.path.exists("uploads"):
os.makedirs("uploads")
# Kullanıcıdan ürün görseli alıyoruz
uploaded_file = st.file_uploader("Bir ürün görseli yükleyin",type=["jpg", "jpeg", "png"])
# Görsel yüklendiyse öneri sistemini çalıştırıyoruz
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}")