Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import tensorflow as tf | |
| import pickle | |
| import cv2 | |
| import numpy as np | |
| import os | |
| # ----------------------------- | |
| # Load model and encoder | |
| # ----------------------------- | |
| model = tf.keras.models.load_model("model/captcha_model.h5") | |
| with open("model/encoder.pkl", "rb") as f: | |
| encoder = pickle.load(f) | |
| # ----------------------------- | |
| # List of available sample images | |
| # ----------------------------- | |
| sample_images = [f"sample_images/{img}" for img in os.listdir("sample_images")] | |
| # ----------------------------- | |
| # Prediction Function | |
| # ----------------------------- | |
| def predict_with_preview(image_name): | |
| image_path = image_name | |
| # Load image for display | |
| img_display = cv2.imread(image_path) | |
| img_display = cv2.cvtColor(img_display, cv2.COLOR_BGR2RGB) | |
| # 🔍 ZOOM IMAGE HERE - 5x bigger | |
| zoom_factor = 5 | |
| height, width = img_display.shape[:2] | |
| new_width = width * zoom_factor | |
| new_height = height * zoom_factor | |
| img_display = cv2.resize(img_display, (new_width, new_height), interpolation=cv2.INTER_NEAREST) | |
| # INTER_NEAREST برای حفظ پیکسلهای واضح | |
| # Process grayscale for prediction | |
| img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) | |
| img = cv2.bitwise_not(img) | |
| img = img / 255.0 | |
| preds = model.predict(np.expand_dims(img, axis=0)) | |
| predicted_indices = [np.argmax(p, axis=1)[0] for p in preds] | |
| pred_chars = encoder.inverse_transform(predicted_indices) | |
| original = os.path.splitext(os.path.basename(image_path))[0] | |
| return img_display, f"✅ Predicted: {''.join(pred_chars)}\n📝 Original: {original}" | |
| # ----------------------------- | |
| # Custom CSS | |
| # ----------------------------- | |
| custom_css = """ | |
| textarea { | |
| min-height: 130px !important; | |
| font-size: 18px !important; | |
| line-height: 1.6 !important; | |
| } | |
| """ | |
| # ----------------------------- | |
| # Gradio App | |
| # ----------------------------- | |
| with gr.Blocks(css=custom_css, theme="soft") as demo: | |
| gr.Markdown("## 🔐 CAPTCHA Reader") | |
| with gr.Row(): | |
| with gr.Column(): | |
| image_input = gr.Dropdown(choices=sample_images, label="Choose CAPTCHA") | |
| submit_btn = gr.Button("Submit", variant="primary") | |
| with gr.Column(): | |
| image_output = gr.Image(label="Selected Image (5x Zoomed)") | |
| text_output = gr.Textbox(label="Prediction") | |
| submit_btn.click(fn=predict_with_preview, inputs=image_input, outputs=[image_output, text_output]) | |
| # ----------------------------- | |
| # Launch App | |
| # ----------------------------- | |
| demo.launch() |