Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,240 +1,272 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
import
|
| 9 |
-
|
| 10 |
-
from
|
| 11 |
-
|
| 12 |
-
import
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
)
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
#
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import spaces
|
| 3 |
+
from huggingface_hub import hf_hub_download
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
import tensorflow as tf
|
| 7 |
+
from tensorflow.keras.models import load_model
|
| 8 |
+
import torch
|
| 9 |
+
from ultralytics import YOLO
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import traceback
|
| 12 |
+
import json
|
| 13 |
+
import pandas as pd
|
| 14 |
+
from itertools import combinations
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
# =============================================================================
|
| 18 |
+
# MODEL LOADING
|
| 19 |
+
# =============================================================================
|
| 20 |
+
|
| 21 |
+
# Load YOLO Card Detection Model from HuggingFace Hub
|
| 22 |
+
card_model_path = hf_hub_download("Oamitai/card-detection", "best.pt")
|
| 23 |
+
card_detection_model = YOLO(card_model_path)
|
| 24 |
+
card_detection_model.conf = 0.5
|
| 25 |
+
|
| 26 |
+
# Load YOLO Shape Detection Model from HuggingFace Hub
|
| 27 |
+
shape_model_path = hf_hub_download("Oamitai/shape-detection", "best.pt")
|
| 28 |
+
shape_detection_model = YOLO(shape_model_path)
|
| 29 |
+
shape_detection_model.conf = 0.5
|
| 30 |
+
|
| 31 |
+
# Load Shape Classification Model (Keras) from HuggingFace Hub
|
| 32 |
+
shape_classification_model = load_model(
|
| 33 |
+
hf_hub_download("Oamitai/shape-classification", "shape_model.keras")
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Load Fill Classification Model (Keras) from HuggingFace Hub
|
| 37 |
+
fill_classification_model = load_model(
|
| 38 |
+
hf_hub_download("Oamitai/fill-classification", "fill_model.keras")
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# =============================================================================
|
| 42 |
+
# UTILITY & PROCESSING FUNCTIONS
|
| 43 |
+
# =============================================================================
|
| 44 |
+
|
| 45 |
+
def check_and_rotate_input_image(board_image: np.ndarray, detector) -> (np.ndarray, bool):
|
| 46 |
+
"""
|
| 47 |
+
Detect card regions and determine if the image needs to be rotated.
|
| 48 |
+
"""
|
| 49 |
+
card_results = detector(board_image)
|
| 50 |
+
card_boxes = card_results[0].boxes.xyxy.cpu().numpy().astype(int)
|
| 51 |
+
if card_boxes.size == 0:
|
| 52 |
+
return board_image, False
|
| 53 |
+
|
| 54 |
+
widths = card_boxes[:, 2] - card_boxes[:, 0]
|
| 55 |
+
heights = card_boxes[:, 3] - card_boxes[:, 1]
|
| 56 |
+
if np.mean(heights) > np.mean(widths):
|
| 57 |
+
return cv2.rotate(board_image, cv2.ROTATE_90_CLOCKWISE), True
|
| 58 |
+
return board_image, False
|
| 59 |
+
|
| 60 |
+
def restore_original_orientation(image: np.ndarray, was_rotated: bool) -> np.ndarray:
|
| 61 |
+
"""
|
| 62 |
+
Restore the original orientation of the image if it was rotated.
|
| 63 |
+
"""
|
| 64 |
+
if was_rotated:
|
| 65 |
+
return cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
|
| 66 |
+
return image
|
| 67 |
+
|
| 68 |
+
def predict_color(shape_image: np.ndarray) -> str:
|
| 69 |
+
"""
|
| 70 |
+
Determine the dominant color in a shape image using HSV thresholds.
|
| 71 |
+
"""
|
| 72 |
+
hsv_image = cv2.cvtColor(shape_image, cv2.COLOR_BGR2HSV)
|
| 73 |
+
green_mask = cv2.inRange(hsv_image, np.array([40, 50, 50]), np.array([80, 255, 255]))
|
| 74 |
+
purple_mask = cv2.inRange(hsv_image, np.array([120, 50, 50]), np.array([160, 255, 255]))
|
| 75 |
+
red_mask1 = cv2.inRange(hsv_image, np.array([0, 50, 50]), np.array([10, 255, 255]))
|
| 76 |
+
red_mask2 = cv2.inRange(hsv_image, np.array([170, 50, 50]), np.array([180, 255, 255]))
|
| 77 |
+
red_mask = cv2.bitwise_or(red_mask1, red_mask2)
|
| 78 |
+
|
| 79 |
+
color_counts = {
|
| 80 |
+
'green': cv2.countNonZero(green_mask),
|
| 81 |
+
'purple': cv2.countNonZero(purple_mask),
|
| 82 |
+
'red': cv2.countNonZero(red_mask)
|
| 83 |
+
}
|
| 84 |
+
return max(color_counts, key=color_counts.get)
|
| 85 |
+
|
| 86 |
+
def predict_card_features(card_image: np.ndarray, shape_detector, fill_model, shape_model, box: list) -> dict:
|
| 87 |
+
"""
|
| 88 |
+
Detect and classify features on a card image.
|
| 89 |
+
"""
|
| 90 |
+
shape_results = shape_detector(card_image)
|
| 91 |
+
card_h, card_w = card_image.shape[:2]
|
| 92 |
+
card_area = card_w * card_h
|
| 93 |
+
|
| 94 |
+
filtered_boxes = [
|
| 95 |
+
[int(x1), int(y1), int(x2), int(y2)]
|
| 96 |
+
for x1, y1, x2, y2 in shape_results[0].boxes.xyxy.cpu().numpy()
|
| 97 |
+
if (x2 - x1) * (y2 - y1) > 0.03 * card_area
|
| 98 |
+
]
|
| 99 |
+
|
| 100 |
+
if not filtered_boxes:
|
| 101 |
+
return {'count': 0, 'color': 'unknown', 'fill': 'unknown', 'shape': 'unknown', 'box': box}
|
| 102 |
+
|
| 103 |
+
fill_input_shape = fill_model.input_shape[1:3]
|
| 104 |
+
shape_input_shape = shape_model.input_shape[1:3]
|
| 105 |
+
fill_imgs, shape_imgs, color_list = [], [], []
|
| 106 |
+
|
| 107 |
+
for fb in filtered_boxes:
|
| 108 |
+
x1, y1, x2, y2 = fb
|
| 109 |
+
shape_img = card_image[y1:y2, x1:x2]
|
| 110 |
+
fill_img = cv2.resize(shape_img, tuple(fill_input_shape)) / 255.0
|
| 111 |
+
shape_img_resized = cv2.resize(shape_img, tuple(shape_input_shape)) / 255.0
|
| 112 |
+
fill_imgs.append(fill_img)
|
| 113 |
+
shape_imgs.append(shape_img_resized)
|
| 114 |
+
color_list.append(predict_color(shape_img))
|
| 115 |
+
|
| 116 |
+
fill_imgs = np.array(fill_imgs)
|
| 117 |
+
shape_imgs = np.array(shape_imgs)
|
| 118 |
+
|
| 119 |
+
fill_preds = fill_model.predict(fill_imgs, batch_size=len(fill_imgs))
|
| 120 |
+
shape_preds = shape_model.predict(shape_imgs, batch_size=len(shape_imgs))
|
| 121 |
+
|
| 122 |
+
fill_labels_list = ['empty', 'full', 'striped']
|
| 123 |
+
shape_labels_list = ['diamond', 'oval', 'squiggle']
|
| 124 |
+
|
| 125 |
+
predicted_fill = [fill_labels_list[np.argmax(pred)] for pred in fill_preds]
|
| 126 |
+
predicted_shape = [shape_labels_list[np.argmax(pred)] for pred in shape_preds]
|
| 127 |
+
|
| 128 |
+
color_label = max(set(color_list), key=color_list.count)
|
| 129 |
+
fill_label = max(set(predicted_fill), key=predicted_fill.count)
|
| 130 |
+
shape_label = max(set(predicted_shape), key=predicted_shape.count)
|
| 131 |
+
|
| 132 |
+
return {'count': len(filtered_boxes), 'color': color_label,
|
| 133 |
+
'fill': fill_label, 'shape': shape_label, 'box': box}
|
| 134 |
+
|
| 135 |
+
def is_set(cards: list) -> bool:
|
| 136 |
+
"""
|
| 137 |
+
Check if a group of cards forms a valid set. For each feature,
|
| 138 |
+
values must be all identical or all distinct.
|
| 139 |
+
"""
|
| 140 |
+
for feature in ['Count', 'Color', 'Fill', 'Shape']:
|
| 141 |
+
if len({card[feature] for card in cards}) not in [1, 3]:
|
| 142 |
+
return False
|
| 143 |
+
return True
|
| 144 |
+
|
| 145 |
+
def find_sets(card_df: pd.DataFrame) -> list:
|
| 146 |
+
"""
|
| 147 |
+
Iterate over all combinations of three cards to identify valid sets.
|
| 148 |
+
"""
|
| 149 |
+
sets_found = []
|
| 150 |
+
for combo in combinations(card_df.iterrows(), 3):
|
| 151 |
+
cards = [entry[1] for entry in combo]
|
| 152 |
+
if is_set(cards):
|
| 153 |
+
sets_found.append({
|
| 154 |
+
'set_indices': [entry[0] for entry in combo],
|
| 155 |
+
'cards': [{feature: card[feature] for feature in
|
| 156 |
+
['Count', 'Color', 'Fill', 'Shape', 'Coordinates']} for card in cards]
|
| 157 |
+
})
|
| 158 |
+
return sets_found
|
| 159 |
+
|
| 160 |
+
def detect_cards_from_image(board_image: np.ndarray, detector) -> list:
|
| 161 |
+
"""
|
| 162 |
+
Extract card regions from the board image using the YOLO card detection model.
|
| 163 |
+
"""
|
| 164 |
+
card_results = detector(board_image)
|
| 165 |
+
card_boxes = card_results[0].boxes.xyxy.cpu().numpy().astype(int)
|
| 166 |
+
return [(board_image[y1:y2, x1:x2], [x1, y1, x2, y2]) for x1, y1, x2, y2 in card_boxes]
|
| 167 |
+
|
| 168 |
+
def classify_cards_from_board_image(board_image: np.ndarray, card_detector, shape_detector, fill_model, shape_model) -> pd.DataFrame:
|
| 169 |
+
"""
|
| 170 |
+
Detect cards from the board image and classify their features.
|
| 171 |
+
"""
|
| 172 |
+
cards = detect_cards_from_image(board_image, card_detector)
|
| 173 |
+
card_data = []
|
| 174 |
+
for card_image, box in cards:
|
| 175 |
+
features = predict_card_features(card_image, shape_detector, fill_model, shape_model, box)
|
| 176 |
+
card_data.append({
|
| 177 |
+
"Count": features['count'],
|
| 178 |
+
"Color": features['color'],
|
| 179 |
+
"Fill": features['fill'],
|
| 180 |
+
"Shape": features['shape'],
|
| 181 |
+
"Coordinates": f"{box[0]}, {box[1]}, {box[2]}, {box[3]}"
|
| 182 |
+
})
|
| 183 |
+
return pd.DataFrame(card_data)
|
| 184 |
+
|
| 185 |
+
def draw_sets_on_image(board_image: np.ndarray, sets_info: list) -> np.ndarray:
|
| 186 |
+
"""
|
| 187 |
+
Draw bounding boxes and labels for each detected set on the board image.
|
| 188 |
+
"""
|
| 189 |
+
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255),
|
| 190 |
+
(255, 255, 0), (255, 0, 255), (0, 255, 255)]
|
| 191 |
+
base_thickness = 8
|
| 192 |
+
base_expansion = 5
|
| 193 |
+
for index, set_info in enumerate(sets_info):
|
| 194 |
+
color = colors[index % len(colors)]
|
| 195 |
+
thickness = base_thickness + 2 * index
|
| 196 |
+
expansion = base_expansion + 15 * index
|
| 197 |
+
for i, card in enumerate(set_info['cards']):
|
| 198 |
+
coordinates = list(map(int, card['Coordinates'].split(',')))
|
| 199 |
+
x1, y1, x2, y2 = coordinates
|
| 200 |
+
x1_exp = max(0, x1 - expansion)
|
| 201 |
+
y1_exp = max(0, y1 - expansion)
|
| 202 |
+
x2_exp = min(board_image.shape[1], x2 + expansion)
|
| 203 |
+
y2_exp = min(board_image.shape[0], y2 + expansion)
|
| 204 |
+
cv2.rectangle(board_image, (x1_exp, y1_exp), (x2_exp, y2_exp), color, thickness)
|
| 205 |
+
if i == 0:
|
| 206 |
+
cv2.putText(board_image, f"Set {index + 1}", (x1_exp, y1_exp - 10),
|
| 207 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, thickness)
|
| 208 |
+
return board_image
|
| 209 |
+
|
| 210 |
+
def classify_and_find_sets_from_array(board_image: np.ndarray, card_detector, shape_detector, fill_model, shape_model) -> (list, np.ndarray):
|
| 211 |
+
"""
|
| 212 |
+
Process the input image: adjust orientation, classify card features, detect sets, and annotate the image.
|
| 213 |
+
"""
|
| 214 |
+
processed_image, was_rotated = check_and_rotate_input_image(board_image, card_detector)
|
| 215 |
+
card_df = classify_cards_from_board_image(processed_image, card_detector, shape_detector, fill_model, shape_model)
|
| 216 |
+
sets_found = find_sets(card_df)
|
| 217 |
+
annotated_image = draw_sets_on_image(processed_image.copy(), sets_found)
|
| 218 |
+
final_image = restore_original_orientation(annotated_image, was_rotated)
|
| 219 |
+
return sets_found, final_image
|
| 220 |
+
|
| 221 |
+
# =============================================================================
|
| 222 |
+
# GRADIO INFERENCE FUNCTION
|
| 223 |
+
# =============================================================================
|
| 224 |
+
|
| 225 |
+
@spaces.GPU()
|
| 226 |
+
def detect_sets(input_image: Image.Image):
|
| 227 |
+
"""
|
| 228 |
+
Process an uploaded image and return the annotated image along with detected sets info.
|
| 229 |
+
"""
|
| 230 |
+
try:
|
| 231 |
+
# Convert the PIL image to OpenCV BGR format
|
| 232 |
+
image_cv = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
|
| 233 |
+
# Run the detection pipeline
|
| 234 |
+
sets_info, annotated_image = classify_and_find_sets_from_array(
|
| 235 |
+
image_cv,
|
| 236 |
+
card_detection_model,
|
| 237 |
+
shape_detection_model,
|
| 238 |
+
fill_classification_model,
|
| 239 |
+
shape_classification_model
|
| 240 |
+
)
|
| 241 |
+
# Convert annotated image back to RGB for display
|
| 242 |
+
annotated_image_rgb = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
|
| 243 |
+
return annotated_image_rgb, json.dumps(sets_info, indent=2)
|
| 244 |
+
except Exception:
|
| 245 |
+
return None, f"Error occurred: {traceback.format_exc()}"
|
| 246 |
+
|
| 247 |
+
# =============================================================================
|
| 248 |
+
# GRADIO INTERFACE
|
| 249 |
+
# =============================================================================
|
| 250 |
+
|
| 251 |
+
with gr.Blocks(css="#col-container { margin: 0 auto; max-width: 800px; }") as demo:
|
| 252 |
+
gr.Markdown("# Set Game Detector\nUpload an image of a Set game board to detect valid sets.")
|
| 253 |
+
|
| 254 |
+
with gr.Row(elem_id="col-container"):
|
| 255 |
+
image_input = gr.Image(label="Upload Set Game Board", type="pil")
|
| 256 |
+
detect_button = gr.Button("Detect Sets")
|
| 257 |
+
|
| 258 |
+
with gr.Row():
|
| 259 |
+
result_image = gr.Image(label="Annotated Image")
|
| 260 |
+
result_info = gr.JSON(label="Detected Sets Info")
|
| 261 |
+
|
| 262 |
+
detect_button.click(
|
| 263 |
+
detect_sets,
|
| 264 |
+
inputs=[image_input],
|
| 265 |
+
outputs=[result_image, result_info]
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
# =============================================================================
|
| 269 |
+
# LAUNCH THE APP
|
| 270 |
+
# =============================================================================
|
| 271 |
+
|
| 272 |
+
demo.launch()
|