Code viewer for World: Character recognition neur...
const PIXELS = 28,
    PIXELSSQUARED = PIXELS * PIXELS,
    NOTRAIN = 6e4,
    NOTEST = 1e4,
    noinput = PIXELSSQUARED,
    nohidden = 24,
    nooutput = 10,
    learningrate = .1;
let do_training = !0;
const TRAINPERSTEP = 30,
    TESTPERSTEP = 5,
    ZOOMFACTOR = 7,
    ZOOMPIXELS = ZOOMFACTOR * PIXELS,
    canvaswidth = 2 * ZOOMPIXELS + 120,
    canvasheight = 3 * ZOOMPIXELS + 102,
    doodlewidth = PIXELS,
    DOODLE_THICK = 15,
    DOODLE_BLUR = 3;
let mnist, nn, canvas, dst, src, hierarchy, contours, img, diffX, diffY, M, doodle, demo, cvOutput = [],
    trainrun = 1,
    train_index = 0,
    testrun = 1,
    test_index = 0,
    total_tests = 0,
    total_correct = 0,
    doodle_exists = !1,
    demo_exists = !1,
    mousedrag = !1;
var train_inputs, test_inputs, demo_inputs, doodle_inputs, thehtml;

function randomWeight() {
    return AB.randomFloatAtoB(-.5, .5)
}
$("#runheaderbox").css({
    "max-height": "95vh"
}), thehtml = "<hr> <h1> 1. Doodle </h1> Top row: Doodle (left) and shrunk (right). <br>  Draw your doodle in top LHS. <button onclick='wipeDoodle();' class='normbutton' >Clear doodle</button> <br> ", AB.msg(thehtml, 1), thehtml = "<hr> <h1> 2. Training </h1> Middle row: Training image magnified (left) and original (right). <br>   <button onclick='do_training = false;' class='normbutton' >Stop training</button> <br> ", AB.msg(thehtml, 3), thehtml = "<h3> Hidden tests </h3> ", AB.msg(thehtml, 5), thehtml = "<hr> <h1> 3. Demo </h1> Bottom row: Test image magnified (left) and  original (right). <br> The network is <i>not</i> trained on any of these images. <br>  <button onclick='makeDemo();' class='normbutton' >Demo test image</button> <br> ", AB.msg(thehtml, 7);
const greenspan = "<span style='font-weight:bold; font-size:x-large; color:darkgreen'> ";

function setup() {
    (canvas = createCanvas(canvaswidth, canvasheight)).position(10, 20), (doodle = createGraphics(ZOOMPIXELS, ZOOMPIXELS)).pixelDensity(1), wipeDoodle(), rect(0, 0, ZOOMPIXELS, ZOOMPIXELS), textSize(16), textAlign(CENTER), text("DRAW A DIGIT", ZOOMPIXELS / 2, ZOOMPIXELS / 2.2), textAlign(CENTER), text("BETWEEN 0-9", ZOOMPIXELS / 2, ZOOMPIXELS / 1.8), rect(0, ZOOMPIXELS + 50, ZOOMPIXELS, ZOOMPIXELS), rect(0, canvasheight - ZOOMPIXELS - 2, ZOOMPIXELS, ZOOMPIXELS), textSize(16), textAlign(CENTER), text("     CLICK     ", 100, canvasheight - ZOOMPIXELS / 1.8), text("'DEMO TEST IMAGE'", 100, canvasheight - ZOOMPIXELS / 2.2), AB.loadingScreen(), $.getScript("/uploads/ke737/opencv_3.3.1.js", function() {
        $.getScript("/uploads/ke737/matrix.js", function() {
            $.getScript("/uploads/ke737/nn.js", function() {
                $.getScript("/uploads/codingtrain/mnist.js", function() {
                    console.log("All JS loaded"), (nn = new NeuralNetwork(noinput, nohidden, nooutput)).setLearningRate(learningrate), loadData()
                })
            })
        })
    })
}

