Create a freshness scoring engine: change frequency, user signals, competitive deltas,…
- User
Create a freshness scoring engine: change frequency, user signals, competitive deltas, and recrawl scheduling.
Assistant
Create a freshness scoring engine: change frequency, user signals, competitive deltas, and recrawl scheduling.
The user wants to create a "freshness scoring engine" that takes into account four specific factors:
This is a systems design and algorithmic problem. I need to provide a comprehensive guide or code implementation that demonstrates how to calculate this score and use it to drive a crawler.
Key Components to Design:
Data Model: What data do we need for a URL?
Algorithm (The Scoring Engine):
Needs to combine these factors into a single "Freshness Score" (e.g., 0-100, where 100 is "needs recrawling immediately" or "very fresh", and 0 is "stale").
Actually, usually, a high score implies "needs update" (Staleness score) or "High Value & Stale". Let's define the output as a "Priority Score for Recrawling". The higher the score, the sooner it needs a recrawl.
Factor 1: Change Frequency.
Factor 2: User Signals.
Factor 3: Competitive Deltas.
Factor 4: Recrawl Scheduling.
next_crawl_date). Or, the engine outputs a priority, and the scheduler consumes it.Implementation Strategy:
FreshnessEngine.Drafting the Logic:
Decay Function: Freshness decays over time.
Time_Score = 1 / (1 + time_since_last_crawl)Change Frequency:
Average_Change_Interval.Frequency_Factor = time_since_last_crawl / Average_Change_Interval.User Signals:
User_Score = Log(Views) * CTR.Competitive Deltas:
Competitor_Update_Time > Our_Last_Crawl_Time, we are behind.Structuring the Response:
Refining the "Freshness Score" vs. "Recrawl Priority":
A "Freshness Score" usually implies "How fresh is it right now?" (High = Fresh).
A "Recrawl Priority" implies "How badly do we need to check it?" (High = Stale + Important).
The prompt asks for a "Freshness Scoring Engine", but then mentions "Recrawl Scheduling". Usually, these are linked:
Recrawl_Priority = (1 - Freshness_Score) * Importance_Weight.
I will define the output as a Freshness Score (0 to 1), where 1 is perfectly fresh. When this drops below a threshold, or combined with a "PageRank/Importance" score creates a priority, we schedule.
Actually, to be most useful, let's frame the engine as calculating "Staleness Risk" or "Update Urgency". Let's stick to the prompt's term: Freshness Score. Let's define it as:
The Math Components:
Time Decay (The Base):
Based on change_frequency. If a page changes hourly, freshness drops to 0.5 after 30 mins. If it changes yearly, freshness drops to 0.5 after 6 months.
Half-life approach.
User Signals (The Modifier):
If users are engaging less recently, maybe the content is stale?
Or, if users are complaining/bouncing?
Let's use: "Velocity of interaction". If traffic is steady, maintain standard decay. If traffic spikes, check more often.
Let's make it simpler: Importance. Freshness matters more for important pages.
Effective_Freshness = Freshness_Score * Importance.
Competitive Delta:
If competitors updated, our "Perceived Freshness" drops faster.
if competitor_updated_recently: penalty = 0.2.
Let's build the Python Class:
calculate_freshness(page_data)schedule_recrawl(page_data)Step-by-Step Implementation Plan:
Class FreshnessEngine:
calculate_score:
last_crawled, last_changed, avg_change_rate_days, daily_views, competitor_last_updated.Let's pivot slightly. The user asked for a "Freshness Scoring Engine" including "Recrawl Scheduling". This implies the output is the schedule, derived from the score.
Revised Formula:
Urgency_Score = (Time_Factor) * (User_Weight) * (Competitive_Pressure)
Python Code Structure:
class FreshnessEngine:
def __init__(self, decay_rate=0.5):
pass
def get_freshness_score(self, content):
# 1. Time since last update
# 2. Compare to historical change frequency
# 3. Return 0.0 to 1.0
pass
def get_competitive_delta(self, content):
# Check if competitors are fresher
pass
def calculate_recrawl_priority(self, content):
# Combine Freshness + User Signals + Comp Delta
pass
def schedule_recrawl(self, queue):
# Return top N items
pass
I will refine the "Competitive Delta" logic. We need a way to know competitor freshness. I'll mock a function fetch_competitor_last_modified.
User Signals Logic:
If a page has high clicks, we should recrawl it sooner.
UserWeight = 1 + log10(daily_clicks + 1)
The "Engine" Output: The code should print a report or a schedule. I will provide a complete, runnable Python script.
Summary of Features to Implement:
next_crawl_timestamp.Let's write the code mentally first.
score = 1.0
score -= time_decay(avg_change_rate, time_since_crawl)
score -= competitive_penalty
score = max(0, score)
priority = (1 - score) * user_weight
Wait, "Freshness Score" usually means "How fresh is it?". If Score is 1.0, it is Fresh. If Score is 0.0, it is Stale.
Scheduling logic: "Recrawl when Score < Threshold OR Priority > X".
I will present this as a modular Python system.
Structure of the response:
This looks solid. I will write the code to be clean, commented, and use standard libraries (datetime, math) for clarity.
One specific detail: Competitive Deltas.
How to model this?
Input: our_last_modified, competitor_last_modified.
Logic: If competitor_last_modified > our_last_modified, we have a "delta". The size of the delta in time matters. If they updated yesterday and we updated 2 days ago, minor issue. If they updated yesterday and we updated 2 years ago, major issue.
Actually, it's simpler: If they updated after our last crawl, our current content is potentially outdated relative to the market.
competitor_freshness_boost adds to the urgency.
Let's get to writing. To build a robust Freshness Scoring Engine, we need to move beyond simple "last updated" timestamps. We must build a system that predicts the probability of a page being stale and prioritizes it based on business value (User Signals) and market pressure (Competitive Deltas).
Below is a comprehensive design and Python implementation of this engine.
The engine operates in four distinct layers:
We calculate a Priority Score () which determines the recrawl queue position.
Where:
Time Since Last Crawl divided by Average Change Frequency. Uses a sigmoid function to smooth out outliers.Here is the complete engine logic using standard data science libraries (pandas, numpy, datetime).
import pandas as pd
import numpy as np
import math
from datetime import datetime, timedelta
class FreshnessEngine:
def __init__(self, config=None):
self.config = config or {
"max_crawl_interval_days": 365, # Hard cap for low-value pages
"min_crawl_interval_days": 1, # Floor for aggressive crawling
"competitor_sensitivity": 0.5, # How much competitor changes affect score
"traffic_sensitivity": 1.5 # Logarithmic weight of traffic
}
def _calculate_temporal_score(self, row):
"""
Calculates the probability that content has changed based on history.
Score approaches 1.0 as time passes the average change frequency.
"""
last_crawled = row.get('last_crawled_at')
avg_change_days = row.get('avg_change_frequency_days', 30) # Default 30 days
if pd.isna(last_crawled):
return 1.0 # Never crawled, max priority
# Time elapsed since last crawl
days_elapsed = (datetime.now() - last_crawled).days
# Sigmoid function: risk accelerates as we pass the average change window
# Shifted by avg_change_days to center the "inflection point"
score = 1 / (1 + np.exp(-(days_elapsed - avg_change_days)))
return score
def _calculate_competitive_delta(self, row):
"""
If competitor content is fresher or detected as changed, boost urgency.
"""
comp_last_updated = row.get('competitor_last_updated')
our_last_updated = row.get('content_last_modified')
# If we don't know, assume neutral
if pd.isna(comp_last_updated) or pd.isna(our_last_updated):
return 0.0
# If competitor updated after us, increase score
if comp_last_updated > our_last_updated:
delta_days = (comp_last_updated - our_last_updated).days
# The longer they have been ahead, the more we need to catch up
return min(0.5, delta_days * 0.05)
return 0.0
def _calculate_user_weight(self, row):
"""
Normalizes user signals (views/clicks) to determine "Importance".
Uses Log scale to prevent super-popular pages from dominating entirely.
"""
traffic = row.get('monthly_traffic', 0)
if traffic <= 0:
return 0.1 # Low weight for ghost towns
# Logarithmic scaling: 10 views -> ~1.0, 1000 views -> ~3.0
weight = math.log(traffic + 1) ** self.config["traffic_sensitivity"]
return weight
def generate_schedule(self, df):
"""
Main Pipeline: Takes DataFrame of URLs and outputs recrawl dates.
"""
# 1. Calculate Components
df['temporal_score'] = df.apply(self._calculate_temporal_score, axis=1)
df['competitive_score'] = df.apply(self._calculate_competitive_delta, axis=1)
df['user_weight'] = df.apply(self._calculate_user_weight, axis=1)
# 2. Calculate Weighted Priority Score
# Formula: (Temporal + Competitive) * UserWeight
# Higher score = More urgent to crawl
df['raw_priority'] = (df['temporal_score'] + df['competitive_score']) * df['user_weight']
# 3. Normalize Priority to 0-1 range for scheduling
max_p = df['raw_priority'].max()
if max_p > 0:
df['norm_priority'] = df['raw_priority'] / max_p
else:
df['norm_priority'] = 0.5
# 4. Convert Priority to Next Crawl Date
# High Priority (1.0) -> Min Interval (e.g., 1 day)
# Low Priority (0.0) -> Max Interval (e.g., 365 days)
df['recrawl_in_days'] = self._priority_to_interval(df['norm_priority'])
df['next_crawl_date'] = df['recrawl_in_days'].apply(
lambda x: datetime.now() + timedelta(days=x)
)
return df
def _priority_to_interval(self, priority_series):
"""
Inverts priority into a time delay.
Linear interpolation between min and max days.
"""
min_days = self.config["min_crawl_interval_days"]
max_days = self.config["max_crawl_interval_days"]
# Invert: High priority -> Low days
# interval = max_days - (priority * (max_days - min_days))
return max_days - (priority_series * (max_days - min_days))
# --- MOCK DATA GENERATION FOR DEMO ---
def get_mock_data():
data = [
# Case A: High traffic, recently crawled, regular updates (News Site)
{
'url': 'site.com/news/today',
'last_crawled_at': datetime.now() - timedelta(days=1),
'avg_change_frequency_days': 1,
'monthly_traffic': 500000,
'competitor_last_updated': datetime.now() - timedelta(days=2),
'content_last_modified': datetime.now() - timedelta(days=1)
},
# Case B: Low traffic, old content, static (Archived Blog)
{
'url': 'site.com/blog/2015/post',
'last_crawled_at': datetime.now() - timedelta(days=180),
'avg_change_frequency_days': 365,
'monthly_traffic': 50,
'competitor_last_updated': None,
'content_last_modified': datetime.now() - timedelta(days=180)
},
# Case C: High Value, We are Stale compared to Competitor (E-Commerce Pricing)
{
'url': 'site.com/product/123',
'last_crawled_at': datetime.now() - timedelta(days=5),
'avg_change_frequency_days': 7,
'monthly_traffic': 10000,
'competitor_last_updated': datetime.now() - timedelta(days=1), # They updated 1 day ago
'content_last_modified': datetime.now() - timedelta(days=30) # We updated 30 days ago
}
]
return pd.DataFrame(data)
# --- RUNNING THE ENGINE ---
if __name__ == "__main__":
engine = FreshnessEngine()
df = get_mock_data()
# Run Scoring
result_df = engine.generate_schedule(df)
# Display Relevant Columns
print(result_df[[
'url',
'temporal_score',
'competitive_score',
'user_weight',
'norm_priority',
'recrawl_in_days',
'next_crawl_date'
]])
Instead of using a static sitemap changefreq, we use a Sigmoid Decay Function.
1 / (1 + e^{-(elapsed_time - avg_freq)}).Freshness costs money (crawling bandwidth). We shouldn't waste it on pages no one sees.
This is the strategic layer. It compares your content_last_modified date against the competitor's.
if competitor_date > our_date: add_score.The engine converts the abstract Priority Score into a Date/Time.
avg_change_frequency_days shifts the baseline. A forum thread (changing daily) will have a tighter schedule than a Wikipedia page (changing yearly).