web / webapp /app.py
LinJennyLin's picture
Upload webapp/app.py with huggingface_hub
03022c2 verified
Raw History Blame
13.4 kB
"""Flask app β€” the shippable front end.
Routes:
/ landing + "paste a wallet" scorer form + email capture
/score GET ?wallet=0x… -> live consistency score card (lead magnet)
/digest latest daily digest rendered as HTML (SEO surface)
/subscribe POST email -> data/subscribers.csv
Run:
cd polymarket-copytrade && source .venv/bin/activate
python webapp/app.py # http://127.0.0.1:5000
"""
from __future__ import annotations
import csv
import re
import os
import sys
from datetime import datetime, timezone
from html import escape
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(_ROOT))
os.chdir(_ROOT) # so config.yaml + data/ resolve regardless of launch cwd
from flask import Flask, request, redirect, url_for
from pmct.client import PolymarketClient
from pmct.score import score_wallet
from pmct.util import load_config, cache_path
app = Flask(__name__)
_cfg = load_config()
_client = PolymarketClient(sleep_sec=0.1)
BRAND = "SharpFlow"
TAGLINE = "The Polymarket smart-money tracker whale trackers miss."
CSS = """
:root{--bg:#0b0e14;--card:#141a24;--ink:#e6edf3;--mut:#8b98a9;--acc:#3fb950;
--warn:#d29922;--bad:#f85149;--line:#232b38}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);
font:16px/1.55 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif}
a{color:#58a6ff;text-decoration:none}.wrap{max-width:820px;margin:0 auto;padding:32px 20px}
.brand{font-weight:800;font-size:22px;letter-spacing:-.02em}.brand span{color:var(--acc)}
.hero{margin:28px 0 10px}.hero h1{font-size:34px;line-height:1.15;margin:0 0 10px;letter-spacing:-.02em}
.hero p{color:var(--mut);font-size:18px;margin:0}
.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:22px;margin:18px 0}
input[type=text],input[type=email]{width:100%;padding:13px 14px;border-radius:10px;
border:1px solid var(--line);background:#0d1219;color:var(--ink);font-size:15px}
.row{display:flex;gap:10px;flex-wrap:wrap}.row>*{flex:1;min-width:180px}
button{background:var(--acc);color:#04130a;border:0;border-radius:10px;padding:13px 18px;
font-weight:700;font-size:15px;cursor:pointer;white-space:nowrap;flex:0 0 auto}
button.ghost{background:transparent;color:var(--ink);border:1px solid var(--line)}
.mut{color:var(--mut)}.small{font-size:13px}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
.tag{display:inline-block;padding:3px 10px;border-radius:999px;font-size:12px;font-weight:700}
.tag.watch{background:#12331d;color:var(--acc)}.tag.whale{background:#3a2f10;color:var(--warn)}
.tag.maker{background:#3a1414;color:var(--bad)}.tag.inconsistent{background:#2a2033;color:#c98bff}
.tag.thin,.tag.bad{background:#20262f;color:var(--mut)}
.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:14px}
.metric{background:#0d1219;border:1px solid var(--line);border-radius:10px;padding:12px}
.metric .k{color:var(--mut);font-size:12px}.metric .v{font-size:20px;font-weight:700;margin-top:2px}
.bar{height:8px;background:#0d1219;border-radius:6px;overflow:hidden;margin-top:6px}
.bar>i{display:block;height:100%;background:var(--acc)}
table{border-collapse:collapse;width:100%;font-size:14px}th,td{border-bottom:1px solid var(--line);
padding:8px 6px;text-align:left}th{color:var(--mut);font-weight:600}
.foot{color:var(--mut);font-size:12px;margin-top:26px;border-top:1px solid var(--line);padding-top:16px}
.pill{border:1px solid var(--line);border-radius:999px;padding:4px 12px;font-size:13px;color:var(--mut)}
.nav{display:flex;align-items:center;justify-content:space-between;gap:16px;
padding-bottom:12px;border-bottom:1px solid var(--line)}
.nav .brand{text-decoration:none;color:var(--ink)}
.navlinks{display:flex;gap:20px}.navlinks a{color:var(--mut);font-weight:600;font-size:14px}
.navlinks a:hover{color:var(--ink)}
.examples{margin-top:14px;display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.exlabel{color:var(--mut);font-size:13px;margin-right:2px}
.chip{border:1px solid var(--line);background:#0d1219;border-radius:999px;
padding:6px 12px;font-size:13px;color:var(--ink)}
.chip:hover{border-color:var(--acc);color:var(--acc)}
"""
# Real wallets that showcase the product's judgement β€” one to follow, one too big
# to mirror, one uncopyable. Doubles as the "try it" hook so a first-time visitor
# never dead-ends on a random address with no Polymarket history.
EXAMPLES = [
("Consistent mid-size", "0x65018f9fc473f6e920b8929a375d39c26a461220"),
("Mega-whale", "0xd235973291b2b75ff4070e9c0b01728c520b0f29"),
("Market-maker", "0xa6cd8300ff70129ced69975180609e40a12b2f2c"),
]
def example_chips(label: str = "Try a real trader:") -> str:
chips = "".join(
f'<a class=chip href="/score?wallet={w}">{escape(t)}</a>' for t, w in EXAMPLES
)
return f'<div class=examples><span class=exlabel>{escape(label)}</span>{chips}</div>'
TAGLABEL = {"watch": "WORTH WATCHING", "whale": "MEGA-WHALE",
"maker": "MARKET-MAKER", "inconsistent": "INCONSISTENT",
"thin": "TOO THIN", "bad": "INVALID"}
def page(title: str, body: str) -> str:
return f"""<!doctype html><html lang=en><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>{escape(title)}</title><meta name=description content="{escape(TAGLINE)}">
<style>{CSS}</style></head><body><div class=wrap>
<div class=nav><a class=brand href="/"><span>β—†</span> {BRAND}</a>
<div class=navlinks><a href="/">Score a wallet</a><a href="/digest">Daily digest</a></div></div>
{body}
<div class=foot>Built from Polymarket public data. <b>Flow intelligence, not financial
advice.</b> Consistency scoring β‰  guaranteed profit. Past performance is not predictive.</div>
</div></body></html>"""
def scorer_form(prefill: str = "") -> str:
return f"""<form action="/score" method=get class=row>
<input type=text name=wallet placeholder="Paste a Polymarket wallet: 0x…"
value="{escape(prefill)}" autocomplete=off spellcheck=false>
<button type=submit>Score it β†’</button></form>"""
@app.route("/")
def home():
body = f"""
<div class=hero><h1>{escape(TAGLINE)}</h1>
<p>Paste any <b>Polymarket wallet</b> and we score it β€” consistent smart money, a whale,
a market-maker, or just lucky. Every tracker flags $10k whales; we surface the
<b>consistent mid-size Polymarket traders</b> they skip.</p></div>
<div class=card><h3 style="margin:0 0 12px">Score any wallet β€” free</h3>
{scorer_form()}
{example_chips()}
<p class="mut small" style="margin:12px 0 0">Paste any Polymarket address. We read its
history and tell you: consistent & copyable, a whale, a market-maker, or just lucky.</p>
</div>
<div class=card><h3 style="margin:0 0 8px">Get the daily digest</h3>
<p class="mut" style="margin:0 0 12px">The top consistent traders and their highest-conviction
moves, once a day. Free tier delayed 24h.</p>
<form action="/subscribe" method=post class=row>
<input type=email name=email placeholder="you@email.com" required>
<button type=submit>Subscribe free</button></form></div>
"""
return page(f"{BRAND} β€” {TAGLINE}", body)
@app.route("/score")
def score():
wallet = (request.args.get("wallet") or "").strip()
if not wallet:
return redirect(url_for("home"))
r = score_wallet(_client, wallet)
if not r.ok:
body = f"""<div class=hero><h1>Nothing to score here</h1>
<p>{escape(r.note)} This wallet has no Polymarket trading history we can read β€”
try a real trader below.</p></div>
<div class=card>{scorer_form(wallet)}
{example_chips("Or try one of these:")}</div>"""
return page(f"{BRAND} β€” score", body)
tag = r.verdict_tag or "thin"
pct = int(round(r.trader_score * 100))
short = f"{r.wallet[:8]}…{r.wallet[-6:]}"
prof = f"https://polymarket.com/profile/{r.wallet}"
body = f"""
<div class=hero><a class="pill mono" href="{escape(prof, quote=True)}" target=_blank rel=noopener title="Verify on Polymarket" style="display:inline-block;margin-bottom:10px;text-decoration:none">{escape(r.wallet)} β†—</a>
<h1 style="margin:6px 0">Trader score: {r.trader_score:.2f}
<span class="tag {tag}">{TAGLABEL.get(tag,tag.upper())}</span></h1>
<div class=bar style="max-width:360px"><i style="width:{pct}%"></i></div>
<p style="margin-top:14px">{escape(r.verdict)}</p></div>
<div class=grid>
<div class=metric><div class=k>Consistency (green months)</div><div class=v>{r.monthly_profit_ratio:.0%}</div></div>
<div class=metric><div class=k>Repeatability</div><div class=v>{r.repeatability:.2f}</div></div>
<div class=metric><div class=k>Copyable (1 βˆ’ rebate)</div><div class=v>{max(0,1-r.rebate_share):.0%}</div></div>
<div class=metric><div class=k>Reconstructed PnL</div><div class=v>${r.total_pnl:,.0f}</div></div>
<div class=metric><div class=k>Avg bet size</div><div class=v>${r.avg_trade_usdc:,.0f}</div></div>
<div class=metric><div class=k>Trades Β· resolved</div><div class=v>{r.n_trades:,} Β· {r.n_resolved_markets}</div></div>
</div>
<div class=card style="margin-top:18px"><b>Score another</b>{scorer_form()}</div>
<p class="mut small">{escape(r.note)}</p>
"""
return page(f"{BRAND} β€” {short} scored", body)
_TABLE_RE = re.compile(r"^\|(.+)\|\s*$")
_LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\s)]+)\)")
_BOLD_RE = re.compile(r"\*\*([^*]+)\*\*")
def _inline(text: str) -> str:
"""Escape text, then render inline **bold** and [label](https url) links.
Links are restricted to http/https so escaped content stays injection-safe."""
out, i = [], 0
for mm in _LINK_RE.finditer(text):
out.append(_bold(text[i:mm.start()]))
label, url = mm.group(1), mm.group(2)
out.append(f'<a href="{escape(url, quote=True)}" target=_blank rel=noopener>{escape(label)}</a>')
i = mm.end()
out.append(_bold(text[i:]))
return "".join(out)
def _bold(text: str) -> str:
parts, i = [], 0
for mm in _BOLD_RE.finditer(text):
parts.append(escape(text[i:mm.start()]))
parts.append(f"<b>{escape(mm.group(1))}</b>")
i = mm.end()
parts.append(escape(text[i:]))
return "".join(parts)
def _md_to_html(md: str) -> str:
"""Tiny markdown renderer: headings, tables, hr, paragraphs. Enough for our
own digest output β€” not a general parser."""
out, rows = [], []
def flush_table():
if not rows:
return
cells = [[c.strip() for c in r.strip("|").split("|")] for r in rows]
body = cells[2:] if len(cells) > 1 and set("".join(cells[1])) <= set("-: ") else cells[1:]
head = cells[0]
h = "".join(f"<th>{_inline(c)}</th>" for c in head)
b = "".join("<tr>" + "".join(f"<td>{_inline(c)}</td>" for c in r) + "</tr>" for r in body)
out.append(f"<table><thead><tr>{h}</tr></thead><tbody>{b}</tbody></table>")
rows.clear()
for ln in md.splitlines():
if _TABLE_RE.match(ln):
rows.append(ln)
continue
flush_table()
s = ln.strip()
if not s:
continue
if s.startswith("### "):
out.append(f"<h3>{escape(s[4:])}</h3>")
elif s.startswith("## "):
out.append(f"<h2>{escape(s[3:])}</h2>")
elif s.startswith("# "):
out.append(f"<h1>{escape(s[2:])}</h1>")
elif s == "---":
out.append("<hr style='border:0;border-top:1px solid var(--line)'>")
else:
out.append(f"<p class=mut>{_inline(s.replace('_', ''))}</p>")
flush_table()
return "\n".join(out)
@app.route("/digest")
def digest():
files = sorted(cache_path(_cfg, ".").glob("digest_*.md"))
if not files:
return page(f"{BRAND} β€” digest",
"<div class=hero><h1>No digest yet</h1>"
"<p class=mut>Run <code>python scripts/05_digest.py</code> to generate one.</p></div>")
md = files[-1].read_text(encoding="utf-8")
body = f"<div class=card>{_md_to_html(md)}</div>" \
f"<div class=card><b>Want it daily by email?</b>" \
f"<form action='/subscribe' method=post class=row style='margin-top:10px'>" \
f"<input type=email name=email placeholder='you@email.com' required>" \
f"<button type=submit>Subscribe free</button></form></div>"
return page(f"{BRAND} β€” daily digest", body)
@app.route("/subscribe", methods=["POST"])
def subscribe():
email = (request.form.get("email") or "").strip().lower()
if "@" in email and "." in email:
path = cache_path(_cfg, "subscribers.csv")
new = not path.exists()
with path.open("a", newline="") as f:
w = csv.writer(f)
if new:
w.writerow(["email", "ts_utc"])
w.writerow([email, datetime.now(timezone.utc).isoformat()])
msg = "You're in. First digest lands next run."
else:
msg = "That email didn't look right β€” try again."
return page(f"{BRAND} β€” subscribed",
f"<div class=hero><h1>{escape(msg)}</h1></div>"
f"<div class=card>{scorer_form()}"
f"<p class='mut small' style='margin-top:10px'>Meanwhile, score any wallet above.</p></div>")
if __name__ == "__main__":
port = int(os.environ.get("PORT", "5055"))
app.run(host="127.0.0.1", port=port, debug=False)