File size: 4,496 Bytes
853e005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Join posts to hourly X trend snapshots (trends/trends.jsonl, written by the hourly snapshot routine).

Each snapshot line is expected to hold a timestamp and a list of trends. Field names are read flexibly:
  time:   snapshot_time | snapshot_at | captured_at | fetched_at | ts | time | timestamp
  trends: trends | data   (each item: trend_name | name | trend, optional rank, post_count | tweet_count | volume | post_volume, woeid); or one trend per line
Added columns (all numeric so the model can use them):
  trend_snapshot_hour   1 if a snapshot exists within +-90 min of the post's creation (coverage flag)
  trend_match           1 if the post text/hashtags contain a trend that was live in that snapshot
  trend_rank            best (lowest) rank of a matched live trend, NaN if none
  trend_volume          post count of that trend, NaN if unknown
  trend_lead_hours      hours between the trend's FIRST appearance in any snapshot and the post
                        (negative = posted before the trend first showed up, i.e. early), NaN if no match
  trend_match_any       1 if the post matches a trend from any snapshot within 24h either side (looser)
  trend_name            matched trend (string, for inspection only)"""
import json, os, re
import numpy as np, pandas as pd
TCOLS=['snapshot_time','snapshot_at','captured_at','fetched_at','ts','time','timestamp']

def _norm(s): return re.sub(r'[^0-9a-z]+',' ',str(s).lower()).strip()

def load_snapshots(path):
    rows=[]
    if not os.path.exists(path): return pd.DataFrame(columns=['snap','name','norm','rank','volume'])
    for line in open(path):
        line=line.strip()
        if not line: continue
        try: d=json.loads(line)
        except Exception: continue
        t=next((d[k] for k in TCOLS if k in d), None)
        items=d.get('trends') or d.get('data') or []
        if isinstance(d,dict) and not items and any(k in d for k in ('trend_name','name','trend')):  # one trend per line (hourly routine format)
            items=[d]
        if t is None: continue
        for i,it in enumerate(items):
            if not isinstance(it,dict): continue
            name=it.get('trend_name') or it.get('name') or it.get('trend')
            if not name: continue
            rows.append(dict(snap=pd.to_datetime(t,utc=True),name=name,norm=_norm(name),
                             rank=it.get('rank',i+1),volume=next((it[k] for k in ('post_count','tweet_count','volume','post_volume') if it.get(k) is not None), None)))
    s=pd.DataFrame(rows)
    if len(s): s=s[s.norm.str.len()>=3]
    return s

def _match(text, norm):
    if norm.startswith(' ') or not norm: return False
    return f' {norm} ' in text

def add_trend_features(df, path):
    snaps=load_snapshots(path)
    out=dict(trend_snapshot_hour=[],trend_match=[],trend_rank=[],trend_volume=[],trend_lead_hours=[],trend_match_any=[],trend_name=[])
    if len(snaps):
        first=snaps.groupby('norm').snap.min().to_dict()
        times=pd.DatetimeIndex(sorted(snaps.snap.unique()))
        bysnap={t:g for t,g in snaps.groupby('snap')}
    for txt,ct in zip(df['text'].fillna(''), pd.to_datetime(df['created_at'],utc=True)):
        r=dict(trend_snapshot_hour=0,trend_match=0,trend_rank=np.nan,trend_volume=np.nan,trend_lead_hours=np.nan,trend_match_any=0,trend_name='')
        if len(snaps):
            T=' '+_norm(txt.replace('#',' '))+' '
            d=np.abs(np.asarray((times-ct)/pd.Timedelta(hours=1),dtype=float))
            j=int(np.argmin(d))
            if d[j]<=1.5:
                r['trend_snapshot_hour']=1
                g=bysnap[times[j]]
                m=g[[_match(T,n) for n in g.norm]]
                if len(m):
                    b=m.sort_values('rank').iloc[0]
                    r.update(trend_match=1,trend_rank=float(b['rank']),trend_volume=float(b['volume']) if pd.notna(b['volume']) else np.nan,
                             trend_lead_hours=(ct-first[b['norm']])/pd.Timedelta(hours=1),trend_name=b['name'])
            near=snaps[(snaps.snap>=ct-pd.Timedelta(hours=24))&(snaps.snap<=ct+pd.Timedelta(hours=24))]
            if len(near):
                mm=[n for n in near.norm.unique() if _match(T,n)]
                if mm:
                    r['trend_match_any']=1
                    if not r['trend_name']:
                        r['trend_name']=mm[0]; r['trend_lead_hours']=(ct-first[mm[0]])/pd.Timedelta(hours=1)
        for k,v in r.items(): out[k].append(v)
    for k,v in out.items(): df[k]=v
    return df