un-captcha / app.py
DarkyMan's picture
Update app.py
32c9571
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from huggingface_hub import from_pretrained_keras
import numpy as np
import gradio as gr
max_length = 6
img_width = 181
img_height = 49
model = from_pretrained_keras("DarkyMan/un-captcha", compile=False)
prediction_model = keras.models.Model(
model.get_layer(name="image").input, model.get_layer(name="dense2").output
)
with open("vocab.txt", "r") as f:
vocab = f.read().splitlines()
num_to_char = layers.StringLookup(
vocabulary=vocab, mask_token=None, invert=True
)
def decode_batch_predictions(pred):
input_len = np.ones(pred.shape[0]) * pred.shape[1]
results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][
:, :max_length
]
output_text = []
for res in results:
res = tf.strings.reduce_join(num_to_char(res)).numpy().decode("utf-8")
output_text.append(res)
return output_text
def classify_image(img_path):
img = tf.io.read_file(img_path)
img = tf.io.decode_png(img, channels=1)
img = tf.image.convert_image_dtype(img, tf.float32)
img = tf.image.resize(img, [img_height, img_width])
img = tf.transpose(img, perm=[1, 0, 2])
img = tf.expand_dims(img, axis=0)
preds = prediction_model.predict(img)
pred_text = decode_batch_predictions(preds)
return pred_text[0]
image = gr.inputs.Image(type='filepath')
text = gr.outputs.Textbox()
iface = gr.Interface(classify_image,image,text,
title="un-captcha",
description = "Recognizes captcha text (pictures)|РаспознаСт тСкст ΠΊΠ°ΠΏΡ‡ΠΈ (ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ)",
article = "Π‘ΡŽΠ΄Ρ‹: https://huggingface.co/DarkyMan/",
examples = ["dd764.png","3p4nn.png"]
)
iface.launch()