ESMATUGBA commited on
Commit
4e90266
·
verified ·
1 Parent(s): c9d542b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -58
app.py CHANGED
@@ -4,84 +4,124 @@ import numpy as np
4
  import os
5
  import warnings
6
 
7
- # --- 1. SİNSİ HATALARI VE UYARILARI SUSTUR (TİTREME ENGELLEYİCİ) ---
8
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # TensorFlow loglarını sustur
9
- warnings.filterwarnings('ignore') # Versiyon uyuşmazlığı uyarılarını gizle
10
 
11
- # --- 2. SAYFA AYARLARI (2026 STANDARDI) ---
12
- st.set_page_config(page_title="Car Logo AI 2026", layout="wide")
13
 
14
- # --- 3. KAYNAK YÖNETİMİ (MODELS & DATASET) ---
15
- # Modelleri ve veri setini RAM'e kilitle (Cache), her seferinde dosyadan okuma!
16
  @st.cache_resource
17
- def load_resources():
18
- # Burada model yükleme kodların varsa onları buraya almalısın
19
- # Örnek: model = joblib.load('model.pkl')
20
- return "Resources Loaded"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- resources = load_resources()
 
23
 
24
- # --- 4. RESİM İŞLEME (ÖNBELLEKLİ) ---
25
  @st.cache_data
26
- def process_img(file_bytes):
27
  nparr = np.frombuffer(file_bytes, np.uint8)
28
  img = cv2.imdecode(nparr, 1)
29
- if img is None: return None, None
30
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
31
  edges = cv2.Canny(gray, 100, 200)
32
- return img, edges
33
 
34
- # --- 5. ARAYÜZ (TR-EN YAN YANA) ---
35
- st.title("🚗 Logo Tanıma Sistemi / Logo Recognition System")
 
36
 
37
- # Titremeyi önlemek için ana içeriği bir container içine alıyoruz
38
- main_container = st.container()
39
 
40
- with main_container:
41
- col_up, col_info = st.columns([2, 1])
 
42
 
43
- with col_up:
44
- uploaded_file = st.file_uploader("Resim Seç / Select Image", type=['jpg', 'png', 'jpeg'])
45
-
46
- if uploaded_file:
47
- # getvalue() kullanımı 'buffer empty' hatasını ve titremeyi önler
48
- raw_img, edge_img = process_img(uploaded_file.getvalue())
49
 
50
- c1, c2 = st.columns(2)
51
-
52
- with c1:
53
- st.markdown("### 🖼️ Görünüm / View")
54
- # DİKKAT: use_container_width yerine width=700 kullanarak titremeyi kestik
55
- st.image(raw_img, channels="BGR", width=500, caption="Orijinal / Original")
56
 
57
- with c2:
58
- st.markdown("### 🎯 Sonuç / Result")
59
- if st.button("Analiz Et / Analyze", type="primary"):
60
- st.balloons()
61
- st.success("✅ Eşleşme Başarılı / Match Successful")
62
- st.metric(label="Güven / Confidence", value="%95")
63
 
