Certainly! Below is an improved version of your ImagePredictorApp GTK application. The enhancements include better error handling, code organization, adherence to PEP 8 standards, type annotations, and improved UI layout for a more user-friendly experience.
Key Improvements:
- Organized Imports: Grouped standard libraries, third-party libraries, and GTK imports separately for better readability.
- Type Annotations: Added type hints to functions for clarity and better development support.
- Enhanced Error Handling: Implemented comprehensive try-except blocks to handle potential errors gracefully.
- PEP 8 Compliance: Reformatted the code to adhere to PEP 8 style guidelines.
- Improved UI Layout: Enhanced the GTK Grid layout with spacing and margin settings for a cleaner interface.
- Dynamic Output Label: Enabled the output label to wrap text, ensuring longer messages are displayed properly.
- Model Loading Feedback: Provided user feedback upon successful or failed model loading.
- Separated Concerns: Divided functionality into smaller, more manageable methods for clarity.
Improved Code:
import os
from io import BytesIO
from typing import Optional
import gi
import requests
from PIL import Image
from fastai.vision.all import load_learner, PILImage, Learner
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
class ImagePredictorApp(Gtk.Window):
def __init__(self):
super().__init__(title="Image Predictor")
self.set_border_width(10)
self.set_default_size(500, 400)
# Initialize model attribute
self.model: Optional[Learner] = None
# Create UI components
self.create_widgets()
def create_widgets(self):
"""Set up the UI components and layout."""
# Load Model Section
self.load_model_button = Gtk.Button(label="Load Model (.pkl or .pth)")
self.load_model_button.connect("clicked", self.on_load_model)
# Image Selection Section
self.image_entry = Gtk.Entry()
self.image_entry.set_placeholder_text("Enter image path or URL")
self.image_button = Gtk.Button(label="Select Image")
self.image_button.connect("clicked", self.on_select_image)
# Threshold Slider Section
self.threshold_label = Gtk.Label(label="Prediction Threshold: 50%")
self.threshold_adjustment = Gtk.Adjustment(50, 0, 100, 1, 10, 0)
self.threshold_slider = Gtk.Scale(
orientation=Gtk.Orientation.HORIZONTAL,
adjustment=self.threshold_adjustment
)
self.threshold_slider.set_digits(0)
self.threshold_slider.connect("value-changed", self.on_threshold_changed)
# Predict Button
self.predict_button = Gtk.Button(label="Predict")
self.predict_button.connect("clicked", self.on_predict)
self.predict_button.set_sensitive(False)
# Output Display
self.output_label = Gtk.Label(label="Output will be shown here.")
self.output_label.set_line_wrap(True)
self.output_label.set_xalign(0)
# Layout using Grid
grid = Gtk.Grid(column_spacing=10, row_spacing=10)
grid.set_border_width(10)
# Adding widgets to the grid
grid.attach(self.load_model_button, 0, 0, 2, 1)
grid.attach(self.image_entry, 0, 1, 1, 1)
grid.attach(self.image_button, 1, 1, 1, 1)
grid.attach(self.threshold_label, 0, 2, 2, 1)
grid.attach(self.threshold_slider, 0, 3, 2, 1)
grid.attach(self.predict_button, 0, 4, 2, 1)
grid.attach(self.output_label, 0, 5, 2, 1)
self.add(grid)
def on_load_model(self, button: Gtk.Button):
"""Handle the Load Model button click."""
dialog = Gtk.FileChooserDialog(
title="Choose a .pkl or .pth file",
parent=self,
action=Gtk.FileChooserAction.OPEN
)
dialog.add_buttons(
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.OK
)
dialog.set_filter(self.create_file_filter())
response = dialog.run()
if response == Gtk.ResponseType.OK:
model_path = dialog.get_filename()
self.load_model(model_path)
dialog.destroy()
def create_file_filter(self) -> Gtk.FileFilter:
"""Create a file filter for model files."""
file_filter = Gtk.FileFilter()
file_filter.set_name("Model Files")
file_filter.add_patterns(["*.pkl", "*.pth"])
return file_filter
def load_model(self, model_path: str):
"""Load the machine learning model from the specified path."""
try:
self.model = load_learner(model_path)
self.predict_button.set_sensitive(True)
self.output_label.set_text(f"Model loaded successfully from:\n{model_path}")
except Exception as e:
self.model = None
self.predict_button.set_sensitive(False)
self.output_label.set_text(f"Failed to load model:\n{e}")
def on_select_image(self, button: Gtk.Button):
"""Handle the Select Image button click."""
dialog = Gtk.FileChooserDialog(
title="Choose an image",
parent=self,
action=Gtk.FileChooserAction.OPEN
)
dialog.add_buttons(
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.OK
)
dialog.set_filter(self.create_image_filter())
response = dialog.run()
if response == Gtk.ResponseType.OK:
image_path = dialog.get_filename()
self.image_entry.set_text(image_path)
dialog.destroy()
def create_image_filter(self) -> Gtk.FileFilter:
"""Create a file filter for image files."""
img_filter = Gtk.FileFilter()
img_filter.set_name("Image Files")
img_filter.add_mime_type("image/png")
img_filter.add_mime_type("image/jpeg")
img_filter.add_pattern("*.png")
img_filter.add_pattern("*.jpg")
img_filter.add_pattern("*.jpeg")
return img_filter
def on_threshold_changed(self, scale: Gtk.Scale):
"""Update the threshold label when the slider value changes."""
value = self.threshold_slider.get_value()
self.threshold_label.set_text(f"Prediction Threshold: {value:.0f}%")
def on_predict(self, button: Gtk.Button):
"""Handle the Predict button click."""
if not self.model:
self.output_label.set_text("Please load a model first.")
return
image_input = self.image_entry.get_text().strip()
if not image_input:
self.output_label.set_text("Please provide an image path or URL.")
return
try:
image = self.load_image(image_input)
except Exception as e:
self.output_label.set_text(f"Error loading image:\n{e}")
return
try:
pred, pred_idx, outputs = self.model.predict(image)
probabilities = outputs.numpy() * 100 # Convert to percentage
classes = self.model.dls.vocab # Get class names
threshold = self.threshold_slider.get_value() # Get the threshold value
# Prepare formatted prediction results
output_lines = ["**Predictions:**"]
for class_name, probability in zip(classes, probabilities):
if probability >= threshold:
line = f"• {class_name}: {probability:.2f}% (Confidence)"
output_lines.append(line)
output_lines.append(f"\n**Overall Prediction:** {pred}")
# Update the output label
self.output_label.set_markup("\n".join(output_lines))
# Optionally, print to terminal
for line in output_lines:
print(line)
except Exception as e:
self.output_label.set_text(f"Error during prediction:\n{e}")
def load_image(self, image_input: str) -> PILImage:
"""
Load an image from a local path or a URL.
Args:
image_input (str): The path or URL of the image.
Returns:
PILImage: The loaded image.
"""
if image_input.startswith(('http://', 'https://', 'ftp://')):
response = requests.get(image_input)
response.raise_for_status()
return PILImage.create(BytesIO(response.content))
elif os.path.isfile(image_input):
return PILImage.create(image_input)
else:
raise ValueError("Invalid image path or URL.")
def main():
"""Initialize and run the GTK application."""
app = ImagePredictorApp()
app.connect("destroy", Gtk.main_quit)
app.show_all()
Gtk.main()
if __name__ == "__main__":
main()
Detailed Explanation of Enhancements:
-
Organized Imports:
- Standard libraries (
os, io, typing) are imported first.
- Third-party libraries (
gi, requests, PIL, fastai) follow.
- GTK-specific imports are handled after setting the required version.
-
Type Annotations:
- Functions include type hints, enhancing code readability and aiding tools like linters and IDEs.
- For example,
def load_model(self, model_path: str) clearly indicates the expected input type.
-
Enhanced Error Handling:
- Wrapped model loading and image processing in try-except blocks to catch and display errors without crashing the application.
- Provides user-friendly error messages through the
output_label.
-
PEP 8 Compliance:
- Consistent indentation, spacing, and line lengths.
- Clear and descriptive naming conventions for variables and methods.
-
Improved UI Layout:
- Added
column_spacing and row_spacing to the Gtk.Grid for better separation between widgets.
- Set margins around the grid to prevent widgets from touching the window edges.
- Used
set_placeholder_text for the image entry to guide users on acceptable inputs.
-
Dynamic Output Label:
- Enabled text wrapping and set horizontal alignment to the left (
xalign=0) to ensure readability of multi-line outputs.
-
Model Loading Feedback:
- After successfully loading a model, the application informs the user by updating the
output_label.
- If model loading fails, the user is notified, and the Predict button remains disabled.
-
Utility Methods:
create_file_filter and create_image_filter methods encapsulate the creation of file filters, improving code modularity.
load_image method centralizes image loading logic, handling both local files and URLs, simplifying the on_predict method.
Additional Suggestions:
- Image Preview: Consider adding an image preview feature to display the selected image within the application.
- Progress Indicator: Implement a progress bar or spinner during long-running operations like model loading or prediction.
- Logging: Incorporate logging instead of printing to the terminal for better debugging and record-keeping.
- Configuration Options: Allow users to adjust other prediction parameters or choose different models dynamically.
These enhancements should make your application more robust, user-friendly, and maintainable. Feel free to further customize the UI and functionality based on your specific requirements!