luisarizmendi commited on
Commit
4463874
·
1 Parent(s): 41e9d13

first commit

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from ultralytics import YOLO
3
+ from PIL import Image
4
+ import os
5
+ import cv2
6
+ import torch
7
+
8
+ DEFAULT_MODEL_URL = "https://github.com/luisarizmendi/ai-apps/raw/refs/heads/main/models/luisarizmendi/object-detector-hardhat-or-hat/object-detector-hardhat-or-hat.pt"
9
+
10
+ def load_model(model_input):
11
+ model = YOLO(model_input)
12
+ if torch.cuda.is_available():
13
+ model.to('cuda')
14
+ print("Using GPU for inference")
15
+ else:
16
+ print("Using CPU for inference")
17
+
18
+ return model
19
+
20
+ def detect_objects_in_files(model_input, files):
21
+ """
22
+ Processes uploaded images for object detection.
23
+ """
24
+ if not files:
25
+ return "No files uploaded.", []
26
+
27
+ model = load_model(model_input)
28
+
29
+ results_images = []
30
+ for file in files:
31
+ try:
32
+ image = Image.open(file).convert("RGB")
33
+ results = model(image)
34
+ result_img_bgr = results[0].plot()
35
+ result_img_rgb = cv2.cvtColor(result_img_bgr, cv2.COLOR_BGR2RGB)
36
+ results_images.append(result_img_rgb)
37
+
38
+ # If you want that images appear one by one (slower)
39
+ #yield "Processing image...", results_images
40
+
41
+ except Exception as e:
42
+ return f"Error processing file: {file}. Exception: {str(e)}", []
43
+
44
+ del model
45
+ torch.cuda.empty_cache()
46
+
47
+ return "Processing completed.", results_images
48
+
49
+ interface = gr.Interface(
50
+ fn=detect_objects_in_files,
51
+ inputs=[
52
+ gr.Textbox(value=DEFAULT_MODEL_URL, label="Model URL", placeholder="Enter the model URL"),
53
+ gr.Files(file_types=["image"], label="Select Images"),
54
+ ],
55
+ outputs=[
56
+ gr.Textbox(label="Status"),
57
+ gr.Gallery(label="Results")
58
+ ],
59
+ title="Object Detection on Images",
60
+ description="Upload images to perform object detection. The model will process each image and display the results."
61
+ )
62
+
63
+ if __name__ == "__main__":
64
+ interface.launch()