bugrahans's picture
Whitepages Scraper Space
4d97166 verified
Raw History Blame Contribute Delete
18.9 kB
from __future__ import annotations
import csv
import html
import tempfile
from typing import Any, Dict, List, Optional, Tuple
import gradio as gr
from tool import (
DEFAULT_CITY,
DEFAULT_NAME,
DEFAULT_STATE,
SCRAPE_DO_SIGNUP_URL,
US_STATES,
ScrapeDoWhitepagesTool,
)
# ZeroGPU hardware refuses to keep a Space alive unless it finds at least one
# @spaces.GPU function at startup. This app is pure HTTP and never touches a GPU,
# so the probe below exists only to satisfy that check. It is never called.
try:
import spaces
@spaces.GPU(duration=1)
def _zerogpu_probe() -> str:
return "ok"
except ImportError:
pass
NO_TOKEN_MD = (
"### Paste your Scrape.do API token above\n\n"
f"No token yet? [Create a free account]({SCRAPE_DO_SIGNUP_URL}) — "
"1,000 free credits a month, no credit card. Every Whitepages page costs 10 credits."
)
ANY_STATE = "Any state"
# --------------------------------------------------------------------- helpers
def _esc(value: Any) -> str:
return html.escape("" if value is None else str(value), quote=True)
def _safe_link(url: Any) -> str:
url = str(url or "")
return url if url.startswith("https://www.whitepages.com/") else ""
def _tool_or_none(token: str) -> Optional[ScrapeDoWhitepagesTool]:
if not token or not token.strip():
return None
return ScrapeDoWhitepagesTool(api_token=token.strip())
def _write_csv(rows: List[Dict[str, Any]], prefix: str) -> Optional[str]:
if not rows:
return None
fieldnames: List[str] = []
for row in rows:
for key in row:
if key not in fieldnames:
fieldnames.append(key)
handle = tempfile.NamedTemporaryFile(
mode="w", suffix=".csv", prefix=f"{prefix}-", delete=False, newline="", encoding="utf-8-sig",
)
writer = csv.DictWriter(handle, fieldnames=fieldnames, extrasaction="ignore")
writer.writeheader()
for row in rows:
writer.writerow({k: " | ".join(v) if isinstance(v, list) else v for k, v in row.items()})
handle.close()
return handle.name
def _error_md(data: Dict[str, Any]) -> str:
out = f"**That didn't go through.**\n\n{data.get('errorMessage') or 'Unknown error'}"
if data.get("hint"):
out += f"\n\n{data['hint']}"
if data.get("credits_used"):
out += f"\n\n{data['credits_used']} credits used."
return out
def _chips(values: List[str], limit: int = 12) -> str:
if not values:
return '<span class="sp-muted">None listed</span>'
shown = "".join(f'<span class="sp-chip">{_esc(v)}</span>' for v in values[:limit])
more = f'<span class="sp-muted">+{len(values) - limit} more</span>' if len(values) > limit else ""
return shown + more
def _address(p: Dict[str, Any]) -> str:
region = " ".join(x for x in (p.get("state"), p.get("zip_code")) if x)
return ", ".join(x for x in (p.get("address"), p.get("city"), region) if x)
def render_people(data: Dict[str, Any]) -> str:
cards = []
for p in data.get("results") or []:
link = _safe_link(p.get("url"))
name = _esc(p.get("name") or "Person")
title = f'<a href="{_esc(link)}" target="_blank" rel="noopener noreferrer">{name}</a>' if link else name
age = f'<span class="sp-age">{_esc(p.get("age_range"))}</span>' if p.get("age_range") else ""
phones = p.get("phones") or []
phone = (f'<div class="sp-line">&#9742; {_esc(phones[0])}'
+ (f' <span class="sp-muted">+{len(phones) - 1}</span>' if len(phones) > 1 else "") + "</div>") if phones else ""
rel = p.get("relatives") or []
rels = f'<div class="sp-muted sp-line">Relatives: {_esc(", ".join(rel[:3]))}{" …" if len(rel) > 3 else ""}</div>' if rel else ""
cards.append(
'<div class="sp-card">'
f'<div class="sp-card-top"><span class="sp-name">{title}</span>{age}</div>'
f'<div class="sp-line">{_esc(_address(p))}</div>{phone}{rels}</div>'
)
if not cards:
cards.append('<div class="sp-empty">No people came back for this search.</div>')
return f'<div class="sp-wrap"><div class="sp-grid">{"".join(cards)}</div></div>'
def render_person(p: Dict[str, Any]) -> str:
link = _safe_link(p.get("url"))
button = (f'<a class="sp-btn" href="{_esc(link)}" target="_blank" rel="noopener noreferrer">View on Whitepages</a>'
if link else "")
rows = [
("Age range", _esc(p.get("age_range")) if p.get("age_range") else '<span class="sp-muted">Not shown</span>'),
("Current address", _esc(_address(p)) or '<span class="sp-muted">Not listed</span>'),
("Neighborhood", _esc(p.get("neighborhood")) or '<span class="sp-muted">Not listed</span>'),
(f"Phones ({len(p.get('phones') or [])})", _chips(p.get("phones") or [])),
(f"Relatives ({len(p.get('relatives') or [])})", _chips(p.get("relatives") or [], 15)),
(f"Associates ({len(p.get('associates') or [])})", _chips(p.get("associates") or [], 15)),
(f"Other names ({len(p.get('aliases') or [])})", _chips(p.get("aliases") or [])),
(f"Previous locations ({len(p.get('previous_locations') or [])})", _chips(p.get("previous_locations") or [], 10)),
]
specs = "".join(f'<div class="sp-spec-name">{k}</div><div class="sp-spec-value">{v}</div>' for k, v in rows)
return (f'<div class="sp-wrap"><div class="sp-profile"><div class="sp-p-name">{_esc(p.get("name"))}</div>'
f'<div class="sp-specs">{specs}</div>{button}</div></div>')
PEOPLE_HEADERS = ["Name", "Age range", "Address", "City", "State", "Phones", "Relatives", "Person page"]
# ---------------------------------------------------------------- handlers
def _picker(choices: List[Tuple[str, str]]) -> Any:
return gr.Dropdown(choices=choices, value=None, visible=bool(choices))
def run_search(token: str, name: str, city: str, state: str, page: float):
tool = _tool_or_none(token)
empty = gr.Dataframe(value=[], headers=PEOPLE_HEADERS)
if tool is None:
return NO_TOKEN_MD, "", empty, {}, None, _picker([])
st = "" if state == ANY_STATE else state
data = tool.search(name, st, (city or "").strip() if st else "", int(page or 1))
if data.get("status") != "success":
return _error_md(data), "", empty, data, None, _picker([])
people = data.get("results") or []
with_phone = sum(1 for p in people if p.get("phones"))
with_address = sum(1 for p in people if p.get("address"))
summary = (f"**{len(people)}** people on page {data.get('page')} · **{with_address}** with an address · "
f"**{with_phone}** with a phone number"
f"\n\n1 request · {data.get('credits_used')} credits used. Pick a person below to open their page.")
table = gr.Dataframe(value=[[p.get("name"), p.get("age_range"), p.get("address"), p.get("city"), p.get("state"),
" | ".join(p.get("phones") or []), " | ".join(p.get("relatives") or []), p.get("url")]
for p in people], headers=PEOPLE_HEADERS)
choices = [(f"{p.get('name')}, {p.get('age_range') or '?'}, {p.get('city')} {p.get('state')}", p["url"])
for p in people if p.get("url")]
return summary, render_people(data), table, data, _write_csv(people, "whitepages-search"), _picker(choices)
def send_to_profile(picked: Optional[str], current: str) -> Tuple[str, str]:
if not picked:
return current, ""
return picked, "Sent. Open the **Profile** tab and press the button."
def run_profile(token: str, url: str):
tool = _tool_or_none(token)
if tool is None:
return NO_TOKEN_MD, "", {}, None
if not url or not url.strip():
return "Paste a Whitepages person page link, or pick a person in the Search tab.", "", {}, None
data = tool.profile(url)
if data.get("status") != "success":
return _error_md(data), "", data, None
p = data["person"]
summary = (f"**{len(p.get('phones') or [])}** phones · **{len(p.get('relatives') or [])}** relatives · "
f"**{len(p.get('associates') or [])}** associates"
f"\n\n1 request · {data.get('credits_used')} credits used")
return summary, render_person(p), data, _write_csv([p], "whitepages-profile")
# ----------------------------------------------------------------------- UI
STYLE = """
<style>
.gradio-container, .gradio-container button, .gradio-container input,
.gradio-container textarea, .gradio-container select {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}
.sp-hero { position: relative; overflow: hidden; border-radius: 18px; padding: 30px 32px 28px 32px; margin-bottom: 16px;
background: radial-gradient(circle at 92% 12%, rgba(47,128,237,.45) 0%, rgba(47,128,237,0) 45%),
linear-gradient(135deg, #0b1b33 0%, #12294d 60%, #1b3a6b 100%); }
.sp-hero, .sp-hero * { color: #ffffff !important; }
.sp-hero-inner { position: relative; z-index: 1; max-width: 640px; }
.sp-hero h1 { font-size: 2.05rem !important; font-weight: 800 !important; margin: 0 0 10px 0 !important; }
.sp-hero h1 span { color: #4aa3ff !important; }
.sp-hero p { margin: 0 0 8px 0 !important; font-size: 1rem !important; line-height: 1.55 !important; opacity: .96; }
.sp-hero a { text-decoration: underline !important; }
.sp-hero a.sp-cta { display: inline-block; margin-top: 12px; padding: 11px 24px; border-radius: 10px;
background: #4aa3ff !important; color: #0b1b33 !important; font-weight: 800 !important; text-decoration: none !important; }
.sp-hero a.sp-cta:hover { filter: brightness(.96); }
.sp-hero-card { position: absolute; right: 34px; top: 50%; transform: translateY(-50%); width: 270px; z-index: 1;
background: #ffffff; border-radius: 14px; padding: 14px 16px; box-shadow: 0 10px 28px rgba(0,0,0,.35); }
.sp-hero-card, .sp-hero-card * { color: #212529 !important; }
.sp-hc-title { font-size: .72rem; font-weight: 800; color: #6c757d !important; text-transform: uppercase; letter-spacing: .05em; margin-bottom: 8px; }
.sp-hc-row { display: grid; grid-template-columns: 1fr auto; gap: 8px; font-size: .84rem; margin: 7px 0; }
.sp-hc-row b { color: #154f99 !important; }
@media (max-width: 900px) { .sp-hero-card { display: none; } }
.sp-note { border-left: 3px solid #4aa3ff; background: #eef5ff; padding: 12px 16px; border-radius: 0 10px 10px 0;
font-size: .9rem; margin-bottom: 12px; color: #212529 !important; }
.gradio-container .primary, .gradio-container button.primary, .gradio-container button[variant="primary"] {
background: #1f6fd1 !important; background-image: none !important; border-color: #1f6fd1 !important;
color: #ffffff !important; border-radius: 10px !important; font-weight: 800 !important; }
.gradio-container .primary:hover, .gradio-container button.primary:hover,
.gradio-container button[variant="primary"]:hover { background: #154f99 !important; }
.gradio-container .tab-nav button.selected { color: #154f99 !important; border-bottom-color: #1f6fd1 !important; }
.sp-wrap { color: #212529 !important; }
.sp-muted { color: #6c757d !important; }
.sp-empty { background: #ffffff; border: 1px solid #e8e8e8; border-radius: 12px; padding: 20px; color: #6c757d !important; }
.sp-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(280px, 100%), 1fr)); gap: 12px; }
.sp-card { background: #ffffff; border: 1px solid #e8e8e8; border-radius: 14px; padding: 12px 14px; }
.sp-card:hover { box-shadow: 0 3px 12px rgba(33,37,41,.10); }
.sp-card-top { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; }
.sp-name a, .sp-name { font-weight: 800; color: #212529 !important; text-decoration: none !important; }
.sp-name a:hover { color: #154f99 !important; text-decoration: underline !important; }
.sp-age { background: #4aa3ff; color: #0b1b33 !important; font-weight: 800; font-size: .75rem; border-radius: 6px; padding: 2px 8px; white-space: nowrap; }
.sp-line { font-size: .84rem; margin-top: 4px; color: #212529 !important; }
.sp-profile { background: #ffffff; border: 1px solid #e8e8e8; border-radius: 16px; padding: 18px 22px; }
.sp-p-name { font-size: 1.4rem; font-weight: 800; color: #212529 !important; }
.sp-specs { display: grid; grid-template-columns: minmax(130px, .35fr) 1fr; border-top: 1px solid #ececec; margin-top: 12px; }
.sp-spec-name, .sp-spec-value { padding: 8px 10px; border-bottom: 1px solid #ececec; font-size: .86rem; }
.sp-spec-name { color: #6c757d !important; }
.sp-spec-value { color: #212529 !important; }
.sp-chip { display: inline-block; background: #f5f3f3; border: 1px solid #e8e8e8; border-radius: 6px; padding: 2px 8px; margin: 2px 4px 2px 0; font-size: .8rem; color: #212529 !important; }
.sp-btn { display: inline-block; margin-top: 14px; padding: 10px 22px; border-radius: 10px; background: #1f6fd1 !important;
color: #ffffff !important; font-weight: 800; text-decoration: none !important; font-size: .9rem; }
footer { display: none !important; }
</style>
"""
HERO = f"""
<div class="sp-hero">
<div class="sp-hero-inner">
<h1>White<span>pages</span> Scraper</h1>
<p><strong>Search a name, get up to 25 people per page as data.</strong> Current address, phone numbers,
age range, neighborhood, previous locations and relatives, then open a person page for associates.
Table, JSON or CSV.</p>
<p>Whitepages is US-only and sits behind Cloudflare. This Space fetches each page through
<a href="https://scrape.do/?utm_source=huggingface&utm_medium=whitepages-scraper" target="_blank" rel="noopener noreferrer">Scrape.do</a>
with a US residential IP and reads the page's JSON-LD block, where the phone numbers the cards mask are in full.</p>
<a class="sp-cta" href="{SCRAPE_DO_SIGNUP_URL}" target="_blank" rel="noopener noreferrer">Get a free API token →</a>
</div>
<div class="sp-hero-card" aria-hidden="true">
<div class="sp-hc-title">One search page · one request</div>
<div class="sp-hc-row"><span>People</span><span><b>25</b></span></div>
<div class="sp-hc-row"><span>Addresses</span><span><b>25</b></span></div>
<div class="sp-hc-row"><span>Phone numbers</span><span><b>15</b></span></div>
</div>
</div>
"""
CREDIT_NOTE = """
<div class="sp-note">
Every page is one request through a US residential IP: 10 Scrape.do credits. A name search page lists up to
25 people; a person page is one more request. The free 1,000 credits a month cover 100 pages.
Ages are ranges, never exact. This is data about real people: don't use it for employment, housing, credit or
insurance decisions (FCRA), and honor opt-out requests.
</div>
"""
FOOTER_MD = f"""
---
### Use it as a smolagents Tool
```python
from smolagents import CodeAgent, InferenceClientModel
from tool import ScrapeDoWhitepagesTool
agent = CodeAgent(
tools=[ScrapeDoWhitepagesTool(api_token="YOUR_SCRAPEDO_TOKEN")],
model=InferenceClientModel(),
)
agent.run("Search Whitepages for {DEFAULT_NAME} in {DEFAULT_CITY}, {DEFAULT_STATE} and list their age ranges and cities.")
```
Or set `SCRAPE_DO_API_TOKEN` in the environment and instantiate with no arguments.
Prefer plain Python? The same scraper is open source: `pip install whitepages-scraper`
([GitHub](https://github.com/bugrahansss/whitepages-scraper)) · No-code: [Apify actor](https://apify.com/scrapedo/whitepages-scraper) ·
Guide: [Whitepages.com Scraping](https://scrape.do/blog/white-pages-scraping/?utm_source=huggingface&utm_medium=whitepages-scraper)
[Scrape.do](https://scrape.do/?utm_source=huggingface&utm_medium=whitepages-scraper) · [Documentation](https://scrape.do/documentation/) · [Sign up free]({SCRAPE_DO_SIGNUP_URL})
"""
def build_demo() -> gr.Blocks:
with gr.Blocks(title="Whitepages Scraper — Scrape.do") as demo:
gr.HTML(STYLE)
gr.HTML(HERO)
api_token = gr.Textbox(
label="Scrape.do API token",
placeholder="Paste your token here",
type="password",
info="Free tier: 1,000 credits a month. 10 credits per Whitepages page.",
)
gr.HTML(CREDIT_NOTE)
with gr.Tabs():
with gr.Tab("Search"):
with gr.Row():
name = gr.Textbox(label="Full name", value=DEFAULT_NAME, scale=3)
city = gr.Textbox(label="City (optional, needs a state)", value=DEFAULT_CITY, scale=2)
state = gr.Dropdown(choices=[ANY_STATE] + US_STATES, value=DEFAULT_STATE, label="State", scale=1)
page = gr.Number(label="Result page", value=1, minimum=1, precision=0, scale=1)
search_btn = gr.Button("Search", variant="primary")
search_summary = gr.Markdown()
search_view = gr.HTML()
search_table = gr.Dataframe(headers=PEOPLE_HEADERS, wrap=True, label="People")
search_csv = gr.File(label="Download results as CSV")
pick = gr.Dropdown(label="Open one of these people in the Profile tab", choices=[], value=None, visible=False)
pick_note = gr.Markdown()
with gr.Accordion("Raw JSON response", open=False):
search_json = gr.JSON()
with gr.Tab("Profile"):
profile_url = gr.Textbox(label="Whitepages person page", value="",
placeholder="https://www.whitepages.com/name/<Name>/<City-ST>/<id>",
info="Pick a person in the Search tab, or paste a person page link from the site.")
profile_btn = gr.Button("Open person page", variant="primary")
profile_summary = gr.Markdown()
profile_view = gr.HTML()
profile_csv = gr.File(label="Download profile as CSV")
with gr.Accordion("Raw JSON response", open=False):
profile_json = gr.JSON()
s_inputs = [api_token, name, city, state, page]
s_outputs = [search_summary, search_view, search_table, search_json, search_csv, pick]
search_btn.click(fn=run_search, inputs=s_inputs, outputs=s_outputs)
name.submit(fn=run_search, inputs=s_inputs, outputs=s_outputs)
pick.change(fn=send_to_profile, inputs=[pick, profile_url], outputs=[profile_url, pick_note])
p_outputs = [profile_summary, profile_view, profile_json, profile_csv]
profile_btn.click(fn=run_profile, inputs=[api_token, profile_url], outputs=p_outputs)
profile_url.submit(fn=run_profile, inputs=[api_token, profile_url], outputs=p_outputs)
gr.Markdown(FOOTER_MD)
return demo
# Hugging Face Spaces launches the module-level `demo` object rather than
# calling launch() itself, so build it at import time.
demo = build_demo()
if __name__ == "__main__":
demo.queue(default_concurrency_limit=4).launch(ssr_mode=False)