Konuşma Takibi (Whisper WebGPU / Speech API) ve Kelime Kelime Dinamik Altyazı Dizici Motoru

_db_core PAKET #19 Whisper WebGPU + Speech API O(log N) Kelime Dizici + .SRT

Konuşma Takibi (Whisper WebGPU / Speech API) ve Kelime Kelime Dinamik Altyazı Dizici Motoru

Blogger CORS ve SharedArrayBuffer engeline takılmayan Inline Blob Web Worker içinde @huggingface/transformers (whisper-tiny / whisper-base, return_timestamps: "word") ve canlı mikrofon için SpeechRecognition (tr-TR) mimarisini birleştiren; O(log N) ikili arama ve yay fiziğiyle 60 FPS <canvas> üzerine Karaoke, Shorts Spring Pop, Hormozi Kutu Vurgusu ve Daktilo altyazıları işleyen uçtan uca konuşma dizgi motoru.

Kinetik Altyazı Stili:
Aşağıdaki herhangi bir kelime çipine tıklayarak o saniyeye atlayabilir ve metni canlı değiştirebilirsiniz.
AKTİF KELİME: #1 "Yapay" İKİLİ ARAMA: O(log N) -> 4 adım | Stil #2 00.00s / 11.40s (22 Kelime)

Mimari Karşılaştırma: Tek HTML İçinde Konuşmayı Kelime Kelime Dizmenin Doğru Yolu

