|
import streamlit as st |
|
from PIL import Image |
|
import tensorflow as tf |
|
import numpy as np |
|
import os |
|
from tensorflow.keras.layers import LSTM |
|
from keras.saving import register_keras_serializable |
|
|
|
|
|
@register_keras_serializable() |
|
class CustomLSTM(LSTM): |
|
pass |
|
|
|
|
|
@st.cache_resource |
|
def load_captcha_model(): |
|
model_path = "model1.keras" |
|
return tf.keras.models.load_model(model_path, custom_objects={'CustomLSTM': CustomLSTM}) |
|
|
|
|
|
model = load_captcha_model() |
|
|
|
|
|
def prepare_captcha_image(img): |
|
try: |
|
|
|
img = img.resize((200, 50)) |
|
img_array = np.array(img.convert('L')) |
|
img_array = img_array / 255.0 |
|
img_array = np.expand_dims(img_array, axis=0) |
|
|
|
|
|
predictions = model.predict(img_array) |
|
|
|
|
|
decoded_captcha = ''.join([chr(np.argmax(pred) + ord('A')) for pred in predictions]) |
|
|
|
return decoded_captcha, predictions |
|
|
|
except Exception as e: |
|
st.error(f"Error preparing image: {e}") |
|
return None, None |
|
|
|
|
|
def run(): |
|
st.title("CAPTCHA Prediction") |
|
img_file = st.file_uploader("Upload a CAPTCHA Image", type=["jpg", "png", "jpeg"]) |
|
|
|
if img_file is not None: |
|
img = Image.open(img_file) |
|
st.image(img, caption="Uploaded CAPTCHA", use_column_width=True) |
|
|
|
|
|
upload_dir = './upload_images/' |
|
os.makedirs(upload_dir, exist_ok=True) |
|
|
|
|
|
save_image_path = os.path.join(upload_dir, img_file.name) |
|
with open(save_image_path, "wb") as f: |
|
f.write(img_file.getbuffer()) |
|
|
|
|
|
predicted_captcha, score = prepare_captcha_image(img) |
|
if predicted_captcha: |
|
st.success(f"**Predicted CAPTCHA: {predicted_captcha}**") |
|
else: |
|
st.error("Failed to predict CAPTCHA.") |
|
|
|
|
|
if __name__ == "__main__": |
|
run() |
|
|