#!/usr/bin/env python3
"""Demo 3 — el yazım yok: bilgisayardaki yazı tipleriyle ve çizgi çizen bir programla üretilmiş rakamları
eğittiğim LeNet-5'e (demo/lenet5.pt) okutmak.

A) Yazı tipleri: `fc-list ':charset=30-39'` ile 0-9 içeren tüm yazı tipi dosyaları. Her rakam büyük çizilir,
   MNIST'teki gibi ön işlenir (kutuya kırp, en-boy oranını koruyarak 20x20'ye sığdır, kütle merkezini 28x28'in
   ortasına koy). Aynı piksel çıktısını veren yazı tipleri tekilleştirilir (Noto ailesinin çoğu aynı rakamları paylaşır).
   Karşılaştırma: aynı rakamlar ÖN İŞLEMESİZ (siyah zeminde beyaz değil, beyaz zeminde siyah ve kutuyu dolduran) — ters renk ve
   yanlış ölçek ağın neyi beklediğini gösterir.
B) Çizgi programı: her rakam için elle tanımladığım kalem yolları (çizgi + yay), rastgele eğim/ölçek/titreme ve kalınlıkla
   çizilir; 10 rakam x 100 örnek; sabit tohum.
Çıktı: demo/rakam-testi.json, demo/rakam-ornekler.npz
"""
import hashlib, json, math, os, subprocess, sys
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont

H = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, H)
from lenet_mnist import LeNet5, MEAN, STD  # noqa: E402

dev = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = LeNet5().to(dev); model.load_state_dict(torch.load(os.path.join(H, 'lenet5.pt'), map_location=dev)); model.eval()


