ESMATUGBA commited on
Commit
09d8565
·
verified ·
1 Parent(s): d517292

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -83
app.py CHANGED
@@ -4,34 +4,37 @@ import numpy as np
4
  import os
5
  import warnings
6
 
7
- # --- 1. SİNSİ HATALARI SUSTUR / SILENCE ERRORS ---
8
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
9
  warnings.filterwarnings('ignore')
10
 
11
- # --- 2. SAYFA AYARLARI / PAGE CONFIG ---
12
  st.set_page_config(page_title="Car Logo AI Pro 2026", layout="wide", page_icon="🚗")
13
 
14
- # --- 3. VERİ SETİNİ BELLEĞE YÜKLE / LOAD DATASET ---
15
  @st.cache_resource
16
  def load_car_dataset(base_path):
17
  dataset = []
18
- # Klasör yolunu normalize et (Windows/Linux uyumu için)
19
- target_path = os.path.normpath(base_path)
20
-
21
- if os.path.exists(target_path):
22
- for root, dirs, files in os.walk(target_path):
23
- for file in files:
24
- if file.lower().endswith(('.png', '.jpg', '.jpeg')):
25
- full_path = os.path.join(root, file)
26
- img = cv2.imread(full_path, 0)
27
- if img is not None:
28
- dataset.append((full_path, cv2.resize(img, (100, 100))))
 
 
29
  return dataset
30
 
31
- # Veri setini yükle
32
- dataset = load_car_dataset('Car_Logo_Dataset')
 
33
 
34
- # --- 4. RESİM İŞLEME / IMAGE PROCESSING ---
35
  @st.cache_data
36
  def process_uploaded_image(file_bytes):
37
  nparr = np.frombuffer(file_bytes, np.uint8)
@@ -41,89 +44,63 @@ def process_uploaded_image(file_bytes):
41
  edges = cv2.Canny(gray, 100, 200)
42
  return img, gray, edges
43
 
44
- # --- 5. ARAYÜZ TASARIMI / UI DESIGN ---
45
- st.title("🚗 Araba Logosu Tanıma Sistemi / Car Logo Recognition")
46
  st.markdown("---")
47
 
48
  col_left, col_right = st.columns([1, 1], gap="large")
49
 
50
  with col_left:
51
- st.subheader("📤 Yükleme Alanı / Upload Area")
52
-
53
- # İstediğin özel 200MB uyarısı
54
- st.markdown("""
55
- <div style="color: #666; font-size: 0.85em; margin-bottom: -10px; font-family: sans-serif;">
56
- 200MB per file • JPG, PNG, JPEG
57
- </div>
58
- """, unsafe_allow_html=True)
59
 
60
- uploaded_file = st.file_uploader(
61
- "Yeni bir logo seçin / Select a new logo",
62
- type=['jpg', 'png', 'jpeg'],
63
- key="main_uploader"
64
- )
65
 
66
- st.markdown("---")
67
-
68
  if uploaded_file:
69
  raw_img, gray_img, edge_img = process_uploaded_image(uploaded_file.getvalue())
70
- st.write("🖼️ **Seçilen Logo / Selected Logo:**")
71
- st.image(raw_img, channels="BGR", width=400)
72
 
73
  with col_right:
74
- st.subheader("🎯 Analiz ve Sonuç / Analysis & Result")
75
- threshold = st.slider("Hassasiyet / Sensitivity (Threshold)", 0.0, 1.0, 0.20)
 
76
 
77
  if uploaded_file:
78
  if st.button("ŞİMDİ TANI / PREDICT NOW", type="primary", use_container_width=True):
79
- with st.spinner("32 Marka Taranıyor... / Scanning 32 Brands..."):
80
- query = cv2.resize(gray_img, (100, 100))
81
- best_score = -1
82
- best_path = None
83
-
84
- for path, temp_img in dataset:
85
- res = cv2.matchTemplate(query, temp_img, cv2.TM_CCOEFF_NORMED)
86
- _, max_val, _, _ = cv2.minMaxLoc(res)
87
- if max_val > best_score:
88
- best_score = max_val
89
- best_path = path
90
-
91
- # --- AKILLI MARKA İSMİ AYIKLAMA ---
92
- if best_path and best_score >= threshold:
93
- st.balloons()
94
 
