CiclopeIA / app.py
jsr90's picture
Update app.py
1cea55c
raw
history blame
3.32 kB
import gradio as gr # Import Gradio library for creating UI
import torch # Import PyTorch for YOLOv5 model
from PIL import Image # Import Pillow for image manipulation
# Load YOLOv5 model from Ultralytics' GitHub repository
model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt', _verbose=False)
# Define a function to predict objects in an image
def predict(image_in_img, image_in_video):
global model # Use the global YOLOv5 model
if image_in_video == None and image_in_img == None: # If both inputs are None, raise an error
raise gr.Error("Please upload an image.")
if image_in_video or image_in_img: # If either input is not None,
image = image_in_video or image_in_img # set the image variable to the non-None input
return model(image).render()[0] # Use the YOLOv5 model to predict objects in the image and return the rendered output
# Define a function to toggle between webcam and file inputs
def toggle(choice):
if choice == "webcam": # If "webcam" is selected,
return gr.update(visible=True, value=None), gr.update(visible=False, value=None) # Show webcam input and hide file input
else: # Otherwise, if "file" is selected,
return gr.update(visible=False, value=None), gr.update(visible=True, value=None) # Show file input and hide webcam input
# Examples to test
ex = [["img1.jpeg"], ["img2.jpeg"], ["img3.jpeg"]]
# Create Gradio UI blocks
with gr.Blocks() as blocks:
gr.Markdown("# CiclopeIA: Imaginando tu futuro") # Display text in Markdown format
gr.Markdown("## Application based on [CiclopeIA Saturdays' project](https://medium.com/saturdays-ai/ciclopeia-imaginando-tu-entorno-14dd3781a7ac)")
gr.Markdown("### Take a photo of a € bill or make it directly with the camera and the model will recognize its value")
with gr.Row(): # Create a row of UI elements
with gr.Column(): # Create a column of UI elements
# Create a radio button to choose between webcam and file inputs
image_or_file_opt = gr.Radio(["file", "webcam"], value="file",
label="How would you like to upload your image?")
# Create an image input for a file, initially hidden
image_in_img = gr.Image(
source="upload", type="filepath")
# Create an image input for the webcam
image_in_video = gr.Image(source="webcam", visible=False, type="filepath")
# Bind the toggle function to the radio button to switch between webcam and file inputs
image_or_file_opt.change(fn=toggle, inputs=[image_or_file_opt],
outputs=[image_in_video, image_in_img], queue=False)
with gr.Column(): # Create another column of UI elements
# Create an output image to display the predicted objects
image_out = gr.Image()
# Create a button to run the prediction function and display the output image
run_btn = gr.Button("Run")
run_btn.click(fn=predict, inputs=[
image_in_img, image_in_video], outputs=[image_out])
gr.Examples(
examples = ex,
inputs = [image_in_img, image_in_video],
outputs = image_out,
)
# Launch the Gradio UI blocks
blocks.launch()