ESMATUGBA commited on
Commit
fb79c27
·
verified ·
1 Parent(s): a944776

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -83
app.py CHANGED
@@ -11,98 +11,123 @@ from numpy.linalg import norm
11
  from PIL import Image
12
  import zipfile
13
 
14
- # --- 1. ZIP DOSYASINI AÇMA ---
15
- # images klasörü yoksa zip'i açar.
16
- if not os.path.exists('images') and os.path.exists('images.zip'):
17
- with st.spinner('Resim arşivi çıkartılıyor, bu işlem biraz zaman alabilir...'):
18
- try:
19
- with zipfile.ZipFile('images.zip', 'r') as zip_ref:
20
- zip_ref.extractall('.')
21
- st.success("Resimler başarıyla çıkartıldı!")
22
- except Exception as e:
23
- st.error(f"Zip açılırken hata oluştu: {e}")
24
-
25
- # Sayfa Ayarları
26
  st.set_page_config(page_title="Moda Öneri Sistemi", layout="centered")
27
- st.title('🛍️ Moda Öneri Sistemi')
28
 
29
- # --- 2. MODEL VE VERİLERİ YÜKLEME ---
 
 
30
  @st.cache_resource
31
- def load_data():
32
- # ResNet50 Modelini Kur
33
- base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
 
 
 
 
 
34
  base_model.trainable = False
35
- model = tf.keras.models.Sequential([base_model, GlobalMaxPool2D()])
36
-
37
- # Pickle dosyalarını yükle
38
- try:
39
- with open('Images_features.pkl', 'rb') as f:
40
- features = np.array(pkl.load(f))
41
- with open('filenames.pkl', 'rb') as f:
42
- filenames = pkl.load(f)
43
- return model, features, filenames
44
- except Exception as e:
45
- st.error(f"Veri yükleme hatası (Pickle): {e}")
46
- return None, None, None
47
-
48
- model, feature_list, filenames = load_data()
49
-
50
- # --- 3. ÖZELLİK ÇIKARMA FONKSİYONU ---
 
 
 
 
 
 
 
 
 
 
51
  def extract_features(img_path, model):
52
- img = image.load_img(img_path, target_size=(224, 224))
 
53
  img_array = image.img_to_array(img)
54
- img_expand_dim = np.expand_dims(img_array, axis=0)
55
- img_preprocess = preprocess_input(img_expand_dim)
56
- result = model.predict(img_preprocess).flatten()
57
- norm_result = result / norm(result)
58
- return norm_result
59
-
60
- # --- 4. KULLANICI ARAYÜZÜ ---
61
- uploaded_file = st.file_uploader("Bir kıyafet resmi yükleyin...", type=['jpg', 'png', 'jpeg'])
62
-
63
- if uploaded_file is not None and model is not None:
64
- # Yüklenen resmi göster
65
- display_image = Image.open(uploaded_file)
66
- st.image(display_image, width=300, caption='Yüklediğiniz Resim')
67
-
68
- # Resmi geçici olarak kaydet
69
- temp_path = "temp_upload.jpg"
70
- with open(temp_path, "wb") as f:
 
 
 
 
 
71
  f.write(uploaded_file.getbuffer())
72
-
73
- # Önerileri Bul
74
- with st.spinner('Benzer ürünler taranıyor...'):
75
- input_features = extract_features(temp_path, model)
76
- neighbors = NearestNeighbors(n_neighbors=6, algorithm='brute', metric='euclidean')
 
 
 
 
 
 
77
  neighbors.fit(feature_list)
78
- distances, indices = neighbors.kneighbors([input_features])
79
-
80
- st.markdown("---")
81
- st.subheader('✨ Benzer Ürünler')
82
-
83
- # --- 5. AKILLI RESİM GÖSTERME SİSTEMİ ---
 
 
84
  cols = st.columns(5)
85
-
86
- # Tüm resimleri tara ve küçük harf-yol eşleşmesi yap (Hata payını sıfırlar)
87
- image_database = {}
88
- if os.path.exists('images'):
89
- for root, dirs, files in os.walk('images'):
90
- for f in files:
91
- image_database[f.lower()] = os.path.join(root, f)
92
-
93
- for i in range(1, 6):
94
  with cols[i-1]:
95
- # Dosya adını temizle (C:\users\123.jpg -> 123.jpg)
96
- full_raw_path = filenames[indices[0][i]].replace('\\', '/')
97
- clean_name = os.path.basename(full_raw_path).lower()
98
-
99
- # Veritabanında (zip'ten çıkan dosyalarda) bu isim var mı?
100
- if clean_name in image_database:
101
- st.image(image_database[clean_name], use_container_width=True)
 
 
 
 
102
  else:
