File size: 2,252 Bytes
659b71a
 
 
 
 
 
4f186ac
659b71a
c9ed9d2
 
 
659b71a
4f186ac
c9ed9d2
659b71a
4f186ac
c9ed9d2
4f186ac
c9ed9d2
6f1cee7
 
 
c9ed9d2
6f1cee7
659b71a
c9ed9d2
4f186ac
659b71a
4f186ac
 
659b71a
4f186ac
659b71a
4f186ac
 
 
 
 
659b71a
 
4f186ac
659b71a
 
 
4f186ac
659b71a
 
 
 
 
 
 
 
 
 
 
c9ed9d2
4f186ac
 
 
 
659b71a
a28b6b5
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import streamlit as st
from PIL import Image
import tensorflow as tf
import numpy as np
import os

# Caching the model loading function to optimize performance
@st.cache_resource
def load_model():
    model_path = "captcha.keras"  # Update with the actual model path
    return tf.keras.models.load_model(model_path)

# Load the model
model = load_model()

# Function to prepare the image for model prediction
def prepare_image(img):
    try:
        # Resize image to the input shape required by the model
        img = img.resize((200, 50))  # Adjust size according to the trained model
        img_array = np.array(img.convert('L'))  # Convert to grayscale if necessary
        img_array = img_array / 255.0  # Normalize image
        img_array = np.expand_dims(img_array, axis=-1)  # Add channel dimension
        img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension

        # Predict the output using the loaded model
        predictions = model.predict(img_array)

        # Decode predictions assuming the model outputs probabilities
        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

# Main function to run the Streamlit app
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)

        # Create the directory if it doesn't exist
        upload_dir = './upload_images/'
        os.makedirs(upload_dir, exist_ok=True)

        # Save the uploaded image
        save_image_path = os.path.join(upload_dir, img_file.name)
        with open(save_image_path, "wb") as f:
            f.write(img_file.getbuffer())

        # Predict the CAPTCHA
        predicted_captcha, score = prepare_image(img)
        if predicted_captcha:
            st.success(f"**Predicted CAPTCHA: {predicted_captcha}**")
        else:
            st.error("Failed to predict CAPTCHA.")

# Run the Streamlit app
if __name__ == "__main__":
    run()