x-virality-model / events_join.py
brainfish's picture
Upload X virality model v2.1 (default) + v2.2: bundles, inference code, model card
853e005 verified
Raw History Blame Contribute Delete
4.9 kB
"""Event features from events/events.jsonl (public calendar built by scripts/build_events.py).
For a post at time t (UTC date D) we look at events on D-1, D and D+1 and match keywords/hashtags against the post text.
Features (all numeric; ev_covered=0 means the post is outside the calendar range so the rest are 0/NaN):
ev_covered 1 if D is inside the calendar range
ev_match 1 if any specific event keyword occurs in the post text (+-1 day)
ev_n_match number of distinct matched events (capped at 5)
ev_specificity best match strength = 1/sqrt(#days the keyword appears in the calendar), higher = rarer, more specific keyword
ev_days_from post date minus event date in days for the best match (-1, 0, +1), NaN if none
ev_cat_<c> one-hot of the best match's category (conflict, disaster, crime, politics, intl, business, sports, science,
arts, holiday, tech, shopping, awards, fashion, other)
ev_cat_n_day number of Wikipedia 'current events' items on the date (how newsy the day is)
hol_any/hol_US/hol_GB/hol_IN/hol_AU public-holiday flags on the post date; hol_n = number of regions with a holiday
Generic keywords (present on >=15 distinct days, shorter than 4 chars) are ignored."""
import json, os, re
from collections import defaultdict
import numpy as np, pandas as pd
HERE = os.path.dirname(os.path.abspath(__file__))
CATS = ['conflict', 'disaster', 'crime', 'politics', 'intl', 'business', 'sports', 'science', 'arts', 'holiday', 'tech', 'shopping', 'awards', 'fashion', 'other']
_MAP = [('armed', 'conflict'), ('attacks', 'conflict'), ('disaster', 'disaster'), ('law', 'crime'), ('politic', 'politics'), ('international', 'intl'),
('business', 'business'), ('sport', 'sports'), ('science', 'science'), ('technology', 'tech'), ('health', 'science'), ('arts', 'arts'),
('holiday', 'holiday'), ('tech', 'tech'), ('shopping', 'shopping'), ('awards', 'awards'), ('fashion', 'fashion')]
EVENT_FEATURES = ['ev_covered', 'ev_match', 'ev_n_match', 'ev_specificity', 'ev_days_from', 'ev_news_day_n', 'hol_any', 'hol_US', 'hol_GB', 'hol_IN', 'hol_AU', 'hol_n'] + [f'ev_cat_{c}' for c in CATS]
def _cat(c):
c = (c or '').lower()
for k, v in _MAP:
if k in c: return v
return 'other'
def _norm(t): return ' ' + re.sub(r'[^0-9a-z\u00c0-\u024f\u0400-\u04ff]+', ' ', str(t).lower().replace('#', ' ')).strip() + ' '
class Events:
def __init__(self, path=os.path.join(HERE, 'events', 'events.jsonl'), generic_days=15):
self.ok = os.path.exists(path); self.by_date = defaultdict(list); self.hol = defaultdict(set); self.news_n = defaultdict(int)
if not self.ok: self.lo = self.hi = None; return
ev = [json.loads(l) for l in open(path)]
days = defaultdict(set)
for e in ev:
for k in e['keywords']: days[k].add(e['date'])
self.kw_days = {k: len(v) for k, v in days.items()}
for e in ev:
if e['category'] == 'holiday' and e['source'] != 'curated':
self.hol[e['date']].add(e['region'])
if e['source'] == 'wikipedia_current_events': self.news_n[e['date']] += 1
kws = [k for k in e['keywords'] if len(k) >= 4 and self.kw_days[k] < generic_days]
if kws: self.by_date[e['date']].append((e['name'], _cat(e['category']), [_norm(k) for k in kws], [self.kw_days[k] for k in kws]))
ds = sorted({e['date'] for e in ev}); self.lo, self.hi = pd.Timestamp(ds[0]).date(), pd.Timestamp(ds[-1]).date()
def features(self, text, posted_at):
ts = pd.Timestamp(posted_at) if posted_at is not None else pd.Timestamp.now(tz='UTC')
d = (ts.tz_localize('UTC') if ts.tzinfo is None else ts.tz_convert('UTC')).date()
f = {k: 0 for k in EVENT_FEATURES}; f['ev_specificity'] = 0.0; f['ev_days_from'] = np.nan
if not self.ok or not (self.lo <= d <= self.hi): return f
f['ev_covered'] = 1; ds = d.isoformat(); f['ev_news_day_n'] = self.news_n.get(ds, 0)
regs = self.hol.get(ds, set()); f['hol_n'] = len(regs); f['hol_any'] = int(bool(regs))
for r in ['US', 'GB', 'IN', 'AU']: f[f'hol_{r}'] = int(r in regs)
T = _norm(text); best = None; names = set()
for off in (-1, 0, 1):
for name, cat, kws, nd in self.by_date.get((d + pd.Timedelta(days=off)).isoformat(), []):
for k, n in zip(kws, nd):
if k in T:
s = 1 / np.sqrt(n); names.add(name)
if best is None or s > best[0]: best = (s, cat, off)
if best:
f['ev_match'] = 1; f['ev_n_match'] = min(len(names), 5); f['ev_specificity'] = best[0]; f['ev_days_from'] = -best[2]; f[f'ev_cat_{best[1]}'] = 1
return f
def frame(self, texts, times):
return pd.DataFrame([self.features(t, a) for t, a in zip(texts, times)])