mayacheruty commited on
Commit
9c9050f
·
verified ·
1 Parent(s): 075a5c7

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -536
app.py DELETED
@@ -1,536 +0,0 @@
1
- """
2
- Bot Or Not (BON) - influencer due-diligence app.
3
- Reads the dataset from the HF dataset repo and the winning embedding model from HF.
4
- Pipeline: classifier score + retrieval (3 similar) + neighbor-vote diagnosis + bot-ring check + generated memo.
5
- CPU friendly. No em-dashes or en-dashes anywhere in the output.
6
- """
7
-
8
- import os, re, json, time, random
9
- from collections import Counter
10
-
11
- import spaces # must be imported before torch for ZeroGPU
12
- import numpy as np
13
- import pandas as pd
14
- import faiss
15
- import joblib
16
- import torch
17
- import gradio as gr
18
- from huggingface_hub import hf_hub_download
19
- from sentence_transformers import SentenceTransformer
20
- from transformers import AutoModelForCausalLM, AutoTokenizer
21
-
22
- # ----------------------------------------------------------------------------
23
- # Config
24
- # ----------------------------------------------------------------------------
25
- DATASET_REPO = "mayacheruty/BON-Synthetic-Influencers" # read dataset live from HF
26
- DATASET_FILE = "bon_dataset.csv"
27
- EMB_MODEL = "BAAI/bge-small-en-v1.5" # winning embedding model, loaded from HF
28
- GEN_MODEL = os.environ.get("BON_GEN_MODEL", "Qwen/Qwen2.5-1.5B-Instruct") # better instruction following
29
-
30
- EMB_FILE = "bon_embeddings.npy" # these four files sit in the Space repo
31
- IDX_FILE = "bon_faiss.index"
32
- DOC_FILE = "bon_docs.parquet"
33
- CLF_FILE = "bon_classifier.pkl"
34
-
35
- K_DETECT = 10 # neighbors used for the fraud vote
36
- TIGHT = 0.98 # tight similarity threshold for coordinated-ring detection
37
- RING_MIN = 15 # a query is "in a ring" if it has this many near-identical neighbors
38
-
39
- # ----------------------------------------------------------------------------
40
- # Load artifacts and models once at startup (never per request)
41
- # ----------------------------------------------------------------------------
42
- print("Loading dataset, docs, classifier ...")
43
- csv_path = hf_hub_download(repo_id=DATASET_REPO, filename=DATASET_FILE, repo_type="dataset")
44
- raw = pd.read_csv(csv_path)
45
- docs = pd.read_parquet(DOC_FILE) # profile_id, doc
46
- FEATURES14 = ["follower_count", "following_count", "posts_count", "account_age_months",
47
- "avg_likes", "avg_comments", "avg_views", "engagement_rate", "like_comment_ratio",
48
- "follower_following_ratio", "view_follower_ratio", "growth_spike_score",
49
- "audience_geo_mismatch", "audience_real_ratio"]
50
- try:
51
- bundle = joblib.load(CLF_FILE)
52
- clf, CLF_FEATURES = bundle["model"], bundle["features"]
53
- except Exception as e: # sklearn version drift, etc.
54
- print("Classifier pickle unavailable (", e, "), retraining from the dataset.")
55
- from sklearn.ensemble import RandomForestClassifier
56
- CLF_FEATURES = FEATURES14
57
- clf = RandomForestClassifier(n_estimators=200, random_state=42).fit(raw[CLF_FEATURES], raw["is_fraud"])
58
-
59
- meta = docs.merge(raw, on="profile_id", how="left").reset_index(drop=True)
60
- arch = meta["archetype"].values
61
- fraud = meta["is_fraud"].values
62
-
63
- print("Loading embedding model from HF ...")
64
- embedder = SentenceTransformer(EMB_MODEL, device="cpu") # pin to CPU so ZeroGPU cannot offload it
65
-
66
- # Embed the dataset with the SAME model used for queries, so both live in one vector space.
67
- # (Loading a saved .npy from a different model/version is what caused zero-similarity matches.)
68
- print("Embedding the dataset (one time at startup) ...")
69
- emb = embedder.encode(meta["doc"].tolist(), batch_size=64, convert_to_numpy=True,
70
- normalize_embeddings=True, device="cpu").astype("float32")
71
- index = faiss.IndexFlatIP(emb.shape[1]); index.add(emb)
72
- assert len(meta) == index.ntotal == emb.shape[0], "row counts do not match"
73
-
74
- # 2D projection for the map (PCA transforms new queries too)
75
- from sklearn.decomposition import PCA
76
- print("Projecting embeddings to 2D (PCA) for the map ...")
77
- _pca = PCA(n_components=2, random_state=42).fit(emb)
78
- _c2 = _pca.transform(emb)
79
- _cmin = _c2.min(axis=0); _cspan = (_c2.max(axis=0) - _cmin) + 1e-9
80
- coords_norm = (_c2 - _cmin) / _cspan
81
- def project(vec):
82
- return (_pca.transform(vec) - _cmin) / _cspan
83
- _rng = np.random.default_rng(0)
84
- _bg = _rng.choice(len(coords_norm), size=min(1400, len(coords_norm)), replace=False)
85
- BON_MAP = [[round(float(coords_norm[i, 0]), 4), round(float(coords_norm[i, 1]), 4), int(fraud[i])]
86
- for i in _bg]
87
-
88
- print("Loading generation model from HF ...")
89
- tok = AutoTokenizer.from_pretrained(GEN_MODEL)
90
- gen = AutoModelForCausalLM.from_pretrained(GEN_MODEL, torch_dtype=torch.float32) # CPU
91
- gen.eval()
92
- print("Ready.")
93
-
94
- # ----------------------------------------------------------------------------
95
- # Feature engineering (identical to the Recommendation notebook)
96
- # ----------------------------------------------------------------------------
97
- def bucket(r):
98
- parts = []
99
- er = r["engagement_rate"]
100
- parts.append("almost no engagement" if er < 1 else "low engagement" if er < 3
101
- else "moderate engagement" if er < 8 else "high engagement")
102
- g = r["audience_geo_mismatch"]
103
- if g > 0.5: parts.append("audience mostly in unrelated regions")
104
- elif g > 0.3: parts.append("noticeable audience geo mismatch")
105
- rr = r["audience_real_ratio"]
106
- parts.append("mostly fake-looking followers" if rr < 0.5 else "mixed follower quality" if rr < 0.75
107
- else "mostly real followers")
108
- if r["follower_following_ratio"] > 80: parts.append("follows almost nobody despite a huge following")
109
- if r["like_comment_ratio"] > 120: parts.append("many likes but very few comments")
110
- if r["growth_spike_score"] > 0.6: parts.append("sudden follower spikes")
111
- return ", ".join(parts)
112
-
113
- def make_doc(r):
114
- return (f"{r['niche']} influencer. {bucket(r)}. "
115
- f"Bio: {r['bio']} Comments: {r['sample_comments']} Audience: {r['audience_note']}")
116
-
117
- def red_flags(r):
118
- f = []
119
- if r["engagement_rate"] < 1: f.append("Engagement rate is near zero.")
120
- elif r["engagement_rate"] < 3: f.append("Engagement rate is low for the follower tier.")
121
- if r["audience_geo_mismatch"] > 0.5: f.append("Most of the audience sits in unrelated regions.")
122
- elif r["audience_geo_mismatch"] > 0.3: f.append("Noticeable audience geography mismatch.")
123
- if r["audience_real_ratio"] < 0.5: f.append("A large share of followers look fake.")
124
- elif r["audience_real_ratio"] < 0.75: f.append("Follower quality is mixed.")
125
- if r["follower_following_ratio"] > 80: f.append("Follows almost nobody despite a large following.")
126
- if r["like_comment_ratio"] > 120: f.append("Many likes but very few comments.")
127
- if r["growth_spike_score"] > 0.6: f.append("Sudden follower spikes in its history.")
128
- return f
129
-
130
- # ----------------------------------------------------------------------------
131
- # Analysis: classifier + retrieval + ring check
132
- # ----------------------------------------------------------------------------
133
- def recommended_actions(verdict, fair_ceiling):
134
- if verdict == "WALK AWAY":
135
- return ["Do not proceed with a paid partnership.",
136
- "If you still consider it, require an independent audience audit first.",
137
- "Do not send product or advance payment."]
138
- if verdict == "NEGOTIATE DOWN":
139
- return [f"Pay only for genuine reach; a fair ceiling is about ${fair_ceiling:,} for one post.",
140
- "Request an audience audit or analytics screenshots before you sign.",
141
- "Start with one paid trial post, not a full campaign."]
142
- return ["Reasonable to proceed at market rate.",
143
- "Confirm deliverables, usage rights, and the posting schedule.",
144
- "Track engagement on the sponsored post to verify performance."]
145
-
146
- def analyze(row):
147
- doc = make_doc(row)
148
- q = embedder.encode([doc], convert_to_numpy=True, normalize_embeddings=True, device="cpu").astype("float32")
149
- sims, nn = index.search(q, 61)
150
- neigh, s = list(nn[0]), sims[0]
151
-
152
- neigh_k = neigh[:K_DETECT]
153
- fraud_types = [arch[n] for n in neigh_k if fraud[n] == 1]
154
- likely = Counter(fraud_types).most_common(1)[0][0] if fraud_types else "none"
155
- n_sim = len(neigh_k)
156
- n_sim_fraud = int(sum(int(fraud[n]) for n in neigh_k)) # case-based evidence over the 10 nearest
157
-
158
- density = int((s[:60] > TIGHT).sum()) # query is not in the index, so no self match
159
- in_ring = density >= RING_MIN
160
-
161
- feats = np.array([[float(row[f]) for f in CLF_FEATURES]])
162
- clf_prob = float(clf.predict_proba(feats)[0, 1]) # numeric classifier
163
- neighbor_rate = n_sim_fraud / max(1, n_sim) # case-based evidence from retrieval
164
- prob = 0.5 * clf_prob + 0.5 * neighbor_rate # combine the two so the verdict is consistent
165
-
166
- qv = q[0]
167
- similar = []
168
- for rank, n in enumerate(neigh[:3]):
169
- cos = float(np.dot(qv, emb[n])) # true cosine (query and dataset both normalized)
170
- similar.append({"archetype": str(arch[n]), "fraud": int(fraud[n]),
171
- "sim": round(max(0.0, cos), 3), "niche": str(meta.iloc[n]["niche"]),
172
- "x": round(float(coords_norm[n, 0]), 4), "y": round(float(coords_norm[n, 1]), 4)})
173
- qxy = project(q)[0] # the query's real position in the same 2D space
174
- authentic_share = max(0.0, 1.0 - prob) # same authenticity basis as the trust score and verdict
175
- genuine_reach = int(row["follower_count"] * authentic_share)
176
- fair_ceiling = int(round(genuine_reach / 1000.0 * 20)) # rough guide: about $20 per 1,000 genuine followers
177
-
178
- trust = int(round(100 * (1 - prob)))
179
- if in_ring or prob >= 0.6: verdict, risk = "WALK AWAY", "high"
180
- elif prob >= 0.35: verdict, risk = "NEGOTIATE DOWN", "medium"
181
- else: verdict, risk = "PAY", "low"
182
-
183
- return {"trust": trust, "verdict": verdict, "risk": risk, "niche": row["niche"],
184
- "platform": row.get("platform", "General"),
185
- "fraud_probability": round(prob, 2), "likely_fraud_type": likely,
186
- "in_ring": in_ring, "density": density,
187
- "red_flags": red_flags(row), "similar": similar,
188
- "n_similar": n_sim, "n_similar_fraud": n_sim_fraud,
189
- "actions": recommended_actions(verdict, fair_ceiling),
190
- "genuine_reach": genuine_reach, "fair_ceiling": fair_ceiling,
191
- "qxy": [round(float(qxy[0]), 4), round(float(qxy[1]), 4)]}
192
-
193
- # ----------------------------------------------------------------------------
194
- # Generation (streamed), with the em-dash / en-dash cleaner from Phase 4
195
- # ----------------------------------------------------------------------------
196
- SYSTEM = ("You are BON, an influencer fraud analyst. Write a short memo to a BRAND advising whether to pay "
197
- "an influencer. Address the brand, never the influencer. No greeting, no signature, no markdown, "
198
- "no asterisks, no bold. Three to four short sentences. Use ONLY the facts given, including the exact "
199
- "trust score, and do not invent numbers. Your recommendation MUST match the given verdict and must "
200
- "not contradict it anywhere in the memo. End with the recommendation in capitals: PAY, NEGOTIATE "
201
- "DOWN, or WALK AWAY. Do not use em-dashes or en-dashes.")
202
-
203
- _CLAUSE_DASHES = ["—", "–", "―", "‒"]
204
- _HYPHENISH = {"−": "-", "‑": "-"}
205
- _QUOTES = {"“": '"', "”": '"', "‘": "'", "’": "'", "…": "..."}
206
-
207
- def humanize(t):
208
- for b, g in _QUOTES.items(): t = t.replace(b, g)
209
- for b, g in _HYPHENISH.items(): t = t.replace(b, g)
210
- for d in _CLAUSE_DASHES: t = re.sub(rf"\s*{d}\s*", ", ", t)
211
- t = re.sub(r"\s+([,.;:!?])", r"\1", t)
212
- t = re.sub(r",\s*,", ",", t)
213
- t = re.sub(r"\s+", " ", t).strip()
214
- return t
215
-
216
- _LABELS = (r"(?:platform|verdict\s*to\s*state|verdict|risk\s*level|risk|similar\s*cases|closest\s*cases|"
217
- r"trust\s*score|likely\s*(?:issue|fraud\s*type)|coordinated\s*bot\s*ring|red\s*flags|facts|memo|"
218
- r"pay\s*/\s*walk[- ]?away|recommendation)")
219
-
220
- def finalize_memo(memo, verdict):
221
- memo = memo.replace("**", "").replace("*", "").replace("#", "").replace("`", "")
222
- memo = re.sub(r"(?<=[A-Z])-(?=[A-Z])", "", memo) # NEGOTIA-TE -> NEGOTIATE
223
- memo = re.sub(r"(?i)\bwalk\s*aways\b", "walk away", memo) # WALK AWAYS -> walk away
224
- memo = re.sub(r"(?i)\bnegotiates\s*down\b", "negotiate down", memo)
225
- memo = re.sub(rf"(?is)\b{_LABELS}\s*:\s*[^.]*\.?", " ", memo) # strip any echoed "Label: value." parts
226
- memo = re.sub(r"\s+", " ", memo).strip().strip(".").strip()
227
- memo = (memo + ".") if memo else "This profile needs a closer look before you commit."
228
- return (memo + " Recommendation: " + verdict + ".").strip() # one clean, canonical recommendation
229
-
230
- def build_prompt(a):
231
- flags = "; ".join(a["red_flags"]) or "none"
232
- ring = "yes" if a["in_ring"] else "no"
233
- return ("Write a three sentence due-diligence note to a brand about whether to pay this influencer. "
234
- "Write plain prose only. Do not use labels, lists, markdown, or headings, and do not repeat the "
235
- "findings word for word. Base it on these findings: "
236
- f"trust score {a['trust']} out of 100; risk {a['risk']}; "
237
- f"{a.get('n_similar_fraud', 0)} of {a.get('n_similar', 10)} most similar past profiles are "
238
- f"fraudulent; likely issue {a['likely_fraud_type']}; coordinated bot ring {ring}; "
239
- f"red flags {flags}. In the three sentences, say plainly what the audience quality means for the "
240
- f"brand's campaign spend. End with exactly: Recommendation: {a['verdict']}")
241
-
242
- @spaces.GPU
243
- def _gpu_probe():
244
- return True # exists only so the ZeroGPU Space starts; all real work runs on CPU
245
-
246
- def generate_memo(a):
247
- msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": build_prompt(a)}]
248
- text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
249
- inp = tok(text, return_tensors="pt")
250
- with torch.inference_mode():
251
- out = gen.generate(**inp, max_new_tokens=150, do_sample=True, temperature=0.3,
252
- top_p=0.9, repetition_penalty=1.2, no_repeat_ngram_size=3,
253
- pad_token_id=tok.eos_token_id)
254
- memo = tok.decode(out[0][inp["input_ids"].shape[1]:], skip_special_tokens=True)
255
- return finalize_memo(humanize(memo), a["verdict"])
256
-
257
- _PRETTY = {"authentic_organic": "Authentic, organic creator", "micro_real": "Genuine micro-creator",
258
- "viral_legit": "Real viral creator", "lightly_boosted": "Lightly boosted",
259
- "bought_followers": "Bought followers", "click_farm_audience": "Click-farm audience",
260
- "bought_engagement": "Bought engagement (fake likes)", "engagement_pod": "Engagement pod",
261
- "ai_persona": "AI-generated persona"}
262
- def _ascii(s):
263
- return str(s).encode("latin-1", "ignore").decode("latin-1")
264
-
265
- def make_pdf(a, memo):
266
- from fpdf import FPDF
267
- from datetime import date
268
- pdf = FPDF(format="A4"); pdf.set_auto_page_break(True, margin=20); pdf.add_page()
269
- W, M, ink, mut = pdf.w, 18, (34, 44, 64), (120, 130, 150)
270
- def L(txt, h=6, size=11, style="", rgb=ink):
271
- pdf.set_x(M); pdf.set_font("Helvetica", style, size); pdf.set_text_color(*rgb)
272
- pdf.multi_cell(W - 2 * M, h, _ascii(txt))
273
- def section(t):
274
- pdf.ln(3); pdf.set_x(M); pdf.set_font("Helvetica", "B", 12); pdf.set_text_color(20, 90, 150)
275
- pdf.multi_cell(W - 2 * M, 7, _ascii(t))
276
- pdf.set_draw_color(205, 218, 236); pdf.set_line_width(0.3); y = pdf.get_y(); pdf.line(M, y, W - M, y); pdf.ln(2)
277
- # header band
278
- pdf.set_fill_color(11, 21, 36); pdf.rect(0, 0, W, 26, style="F")
279
- pdf.set_xy(M, 8); pdf.set_font("Helvetica", "B", 17); pdf.set_text_color(255, 255, 255); pdf.cell(20, 9, "BON")
280
- pdf.set_xy(M + 21, 9); pdf.set_font("Helvetica", "", 12); pdf.set_text_color(150, 200, 240); pdf.cell(70, 7, "Investigator Report")
281
- pdf.set_xy(W - M - 45, 10); pdf.set_font("Helvetica", "", 9); pdf.set_text_color(180, 200, 220)
282
- pdf.cell(45, 6, _ascii(date.today().isoformat()), align="R")
283
- # verdict badge
284
- vc = {"WALK AWAY": (214, 74, 90), "NEGOTIATE DOWN": (210, 150, 50), "PAY": (45, 170, 120)}.get(a["verdict"], (90, 110, 140))
285
- pdf.set_fill_color(*vc); pdf.rect(M, 34, W - 2 * M, 16, style="F")
286
- pdf.set_xy(M + 5, 37); pdf.set_font("Helvetica", "B", 14); pdf.set_text_color(255, 255, 255); pdf.cell(110, 10, _ascii(f"Verdict: {a['verdict']}"))
287
- pdf.set_xy(W - M - 60, 38); pdf.set_font("Helvetica", "B", 12); pdf.set_text_color(255, 255, 255); pdf.cell(55, 8, _ascii(f"Trust {a['trust']} / 100"), align="R")
288
- pdf.set_y(57)
289
- section("Analyst memo"); L(memo)
290
- section("Recommended actions")
291
- for x in a.get("actions", []): L(f"- {x}")
292
- section("Comparable cases")
293
- nn, nf = a.get("n_similar", 10), a.get("n_similar_fraud", 0)
294
- L(f"Compared to 10,000 labeled cases, {nf} of the {nn} most similar are fraudulent. Closest examples:")
295
- for c in a["similar"]:
296
- lbl = "likely fake" if c["fraud"] else "genuine"
297
- L(f"- {_PRETTY.get(c['archetype'], c['archetype'])} ({lbl}, {round(c['sim'] * 100)}% match)")
298
- section("Estimated value")
299
- L(f"Genuine reach: about {a['genuine_reach']:,} real followers.")
300
- L(f"Rough fair-value ceiling for one sponsored post: about ${a['fair_ceiling']:,}.")
301
- section("Red flags")
302
- for f in (a["red_flags"] or ["none"]): L(f"- {f}")
303
- pdf.ln(4)
304
- L("BON is a decision aid based on behavioral signals, not a verdict on a real person. Value figures are "
305
- "illustrative estimates, not financial advice.", 5, 9, "I", mut)
306
- path = "/tmp/BON_report.pdf"; pdf.output(path); return path
307
-
308
- def fallback_memo(a):
309
- lead = {"WALK AWAY": "This profile shows strong signs of an inauthentic audience.",
310
- "NEGOTIATE DOWN": "This profile looks partly real but padded.",
311
- "PAY": "This profile looks authentic."}.get(a["verdict"], "")
312
- flags = " ".join(a["red_flags"]) if a["red_flags"] else "No strong red flags were found."
313
- ring = " It also sits inside a coordinated bot ring." if a["in_ring"] else ""
314
- return humanize(f"{lead} Trust score {a['trust']} out of 100, with a fraud probability of "
315
- f"{a['fraud_probability']:.2f}. {flags}{ring} Recommendation: {a['verdict']}.")
316
-
317
- # ----------------------------------------------------------------------------
318
- # Gradio entry point: stream data JSON, then the memo
319
- # ----------------------------------------------------------------------------
320
- # Only the simple, public metrics a brand can actually get. Everything else is derived or optional.
321
- INPUT_FIELDS = ["platform", "niche", "follower_count", "following_count", "posts_count",
322
- "avg_likes", "avg_comments", "bio",
323
- "account_age_months", "avg_views",
324
- "audience_real_ratio", "audience_geo_mismatch", "growth_spike_score",
325
- "sample_comments", "post_caption", "audience_note"]
326
-
327
- def _num(x, d=0.0):
328
- try:
329
- f = float(x)
330
- return max(0.0, f)
331
- except (TypeError, ValueError):
332
- return d
333
-
334
- def build_row(v):
335
- foll = _num(v["follower_count"]); following = _num(v["following_count"])
336
- likes = _num(v["avg_likes"]); comments = _num(v["avg_comments"]); views = _num(v["avg_views"])
337
- return {
338
- "platform": v.get("platform") or "General",
339
- "niche": v["niche"] or "lifestyle",
340
- "follower_count": foll, "following_count": following,
341
- "posts_count": _num(v["posts_count"]),
342
- "account_age_months": _num(v["account_age_months"], 24.0), # neutral default if unknown
343
- "avg_likes": likes, "avg_comments": comments, "avg_views": views,
344
- # derived ratios (a brand never enters these directly)
345
- "engagement_rate": (likes + comments) / foll * 100 if foll > 0 else 0.0,
346
- "like_comment_ratio": likes / comments if comments > 0 else likes,
347
- "follower_following_ratio": foll / following if following > 0 else foll,
348
- "view_follower_ratio": views / foll if (views > 0 and foll > 0) else 1.0, # neutral if no video views
349
- # optional audit signals (neutral defaults if left alone)
350
- "growth_spike_score": min(1.0, _num(v["growth_spike_score"], 0.2)),
351
- "audience_geo_mismatch": min(1.0, _num(v["audience_geo_mismatch"], 0.2)),
352
- "audience_real_ratio": min(1.0, _num(v["audience_real_ratio"], 0.8)),
353
- "bio": v["bio"] or "", "sample_comments": v["sample_comments"] or "",
354
- "post_caption": v["post_caption"] or "", "audience_note": v["audience_note"] or "",
355
- }
356
-
357
- def investigate(*vals):
358
- v = dict(zip(INPUT_FIELDS, vals))
359
- a = analyze(build_row(v))
360
- try:
361
- memo = generate_memo(a)
362
- except Exception as e:
363
- print("generation failed, using fallback:", e)
364
- memo = fallback_memo(a)
365
- try:
366
- pdf = make_pdf(a, memo)
367
- except Exception as e:
368
- print("pdf failed:", e); pdf = None
369
- return json.dumps({**a, "done": True}), memo, pdf # data + memo + downloadable report
370
-
371
- # ----------------------------------------------------------------------------
372
- # Quick Starters (3 one-click examples)
373
- # ----------------------------------------------------------------------------
374
- PRESETS = {
375
- "clickfarm": {
376
- "platform": "Instagram",
377
- "niche": "crypto", "follower_count": 220000, "following_count": 410, "posts_count": 60,
378
- "avg_likes": 350, "avg_comments": 6, "account_age_months": 8, "avg_views": 120000,
379
- "audience_real_ratio": 0.28, "audience_geo_mismatch": 0.8, "growth_spike_score": 0.82,
380
- "bio": "Crypto signals daily. DM for VIP access. Guaranteed profits.",
381
- "sample_comments": "amazing signals || to the moon || best group || just joined",
382
- "post_caption": "New signal is live, do not miss it", "audience_note": "global crypto traders"},
383
- "authentic": {
384
- "platform": "Instagram",
385
- "niche": "fitness", "follower_count": 18000, "following_count": 620, "posts_count": 340,
386
- "avg_likes": 1600, "avg_comments": 140, "account_age_months": 41, "avg_views": 22000,
387
- "audience_real_ratio": 0.93, "audience_geo_mismatch": 0.15, "growth_spike_score": 0.12,
388
- "bio": "Coach sharing real training and honest progress.",
389
- "sample_comments": "this helped me so much || tried it today || love your form tips",
390
- "post_caption": "Week 6 of the program, here is what changed", "audience_note": "mostly local, engaged"},
391
- "boosted": {
392
- "platform": "Instagram",
393
- "niche": "beauty", "follower_count": 75000, "following_count": 900, "posts_count": 210,
394
- "avg_likes": 2100, "avg_comments": 60, "account_age_months": 22, "avg_views": 40000,
395
- "audience_real_ratio": 0.68, "audience_geo_mismatch": 0.32, "growth_spike_score": 0.5,
396
- "bio": "Beauty and skincare, sharing what works.",
397
- "sample_comments": "obsessed || need this || where is it from || nice",
398
- "post_caption": "My current everyday routine", "audience_note": "mixed regions"},
399
- }
400
- # text variations so each example run of a persona reads a little differently
401
- VARIANTS = {
402
- "clickfarm": {
403
- "bio": ["Crypto signals daily. DM for VIP access. Guaranteed profits.",
404
- "Daily crypto calls. Join the VIP group. Profits guaranteed.",
405
- "Free crypto signals. DM to join our winning group today."],
406
- "sample_comments": ["amazing signals || to the moon || best group || just joined",
407
- "to the moon || huge gains || best signals || joined now",
408
- "profit daily || legit group || just joined || lets go"]},
409
- "authentic": {
410
- "bio": ["Coach sharing real training and honest progress.",
411
- "Strength coach. Real programs, honest results, no hype.",
412
- "Helping people train smart. Real progress, no shortcuts."],
413
- "sample_comments": ["this helped me so much || tried it today || love your form tips",
414
- "so helpful || tried this today || your tips changed my training",
415
- "great advice || started this week || form tips are gold"]},
416
- "boosted": {
417
- "bio": ["Beauty and skincare, sharing what works.",
418
- "Skincare and beauty. Honest reviews of what actually works.",
419
- "Beauty tips and product picks that hold up."],
420
- "sample_comments": ["obsessed || need this || where is it from || nice",
421
- "love this || need it || where to buy || so pretty",
422
- "obsessed || adding to cart || where from || gorgeous"]},
423
- }
424
-
425
- # keep the authenticity signal inside each persona's band so the type never drifts
426
- REAL_BANDS = {"clickfarm": (0.20, 0.38), "authentic": (0.88, 0.97), "boosted": (0.60, 0.75)}
427
-
428
- def preset(name):
429
- p = dict(PRESETS[name])
430
- def jit(x, frac=0.15):
431
- return max(0, round(x * (1 + random.uniform(-frac, frac))))
432
- for k in ["follower_count", "following_count", "posts_count", "avg_likes",
433
- "avg_comments", "avg_views", "account_age_months"]:
434
- if isinstance(p.get(k), (int, float)):
435
- p[k] = jit(p[k])
436
- for k in ["audience_real_ratio", "audience_geo_mismatch", "growth_spike_score"]:
437
- if k in p:
438
- p[k] = round(min(1.0, max(0.0, p[k] + random.uniform(-0.05, 0.05))), 2)
439
- lo, hi = REAL_BANDS.get(name, (0.0, 1.0)) # clamp the key authenticity signal to the band
440
- p["audience_real_ratio"] = round(min(hi, max(lo, p["audience_real_ratio"])), 2)
441
- for k, opts in VARIANTS.get(name, {}).items():
442
- p[k] = random.choice(opts)
443
- return [p[k] for k in INPUT_FIELDS]
444
-
445
-
446
- # ----------------------------------------------------------------------------
447
- # UI: CSS + JS injected once via head; animation is client side and data driven
448
- # ----------------------------------------------------------------------------
449
- _here = os.path.dirname(os.path.abspath(__file__))
450
- def _read(name):
451
- p = os.path.join(_here, name)
452
- return open(p, encoding="utf-8").read() if os.path.exists(p) else ""
453
- HEAD = ("<script>window.BON_MAP=" + json.dumps(BON_MAP) + ";</script>"
454
- + f"<style>{_read('bon_ui.css')}</style><script>{_read('bon_ui.js')}</script>")
455
-
456
- with gr.Blocks(title="Bot Or Not", head=HEAD, theme=gr.themes.Base()) as demo:
457
- gr.HTML("<div class='bon-hero'><h1>Start an Investigation</h1>"
458
- "<p>Investigate any creator across Instagram, TikTok, or YouTube</p>"
459
- "<div class='bon-tagline'>"
460
- "<div class='l1'>Every influencer tells a story. BON helps you discover whether it's real.</div>"
461
- "<div class='l2'>BON, the AI Investigator</div>"
462
- "</div></div>")
463
- with gr.Row(elem_id="bon-hero-actions"):
464
- manual_btn = gr.Button("Analyze Manually", variant="primary", elem_id="bon-analyze-manual")
465
- scan_btn = gr.Button("Instant Creator Scan", elem_id="bon-scan")
466
- gr.HTML('<div class="bon-coming">Instant Creator Scan is coming soon</div>')
467
-
468
- with gr.Column(visible=False, elem_id="bon-form") as manual_acc:
469
- with gr.Row():
470
- starter1 = gr.Button("Example: a likely-fake account")
471
- starter2 = gr.Button("Example: a genuine creator")
472
- starter3 = gr.Button("Example: a borderline case")
473
- gr.HTML('<div class="bon-hint"><b>New here?</b> Click a <b>Quick Starter</b> above to run a full '
474
- 'example, then edit the numbers. Enter only what you can see on the public profile. '
475
- 'Everything else is optional.</div>')
476
- comps = {}
477
- with gr.Row():
478
- comps["platform"] = gr.Dropdown(["General", "Instagram", "TikTok", "YouTube"],
479
- value="General", label="platform")
480
- comps["niche"] = gr.Dropdown(["lifestyle", "crypto", "fitness", "beauty", "fashion", "tech",
481
- "travel", "food", "gaming"], value="lifestyle", label="niche")
482
- with gr.Row():
483
- comps["follower_count"] = gr.Number(label="followers", value=0, minimum=0)
484
- comps["following_count"] = gr.Number(label="accounts they follow", value=0, minimum=0)
485
- with gr.Row():
486
- comps["posts_count"] = gr.Number(label="total posts", value=0, minimum=0)
487
- comps["avg_likes"] = gr.Number(label="avg likes per post (estimate)", value=0, minimum=0)
488
- comps["avg_comments"] = gr.Number(label="avg comments per post (estimate)", value=0, minimum=0)
489
- comps["bio"] = gr.Textbox(label="bio (optional)", lines=2, placeholder="Paste the profile bio")
490
- with gr.Accordion("Advanced (optional)", open=False):
491
- gr.Markdown("Add any of these if you have them. The analysis runs fine without them.")
492
- comps["account_age_months"] = gr.Number(label="account age in months (if known)", value=0, minimum=0)
493
- comps["avg_views"] = gr.Number(label="avg views per post (video, e.g. TikTok or Reels)", value=0, minimum=0)
494
- comps["audience_real_ratio"] = gr.Slider(0, 1, value=0.8, step=0.01, label="share of real followers",
495
- info="0 to 1. 0.9 means about 90 percent of followers look genuine.")
496
- comps["audience_geo_mismatch"] = gr.Slider(0, 1, value=0.2, step=0.01, label="audience geo mismatch",
497
- info="0 to 1. Higher means more followers in unrelated countries.")
498
- comps["growth_spike_score"] = gr.Slider(0, 1, value=0.2, step=0.01, label="growth spike score",
499
- info="0 to 1. Higher means sudden, unnatural jumps in followers.")
500
- comps["sample_comments"] = gr.Textbox(label="sample comments (optional)", lines=2,
501
- placeholder="great || love this || where can I buy")
502
- comps["post_caption"] = gr.Textbox(label="post caption (optional)", lines=1,
503
- placeholder="New drop is live")
504
- comps["audience_note"] = gr.Textbox(label="audience note (optional)", lines=1,
505
- placeholder="mostly US, ages 18 to 24")
506
- run_btn = gr.Button("Investigate", variant="primary", elem_id="bon-investigate")
507
-
508
- gr.HTML('<div id="bon-stage-mount"></div>') # animation stage renders here, below the form
509
-
510
- report_dl = gr.DownloadButton("Export PDF report", elem_id="bon-dl")
511
- data_box = gr.Textbox(visible=False, elem_id="bon-data")
512
- memo_box = gr.Textbox(visible=False, elem_id="bon-memo")
513
-
514
- ordered = [comps[k] for k in INPUT_FIELDS]
515
-
516
- # start the animation on click, then run the streaming analysis
517
- run_btn.click(None, None, None, js="() => window.BON && window.BON.begin()")
518
- run_btn.click(investigate, ordered, [data_box, memo_box, report_dl])
519
-
520
- # feed real data and streamed memo into the animation
521
- data_box.change(None, data_box, None, js="(v) => window.BON && window.BON.onData(v)")
522
- memo_box.change(None, memo_box, None, js="(v) => window.BON && window.BON.onMemo(v)")
523
-
524
- # landing: "Analyze Manually" opens the existing workflow; "Instant Creator Scan" opens a coming-soon modal
525
- manual_btn.click(lambda: gr.update(visible=True), None, manual_acc).then(
526
- None, None, None,
527
- js="() => setTimeout(function(){var e=document.getElementById('bon-form'); if(e) e.scrollIntoView({behavior:'smooth', block:'start'});}, 130)")
528
- scan_btn.click(None, None, None, js="() => window.bonShowScanModal && window.bonShowScanModal()")
529
-
530
- # quick starters fill the form, then auto-run
531
- for b, key in [(starter1, "clickfarm"), (starter2, "authentic"), (starter3, "boosted")]:
532
- b.click(lambda k=key: preset(k), None, ordered).then(
533
- None, None, None, js="() => document.getElementById('bon-investigate').click()")
534
-
535
- if __name__ == "__main__":
536
- demo.queue().launch()