95
- # Yolu parçalarına ayır
96
- parts = os.path.normpath(best_path).split(os.sep)
 
 
 
 
97
 
98
- # Klasör yapısına göre marka adını bul (Genelde sondan bir önceki parça)
99
- if len(parts) > 1:
100
- raw_brand = parts[-2]
101
- # Eğer üst klasör ismini (Car_Logo_Dataset) aldıysa dosya adına bak
102
- if "DATASET" in raw_brand.upper() or raw_brand == ".":
103
- raw_brand = parts[-1].split('.')[0]
 
 
 
 
 
 
104
  else:
105
- raw_brand = parts[-1].split('.')[0]
106
 
107
- # Gereksiz karakterleri ve sayıları temizle
108
- brand_name = ''.join([i for i in raw_brand if not i.isdigit() and i not in ['-', '_']]).strip().upper()
109
-
110
- st.success(f"### TAHMİN / PREDICTION: **{brand_name}**")
111
- st.metric("Benzerlik / Similarity", f"%{int(best_score*100)}")
112
- st.image(best_path, width=150, caption=f"Eşleşen: {brand_name}")
113
- else:
114
- st.error("❌ Eşleşme Bulunamadı / Match Not Found")
115
-
116
- # --- 6. TEKNİK ANALİZ ---
117
  if uploaded_file:
118
  st.markdown("---")
119
- with st.expander("🔍 Teknik Detaylar / Technical Details"):
120
- t1, t2 = st.tabs(["🇹🇷 Türkçe", "🇺🇸 English"])
121
- with t1:
122
- st.image(edge_img, width=300, caption="Kenar Analizi")
123
- st.info(f"Sistem veri setindeki {len(dataset)} referans ile karşılaştırma yaptı.")
124
- with t2:
125
- st.image(edge_img, width=300, caption="Edge Analysis")
126
- st.info(f"System compared with {len(dataset)} reference images.")
127
-
128
- # Görsel Stil
129
- st.markdown("<style>.stMetric { background: #f0f2f6; border-radius: 10px; padding: 10px; }</style>", unsafe_allow_html=True)
 
4
  import os
5
  import warnings
6
 
7
+ # --- 1. SİNSİ HATALARI SUSTUR ---
8
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
9
  warnings.filterwarnings('ignore')
10
 
11
+ # --- 2. SAYFA AYARLARI ---
12
  st.set_page_config(page_title="Car Logo AI Pro 2026", layout="wide", page_icon="🚗")
13
 
14
+ # --- 3. VERİ SETİNİ BELLEĞE YÜKLE (Gelişmiş Yol Algılama) ---
15
  @st.cache_resource
16
  def load_car_dataset(base_path):
17
  dataset = []
18
+ # Klasör yoksa boş liste dön, hata verme
19
+ if not os.path.exists(base_path):
20
+ return dataset
21
+
22
+ for root, dirs, files in os.walk(base_path):
23
+ for file in files:
24
+ if file.lower().endswith(('.png', '.jpg', '.jpeg')):
25
+ full_path = os.path.join(root, file)
26
+ # OpenCV resim okuma (Gri ton)
27
+ img = cv2.imread(full_path, 0)
28
+ if img is not None:
29
+ # Hız için önceden boyutlandırıyoruz
30
+ dataset.append((full_path, cv2.resize(img, (100, 100))))
31
  return dataset
32
 
33
+ # Hem 'Car_Logo_Dataset' hem de 'dataset' isimlerini kontrol et (Hugging Face uyumu)
34
+ folder_name = 'Car_Logo_Dataset' if os.path.exists('Car_Logo_Dataset') else 'dataset'
35
+ dataset = load_car_dataset(folder_name)
36
 
