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 'None listed' shown = "".join(f'{_esc(v)}' for v in values[:limit]) more = f'+{len(values) - limit} more' 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'{name}' if link else name age = f'{_esc(p.get("age_range"))}' if p.get("age_range") else "" phones = p.get("phones") or [] phone = (f'
☎ {_esc(phones[0])}' + (f' +{len(phones) - 1}' if len(phones) > 1 else "") + "
") if phones else "" rel = p.get("relatives") or [] rels = f'
Relatives: {_esc(", ".join(rel[:3]))}{" …" if len(rel) > 3 else ""}
' if rel else "" cards.append( '
' f'
{title}{age}
' f'
{_esc(_address(p))}
{phone}{rels}
' ) if not cards: cards.append('
No people came back for this search.
') return f'
{"".join(cards)}
' def render_person(p: Dict[str, Any]) -> str: link = _safe_link(p.get("url")) button = (f'View on Whitepages' if link else "") rows = [ ("Age range", _esc(p.get("age_range")) if p.get("age_range") else 'Not shown'), ("Current address", _esc(_address(p)) or 'Not listed'), ("Neighborhood", _esc(p.get("neighborhood")) or 'Not listed'), (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'
{k}
{v}
' for k, v in rows) return (f'
{_esc(p.get("name"))}
' f'
{specs}
{button}
') 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 = """ """ HERO = f"""

Whitepages Scraper

Search a name, get up to 25 people per page as data. Current address, phone numbers, age range, neighborhood, previous locations and relatives, then open a person page for associates. Table, JSON or CSV.

Whitepages is US-only and sits behind Cloudflare. This Space fetches each page through Scrape.do with a US residential IP and reads the page's JSON-LD block, where the phone numbers the cards mask are in full.

Get a free API token →
""" CREDIT_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.
""" 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///", 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)