EVREN Platformu üzerinde eğittiğim nesne tespiti modellerini açık kaynak topluluğuna canlı demo olarak sunmak istediğimde, klasik Gradio veya FastAPI tabanlı bir Hugging Face Space kurmanın üç yapısal maliyetiyle karşılaştım:
- Uyku (Sleep) ve soğuk başlangıç: Ücretsiz CPU Space'leri 48 saat hareketsizlikte uykuya geçiyor; okur bağlantıya tıkladığında ilk açılışta onlarca saniye bekliyor.
- GPU faturası: Eşzamanlı birkaç kullanıcı görsel yüklediğinde tek çekirdekli sunucu CPU'su tıkanıyor; bulut GPU kiralamak ise herkese açık bir demo için sürdürülebilir olmuyor.
-
Veri gizliliği: Sağlık, endüstriyel PCB denetimi veya güvenlik kamerası gibi hassas görselleri uzak bir sunucuya
POSTetmek kullanıcıyı haklı olarak tedirgin ediyor.
Çözüm olarak çıkarım motorunu sunucudan tamamen söküp kullanıcının kendi tarayıcısına taşıdım. Canlıda çalışan EVREN-Live-Object-Detection-Demo Space'i yalnızca index.html, style.css ve README.md dosyalarından oluşan bir Hugging Face Static Space (sdk: static) olarak yayınlanıyor; ağırlıkları doğrudan Hugging Face Hub'dan tarayıcıya çekiyor ve görseli cihazdan hiç çıkarmadan çıkarım yapıyor.
Bu yazı, Seri 3'ün önceki iki yazısı olan Saf ONNX Runtime ve NumPy ile Üretim Çıkarım Motoru ve Ham YOLO ZIP'ten Hugging Face Parquet'e makalelerinin doğrudan devamıdır. Python tarafında kurduğum ONNX sözleşmesini bu kez tamamen istemci tarafına (tarayıcıya) taşıyorum.
1. Canlı Space Envanteri: Gerçek ONNX Boyutları ve Tensör Şekilleri
Tarayıcıda nesne tespiti tasarlarken ilk dikkat ettiğim metrik, kullanıcının ilk açılışta indireceği .onnx ağırlık boyutu ve modelin gerçek giriş/çıkış tensör sözleşmesi oldu. Canlı EVREN-Live-Object-Detection-Demo Space'inde sunduğum dört üretim modelini onnxruntime ile doğrudan incelediğimde elde ettiğim gerçek değerler şöyle:
| Model Deposu (Hugging Face) | Mimari | Sınıf Sayısı | Gerçek best.onnx Boyutu |
Giriş Tensörü (images) |
640×640 Çıkış Şekli (output0) |
|---|---|---|---|---|---|
| yolo11s-pcb-defect-inspection-6class-tr | YOLO11s | 6 | 36.00 MB (37,753,415 B) | float32 [batch, 3, H, W] |
[1, 10, 8400] |
| yolo26s-wildfire-smoke-early-detection-tr | YOLO26s | 1 | 36.29 MB (38,054,802 B) | float32 [batch, 3, H, W] |
[1, 5, 8400] |
| yolo26s-highway-traffic-signs-23class-tr | YOLO26s | 23 | 36.32 MB (38,089,296 B) | float32 [batch, 3, H, W] |
[1, 27, 8400] |
| yolo26x-industrial-ppe-safety-pro-tr | YOLO26x | 5 | 209.63 MB (219,813,382 B) | float32 [batch, 3, H, W] |
[1, 9, 8400] |
Bu tablodan tarayıcı mimarisi açısından iki kritik ders çıkardım:
-
36 MB vs. 209.63 MB gerçekliği:
YOLO11sveYOLO26ssınıfı modeller (~36 MB) mobil bağlantıda bile saniyeler içinde inip tarayıcı önbelleğine yerleşiyor. Buna karşılıkYOLO26x(209.63 MB) gibi büyük ağırlıklar yalnızca yüksek RAM'li masaüstü tarayıcılarda ve kullanıcıya açık boyut uyarısı verilerek yüklenmeli. -
İki farklı çıkış sözleşmesi: Yukarıdaki dört ham ONNX dışa aktarımının tamamı
[1, 4 + C, 8400]([cx, cy, w, h, cls_0..cls_{C-1}]) şeklinde dönüyor ve istemci tarafında sınıf-bazlı NMS gerektiriyor. Öte yandannms=Trueile uçtan uca (end-to-end) dışa aktarılan ONNX modeller[1, 300, 6]([x1, y1, x2, y2, score, class_id]) döndürüyor. Tarayıcı ayrıştırıcısını her iki şekli otomatik tanıyacak biçimde yazmak ileride yeni model eklerken kod değiştirmeyi ortadan kaldırıyor.
2. Tarayıcıda ONNX Runtime Web Kullanırken Karşılaştığım 5 Kritik Tuzak
İlk canlı Space sürümüm yalnızca executionProviders: ["wasm"] ile çalışan yalın bir kurulumdu. Bunu üretim dayanıklılığına çıkarırken beş sessiz hata noktasıyla karşılaştım:
Tuzak 1: COOP/COEP Başlığı Olmadan Çok İş Parçacıklı WASM Açmak
Hugging Face Static Space ortamında özel Cross-Origin-Opener-Policy ve Cross-Origin-Embedder-Policy başlıkları tanımlanmadığı için self.crossOriginIsolated değeri false döner ve SharedArrayBuffer kapalı kalır. Bu ortamda ort.env.wasm.numThreads değerini körü körüne 4 yapmak sessiz uyarılar veya başlatma hataları doğurur. Çözüm: ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 2) : 1; şeklinde güvenli sınır koymak.
Tuzak 2: WebGPU Fallback ve output.getData() Farkı
onnxruntime-web için ort.webgpu.min.js paketini kullandığımda WebGPU destekli tarayıcılarda (Chrome, Edge, güncel Safari ve Firefox) ciddi hız artışı elde ettim; ancak iki detay hayati önem taşıyor:
-
navigator.gpuvarlığı tek başına yeterli değil;await navigator.gpu.requestAdapter()nulldönebilir ya da büyük modellerde oturum açılıp ilksession.run()çağrısında GPU bellek/operatör hatası fırlatabilir. Bu yüzden hem oturum açılışını hem desession.run()çağrısınıtry/catchile koruyup WebGPU hata verdiğinde oturumurelease()edip otomatik olarak["wasm"]sağlayıcısına düşmek gerekiyor. - WebGPU sağlayıcısında çıktı tensörü GPU belleğinde tutulabilir; bu durumda doğrudan
output.dataokumak hata fırlatır.await output.getData()çağırmak hem WebGPU hem WASM oturumlarında güvenleFloat32Arraydöndürür.
Tuzak 3: tensor.dispose(), session.release() ve URL.revokeObjectURL() Unutmak (Bellek Sızıntısı)
Python'da çöp toplayıcı (GC) kısa sürede temizlik yapsa da tarayıcıda ONNX Runtime Web'in oluşturduğu WASM/WebGPU tensör tamponları, önbellekte biriken oturumlar ve URL.createObjectURL(file) nesneleri açıkça serbest bırakılmadığında ardışık çıkarımlarda veya model geçişlerinde tarayıcı sekmesi bellek şişmesinden çökebiliyor. Her çıkarımı try { ... } finally { if (inputTensor) inputTensor.dispose(); if (outMap) Object.values(outMap).forEach((t) => t.dispose()); } bloğuyla sarmak, model değiştirirken önceki oturumu await prev.session.release() ile serbest bırakmak ve görsel yüklendiğinde URL.revokeObjectURL(objUrl) çağırmak bu sızıntıyı tamamen kesiyor.
Tuzak 4: Hugging Face Hub URL'sinde /blob/ vs /resolve/ ve CORS Preflight
Hugging Face Hub'dan tarayıcıya model indirirken /blob/main/best.onnx yerine mutlaka /resolve/main/best.onnx kullanmak gerekiyor. Canlı HTTP başlık testinde doğruladığım akış şöyle işliyor:
-
huggingface.co/.../resolve/main/best.onnxisteğiHTTP/2 302veaccess-control-allow-origin: <Space-Origin>başlığıyla Xet/LFS CDN adresine (us.aws.cdn.hf.co) yönlendiriyor. - CDN yanıtı
HTTP/2 200veaccess-control-allow-origin: *başlığıyla ham ikili dosyayı teslim ediyor. - İstek içine gereksiz özel HTTP başlıkları (örneğin
X-Custom-*veyaAuthorization) eklenirse tarayıcı yönlendirmede CORS preflight hatası üretebilir; herkese açık modellerde yalınfetch(url, { mode: "cors", cache: "force-cache" })kullanmak en temiz yoldur. (Not: Birçok tarayıcının standart HTTP önbelleği ~50–100 MB üzerindeki tekil dosyaları diskte tutmayabilir; 200 MB+ modellerde kalıcı önbellekleme için Cache Storage API veya OPFS/IndexedDB kullanmak gerekir.)
Tuzak 5: Retina / HiDPI Ekranlarda Bulanık Canvas Kutuları (DPR Ölçekleme)
<canvas> genişliğini yalnızca görselin ham piksel boyutuna eşitleyip CSS ile küçülttüğümde yüksek yoğunluklu (devicePixelRatio = 2 veya 3) ekranlarda kutu kenarlıkları ve etiket metinleri bulanıklaşıyor. Çözüm: Canvas'ın görünen CSS boyutunu (displayW × displayH) hesaplayıp fiziksel tamponu displayW * dpr olarak ayarlamak (mobil bellek tüketimini sınırlamak için dpr değerini 2 ile sınırlandırarak), ardından ctx.setTransform(dpr, 0, 0, dpr, 0, 0) ile çizimi mantıksal piksel uzayında netleştirmek.
3. Hugging Face Static Space Kurulumu (README.md YAML)
Bir Hugging Face Static Space'i ayağa kaldırmak için requirements.txt, Dockerfile veya Python sunucu kodu gerekmez. Depo kökündeki README.md dosyasına aşağıdaki YAML üst bilgisini eklemek yeterlidir:
---
title: EVREN Live Object Detection Demo (Browser ONNX)
emoji: 🎯
colorFrom: green
colorTo: indigo
sdk: static
app_file: index.html
pinned: true
license: apache-2.0
short_description: Live browser ONNX object detection for EVREN vision models
models:
- kenantabak/yolo11s-pcb-defect-inspection-6class-tr
- kenantabak/yolo26x-industrial-ppe-safety-pro-tr
- kenantabak/yolo26s-wildfire-smoke-early-detection-tr
- kenantabak/yolo26s-highway-traffic-signs-23class-tr
---
Bu dosyayı ve tek sayfalık index.html uygulamasını huggingface.co/spaces/<kullanici>/<space-adi> reposuna gönderdiğim anda Space anında yayınlanır, asla uykuya geçmez ve GPU maliyeti sıfırdır.
4. Üretim Kalitesinde Tarayıcı Çıkarım Motoru (index.html)
Aşağıdaki tek dosya index.html, doğrudan kopyalanıp bir Hugging Face Static Space'ine veya herhangi bir statik sunucuya bırakıldığında çalışan tam üretim uygulamasıdır (canlı Space reposunda stiller ayrı style.css dosyasındadır; aşağıda tek dosyada kopyalanıp çalıştırılabilir tam sürümü paylaşıyorum). İçinde WebGPU → WASM otomatik geçişi (oturum açılışı + çalışma zamanı geri dönüşü), büyük model indirme onayı, letterbox + unpad + clamp, tensor.dispose(), DPR ölçekli Canvas çizimi, çift formatlı YOLO çıkış ayrıştırıcı ([1, N, 6] ve [1, 4+C, anchors]) + sınıf-bazlı NMS ve canlı Hugging Face model bağlantıları yer alıyor:
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EVREN Tarayıcı ONNX Nesne Tespiti (WebGPU / WASM)</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/ort.webgpu.min.js"></script>
<style>
:root { --bg:#0b1120; --card:#111a2e; --border:#1e293b; --accent:#38bdf8; --text:#f8fafc; --muted:#94a3b8; }
* { box-sizing: border-box; font-family: Inter, system-ui, -apple-system, sans-serif; }
body { margin: 0; background: var(--bg); color: var(--text); padding: 20px; }
.wrap { max-width: 1080px; margin: 0 auto; display: grid; grid-template-columns: 340px 1fr; gap: 18px; }
@media (max-width: 860px) { .wrap { grid-template-columns: 1fr; } }
.card { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 16px; }
label { display: block; font-size: .84rem; color: var(--muted); margin: 10px 0 6px; font-weight: 600; }
select, input { width: 100%; }
select, input[type="file"] { background: #0f172a; color: var(--text); border: 1px solid #334155; border-radius: 8px; padding: 8px; }
button { width: 100%; margin-top: 14px; padding: 11px; border: 0; border-radius: 9px; background: var(--accent); color: #0b1120; font-weight: 700; cursor: pointer; }
button:disabled { opacity: .5; cursor: not-allowed; }
.status { margin-top: 10px; font-size: .84rem; color: var(--accent); min-height: 20px; }
.stage { display: flex; justify-content: center; align-items: center; min-height: 360px; background: #070c18; border-radius: 10px; border: 1px dashed #334155; padding: 8px; }
canvas { display: block; max-width: 100%; height: auto; }
table { width: 100%; border-collapse: collapse; margin-top: 12px; font-size: .84rem; }
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--border); }
</style>
</head>
<body>
<div class="wrap">
<div class="card">
<h2 style="margin:0 0 8px;font-size:1.1rem;">Tarayıcı ONNX Nesne Tespiti</h2>
<label for="modelSel">1. Üretim Modeli (HF Hub)</label>
<select id="modelSel">
<option value="pcb">PCB Hata Tespiti · YOLO11s (36.0 MB)</option>
<option value="smoke">Orman Yangını Dumanı · YOLO26s (36.3 MB)</option>
<option value="traffic">Trafik İşaretleri (23 Sınıf) · YOLO26s (36.3 MB)</option>
<option value="ppe">Endüstriyel KKD · YOLO26x (209.6 MB - Büyük)</option>
</select>
<label for="fileIn">2. Görsel Seç (Cihazdan Çıkmaz)</label>
<input type="file" id="fileIn" accept="image/*" />
<label>3. Güven Eşiği: <span id="confVal">0.25</span></label>
<input type="range" id="confSl" min="0.05" max="0.90" step="0.05" value="0.25" />
<label>4. NMS IoU Eşiği: <span id="iouVal">0.45</span></label>
<input type="range" id="iouSl" min="0.10" max="0.90" step="0.05" value="0.45" />
<button id="runBtn" disabled>Çıkarımı Başlat</button>
<div class="status" id="status">Başlamak için bir görsel seçin.</div>
</div>
<div class="card">
<div class="stage" id="stage"><canvas id="outCanvas"></canvas></div>
<div id="report"></div>
</div>
</div>
<script>
const MODEL_CFG = {
pcb: {
repo: "kenantabak/yolo11s-pcb-defect-inspection-6class-tr",
url: "https://huggingface.co/kenantabak/yolo11s-pcb-defect-inspection-6class-tr/resolve/main/best.onnx",
sizeMB: 36.0,
inputSize: 640,
classes: ["missing_hole", "mouse_bite", "open_circuit", "short", "spur", "spurious_copper"]
},
smoke: {
repo: "kenantabak/yolo26s-wildfire-smoke-early-detection-tr",
url: "https://huggingface.co/kenantabak/yolo26s-wildfire-smoke-early-detection-tr/resolve/main/best.onnx",
sizeMB: 36.3,
inputSize: 640,
classes: ["smoke"]
},
traffic: {
repo: "kenantabak/yolo26s-highway-traffic-signs-23class-tr",
url: "https://huggingface.co/kenantabak/yolo26s-highway-traffic-signs-23class-tr/resolve/main/best.onnx",
sizeMB: 36.3,
inputSize: 640,
classes: [
"Car", "Danger Ahead", "Give Way", "GreenSignal", "Left Sharp Curve",
"No Entry", "No Over Taking", "No Parking", "No Stopping", "No U-Turn",
"Pedestrian Crossing", "RedSignal", "Right Sharp Curve", "Road Work",
"Roundabout", "School Zone", "Speed Limit 20", "Speed Limit 30",
"Speed Limit 50", "Speed Limit 60", "Speed Limit 80", "Stop", "YellowSignal"
]
},
ppe: {
repo: "kenantabak/yolo26x-industrial-ppe-safety-pro-tr",
url: "https://huggingface.co/kenantabak/yolo26x-industrial-ppe-safety-pro-tr/resolve/main/best.onnx",
sizeMB: 209.6,
inputSize: 640,
classes: ["boots", "gloves", "helmet", "human", "vest"]
}
};
const PALETTE = ["#38bdf8", "#10b981", "#f59e0b", "#ef4444", "#a855f7", "#ec4899", "#14b8a6", "#6366f1"];
const offscreenCanvas = document.createElement("canvas");
const offscreenCtx = offscreenCanvas.getContext("2d", { willReadFrequently: true });
let activeSession = null; // { key, session, activeEP } - model degisiminde release() edilir
let loadedImg = null;
const modelSel = document.getElementById("modelSel");
const fileIn = document.getElementById("fileIn");
const confSl = document.getElementById("confSl");
const iouSl = document.getElementById("iouSl");
const runBtn = document.getElementById("runBtn");
const statusEl = document.getElementById("status");
const stageEl = document.getElementById("stage");
const reportEl = document.getElementById("report");
const canvas = document.getElementById("outCanvas");
const ctx = canvas.getContext("2d");
// Static Space ortaminda COOP/COEP olmadiginda WASM thread sayisini guvenli tut ve CDN yolunu sabitle
ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/";
ort.env.wasm.numThreads = self.crossOriginIsolated
? Math.min(4, navigator.hardwareConcurrency || 2)
: 1;
confSl.addEventListener("input", () => {
document.getElementById("confVal").textContent = Number(confSl.value).toFixed(2);
});
iouSl.addEventListener("input", () => {
document.getElementById("iouVal").textContent = Number(iouSl.value).toFixed(2);
});
fileIn.addEventListener("change", (event) => {
const file = event.target.files?.[0];
if (!file) return;
const objUrl = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
URL.revokeObjectURL(objUrl); // Blob bellek sizintisini onle
loadedImg = img;
reportEl.innerHTML = "";
drawResult(img, [], []);
runBtn.disabled = false;
statusEl.textContent = `Görsel hazır (${img.naturalWidth}×${img.naturalHeight}). Çıkarımı başlatabilirsiniz.`;
};
img.onerror = () => {
URL.revokeObjectURL(objUrl);
statusEl.textContent = "Görsel okunamadı. Geçerli bir JPG/PNG/WebP seçin.";
};
img.src = objUrl;
});
async function canUseWebGPU() {
if (!("gpu" in navigator)) return false;
try {
const adapter = await navigator.gpu.requestAdapter();
return Boolean(adapter);
} catch {
return false;
}
}
async function releaseActiveSession() {
if (!activeSession) return;
try {
await activeSession.session.release();
} catch (relErr) {
console.warn("Önceki oturum serbest bırakılamadı:", relErr);
}
activeSession = null;
}
async function getSession(modelKey, { forceWasm = false } = {}) {
if (!forceWasm && activeSession && activeSession.key === modelKey) return activeSession;
const cfg = MODEL_CFG[modelKey];
if (!forceWasm && cfg.sizeMB > 100) {
const ok = window.confirm(
`${cfg.repo} yaklaşık ${cfg.sizeMB} MB boyutunda. İndirmeye devam etmek istiyor musunuz?`
);
if (!ok) throw new Error("Büyük model indirmesi kullanıcı tarafından iptal edildi.");
}
await releaseActiveSession();
statusEl.textContent = `${cfg.repo} indiriliyor (~${cfg.sizeMB} MB)...`;
// HF Hub /resolve/main/best.onnx -> 302 -> CDN (Access-Control-Allow-Origin: *)
const resp = await fetch(cfg.url, { mode: "cors", cache: "force-cache" });
if (!resp.ok) throw new Error(`Model indirilemedi (HTTP ${resp.status})`);
const modelBytes = new Uint8Array(await resp.arrayBuffer());
let session = null;
let activeEP = "wasm";
if (!forceWasm && await canUseWebGPU()) {
try {
statusEl.textContent = "WebGPU oturumu başlatılıyor...";
session = await ort.InferenceSession.create(modelBytes, {
executionProviders: ["webgpu"],
graphOptimizationLevel: "all"
});
activeEP = "webgpu";
} catch (gpuErr) {
console.warn("WebGPU başlatılamadı, WASM fallback devreye giriyor:", gpuErr);
}
}
if (!session) {
statusEl.textContent = "WASM oturumu başlatılıyor...";
session = await ort.InferenceSession.create(modelBytes, {
executionProviders: ["wasm"],
graphOptimizationLevel: "all"
});
activeEP = "wasm";
}
activeSession = { key: modelKey, session, activeEP };
return activeSession;
}
function letterboxPreprocess(img, targetSize = 640) {
const imgW = img.naturalWidth;
const imgH = img.naturalHeight;
const scale = Math.min(targetSize / imgW, targetSize / imgH);
const newW = Math.round(imgW * scale);
const newH = Math.round(imgH * scale);
const padX = Math.floor((targetSize - newW) / 2);
const padY = Math.floor((targetSize - newH) / 2);
offscreenCanvas.width = targetSize;
offscreenCanvas.height = targetSize;
offscreenCtx.fillStyle = "rgb(114, 114, 114)";
offscreenCtx.fillRect(0, 0, targetSize, targetSize);
offscreenCtx.drawImage(img, padX, padY, newW, newH);
const rgba = offscreenCtx.getImageData(0, 0, targetSize, targetSize).data;
const plane = targetSize * targetSize;
const chw = new Float32Array(3 * plane);
for (let i = 0; i < plane; i++) {
const base = i * 4;
chw[i] = rgba[base] / 255.0;
chw[plane + i] = rgba[base + 1] / 255.0;
chw[2 * plane + i] = rgba[base + 2] / 255.0;
}
return {
tensor: new ort.Tensor("float32", chw, [1, 3, targetSize, targetSize]),
scale,
padX,
padY
};
}
function computeIoU(a, b) {
const x1 = Math.max(a.x1, b.x1);
const y1 = Math.max(a.y1, b.y1);
const x2 = Math.min(a.x2, b.x2);
const y2 = Math.min(a.y2, b.y2);
const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
const areaA = Math.max(0, a.x2 - a.x1) * Math.max(0, a.y2 - a.y1);
const areaB = Math.max(0, b.x2 - b.x1) * Math.max(0, b.y2 - b.y1);
return inter / (areaA + areaB - inter + 1e-6);
}
function clampUnpadBox(x1, y1, x2, y2, scale, padX, padY, imgW, imgH) {
const cx1 = Math.max(0, Math.min(imgW, (x1 - padX) / scale));
const cy1 = Math.max(0, Math.min(imgH, (y1 - padY) / scale));
const cx2 = Math.max(0, Math.min(imgW, (x2 - padX) / scale));
const cy2 = Math.max(0, Math.min(imgH, (y2 - padY) / scale));
if (cx2 <= cx1 || cy2 <= cy1) return null;
return { x1: cx1, y1: cy1, x2: cx2, y2: cy2 };
}
function decodeDetections(data, dims, confThr, iouThr, scale, padX, padY, imgW, imgH, maxDet = 100) {
const candidates = [];
// Durum A: Uctan uca (nms=True) cikis -> [1, N, 6] => [x1, y1, x2, y2, score, cls]
if (dims.length === 3 && dims[2] === 6 && dims[1] <= 1000) {
for (let i = 0; i < dims[1]; i++) {
const off = i * 6;
const score = data[off + 4];
if (score < confThr) continue;
const cls = Math.round(data[off + 5]);
if (!Number.isFinite(cls) || cls < 0) continue;
const box = clampUnpadBox(
data[off], data[off + 1], data[off + 2], data[off + 3],
scale, padX, padY, imgW, imgH
);
if (!box) continue;
candidates.push({ ...box, score, cls });
}
return candidates.sort((a, b) => b.score - a.score).slice(0, maxDet);
}
// Durum B: Ham YOLO cikisi -> [1, 4 + C, anchors] (orn. [1, 10, 8400], [1, 27, 8400])
if (dims.length !== 3 || dims[1] <= 4 || dims[2] <= 0 || dims[1] > dims[2]) {
throw new Error(`Desteklenmeyen çıktı tensör şekli: [${dims.join(", ")}]`);
}
const channels = dims[1];
const anchors = dims[2];
const numClasses = channels - 4;
for (let a = 0; a < anchors; a++) {
let bestCls = 0;
let bestScore = -1;
for (let c = 0; c < numClasses; c++) {
const s = data[(4 + c) * anchors + a];
if (s > bestScore) {
bestScore = s;
bestCls = c;
}
}
if (bestScore < confThr) continue;
const cx = data[a];
const cy = data[anchors + a];
const bw = data[2 * anchors + a];
const bh = data[3 * anchors + a];
const box = clampUnpadBox(
cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2,
scale, padX, padY, imgW, imgH
);
if (!box) continue;
candidates.push({ ...box, score: bestScore, cls: bestCls });
}
// Sinif-bazli acgozlu NMS
candidates.sort((a, b) => b.score - a.score);
const kept = [];
for (const det of candidates) {
let suppressed = false;
for (const k of kept) {
if (k.cls === det.cls && computeIoU(k, det) > iouThr) {
suppressed = true;
break;
}
}
if (!suppressed) {
kept.push(det);
if (kept.length >= maxDet) break;
}
}
return kept;
}
function drawResult(img, dets, classNames) {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const availW = stageEl.clientWidth > 16 ? stageEl.clientWidth - 16 : 320;
const maxW = Math.max(160, availW);
const maxH = 540;
const viewScale = Math.min(1, maxW / img.naturalWidth, maxH / img.naturalHeight);
const dispW = Math.round(img.naturalWidth * viewScale);
const dispH = Math.round(img.naturalHeight * viewScale);
canvas.style.width = `${dispW}px`;
canvas.style.height = `${dispH}px`;
canvas.width = Math.round(dispW * dpr);
canvas.height = Math.round(dispH * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, dispW, dispH);
ctx.drawImage(img, 0, 0, dispW, dispH);
ctx.font = "600 13px Inter, system-ui, sans-serif";
ctx.lineWidth = 2;
for (const d of dets) {
const col = PALETTE[Math.abs(d.cls) % PALETTE.length];
const name = classNames[d.cls] ?? `class_${d.cls}`;
const rx = d.x1 * viewScale;
const ry = d.y1 * viewScale;
const rw = (d.x2 - d.x1) * viewScale;
const rh = (d.y2 - d.y1) * viewScale;
ctx.strokeStyle = col;
ctx.strokeRect(rx, ry, rw, rh);
const label = `${name} ${(d.score * 100).toFixed(1)}%`;
const pad = 6;
const textW = ctx.measureText(label).width + pad * 2;
const tagH = 20;
const tagX = Math.max(0, Math.min(rx, dispW - textW));
const tagY = Math.max(0, Math.min(ry >= tagH ? ry - tagH : ry, dispH - tagH));
ctx.fillStyle = col;
ctx.fillRect(tagX, tagY, textW, tagH);
ctx.fillStyle = "#0b1120";
ctx.fillText(label, tagX + pad, tagY + 14);
}
}
function escapeHtml(text) {
return String(text).replace(/[&<>"']/g, (ch) => (
{ "&": "&", "<": "<", ">": ">", "\"": """, "'": "'" }[ch]
));
}
runBtn.addEventListener("click", async () => {
const img = loadedImg;
if (!img) return;
runBtn.disabled = true;
fileIn.disabled = true;
modelSel.disabled = true;
let inputTensor = null;
let outMap = null;
try {
const key = modelSel.value;
const cfg = MODEL_CFG[key];
let entry = await getSession(key);
statusEl.textContent = `Çıkarım çalışıyor (${entry.activeEP.toUpperCase()})...`;
let t0 = performance.now();
const prep = letterboxPreprocess(img, cfg.inputSize);
inputTensor = prep.tensor;
let rawData = null;
let outDims = null;
try {
outMap = await entry.session.run({ [entry.session.inputNames[0]]: inputTensor });
const outputTensor = outMap[entry.session.outputNames[0]];
// getData() hem WebGPU (GPU->CPU okuma) hem WASM icin guvenlidir
rawData = await outputTensor.getData();
outDims = outputTensor.dims;
} catch (runErr) {
if (entry.activeEP !== "webgpu") throw runErr;
console.warn("WebGPU çıkarım hatası, WASM ile yeniden deneniyor:", runErr);
if (outMap) {
Object.values(outMap).forEach((t) => t.dispose());
outMap = null;
}
await releaseActiveSession();
entry = await getSession(key, { forceWasm: true });
statusEl.textContent = "WebGPU hatası sonrası WASM ile yeniden deneniyor...";
t0 = performance.now();
outMap = await entry.session.run({ [entry.session.inputNames[0]]: inputTensor });
const outputTensor = outMap[entry.session.outputNames[0]];
rawData = await outputTensor.getData();
outDims = outputTensor.dims;
}
const dets = decodeDetections(
rawData,
outDims,
Number(confSl.value),
Number(iouSl.value),
prep.scale,
prep.padX,
prep.padY,
img.naturalWidth,
img.naturalHeight
);
const elapsedMs = (performance.now() - t0).toFixed(1);
drawResult(img, dets, cfg.classes);
statusEl.textContent = `${entry.activeEP.toUpperCase()} · ${elapsedMs} ms · ${dets.length} tespit`;
if (!dets.length) {
reportEl.innerHTML = `<p style="color:#94a3b8;font-size:.86rem;">Eşik (${confSl.value}) üzerinde tespit yok.</p>`;
} else {
const rows = dets.map((d) => {
const clsName = escapeHtml(cfg.classes[d.cls] ?? `class_${d.cls}`);
const boxTxt = `[${Math.round(d.x1)}, ${Math.round(d.y1)}, ${Math.round(d.x2)}, ${Math.round(d.y2)}]`;
return `<tr><td><code>${clsName}</code></td><td>${(d.score * 100).toFixed(1)}%</td><td><code>${boxTxt}</code></td></tr>`;
}).join("");
reportEl.innerHTML = `<table><thead><tr><th>Sınıf</th><th>Güven</th><th>Kutu [x1, y1, x2, y2]</th></tr></thead><tbody>${rows}</tbody></table>`;
}
} catch (err) {
statusEl.textContent = `Hata: ${err.message}`;
} finally {
// WebGPU / WASM bellek sizintisini onlemek icin tum tensorleri her kosulda serbest birak
if (inputTensor) inputTensor.dispose();
if (outMap) Object.values(outMap).forEach((t) => t.dispose());
runBtn.disabled = false;
fileIn.disabled = false;
modelSel.disabled = false;
}
});
</script>
</body>
</html>
5. Mimari Karşılaştırma: Sunucu Tabanlı Space vs. Tarayıcı ONNX Static Space
| Kriter | Klasik Gradio / FastAPI Space (CPU) | Tarayıcı ONNX + Hugging Face Static Space |
|---|---|---|
| GPU / Sunucu Maliyeti | Ücretsiz CPU yavaş; GPU ücretli | 0 $ (hesaplama istemci cihazında) |
| Uyku / Soğuk Başlangıç | 48 saat sonra uyur, konteyner yeniden başlar | Sıfır uyku (anında statik HTML teslimi) |
| Görsel Gizliliği | Görsel sunucuya POST edilir |
%100 yerel (görsel cihazdan çıkmaz) |
| Ölçeklenebilirlik | Eşzamanlı kullanıcı arttıkça kuyruk oluşur | Doğal yatay ölçek (her kullanıcı kendi donanımını kullanır) |
| Sınırlama | Büyük modeller sunucu RAM'inde tutulabilir | 150 MB+ ağırlıklar mobil cihazlarda ağır kalır |
6. Canlı Demo ve Açık Kaynak Bağlantıları
- Canlı Tarayıcı Demosu (HF Static Space): EVREN-Live-Object-Detection-Demo
-
Canlı ONNX Modelleri:
- yolo11s-pcb-defect-inspection-6class-tr (36.00 MB)
- yolo26s-wildfire-smoke-early-detection-tr (36.29 MB)
- yolo26s-highway-traffic-signs-23class-tr (36.32 MB)
- yolo26x-industrial-ppe-safety-pro-tr (209.63 MB)
- Önceki Seri 3 Yazıları:
- Ekosistem: EVREN Platformu · Hugging Face (@kenantabak) · GitHub (@kenantabak)
Top comments (0)