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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
import os
|
3 |
+
from io import BytesIO
|
4 |
+
|
5 |
+
import cv2
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import pyrebase
|
9 |
+
import requests
|
10 |
+
from openai import OpenAI
|
11 |
+
from PIL import Image, ImageDraw, ImageFont
|
12 |
+
from ultralytics import YOLO
|
13 |
+
|
14 |
+
from prompts import remove_unwanted_prompt
|
15 |
+
|
16 |
+
|
17 |
+
def get_middle_thumbnail(input_image: Image, grid_size=(10, 10), padding=3):
|
18 |
+
"""
|
19 |
+
Extract the middle thumbnail from a sprite sheet, handling different aspect ratios
|
20 |
+
and removing padding.
|
21 |
+
|
22 |
+
Args:
|
23 |
+
input_image: PIL Image
|
24 |
+
grid_size: Tuple of (columns, rows)
|
25 |
+
padding: Number of padding pixels on each side (default 3)
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
PIL.Image: The middle thumbnail image with padding removed
|
29 |
+
"""
|
30 |
+
sprite_sheet = input_image
|
31 |
+
|
32 |
+
# Calculate thumbnail dimensions based on actual sprite sheet size
|
33 |
+
sprite_width, sprite_height = sprite_sheet.size
|
34 |
+
thumb_width_with_padding = sprite_width // grid_size[0]
|
35 |
+
thumb_height_with_padding = sprite_height // grid_size[1]
|
36 |
+
|
37 |
+
# Remove padding to get actual image dimensions
|
38 |
+
thumb_width = thumb_width_with_padding - (2 * padding) # 726 - 6 = 720
|
39 |
+
thumb_height = thumb_height_with_padding - (2 * padding) # varies based on input
|
40 |
+
|
41 |
+
# Calculate the middle position
|
42 |
+
total_thumbs = grid_size[0] * grid_size[1]
|
43 |
+
middle_index = total_thumbs // 2
|
44 |
+
|
45 |
+
# Calculate row and column of middle thumbnail
|
46 |
+
middle_row = middle_index // grid_size[0]
|
47 |
+
middle_col = middle_index % grid_size[0]
|
48 |
+
|
49 |
+
# Calculate pixel coordinates for cropping, including padding offset
|
50 |
+
left = (middle_col * thumb_width_with_padding) + padding
|
51 |
+
top = (middle_row * thumb_height_with_padding) + padding
|
52 |
+
right = left + thumb_width # Don't add padding here
|
53 |
+
bottom = top + thumb_height # Don't add padding here
|
54 |
+
|
55 |
+
# Crop and return the middle thumbnail
|
56 |
+
middle_thumb = sprite_sheet.crop((left, top, right, bottom))
|
57 |
+
return middle_thumb
|
58 |
+
|
59 |
+
|
60 |
+
def get_person_bbox(frame, model):
|
61 |
+
"""Detect person and return the largest bounding box"""
|
62 |
+
results = model(frame, classes=[0]) # class 0 is person in COCO
|
63 |
+
|
64 |
+
if not results or len(results[0].boxes) == 0:
|
65 |
+
return None
|
66 |
+
|
67 |
+
# Get all person boxes
|
68 |
+
boxes = results[0].boxes.xyxy.cpu().numpy()
|
69 |
+
# Calculate areas to find the largest person
|
70 |
+
areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
|
71 |
+
largest_idx = np.argmax(areas)
|
72 |
+
|
73 |
+
return boxes[largest_idx]
|
74 |
+
|
75 |
+
|
76 |
+
def generate_crops(frame):
|
77 |
+
"""Generate both 16:9 and 9:16 crops based on person detection"""
|
78 |
+
# Load YOLO model
|
79 |
+
model = YOLO("yolo11n.pt")
|
80 |
+
|
81 |
+
# Convert PIL Image to cv2 format if needed
|
82 |
+
if isinstance(frame, Image.Image):
|
83 |
+
frame = cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR)
|
84 |
+
|
85 |
+
original_height, original_width = frame.shape[:2]
|
86 |
+
bbox = get_person_bbox(frame, model)
|
87 |
+
|
88 |
+
if bbox is None:
|
89 |
+
return None, None
|
90 |
+
|
91 |
+
# Extract coordinates
|
92 |
+
x1, y1, x2, y2 = map(int, bbox)
|
93 |
+
person_height = y2 - y1
|
94 |
+
person_width = x2 - x1
|
95 |
+
person_center_x = (x1 + x2) // 2
|
96 |
+
person_center_y = (y1 + y2) // 2
|
97 |
+
|
98 |
+
# Generate 16:9 crop (focus on upper body)
|
99 |
+
aspect_ratio_16_9 = 16 / 9
|
100 |
+
crop_width_16_9 = min(original_width, int(person_height * aspect_ratio_16_9))
|
101 |
+
crop_height_16_9 = min(original_height, int(crop_width_16_9 / aspect_ratio_16_9))
|
102 |
+
|
103 |
+
# For 16:9, center horizontally and align top with person's top
|
104 |
+
x1_16_9 = max(0, person_center_x - crop_width_16_9 // 2)
|
105 |
+
x2_16_9 = min(original_width, x1_16_9 + crop_width_16_9)
|
106 |
+
y1_16_9 = max(0, y1) # Start from person's top
|
107 |
+
y2_16_9 = min(original_height, y1_16_9 + crop_height_16_9)
|
108 |
+
|
109 |
+
# Adjust if exceeding boundaries
|
110 |
+
if x2_16_9 > original_width:
|
111 |
+
x1_16_9 = original_width - crop_width_16_9
|
112 |
+
x2_16_9 = original_width
|
113 |
+
if y2_16_9 > original_height:
|
114 |
+
y1_16_9 = original_height - crop_height_16_9
|
115 |
+
y2_16_9 = original_height
|
116 |
+
|
117 |
+
# Generate 9:16 crop (full body)
|
118 |
+
aspect_ratio_9_16 = 9 / 16
|
119 |
+
crop_width_9_16 = min(original_width, int(person_height * aspect_ratio_9_16))
|
120 |
+
crop_height_9_16 = min(original_height, int(crop_width_9_16 / aspect_ratio_9_16))
|
121 |
+
|
122 |
+
# For 9:16, center both horizontally and vertically
|
123 |
+
x1_9_16 = max(0, person_center_x - crop_width_9_16 // 2)
|
124 |
+
x2_9_16 = min(original_width, x1_9_16 + crop_width_9_16)
|
125 |
+
y1_9_16 = max(0, person_center_y - crop_height_9_16 // 2)
|
126 |
+
y2_9_16 = min(original_height, y1_9_16 + crop_height_9_16)
|
127 |
+
|
128 |
+
# Adjust if exceeding boundaries
|
129 |
+
if x2_9_16 > original_width:
|
130 |
+
x1_9_16 = original_width - crop_width_9_16
|
131 |
+
x2_9_16 = original_width
|
132 |
+
if y2_9_16 > original_height:
|
133 |
+
y1_9_16 = original_height - crop_height_9_16
|
134 |
+
y2_9_16 = original_height
|
135 |
+
|
136 |
+
# Create crops
|
137 |
+
crop_16_9 = frame[y1_16_9:y2_16_9, x1_16_9:x2_16_9]
|
138 |
+
crop_9_16 = frame[y1_9_16:y2_9_16, x1_9_16:x2_9_16]
|
139 |
+
|
140 |
+
# Resize to standard dimensions
|
141 |
+
crop_16_9 = cv2.resize(crop_16_9, (426, 240)) # 16:9 aspect ratio
|
142 |
+
crop_9_16 = cv2.resize(crop_9_16, (240, 426)) # 9:16 aspect ratio
|
143 |
+
|
144 |
+
return crop_16_9, crop_9_16
|
145 |
+
|
146 |
+
|
147 |
+
def visualize_crops(image, bbox, crops_info):
|
148 |
+
"""
|
149 |
+
Visualize original bbox and calculated crops
|
150 |
+
bbox: [x1, y1, x2, y2]
|
151 |
+
crops_info: dict with 'crop_16_9' and 'crop_9_16' coordinates
|
152 |
+
"""
|
153 |
+
viz = image.copy()
|
154 |
+
|
155 |
+
# Draw original person bbox in blue
|
156 |
+
cv2.rectangle(
|
157 |
+
viz, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (255, 0, 0), 2
|
158 |
+
)
|
159 |
+
|
160 |
+
# Draw 16:9 crop in green
|
161 |
+
crop_16_9 = crops_info["crop_16_9"]
|
162 |
+
cv2.rectangle(
|
163 |
+
viz,
|
164 |
+
(int(crop_16_9["x1"]), int(crop_16_9["y1"])),
|
165 |
+
(int(crop_16_9["x2"]), int(crop_16_9["y2"])),
|
166 |
+
(0, 255, 0),
|
167 |
+
2,
|
168 |
+
)
|
169 |
+
|
170 |
+
# Draw 9:16 crop in red
|
171 |
+
crop_9_16 = crops_info["crop_9_16"]
|
172 |
+
cv2.rectangle(
|
173 |
+
viz,
|
174 |
+
(int(crop_9_16["x1"]), int(crop_9_16["y1"])),
|
175 |
+
(int(crop_9_16["x2"]), int(crop_9_16["y2"])),
|
176 |
+
(0, 0, 255),
|
177 |
+
2,
|
178 |
+
)
|
179 |
+
|
180 |
+
return viz
|
181 |
+
|
182 |
+
|
183 |
+
def encode_image_to_base64(image: Image.Image, format: str = "JPEG") -> str:
|
184 |
+
"""
|
185 |
+
Convert a PIL image to a base64 string.
|
186 |
+
|
187 |
+
Args:
|
188 |
+
image: PIL Image object
|
189 |
+
format: Image format to use for encoding (default: PNG)
|
190 |
+
|
191 |
+
Returns:
|
192 |
+
Base64 encoded string of the image
|
193 |
+
"""
|
194 |
+
buffered = BytesIO()
|
195 |
+
image.save(buffered, format=format)
|
196 |
+
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
197 |
+
|
198 |
+
|
199 |
+
def add_top_numbers(
|
200 |
+
input_image,
|
201 |
+
num_divisions=20,
|
202 |
+
margin=90,
|
203 |
+
font_size=120,
|
204 |
+
dot_spacing=20,
|
205 |
+
):
|
206 |
+
"""
|
207 |
+
Add numbered divisions across the top and bottom of any image with dotted vertical lines.
|
208 |
+
|
209 |
+
Args:
|
210 |
+
input_image (Image): PIL Image
|
211 |
+
num_divisions (int): Number of divisions to create
|
212 |
+
margin (int): Size of margin in pixels for numbers
|
213 |
+
font_size (int): Font size for numbers
|
214 |
+
dot_spacing (int): Spacing between dots in pixels
|
215 |
+
"""
|
216 |
+
# Load the image
|
217 |
+
original_image = input_image
|
218 |
+
|
219 |
+
# Create new image with extra space for numbers on top and bottom
|
220 |
+
new_width = original_image.width
|
221 |
+
new_height = original_image.height + (
|
222 |
+
2 * margin
|
223 |
+
) # Add margin to both top and bottom
|
224 |
+
new_image = Image.new("RGB", (new_width, new_height), "white")
|
225 |
+
|
226 |
+
# Paste original image in the middle
|
227 |
+
new_image.paste(original_image, (0, margin))
|
228 |
+
|
229 |
+
# Initialize drawing context
|
230 |
+
draw = ImageDraw.Draw(new_image)
|
231 |
+
|
232 |
+
try:
|
233 |
+
font = ImageFont.truetype("arial.ttf", font_size)
|
234 |
+
except OSError:
|
235 |
+
print("Using default font")
|
236 |
+
font = ImageFont.load_default(size=font_size)
|
237 |
+
|
238 |
+
# Calculate division width
|
239 |
+
division_width = original_image.width / num_divisions
|
240 |
+
|
241 |
+
# Draw division numbers and dotted lines
|
242 |
+
for i in range(num_divisions):
|
243 |
+
x = (i * division_width) + (division_width / 2)
|
244 |
+
|
245 |
+
# Draw number at top
|
246 |
+
draw.text((x, margin // 2), str(i + 1), fill="black", font=font, anchor="mm")
|
247 |
+
|
248 |
+
# Draw number at bottom
|
249 |
+
draw.text(
|
250 |
+
(x, new_height - (margin // 2)),
|
251 |
+
str(i + 1),
|
252 |
+
fill="black",
|
253 |
+
font=font,
|
254 |
+
anchor="mm",
|
255 |
+
)
|
256 |
+
|
257 |
+
# Draw dotted line from top margin to bottom margin
|
258 |
+
y_start = margin
|
259 |
+
y_end = new_height - margin
|
260 |
+
|
261 |
+
# Draw dots with specified spacing
|
262 |
+
current_y = y_start
|
263 |
+
while current_y < y_end:
|
264 |
+
draw.circle(
|
265 |
+
[x - 1, current_y - 1, x + 1, current_y + 1],
|
266 |
+
fill="black",
|
267 |
+
width=5,
|
268 |
+
radius=3,
|
269 |
+
)
|
270 |
+
current_y += dot_spacing
|
271 |
+
|
272 |
+
return new_image
|
273 |
+
|
274 |
+
|
275 |
+
def crop_and_draw_divisions(
|
276 |
+
input_image,
|
277 |
+
left_division,
|
278 |
+
right_division,
|
279 |
+
num_divisions=20,
|
280 |
+
line_color=(255, 0, 0),
|
281 |
+
line_width=2,
|
282 |
+
head_margin_percent=0.1,
|
283 |
+
):
|
284 |
+
"""
|
285 |
+
Create both 9:16 and 16:9 crops and draw guide lines.
|
286 |
+
|
287 |
+
Args:
|
288 |
+
input_image (Image): PIL Image
|
289 |
+
left_division (int): Left-side division number (1-20)
|
290 |
+
right_division (int): Right-side division number (1-20)
|
291 |
+
num_divisions (int): Total number of divisions (default=20)
|
292 |
+
line_color (tuple): RGB color tuple for lines (default: red)
|
293 |
+
line_width (int): Width of lines in pixels (default: 2)
|
294 |
+
head_margin_percent (float): Percentage margin above head (default: 0.1)
|
295 |
+
|
296 |
+
Returns:
|
297 |
+
tuple: (cropped_image_16_9, image_with_lines, cropped_image_9_16)
|
298 |
+
"""
|
299 |
+
yolo_model = YOLO("yolo11n.pt")
|
300 |
+
# Calculate division width and boundaries
|
301 |
+
division_width = input_image.width / num_divisions
|
302 |
+
left_boundary = (left_division - 1) * division_width
|
303 |
+
right_boundary = right_division * division_width
|
304 |
+
|
305 |
+
# First get the 9:16 crop
|
306 |
+
cropped_image_9_16 = input_image.crop(
|
307 |
+
(left_boundary, 0, right_boundary, input_image.height)
|
308 |
+
)
|
309 |
+
|
310 |
+
# Run YOLO on the 9:16 crop to get person bbox
|
311 |
+
bbox = yolo_model(cropped_image_9_16, classes=[0])[0].boxes.xyxy.cpu().numpy()[0]
|
312 |
+
x1, y1, x2, y2 = bbox
|
313 |
+
|
314 |
+
# Calculate top boundary with head margin
|
315 |
+
head_margin = (y2 - y1) * head_margin_percent
|
316 |
+
top_boundary = max(0, y1 - head_margin)
|
317 |
+
|
318 |
+
# Calculate 16:9 dimensions based on the width between divisions
|
319 |
+
crop_width = right_boundary - left_boundary
|
320 |
+
crop_height_16_9 = int(crop_width * 9 / 16)
|
321 |
+
|
322 |
+
# Calculate bottom boundary for 16:9
|
323 |
+
bottom_boundary = min(input_image.height, top_boundary + crop_height_16_9)
|
324 |
+
|
325 |
+
# Create 16:9 crop from original image
|
326 |
+
cropped_image_16_9 = input_image.crop(
|
327 |
+
(left_boundary, top_boundary, right_boundary, bottom_boundary)
|
328 |
+
)
|
329 |
+
|
330 |
+
# Draw guide lines for both crops on original image
|
331 |
+
image_with_lines = input_image.copy()
|
332 |
+
draw = ImageDraw.Draw(image_with_lines)
|
333 |
+
|
334 |
+
# Draw vertical lines (for both crops)
|
335 |
+
draw.line(
|
336 |
+
[(left_boundary, 0), (left_boundary, input_image.height)],
|
337 |
+
fill=line_color,
|
338 |
+
width=line_width,
|
339 |
+
)
|
340 |
+
draw.line(
|
341 |
+
[(right_boundary, 0), (right_boundary, input_image.height)],
|
342 |
+
fill=line_color,
|
343 |
+
width=line_width,
|
344 |
+
)
|
345 |
+
|
346 |
+
# Draw horizontal lines (for 16:9 crop)
|
347 |
+
draw.line(
|
348 |
+
[(left_boundary, top_boundary), (right_boundary, top_boundary)],
|
349 |
+
fill=line_color,
|
350 |
+
width=line_width,
|
351 |
+
)
|
352 |
+
draw.line(
|
353 |
+
[(left_boundary, bottom_boundary), (right_boundary, bottom_boundary)],
|
354 |
+
fill=line_color,
|
355 |
+
width=line_width,
|
356 |
+
)
|
357 |
+
|
358 |
+
return cropped_image_16_9, image_with_lines, cropped_image_9_16
|
359 |
+
|
360 |
+
|
361 |
+
def analyze_image(numbered_input_image: Image, prompt, input_image):
|
362 |
+
"""
|
363 |
+
Perform inference on an image using GPT-4V.
|
364 |
+
|
365 |
+
Args:
|
366 |
+
numbered_input_image (Image): PIL Image
|
367 |
+
prompt (str): The prompt/question about the image
|
368 |
+
input_image (Image): input image without numbers
|
369 |
+
|
370 |
+
Returns:
|
371 |
+
str: The model's response
|
372 |
+
"""
|
373 |
+
client = OpenAI()
|
374 |
+
base64_image = encode_image_to_base64(numbered_input_image, format="JPEG")
|
375 |
+
|
376 |
+
messages = [
|
377 |
+
{
|
378 |
+
"role": "user",
|
379 |
+
"content": [
|
380 |
+
{"type": "text", "text": prompt},
|
381 |
+
{
|
382 |
+
"type": "image_url",
|
383 |
+
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
|
384 |
+
},
|
385 |
+
],
|
386 |
+
}
|
387 |
+
]
|
388 |
+
|
389 |
+
response = client.chat.completions.create(
|
390 |
+
model="gpt-4o", messages=messages, max_tokens=300
|
391 |
+
)
|
392 |
+
|
393 |
+
messages.extend(
|
394 |
+
[
|
395 |
+
{"role": "assistant", "content": response.choices[0].message.content},
|
396 |
+
{
|
397 |
+
"role": "user",
|
398 |
+
"content": "please return the response in the json with keys left_row and right_row",
|
399 |
+
},
|
400 |
+
],
|
401 |
+
)
|
402 |
+
|
403 |
+
response = (
|
404 |
+
client.chat.completions.create(model="gpt-4o", messages=messages)
|
405 |
+
.choices[0]
|
406 |
+
.message.content
|
407 |
+
)
|
408 |
+
|
409 |
+
left_index = response.find("{")
|
410 |
+
right_index = response.rfind("}")
|
411 |
+
|
412 |
+
try:
|
413 |
+
if left_index != -1 and right_index != -1:
|
414 |
+
response_json = eval(response[left_index : right_index + 1])
|
415 |
+
cropped_image_16_9, image_with_lines, cropped_image_9_16 = (
|
416 |
+
crop_and_draw_divisions(
|
417 |
+
input_image=input_image,
|
418 |
+
left_division=response_json["left_row"],
|
419 |
+
right_division=response_json["right_row"],
|
420 |
+
)
|
421 |
+
)
|
422 |
+
except Exception as e:
|
423 |
+
print(e)
|
424 |
+
return input_image, input_image, input_image
|
425 |
+
|
426 |
+
return cropped_image_16_9, image_with_lines, cropped_image_9_16
|
427 |
+
|
428 |
+
|
429 |
+
def get_sprite_firebase(cid, rsid, uid):
|
430 |
+
config = {
|
431 |
+
"apiKey": f"{os.getenv('FIREBASE_API_KEY')}",
|
432 |
+
"authDomain": f"{os.getenv('FIREBASE_AUTH_DOMAIN')}",
|
433 |
+
"databaseURL": f"{os.getenv('FIREBASE_DATABASE_URL')}",
|
434 |
+
"projectId": f"{os.getenv('FIREBASE_PROJECT_ID')}",
|
435 |
+
"storageBucket": f"{os.getenv('FIREBASE_STORAGE_BUCKET')}",
|
436 |
+
"messagingSenderId": f"{os.getenv('FIREBASE_MESSAGING_SENDER_ID')}",
|
437 |
+
"appId": f"{os.getenv('FIREBASE_APP_ID')}",
|
438 |
+
"measurementId": f"{os.getenv('FIREBASE_MEASUREMENT_ID')}",
|
439 |
+
}
|
440 |
+
config = {
|
441 |
+
"apiKey": "AIzaSyB4n2UpGtWsTPj2qd9zChzLevhFkLPliXI",
|
442 |
+
"authDomain": "roll-dev-7c14a.firebaseapp.com",
|
443 |
+
"databaseURL": "https://roll-dev-7c14a-default-rtdb.firebaseio.com",
|
444 |
+
"projectId": "roll-dev-7c14a",
|
445 |
+
"storageBucket": "roll-dev-7c14a.firebasestorage.app",
|
446 |
+
"messagingSenderId": "556047642295",
|
447 |
+
"appId": "1:556047642295:web:be8714a223d3763efa2732",
|
448 |
+
"measurementId": "G-RE6ZGE7DGG",
|
449 |
+
}
|
450 |
+
firebase = pyrebase.initialize_app(config)
|
451 |
+
db = firebase.database()
|
452 |
+
account_id = "roll-dev-account" # os.getenv('ROLL_ACCOUNT')
|
453 |
+
|
454 |
+
COLLAB_EDIT_LINK = "collab_sprite_link_handler"
|
455 |
+
|
456 |
+
path = f"{account_id}/{COLLAB_EDIT_LINK}/{uid}/{cid}/{rsid}"
|
457 |
+
|
458 |
+
data = db.child(path).get()
|
459 |
+
return data.val()
|
460 |
+
|
461 |
+
|
462 |
+
def get_image_crop(cid=None, rsid=None, uid=None):
|
463 |
+
"""Function that returns both 16:9 and 9:16 crops"""
|
464 |
+
image_paths = get_sprite_firebase(cid, rsid, uid)
|
465 |
+
|
466 |
+
input_images = []
|
467 |
+
mid_images = []
|
468 |
+
cropped_image_16_9s = []
|
469 |
+
images_with_lines = []
|
470 |
+
cropped_image_9_16s = []
|
471 |
+
|
472 |
+
for image_path in image_paths:
|
473 |
+
response = requests.get(image_path)
|
474 |
+
|
475 |
+
input_image = Image.open(BytesIO(response.content))
|
476 |
+
input_images.append(input_image)
|
477 |
+
|
478 |
+
# Get the middle thumbnail
|
479 |
+
mid_image = get_middle_thumbnail(input_image)
|
480 |
+
mid_images.append(mid_image)
|
481 |
+
|
482 |
+
numbered_mid_image = add_top_numbers(
|
483 |
+
input_image=mid_image,
|
484 |
+
num_divisions=20,
|
485 |
+
margin=50,
|
486 |
+
font_size=30,
|
487 |
+
dot_spacing=20,
|
488 |
+
)
|
489 |
+
|
490 |
+
cropped_image_16_9, image_with_lines, cropped_image_9_16 = analyze_image(
|
491 |
+
numbered_mid_image, remove_unwanted_prompt(2), mid_image
|
492 |
+
)
|
493 |
+
cropped_image_16_9s.append(cropped_image_16_9)
|
494 |
+
images_with_lines.append(image_with_lines)
|
495 |
+
cropped_image_9_16s.append(cropped_image_9_16)
|
496 |
+
|
497 |
+
return gr.Gallery(
|
498 |
+
[
|
499 |
+
*input_images,
|
500 |
+
*mid_images,
|
501 |
+
*cropped_image_16_9s,
|
502 |
+
*images_with_lines,
|
503 |
+
*cropped_image_9_16s,
|
504 |
+
]
|
505 |
+
)
|
prompts.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict
|
2 |
+
|
3 |
+
|
4 |
+
def get_street_interview_prompt(
|
5 |
+
transcript: str, uid: str, rsid: str, link_start: str
|
6 |
+
) -> str:
|
7 |
+
"""Generate prompt for street interview analysis."""
|
8 |
+
return f"""This is a transcript for a street interview. Call Details are as follows:
|
9 |
+
User ID UID: {uid}
|
10 |
+
RSID: {rsid}
|
11 |
+
Transcript: {transcript}
|
12 |
+
|
13 |
+
Your task is to analyze this street interview transcript and identify the final/best timestamps for each topic or question discussed. Here are the key rules:
|
14 |
+
The user might repeat the answer to the question sometimes, you need to pick the very last answer intelligently
|
15 |
+
|
16 |
+
1. For any topic/answer that appears multiple times in the transcript (even partially):
|
17 |
+
- The LAST occurrence is always considered the best version. If the same thing is said multiple times, the last time is the best, all previous times are considered as additional takes.
|
18 |
+
- This includes cases where parts of an answer are scattered throughout the transcript
|
19 |
+
- Even slight variations of the same answer should be tracked
|
20 |
+
- List timestamps for ALL takes, with the final take highlighted as the best answer
|
21 |
+
|
22 |
+
2. Introduction handling:
|
23 |
+
- Question 1 is ALWAYS the speaker's introduction/self-introduction
|
24 |
+
- If someone introduces themselves multiple times, use the last introduction as best answer
|
25 |
+
- Include all variations of how they state their name/background
|
26 |
+
- List ALL introduction timestamps chronologically
|
27 |
+
|
28 |
+
3. Question sequence:
|
29 |
+
- After the introduction, list questions in the order they were first asked
|
30 |
+
- If a question or introduction is revisited later at any point, please use the later timestamp
|
31 |
+
- Track partial answers to the same question across the transcript
|
32 |
+
|
33 |
+
You need to make sure that any words that are repeated, you need to pick the last of them.
|
34 |
+
|
35 |
+
Return format:
|
36 |
+
|
37 |
+
[Question Title]
|
38 |
+
Total takes: [X] (Include ONLY if content appears more than once)
|
39 |
+
- [Take 1. <div id='topic' style="display: inline"> 15s at 12:30 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{765}}&uid={{uid}})
|
40 |
+
- [Take 2. <div id='topic' style="display: inline"> 30s at 14:45 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{885}}&et={{915}}&uid={{uid}})
|
41 |
+
...
|
42 |
+
- [Take X (Best) <div id='topic' style="display: inline"> 1m 10s at 16:20 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{980}}&et={{1050}}&uid={{uid}})"""
|
43 |
+
|
44 |
+
|
45 |
+
def get_street_interview_system_prompt(
|
46 |
+
cid: str, rsid: str, origin: str, ct: str
|
47 |
+
) -> str:
|
48 |
+
"""Generate system prompt for street interview analysis."""
|
49 |
+
return f"""You are analyzing a transcript for Call ID: {cid}, Session ID: {rsid}, Origin: {origin}, Call Type: {ct}.
|
50 |
+
CORE REQUIREMENT:
|
51 |
+
- TIMESTAMPS: A speaker can repeat the answer to a question multiple times. You need to pick the last answer very carefully and choose that as best take. Make sure that that same answer is not repeated again after the best answer.
|
52 |
+
|
53 |
+
YOU SHOULD Prioritize accuracy in timestamp at every cost. Read the Transcript carefully and decide where an answer starts and ends. You will have speaker labels so you need to be very sharp."""
|
54 |
+
|
55 |
+
|
56 |
+
def get_live_event_system_prompt(
|
57 |
+
cid: str,
|
58 |
+
rsid: str,
|
59 |
+
origin: str,
|
60 |
+
ct: str,
|
61 |
+
speaker_mapping: Dict[str, str],
|
62 |
+
transcript: str,
|
63 |
+
) -> str:
|
64 |
+
"""Generate system prompt for RollAI call analysis."""
|
65 |
+
return f"""You are a helpful assistant developed by Roll.AI(Leading AI tool for Remote production) who is analyzing the transcript for a RollAI Call. Following are the details:
|
66 |
+
- Call ID: {cid}
|
67 |
+
- Session ID: {rsid}
|
68 |
+
- Origin: {origin}
|
69 |
+
- Call Type: {ct}
|
70 |
+
- Speakers: {", ".join(speaker_mapping.values())}
|
71 |
+
- Diarized Transcript: {transcript}
|
72 |
+
|
73 |
+
You are tasked with creating social media clips from the transcript, You need to shortlist the atleast two short clips for EACH SPEAKER. There are some requirments:
|
74 |
+
|
75 |
+
CORE REQUIREMENTS:
|
76 |
+
1. SPEAKER Overlap in the CLIP: When specifying the duration for the script, make sure that in that duration:
|
77 |
+
- There is only continuous dialogue from that speaker.
|
78 |
+
- As soon as another speaker starts talking or the topic ends, the clip MUST end.
|
79 |
+
|
80 |
+
2. DURATION RULES:
|
81 |
+
- Each clip must be between 20 seconds to 120 seconds.
|
82 |
+
|
83 |
+
3. SPEAKER COVERAGE:
|
84 |
+
- Minimum 2 topics per speaker, aim for 3 if good content exists
|
85 |
+
|
86 |
+
CRITICAL: When analyzing timestamps, you must verify that in the duration specified:
|
87 |
+
1. No other speaker talks during the selected timeframe
|
88 |
+
2. The speaker talks continuously for at least 20 seconds
|
89 |
+
3. The clip ends BEFORE any interruption or speaker change"""
|
90 |
+
|
91 |
+
|
92 |
+
def get_live_event_user_prompt(uid: str, link_start: str) -> str:
|
93 |
+
"""Generate user prompt for RollAI call analysis."""
|
94 |
+
return f"""User ID: {uid}
|
95 |
+
|
96 |
+
Your task is to find the starting time, ending time, and the duration for the each topic in the above Short Listed Topics. You need to return the answer in the following format.
|
97 |
+
Please make sure that in the duration of 1 speaker, there is no segment of any other speaker. The shortlisted duration must be of a single speaker
|
98 |
+
|
99 |
+
Return Format requirements:
|
100 |
+
SPEAKER FORMAT:
|
101 |
+
**Speaker Name**
|
102 |
+
1. [Topic title <div id='topic' style="display: inline"> 22s at 12:30 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{772}}&uid={{uid}})
|
103 |
+
2. [Topic title <div id='topic' style="display: inline"> 43s at 14:45 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{885}}&et={{928}}&uid={{uid}})
|
104 |
+
3. [Topic title <div id='topic' style="display: inline"> 58s at 16:20 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{980}}&et={{1038}}&uid={{uid}})
|
105 |
+
**Speaker Name**
|
106 |
+
...."""
|
107 |
+
|
108 |
+
|
109 |
+
def get_chat_system_prompt(
|
110 |
+
cid: str,
|
111 |
+
rsid: str,
|
112 |
+
origin: str,
|
113 |
+
ct: str,
|
114 |
+
speaker_mapping: Dict[str, str],
|
115 |
+
transcript: str,
|
116 |
+
link_start: str,
|
117 |
+
) -> str:
|
118 |
+
"""Generate system prompt for chat analysis."""
|
119 |
+
return f"""You are a helpful assistant analyzing transcripts and generating timestamps and URL. The user will ask you questions regarding the social media clips from the transcript.
|
120 |
+
Call ID is {cid},
|
121 |
+
Session ID is {rsid},
|
122 |
+
origin is {origin},
|
123 |
+
Call Type is {ct}.
|
124 |
+
Speakers: {", ".join(speaker_mapping.values())}
|
125 |
+
Transcript: {transcript}
|
126 |
+
|
127 |
+
If a user asks timestamps for a specific topic or things, find the start time and end time of that specific topic and return answer in the format:
|
128 |
+
Answers and URLs should be formated as follows:
|
129 |
+
[Topic title <div id='topic' style="display: inline"> 22s at 12:30 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{772}}&uid={{uid}})
|
130 |
+
For Example:
|
131 |
+
If the start time is 10:13 and end time is 10:18, the url will be:
|
132 |
+
{link_start}://roll.ai/colab/1234aq_12314/51234151?st=613&et=618&uid=82314
|
133 |
+
In the URL, make sure that after RSID there is ? and then rest of the fields are added via &.
|
134 |
+
You can include multiple links here that can related to the user answer. ALWAYS ANSWER FROM THE TRANSCRIPT.
|
135 |
+
RULE: When selecting timestamps for the answer, always use the **starting time (XX:YY)** as the reference point for your response, with the duration (Z seconds) calculated from this starting time, not the ending time of the segment.
|
136 |
+
|
137 |
+
Example 1:
|
138 |
+
User: Suggest me some clips that can go viral on Instagram.
|
139 |
+
Response:
|
140 |
+
1. [Clip 1 <div id='topic' style="display: inline"> 22s at 12:30 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{772}}&uid={{uid}})
|
141 |
+
User: Give me the URL where each person has introduced themselves.
|
142 |
+
2. [Clip 2 <div id='topic' style="display: inline"> 10s at 10:00 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{600}}&et={{610}}&uid={{uid}})
|
143 |
+
|
144 |
+
Example 2:
|
145 |
+
Provide the exact timestamp where the person begins their introduction, typically starting with phrases like "Hi," "Hello," "I am," or "My name is," and include the full introduction, covering everything they say about themselves, including their name, role, background, current responsibilities, organization, and any additional details they provide about their work or personal interests.
|
146 |
+
1. [Person Name1 <div id='topic' style="display: inline"> 43s at 14:45 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{885}}&et={{928}}&uid={{uid}})
|
147 |
+
2. [Person Name2 <div id='topic' style="display: inline"> 58s at 16:20 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{980}}&et={{1038}}&uid={{uid}})
|
148 |
+
....
|
149 |
+
|
150 |
+
If the user provides a link to the agenda, use the correct_speaker_name_with_url function to correct the speaker names based on the agenda.
|
151 |
+
If the user provides the correct call type, use the correct_call_type function to correct the call type. Call Type for street interviews is 'si'."""
|
152 |
+
|
153 |
+
|
154 |
+
def remove_unwanted_prompt(number_of_speakers: int):
|
155 |
+
if number_of_speakers == 2:
|
156 |
+
return """I want to crop this image such that no unwanted or Partial Object or Partial Human is in the image.
|
157 |
+
Please analyze the image such that you tell me the row number on both the left and right sides of the image inside which there is the no unwanted partial object."""
|
utils.py
CHANGED
@@ -87,6 +87,13 @@ openai_tools = [
|
|
87 |
},
|
88 |
},
|
89 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
]
|
91 |
|
92 |
|
|
|
87 |
},
|
88 |
},
|
89 |
},
|
90 |
+
{
|
91 |
+
"type": "function",
|
92 |
+
"function": {
|
93 |
+
"name": "get_image",
|
94 |
+
"description": "If the user asks you to show crops, you need to call this function",
|
95 |
+
},
|
96 |
+
},
|
97 |
]
|
98 |
|
99 |
|