DeepFashion / product_similarity.py
tayyardurden's picture
Upload 6 files
949a4bc verified
raw
history blame contribute delete
No virus
9.33 kB
import pandas as pd
import streamlit as st
from tensorflow.keras.preprocessing import image as kimage
from cryptography.fernet import Fernet
import os
from io import BytesIO
from dotenv import load_dotenv
load_dotenv()
dec_key =os.getenv("FERNET_KEY")
cipher_suite=Fernet(dec_key)
st.set_page_config(
layout="wide",
initial_sidebar_state="expanded",
)
@st.cache_data
def load_data():
# Read the encrypted content from the Excel file
with open('pantolon-v3.xlsx.enc', 'rb') as file:
encrypted_data = file.read()
# Decrypt the data
decrypted_data = cipher_suite.decrypt(encrypted_data)
# Load the decrypted data into a pandas DataFrame
df = pd.read_excel(BytesIO(decrypted_data))
return df
# Read the encrypted content from model.py.enc file
with open('model_takemura.py.enc', 'rb') as file:
encrypted_model_takemura = file.read()
decrypted_model_takemura = cipher_suite.decrypt(encrypted_model_takemura)
decrypted_model_str_takemura = decrypted_model_takemura.decode()
# Execute the decrypted model string
exec(decrypted_model_str_takemura)
# Read the encrypted content from model.py.enc file
with open('model_hayabusa.py.enc', 'rb') as file:
encrypted_model_hayabusa = file.read()
decrypted_model_hayabusa = cipher_suite.decrypt(encrypted_model_hayabusa)
decrypted_model_str_hayabusa = decrypted_model_hayabusa.decode()
# Execute the decrypted model string
exec(decrypted_model_str_hayabusa)
# Read the encrypted content from model.py.enc file
with open('model_shogun.py.enc', 'rb') as file:
encrypted_model_shogun = file.read()
decrypted_model_shogun = cipher_suite.decrypt(encrypted_model_shogun)
decrypted_model_str_shogun = decrypted_model_shogun.decode()
# Execute the decrypted model string
exec(decrypted_model_str_shogun)
#
# # Read the encrypted content from model.py.enc file
# with open('preprocessing.py.enc', 'rb') as file:
# encrypted_preprocessing = file.read()
#
# decrypted_preprocessing = cipher_suite.decrypt(encrypted_preprocessing)
# decrypted_str_preprocessing = decrypted_preprocessing.decode()
#
# # Execute the decrypted model string
# exec(decrypted_str_preprocessing)
#
def page1():
st.title("Ürün Benzerlik Analizi")
st.write(
"Ürün benzerlik analizi, ürününüzün fotoğrafını yükleyerek benzer ürünleri ve verilerini bulmanızı sağlar.")
image = st.sidebar.file_uploader("Lütfen ürününüzün fotoğrafını yükleyin:")
st.markdown("""
<style>
.stTabs [data-baseweb="tab-list"] {
gap: 20px;
padding: 10px/* Increase the gap between tabs */
}
.stTabs [data-baseweb="tab-list"] button [data-testid="stMarkdownContainer"] p {
font-size:1.5rem;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.stTabs [data-baseweb="tab"] {
height: 50px;
white-space: pre-wrap;
border-radius: 12px; /* Make the tabs look like pills */
padding: 10px 20px; /* Add padding to the tabs */
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); /* Add shadow to the tabs */
transition: background-color 0.3s ease; /* Add transition effect */
color: #333; /* Change the text color to a soft black */
}
.stTabs [aria-selected="true"] {
background-color: #e0e0e0; /* Change the background color to a soft gray */
border-color: #3d5afe; /* Add border color to the selected tab */
color: #ffffff; /* Change the text color to a soft blue */;
}
.stTabs [aria-selected="true"]:hover {
background-color: #d0d0d0; /* Change background color when hover on the selected tab */
}
</style>""", unsafe_allow_html=True)
tab1, tab2 = st.tabs(["Benzer Ürün Analizi", "Ürün Özellik Analizi"])
if image is not None:
st.sidebar.success("Görsel başarıyla yüklendi.")
product_category = st.sidebar.selectbox("Lütfen ürün kategorisi seçin:",
["Pantolon", "Gömlek - (Test)", "Elbise - (Test)", "Ceket - (Test)",
"Hırka - (Test)"])
if product_category == "Pantolon":
default_product_details = ["Desen", "Bel", "Paça"] # Assign a default value
product_details = st.sidebar.multiselect("Benzerlik için öncelik sırasına göre detay seçin:",
["Bel", "Desen", "Paça"],
default=default_product_details)
if not product_details: # If product_details is an empty list
st.sidebar.error("En az 1 özellik seçilmelidir.")
with tab1:
# Create placeholders for both buttons
analyse_button_placeholder = st.empty()
show_results_button_placeholder = st.empty()
# Check if 'analysis_done' is in session state and if it's True
if 'analysis_done' not in st.session_state or not st.session_state['analysis_done']:
# Display the "Hayabusa ile Analiz Yap" button
analyse_button = analyse_button_placeholder.button("Hayabusa ile Analiz Yap")
if analyse_button:
# Clear the "Hayabusa ile Analiz Yap" button
analyse_button_placeholder.empty()
status_placeholder = st.empty()
status_placeholder.status("Analizi yapılıyor...")
filenames = model_2(image)
st.session_state['filenames'] = filenames
st.session_state['image'] = image
st.session_state['analysis_done'] = True
status_placeholder.success("Analiz tamamlandı.")
if 'analysis_done' in st.session_state and st.session_state['analysis_done']:
# Check if 'show_results' is in session state and if it's True
if 'show_results' not in st.session_state or not st.session_state['show_results']:
# Display the "Hayabusa Sonuçlarını Göster" button
show_results_button = show_results_button_placeholder.button("Hayabusa Sonuçlarını Göster",
key='button2')
if show_results_button:
# Clear the "Hayabusa Sonuçlarını Göster" button
show_results_button_placeholder.empty()
st.session_state['show_results'] = True
status_placeholder_2 = st.empty()
status_placeholder_2.status("Sonuçlar toplanıyor...")
if 'show_results' in st.session_state and st.session_state['show_results']:
image_dir = "general/PANTOLON"
df = load_data()
st.empty()
for _ in range(5):
try:
takemura_output = takemura(st.session_state['filenames'], image, product_details)
filenames = takemura_output.split('\n')
for filename in filenames:
filename_without_extension = os.path.splitext(filename)[0]
filename_without_extension = filename_without_extension.split('_')[0]
matching_rows = df.loc[df['ItemOption'] == filename_without_extension]
if not matching_rows.empty:
for _, row in matching_rows.iterrows():
cols = st.columns([2, 8]) # Adjust these values for desired widths
img_path = os.path.join(image_dir, filename)
img = kimage.load_img(img_path)
cols[0].image(img, width=200)
# cols[1].dataframe(pd.DataFrame(row).T)
half = len(row) // 2 # Find the midpoint of the row
# Split the row into two parts
row_upper_half = row.iloc[:half]
row_lower_half = row.iloc[half:]
# Display the two parts in two separate dataframes
cols[1].dataframe(pd.DataFrame(row_upper_half).T)
cols[1].dataframe(pd.DataFrame(row_lower_half).T)
status_placeholder_2.success("Sonuçlar başarıyla toplandı.")
else:
st.write(f"Ürün isimlerini maalesef eşleştiremedim {filename_without_extension}")
break
except Exception as e:
st.write(f"Hayabusa için Lütfen 'Sonuçları Göster' butonuna tekrar basınız.. ...")
st.session_state['show_results'] = False
with tab2:
shogun(image)
else:
st.write("Please upload an image.")