File size: 725 Bytes
4d9fcca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from datetime import datetime, timezone
import math

def compute_freshness(ts, half_life_days=30):
    """

    Exponential decay score between 0 and 1.

    - 1.0 -> now

    - 0.5 -> half_life_days old

    - Approaches 0 -> when docs get very old

    """
    if not ts:
        return 0.5
    if isinstance(ts, str):
        ts = ts.replace("Z", "+00:00")
        try:
            ts = datetime.fromisoformat(ts)
        except Exception:
            return 0.5
    if ts.tzinfo is None:
        ts = ts.replace(tzinfo=timezone.utc)

    age_days = (datetime.now(timezone.utc) - ts).total_seconds() / 86400.0
    lam = math.log(2) / max(float(half_life_days), 1.0)
    return math.exp(-lam * age_days)