File size: 4,095 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 | """v2 features: v1 hand features (with thread fix) + author profile + trend-match + cached text/image embeddings.
Shared by train_v2.py, predict_v2.py and serve.py."""
import math, datetime as dt
import numpy as np, pandas as pd
from features import text_features, post_features, TEXT_FEATURES
FOLLOWER_BUCKETS = [0, 1_000, 10_000, 100_000, 1_000_000, float('inf')]
BUCKET_NAMES = ['<1k', '1k-10k', '10k-100k', '100k-1M', '1M+']
def follower_bucket(f):
return int(np.searchsorted(FOLLOWER_BUCKETS, max(float(f or 0), 0), side='right') - 1)
# is_reply now means "reply to someone else"; a reply to your own post is a thread continuation (is_thread)
POST_V2 = ['has_media', 'has_photo', 'has_video', 'is_reply', 'is_thread', 'is_quote', 'hour_utc_sin', 'hour_utc_cos', 'is_weekend']
AUTHOR_V2 = ['log_followers', 'verified', 'vt_business', 'log_following', 'log_tweets', 'log_listed',
'account_age_years', 'follow_ratio', 'listed_per_1k_followers', 'profile_known']
TREND_V2 = ['trend_snapshot_hour', 'trend_match', 'trend_rank', 'trend_volume', 'trend_lead_hours', 'trend_match_any']
HAND_V2 = TEXT_FEATURES + POST_V2
def author_profile(followers, verified=0, verified_type=None, following=None, tweets=None, listed=None,
account_created=None, at=None):
lf = math.log10(1 + max(float(followers or 0), 0))
known = following is not None and tweets is not None
f = dict(log_followers=lf, verified=int(bool(verified)), vt_business=int(str(verified_type) in ('business', 'government')),
log_following=math.log10(1 + following) if following is not None else np.nan,
log_tweets=math.log10(1 + tweets) if tweets is not None else np.nan,
log_listed=math.log10(1 + listed) if listed is not None else np.nan,
account_age_years=np.nan, follow_ratio=np.nan, listed_per_1k_followers=np.nan, profile_known=int(known))
if following is not None: f['follow_ratio'] = lf - math.log10(1 + following)
if listed is not None: f['listed_per_1k_followers'] = 1000 * listed / max(float(followers or 0), 100)
if account_created is not None:
at = pd.Timestamp(at or dt.datetime.now(dt.timezone.utc)); ac = pd.Timestamp(account_created)
if at.tzinfo is None: at = at.tz_localize('UTC')
if ac.tzinfo is None: ac = ac.tz_localize('UTC')
f['account_age_years'] = (at - ac).total_seconds() / (365.25 * 86400)
return f
def hand_features(text, has_photo=0, has_video=0, is_reply=0, is_thread=0, is_quote=0, posted_at=None, n_links=None):
ts = pd.Timestamp(posted_at) if posted_at is not None else pd.Timestamp.now(tz='UTC')
if ts.tzinfo is None: ts = ts.tz_localize('UTC')
ts = ts.tz_convert('UTC')
f = text_features(text, n_links=n_links)
# a thread continuation is not a reply to someone else
f.update(post_features(has_photo, has_video, int(bool(is_reply) and not bool(is_thread)), is_quote, ts.hour, ts.weekday()))
f['is_thread'] = int(bool(is_thread))
return f
def thread_flag(is_reply, in_reply_to_user_id, author_id, text):
"""Self-reply = thread. If the reply target is unknown, a reply whose text does not open with @mentions is
almost always a self-thread on X (replies to others are prefixed with the @handles)."""
if not is_reply: return 0
if isinstance(in_reply_to_user_id, str) and in_reply_to_user_id and in_reply_to_user_id != 'nan':
return int(str(in_reply_to_user_id) == str(author_id))
return int(not str(text or '').lstrip().startswith('@'))
def embedding_block(text_emb, img_emb, pca_text, pca_img):
"""text_emb (n,384) required; img_emb (n,512) with NaN rows where no image -> PCA comps + has_img_emb."""
t = pca_text.transform(text_emb)
out = {f'txt_{i}': t[:, i] for i in range(t.shape[1])}
has = ~np.isnan(img_emb).any(1)
ic = np.full((len(img_emb), pca_img.n_components_), np.nan)
if has.any(): ic[has] = pca_img.transform(img_emb[has])
for i in range(ic.shape[1]): out[f'img_{i}'] = ic[:, i]
out['has_img_emb'] = has.astype(int)
return pd.DataFrame(out)
|