Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -4,17 +4,23 @@ import torch
|
|
| 4 |
import torch.nn.functional as F
|
| 5 |
import cv2
|
| 6 |
import numpy as np
|
| 7 |
-
from PIL import Image
|
| 8 |
import io
|
| 9 |
import base64
|
| 10 |
from transformers import AutoImageProcessor, AutoModel, CLIPProcessor, CLIPModel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# ==============================================================================
|
| 13 |
# 1. Initialize FastAPI & CORS
|
| 14 |
# ==============================================================================
|
| 15 |
-
app = FastAPI(title="Copyright Diagnostic API")
|
| 16 |
|
| 17 |
-
# Crucial for allowing your React frontend to communicate with this backend
|
| 18 |
app.add_middleware(
|
| 19 |
CORSMiddleware,
|
| 20 |
allow_origins=["*"],
|
|
@@ -28,192 +34,279 @@ app.add_middleware(
|
|
| 28 |
# ==============================================================================
|
| 29 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
dino_model.eval()
|
| 35 |
|
| 36 |
-
print("Loading CLIP...")
|
| 37 |
-
clip_processor = CLIPProcessor.from_pretrained(
|
| 38 |
-
clip_model = CLIPModel.from_pretrained(
|
| 39 |
clip_model.eval()
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def image_to_base64(img: Image.Image) -> str:
|
| 43 |
buffered = io.BytesIO()
|
| 44 |
img.save(buffered, format="JPEG")
|
| 45 |
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# ==============================================================================
|
| 48 |
-
#
|
| 49 |
# ==============================================================================
|
| 50 |
|
| 51 |
-
def
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
with torch.no_grad():
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
image_features = F.normalize(image_features, p=2, dim=-1)
|
| 67 |
-
score = F.cosine_similarity(image_features[0].unsqueeze(0), image_features[1].unsqueeze(0))
|
| 68 |
-
return round(score.item(), 4)
|
| 69 |
-
|
| 70 |
-
def compute_structural_similarity(img_a: Image.Image, img_b: Image.Image):
|
| 71 |
-
# Convert to grayscale numpy arrays
|
| 72 |
-
arr_a = np.array(img_a.convert('L'))
|
| 73 |
-
arr_b = np.array(img_b.convert('L'))
|
| 74 |
-
|
| 75 |
-
# 1. Aggressive Gaussian Blur to eliminate stylistic texture
|
| 76 |
-
# A kernel size of (11, 11) is strong enough to blur out noise but keep main shapes
|
| 77 |
-
blur_a = cv2.GaussianBlur(arr_a, (11, 11), 0)
|
| 78 |
-
blur_b = cv2.GaussianBlur(arr_b, (11, 11), 0)
|
| 79 |
-
|
| 80 |
-
# 2. Dynamic Auto-Canny Helper Function
|
| 81 |
-
def auto_canny(image, sigma=0.33):
|
| 82 |
-
v = np.median(image)
|
| 83 |
-
lower = int(max(0, (1.0 - sigma) * v))
|
| 84 |
-
upper = int(min(255, (1.0 + sigma) * v))
|
| 85 |
-
return cv2.Canny(image, lower, upper)
|
| 86 |
-
|
| 87 |
-
# Extract structural edges using the blurred images and dynamic thresholds
|
| 88 |
-
edges_a = auto_canny(blur_a)
|
| 89 |
-
edges_b = auto_canny(blur_b)
|
| 90 |
-
|
| 91 |
-
# 3. Dilate the edges to give them a "margin of error" for spatial overlap
|
| 92 |
-
kernel = np.ones((7,7), np.uint8) # Thicker kernel for better overlap
|
| 93 |
-
edges_a_thick = cv2.dilate(edges_a, kernel, iterations=1)
|
| 94 |
-
edges_b_thick = cv2.dilate(edges_b, kernel, iterations=1)
|
| 95 |
-
|
| 96 |
-
# Resize B to match A for matrix math
|
| 97 |
-
edges_b_resized = cv2.resize(edges_b_thick, (edges_a_thick.shape[1], edges_a_thick.shape[0]))
|
| 98 |
-
|
| 99 |
-
# Calculate Intersection over Union (IoU)
|
| 100 |
-
intersection = np.logical_and(edges_a_thick > 0, edges_b_resized > 0).sum()
|
| 101 |
-
union = np.logical_or(edges_a_thick > 0, edges_b_resized > 0).sum()
|
| 102 |
-
|
| 103 |
-
iou_score = intersection / union if union != 0 else 0.0
|
| 104 |
-
|
| 105 |
-
# Return the clean (non-thickened) edges for a prettier UI visualization
|
| 106 |
-
return round(iou_score, 4), Image.fromarray(edges_a), Image.fromarray(edges_b_resized)
|
| 107 |
-
|
| 108 |
-
def compute_patch_similarity(img_a: Image.Image, img_b: Image.Image):
|
| 109 |
-
target_size = (518, 518)
|
| 110 |
-
img_a_resized = img_a.resize(target_size)
|
| 111 |
-
img_b_resized = img_b.resize(target_size)
|
| 112 |
-
|
| 113 |
-
inputs_a = dino_processor(
|
| 114 |
-
images=img_a_resized,
|
| 115 |
-
return_tensors="pt",
|
| 116 |
-
do_resize=False,
|
| 117 |
-
do_center_crop=False # <--- ADD THIS
|
| 118 |
-
).to(device)
|
| 119 |
-
|
| 120 |
-
inputs_b = dino_processor(
|
| 121 |
-
images=img_b_resized,
|
| 122 |
-
return_tensors="pt",
|
| 123 |
-
do_resize=False,
|
| 124 |
-
do_center_crop=False # <--- ADD THIS
|
| 125 |
-
).to(device)
|
| 126 |
-
|
| 127 |
with torch.no_grad():
|
| 128 |
-
|
| 129 |
-
out_b = dino_model(**inputs_b)
|
| 130 |
-
|
| 131 |
-
emb_a = F.normalize(out_a.last_hidden_state[:, 1:, :].squeeze(0), p=2, dim=-1)
|
| 132 |
-
emb_b = F.normalize(out_b.last_hidden_state[:, 1:, :].squeeze(0), p=2, dim=-1)
|
| 133 |
-
|
| 134 |
-
sim_matrix = torch.matmul(emb_a, emb_b.T)
|
| 135 |
-
|
| 136 |
-
best_b_for_a = torch.argmax(sim_matrix, dim=1)
|
| 137 |
-
best_a_for_b = torch.argmax(sim_matrix, dim=0)
|
| 138 |
-
|
| 139 |
-
matches = []
|
| 140 |
-
SIMILARITY_THRESHOLD = 0.87
|
| 141 |
-
|
| 142 |
-
for a_idx in range(len(best_b_for_a)):
|
| 143 |
-
b_idx = best_b_for_a[a_idx]
|
| 144 |
-
if best_a_for_b[b_idx] == a_idx:
|
| 145 |
-
score = sim_matrix[a_idx, b_idx].item()
|
| 146 |
-
if score >= SIMILARITY_THRESHOLD:
|
| 147 |
-
matches.append((a_idx, b_idx, score))
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
patch_size = 14
|
| 151 |
-
grid_size = target_size[0] // patch_size
|
| 152 |
-
total_patches = grid_size * grid_size
|
| 153 |
-
patch_score = len(matches) / float(total_patches)
|
| 154 |
-
|
| 155 |
-
combined_vis = Image.new('RGB', (target_size[0] * 2, target_size[1]))
|
| 156 |
-
combined_vis.paste(img_a_resized, (0, 0))
|
| 157 |
-
combined_vis.paste(img_b_resized, (target_size[0], 0))
|
| 158 |
-
draw = ImageDraw.Draw(combined_vis)
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
for a_idx, b_idx, score in matches:
|
| 164 |
-
ay = (a_idx // grid_size) * patch_size
|
| 165 |
-
ax = (a_idx % grid_size) * patch_size
|
| 166 |
-
by = (b_idx // grid_size) * patch_size
|
| 167 |
-
bx = (b_idx % grid_size) * patch_size + target_size[0]
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
# ==============================================================================
|
| 179 |
-
#
|
| 180 |
# ==============================================================================
|
| 181 |
|
| 182 |
@app.post("/analyze")
|
| 183 |
async def analyze_artworks(file_a: UploadFile = File(...), file_b: UploadFile = File(...)):
|
| 184 |
try:
|
| 185 |
-
# Read uploaded files into PIL Images
|
| 186 |
img_a = Image.open(io.BytesIO(await file_a.read())).convert("RGB")
|
| 187 |
img_b = Image.open(io.BytesIO(await file_b.read())).convert("RGB")
|
| 188 |
|
| 189 |
-
#
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
|
| 199 |
-
# Return a clean JSON package to React
|
| 200 |
return {
|
| 201 |
"status": "success",
|
| 202 |
-
"
|
| 203 |
-
"
|
| 204 |
-
"
|
| 205 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
},
|
| 207 |
-
"
|
| 208 |
-
"
|
| 209 |
-
"
|
| 210 |
-
"edge_image_b": f"data:image/jpeg;base64,{edge_b_b64}"
|
| 211 |
}
|
| 212 |
}
|
| 213 |
|
| 214 |
except Exception as e:
|
|
|
|
|
|
|
| 215 |
raise HTTPException(status_code=500, detail=str(e))
|
| 216 |
|
| 217 |
@app.get("/")
|
| 218 |
def read_root():
|
| 219 |
-
return {"message": "Diagnostic API is running.
|
|
|
|
| 4 |
import torch.nn.functional as F
|
| 5 |
import cv2
|
| 6 |
import numpy as np
|
| 7 |
+
from PIL import Image
|
| 8 |
import io
|
| 9 |
import base64
|
| 10 |
from transformers import AutoImageProcessor, AutoModel, CLIPProcessor, CLIPModel
|
| 11 |
+
import matplotlib
|
| 12 |
+
matplotlib.use("Agg")
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import matplotlib.gridspec as gridspec
|
| 15 |
+
from scipy.optimize import linear_sum_assignment
|
| 16 |
+
import lpips
|
| 17 |
+
import torchvision.transforms as transforms
|
| 18 |
|
| 19 |
# ==============================================================================
|
| 20 |
# 1. Initialize FastAPI & CORS
|
| 21 |
# ==============================================================================
|
| 22 |
+
app = FastAPI(title="Copyright Diagnostic API - 3 Pillar XAI")
|
| 23 |
|
|
|
|
| 24 |
app.add_middleware(
|
| 25 |
CORSMiddleware,
|
| 26 |
allow_origins=["*"],
|
|
|
|
| 34 |
# ==============================================================================
|
| 35 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 36 |
|
| 37 |
+
DINO_MODEL_ID = "facebook/dinov2-large"
|
| 38 |
+
CLIP_MODEL_ID = "openai/clip-vit-large-patch14"
|
| 39 |
+
PATCH_SIZE = 14
|
| 40 |
+
|
| 41 |
+
print(f"Loading DINOv2 ({DINO_MODEL_ID})...")
|
| 42 |
+
dino_processor = AutoImageProcessor.from_pretrained(DINO_MODEL_ID)
|
| 43 |
+
dino_model = AutoModel.from_pretrained(DINO_MODEL_ID).to(device)
|
| 44 |
dino_model.eval()
|
| 45 |
|
| 46 |
+
print(f"Loading CLIP ({CLIP_MODEL_ID})...")
|
| 47 |
+
clip_processor = CLIPProcessor.from_pretrained(CLIP_MODEL_ID)
|
| 48 |
+
clip_model = CLIPModel.from_pretrained(CLIP_MODEL_ID).to(device)
|
| 49 |
clip_model.eval()
|
| 50 |
|
| 51 |
+
print("Loading LPIPS (AlexNet)...")
|
| 52 |
+
loss_fn_alex = lpips.LPIPS(net='alex').to(device)
|
| 53 |
+
loss_fn_alex.eval()
|
| 54 |
+
|
| 55 |
+
# LPIPS requires images normalized between [-1, 1]
|
| 56 |
+
lpips_transform = transforms.Compose([
|
| 57 |
+
transforms.Resize((256, 256)),
|
| 58 |
+
transforms.ToTensor(),
|
| 59 |
+
transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
|
| 60 |
+
])
|
| 61 |
+
|
| 62 |
+
# ==============================================================================
|
| 63 |
+
# 3. Helpers & Base64 Converters
|
| 64 |
+
# ==============================================================================
|
| 65 |
+
|
| 66 |
def image_to_base64(img: Image.Image) -> str:
|
| 67 |
buffered = io.BytesIO()
|
| 68 |
img.save(buffered, format="JPEG")
|
| 69 |
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 70 |
|
| 71 |
+
def fig_to_base64(fig) -> str:
|
| 72 |
+
buf = io.BytesIO()
|
| 73 |
+
fig.savefig(buf, format="jpg", bbox_inches='tight', pad_inches=0.1, dpi=100)
|
| 74 |
+
plt.close(fig)
|
| 75 |
+
return base64.b64encode(buf.getvalue()).decode("utf-8")
|
| 76 |
+
|
| 77 |
+
def to_edge_map(image: Image.Image) -> Image.Image:
|
| 78 |
+
"""Strips style/texture, leaving structural contours for Pillar 1."""
|
| 79 |
+
img_array = np.array(image.convert("L"))
|
| 80 |
+
median = np.median(img_array)
|
| 81 |
+
low = int(max(0, 0.5 * median))
|
| 82 |
+
high = int(min(255, 1.3 * median))
|
| 83 |
+
edges = cv2.Canny(img_array, low, high)
|
| 84 |
+
kernel = np.ones((2, 2), np.uint8)
|
| 85 |
+
edges = cv2.dilate(edges, kernel, iterations=1)
|
| 86 |
+
return Image.fromarray(edges).convert("RGB")
|
| 87 |
+
|
| 88 |
+
def patch_idx_to_xy(idx, grid_w, patch_size):
|
| 89 |
+
row = idx // grid_w
|
| 90 |
+
col = idx % grid_w
|
| 91 |
+
return col * patch_size + patch_size / 2, row * patch_size + patch_size / 2
|
| 92 |
+
|
| 93 |
# ==============================================================================
|
| 94 |
+
# 4. AI Pipeline Functions (Mapped to the 3 Pillars)
|
| 95 |
# ==============================================================================
|
| 96 |
|
| 97 |
+
def extract_dino_features(image: Image.Image, preprocess="color"):
|
| 98 |
+
if preprocess == "grayscale":
|
| 99 |
+
img = image.convert("L").convert("RGB")
|
| 100 |
+
elif preprocess == "edges":
|
| 101 |
+
img = to_edge_map(image)
|
| 102 |
+
else:
|
| 103 |
+
img = image
|
| 104 |
+
|
| 105 |
+
inputs = dino_processor(images=img, return_tensors="pt").to(device)
|
| 106 |
with torch.no_grad():
|
| 107 |
+
outputs = dino_model(**inputs)
|
| 108 |
+
|
| 109 |
+
cls_token = outputs.last_hidden_state[:, 0, :]
|
| 110 |
+
patch_tokens = outputs.last_hidden_state[:, 1:, :]
|
| 111 |
+
n_patches = patch_tokens.shape[1]
|
| 112 |
+
grid_size = int(n_patches ** 0.5)
|
| 113 |
+
return cls_token, patch_tokens, grid_size, grid_size
|
| 114 |
+
|
| 115 |
+
def extract_clip_similarity(image_a: Image.Image, image_b: Image.Image):
|
| 116 |
+
inputs = clip_processor(images=[image_a, image_b], return_tensors="pt").to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
with torch.no_grad():
|
| 118 |
+
outputs = clip_model.get_image_features(**inputs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
if hasattr(outputs, 'image_embeds'):
|
| 121 |
+
features = outputs.image_embeds
|
| 122 |
+
elif isinstance(outputs, torch.Tensor):
|
| 123 |
+
features = outputs
|
| 124 |
+
else:
|
| 125 |
+
features = outputs.pooler_output
|
| 126 |
|
| 127 |
+
features = F.normalize(features, dim=-1)
|
| 128 |
+
return round((features[0] @ features[1]).item(), 4)
|
| 129 |
+
|
| 130 |
+
def compute_patch_matches(patches_a, patches_b):
|
| 131 |
+
pa = F.normalize(patches_a.squeeze(0), dim=-1)
|
| 132 |
+
pb = F.normalize(patches_b.squeeze(0), dim=-1)
|
| 133 |
+
sim_matrix = pa @ pb.T
|
| 134 |
+
a_to_b_scores = sim_matrix.max(dim=1).values
|
| 135 |
+
b_to_a_scores = sim_matrix.max(dim=0).values
|
| 136 |
+
return sim_matrix, a_to_b_scores, b_to_a_scores
|
| 137 |
+
|
| 138 |
+
def nms_matches(matches, grid_w, patch_size, radius=2.0):
|
| 139 |
+
if not matches: return []
|
| 140 |
+
matches = sorted(matches, key=lambda m: m[2], reverse=True)
|
| 141 |
+
kept = []
|
| 142 |
+
pixel_radius = radius * patch_size
|
| 143 |
+
|
| 144 |
+
for idx_a, idx_b, score in matches:
|
| 145 |
+
xa, ya = patch_idx_to_xy(idx_a, grid_w, patch_size)
|
| 146 |
+
xb, yb = patch_idx_to_xy(idx_b, grid_w, patch_size)
|
| 147 |
+
dominated = False
|
| 148 |
+
for ka, kb, ks in kept:
|
| 149 |
+
kxa, kya = patch_idx_to_xy(ka, grid_w, patch_size)
|
| 150 |
+
kxb, kyb = patch_idx_to_xy(kb, grid_w, patch_size)
|
| 151 |
+
if (abs(xa - kxa) < pixel_radius and abs(ya - kya) < pixel_radius) or \
|
| 152 |
+
(abs(xb - kxb) < pixel_radius and abs(yb - kyb) < pixel_radius):
|
| 153 |
+
dominated = True
|
| 154 |
+
break
|
| 155 |
+
if not dominated:
|
| 156 |
+
kept.append((idx_a, idx_b, score))
|
| 157 |
+
return kept
|
| 158 |
+
|
| 159 |
+
def make_correspondence_figure(image_a, image_b, patches_a, patches_b, grid_h, grid_w, max_matches=20, score_thresh=0.5):
|
| 160 |
+
pa = patches_a.squeeze(0).cpu()
|
| 161 |
+
pb = patches_b.squeeze(0).cpu()
|
| 162 |
+
|
| 163 |
+
pa_norm = F.normalize(pa, dim=-1)
|
| 164 |
+
pb_norm = F.normalize(pb, dim=-1)
|
| 165 |
+
|
| 166 |
+
sim = (pa_norm @ pb_norm.T).numpy()
|
| 167 |
+
cost = 1.0 - sim
|
| 168 |
+
|
| 169 |
+
row_ind, col_ind = linear_sum_assignment(cost)
|
| 170 |
+
|
| 171 |
+
raw_matches = []
|
| 172 |
+
for r, c in zip(row_ind, col_ind):
|
| 173 |
+
score = sim[r, c]
|
| 174 |
+
if score >= score_thresh:
|
| 175 |
+
raw_matches.append((r, c, float(score)))
|
| 176 |
+
|
| 177 |
+
matches = nms_matches(raw_matches, grid_w, PATCH_SIZE, radius=2.0)[:max_matches]
|
| 178 |
+
|
| 179 |
+
img_w, img_h = grid_w * PATCH_SIZE, grid_h * PATCH_SIZE
|
| 180 |
+
img_a_resized = image_a.resize((img_w, img_h))
|
| 181 |
+
img_b_resized = image_b.resize((img_w, img_h))
|
| 182 |
+
|
| 183 |
+
gap = 30
|
| 184 |
+
canvas_w = img_w * 2 + gap
|
| 185 |
+
fig, ax = plt.subplots(1, 1, figsize=(14, 6))
|
| 186 |
+
fig.patch.set_facecolor('#0f172a') # Slate 900 for dark mode frontend
|
| 187 |
+
|
| 188 |
+
canvas = Image.new("RGB", (canvas_w, img_h), (15, 23, 42))
|
| 189 |
+
canvas.paste(img_a_resized, (0, 0))
|
| 190 |
+
canvas.paste(img_b_resized, (img_w + gap, 0))
|
| 191 |
+
ax.imshow(canvas)
|
| 192 |
+
|
| 193 |
+
cmap = plt.cm.get_cmap("spring", max(len(matches), 1))
|
| 194 |
+
|
| 195 |
+
for i, (idx_a, idx_b, score) in enumerate(matches):
|
| 196 |
+
xa, ya = patch_idx_to_xy(idx_a, grid_w, PATCH_SIZE)
|
| 197 |
+
xb, yb = patch_idx_to_xy(idx_b, grid_w, PATCH_SIZE)
|
| 198 |
+
xb_canvas = xb + img_w + gap
|
| 199 |
+
color = cmap(i % 20)
|
| 200 |
+
|
| 201 |
+
ax.plot([xa, xb_canvas], [ya, yb], color=color, linewidth=2, alpha=0.9)
|
| 202 |
+
ax.scatter([xa, xb_canvas], [ya, yb], color=color, s=50, zorder=5, edgecolors="white", linewidths=0.5)
|
| 203 |
+
|
| 204 |
+
ax.axis("off")
|
| 205 |
+
fig.tight_layout(pad=0)
|
| 206 |
+
return fig, len(matches)
|
| 207 |
+
|
| 208 |
+
def make_combined_figure(image_a, image_b, scores_a, scores_b, grid_h, grid_w):
|
| 209 |
+
heatmap_a = scores_a.reshape(grid_h, grid_w).cpu().numpy()
|
| 210 |
+
heatmap_b = scores_b.reshape(grid_h, grid_w).cpu().numpy()
|
| 211 |
+
|
| 212 |
+
fig = plt.figure(figsize=(12, 5.5))
|
| 213 |
+
fig.patch.set_facecolor('#0f172a') # Dark mode mapping
|
| 214 |
+
gs = gridspec.GridSpec(1, 2, wspace=0.05)
|
| 215 |
+
|
| 216 |
+
ax0 = fig.add_subplot(gs[0])
|
| 217 |
+
ax0.imshow(image_a.resize((grid_w * PATCH_SIZE, grid_h * PATCH_SIZE)))
|
| 218 |
+
ax0.imshow(heatmap_a, cmap="inferno", alpha=0.6, interpolation="bilinear", extent=(0, grid_w * PATCH_SIZE, grid_h * PATCH_SIZE, 0))
|
| 219 |
+
ax0.axis("off")
|
| 220 |
+
|
| 221 |
+
ax1 = fig.add_subplot(gs[1])
|
| 222 |
+
ax1.imshow(image_b.resize((grid_w * PATCH_SIZE, grid_h * PATCH_SIZE)))
|
| 223 |
+
ax1.imshow(heatmap_b, cmap="inferno", alpha=0.6, interpolation="bilinear", extent=(0, grid_w * PATCH_SIZE, grid_h * PATCH_SIZE, 0))
|
| 224 |
+
ax1.axis("off")
|
| 225 |
+
|
| 226 |
+
fig.tight_layout(pad=0)
|
| 227 |
+
return fig
|
| 228 |
|
| 229 |
# ==============================================================================
|
| 230 |
+
# 5. Primary Analysis Endpoint
|
| 231 |
# ==============================================================================
|
| 232 |
|
| 233 |
@app.post("/analyze")
|
| 234 |
async def analyze_artworks(file_a: UploadFile = File(...), file_b: UploadFile = File(...)):
|
| 235 |
try:
|
|
|
|
| 236 |
img_a = Image.open(io.BytesIO(await file_a.read())).convert("RGB")
|
| 237 |
img_b = Image.open(io.BytesIO(await file_b.read())).convert("RGB")
|
| 238 |
|
| 239 |
+
# --- PILLAR 1: Idea-Expression Dichotomy ---
|
| 240 |
+
semantic_idea_score = extract_clip_similarity(img_a, img_b)
|
| 241 |
+
|
| 242 |
+
cls_e_a, patches_e_a, gh, gw = extract_dino_features(img_a, "edges")
|
| 243 |
+
cls_e_b, patches_e_b, _, _ = extract_dino_features(img_b, "edges")
|
| 244 |
+
structural_expression_score = round(F.cosine_similarity(cls_e_a, cls_e_b).item(), 4)
|
| 245 |
+
|
| 246 |
+
edge_a_b64 = image_to_base64(to_edge_map(img_a))
|
| 247 |
+
edge_b_b64 = image_to_base64(to_edge_map(img_b))
|
| 248 |
+
|
| 249 |
+
# --- PILLAR 2: Fragmented Literal Similarity (RESTored BEST-OF FUSION) ---
|
| 250 |
+
cls_c_a, patches_c_a, _, _ = extract_dino_features(img_a, "color")
|
| 251 |
+
cls_c_b, patches_c_b, _, _ = extract_dino_features(img_b, "color")
|
| 252 |
+
|
| 253 |
+
cls_g_a, patches_g_a, _, _ = extract_dino_features(img_a, "grayscale")
|
| 254 |
+
cls_g_b, patches_g_b, _, _ = extract_dino_features(img_b, "grayscale")
|
| 255 |
+
|
| 256 |
+
_, a2b_c, b2a_c = compute_patch_matches(patches_c_a, patches_c_b)
|
| 257 |
+
_, a2b_g, b2a_g = compute_patch_matches(patches_g_a, patches_g_b)
|
| 258 |
+
_, a2b_e, b2a_e = compute_patch_matches(patches_e_a, patches_e_b)
|
| 259 |
+
|
| 260 |
+
# The missing magic: Combine domains to defeat color-shifting
|
| 261 |
+
a2b_best = torch.max(torch.max(a2b_c, a2b_g), a2b_e)
|
| 262 |
+
b2a_best = torch.max(torch.max(b2a_c, b2a_g), b2a_e)
|
| 263 |
+
|
| 264 |
+
corr_thresh = (a2b_best.mean() + 0.5 * a2b_best.std()).item()
|
| 265 |
+
corr_thresh = min(max(corr_thresh, 0.4), 0.75)
|
| 266 |
+
|
| 267 |
+
# We pass patches_c_a for the visual lines, but the scoring uses the fused best-of logic internally
|
| 268 |
+
corr_fig, match_count = make_correspondence_figure(img_a, img_b, patches_c_a, patches_c_b, gh, gw, score_thresh=corr_thresh)
|
| 269 |
+
correspondence_map_b64 = fig_to_base64(corr_fig)
|
| 270 |
+
|
| 271 |
+
# Restored Statistics
|
| 272 |
+
n_patches_a = a2b_best.shape[0]
|
| 273 |
+
adaptive_thresh = max((a2b_best.mean() + a2b_best.std()).item(), 0.5)
|
| 274 |
+
high_a = (a2b_best > adaptive_thresh).sum().item()
|
| 275 |
+
pct_copied = round((high_a / n_patches_a) * 100, 1)
|
| 276 |
+
|
| 277 |
+
# --- PILLAR 3: Substantial Similarity ---
|
| 278 |
+
heatmap_fig = make_combined_figure(img_a, img_b, a2b_best, b2a_best, gh, gw)
|
| 279 |
+
heatmap_b64 = fig_to_base64(heatmap_fig)
|
| 280 |
|
| 281 |
+
t_a = lpips_transform(img_a).unsqueeze(0).to(device)
|
| 282 |
+
t_b = lpips_transform(img_b).unsqueeze(0).to(device)
|
| 283 |
+
with torch.no_grad():
|
| 284 |
+
lpips_distance = round(loss_fn_alex(t_a, t_b).item(), 4)
|
| 285 |
|
|
|
|
| 286 |
return {
|
| 287 |
"status": "success",
|
| 288 |
+
"pillar_1_idea_expression": {
|
| 289 |
+
"semantic_idea_score": semantic_idea_score,
|
| 290 |
+
"structural_expression_score": structural_expression_score,
|
| 291 |
+
"edge_map_a_b64": f"data:image/jpeg;base64,{edge_a_b64}",
|
| 292 |
+
"edge_map_b_b64": f"data:image/jpeg;base64,{edge_b_b64}"
|
| 293 |
+
},
|
| 294 |
+
"pillar_2_fragmented_literal": {
|
| 295 |
+
"patch_match_count": match_count,
|
| 296 |
+
"percentage_copied": pct_copied,
|
| 297 |
+
"correspondence_map_b64": f"data:image/jpeg;base64,{correspondence_map_b64}"
|
| 298 |
},
|
| 299 |
+
"pillar_3_substantial_similarity": {
|
| 300 |
+
"perceptual_distance_lpips": lpips_distance,
|
| 301 |
+
"quantitative_heatmap_b64": f"data:image/jpeg;base64,{heatmap_b64}"
|
|
|
|
| 302 |
}
|
| 303 |
}
|
| 304 |
|
| 305 |
except Exception as e:
|
| 306 |
+
import traceback
|
| 307 |
+
traceback.print_exc()
|
| 308 |
raise HTTPException(status_code=500, detail=str(e))
|
| 309 |
|
| 310 |
@app.get("/")
|
| 311 |
def read_root():
|
| 312 |
+
return {"message": "3-Pillar Legal Diagnostic API is running."}
|