103
- st.error(f"Eksik:\n{clean_name}")
104
 
105
- # Alt bilgi (Hata ayıklama için resim sayısını gösterir)
106
- if os.path.exists('images'):
107
- count = sum([len(files) for r, d, files in os.walk('images')])
108
- st.sidebar.write(f"Sistemdeki Toplam Resim: {count}")
 
11
  from PIL import Image
12
  import zipfile
13
 
14
+ # -----------------------------
15
+ # 1 ZIP VARSA
16
+ # -----------------------------
17
+ if not os.path.exists("images"):
18
+ if os.path.exists("images.zip"):
19
+ with zipfile.ZipFile("images.zip", "r") as zip_ref:
20
+ zip_ref.extractall(".")
21
+ st.write("images klasörü zipten çıkarıldı")
22
+
23
+ # -----------------------------
24
+ # 2 SAYFA AYARI
25
+ # -----------------------------
26
  st.set_page_config(page_title="Moda Öneri Sistemi", layout="centered")
27
+ st.title("🛍️ Moda Öneri Sistemi")
28
 
29
+ # -----------------------------
30
+ # 3 MODEL YÜKLE
31
+ # -----------------------------
32
  @st.cache_resource
33
+ def load_model():
34
+
35
+ base_model = ResNet50(
36
+ weights='imagenet',
37
+ include_top=False,
38
+ input_shape=(224,224,3)
39
+ )
40
+
41
  base_model.trainable = False
42
+
43
+ model = tf.keras.models.Sequential([
44
+ base_model,
45
+ GlobalMaxPool2D()
46
+ ])
47
+
48
+ return model
49
+
50
+ model = load_model()
51
+
52
+ # -----------------------------
53
+ # 4 FEATURE VE DOSYA LİSTESİ
54
+ # -----------------------------
55
+ @st.cache_resource
56
+ def load_data():
57
+
58
+ features = np.array(pkl.load(open("Images_features.pkl","rb")))
59
+ filenames = pkl.load(open("filenames.pkl","rb"))
60
+
61
+ return features, filenames
62
+
63
+ feature_list, filenames = load_data()
64
+
65
+ # -----------------------------
66
+ # 5 FEATURE ÇIKAR
67
+ # -----------------------------
68
  def extract_features(img_path, model):
69
+
70
+ img = image.load_img(img_path, target_size=(224,224))
71
  img_array = image.img_to_array(img)
72
+
73
+ expanded = np.expand_dims(img_array, axis=0)
74
+
75
+ preprocessed = preprocess_input(expanded)
76
+
77
+ result = model.predict(preprocessed).flatten()
78
+
79
+ normalized = result / norm(result)
80
+
81
+ return normalized
82
+
83
+ # -----------------------------
84
+ # 6 RESİM YÜKLEME
85
+ # -----------------------------
86
+ uploaded_file = st.file_uploader("Bir kıyafet resmi yükleyin", type=["jpg","png","jpeg"])
87
+
88
+ if uploaded_file is not None:
89
+
90
+ img = Image.open(uploaded_file)
91
+ st.image(img, width=300)
92
+
93
+ with open("temp.jpg","wb") as f:
94
  f.write(uploaded_file.getbuffer())
95
+
96
+ with st.spinner("Benzer ürünler aranıyor..."):
97
+
98
+ input_feature = extract_features("temp.jpg", model)
99
+
100
+ neighbors = NearestNeighbors(
101
+ n_neighbors=6,
102
+ algorithm="brute",
103
+ metric="euclidean"
104
+ )
105
+
106
  neighbors.fit(feature_list)
107
+
108
+ distances, indices = neighbors.kneighbors([input_feature])
109
+
110
+ st.subheader("✨ Benzer Ürünler")
111
+
112
+ # -----------------------------
113
+ # 7 RESİMLERİ GÖSTER
114
+ # -----------------------------
115
  cols = st.columns(5)
116
+
117
+ for i in range(1,6):
118
+
 
 
 
 
 
 
119
  with cols[i-1]:
120
+
121
+ file_path = filenames[indices[0][i]]
122
+
123
+ file_name = os.path.basename(file_path)
124
+
125
+ image_path = os.path.join("images", file_name)
126
+
127
+ if os.path.exists(image_path):
128
+
129
+ st.image(image_path, use_container_width=True)
130
+
131
  else:
 
132
 
133
+ st.write("Eksik:", file_name)