ESMATUGBA commited on
Commit
ca453f0
·
verified ·
1 Parent(s): e6bab3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -93
app.py CHANGED
@@ -1,93 +1,109 @@
1
- import streamlit as st
2
- import os
3
- import numpy as np
4
- import pickle as pkl
5
- import tensorflow as tf
6
- from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
7
- from tensorflow.keras.preprocessing import image
8
- from tensorflow.keras.layers import GlobalMaxPool2D
9
- from sklearn.neighbors import NearestNeighbors
10
- from numpy.linalg import norm
11
- from PIL import Image
12
-
13
- # Sayfa Ayarları ve Ortalama
14
- st.set_page_config(page_title="Moda Öneri Sistemi", layout="centered")
15
-
16
- st.markdown("""
17
- <style>
18
- .stTitle, .stSubheader, p { text-align: center; }
19
- .stImage { display: flex; justify-content: center; }
20
- </style>
21
- """, unsafe_allow_html=True)
22
-
23
- st.title('🛍️ Moda Öneri Sistemi')
24
-
25
- @st.cache_resource
26
- def load_data():
27
- base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
28
- base_model.trainable = False
29
- model = tf.keras.models.Sequential([base_model, GlobalMaxPool2D()])
30
-
31
- # Pickle dosyalarını arama
32
- pkl_options = ['Images_features.pkl', 'embeddings.pkl', 'src/Images_features.pkl', 'src/embeddings.pkl']
33
- features_file = next((f for f in pkl_options if os.path.exists(f)), None)
34
-
35
- fn_options = ['filenames.pkl', 'src/filenames.pkl']
36
- filenames_file = next((f for f in fn_options if os.path.exists(f)), None)
37
-
38
- if not features_file or not filenames_file:
39
- st.error("HATA: .pkl dosyaları bulunamadı!")
40
- return None, None, None
41
-
42
- features = np.array(pkl.load(open(features_file, 'rb')))
43
- filenames = pkl.load(open(filenames_file, 'rb'))
44
- return model, features, filenames
45
-
46
- model, feature_list, filenames = load_data()
47
-
48
- def extract_features(img_path, model):
49
- img = image.load_img(img_path, target_size=(224, 224))
50
- img_array = image.img_to_array(img)
51
- img_expand_dim = np.expand_dims(img_array, axis=0)
52
- img_preprocess = preprocess_input(img_expand_dim)
53
- result = model.predict(img_preprocess).flatten()
54
- norm_result = result / norm(result)
55
- return norm_result
56
-
57
- uploaded_file = st.file_uploader("Kıyafet resmi yükleyin...", type=['jpg', 'png', 'jpeg'])
58
-
59
- if uploaded_file is not None and model is not None:
60
- col1, col2, col3 = st.columns([1, 2, 1])
61
- with col2:
62
- display_image = Image.open(uploaded_file)
63
- st.image(display_image, use_container_width=True, caption='Yüklenen Resim')
64
-
65
- temp_path = "temp_upload.jpg"
66
- with open(temp_path, "wb") as f:
67
- f.write(uploaded_file.getbuffer())
68
-
69
- input_features = extract_features(temp_path, model)
70
- neighbors = NearestNeighbors(n_neighbors=6, algorithm='brute', metric='euclidean')
71
- neighbors.fit(feature_list)
72
- distances, indices = neighbors.kneighbors([input_features])
73
-
74
- st.markdown("---")
75
- st.subheader('✨ Benzer Ürünler')
76
-
77
- cols = st.columns(5)
78
- for i in range(1, 6):
79
- with cols[i-1]:
80
- # DOSYA YOLU HATASINI ÇÖZEN KISIM:
81
- raw_path = filenames[indices[0][i]].replace('\\', '/')
82
- img_name = os.path.basename(raw_path) # Örn: '1528.jpg'
83
-
84
- # Hugging Face'te resimlerin olduğu muhtemel yerler
85
- p1 = os.path.join('images', img_name)
86
- p2 = os.path.join('src', 'images', img_name)
87
-
88
- if os.path.exists(p1):
89
- st.image(p1, use_container_width=True)
90
- elif os.path.exists(p2):
91
- st.image(p2, use_container_width=True)
92
- else:
93
- st.error(f"Eksik: {img_name}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Haklısın, parça parça eklemeler yapınca kafa karışması çok normal. Şimdi her şeyi tek bir pakette birleştirelim.
2
+
3
+ Hugging Face'te çalışan, dosya yollarını otomatik düzelten ve büyük/küçük harf hatalarını (Linux kaynaklı) engelleyen en sağlam kodu aşağıya yazıyorum.
4
+
5
+ 1. app.py (Tüm Kod)
6
+ Bu kodu kopyala ve Hugging Face'teki app.py dosyasının içine tamamen yapıştır (eskisini sil):
7
+
8
+ Python
9
+ import streamlit as st
10
+ import os
11
+ import numpy as np
12
+ import pickle as pkl
13
+ import tensorflow as tf
14
+ from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
15
+ from tensorflow.keras.preprocessing import image
16
+ from tensorflow.keras.layers import GlobalMaxPool2D
17
+ from sklearn.neighbors import NearestNeighbors
18
+ from numpy.linalg import norm
19
+ from PIL import Image
20
+
21
+ # Sayfa tasarımı
22
+ st.set_page_config(page_title="Moda Öneri Sistemi", layout="centered")
23
+
24
+ st.markdown("""
25
+ <style>
26
+ .stTitle, .stSubheader, p { text-align: center; }
27
+ .stImage { display: flex; justify-content: center; }
28
+ </style>
29
+ """, unsafe_allow_html=True)
30
+
31
+ st.title('🛍️ Moda Öneri Sistemi')
32
+
33
+ # Model ve verileri yükle
34
+ @st.cache_resource
35
+ def load_data():
36
+ # ResNet50 modelini hazırla
37
+ base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
38
+ base_model.trainable = False
39
+ model = tf.keras.models.Sequential([base_model, GlobalMaxPool2D()])
40
+
41
+ # Pickle dosyalarını kontrol et (Ana dizinde arar)
42
+ try:
43
+ features = np.array(pkl.load(open('Images_features.pkl', 'rb')))
44
+ filenames = pkl.load(open('filenames.pkl', 'rb'))
45
+ return model, features, filenames
46
+ except FileNotFoundError:
47
+ st.error("HATA: .pkl dosyaları ana dizinde bulunamadı!")
48
+ return None, None, None
49
+
50
+ model, feature_list, filenames = load_data()
51
+
52
+ def extract_features(img_path, model):
53
+ img = image.load_img(img_path, target_size=(224, 224))
54
+ img_array = image.img_to_array(img)
55
+ img_expand_dim = np.expand_dims(img_array, axis=0)
56
+ img_preprocess = preprocess_input(img_expand_dim)
57
+ result = model.predict(img_preprocess).flatten()
58
+ norm_result = result / norm(result)
59
+ return norm_result
60
+
61
+ # Dosya yükleme alanı
62
+ uploaded_file = st.file_uploader("Kıyafet resmi seçin...", type=['jpg', 'png', 'jpeg'])
63
+
64
+ if uploaded_file is not None and model is not None:
65
+ # Seçilen resmi göster
66
+ col1, col2, col3 = st.columns([1, 2, 1])
67
+ with col2:
68
+ display_image = Image.open(uploaded_file)
69
+ st.image(display_image, use_container_width=True, caption='Yüklediğiniz Resim')
70
+
71
+ # Geçici olarak kaydet
72
+ temp_path = "temp_upload.jpg"
73
+ with open(temp_path, "wb") as f:
74
+ f.write(uploaded_file.getbuffer())
75
+
76
+ # Benzerleri bul
77
+ with st.spinner('Öneriler hazırlanıyor...'):
78
+ input_features = extract_features(temp_path, model)
79
+ neighbors = NearestNeighbors(n_neighbors=6, algorithm='brute', metric='euclidean')
80
+ neighbors.fit(feature_list)
81
+ distances, indices = neighbors.kneighbors([input_features])
82
+
83
+ st.markdown("---")
84
+ st.subheader(' Benzer Ürünler')
85
+
86
+ cols = st.columns(5)
87
+
88
+ # Resim klasörünü tara (Büyük/küçük harf duyarlılığı için)
89
+ image_folder = 'images'
90
+ if os.path.exists(image_folder):
91
+ available_files = os.listdir(image_folder)
92
+ # Dosya adlarını küçük harfe çevirerek bir sözlük oluştur (Hızlı arama için)
93
+ file_map = {f.lower(): f for f in available_files}
94
+ else:
95
+ file_map = {}
96
+ st.error("'images' klasörü bulunamadı!")
97
+
98
+ for i in range(1, 6):
99
+ with cols[i-1]:
100
+ # Pickle içindeki yolu temizle (Windows yollarını Linux'a çevir)
101
+ raw_path = filenames[indices[0][i]].replace('\\', '/')
102
+ target_name = os.path.basename(raw_path).lower()
103
+
104
+ # Klasörde bu resim var mı bak
105
+ if target_name in file_map:
106
+ final_path = os.path.join(image_folder, file_map[target_name])
107
+ st.image(final_path, use_container_width=True)
108
+ else:
109
+ st.warning(f"Bulunamadı: {target_name}")