1657866Y commited on
Commit
edf0436
·
verified ·
1 Parent(s): af4c3c1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -0
app.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+ from PIL import Image
3
+ import gradio as gr
4
+ from huggingface_hub import snapshot_download
5
+ import os
6
+ import tempfile
7
+ import cv2
8
+
9
+ model_path = "best.onnx"
10
+
11
+
12
+ def load_model(repo_id):
13
+ download_dir = snapshot_download(repo_id)
14
+ print(download_dir)
15
+ path = os.path.join(download_dir, "best.onnx")
16
+ print(path)
17
+ detection_model = YOLO(path, task='detect')
18
+ return detection_model
19
+
20
+
21
+ def process_image(pilimg):
22
+ source = pilimg
23
+ result = detection_model.predict(source, conf=0.5)
24
+ img_bgr = result[0].plot()
25
+ out_pilimg = Image.fromarray(img_bgr[..., ::-1]) # RGB-order PIL image
26
+ return out_pilimg
27
+
28
+
29
+ def process_video(video):
30
+ cap = cv2.VideoCapture(video)
31
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
32
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
33
+ fps = cap.get(cv2.CAP_PROP_FPS)
34
+
35
+ temp_dir = tempfile.mkdtemp()
36
+ fourcc = cv2.VideoWriter_fourcc(*'MP4V')
37
+ output_path = os.path.join(temp_dir, "output.mp4")
38
+ output = cv2.VideoWriter(output_path, fourcc, fps, (int(width), int(height)))
39
+
40
+ # Loop through the video frames
41
+ while cap.isOpened():
42
+ # Read a frame from the video
43
+ success, frame = cap.read()
44
+
45
+ if success:
46
+ # Run YOLO inference on the frame on GPU Device 0
47
+ results = detection_model.predict(frame, conf=0.5)
48
+
49
+ # Visualize the results on the frame
50
+ annotated_frame = results[0].plot()
51
+
52
+ # Write the annotated frame
53
+ output.write(annotated_frame)
54
+
55
+ output.release()
56
+ output.release()
57
+ cv2.destroyAllWindows()
58
+ cv2.waitKey(1)
59
+ return output_path
60
+
61
+
62
+ REPO_ID = "1657866Y/grocery"
63
+ detection_model = load_model(REPO_ID)
64
+
65
+ # Create the interface for image upload
66
+ image_interface = gr.Interface(fn=process_image,
67
+ inputs=gr.Image(type="pil"),
68
+ outputs=gr.Image(type="pil"))
69
+
70
+ # Create the interface for video upload
71
+ video_interface = gr.Interface(fn=process_video,
72
+ inputs=gr.Video(label="Upload a Video"),
73
+ outputs="video")
74
+
75
+ # Use gr.Blocks to arrange components and launch the app
76
+ with gr.Blocks() as app:
77
+ # Add a header using Markdown
78
+ gr.Markdown("# Grocery? No wait!")
79
+ gr.Markdown("Choose whether to upload an image or a video below!")
80
+
81
+ # Add the tabbed interface
82
+ gr.TabbedInterface([image_interface, video_interface],
83
+ tab_names=["Image Upload", "Video Upload"])
84
+
85
+
86
+ # Launch the interface
87
+ app.launch()