Download predict_v2.py from brainfish/x-virality-model: direct link, hf CLI and curl.
- Browser
- Download file 5.07 kB
-
https://huggingface.co/brainfish/x-virality-model/resolve/main/predict_v2.py
- Command line
-
hf download hf://brainfish/x-virality-model/predict_v2.py
-
curl -L -o predict_v2.py https://huggingface.co/brainfish/x-virality-model/resolve/main/predict_v2.py
5.07 kB
| #!/usr/bin/env python3 | |
| """Score a draft X post with virality model v2 (author-relative label). | |
| P(viral_v2) = calibrated probability that the post lands in the top 5% of posts *relative to the author's own | |
| usual engagement*, among accounts of a similar follower size. Also returns a predicted impressions range. | |
| Usage: python predict_v2.py "text" --followers 170 [--following 157 --tweets 329 --listed 7 --account-created 2010-03-01] | |
| [--verified] [--photo] [--video] [--reply|--thread] [--quote] [--image-url URL ...] [--posted-at ISO]""" | |
| import argparse, json, os, sys | |
| import joblib, numpy as np, pandas as pd | |
| HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE) | |
| import calibration # noqa: F401 | |
| from features_v2 import hand_features, author_profile, embedding_block, TREND_V2 | |
| PATHS = {'v2': os.path.join('model_v2', 'virality_v2.joblib'), 'v2.1': os.path.join('model_v2b', 'virality_v2b.joblib'), | |
| 'v2.2': os.path.join('model_v2c', 'virality_v2c.joblib')} # v2.2: available, not the default | |
| _B = {} | |
| _EV = None | |
| def _bundle(version='v2.1'): | |
| if version not in _B: _B[version] = joblib.load(os.path.join(HERE, PATHS[version])) | |
| return _B[version] | |
| def _events(): | |
| global _EV | |
| if _EV is None: | |
| from events_join import Events | |
| _EV = Events() | |
| return _EV | |
| def _trend(text, posted_at): | |
| try: | |
| from trends_join import add_trend_features | |
| d = add_trend_features(pd.DataFrame({'text': [text], 'created_at': [pd.Timestamp(posted_at or pd.Timestamp.now(tz='UTC'))]}), | |
| os.path.join(HERE, 'trends', 'trends.jsonl')) | |
| return {c: d[c].iloc[0] for c in TREND_V2} | |
| except Exception: | |
| return {c: (0 if c in ('trend_snapshot_hour', 'trend_match', 'trend_match_any') else np.nan) for c in TREND_V2} | |
| def featurize(text, followers=None, verified=False, verified_type=None, following=None, tweets=None, listed=None, account_created=None, | |
| has_photo=False, has_video=False, is_reply=False, is_thread=False, is_quote=False, posted_at=None, image_urls=None, version='v2.1'): | |
| b = _bundle(version) | |
| f = hand_features(text, has_photo, has_video, is_reply, is_thread, is_quote, posted_at) | |
| f.update(author_profile(followers, verified, verified_type, following, tweets, listed, account_created, posted_at)) | |
| if followers is None: # text-only: let the trees route missing author size down their default branch | |
| f.update(log_followers=np.nan, follow_ratio=np.nan, listed_per_1k_followers=np.nan) | |
| f.update(_trend(text, posted_at)) | |
| f.update(_events().features(text, posted_at)) # public events calendar + holidays (events/events.jsonl); zeros if the file is missing | |
| from embed import embed_texts, embed_image_urls | |
| T = embed_texts([text]); I = np.full((1, 512), np.nan, np.float32); img_used = False | |
| if image_urls: | |
| v = embed_image_urls(image_urls) | |
| if v is not None: I[0] = v; img_used = True | |
| f.update(embedding_block(T, I, b['pca_text'], b['pca_img']).iloc[0].to_dict()) | |
| return pd.DataFrame([f]), img_used | |
| def predict(text, version='v2.1', **kw): | |
| b = _bundle(version); X, img_used = featurize(text, version=version, **kw) | |
| s = b['model'].predict_proba(X[b['features']])[:, 1] if b['score_is_prob'] else b['model'].predict(X[b['features']]) | |
| p = float(b['calibrator'].predict(s)[0]) | |
| li = float(b['impressions_model'].predict(X[b['impressions_features']])[0]); q = b['impressions_q80'] | |
| return dict(p_viral=p, raw_score=float(s[0]), threshold=b['thresholds']['f1'], conformal_threshold=b['thresholds']['conformal_recall80'], | |
| viral=p >= b['thresholds']['f1'], base_rate=b['base_rate'], image_used=img_used, | |
| impressions_pred=int(round(10 ** li - 1)), impressions_80=[int(max(0, round(10 ** (li - q) - 1))), int(round(10 ** (li + q) - 1))], | |
| X=X) | |
| if __name__ == '__main__': | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument('text'); ap.add_argument('--followers', type=int, default=0); ap.add_argument('--following', type=int) | |
| ap.add_argument('--tweets', type=int); ap.add_argument('--listed', type=int); ap.add_argument('--account-created') | |
| ap.add_argument('--verified', action='store_true'); ap.add_argument('--photo', action='store_true'); ap.add_argument('--video', action='store_true') | |
| ap.add_argument('--reply', action='store_true'); ap.add_argument('--thread', action='store_true'); ap.add_argument('--quote', action='store_true') | |
| ap.add_argument('--image-url', nargs='*'); ap.add_argument('--posted-at') | |
| a = ap.parse_args() | |
| r = predict(a.text, followers=a.followers, verified=a.verified, following=a.following, tweets=a.tweets, listed=a.listed, | |
| account_created=a.account_created, has_photo=a.photo, has_video=a.video, is_reply=a.reply, is_thread=a.thread, | |
| is_quote=a.quote, posted_at=a.posted_at, image_urls=a.image_url) | |
| r.pop('X'); print(json.dumps(r, indent=1)) | |