Spaces:
Build error
Build error
| import gradio as gr | |
| import tensorflow as tf | |
| import numpy as np | |
| from PIL import Image | |
| import logging | |
| # Set up logging | |
| logging.basicConfig(level=logging.INFO) | |
| # Load the model | |
| try: | |
| model = tf.keras.models.load_model("ElYazisiRakamlariTahmin.h5") | |
| logging.info("Model loaded successfully") | |
| except Exception as e: | |
| logging.error(f"Error loading model: {str(e)}") | |
| model = None | |
| def preprocess_image(image): | |
| try: | |
| # Convert to grayscale | |
| image = image.convert("L") | |
| # Resize to 28x28 pixels | |
| image = image.resize((28, 28)) | |
| # Convert to numpy array and normalize | |
| img_array = np.array(image, dtype=np.float32) / 255.0 | |
| # Reshape to (1, 28, 28) as per your model's input shape | |
| img_array = img_array.reshape(1, 28, 28) | |
| logging.info("Image preprocessed successfully") | |
| return img_array | |
| except Exception as e: | |
| logging.error(f"Error in preprocessing: {str(e)}") | |
| return None | |
| def predict_digit(image): | |
| if model is None: | |
| return "Error: Model not loaded properly" | |
| try: | |
| # Check if the input is a valid image | |
| if not isinstance(image, Image.Image): | |
| return "Error: Invalid input. Please upload an image." | |
| preprocessed = preprocess_image(image) | |
| if preprocessed is None: | |
| return "Error: Failed to preprocess the image" | |
| # Make prediction | |
| logits = model.predict(preprocessed) | |
| probabilities = tf.nn.softmax(logits).numpy()[0] | |
| predicted_digit = np.argmax(probabilities) | |
| confidence = probabilities[predicted_digit] | |
| # Get top 3 predictions | |
| top_3_indices = np.argsort(probabilities)[-3:][::-1] | |
| top_3_probs = probabilities[top_3_indices] | |
| result = f"Predicted Digit: {predicted_digit}\n" | |
| result += f"Confidence: {confidence:.2f}\n\n" | |
| result += "Top 3 Predictions:\n" | |
| for digit, prob in zip(top_3_indices, top_3_probs): | |
| result += f"Digit {digit}: {prob:.2f}\n" | |
| logging.info(f"Prediction made: {result}") | |
| return result | |
| except Exception as e: | |
| logging.error(f"Error in prediction: {str(e)}") | |
| return f"Error during prediction: {str(e)}" | |
| # Gradio interface | |
| iface = gr.Interface( | |
| fn=predict_digit, | |
| inputs=gr.Image(type="pil"), | |
| outputs="text", | |
| title="Handwritten Digit Recognition", | |
| description="Upload an image of a handwritten digit (0-9) to get a prediction." | |
| ) | |
| # For debugging: print model summary | |
| if model is not None: | |
| model.summary() | |
| # Launch the interface | |
| iface.launch() |