Spaces:
Running
on
Zero
Running
on
Zero
Create demo.py
Browse files
demo.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import numpy as np
|
5 |
+
from PIL import Image
|
6 |
+
from transformers import AutoModelForCausalLM
|
7 |
+
import matplotlib
|
8 |
+
|
9 |
+
matplotlib.use("Agg") # Use Agg backend for non-interactive plotting
|
10 |
+
|
11 |
+
|
12 |
+
os.environ["HF_TOKEN"] = os.environ.get("TOKEN_FROM_SECRET") or True
|
13 |
+
model = AutoModelForCausalLM.from_pretrained(
|
14 |
+
"vikhyatk/moondream-next",
|
15 |
+
trust_remote_code=True,
|
16 |
+
torch_dtype=torch.float16,
|
17 |
+
device_map={"": "cuda"},
|
18 |
+
revision="69420e0c6596863b4f0059e365fadc5cb388e8fd"
|
19 |
+
)
|
20 |
+
|
21 |
+
|
22 |
+
def visualize_gaze_multi(face_boxes, gaze_points, image=None, show_plot=True):
|
23 |
+
"""Visualization function with reduced whitespace"""
|
24 |
+
# Calculate figure size based on image aspect ratio
|
25 |
+
if image is not None:
|
26 |
+
height, width = image.shape[:2]
|
27 |
+
aspect_ratio = width / height
|
28 |
+
fig_height = 6 # Base height
|
29 |
+
fig_width = fig_height * aspect_ratio
|
30 |
+
else:
|
31 |
+
width, height = 800, 600
|
32 |
+
fig_width, fig_height = 10, 8
|
33 |
+
|
34 |
+
# Create figure with tight layout
|
35 |
+
fig = plt.figure(figsize=(fig_width, fig_height))
|
36 |
+
ax = fig.add_subplot(111)
|
37 |
+
|
38 |
+
if image is not None:
|
39 |
+
ax.imshow(image)
|
40 |
+
else:
|
41 |
+
ax.set_facecolor("#1a1a1a")
|
42 |
+
fig.patch.set_facecolor("#1a1a1a")
|
43 |
+
|
44 |
+
colors = plt.cm.rainbow(np.linspace(0, 1, len(face_boxes)))
|
45 |
+
|
46 |
+
for face_box, gaze_point, color in zip(face_boxes, gaze_points, colors):
|
47 |
+
hex_color = "#{:02x}{:02x}{:02x}".format(
|
48 |
+
int(color[0] * 255), int(color[1] * 255), int(color[2] * 255)
|
49 |
+
)
|
50 |
+
|
51 |
+
x, y, width_box, height_box = face_box
|
52 |
+
gaze_x, gaze_y = gaze_point
|
53 |
+
|
54 |
+
face_center_x = x + width_box / 2
|
55 |
+
face_center_y = y + height_box / 2
|
56 |
+
|
57 |
+
face_rect = plt.Rectangle(
|
58 |
+
(x, y), width_box, height_box, fill=False, color=hex_color, linewidth=2
|
59 |
+
)
|
60 |
+
ax.add_patch(face_rect)
|
61 |
+
|
62 |
+
points = 50
|
63 |
+
alphas = np.linspace(0.8, 0, points)
|
64 |
+
|
65 |
+
x_points = np.linspace(face_center_x, gaze_x, points)
|
66 |
+
y_points = np.linspace(face_center_y, gaze_y, points)
|
67 |
+
|
68 |
+
for i in range(points - 1):
|
69 |
+
ax.plot(
|
70 |
+
[x_points[i], x_points[i + 1]],
|
71 |
+
[y_points[i], y_points[i + 1]],
|
72 |
+
color=hex_color,
|
73 |
+
alpha=alphas[i],
|
74 |
+
linewidth=4,
|
75 |
+
)
|
76 |
+
|
77 |
+
ax.scatter(gaze_x, gaze_y, color=hex_color, s=100, zorder=5)
|
78 |
+
ax.scatter(gaze_x, gaze_y, color="white", s=50, zorder=6)
|
79 |
+
|
80 |
+
# Set plot limits and remove axes
|
81 |
+
ax.set_xlim(0, width)
|
82 |
+
ax.set_ylim(height, 0)
|
83 |
+
ax.set_aspect("equal")
|
84 |
+
ax.set_xticks([])
|
85 |
+
ax.set_yticks([])
|
86 |
+
|
87 |
+
# Remove padding around the plot
|
88 |
+
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
|
89 |
+
|
90 |
+
return fig
|
91 |
+
|
92 |
+
@spaces.GPU(duration=15)
|
93 |
+
def process_image(input_image):
|
94 |
+
try:
|
95 |
+
# Convert to PIL Image if needed
|
96 |
+
if isinstance(input_image, np.ndarray):
|
97 |
+
pil_image = Image.fromarray(input_image)
|
98 |
+
else:
|
99 |
+
pil_image = input_image
|
100 |
+
|
101 |
+
# Get image encoding
|
102 |
+
enc_image = model.encode_image(pil_image)
|
103 |
+
|
104 |
+
# Detect faces
|
105 |
+
faces = model.detect(enc_image, "face")["objects"]
|
106 |
+
|
107 |
+
if not faces:
|
108 |
+
return None, "No faces detected in the image."
|
109 |
+
|
110 |
+
# Process each face
|
111 |
+
face_boxes = []
|
112 |
+
gaze_points = []
|
113 |
+
|
114 |
+
for face in faces:
|
115 |
+
face_center = (
|
116 |
+
(face["x_min"] + face["x_max"]) / 2,
|
117 |
+
(face["y_min"] + face["y_max"]) / 2,
|
118 |
+
)
|
119 |
+
gaze = model.detect_gaze(enc_image, face_center)
|
120 |
+
|
121 |
+
if gaze is None:
|
122 |
+
continue
|
123 |
+
|
124 |
+
face_box = (
|
125 |
+
face["x_min"] * pil_image.width,
|
126 |
+
face["y_min"] * pil_image.height,
|
127 |
+
(face["x_max"] - face["x_min"]) * pil_image.width,
|
128 |
+
(face["y_max"] - face["y_min"]) * pil_image.height,
|
129 |
+
)
|
130 |
+
|
131 |
+
gaze_point = (
|
132 |
+
gaze["x"] * pil_image.width,
|
133 |
+
gaze["y"] * pil_image.height,
|
134 |
+
)
|
135 |
+
|
136 |
+
face_boxes.append(face_box)
|
137 |
+
gaze_points.append(gaze_point)
|
138 |
+
|
139 |
+
# Create visualization
|
140 |
+
image_array = np.array(pil_image)
|
141 |
+
fig = visualize_gaze_multi(
|
142 |
+
face_boxes, gaze_points, image=image_array, show_plot=False
|
143 |
+
)
|
144 |
+
|
145 |
+
return fig, f"Detected {len(faces)} faces."
|
146 |
+
|
147 |
+
except Exception as e:
|
148 |
+
return None, f"Error processing image: {str(e)}"
|
149 |
+
|
150 |
+
|
151 |
+
with gr.Blocks(title="Moondream Gaze Detection") as app:
|
152 |
+
gr.Markdown("# 🌔 Moondream Gaze Detection")
|
153 |
+
gr.Markdown("Upload an image to detect faces and visualize their gaze directions.")
|
154 |
+
|
155 |
+
with gr.Row():
|
156 |
+
with gr.Column():
|
157 |
+
input_image = gr.Image(label="Input Image", type="pil")
|
158 |
+
|
159 |
+
with gr.Column():
|
160 |
+
output_text = gr.Textbox(label="Status")
|
161 |
+
output_plot = gr.Plot(label="Visualization")
|
162 |
+
|
163 |
+
input_image.change(
|
164 |
+
fn=process_image, inputs=[input_image], outputs=[output_plot, output_text]
|
165 |
+
)
|
166 |
+
|
167 |
+
gr.Examples(
|
168 |
+
examples=["gaze_test.jpg", "gaze_test2.jpg", "gaze_test3.jpg"],
|
169 |
+
inputs=input_image,
|
170 |
+
)
|
171 |
+
|
172 |
+
if __name__ == "__main__":
|
173 |
+
app.launch()
|