function loadData() {
    loadMNIST(function(t) {
        mnist = t, console.log("All data loaded into mnist object:"), console.log(mnist), AB.removeLoading()
    })
}

function getImage(t) {
    let e = createImage(PIXELS, PIXELS);
    e.loadPixels();
    for (let n = 0; n < PIXELSSQUARED; n++) {
        let o = t[n],
            i = 4 * n;
        e.pixels[i + 0] = o, e.pixels[i + 1] = o, e.pixels[i + 2] = o, e.pixels[i + 3] = 255
    }
    return e.updatePixels(), e
}

function getInputs(t) {
    let e = [];
    for (let n = 0; n < PIXELSSQUARED; n++) {
        let o = t[n];
        e[n] = o / 255
    }
    return e
}

function trainit(t) {
    let e = mnist.train_images[train_index],
        n = mnist.train_labels[train_index];
    if (t) {
        var o = getImage(e);
        image(o, 0, ZOOMPIXELS + 50, ZOOMPIXELS, ZOOMPIXELS), image(o, ZOOMPIXELS + 50, ZOOMPIXELS + 50, PIXELS, PIXELS)
    }
    let i = getInputs(e),
        s = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    s[n] = 1, train_inputs = i, nn.train(i, s), thehtml = " trainrun: " + trainrun + "<br> no: " + train_index, AB.msg(thehtml, 4), ++train_index == NOTRAIN && (train_index = 0, console.log("finished trainrun: " + trainrun), trainrun++)
}

function testit() {
    let t = mnist.test_images[test_index],
        e = mnist.test_labels[test_index],
        n = getInputs(t);
    test_inputs = n;
    let o = findMax(nn.predict(n));
    total_tests++, o == e && total_correct++;
    let i = total_correct / total_tests * 100;
    thehtml = " testrun: " + testrun + "<br> no: " + total_tests + " <br>  correct: " + total_correct + "<br>  score: " + greenspan + i.toFixed(2) + "</span>", AB.msg(thehtml, 6), ++test_index == NOTEST && (console.log("finished testrun: " + testrun + " score: " + i.toFixed(2)), testrun++, test_index = 0, total_tests = 0, total_correct = 0)
}

function find123(t) {
    let e = 0,
        n = 0,
        o = 0,
        i = 0,
        s = 0,
        r = 0;
    for (let a = 0; a < t.length; a++) t[a] > i ? (e = a, i = t[a]) : t[a] > s ? (n = a, s = t[a]) : t[a] > r && (o = a, r = t[a]);
    return [e, n, o]
}

function findMax(t) {
    let e = 0,
        n = 0;
    for (let o = 0; o < t.length; o++) t[o] > n && (e = o, n = t[o]);
    return e
}