def mnistify(im):
    """im: 'L' görüntü, beyaz mürekkep siyah zemin. MNIST ön işleme: 20x20 kutu + kütle merkezi ortada."""
    a = np.asarray(im, np.float32)
    ys, xs = np.nonzero(a > 10)
    if len(xs) == 0:
        return np.zeros((28, 28), np.uint8)
    a = a[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
    h, w = a.shape; s = 20.0 / max(h, w)
    nh, nw = max(1, round(h * s)), max(1, round(w * s))
    a = np.asarray(Image.fromarray(a.astype(np.uint8)).resize((nw, nh), Image.LANCZOS), np.float32)
    out = np.zeros((28, 28), np.float32)  # float 'F' görüntü olarak kaydırılacak
    y0, x0 = (28 - nh) // 2, (28 - nw) // 2
    out[y0:y0 + nh, x0:x0 + nw] = a
    yy, xx = np.mgrid[0:28, 0:28]; m = out.sum()
    cy, cx = (yy * out).sum() / m, (xx * out).sum() / m  # kütle merkezi (piksel merkezleri)
    dx, dy = 13.5 - cx, 13.5 - cy
    im2 = Image.fromarray(out).transform((28, 28), Image.AFFINE, (1, 0, -dx, 0, 1, -dy), resample=Image.BILINEAR)
    return np.clip(np.asarray(im2), 0, 255).astype(np.uint8)


def naive(ch, font):
    """Ön işlemesiz: beyaz zemin, siyah rakam, 28x28'i dolduracak boyutta (bir belgeden doğrudan kesilmiş gibi)."""
    im = Image.new('L', (28, 28), 255); d = ImageDraw.Draw(im)
    f = ImageFont.truetype(font, 26)
    d.text((14, 14), ch, font=f, fill=0, anchor='mm')
    return np.asarray(im, np.uint8)


def predict(batch):
    x = torch.tensor(np.stack(batch), dtype=torch.float32, device=dev).unsqueeze(1) / 255.0
    x = (x - MEAN) / STD
    with torch.no_grad():
        p = torch.softmax(model(x), 1).cpu().numpy()
    return p.argmax(1), p.max(1), p


def render_font(ch, font):
    f = ImageFont.truetype(font, 160)
    im = Image.new('L', (260, 260), 0); d = ImageDraw.Draw(im)
    d.text((130, 130), ch, font=f, fill=255, anchor='mm')
    return mnistify(im)


# ---------------- A) yazı tipleri ----------------
files = subprocess.run(['fc-list', ':charset=30-39', '--format', '%{file}|%{family[0]}|%{style[0]}\n'],
                       capture_output=True, text=True).stdout.strip().splitlines()
fonts = sorted({tuple(l.split('|')[:3]) for l in files if l.split('|')[0].lower().endswith(('.ttf', '.otf', '.ttc'))})
# D050000L (URW Dingbats) fc-list'e göre 0-9 kodlarını içeriyor ama o kodlarda kalem, onay işareti, çarpı gibi semboller var:
# rakam değil, testten çıkarıldı (kontakt sayfasında gözle görüldü).
HARIC = {'D050000L': 'Dingbats: 0-9 kodlarında rakam yerine semboller'}
seen, uniq, failed = {}, [], []
for path, fam, sty in fonts:
    if fam in HARIC:
        failed.append({'dosya': path, 'hata': 'hariç: ' + HARIC[fam]}); continue
    try:
        glyphs = [render_font(str(k), path) for k in range(10)]
    except Exception as e:  # bazı .ttc/renkli yazı tipleri PIL'de açılmıyor
        failed.append({'dosya': path, 'hata': str(e)[:120]}); continue
    if any(g.max() == 0 for g in glyphs):
        failed.append({'dosya': path, 'hata': 'boş glif'}); continue
    key = hashlib.md5(np.stack(glyphs).tobytes()).hexdigest()
    if key in seen:
        seen[key]['ayni_cizim'].append(fam + ' ' + sty); continue
    rec = {'aile': fam, 'stil': sty, 'dosya': path, 'ayni_cizim': [], 'glyphs': glyphs}
    seen[key] = rec; uniq.append(rec)

allg = [g for r in uniq for g in r['glyphs']]
pred, conf, _ = predict(allg)
rows = []
for i, r in enumerate(uniq):
    p = pred[i * 10:(i + 1) * 10]; c = conf[i * 10:(i + 1) * 10]
    r['tahmin'] = p.tolist(); r['guven'] = np.round(c, 3).tolist(); r['dogru'] = int((p == np.arange(10)).sum())
font_ok = int((pred == np.tile(np.arange(10), len(uniq))).sum())
per_digit_font = [int((pred.reshape(-1, 10)[:, k] == k).sum()) for k in range(10)]
font_wrong = [{'aile': uniq[i // 10]['aile'], 'stil': uniq[i // 10]['stil'], 'dogru': i % 10, 'tahmin': int(pred[i]), 'guven': round(float(conf[i]), 3)}
              for i in range(len(pred)) if pred[i] != i % 10]
font_wrong.sort(key=lambda w: -w['guven'])

# ön işlemesiz karşılaştırma (aynı tekil yazı tipleri)
nv = [naive(str(k), r['dosya']) for r in uniq for k in range(10)]
npred, nconf, _ = predict(nv)
naive_ok = int((npred == np.tile(np.arange(10), len(uniq))).sum())
naive_hist = np.bincount(npred, minlength=10).tolist()
# yalnız renk ters çevrilmiş (beyaz zemin) ama ölçek doğru
inv = [255 - g for g in allg]
ipred, _, _ = predict(inv)
inv_ok = int((ipred == np.tile(np.arange(10), len(uniq))).sum())

# ---------------- B) çizgi çizen program ----------------
# Yollar 0..1 kutusunda (x sağa, y aşağı). 'L' = çizgi noktaları, 'A' = yay (cx, cy, rx, ry, başlangıç°, bitiş°)
STROKES = {
    0: [('A', .5, .5, .30, .42, 0, 360)],
    1: [('L', [(.35, .25), (.55, .08), (.55, .92)])],
    2: [('A', .5, .32, .28, .24, 200, 380), ('L', [(.78, .34), (.22, .92), (.82, .92)])],
    3: [('A', .48, .29, .26, .21, 210, 450), ('A', .48, .70, .30, .23, 270, 520)],
    4: [('L', [(.62, .92), (.62, .08), (.18, .66), (.86, .66)])],
    5: [('L', [(.78, .08), (.30, .08), (.26, .45)]), ('A', .50, .66, .30, .26, 220, 500)],
    6: [('L', [(.72, .10), (.32, .52)]), ('A', .50, .68, .27, .24, 0, 360)],
    7: [('L', [(.18, .10), (.84, .10), (.40, .92)])],
    8: [('A', .5, .28, .23, .20, 0, 360), ('A', .5, .70, .29, .23, 0, 360)],
    9: [('A', .50, .32, .27, .24, 0, 360), ('L', [(.76, .36), (.62, .92)])],
}


def draw_digit(k, rng, S=112):
    im = Image.new('L', (S, S), 0); d = ImageDraw.Draw(im)
    slant = rng.uniform(-0.25, 0.25); sx = rng.uniform(0.8, 1.15); sy = rng.uniform(0.85, 1.1); rot = math.radians(rng.uniform(-10, 10))
    w = int(rng.uniform(6, 14))
    def T(x, y):
        x, y = (x - .5) * sx, (y - .5) * sy
        x = x - slant * y
        x, y = x * math.cos(rot) - y * math.sin(rot), x * math.sin(rot) + y * math.cos(rot)
        j = 0.025
        return ((x + .5 + rng.normal(0, j)) * S * 0.8 + S * 0.1, (y + .5 + rng.normal(0, j)) * S * 0.8 + S * 0.1)
    for st in STROKES[k]:
        if st[0] == 'L':
            pts = [T(*p) for p in st[1]]
        else:
            _, cx, cy, rx, ry, a0, a1 = st
            n = 40; jr = rng.normal(0, 0.02, 2)
            pts = [T(cx + (rx + jr[0]) * math.cos(math.radians(a0 + (a1 - a0) * t / n)), cy + (ry + jr[1]) * math.sin(math.radians(a0 + (a1 - a0) * t / n))) for t in range(n + 1)]
        d.line(pts, fill=255, width=w, joint='curve')
        for p in (pts[0], pts[-1]):
            d.ellipse([p[0] - w / 2, p[1] - w / 2, p[0] + w / 2, p[1] + w / 2], fill=255)
    return mnistify(im)


rng = np.random.default_rng(2026)
strokes = [(k, draw_digit(k, rng)) for k in range(10) for _ in range(100)]
spred, sconf, _ = predict([g for _, g in strokes])
slab = np.array([k for k, _ in strokes])
stroke_ok = int((spred == slab).sum())
per_digit_stroke = [int(((spred == slab) & (slab == k)).sum()) for k in range(10)]
scm = np.zeros((10, 10), int)
for a, b in zip(slab, spred):
    scm[a, b] += 1

# C) ek deney: 1'in tepesindeki şapkayı kaldırınca ne oluyor? (yalnız düz çubuk, ayrı tohum)
STROKES[1] = [('L', [(.55, .08), (.55, .92)])]
rng1 = np.random.default_rng(2027)
ones = [draw_digit(1, rng1) for _ in range(100)]
opred, _, _ = predict(ones)
ones_ok = int((opred == 1).sum()); ones_hist = np.bincount(opred, minlength=10).tolist()

np.savez_compressed(os.path.join(H, 'rakam-ornekler.npz'), ones_bar=np.stack(ones), ones_bar_pred=opred, font=np.stack(allg), font_pred=pred, naive=np.stack(nv), naive_pred=npred,
                    stroke=np.stack([g for _, g in strokes]), stroke_lab=slab, stroke_pred=spred, stroke_conf=sconf)
res = {
    'aciklama': 'LeNet-5 (demo/lenet5.pt, MNIST ile eğitilmiş) · bilgisayardaki yazı tipleri + çizgi programı rakamları',
    'yazi_tipi': {'fc_list_dosya': len(fonts), 'acilamayan': failed, 'tekil_cizim': len(uniq), 'ornek': 10 * len(uniq),
                  'dogru': font_ok, 'dogruluk': round(font_ok / (10 * len(uniq)), 4), 'rakam_bazinda_dogru': per_digit_font,
                  'yanlislar': font_wrong,
                  'aileler': [{k: v for k, v in r.items() if k != 'glyphs'} for r in uniq]},
    'on_islemesiz': {'aciklama': 'aynı yazı tipleri, beyaz zemin siyah rakam, 28x28 kutuyu dolduran, MNIST ön işlemesi yok',
                     'dogru': naive_ok, 'dogruluk': round(naive_ok / (10 * len(uniq)), 4), 'tahmin_dagilimi': naive_hist},
    'yalniz_renk_ters': {'aciklama': 'MNIST ön işlemeli rakamlar, yalnız renkleri ters (beyaz zemin)', 'dogru': inv_ok,
                         'dogruluk': round(inv_ok / (10 * len(uniq)), 4)},
    'cizgi_programi': {'ornek': len(strokes), 'tohum': 2026, 'dogru': stroke_ok, 'dogruluk': round(stroke_ok / len(strokes), 4),
                       'rakam_bazinda_dogru_100de': per_digit_stroke, 'karisiklik': scm.tolist()},
    'ek_bir_duz_cubuk': {'aciklama': "çizgi programında 1'in şapkası kaldırıldı (yalnız dikey çubuk), 100 örnek, tohum 2027",
                         'dogru': ones_ok, 'tahmin_dagilimi': ones_hist},
}
json.dump(res, open(os.path.join(H, 'rakam-testi.json'), 'w'), ensure_ascii=False, indent=1)
print('yazı tipi dosyası', len(fonts), 'tekil', len(uniq), 'doğru', font_ok, '/', 10 * len(uniq), per_digit_font)
print('ön işlemesiz', naive_ok, naive_hist, '| yalnız ters renk', inv_ok)
print('çizgi', stroke_ok, '/', len(strokes), per_digit_stroke)
print('düz 1', ones_ok, ones_hist)
print('en emin yanlışlar', font_wrong[:8])
