Site Preview Kit: helper scripts
The 7 small Python scripts the Site Preview Kit prompts call (Places search, site scoring, detail extraction, site check, review list, safe sender). Part 2 of 2.
Free (Python 3, standard library only)
How to install
SITE PREVIEW KIT, part 2 of 2: the helper scripts (Python 3, standard library only). The other REVAMP row has the setup guide, the hard rules and the prompts.
HOW TO USE: make a new empty folder, open Claude Code in it and paste: "Create each file below exactly as written, with the path shown after FILE:. Change nothing. Then run python scripts/send_approved.py --help to check it works." Then follow the guide in the other row. Safety built in: send_approved.py refuses to send to any real website unless you add --live yourself, stops at a CAPTCHA, blocks messages with no opt-out line, and stops at the daily cap of 5. Read it before you trust it.
=== FILE: scripts/places_search.py === #!/usr/bin/env python3 """Step 1: find local businesses with the OFFICIAL Google Places API (New). No scraping.
Stores PLACE IDs ONLY (Google allows place IDs to be stored). Website and phone are fetched live for one place at a time (Place Details) and kept in a temporary work file you delete after use.
python places_search.py search --query "picture framing in Marrow Bay" --out work/place_ids.json
python places_search.py details --ids work/place_ids.json --limit 5 --out work/details.tmp.json
python places_search.py purge (deletes the temp details file)Add --dry-run to print the exact HTTP request and send nothing (also the behaviour when no key is set). The key is read from the environment variable GOOGLE_PLACES_API_KEY. Never put it in a file. Python standard library only. """ import argparse, json, os, sys, urllib.request, urllib.error
SEARCH_URL = "https://places.googleapis.com/v1/places:searchText" DETAILS_URL = "https://places.googleapis.com/v1/places/{id}" SEARCH_MASK = "places.id" # Text Search Essentials ID Only SKU DETAILS_MASK = "id,displayName,websiteUri,nationalPhoneNumber,formattedAddress" # Enterprise SKU HARD_CAP = 20 # never more than this in one run, whatever the flag says TMP = "work/details.tmp.json"
def call(method, url, key, mask, body=None, dry=False): headers = {"Content-Type": "application/json", "X-Goog-FieldMask": mask} if dry or not key: shown = dict(headers, **{"X-Goog-Api-Key": "<YOUR_KEY>"}) print(f"[DRY RUN] {method} {url}") for k, v in shown.items(): print(f" {k}: {v}") if body is not None: print(" body:", json.dumps(body)) if not key and not dry: print(" (no GOOGLE_PLACES_API_KEY set: nothing was sent)") return None headers["X-Goog-Api-Key"] = key data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=30) as r: return json.load(r) except urllib.error.HTTPError as e: sys.exit(f"Places API error {e.code}: {e.read().decode()[:400]}")
def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) s = sub.add_parser("search") s.add_argument("--query", required=True) s.add_argument("--limit", type=int, default=5) s.add_argument("--out", default="work/place_ids.json") s.add_argument("--dry-run", action="store_true") d = sub.add_parser("details") d.add_argument("--ids", default="work/place_ids.json") d.add_argument("--limit", type=int, default=5) d.add_argument("--out", default=TMP) d.add_argument("--dry-run", action="store_true") sub.add_parser("purge") a = ap.parse_args() key = os.environ.get("GOOGLE_PLACES_API_KEY", "")
if a.cmd == "purge": if os.path.exists(TMP): os.remove(TMP) print("deleted", TMP) return limit = min(a.limit, HARD_CAP) os.makedirs("work", exist_ok=True) if a.cmd == "search": body = {"textQuery": a.query, "pageSize": limit} res = call("POST", SEARCH_URL, key, SEARCH_MASK, body, a.dry_run) if res is None: return ids = [p["id"] for p in res.get("places", [])][:limit] json.dump({"query": a.query, "place_ids": ids}, open(a.out, "w"), indent=2) print(f"saved {len(ids)} place IDs to {a.out} (IDs only)") else: ids = json.load(open(a.ids))["place_ids"][:limit] out = [] for pid in ids: r = call("GET", DETAILS_URL.format(id=pid), key, DETAILS_MASK, None, a.dry_run) if r: out.append({"id": r.get("id"), "name": r.get("displayName", {}).get("text"), "website": r.get("websiteUri"), "phone": r.get("nationalPhoneNumber"), "address": r.get("formattedAddress")}) if out: json.dump(out, open(a.out, "w"), indent=2) print(f"wrote {len(out)} businesses to {a.out}. TEMPORARY: run 'purge' when the batch is done.")
if __name__ == "__main__": main()
=== FILE: scripts/score_site.py === #!/usr/bin/env python3 """Step 2: judge whether a site looks outdated. Reads one URL or local .html file, prints a score 0-100 (higher = more outdated) and the reasons. Heuristic only; a human (you) makes the call.
python score_site.py ../../demo/old-site/index.html""" import re, sys, urllib.request, json
CHECKS = [ # (label, regex on lowercased html, points) ("uses <font> tags", r"<font\b", 12), ("uses <marquee>/<blink>", r"<(marquee|blink)\b", 15), ("table-based layout", r"<table[^>]*(border|cellpadding|bgcolor)", 12), ("old bgcolor/vlink attributes", r"(bgcolor|vlink)=", 8), ("'under construction' / 'best viewed in'", r"under construction|best viewed in", 12), ("visitor counter / guestbook", r"visitor number|guestbook|hit counter", 8), ("Flash / frames", r"<(embed|frameset|frame)\b|\.swf", 10), ] NEGATIVE = [ # modern signals reduce the score ("responsive viewport meta", r"name=.viewport", -15), ("modern CSS (flex/grid/media query)", r"display:\s*(flex|grid)|@media", -15), ]
def load(src): if re.match(r"https?://", src): req = urllib.request.Request(src, headers={"User-Agent": "SitePreviewKit-check/1.0"}) return urllib.request.urlopen(req, timeout=20).read().decode("utf-8", "replace") return open(src, encoding="utf-8", errors="replace").read()
def main(): html = load(sys.argv[1]) low = html.lower() score, why = 0, [] for label, rx, pts in CHECKS + NEGATIVE: if re.search(rx, low): score += pts why.append((label, pts)) years = [int(y) for y in re.findall(r"(?:copyright|©|updated)[^<]{0,40}?((?:19|20)\d\d)", low)] if years and max(years) <= 2018: score += 20 why.append((f"last year mentioned: {max(years)}", 20)) score = max(0, min(100, score)) verdict = "OUTDATED" if score >= 45 else "maybe" if score >= 25 else "looks current" print(json.dumps({"source": sys.argv[1], "score": score, "verdict": verdict, "reasons": [f"{l} ({p:+d})" for l, p in why]}, indent=2))
if __name__ == "__main__": main()
=== FILE: scripts/extract_details.py === #!/usr/bin/env python3 """Step 3: read the real details from an old site (one URL or file) into details.json. Pulls: title, phones, emails, headings, list items (services), quotes, hours, images, contact page link. Claude then writes the copy from this file ONLY and must not invent facts. Standard library only.
python extract_details.py ../../demo/old-site/index.html --out ../../demo/out/details.json""" import argparse, json, re, urllib.request from html.parser import HTMLParser
class P(HTMLParser): def __init__(s): super().__init__() s.title = ""; s.in_title = False; s.h = []; s.li = []; s.cur = None s.text = []; s.imgs = []; s.links = []; s.skip = 0
def handle_starttag(s, t, a): a = dict(a) if t == "title": s.in_title = True if t in ("script", "style"): s.skip += 1 if t in ("h1", "h2", "h3", "li"): s.cur = t if t in ("br", "p", "li", "h1", "h2", "h3", "tr"): s.text.append("\n") if t == "img" and a.get("src"): s.imgs.append({"src": a["src"], "alt": a.get("alt", "")}) if t == "a" and a.get("href"): s.links.append(a["href"])
def handle_endtag(s, t): if t == "title": s.in_title = False if t in ("script", "style"): s.skip -= 1 if t == s.cur: s.cur = None
def handle_data(s, d): if s.skip: return if s.in_title: s.title += d d2 = " ".join(d.split()) if not d2: return s.text.append(d2) if s.cur in ("h1", "h2", "h3"): s.h.append(d2) if s.cur == "li": s.li.append(d2)
def load(src): if re.match(r"https?://", src): req = urllib.request.Request(src, headers={"User-Agent": "SitePreviewKit-check/1.0"}) return urllib.request.urlopen(req, timeout=20).read().decode("utf-8", "replace") return open(src, encoding="utf-8", errors="replace").read()
ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("--out", default="details.json") a = ap.parse_args() html = load(a.src) p = P() p.feed(html) lines = [" ".join(l.split()) for l in " ".join(p.text).split("\n")] lines = [l for l in lines if l] text = "\n".join(lines) flat = " ".join(lines) data = { "source": a.src, "business_name": " ".join(p.title.split()).split(" - ")[0], "phones": sorted(set(x.strip() for x in re.findall(r"\(\d{3}\)\s?\d{3}-\d{4}|\+?\d[\d ]{2,}[\d-]{6,}", flat))), "emails": sorted(set(re.findall(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+", html))), "address_lines": [l for l in lines if re.match(r"\d+\s+[A-Z][a-z]+ (Lane|Street|St|Road|Rd|Ave|Avenue)\b", l)], "headings": p.h, "services_or_list_items": p.li, "quotes": [{"text": q, "by": b.split(" You are")[0].strip()} for q, b in re.findall(r"\"([^\"]{20,200})\"\s*-\s*([^\n]{2,40})", text)], "hours_lines": [l for l in lines if re.match(r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun|Closed)", l)], "images": p.imgs, "links": sorted(set(p.links)), "contact_page": next((l for l in p.links if "contact" in l.lower()), None), "visible_text": flat[:4000], "note": "Quotes are the business's own testimonials: say 'from the old site' unless the owner confirms.", } json.dump(data, open(a.out, "w"), indent=2) print(f"wrote {a.out}: {len(data['phones'])} phone(s), {len(data['services_or_list_items'])} list items, {len(data['images'])} images")
=== FILE: scripts/check_site.py === #!/usr/bin/env python3 """Step 4/5 check: is the new site safe and faithful? Run on the built folder before you deploy.
python check_site.py ../../demo/new-site ../../demo/out/details.jsonChecks: noindex meta on every page, _headers X-Robots-Tag, robots.txt disallow, viewport meta, the real phone and address from details.json are present, no external requests, sample-marked testimonials. Exit code 1 if anything fails.""" import glob, json, os, re, sys
root, details = sys.argv[1], json.load(open(sys.argv[2], encoding="utf-8")) fails = [] pages = glob.glob(os.path.join(root, "**", "*.html"), recursive=True) alltext = "" for p in pages: h = open(p, encoding="utf-8").read(); alltext += h if not re.search(r'<meta[^>]+name="robots"[^>]+noindex', h, re.I): fails.append(f"{p}: no noindex meta") if "viewport" not in h: fails.append(f"{p}: no viewport meta") if re.search(r'(src|href)="https?://(?!127\.0\.0\.1|localhost)', h): fails.append(f"{p}: external request") hdr = os.path.join(root, "_headers") if not (os.path.exists(hdr) and "noindex" in open(hdr).read()): fails.append("_headers with X-Robots-Tag noindex missing") rb = os.path.join(root, "robots.txt") if not (os.path.exists(rb) and "Disallow: /" in open(rb).read()): fails.append("robots.txt Disallow missing") flat = re.sub(r"\s+", " ", alltext) for ph in details["phones"]: if ph not in flat: fails.append(f"phone not found: {ph}") for ad in details["address_lines"][:1]: street = ad.split(",")[0].split(":")[-1].strip() if street[-20:] not in flat: fails.append(f"address not found: {street}") for q in details["quotes"]: if q["text"][:30] not in flat: continue if "from the old site" not in flat.lower() and "sample" not in flat.lower(): fails.append("testimonials not labelled") print(f"{len(pages)} page(s) checked") print("PASS" if not fails else "FAIL:\n " + "\n ".join(fails)) sys.exit(1 if fails else 0)
=== FILE: scripts/review.py === #!/usr/bin/env python3 """Step 7a: the REVIEW LIST. Nothing is sent until you approve each item here.
python review.py show review.json # print every old site, preview link and message
python review.py approve review.json demo-001 # mark one item approved (you read it first)
python review.py skip review.json demo-001review.json is a list of items: {"id","business","old_site","contact_url","preview_url","message","subject","approved":false,"sent":false} Approval is a deliberate per-item action. There is no 'approve all'. """ import json, sys
cmd, path = sys.argv[1], sys.argv[2] items = json.load(open(path, encoding="utf-8")) if cmd == "show": for i in items: flag = "APPROVED" if i.get("approved") else "pending" print(f"--- {i['id']} | {i['business']} | {flag} | sent={i.get('sent', False)}") print(f"old site : {i['old_site']}\nnew site : {i['preview_url']}\nform : {i['contact_url']}") print(f"subject : {i['subject']}\n{i['message']}\n") else: target = sys.argv[3] for i in items: if i["id"] == target: i["approved"] = cmd == "approve" print(f"{target}: approved={i['approved']}") json.dump(items, open(path, "w", encoding="utf-8"), indent=2)
=== FILE: scripts/local_test_form.py === #!/usr/bin/env python3 """A LOCAL test contact-form receiver. Listens on 127.0.0.1 only. Every POST /contact is appended to outbox.jsonl (nothing is emailed, nothing leaves this PC). Also serves a folder so the old/new demo sites open in a browser.
python local_test_form.py --serve ../../demo --port 8765 --outbox ../../demo/out/outbox.jsonlThen open http://127.0.0.1:8765/old-site/index.html """ import argparse, json, os, time, functools from http.server import HTTPServer, SimpleHTTPRequestHandler from urllib.parse import parse_qs
ap = argparse.ArgumentParser() ap.add_argument("--serve", default=".") ap.add_argument("--port", type=int, default=8765) ap.add_argument("--outbox", default="outbox.jsonl") a = ap.parse_args()
class H(SimpleHTTPRequestHandler): def do_POST(self): n = int(self.headers.get("Content-Length", 0)) form = {k: v[0] for k, v in parse_qs(self.rfile.read(n).decode()).items()} rec = {"received": time.strftime("%Y-%m-%d %H:%M:%S"), "path": self.path, "form": form} with open(a.outbox, "a", encoding="utf-8") as f: f.write(json.dumps(rec) + "\n") body = b"<html><body style='font-family:sans-serif'><h2>Thank you!</h2><p>Your message was received (local test form).</p></body></html>" self.send_response(200) self.send_header("Content-Type", "text/html") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body)
def end_headers(self): self.send_header("Access-Control-Allow-Origin", "*") super().end_headers()
os.makedirs(os.path.dirname(os.path.abspath(a.outbox)), exist_ok=True) handler = functools.partial(H, directory=a.serve) print(f"serving {a.serve} on http://127.0.0.1:{a.port} (form posts logged to {a.outbox})") HTTPServer(("127.0.0.1", a.port), handler).serve_forever()
=== FILE: scripts/send_approved.py === #!/usr/bin/env python3 """Step 7b: send ONLY approved items through a plain HTML contact form. Built-in safety rules:
- Only items with approved=true and sent=false.
- Daily cap: default 5 (--cap), counted from sent_log.jsonl. Hard ceiling 10.
- Every message must name the sender, contain the opt-out line, the preview link, and a postal address
(checked against sender.json). Otherwise the item is blocked.
- CAPTCHA (reCAPTCHA, hCaptcha, Turnstile, 'captcha' fields) or no plain form found: the item is
FLAGGED for you and NOT sent. This script never tries to get around a CAPTCHA.
- Domains listed in optout.txt (one per line) are never contacted.
- By default only local test hosts (127.0.0.1 / localhost) are allowed. Real sites need --live,
which is for you to switch on yourself after reading the guide.
python send_approved.py review.json sender.json --log sent_log.jsonl""" import argparse, json, re, sys, time, urllib.parse, urllib.request from html.parser import HTMLParser
CAPTCHA_RX = re.compile(r"g-recaptcha|recaptcha|h-captcha|hcaptcha|cf-turnstile|turnstile|captcha", re.I) HARD_CEILING = 10
class FormFinder(HTMLParser): def __init__(s): super().__init__(); s.forms = []; s.cur = None; s.in_ta = None def handle_starttag(s, t, a): a = dict(a) if t == "form": s.cur = {"action": a.get("action", ""), "method": a.get("method", "get").lower(), "fields": []}; s.forms.append(s.cur) elif s.cur is not None and t in ("input", "textarea", "select") and a.get("name"): s.cur["fields"].append({"name": a["name"], "type": a.get("type", t), "value": a.get("value", "")}) def handle_endtag(s, t): if t == "form": s.cur = None
def fetch(url): req = urllib.request.Request(url, headers={"User-Agent": "SitePreviewKit-sender/1.0 (identified sender)"}) return urllib.request.urlopen(req, timeout=20).read().decode("utf-8", "replace")
def is_local(url): return urllib.parse.urlparse(url).hostname in ("127.0.0.1", "localhost")
def sent_today(log): today = time.strftime("%Y-%m-%d") try: return sum(1 for l in open(log, encoding="utf-8") if json.loads(l).get("date") == today and json.loads(l).get("status") == "sent") except FileNotFoundError: return 0
def validate(item, sender): msg, problems = item["message"], [] if sender["name"] not in msg: problems.append("sender name missing") if sender["optout_line"] not in msg: problems.append("opt-out line missing") if item["preview_url"] not in msg: problems.append("preview link missing") if sender["postal_address"] not in msg: problems.append("postal address missing") if not item.get("subject") or re.search(r"\b(re:|fwd:|invoice|order|urgent)\b", item["subject"], re.I): problems.append("subject empty or misleading") return problems
def log(path, rec): rec["date"] = time.strftime("%Y-%m-%d"); rec["time"] = time.strftime("%H:%M:%S") open(path, "a", encoding="utf-8").write(json.dumps(rec) + "\n")
def main(): ap = argparse.ArgumentParser() ap.add_argument("review"); ap.add_argument("sender") ap.add_argument("--log", default="sent_log.jsonl"); ap.add_argument("--cap", type=int, default=5) ap.add_argument("--optout", default="optout.txt"); ap.add_argument("--live", action="store_true") a = ap.parse_args() cap = min(a.cap, HARD_CEILING) items = json.load(open(a.review, encoding="utf-8")); sender = json.load(open(a.sender, encoding="utf-8")) try: optout = {l.strip().lower() for l in open(a.optout) if l.strip()} except FileNotFoundError: optout = set()
for it in items: if not it.get("approved") or it.get("sent"): continue host = (urllib.parse.urlparse(it["contact_url"]).hostname or "").lower() if sent_today(a.log) >= cap: print(f"STOP: daily cap of {cap} reached. Remaining approved items wait for tomorrow."); break if host in optout: print(f"{it['id']}: BLOCKED, {host} is on the opt-out list"); log(a.log, {"id": it["id"], "status": "blocked-optout"}); continue if not is_local(it["contact_url"]) and not a.live: print(f"{it['id']}: BLOCKED, not a local test host and --live is off"); log(a.log, {"id": it["id"], "status": "blocked-not-live"}); continue bad = validate(it, sender) if bad: print(f"{it['id']}: BLOCKED, {', '.join(bad)}"); log(a.log, {"id": it["id"], "status": "blocked-message", "why": bad}); continue try: html = fetch(it["contact_url"]) except Exception as e: print(f"{it['id']}: FLAG for you, could not open the contact page ({e})"); log(a.log, {"id": it["id"], "status": "flagged-unreachable"}); continue if CAPTCHA_RX.search(html): print(f"{it['id']}: FLAGGED, CAPTCHA on the form. NOT sent. Send it by hand or skip it.") log(a.log, {"id": it["id"], "status": "flagged-captcha"}); continue ff = FormFinder(); ff.feed(html) form = next((f for f in ff.forms if f["method"] == "post" and any(x["type"] == "textarea" for x in f["fields"])), None) if not form: print(f"{it['id']}: FLAGGED, no plain contact form found (JS-only form?). NOT sent."); log(a.log, {"id": it["id"], "status": "flagged-no-form"}); continue data = {} for f in form["fields"]: n = f["name"].lower() if f["type"] == "textarea" or "message" in n or "comment" in n: data[f["name"]] = it["message"] elif "mail" in n: data[f["name"]] = sender["reply_email"] elif "phone" in n or "tel" in n: data[f["name"]] = sender.get("phone", "") elif "name" in n: data[f["name"]] = sender["name"] elif "subject" in n: data[f["name"]] = it["subject"] elif f["type"] in ("hidden", "submit"): data[f["name"]] = f["value"] url = urllib.parse.urljoin(it["contact_url"], form["action"]) if not is_local(url) and not a.live: print(f"{it['id']}: BLOCKED, form posts to a non-local host"); log(a.log, {"id": it["id"], "status": "blocked-not-live"}); continue req = urllib.request.Request(url, data=urllib.parse.urlencode(data).encode(), method="POST", headers={"User-Agent": "SitePreviewKit-sender/1.0 (identified sender)"}) code = urllib.request.urlopen(req, timeout=20).status it["sent"] = True log(a.log, {"id": it["id"], "status": "sent", "http": code, "to": host}) print(f"{it['id']}: SENT (HTTP {code}) to {url}") time.sleep(1) json.dump(items, open(a.review, "w", encoding="utf-8"), indent=2)
if __name__ == "__main__": main()
Want to put Site Preview Kit: helper scripts to work in your business?
Inside CTRL + AI, my private AI community, I show you step by step how to use tools like this: real demos, courses on Claude, AI agents and automations, and a community of business owners and builders.
Add a card to start. You pay nothing for 7 days, then $19/month. Cancel anytime before day 7 and you're not charged.