# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# %matplotlib inline
import matplotlib.pyplot as plt

# +
from flask import Flask, render_template, request, jsonify, redirect
import base64
import numpy as np
import pickle as pkl
import cv2
import os
from predict import predict_digit
app = Flask(__name__)
stats = None
img4 = None

if not os.path.exists('stats/stats.pkl'):
    stats = { 'yes':0, 'no':0 }
    with open('stats/stats.pkl', 'wb') as fp:
        pkl.dump(stats,fp)


@app.route('/')
def home():
    acc = '100'
    with open('stats/stats.pkl', 'rb') as fp:
        global stats;
        stats = pkl.load(fp)
        total = sum(stats.values())
        if total!=0: acc = f"{ 100*stats['yes']/total:.2f} ({stats['yes']}/{total})"
    return render_template('index.html',data = {'status':False, 'accuracy':acc} ) 

@app.route('/charrecognize', methods = ['POST'])
def predict():
    global img4;
    if request.method == 'POST':
        data = request.get_json()
        imagebase64 = data['image']
        binary = base64.b64decode(imagebase64)
        img = np.asarray(bytearray(binary), dtype="uint8")
        img = cv2.imdecode(img, 0)
        
        canny = cv2.Canny( cv2.blur(img, (3,3)), 100, 250)
        contours, _ = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE )
        idx = np.argmax( list( map( cv2.contourArea, contours ) ) )
        x,y,w,h = cv2.boundingRect(contours[idx])
        img = 255-img[ y:y+h, x:x+w ]
        img4 = img
        img = (cv2.resize(img, (20, 20))>127)*1
        final = np.zeros( (28,28) )
        final[ 4:24,4:24 ] = img
        final = final.reshape(1,28,28,1)
        return jsonify({
            'prediction': predict_digit(final),
            'status': True
        });

@app.route('/no', methods=['get'])
def no():
    with open('stats/stats.pkl', 'wb') as fp:
        stats['no']+=1
        pkl.dump(stats,fp)
    return redirect('/')

@app.route('/yes', methods=['get'])
def yes():
    with open('stats/stats.pkl', 'wb') as fp:
        stats['yes']+=1
        pkl.dump(stats,fp)
    return redirect('/')
        
if __name__=='__main__':
    app.run(host = '0.0.0.0',port = int(3000))
# -

img4.min()

plt.imshow( cv2.resize(img, (20, 20), cmap='gray' )

cv2.boundingRect(img4[1][0])

plt.imshow(img4[0][ 15:15+243,25:25+156 ])



StarcoderdataJupyterScriptsDedupFiltered