digital-art-api / lib /phash.py
Ruzzel Mendoza
Show Multiple Matches for Plagiarized Artworks
1a39441
Raw History Blame
5.52 kB
from io import BytesIO
from typing import Dict, Any
import requests
from PIL import Image, ImageOps, ImageFilter
import imagehash
HASH_SIZE = 8
MAX_DISTANCE = HASH_SIZE * HASH_SIZE
# -----------------------------
# IMAGE PREPROCESSING
# -----------------------------
def preprocess_image(img: Image.Image):
if img.mode in ("RGBA", "LA"):
bg = Image.new("RGB", img.size, (255, 255, 255))
bg.paste(img, mask=img.split()[-1])
img = bg
else:
img = img.convert("RGB")
img = img.convert("L")
img = img.filter(ImageFilter.GaussianBlur(radius=1))
return img
# -----------------------------
# HASH GENERATION
# -----------------------------
def compute_hashes(img: Image.Image):
return {
"phash": str(imagehash.phash(img, hash_size=HASH_SIZE)),
"dhash": str(imagehash.dhash(img, hash_size=HASH_SIZE)),
"whash": str(imagehash.whash(img, hash_size=HASH_SIZE))
}
def generate_transform_hashes(img: Image.Image):
transforms = {
"0": img,
"90": img.rotate(90, expand=True),
"180": img.rotate(180, expand=True),
"270": img.rotate(270, expand=True),
"mirror": ImageOps.mirror(img),
"flip": ImageOps.flip(img)
}
return {k: compute_hashes(v) for k, v in transforms.items()}
def generate_block_hashes(img: Image.Image):
w, h = img.size
blocks = {
"top_left": img.crop((0, 0, w//2, h//2)),
"top_right": img.crop((w//2, 0, w, h//2)),
"bottom_left": img.crop((0, h//2, w//2, h)),
"bottom_right": img.crop((w//2, h//2, w, h)),
"center": img.crop((w//4, h//4, 3*w//4, 3*h//4))
}
return {k: compute_hashes(preprocess_image(v)) for k, v in blocks.items()}
def generate_hashes(image_file):
try:
img = Image.open(image_file)
img = preprocess_image(img)
return {
"transforms": generate_transform_hashes(img),
"blocks": generate_block_hashes(img)
}
except Exception as e:
print("Error generating hashes:", e)
return None
def generate_hash_from_url(url):
try:
headers = {"User-Agent": "Mozilla/5.0"}
resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
return generate_hashes(BytesIO(resp.content))
except Exception as e:
print("Error fetching URL:", e)
return None
# -----------------------------
# DISTANCE CALCULATION
# -----------------------------
def hamming(hash1, hash2):
return imagehash.hex_to_hash(hash1) - imagehash.hex_to_hash(hash2)
def weighted_distance(hash1, hash2, weights=None):
if weights is None:
weights = {"phash": 0.8, "dhash": 0.1, "whash": 0.1}
total, weight_sum = 0, 0
for algo, w in weights.items():
total += hamming(hash1[algo], hash2[algo]) * w
weight_sum += w
return total / weight_sum
def compare_transforms(hashes1, hashes2):
min_dist = float("inf")
for t1 in hashes1:
for t2 in hashes2:
d = weighted_distance(hashes1[t1], hashes2[t2])
if d < min_dist:
min_dist = d
return (1 - min_dist / MAX_DISTANCE) * 100
def compare_blocks(blocks1, blocks2):
min_dist = float("inf")
for b1 in blocks1:
for b2 in blocks2:
d = weighted_distance(blocks1[b1], blocks2[b2])
if d < min_dist:
min_dist = d
return (1 - min_dist / MAX_DISTANCE) * 100
def compare_hash_sets(hashset1, hashset2):
transform_sim = compare_transforms(hashset1["transforms"], hashset2["transforms"])
block_sim = compare_blocks(hashset1["blocks"], hashset2["blocks"])
final_score = 0.3 * transform_sim + 0.7 * block_sim
return {
"transform_similarity": round(transform_sim, 2),
"block_similarity": round(block_sim, 2),
"final_similarity": round(final_score, 2)
}
def scan_database(upload_hashes, artworks):
best_match = None
best_score = -1
best_match_list = []
for art in artworks:
db_hashes = art["perceptual_hash"]
score = compare_hash_sets(upload_hashes, db_hashes)["final_similarity"]
if score > best_score:
best_score = score
best_match = {"artwork_id": art["id"], "similarity": best_score, "url": art["c_secure_url"]}
best_match_list.insert(0, best_match)
return best_match_list[:5] if len(best_match_list) >= 5 else best_match_list
def generate_hash_from_serp(payload):
hashed = {}
for i, item in enumerate(payload.get("organic", [])):
h = generate_hash_from_url(item["imageUrl"])
if h:
hashed[str(i)] = {
"hashes": h,
"source": item["source"],
"link": item["link"],
"imageUrl": item["imageUrl"]
}
return hashed
def check_distance_between_serp(uploaded, searched):
best_data = {}
best_score = -1
best_data_list = []
for url, image_data in searched.items():
sim = compare_hash_sets(uploaded, image_data["hashes"])["final_similarity"]
if sim > best_score:
best_score = sim
best_data = {
"source": image_data["source"],
"link": image_data["link"],
"url": image_data["imageUrl"],
"similarity": round(sim, 2)
}
best_data_list.insert(0, best_data)
return best_data_list[:5] if len(best_data_list) >= 5 else best_data_list