64
- # --- TEKNİK DETAYLAR (EXPANDER TİTREMEZ) ---
65
- st.divider()
66
- with st.expander("🔍 Görüntü İşleme / Image Processing"):
67
- # Türkçe ve İngilizce Yan Yana Kolonlar
68
- tr_col, en_col = st.columns(2)
69
-
70
- with tr_col:
71
- st.write("### 🇹🇷 Türkçe Detay")
72
- st.image(edge_img, width=300, caption="Kenar Analizi")
73
- st.info("Logonun dış hatları Canny algoritması ile çıkarıldı.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- with en_col:
76
- st.write("### 🇺🇸 English Detail")
77
- st.image(edge_img, width=300, caption="Edge Analysis")
78
- st.info("Outlines extracted using Canny algorithm.")
79
 
80
- # Gereksiz boşlukları ve Streamlit menüsünü gizleyerek titremeyi azaltan CSS
81
  st.markdown("""
82
  <style>
83
- #MainMenu {visibility: hidden;}
84
- footer {visibility: hidden;}
85
- .block-container {padding-top: 2rem;}
86
  </style>
87
  """, unsafe_allow_html=True)
 
4
  import os
5
  import warnings
6
 
7
+ # --- 1. SİNSİ HATALARI SUSTUR (2026 OPTİMİZASYONU) ---
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 (TİTREMEYİ ÖNLEYEN ANA YER) ---
 
15
  @st.cache_resource
16
+ def load_car_dataset(base_path):
17
+ dataset = []
18
+ # Eğer klasör yoksa hata verme, ana dizine bak
19
+ if not os.path.exists(base_path):
20
+ image_files = [f for f in os.listdir('.') if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
21
+ for f in image_files:
22
+ img = cv2.imread(f, 0)
23
+ if img is not None:
24
+ dataset.append((f, cv2.resize(img, (100, 100))))
25
+ else:
26
+ for root, dirs, files in os.walk(base_path):
27
+ for file in files:
28
+ if file.lower().endswith(('.png', '.jpg', '.jpeg')):
29
+ full_path = os.path.join(root, file)
30
+ img = cv2.imread(full_path, 0)
31
+ if img is not None:
32
+ dataset.append((full_path, cv2.resize(img, (100, 100))))
33
+ return dataset
34
 
35
+ # Veri setini yükle (32 markalık klasörü tara)
36
+ dataset = load_car_dataset('Car_Logo_Dataset')
37
 
38
+ # --- 4. RESİM İŞLEME FONKSİYONU ---
39
  @st.cache_data
40
+ def process_uploaded_image(file_bytes):
41
  nparr = np.frombuffer(file_bytes, np.uint8)
42
  img = cv2.imdecode(nparr, 1)
43
+ if img is None: return None, None, None
44
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
45
  edges = cv2.Canny(gray, 100, 200)
46
+ return img, gray, edges
47
 
48
+ # --- 5. ARAYÜZ TASARIMI / UI DESIGN ---
49
+ st.title("🚗 Araba Logosu Tanıma Sistemi / Car Logo Recognition")
50
+ st.markdown("---")
51
 
52
+ # Sol ve Sağ Kolon Ayarı
53
+ col_ui, col_res = st.columns([1, 1], gap="large")
54
 
55
+ with col_ui:
56
+ st.subheader("📤 Yükleme Paneli / Upload Panel")
57
+ uploaded_file = st.file_uploader("Bir logo seçin / Select a logo", type=['jpg', 'png', 'jpeg'])
58
 
59
+ # Hassasiyet Sliderı
60
+ threshold = st.sidebar.slider("Hassasiyet / Sensitivity (Threshold)", 0.0, 1.0, 0.20)
61
+ st.sidebar.info(f"Sistemde yüklü referans sayısı: {len(dataset)}")
 
 
 
62
 
63
+ if uploaded_file:
64
+ # Resmi işle (Önbellekten gelir, titreme yapmaz)
65
+ raw_img, gray_img, edge_img = process_uploaded_image(uploaded_file.getvalue())
 
 
 
66
 
67
+ with col_ui:
68
+ # 2026 Standartlarında sabit genişlik (Titremeyi önler)
69
+ st.image(raw_img, channels="BGR", width=450, caption="Yüklenen / Uploaded")
 
 
 
70
 
71
+ with col_res:
72
+ st.subheader("🎯 Analiz Sonucu / Analysis Result")
73
+
74
+ if st.button("ŞİMDİ TANI / PREDICT NOW", type="primary"):
75
+ with st.spinner("32 Marka Taranıyor... / Scanning..."):
76
+ # Karşılaştırma döngüsü
77
+ query = cv2.resize(gray_img, (100, 100))
78
+ best_score = -1
79
+ best_path = None
80
+
81
+ for path, temp_img in dataset:
82
+ res = cv2.matchTemplate(query, temp_img, cv2.TM_CCOEFF_NORMED)
83
+ _, max_val, _, _ = cv2.minMaxLoc(res)
84
+ if max_val > best_score:
85
+ best_score = max_val
86
+ best_path = path
87
+
88
+ # MARKAYI YAZDIRMA BÖLÜMÜ
89
+ if best_path and best_score >= threshold:
90
+ st.balloons()
91
+
92
+ # Dosya yolundan 32 markadan hangisi olduğunu bul
93
+ folder_name = os.path.basename(os.path.dirname(best_path))
94
+ if not folder_name or folder_name == '.':
95
+ folder_name = os.path.basename(best_path).split('.')[0]
96
+
97
+ # İsmi temizle ve büyük harf yap
98
+ brand_name = ''.join([i for i in folder_name if not i.isdigit() and i not in ['-', '_']]).strip().upper()
99
+
100
+ st.success(f"### TAHMİN / PREDICTION: **{brand_name}**")
101
+ st.metric("Benzerlik / Similarity", f"%{int(best_score*100)}")
102
+ st.image(best_path, width=150, caption=f"Eşleşen: {brand_name}")
103
+ else:
104
+ st.error("❌ Eşleşme Bulunamadı / Match Not Found")
105
+
106
+ # --- TEKNİK ANALİZ (TİTREMEYEN ALT BÖLÜM) ---
107
+ st.markdown("---")
108
+ with st.expander("🔍 Teknik Görüntü Analizi / Technical Image Analysis"):
109
+ tr_col, en_col = st.columns(2)
110
+
111
+ with tr_col:
112
+ st.write("### 🇹🇷 Türkçe Analiz")
113
+ st.image(edge_img, width=300, caption="Canny Kenar Tespiti")
114
+ st.write(f"Logonun dış hatları çıkartıldı ve sistemdeki {len(dataset)} resimle karşılaştırıldı.")
115
 
116
+ with en_col:
117
+ st.write("### 🇺🇸 English Analysis")
118
+ st.image(edge_img, width=300, caption="Canny Edge Detection")
119
+ st.write(f"Outlines were extracted and compared with {len(dataset)} reference images.")
120
 
121
+ # Stil Ayarları (2026 Görünümü)
122
  st.markdown("""
123
  <style>
124
+ .stButton>button { height: 3em; font-size: 20px; font-weight: bold; }
125
+ .stMetric { background: #f0f2f6; padding: 10px; border-radius: 10px; }
 
126
  </style>
127
  """, unsafe_allow_html=True)