import numpy as np import gradio as gr from PIL import Image from skimage.metrics import structural_similarity as ssim import cv2 import pytesseract from difflib import SequenceMatcher # Function to calculate SSIM between two images def calculate_ssim(img1, img2): img1_gray = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY) img2_gray = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY) return ssim(img1_gray, img2_gray) # Function to compare trademarks based on text similarity def compare_text(trademark1, trademark2): text1 = pytesseract.image_to_string(trademark1).lower() text2 = pytesseract.image_to_string(trademark2).lower() similarity_ratio = SequenceMatcher(None, text1, text2).ratio() return similarity_ratio # Function to compare trademarks based on color similarity def compare_colors(trademark1, trademark2): trademark1 = trademark1.convert("RGB") trademark2 = trademark2.convert("RGB") colors1 = trademark1.getcolors(trademark1.size[0] * trademark1.size[1]) colors2 = trademark2.getcolors(trademark2.size[0] * trademark2.size[1]) color_vector1 = np.zeros(3) color_vector2 = np.zeros(3) for count, color in colors1: color_vector1 += np.array(color) * count for count, color in colors2: color_vector2 += np.array(color) * count color_vector1 /= trademark1.size[0] * trademark1.size[1] color_vector2 /= trademark2.size[0] * trademark2.size[1] color_similarity = 1 - np.linalg.norm(color_vector1 - color_vector2) return color_similarity # Function to compare trademarks based on multiple aspects def compare_trademarks(trademark1, trademark2): # Resize images to a consistent size size = (300, 300) trademark1_resized = trademark1.resize(size) trademark2_resized = trademark2.resize(size) ssim_score = calculate_ssim(np.array(trademark1_resized), np.array(trademark2_resized)) text_similarity = compare_text(trademark1, trademark2) color_similarity = compare_colors(trademark1, trademark2) # Adjust weights based on the importance of each aspect ssim_weight = 0.6 text_weight = 0.2 color_weight = 0.2 overall_similarity = (ssim_weight * ssim_score) + (text_weight * text_similarity) + (color_weight * color_similarity) return overall_similarity # Function to perform trademark conflict prevention def prevent_trademark_conflict(trademark1, trademark2): similarity_score = compare_trademarks(trademark1, trademark2) result = f"Trademark Similarity Score: {similarity_score:.4f}" return result iface = gr.Interface( fn=prevent_trademark_conflict, inputs=[ gr.inputs.Image(type="pil", label="Trademark Image 1"), gr.inputs.Image(type="pil", label="Trademark Image 2") ], outputs="text", title="Trademark Conflict Prevention", description="Upload two trademark images to prevent conflict." ) iface.launch()