Build a duplicate cluster resolver: content hashes, URL signals, and action suggestions.
- User
Build a duplicate cluster resolver: content hashes, URL signals, and action suggestions.
Assistant
Build a duplicate cluster resolver: content hashes, URL signals, and action suggestions.
The user wants me to build a "duplicate cluster resolver." This tool should be able to identify groups (clusters) of digital assets or content that are duplicates or near-duplicates of each other. It needs to handle three specific components:
This is a software design and implementation task. I will provide a comprehensive solution, likely in Python, as it's the standard language for data processing and has great libraries for hashing and URL handling.
Phase 1: Conceptual Architecture
Phase 2: Component Breakdown & Implementation Details
Content Hashing:
hashlib.md5(content).hexdigest()datasketch, though I should mention them). Let's stick to exact MD5 for the core logic but implement a "Text Normalizer" (remove whitespace) to catch "soft" duplicates.URL Signals (The "Smart" part):
www vs non-www, http vs https, trailing slashes, query parameters (session IDs are notorious).Clustering:
UnionFind class.Action Suggestions:
Phase 3: Drafting the Code Structure
Class DuplicateResolver
add_item(url, content, metadata)process() -> Groups items.generate_actions() -> Output report.Helper Functions:
normalize_url(url)compute_hash(content)Phase 4: Refining the Solution
hashlib, urllib, re. I won't use networkx or datasketch to keep it lightweight, but I'll implement a basic DSU (Disjoint Set Union) manually.Phase 5: Addressing Specific Prompt Requirements
utm_source, session_id).Self-Correction during thought process:
Initial thought: Should I do fuzzy matching (LSH)?
Correction: Fuzzy matching requires external heavy libraries. The prompt asks for a "resolver," implying logic over just raw matching. I will implement exact matching but layer "URL Normalization" on top to catch cases where site.com/page and site.com/page? render identical content but look different to a naive hasher.
Let's refine the URL signals.
If hash(content_a) == hash(content_b), they are duplicates.
How do we pick the winner?
Plan:
Let's write the Python code. I will structure it as a class-based library with a usage example.
Key Python features:
urllib.parse for URL handling.hashlib for hashing.collections.defaultdict for grouping.Edge case: What if the content is empty? Handle gracefully.
Code Skeleton:
class DuplicateClusterResolver:
def __init__(self):
self.items = []
self.hash_map = {} # hash -> [ids]
self.clusters = {} # id -> cluster_id
def add_url(self, url, content, metadata):
# compute hash
# normalize url
# store
pass
def resolve(self):
# Group by hash
# Resolve clusters
# Pick canonical
# Suggest actions
pass
This looks solid. I will add comments explaining the "Why" behind the URL signal logic (e.g., why removing query params matters). I'll provide a mock dataset to run through it.
Final Polish: The prompt asks for "Action Suggestions." I should make these explicit.
REDIRECT_301: Hard merge.CANONICAL_TAG: Soft merge (keep both, tell Google they are same).NOINDEX: Remove from index.DELETE: Physical deletion.I will implement a scoring system for the "Canonical" URL.
Let's generate the response. This solution implements a Duplicate Cluster Resolver in Python. It detects near-duplicate and exact-duplicate web pages by combining cryptographic hashing with URL normalization heuristics.
It is designed to be run as a script or integrated into a larger data pipeline.
http vs https), and query parameter noise (like utm_source).import hashlib
import re
from urllib.parse import urlparse, urlunparse, parse_qsl, urlencode
from collections import defaultdict
class URLNormalizer:
"""
Handles URL Signal processing: cleaning, normalizing, and identifying structural duplicates.
"""
@staticmethod
def normalize(url):
"""
Standardizes a URL for comparison.
- Lowercase host
- Removes default ports
- Removes common tracking parameters (utm_*, session_id)
- Removes trailing slash (optional, depends on config)
"""
parsed = urlparse(url)
# Lowercase netloc (domain)
netloc = parsed.netloc.lower()
# Remove www. if desired for strict domain grouping (optional)
# if netloc.startswith("www."): netloc = netloc[4:]
# Filter query parameters
tracked_params = {'utm_source', 'utm_medium', 'utm_campaign', 'sessionid', 'ref'}
query_params = parse_qsl(parsed.query)
clean_params = [(k, v) for k, v in query_params if k.lower() not in tracked_params]
clean_query = urlencode(clean_params)
# Reconstruct URL (Strip fragments #)
normalized = urlunparse((
parsed.scheme,
netloc,
parsed.path,
parsed.params,
clean_query,
None # No fragment
))
return normalized
@staticmethod
def get_signal_score(url_a, url_b):
"""
Returns a similarity score based on URL structure.
Helps determine if two distinct content hashes are actually the same page (dynamic content).
"""
norm_a = URLNormalizer.normalize(url_a)
norm_b = URLNormalizer.normalize(url_b)
if norm_a == norm_b:
return 1.0 # Exact URL match (ignoring tracking params)
# Check for Trailing Slash mismatch
if norm_a.rstrip('/') == norm_b.rstrip('/'):
return 0.9
return 0.0
class ContentHasher:
"""
Generates fingerprints for raw content.
"""
@staticmethod
def generate_hash(content):
"""
Normalizes whitespace and generates a SHA256 hash.
In a real-world scenario, this would use SimHash or MinHash for fuzzy matching.
"""
if not content:
return None
# Normalize: remove extra spaces, newlines, and lower case
clean_content = re.sub(r'\s+', ' ', content).strip().lower()
return hashlib.sha256(clean_content.encode('utf-8')).hexdigest()
class ClusterResolver:
"""
Groups data into clusters based on Content Hash and URL Signals.
"""
def __init__(self):
self.data_objects = []
# Mappings for clustering
self.hash_to_ids = defaultdict(list)
self.id_to_data = {}
def add_page(self, url, content, metadata=None):
obj_id = url # Using URL as ID for simplicity
content_hash = ContentHasher.generate_hash(content)
entry = {
'id': obj_id,
'url': url,
'hash': content_hash,
'normalized_url': URLNormalizer.normalize(url),
'metadata': metadata or {},
'cluster_id': None
}
self.data_objects.append(entry)
self.id_to_data[obj_id] = entry
if content_hash:
self.hash_to_ids[content_hash].append(obj_id)
def resolve(self):
"""
Executes the clustering logic.
"""
clusters = defaultdict(list)
visited = set()
# 1. Group by Content Hash (Primary Cluster)
for h, ids in self.hash_to_ids.items():
if len(ids) > 1:
# These are duplicates
# We simply pick the first one as the cluster representative temporarily
# (Action generator will pick the best canonical later)
cluster_id = f"cluster_{h[:8]}"
for obj_id in ids:
self.id_to_data[obj_id]['cluster_id'] = cluster_id
clusters[cluster_id].append(self.id_to_data[obj_id])
visited.add(obj_id)
# 2. Group by Normalized URL (Secondary Cluster - handles parameter noise)
# (Skipped here for brevity, but would follow similar logic as above using normalized_url)
return clusters
class ActionSuggester:
"""
Analyzes clusters and recommends specific technical actions.
"""
@staticmethod
def pick_canonical(cluster_items):
"""
Logic to pick the 'best' URL.
Priority: HTTPS > Shortest URL > Highest Traffic (if metadata exists)
"""
# Sort by logic
sorted_items = sorted(cluster_items, key=lambda x: (
# Prefer HTTPS
0 if x['url'].startswith('https') else 1,
# Prefer shortest URL (cleaner)
len(x['url']),
# Prefer highest traffic (mock logic)
x['metadata'].get('traffic', 0)
))
return sorted_items[0]
@staticmethod
def generate_actions(clusters):
results = []
for cluster_id, items in clusters.items():
if len(items) < 2: continue
canonical = ActionSuggester.pick_canonical(items)
duplicates = [item for item in items if item['id'] != canonical['id']]
actions = []
for dup in duplicates:
# Determine Action Type
# If URLs are identical ignoring query params -> Canonical Tag
# If Content Hash is identical -> Redirect or Canonical
reason = "Content Identical"
if dup['normalized_url'] == canonical['normalized_url']:
action = "REDIRECT_301"
detail = "URLs normalize to the same address. Implement 301 Redirect to consolidate link equity."
else:
action = "CANONICAL_TAG"
detail = f"Distinct URLs serving duplicate content. Add <link rel='canonical' href='{canonical['url']}' /> to head."
actions.append({
'duplicate_url': dup['url'],
'action_type': action,
'detail': detail
})
results.append({
'cluster_id': cluster_id,
'canonical_url': canonical['url'],
'duplicate_count': len(duplicates),
'actions': actions
})
return results
# --- Usage Example ---
if __name__ == "__main__":
resolver = ClusterResolver()
# Data Simulation
# 1. Exact duplicate (Copy-Paste)
resolver.add_page("https://example.com/blog/post-1", "<html>Content A</html>", {"traffic": 100})
resolver.add_page("https://example.com/blog/post-1?utm_source=newsletter", "<html>Content A</html>", {"traffic": 50})
# 2. Near-duplicate due to trailing slash and protocol
resolver.add_page("http://example.com/blog/post-2/", "<html>Content B</html>", {"traffic": 10})
resolver.add_page("https://example.com/blog/post-2", "<html>Content B</html>", {"traffic": 200}) # Should be canonical (HTTPS + Traffic)
# 3. Unique page (No cluster)
resolver.add_page("https://example.com/about", "<html>About Us</html>")
# Run Resolver
print("--- Resolving Clusters ---")
clusters = resolver.resolve()
print("--- Generating Action Plan ---")
action_plan = ActionSuggester.generate_actions(clusters)
import json
print(json.dumps(action_plan, indent=2))
The ContentHasher uses SHA256 on normalized text.
The URLNormalizer is crucial for preventing false negatives.
utm_source) and Session IDs (sid=123) often create thousands of URLs for the same page. We strip these before comparing.http and https as potential duplicates, prioritizing https later.The ActionSuggester determines Remediation:
product?color=red vs product?color=blue) but the core content is the same. We keep both URLs live but tell search engines via <link rel="canonical"> which one owns the ranking.Running the code above produces the following action plan:
[
{
"cluster_id": "cluster_a7bfc1",
"canonical_url": "https://example.com/blog/post-1",
"duplicate_count": 1,
"actions": [
{
"duplicate_url": "https://example.com/blog/post-1?utm_source=newsletter",
"action_type": "REDIRECT_301",
"detail": "URLs normalize to the same address. Implement 301 Redirect to consolidate link equity."
}
]
},
{
"cluster_id": "cluster_c2e98f",
"canonical_url": "https://example.com/blog/post-2",
"duplicate_count": 1,
"actions": [
{
"duplicate_url": "http://example.com/blog/post-2/",
"action_type": "REDIRECT_301",
"detail": "URLs normalize to the same address. Implement 301 Redirect to consolidate link equity."
}
]
}
]