function draw() {
    if (void 0 !== mnist) {
        if (rect(0, 0, ZOOMPIXELS, ZOOMPIXELS), textSize(16), textAlign(CENTER), text("DRAW A DIGIT", ZOOMPIXELS / 2, ZOOMPIXELS / 2.2), textAlign(CENTER), text("BETWEEN 0-9", ZOOMPIXELS / 2, ZOOMPIXELS / 1.8), do_training) {
            for (let t = 0; t < TRAINPERSTEP; t++) trainit(0 === t);
            for (let t = 0; t < TESTPERSTEP; t++) testit()
        }
        if (demo_exists && (drawDemo(), guessDemo()), doodle_exists && (drawDoodle(), guessDoodle()), mouseIsPressed) {
            var t = ZOOMPIXELS - 2;
            mouseX < t && mouseY < t && pmouseX < t && pmouseY < t && (mousedrag = !0, doodle_exists = !0, doodle.stroke("cream"), strokeJoin(BEVEL), doodle.strokeWeight(DOODLE_THICK), doodle.line(mouseX, mouseY, pmouseX, pmouseY))
        } else if (mousedrag) {
            mousedrag = !1, console.log("Doodle detected"), (img = doodle.get()).resize(PIXELS, PIXELS), img.loadPixels(), imagedata = img.imageData, src = cv.matFromImageData(imagedata), dst = cv.Mat.zeros(src.cols, src.rows, cv.CV_8UC3), cv.cvtColor(src, src, cv.COLOR_RGBA2GRAY, 0), cv.threshold(src, src, 120, 255, cv.THRESH_BINARY), contours = new cv.MatVector, hierarchy = new cv.Mat, cv.findContours(src, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE);
            let t = contours.get(0),
                e = cv.moments(t, !1);
            M = e.m00;
            let n = Math.round(e.m10 / e.m00 * 100) / 100,
                o = Math.round(e.m01 / e.m00 * 100) / 100,
                i = PIXELS / 2,
                s = PIXELS / 2;
            diffX = Math.round(i - n), diffY = Math.round(s - o);
            let r = cv.matFromArray(2, 3, cv.CV_64FC1, [1, 0, diffX, 0, 1, diffY]);
            return dsize = new cv.Size(src.rows, src.cols), cv.warpAffine(src, dst, r, dsize, cv.INTER_LINEAR, cv.BORDER_CONSTANT, new cv.Scalar), cvOutput = getInputs(dst.data8S), image(img, ZOOMPIXELS + 120 + diffX * ZOOMFACTOR, 0 + diffY * ZOOMFACTOR, ZOOMPIXELS, ZOOMPIXELS), console.log("%c ***** DOODLE CENTERED  ***** ", "background: #222; color: #bada55"), cvOutput
        }
    }
}

function makeDemo() {
    demo_exists = !0;
    var t = AB.randomIntAtoB(0, NOTEST - 1);
    demo = mnist.test_images[t];
    var e = mnist.test_labels[t];
    thehtml = "Test image no: " + t + "<br>Classification: " + e + "<br>", AB.msg(thehtml, 8)
}

function drawDemo() {
    var t = getImage(demo);
    image(t, 0, canvasheight - (ZOOMPIXELS + 2), ZOOMPIXELS, ZOOMPIXELS), image(t, ZOOMPIXELS + 50, canvasheight - ZOOMPIXELS, PIXELS, PIXELS)
}

function guessDemo() {
    let t = getInputs(demo);
    demo_inputs = t;
    let e = findMax(nn.predict(t));
    thehtml = " We classify it as: " + greenspan + e + "</span>", AB.msg(thehtml, 9)
}

function drawDoodle() {
    let t = doodle.get();
    image(t, 0, 0, ZOOMPIXELS, ZOOMPIXELS), image(t, ZOOMPIXELS + 50, 0, PIXELS, PIXELS)
}

function guessDoodle() {
    (img = doodle.get()).resize(PIXELS, PIXELS), img.loadPixels();
    let t = [];
    for (let e = 0; e < PIXELSSQUARED; e++) t[e] = img.pixels[4 * e] / 255;
    let e = Array.from(t);
    for (let t = 0; t < e.length; t++) e[t] = cvOutput[t];
    t = Array.from(e);
    for (let e = 0; e < t.length; e++) t[e] = -255 * t[e];
    doodle_inputs = t;
    let n = find123(nn.predict(t));
    thehtml = " We classify it as: " + greenspan + n[0] + "</span> <br> No.2 guess is: " + greenspan + n[1] + "</span> <br>No.3 guess is: " + greenspan + n[2] + "</span>", AB.msg(thehtml, 2), AB.msg(thehtml, 2)
}

function wipeDoodle() {
    doodle_exists = !1, doodle.background("black")
}

function showInputs(t) {
    var e = "";
    for (let n = 0; n < t.length; n++) {
        n % PIXELS == 0 && (e += "\n"), e = e + " " + t[n].toFixed(2)
    }
    console.log(e)
}