Update run.py
Browse files
run.py
CHANGED
|
@@ -1,19 +1,12 @@
|
|
| 1 |
-
from flask import Flask
|
| 2 |
from flask_cors import CORS, cross_origin
|
| 3 |
-
from flask import request
|
| 4 |
-
from flask import jsonify
|
| 5 |
-
|
| 6 |
import os
|
| 7 |
import numpy as np
|
| 8 |
-
import matplotlib.pyplot as plt
|
| 9 |
-
|
| 10 |
-
from pathlib import Path
|
| 11 |
-
from collections import Counter
|
| 12 |
-
|
| 13 |
import tensorflow as tf
|
| 14 |
from tensorflow import keras
|
| 15 |
from tensorflow.keras import layers
|
| 16 |
import time
|
|
|
|
| 17 |
# Khởi tạo Flask Server Backend
|
| 18 |
app = Flask(__name__)
|
| 19 |
# Apply Flask CORS
|
|
@@ -26,77 +19,67 @@ batch_size = 16
|
|
| 26 |
img_width = 145
|
| 27 |
img_height = 50
|
| 28 |
downsample_factor = 4
|
| 29 |
-
|
| 30 |
max_length = 15
|
|
|
|
| 31 |
char_to_num = layers.StringLookup(vocabulary=list(characters), mask_token=None)
|
| 32 |
num_to_char = layers.StringLookup(
|
| 33 |
vocabulary=char_to_num.get_vocabulary(), mask_token=None, invert=True
|
| 34 |
)
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
class CTCLayer(layers.Layer):
|
| 43 |
-
def __init__(self, name=None):
|
| 44 |
-
super().__init__(name=name)
|
| 45 |
self.loss_fn = keras.backend.ctc_batch_cost
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
model = keras.models.load_model("model_bidv.h5", custom_objects={"CTCLayer": CTCLayer})
|
| 52 |
-
# Get the prediction model by extracting layers till the output layer
|
| 53 |
prediction_model = keras.models.Model(
|
| 54 |
model.get_layer(name="image").input, model.get_layer(name="dense2").output
|
| 55 |
)
|
| 56 |
|
| 57 |
# Đọc ảnh base64 và mã hóa
|
| 58 |
-
def encode_base64x(
|
| 59 |
-
img = tf.io.decode_base64(
|
| 60 |
img = tf.io.decode_png(img, channels=1)
|
| 61 |
img = tf.image.convert_image_dtype(img, tf.float32)
|
| 62 |
img = tf.image.resize(img, [img_height, img_width])
|
| 63 |
img = tf.transpose(img, perm=[1, 0, 2])
|
| 64 |
return {"image": img}
|
| 65 |
-
|
|
|
|
| 66 |
def decode_batch_predictions(pred):
|
| 67 |
input_len = np.ones(pred.shape[0]) * pred.shape[1]
|
| 68 |
-
# Use greedy search. For complex tasks, you can use beam search
|
| 69 |
results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][
|
| 70 |
:, :max_length
|
| 71 |
]
|
| 72 |
-
# Iterate over the results and get back the text
|
| 73 |
output_text = []
|
| 74 |
for res in results:
|
| 75 |
res = tf.strings.reduce_join(num_to_char(res)).numpy().decode("utf-8")
|
| 76 |
output_text.append(res)
|
| 77 |
return output_text
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
# hàm để truy cập: 127.0.0.1/run -> 127.0.0.1 là ip server
|
| 84 |
-
@app.route("/api/captcha/bidv", methods=["POST"])
|
| 85 |
@cross_origin(origin='*')
|
| 86 |
-
def
|
| 87 |
content = request.json
|
| 88 |
-
|
| 89 |
-
imgstring = content
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
listImage = np.array([image_encode])
|
| 92 |
preds = prediction_model.predict(listImage)
|
| 93 |
pred_texts = decode_batch_predictions(preds)
|
| 94 |
captcha = pred_texts[0].replace('[UNK]', '').replace('-', '')
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
return response
|
| 98 |
-
|
| 99 |
|
| 100 |
-
#
|
| 101 |
if __name__ == '__main__':
|
| 102 |
-
app.run(host='0.0.0.0', port=
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
from flask_cors import CORS, cross_origin
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import tensorflow as tf
|
| 6 |
from tensorflow import keras
|
| 7 |
from tensorflow.keras import layers
|
| 8 |
import time
|
| 9 |
+
|
| 10 |
# Khởi tạo Flask Server Backend
|
| 11 |
app = Flask(__name__)
|
| 12 |
# Apply Flask CORS
|
|
|
|
| 19 |
img_width = 145
|
| 20 |
img_height = 50
|
| 21 |
downsample_factor = 4
|
|
|
|
| 22 |
max_length = 15
|
| 23 |
+
|
| 24 |
char_to_num = layers.StringLookup(vocabulary=list(characters), mask_token=None)
|
| 25 |
num_to_char = layers.StringLookup(
|
| 26 |
vocabulary=char_to_num.get_vocabulary(), mask_token=None, invert=True
|
| 27 |
)
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
class CTCLayer(layers.Layer):
|
| 30 |
+
def __init__(self, name=None, **kwargs):
|
| 31 |
+
super().__init__(name=name, **kwargs)
|
| 32 |
self.loss_fn = keras.backend.ctc_batch_cost
|
| 33 |
|
| 34 |
+
# Load model (Đảm bảo file model_bidv.h5 đã được upload cùng thư mục với file app.py)
|
|
|
|
|
|
|
|
|
|
| 35 |
model = keras.models.load_model("model_bidv.h5", custom_objects={"CTCLayer": CTCLayer})
|
|
|
|
| 36 |
prediction_model = keras.models.Model(
|
| 37 |
model.get_layer(name="image").input, model.get_layer(name="dense2").output
|
| 38 |
)
|
| 39 |
|
| 40 |
# Đọc ảnh base64 và mã hóa
|
| 41 |
+
def encode_base64x(base64_str):
|
| 42 |
+
img = tf.io.decode_base64(base64_str)
|
| 43 |
img = tf.io.decode_png(img, channels=1)
|
| 44 |
img = tf.image.convert_image_dtype(img, tf.float32)
|
| 45 |
img = tf.image.resize(img, [img_height, img_width])
|
| 46 |
img = tf.transpose(img, perm=[1, 0, 2])
|
| 47 |
return {"image": img}
|
| 48 |
+
|
| 49 |
+
# Giải mã kết quả AI dự đoán
|
| 50 |
def decode_batch_predictions(pred):
|
| 51 |
input_len = np.ones(pred.shape[0]) * pred.shape[1]
|
|
|
|
| 52 |
results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][
|
| 53 |
:, :max_length
|
| 54 |
]
|
|
|
|
| 55 |
output_text = []
|
| 56 |
for res in results:
|
| 57 |
res = tf.strings.reduce_join(num_to_char(res)).numpy().decode("utf-8")
|
| 58 |
output_text.append(res)
|
| 59 |
return output_text
|
| 60 |
|
| 61 |
+
# Sửa lại Route đồng bộ với link Hugging Face của bạn
|
| 62 |
+
@app.route("/vanducdev/captcha/vcb", methods=["POST"])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
@cross_origin(origin='*')
|
| 64 |
+
def vcb_captcha():
|
| 65 |
content = request.json
|
| 66 |
+
# Chấp nhận cả key 'image' hoặc 'base64' để tránh lỗi bên gọi gửi sai key
|
| 67 |
+
imgstring = content.get('image') or content.get('base64')
|
| 68 |
+
|
| 69 |
+
if not imgstring:
|
| 70 |
+
return jsonify(status="error", message="Missing image/base64 data"), 400
|
| 71 |
+
|
| 72 |
+
# Xử lý chuẩn hóa chuỗi base64 cho hàm decode_base64 của tensorflow
|
| 73 |
+
imgstring = imgstring.replace("+", "-").replace("/", "_")
|
| 74 |
+
|
| 75 |
+
image_encode = encode_base64x(imgstring)["image"]
|
| 76 |
listImage = np.array([image_encode])
|
| 77 |
preds = prediction_model.predict(listImage)
|
| 78 |
pred_texts = decode_batch_predictions(preds)
|
| 79 |
captcha = pred_texts[0].replace('[UNK]', '').replace('-', '')
|
| 80 |
+
|
| 81 |
+
return jsonify(status="success", captcha=captcha)
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
# BẮT BUỘC CHẠY CỔNG 7860 TRÊN HUGGING FACE
|
| 84 |
if __name__ == '__main__':
|
| 85 |
+
app.run(host='0.0.0.0', port=7860)
|