MediaWiki:Gadget-LabelScan.js: Unterschied zwischen den Versionen

Keine Bearbeitungszusammenfassung
Keine Bearbeitungszusammenfassung
Zeile 3: Zeile 3:
   'use strict';
   'use strict';


   // =============================
   // ------------------------------------------------------------
   //  KONFIGURATION
  // 0) Konfiguration
   // =============================
   // ------------------------------------------------------------
   // Debug-Ausgabe der reinen OCR-Texte (Optional: im Browser einstellen)
   // window.ADOS_SCAN_DEBUG = true;


   // ← Für Tests leer lassen: const ADOS_CATEGORIES = [];
   // In diesen Kategorien sollen Treffer bevorzugt gesucht werden:
   const ADOS_CATEGORIES = [
   const ADOS_CATEGORIES = [
     'Alle A Dream of Scotland Abfüllungen',
     'Alle A Dream of Scotland Abfüllungen',
Zeile 18: Zeile 20:
   ];
   ];


const KNOWN_TOKENS = [
   // Distillery-/Marken-Tokens (wird für „hints“ verwendet)
   // Distillery / Herkunft / Regionen
   const KNOWN_TOKENS = [
   'Ireland','Irland','Irish','Single Malt','Bourbon Barrel',
    'Ardbeg','Ardmore','Arran','Auchroisk','Ben Nevis','Blair Athol','Bowmore',
  'Cask Strength','1st Fill','First Fill',
    'Caol Ila','Clynelish','Glenallachie','Glenrothes','Longmorn','Lagavulin',
  'Aged','Years','Yo',
    'Tullibardine','Dalmore','Benrinnes','Mortlach','Glenlivet','Inchgower',
 
    'Islay','Speyside','Highland','Lowland','Campbeltown','Ireland'
  // ADOS Serien / Motivserien
  ];
  'A Dream of Scotland','A Dream of Ireland',
  'The Tasteful 8','Heroes of Childhood',
  'Space Girls','Fine Art of Whisky','The Fine Art of Whisky',
  'Friendly Mr. Z','Whiskytainment','Rumbastic',
 
  // Häufige Motivwörter
  'Unicorn','Bull','Hero','Childhood',
 
  // Distillery Namen, universell
  'Ardbeg','Ardmore','Arran','Auchroisk','Ben Nevis','Blair Athol','Bowmore',
  'Caol Ila','Clynelish','Glenallachie','Glenrothes','Longmorn',
  'Lagavulin','Tullibardine','Dalmore','Benrinnes','Mortlach','Glenlivet',
  'Inchgower','Bunnahabhain','Springbank','Caperdonich','Linkwood','Glen Scotia'
];
 
  // =============================
  //  UI-Hilfen
  // =============================


  // ------------------------------------------------------------
  // 1) UI Helpers
  // ------------------------------------------------------------
   function hasUI () {
   function hasUI () {
     return !!document.getElementById('ados-scan-run') &&
     return !!document.getElementById('ados-scan-run') &&
           !!document.getElementById('ados-scan-file');
           !!document.getElementById('ados-scan-file');
   }
   }
   function setStatus (t) {
   function setStatus (t) {
     var el = document.getElementById('ados-scan-status');
     var el = document.getElementById('ados-scan-status');
     if (el) el.textContent = t || '';
     if (el) el.textContent = t || '';
   }
   }
   function setProgress (p) {
   function setProgress (p) {
     var bar = document.getElementById('ados-scan-progress');
     var bar = document.getElementById('ados-scan-progress');
Zeile 60: Zeile 45:
     else { bar.hidden = false; bar.value = Math.max(0, Math.min(1, p)); }
     else { bar.hidden = false; bar.value = Math.max(0, Math.min(1, p)); }
   }
   }
   function showPreview (file) {
   function showPreview (file) {
     var url = URL.createObjectURL(file);
     var url = URL.createObjectURL(file);
     var prev = document.getElementById('ados-scan-preview');
     var prev = document.getElementById('ados-scan-preview');
     if (prev) {
     if (prev) {
       prev.innerHTML = '<img alt="Vorschau" src="' + url + '">';
       prev.innerHTML = '<img alt="Vorschau" style="max-width:100%;height:auto;border-radius:8px" src="' + url + '">';
       prev.setAttribute('aria-hidden', 'false');
       prev.setAttribute('aria-hidden', 'false');
     }
     }
   }
   }
  function esc (s) { return mw.html.escape(String(s || '')); }


   function showOCRText (t) {
   // ------------------------------------------------------------
    var el = document.getElementById('ados-scan-ocr');
   // 2) Tesseract bei Bedarf laden
    if (el) el.textContent = (t || '').trim();
   // ------------------------------------------------------------
  }
 
   // =============================
  //  Tesseract laden (nur 1x)
   // =============================
 
   var tesseractReady;
   var tesseractReady;
   function ensureTesseract () {
   function ensureTesseract () {
Zeile 101: Zeile 80:
   }
   }


   // =============================
   // ------------------------------------------------------------
   //  Vorverarbeitung (OCR)
  // 3) Bild-Vorverarbeitung
   //   Graustufen + Unsharp + adaptive Schwelle
   //   - skalieren
   // =============================
   //    - adaptives Thresholding (besser gegen Glanz/Folie)
 
   //   - relative Crops zum Auslesen bestimmter Zonen
   async function preprocessImage (file) {
   // ------------------------------------------------------------
     const img = await new Promise((res, rej) => {
   function fixCanvasOrientation(img, maxSide=2200) {
      const o = new Image();
     const scale = Math.min(1, maxSide / Math.max(img.width, img.height));
      o.onload = () => res(o);
    const w = Math.round(img.width * scale);
      o.onerror = rej;
    const h = Math.round(img.height * scale);
      o.src = URL.createObjectURL(file);
    const c = document.createElement('canvas');
     });
    c.width = w; c.height = h;
 
    const ctx = c.getContext('2d');
     const MAX = 1800;
    ctx.imageSmoothingEnabled = true;
     const s = Math.min(1, (img.width > img.height) ? MAX / img.width : MAX / img.height);
    ctx.drawImage(img, 0, 0, w, h);
     const w = Math.round(img.width * s), h = Math.round(img.height * s);
     return c;
 
  }
     const c = document.createElement('canvas'); c.width = w; c.height = h;
  function cropRel(srcCanvas, x, y, w, h) {
     const g = c.getContext('2d', { willReadFrequently: true });
     const sw = srcCanvas.width, sh = srcCanvas.height;
     g.imageSmoothingEnabled = true;
     const cx = Math.round(x * sw), cy = Math.round(y * sh);
     g.drawImage(img, 0, 0, w, h);
     const cw = Math.round(w * sw), ch = Math.round(h * sh);
    const out = document.createElement('canvas');
    out.width = cw; out.height = ch;
    const octx = out.getContext('2d');
    octx.drawImage(srcCanvas, cx, cy, cw, ch, 0, 0, cw, ch);
    return out;
  }
  function adaptiveThreshold(srcCanvas) {
     const w = srcCanvas.width, h = srcCanvas.height;
    const out = document.createElement('canvas'); out.width = w; out.height = h;
     const sctx = srcCanvas.getContext('2d');
     const octx = out.getContext('2d');
     const id = sctx.getImageData(0,0,w,h);
    const d = id.data;


     // → Graustufen
     const gray = new Uint8ClampedArray(w*h);
    let id = g.getImageData(0, 0, w, h), d = id.data;
     for (let i=0,j=0;i<d.length;i+=4,++j) {
     for (let i=0;i<d.length;i+=4){
       gray[j] = (0.2126*d[i] + 0.7152*d[i+1] + 0.0722*d[i+2])|0;
       const y = 0.2126*d[i] + 0.7152*d[i+1] + 0.0722*d[i+2];
      d[i]=d[i+1]=d[i+2]=y;
     }
     }
    g.putImageData(id, 0, 0);
     const S = new Uint32Array((w+1)*(h+1));
 
     for (let y=1;y<=h;y++) {
    // → Unsharp (leichter Hochpass)
      let rowsum = 0;
    id = g.getImageData(0,0,w,h); d = id.data;
       for (let x=1;x<=w;x++) {
     const copy = new Uint8ClampedArray(d);
         const v = gray[(y-1)*w + (x-1)];
    const idx = (x,y)=>4*(y*w+x);
        rowsum += v;
     for (let y=1;y<h-1;y++){
        S[y*(w+1)+x] = S[(y-1)*(w+1)+x] + rowsum;
       for (let x=1;x<w-1;x++){
         const i0=idx(x,y), a=copy[i0], b=copy[idx(x-1,y)], c0=copy[idx(x+1,y)],
              d0=copy[idx(x,y-1)], e=copy[idx(x,y+1)];
        const lap = 4*a - b - c0 - d0 - e;
        const v = Math.max(0, Math.min(255, a + 0.3*lap));
        d[i0]=d[i0+1]=d[i0+2]=v;
       }
       }
     }
     }
     g.putImageData(id,0,0);
     const win = Math.max(15, Math.round(Math.min(w,h)/24));
    const outD = octx.createImageData(w,h); const od = outD.data;
    const C = 7;


    // → adaptive Schwelle (lokaler Mittelwert)
     for (let y=0;y<h;y++) {
    const win = 25, half = (win|0);
       const y0 = Math.max(0, y - win), y1 = Math.min(h-1, y + win);
    id = g.getImageData(0,0,w,h); d = id.data;
      for (let x=0;x<w;x++) {
     for (let y=0;y<h;y++){
        const x0 = Math.max(0, x - win), x1 = Math.min(w-1, x + win);
       for (let x=0;x<w;x++){
        const A = S[y0*(w+1)+x0];
        let sum=0, cnt=0;
        const B = S[(y1+1)*(w+1)+x0];
        for (let yy=Math.max(0,y-half); yy<=Math.min(h-1,y+half); yy+=5){
        const Cc= S[y0*(w+1)+(x1+1)];
          for (let xx=Math.max(0,x-half); xx<=Math.min(w-1,x+half); xx+=5){
        const Dd= S[(y1+1)*(w+1)+(x1+1)];
            sum += d[4*(yy*w+xx)];
         const area = (x1-x0+1)*(y1-y0+1);
            cnt++;
         const mean = ((Dd + A - B - Cc) / area);
          }
         const g = gray[y*w + x];
         }
         const pix = g < (mean - C) ? 0 : 255;
         const thr = (sum/cnt) - 6;
         const k = (y*w + x)*4;
         const i = 4*(y*w+x);
        od[k]=od[k+1]=od[k+2]=pix; od[k+3]=255;
         const v = d[i] < thr ? 0 : 255;
         d[i]=d[i+1]=d[i+2]=v;
       }
       }
     }
     }
     g.putImageData(id,0,0);
     octx.putImageData(outD,0,0);
 
     return out;
     return c;
   }
   }
 
   async function preprocessImage(file) {
  // Hilfsfunktionen für Varianten
     const img = await new Promise((res, rej) => {
   function crop(canvas, x, y, w, h){
      const o = new Image();
     const c = document.createElement('canvas'); c.width=w; c.height=h;
      o.onload = () => res(o);
    c.getContext('2d').drawImage(canvas, x, y, w, h, 0, 0, w, h);
      o.onerror = rej;
    return c;
      o.src = URL.createObjectURL(file);
  }
  function rotate(canvas, deg){
    const r = document.createElement('canvas');
    const ctx = r.getContext('2d');
    if (deg % 180 === 0){ r.width=canvas.width; r.height=canvas.height; }
    else { r.width=canvas.height; r.height=canvas.width; }
    ctx.translate(r.width/2, r.height/2);
    ctx.rotate(deg*Math.PI/180);
    ctx.drawImage(canvas, -canvas.width/2, -canvas.height/2);
    return r;
  }
 
  async function ocrOne(canvas, lang) {
    const res = await Tesseract.recognize(canvas, lang, {
      // Sparse text funktioniert bei Labels (verschieden orientierte Textblöcke)
      tessedit_pageseg_mode: 11,
      preserve_interword_spaces: 1
     });
     });
     return { text: (res?.data?.text||'').trim(), conf: res?.data?.confidence||0 };
     const base = fixCanvasOrientation(img, 2200);
    const bin  = adaptiveThreshold(base);
    return { base, bin };
   }
   }


   // =============================
   // ------------------------------------------------------------
   //   Mehrfach-OCR (Rotationen/Regionen) + Fallback-Sprache
   // 4) OCR (Mehrzonen, Whitelists)
   // =============================
   // ------------------------------------------------------------
  async function runOCR(file) {
    await ensureTesseract();
    setProgress(0);
    const { base, bin } = await preprocessImage(file);


  async function runOCR(file){
    const zones = [
    await ensureTesseract();
      { name:'header',  crop:[0.00,0.00,1.00,0.28],  psm:6, whitelist:'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -&.,’\'' },
    setProgress(0.01);
      { name:'body',    crop:[0.00,0.28,1.00,0.52],  psm:6, whitelist:null },
     const base = await preprocessImage(file);
      { name:'footer',  crop:[0.00,0.80,1.00,0.20],  psm:6, whitelist:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 %°.,-’\'' },
     ];


    // Kandidatenflächen
     const texts = [];
     const variants = [];
     let step = 0, total = zones.length*2;
     variants.push(base); // komplett
    variants.push(crop(base, 0, 0, Math.round(base.width*0.4), base.height)); // linke Spalte
    variants.push(crop(base, 0, Math.round(base.height*0.72), base.width, Math.round(base.height*0.28))); // unteres Banner


    // + Rotationen
     for (const z of zones) {
    const more = [];
       const cropBin  = cropRel(bin, ...z.crop);
     for (const v of variants){
      const cropBase = cropRel(base, ...z.crop);
       more.push(v, rotate(v, 90), rotate(v, -90));
    }


    // zwei Sprachmodi testen
      async function pass(canvas) {
    const results = [];
        const opts = { tessedit_pageseg_mode: z.psm, preserve_interword_spaces: 1 };
    for (const canv of more){
        if (z.whitelist) opts.tessedit_char_whitelist = z.whitelist;
      for (const lang of ['deu+eng','eng']){
        const out = await Tesseract.recognize(canvas, 'deu+eng', {
        try {
          logger: m => { if(m.status==='recognizing text') setProgress((step + m.progress)/total); }
          const r = await ocrOne(canv, lang);
        , ...opts });
          results.push(r);
         step += 1;
         } catch(e){ /* einzelne Fehlschläge ignorieren */ }
        return out.data?.text || '';
       }
       }
      const t1 = await pass(cropBin);
      const t2 = await pass(cropBase);
      texts.push(t1, t2);
     }
     }
     setProgress(null);
     setProgress(null);
    const full = texts.join('\n');


     results.sort((a,b)=> (b.conf||0)-(a.conf||0));
     // Optionales Debug auf der Seite
     return (results[0]?.text)||'';
    try {
      if (window.ADOS_SCAN_DEBUG) {
        const box = document.getElementById('ados-scan-ocr');
        if (box) box.textContent = full;
      }
     } catch (e) {}
 
    return full;
   }
   }


   // =============================
   // ------------------------------------------------------------
   //   Hinweise aus OCR
   // 5) Hints extrahieren (mit Normalisierung & Fuzzy-Fixes)
   // =============================
   // ------------------------------------------------------------
 
   function extractHints (text) {
   function extractHints (text) {
     const raw = String(text || '').replace(/\s+/g, ' ').trim();
     const raw = String(text || '').replace(/\s+/g, ' ').trim();


// Speziell für "The Tasteful 8 / Heroes of Childhood"
    // Aggressive Normalisierung
if (/TASTEFUL\s*8/i.test(raw)) {
    let norm = raw
  if (!raw.includes('The Tasteful 8')) raw += ' The Tasteful 8';
      .replace(/[“”„‟]/g,'"')
}
      .replace(/[’‘´`]/g,"'")
if (/HEROES\s+OF\s+CHILDHOOD/i.test(raw)) {
      .replace(/[|]/g,'I')
  if (!raw.includes('Heroes of Childhood')) raw += ' Heroes of Childhood';
      .replace(/[\u2010-\u2015]/g,'-')
}
      .replace(/\s+/g,' ')
      .trim();


    // Häufige Fixes
    const fixes = [
      [/T[\s]*A[\s]*S[\s]*T[\s]*E[\s]*F[\s]*U[\s]*L[\s]*8/i, 'The Tasteful 8'],
      [/HEROE?S?\s+OF\s+CHILDHOOD/i, 'Heroes of Childhood'],
      [/IR(E|I)LAND/i, 'Ireland'],
      [/O?LOROSO/i, 'Oloroso'],
      [/PX/i, 'PX'],
      [/1ST\s*FILL/i, '1st Fill'],
      [/\b([12][0-9])\s*(?:Y(?:EARS?)?|YO|JAHRE?)\b/ig, (m,p)=>`${p} Years`],
    ];
    for (const [re, rep] of fixes) norm = norm.replace(re, rep);
    // Tokens, die im Text vorkommen
     const foundNames = [];
     const foundNames = [];
     KNOWN_TOKENS.forEach(t => {
     KNOWN_TOKENS.forEach(t => {
       const re = new RegExp('\\b' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'i');
       const re = new RegExp('\\b' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'i');
       if (re.test(raw)) foundNames.push(t);
       if (re.test(norm)) foundNames.push(t);
     });
     });


    // Serien
    if (/The Tasteful 8/i.test(norm) && !foundNames.includes('The Tasteful 8')) foundNames.push('The Tasteful 8');
    if (/Heroes of Childhood/i.test(norm) && !foundNames.includes('Heroes of Childhood')) foundNames.push('Heroes of Childhood');
    if (/Ireland/i.test(norm) && !foundNames.includes('Ireland')) foundNames.push('Ireland');
    // Alter
     const ages = [];
     const ages = [];
    let m;
     const ageRe = /\b([1-9]\d?)\s?(?:years?|yo|jahr(?:e)?)\b/gi;
     const ageRe = /\b([1-9]\d?)\s?(?:years?|yo|jahr(?:e)?)\b/gi;
    let m;
     while ((m = ageRe.exec(norm)) !== null) { const n = m[1]; if (!ages.includes(n)) ages.push(n); }
     while ((m = ageRe.exec(raw)) !== null) {
      const n = m[1]; if (!ages.includes(n)) ages.push(n);
    }


    // Jahrgänge
     const years = [];
     const years = [];
     const yearRe = /\b(19|20)\d{2}\b/g;
     const yearRe = /\b(19|20)\d{2}\b/g;
     while ((m = yearRe.exec(raw)) !== null) {
     while ((m = yearRe.exec(norm)) !== null) { if (!years.includes(m[0])) years.push(m[0]); }
      if (!years.includes(m[0])) years.push(m[0]);
    }


    // ein paar markante Wörter
     const wordRe = /\b[A-ZÄÖÜ][A-Za-zÄÖÜäöüß\-]{3,}\b/g;
     const wordRe = /\b[A-ZÄÖÜ][A-Za-zÄÖÜäöüß\-]{3,}\b/g;
     const uniq = new Set(); let w; const words = [];
     const uniq = new Set(); let w; const words = [];
     while ((w = wordRe.exec(raw)) !== null) {
     while ((w = wordRe.exec(norm)) !== null) {
       const s = w[0];
       const s = w[0];
       if (!uniq.has(s)) { uniq.add(s); words.push(s); if (words.length >= 8) break; }
       if (!uniq.has(s)) { uniq.add(s); words.push(s); if (words.length >= 8) break; }
     }
     }


     return { names: foundNames, ages, years, words, raw };
     return { names: foundNames, ages, years, words, raw: norm };
  }
 
  // =============================
  //  Suche (3 Pässe) + Fallbacks
  // =============================
 
  function esc (s) { return mw.html.escape(String(s || '')); }
 
  function incatStr () {
    return (ADOS_CATEGORIES || []).map(c => 'incategory:"' + c + '"').join(' ');
   }
   }


  // ------------------------------------------------------------
  // 6) Suche im Wiki (3 Pässe)
  // ------------------------------------------------------------
   async function searchWikiSmart (hints, limit) {
   async function searchWikiSmart (hints, limit) {
     await mw.loader.using(['mediawiki.api','mediawiki.util','mediawiki.html']);
     await mw.loader.using('mediawiki.api');
     const api = new mw.Api();
     const api = new mw.Api();
     const ns0 = 0;
     const ns0 = 0;
     const MAX = limit || 12;
     const MAX = limit || 12;


     // PASS 1: intitle-Kombis (präzise)
     function incatStr () {
      return ADOS_CATEGORIES.map(c => 'incategory:"' + c + '"').join(' ');
    }
 
     const pass1 = [];
     const pass1 = [];
     if (hints.names.length) {
     if (hints.names.length) {
Zeile 302: Zeile 296:
     }
     }


    // PASS 2: gewichtete Volltextsuche
     const key = []
     const key = []
       .concat(hints.names.slice(0, 2), hints.ages.slice(0, 1), hints.years.slice(0, 1), hints.words.slice(0, 3))
       .concat(hints.names.slice(0, 2), hints.ages.slice(0, 1), hints.years.slice(0, 1), hints.words.slice(0, 3))
Zeile 308: Zeile 301:
     const pass2 = key ? [ `${key} ${incatStr()}` ] : [];
     const pass2 = key ? [ `${key} ${incatStr()}` ] : [];


    // PASS 3: Prefix auf Titel
     const pass3 = [];
     const pass3 = [];
     if (hints.names.length) pass3.push(hints.names[0]);
     if (hints.names.length) pass3.push(hints.names[0]);
Zeile 328: Zeile 320:
     for (const q of pass2) { await runSr(q); if (out.length >= MAX) return out.slice(0, MAX); }
     for (const q of pass2) { await runSr(q); if (out.length >= MAX) return out.slice(0, MAX); }


    // Prefix (list=prefixsearch)
     for (const p of pass3) {
     for (const p of pass3) {
       const r = await api.get({ action: 'query', list: 'prefixsearch', pssearch: p, psnamespace: ns0, pslimit: MAX });
       const r = await api.get({ action: 'query', list: 'prefixsearch', pssearch: p, psnamespace: ns0, pslimit: MAX });
Zeile 344: Zeile 335:
   }
   }


   // ganz einfacher Fuzzy-Fallback auf Suchergebnissen
   // ------------------------------------------------------------
  function scoreTitle(title, hints){
   // 7) Treffer rendern
    const t = String(title||'').toLowerCase();
   // ------------------------------------------------------------
    let s = 0;
    hints.names.forEach(n => { if (t.includes(n.toLowerCase())) s += 1.0; });
    hints.words.forEach(n => { if (t.includes(n.toLowerCase())) s += 0.4; });
    hints.ages.forEach(a => { if (t.includes(String(a))) s += 0.4; });
    hints.years.forEach(y => { if (t.includes(String(y))) s += 0.4; });
    return s;
  }
 
  async function fallbackFuzzyTitles(hints, limit){
    await mw.loader.using('mediawiki.api');
    const api = new mw.Api();
    const MAX = limit || 12;
 
    // Breite Suche mit Tokens (mit/ohne Kategorie)
    const q1 = []
      .concat(hints.names.slice(0,2), hints.ages.slice(0,1), hints.years.slice(0,1), hints.words.slice(0,3))
      .map(x => `"${x}"`).join(' ');
    const q = `${q1} ${incatStr()}`.trim();
 
    const r = await api.get({ action:'query', list:'search', srsearch:q || hints.raw.split(/\s+/).slice(0,6).join(' '), srlimit:50, formatversion:2 });
    const items = (r.query?.search || []);
    const scored = items.map(it => ({ ...it, _score: scoreTitle(it.title, hints) }));
    scored.sort((a,b)=> b._score - a._score);
    const top = scored.slice(0, MAX).filter(x=> x._score >= 0.10); // großzügiger
    return top;
  }
 
   async function broadSearchNoCategory(hints, limit){
    await mw.loader.using('mediawiki.api');
    const api = new mw.Api();
    const MAX = limit || 12;
 
    const parts = []
      .concat(hints.names.slice(0,2), hints.ages.slice(0,1), hints.years.slice(0,1), hints.words.slice(0,3))
      .map(x => `"${x}"`);
    const q = parts.length ? parts.join(' ') : hints.raw.split(/\s+/).slice(0,6).join(' ');
 
    const r = await api.get({ action:'query', list:'search', srsearch:q, srlimit:MAX, formatversion:2 });
    return (r.query?.search || []);
  }
 
  // =============================
  //  Ergebnisse rendern
   // =============================
 
   function renderResults (items) {
   function renderResults (items) {
     var box = document.getElementById('ados-scan-results');
     var box = document.getElementById('ados-scan-results');
Zeile 413: Zeile 359:
   }
   }


   // =============================
   // ------------------------------------------------------------
   //   Binding
   // 8) Bindings (Buttons, Dropzone, Fallbacks)
   // =============================
   // ------------------------------------------------------------
 
   var BOUND = false;
   var BOUND = false;
   function bind () {
   function bind () {
     if (BOUND || !hasUI()) return;
     if (BOUND || !hasUI()) return;
     var runBtn = document.getElementById('ados-scan-run');
     var runBtn = document.getElementById('ados-scan-run');
     var fileIn = document.getElementById('ados-scan-file');
     var fileIn = document.getElementById('ados-scan-file');
     var bigBtn = document.getElementById('ados-scan-bigbtn');
     var bigBtn = document.getElementById('ados-scan-bigbtn');
     var form = document.getElementById('ados-scan-form');
     var drop  = document.getElementById('ados-scan-drop');


     if (!runBtn || !fileIn) return;
     if (!runBtn || !fileIn) return;
Zeile 435: Zeile 379:
     });
     });


     function onSubmit(ev){
     // Drag&Drop
    if (drop) {
      ['dragenter','dragover'].forEach(ev =>
        drop.addEventListener(ev, e => { e.preventDefault(); drop.classList.add('is-over'); }));
      ['dragleave','drop'].forEach(ev =>
        drop.addEventListener(ev, e => { e.preventDefault(); drop.classList.remove('is-over'); }));
      drop.addEventListener('drop', e => {
        const f = e.dataTransfer?.files?.[0];
        if (f) { fileIn.files = e.dataTransfer.files; showPreview(f); }
      });
    }
 
    runBtn.addEventListener('click', async function (ev) {
       ev.preventDefault();
       ev.preventDefault();
       if (!(fileIn.files && fileIn.files[0])) { alert('Bitte ein Foto auswählen oder aufnehmen.'); return; }
       if (!(fileIn.files && fileIn.files[0])) { alert('Bitte ein Foto auswählen oder aufnehmen.'); return; }
       var f = fileIn.files[0];
       var f = fileIn.files[0];
       (async function(){
       try {
         try {
         runBtn.disabled = true; runBtn.textContent = 'Erkenne …';
          runBtn.disabled = true; runBtn.textContent = 'Erkenne …';
        setStatus('Erkenne Label …');
          setStatus('Erkenne Label …');
        var text = await runOCR(f);
          const text = await runOCR(f);
        if (window.ADOS_SCAN_DEBUG) {
          showOCRText(text);
           const dbg = document.getElementById('ados-scan-ocr');
 
           if (dbg) dbg.textContent = text;
          setStatus('Suche im Wiki …');
          const hints = extractHints(text);
 
          let hits = await searchWikiSmart(hints, 12);
          if (!hits || !hits.length) {
            setStatus('Kein direkter Treffer – Fuzzy über Kategorien …');
            hits = await fallbackFuzzyTitles(hints, 12);
           }
          if (!hits || !hits.length) {
            setStatus('Kein Treffer – breite Suche ohne Kategorien …');
            hits = await broadSearchNoCategory(hints, 12);
          }
 
          renderResults(hits);
          setStatus('Fertig.');
        } catch (e) {
          console.error('[LabelScan]', e);
           setStatus('Fehler bei Erkennung/Suche. Bitte erneut versuchen.');
        } finally {
          runBtn.disabled = false; runBtn.textContent = 'Erkennen & suchen';
         }
         }
       })();
        setStatus('Suche im Wiki …');
     }
        var hints = extractHints(text);
        var hits = await searchWikiSmart(hints, 12);
        renderResults(hits);
        setStatus('Fertig.');
       } catch (e) {
        console.error('[LabelScan]', e);
        setStatus('Fehler bei Erkennung/Suche. Bitte erneut versuchen.');
      } finally {
        runBtn.disabled = false; runBtn.textContent = '🔍 Erkennen & suchen';
      }
     });


    runBtn.addEventListener('click', onSubmit);
     // Sicherheit gegen Overlays
    if (form) form.addEventListener('submit', onSubmit);
 
     // Sicherheit
     var wrap = document.getElementById('ados-labelscan');
     var wrap = document.getElementById('ados-labelscan');
     if (wrap) wrap.style.position = 'relative';
     if (wrap) wrap.style.position = 'relative';
Zeile 481: Zeile 424:
   }
   }


  // initial & Fallback-Bindings
   if (document.readyState === 'loading') {
   if (document.readyState === 'loading') {
     document.addEventListener('DOMContentLoaded', bind);
     document.addEventListener('DOMContentLoaded', bind);
Zeile 490: Zeile 434:
   var mo = new MutationObserver(function () { if (!BOUND) bind(); });
   var mo = new MutationObserver(function () { if (!BOUND) bind(); });
   mo.observe(document.documentElement || document.body, { childList: true, subtree: true });
   mo.observe(document.documentElement || document.body, { childList: true, subtree: true });
})();
})();