37
+ # --- 4. RESİM İŞLEME ---
38
  @st.cache_data
39
  def process_uploaded_image(file_bytes):
40
  nparr = np.frombuffer(file_bytes, np.uint8)
 
44
  edges = cv2.Canny(gray, 100, 200)
45
  return img, gray, edges
46
 
47
+ # --- 5. ARAYÜZ TASARIMI ---
48
+ st.title("🚗 Araba Logosu Tanıma / Car Logo Recognition")
49
  st.markdown("---")
50
 
51
  col_left, col_right = st.columns([1, 1], gap="large")
52
 
53
  with col_left:
54
+ st.subheader("📤 Yükleme / Upload")
55
+ st.markdown('<div style="color: #666; font-size: 0.85em; margin-bottom: -10px;">200MB per file • JPG, PNG, JPEG</div>', unsafe_allow_html=True)
 
 
 
 
 
 
56
 
57
+ uploaded_file = st.file_uploader("Yeni bir logo seçin / Select a new logo", type=['jpg', 'png', 'jpeg'], key="main_up")
 
 
 
 
58
 
 
 
59
  if uploaded_file:
60
  raw_img, gray_img, edge_img = process_uploaded_image(uploaded_file.getvalue())
61
+ st.image(raw_img, channels="BGR", width=400, caption="Seçilen Logo")
 
62
 
63
  with col_right:
64
+ st.subheader("🎯 Sonuç / Result")
65
+ # Hassasiyeti biraz düşürdüm (0.15) ki Hugging Face'te daha kolay bulsun
66
+ threshold = st.slider("Hassasiyet / Sensitivity", 0.0, 1.0, 0.15)
67
 
68
  if uploaded_file:
69
  if st.button("ŞİMDİ TANI / PREDICT NOW", type="primary", use_container_width=True):
70
+ if len(dataset) == 0:
71
+ st.error("Veri seti yüklenemedi! Klasör ismini kontrol edin.")
72
+ else:
73
+ with st.spinner("Eşleştiriliyor..."):
74
+ query = cv2.resize(gray_img, (100, 100))
75
+ best_score = -1
76
+ best_path = None
 
 
 
 
 
 
 
 
77
 
78
+ for path, temp_img in dataset:
79
+ res = cv2.matchTemplate(query, temp_img, cv2.TM_CCOEFF_NORMED)
80
+ _, max_val, _, _ = cv2.minMaxLoc(res)
81
+ if max_val > best_score:
82
+ best_score = max_val
83
+ best_path = path
84
 
85
+ if best_path and best_score >= threshold:
86
+ st.balloons()
87
+ # Klasör yapısından marka adını çek (Garantili yöntem)
88
+ parts = os.path.normpath(best_path).split(os.sep)
89
+ # Eğer klasör içindeyse klasör adını, değilse dosya adını al
90
+ brand_raw = parts[-2] if len(parts) > 1 and parts[-2].lower() not in [folder_name.lower(), '.'] else parts[-1].split('.')[0]
91
+
92
+ brand_name = ''.join([i for i in brand_raw if not i.isdigit() and i not in ['-', '_']]).strip().upper()
93
+
94
+ st.success(f"### TAHMİN: **{brand_name}**")
95
+ st.metric("Benzerlik", f"%{int(best_score*100)}")
96
+ st.image(best_path, width=150)
97
  else:
98
+ st.error("❌ Eşleşme Bulunamadı. Hassasiyeti düşürmeyi deneyin.")
99
 
100
+ # --- 6. TEKNİK DETAYLAR ---
 
 
 
 
 
 
 
 
 
101
  if uploaded_file:
102
  st.markdown("---")
103
+ with st.expander("🔍 Teknik Detaylar"):
104
+ c1, c2 = st.columns(2)
105
+ c1.image(edge_img, width=300, caption="Kenar Analizi")
106
+ c2.image(cv2.resize(gray_img, (100, 100)), caption="AI Girişi")