x-virality-model / features.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.45 kB
"""Feature extraction shared by train.py and predict.py."""
import json, os, re, math
import numpy as np
import emoji
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
HERE = os.path.dirname(os.path.abspath(__file__))
_VADER = SentimentIntensityAnalyzer()
_NRC = json.load(open(os.path.join(HERE, 'nrc_emotion_lexicon.json')))
EMOTIONS = ["anger", "anticipation", "disgust", "fear", "joy", "sadness", "surprise", "trust"]
URL_RE = re.compile(r'https?://\S+')
TCO_RE = re.compile(r'https?://t\.co/\S+')
HASH_RE = re.compile(r'(?<!\w)#\w+')
MENT_RE = re.compile(r'(?<!\w)@\w+')
NUM_RE = re.compile(r'\b\d[\d,\.]*%?|\$\d')
WORD_RE = re.compile(r"[a-z']+")
HOOK_RE = re.compile(r"^(breaking|just in|new:|this is|here'?s|how to|why |what |when |who |the truth|unpopular opinion|thread|psa|reminder|imagine|me when|pov|nobody|everyone|i can'?t believe|wait|lol|omg)", re.I)
CTA_RE = re.compile(r"\b(retweet|repost|rt if|like if|follow|share|comment|reply|drop a|tag someone|vote)\b", re.I)
LIST_RE = re.compile(r'(^|\n)\s*(\d+[\.\)]|[-•✅👉🔹▪️])\s', re.M)
POSITIVE_ENG = ['likes', 'reposts', 'replies', 'quotes']
TEXT_FEATURES = [
'n_chars', 'n_words', 'n_lines', 'caps_ratio', 'n_exclaim', 'n_question', 'starts_question',
'hook_opening', 'has_cta', 'is_list', 'n_numbers', 'n_emojis', 'n_hashtags', 'n_mentions',
'n_links', 'starts_with_mention', 'vader_compound', 'vader_pos', 'vader_neg', 'vader_neu',
'sentiment_abs',
] + [f'emo_{e}' for e in EMOTIONS] + ['emo_total']
POST_FEATURES = ['has_media', 'has_photo', 'has_video', 'is_reply', 'is_quote', 'hour_utc_sin', 'hour_utc_cos', 'is_weekend']
# Only author signals a user can supply for a draft (follower count, verified badge).
# Following count, tweet count and account age were tried but dropped: they acted as sampling artefacts
# (e.g. prolific keyword-search posters) and are rarely known for a draft.
AUTHOR_FEATURES = ['log_followers', 'verified']
CONTENT_FEATURES = TEXT_FEATURES + POST_FEATURES
ALL_FEATURES = CONTENT_FEATURES + AUTHOR_FEATURES
def clean_text(text):
import html
t = html.unescape(text or '')
# X appends a t.co link for attached media/quoted posts at the very end; drop those trailing links
t = re.sub(r'(\s*https?://t\.co/\S+)+\s*$', '', t)
return t
def text_features(text, n_links=None):
raw = text or ''
t = clean_text(raw)
words = WORD_RE.findall(t.lower())
letters = [c for c in t if c.isalpha()]
vs = _VADER.polarity_scores(t)
emo = {e: 0 for e in EMOTIONS}
for w in words:
for a in _NRC.get(w, []):
if a in emo: emo[a] += 1
nw = max(len(words), 1)
body = MENT_RE.sub('', t).strip()
f = dict(
n_chars=len(t), n_words=len(words), n_lines=t.count('\n') + 1,
caps_ratio=(sum(c.isupper() for c in letters) / len(letters)) if letters else 0.0,
n_exclaim=t.count('!'), n_question=t.count('?'),
starts_question=int(bool(re.match(r'^[^.!?\n]{0,120}\?', body))),
hook_opening=int(bool(HOOK_RE.match(body))), has_cta=int(bool(CTA_RE.search(t))),
is_list=int(len(LIST_RE.findall(t)) >= 2), n_numbers=len(NUM_RE.findall(t)),
n_emojis=emoji.emoji_count(t), n_hashtags=len(HASH_RE.findall(t)), n_mentions=len(MENT_RE.findall(t)),
n_links=len(URL_RE.findall(t)) if n_links is None else n_links,
starts_with_mention=int(t.strip().startswith('@')),
vader_compound=vs['compound'], vader_pos=vs['pos'], vader_neg=vs['neg'], vader_neu=vs['neu'],
sentiment_abs=abs(vs['compound']),
)
for e in EMOTIONS: f[f'emo_{e}'] = emo[e] / nw
f['emo_total'] = sum(emo.values()) / nw
return f
def post_features(has_photo=0, has_video=0, is_reply=0, is_quote=0, hour_utc=None, weekday=None):
import datetime as dt
now = dt.datetime.now(dt.timezone.utc)
h = now.hour if hour_utc is None else hour_utc
wd = now.weekday() if weekday is None else weekday
return dict(has_media=int(bool(has_photo or has_video)), has_photo=int(bool(has_photo)), has_video=int(bool(has_video)),
is_reply=int(bool(is_reply)), is_quote=int(bool(is_quote)),
hour_utc_sin=math.sin(2 * math.pi * h / 24), hour_utc_cos=math.cos(2 * math.pi * h / 24),
is_weekend=int(wd >= 5))
def author_features(followers, verified=0):
return dict(log_followers=math.log10(1 + max(followers, 0)), verified=int(bool(verified)))