Tarayıcıda konuşmayı metne ve kelime zaman damgalarına dönüştürürken yapılan en yaygın hata, new Worker('worker.js') ile harici dosya çağırmak (Blogger ve file:// üzerinde SecurityError verir) ya da 48kHz ham videoyu doğrudan Whisper modeline beslemektir:

Alt Sistem Kırılgan Yaklaşım (Anti-Pattern) _db_core Endüstriyel Standart
Web Worker Yükleme Ayrı worker.js dosyası (Blogger / CDN farklı origin hatası) veya ana iş parçacığını dondurma Blob([workerCode], { type: 'application/javascript' }) + ESM import() ile tek-HTML çalışan izole Worker
Whisper Ses Girişi 44.1kHz / 48kHz stereo diziyi doğrudan modele verip bozuk zaman damgası alma OfflineAudioContext(1, Math.ceil(dur * 16000), 16000) ile kesin 16000 Hz mono Float32Array
Kelime Eşleştirme Her karede (60 FPS) binlerce kelimelik dizide Array.find() ile doğrusal tarama Sıralı zaman damgalarında O(log N) İkili Arama (Binary Search) ile 12-14 adımda anlık yakalama
Canlı Mikrofon Modu Mikrofon akışında ağır modeli her 200ms'de baştan koşturup CPU'yu kilitleme Canlı dikte için sıfır indirmeli SpeechRecognition (tr-TR, interimResults: true), kayıtlı dosya için Whisper

1. Blogger CORS ve SharedArrayBuffer Engeline Takılmayan Blob Worker + Whisper 16kHz Kurulumu

Aşağıdaki mimari, hiçbir harici .js dosyasına ihtiyaç duymadan tek bir HTML içinde @huggingface/transformers kütüphanesini Blob Worker içinden yükler, SharedArrayBuffer bulunmayan sayfalarda tek iş parçacıklı WASM/WebGPU moduna otomatik geçer, model indirme yüzdesini arayüze bildirir ve return_timestamps: 'word' ile her kelimenin [start, end] saniyesini döndürür:

whisper-blob-worker.js - 16kHz OfflineAudioContext + Inline ESM Worker (Word Timestamps)
// 1. Herhangi bir Video/Ses dosyasını Whisper standardı olan 16.000 Hz Mono Float32Array'e çevir
async function extract16kHzMonoForWhisper(file) {
  const raw = await file.arrayBuffer();
  const AudioCtx = window.AudioContext || window.webkitAudioContext;
  const ctx = new AudioCtx();
  try {
    const decoded = await ctx.decodeAudioData(raw);
    const offline = new OfflineAudioContext(1, Math.ceil(decoded.duration * 16000), 16000);
    const src = offline.createBufferSource();
    src.buffer = decoded;
    src.connect(offline.destination);
    src.start(0);
    const rendered = await offline.startRendering();
    return rendered.getChannelData(0); // 16kHz Mono Float32Array
  } finally {
    await ctx.close();
  }
}

// 2. Blogger CORS ve SharedArrayBuffer engeline takılmayan Inline Blob Worker oluştur
function createWhisperWordWorker(onProgress, onWordsReady, onError) {
  const workerSource = `
    import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.3.3';
    env.allowLocalModels = false;
    // SharedArrayBuffer olmayan ortamlarda (Blogger vb.) çökmemesi için numThreads = 1
    if (env.backends && env.backends.onnx && env.backends.onnx.wasm) {
      env.backends.onnx.wasm.numThreads = self.crossOriginIsolated ? 4 : 1;
    }

    let transcriber = null;

    self.onmessage = async (e) => {
      const { pcm16k, lang = 'turkish', modelId = 'onnx-community/whisper-tiny' } = e.data;
      try {
        if (!transcriber) {
          const hasWebGPU = typeof navigator !== 'undefined' && !!navigator.gpu;
          transcriber = await pipeline('automatic-speech-recognition', modelId, {
            device: hasWebGPU ? 'webgpu' : 'wasm',
            dtype: hasWebGPU ? 'fp32' : 'q8',
            progress_callback: (p) => self.postMessage({ type: 'progress', info: p })
          });
        }

        const result = await transcriber(pcm16k, {
          language: lang,
          task: 'transcribe',
          return_timestamps: 'word',
          chunk_length_s: 25,
          stride_length_s: 4
        });

        const words = (result.chunks || []).map((c) => ({
          word: String(c.text || '').trim(),
          start: c.timestamp[0] || 0,
          end: c.timestamp[1] || ((c.timestamp[0] || 0) + 0.35)
        })).filter((w) => w.word.length > 0);

        self.postMessage({ type: 'done', words });
      } catch (err) {
        self.postMessage({ type: 'error', message: err.message || String(err) });
      }
    };
  `;

  const blob = new Blob([workerSource], { type: 'application/javascript' });
  const workerUrl = URL.createObjectURL(blob);
  const worker = new Worker(workerUrl, { type: 'module' });

  worker.onmessage = (e) => {
    if (e.data.type === 'progress' && onProgress) onProgress(e.data.info);
    else if (e.data.type === 'done' && onWordsReady) onWordsReady(e.data.words);
    else if (e.data.type === 'error' && onError) onError(e.data.message);
  };

  return {
    transcribe(pcm16k, lang = 'turkish') {
      // Transferable ArrayBuffer kopyasıyla ana iş parçacığını sıfır gecikmeyle koru
      const copy = new Float32Array(pcm16k);
      worker.postMessage({ pcm16k: copy, lang }, [copy.buffer]);
    },
    terminate() {
      worker.terminate();
      URL.revokeObjectURL(workerUrl);
    }
  };
}

2. O(log N) İkili Arama (Binary Search) ve Yay Fiziği (Spring Pop) Altyazı Çizici

Uzun videolarda binlerce kelimelik transkript dizisini saniyede 60 kez baştan sona taramak yerine O(log N) ikili arama kullanılır. Aktif kelime bulunduğunda geçen yerel süre (elapsed = currentTime - word.start) sönümlü harmonik yay denklemine sokularak Shorts/Reels videolarındaki karakteristik zıplayan vurgu (Spring Pop) elde edilir:

kinetic-caption-renderer.js - O(log N) Aktif Kelime Yakalayıcı & Sönümlü Yay Fiziği
function findActiveWordBinarySearch(words, currentTime) {
  let low = 0;
  let high = words.length - 1;
  let candidate = -1;

  while (low <= high) {
    const mid = (low + high) >> 1;
    const w = words[mid];
    if (currentTime >= w.start) {
      candidate = mid;
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }

  if (candidate !== -1 && currentTime <= words[candidate].end + 0.18) {
    return candidate;
  }
  return -1;
}

// Sönümlü yay fiziği: Kelime ekrana düştüğü anda 0.72 -> 1.20 -> 1.00 ölçeğine zıplar
function computeSpringPopScale(elapsedSec) {
  const t = Math.max(0, elapsedSec);
  const damping = 13.5;
  const angularFreq = 26.0;
  return 1 - 0.32 * Math.exp(-damping * t) * Math.cos(angularFreq * t);
}

function drawHormoziChunkOnCanvas(ctx, words, activeIdx, centerX, baselineY) {
  if (activeIdx < 0) return;
  const groupSize = 4;
  const groupStart = Math.floor(activeIdx / groupSize) * groupSize;
  const slice = words.slice(groupStart, groupStart + groupSize);

  ctx.save();
  ctx.font = '900 28px Inter, sans-serif';
  ctx.textBaseline = 'middle';

  const gap = 12;
  const widths = slice.map((item) => ctx.measureText(item.word.toUpperCase()).width);
  const totalW = widths.reduce((a, b) => a + b, 0) + gap * Math.max(0, slice.length - 1);
  let cursorX = centerX - totalW * 0.5;

  slice.forEach((item, idx) => {
    const globalIdx = groupStart + idx;
    const label = item.word.toUpperCase();
    const w = widths[idx];

    if (globalIdx === activeIdx) {
      ctx.fillStyle = '#facc15';
      ctx.beginPath();
      ctx.roundRect(cursorX - 8, baselineY - 22, w + 16, 44, 9);
      ctx.fill();
      ctx.fillStyle = '#090d16';
      ctx.fillText(label, cursorX, baselineY);
    } else {
      ctx.lineWidth = 5;
      ctx.strokeStyle = 'rgba(0, 0, 0, 0.85)';
      ctx.strokeText(label, cursorX, baselineY);
      ctx.fillStyle = '#f8fafc';
      ctx.fillText(label, cursorX, baselineY);
    }
    cursorX += w + gap;
  });
  ctx.restore();
}

3. Standart .SRT ve .VTT Zaman Damgası Biçimlendirici

Kelime bazlı diziyi profesyonel kurgu yazılımlarına (Premiere Pro, DaVinci Resolve, CapCut) veya HTML5 <track> bileşenine aktarmak için kelimeler 4'erli okunabilir satırlarda gruplanır. .SRT milisaniye ayıracı olarak virgül (00:00:03,420), .VTT ise nokta (00:00:03.420) kullanır:

subtitle-srt-vtt-exporter.js - Milisaniye Hassasiyetli .SRT ve WebVTT Üreteci
function formatSubtitleTimestamp(seconds, separator = ',') {
  const safeMs = Math.max(0, Math.round(seconds * 1000));
  const hrs = Math.floor(safeMs / 3600000);
  const mins = Math.floor((safeMs % 3600000) / 60000);
  const secs = Math.floor((safeMs % 60000) / 1000);
  const ms = safeMs % 1000;

  const pad2 = (n) => String(n).padStart(2, '0');
  const pad3 = (n) => String(n).padStart(3, '0');
  return `${pad2(hrs)}:${pad2(mins)}:${pad2(secs)}${separator}${pad3(ms)}`;
}

function buildSrtAndVttFromWords(words, wordsPerCue = 4) {
  const srtBlocks = [];
  const vttBlocks = ['WEBVTT\n'];
  let cueNumber = 1;

  for (let i = 0; i < words.length; i += wordsPerCue) {
    const group = words.slice(i, i + wordsPerCue);
    const startSec = group[0].start;
    const endSec = Math.max(startSec + 0.25, group[group.length - 1].end);
    const textLine = group.map((w) => w.word).join(' ');

    srtBlocks.push(
      `${cueNumber}\n${formatSubtitleTimestamp(startSec, ',')} --> ${formatSubtitleTimestamp(endSec, ',')}\n${textLine}`
    );
    vttBlocks.push(
      `${formatSubtitleTimestamp(startSec, '.')} --> ${formatSubtitleTimestamp(endSec, '.')}\n${textLine}`
    );
    cueNumber++;
  }

  return {
    srt: srtBlocks.join('\n\n') + '\n',
    vtt: vttBlocks.join('\n\n') + '\n'
  };
}
İlerleme Çubuğu Zorunluluğu whisper-tiny (~40 MB) ilk çalıştırmada tarayıcı önbelleğine (Cache API) indirilir; progress_callback ile yüzde çubuğu göstermek kullanıcı deneyimi için zorunludur.
Canvas Burn-In Avantajı Altyazıyı DOM yerine doğrudan video <canvas> katmanına çizdiğinizde canvas.captureStream(60) ile altyazısı gömülü MP4/WEBM video kaydedebilirsiniz.
Hibrit Dikte + Dosya Modu Anlık kamera/mikrofon kaydında sıfır gecikmeli SpeechRecognition (tr-TR), yüklenen video dosyalarında ise Blob Worker Whisper kullanarak iki dünyayı birleştirin.

Yorumlar

Yorum Gönder

Opromt · Ücretsiz yayınlarımız sizler için , Kopyala, yapıştır, kullan. ← Ana Sayfa