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 SCRAPE_DO_SIGNUP_URL, SORT_OPTIONS, ScrapeDoGoogleMapsTool # 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 UTM = "utm_source=huggingface&utm_medium=google-maps-leads-scraper" 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 call is 10 credits; one search page returns 20 places." ) SORT_LABELS = {"newest": "Newest", "most_relevant": "Most relevant", "highest_rating": "Highest rating", "lowest_rating": "Lowest rating"} PLACE_HEADERS = ["Name", "Category", "Rating", "Reviews", "Phone", "Website", "Address", "Hours", "Place ID"] # --------------------------------------------------------------------- helpers def _esc(value: Any) -> str: return html.escape("" if value is None else str(value), quote=True) def _safe_url(url: Any) -> str: url = str(url or "") return url if url.startswith("https://") else "" def _tool(token: str) -> Optional[ScrapeDoGoogleMapsTool]: token = (token or "").strip() return ScrapeDoGoogleMapsTool(api_token=token) if token else None def _write_csv(rows: List[Dict[str, Any]], prefix: str) -> Optional[str]: if not rows: return None fields: List[str] = [] for row in rows: for key in row: if key not in fields: fields.append(key) handle = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", prefix=f"{prefix}-", delete=False, newline="", encoding="utf-8-sig") writer = csv.DictWriter(handle, fieldnames=fields, extrasaction="ignore") writer.writeheader() for row in rows: writer.writerow({k: (" | ".join(map(str, v)) if isinstance(v, list) else (str(v) if isinstance(v, dict) 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']}" return out def _stars(rating: Any) -> str: try: r = float(rating) except (TypeError, ValueError): return 'No rating' return f'★ {r:.1f}' def render_places(places: List[Dict[str, Any]]) -> str: cards = [] for p in places: site = _safe_url(p.get("website")) maps = _safe_url(p.get("maps_url")) name = _esc(p.get("name")) title = f'{name}' if maps else name reviews = f' ({p["reviews"]:,})' if isinstance(p.get("reviews"), int) else "" lines = [f'
{_esc(p.get("category"))}
'] if p.get("address"): lines.append(f'
{_esc(p["address"])}
') contact = [] if p.get("phone"): contact.append(_esc(p["phone"])) if site: short = site.split("//", 1)[-1].split("/", 1)[0] contact.append(f'{_esc(short)}') if contact: lines.append(f'
{" · ".join(contact)}
') if p.get("open_state"): lines.append(f'
{_esc(p["open_state"])}
') cards.append(f'
{title}' f'{_stars(p.get("rating"))}{reviews}
{"".join(lines)}
') if not cards: cards.append('
No places came back for this search.
') return f'
{"".join(cards)}
' def render_place(p: Dict[str, Any]) -> str: breakdown = p.get("rating_breakdown") or {} total = sum(breakdown.values()) or 1 bars = "".join( f'
{s}★
' f'{breakdown.get(s, 0):,}
' for s in ("5", "4", "3", "2", "1") if breakdown ) attrs = "".join(f'
{_esc(k.replace("_", " ").title())} {_esc(", ".join(v))}
' for k, v in (p.get("attributes") or {}).items()) site = _safe_url(p.get("website")) rows = [ ("Category", _esc(", ".join(p.get("categories") or [])) or "—"), ("Rating", f'{_stars(p.get("rating"))} {p.get("reviews") or 0:,} reviews'), ("Phone", _esc(p.get("phone")) or "—"), ("Website", f'{_esc(site)}' if site else "—"), ("Address", _esc(p.get("address")) or "—"), ("Plus code", _esc(p.get("plus_code")) or "—"), ("Coordinates", f'{p.get("latitude")}, {p.get("longitude")}' if p.get("latitude") is not None else "—"), ("Hours", _esc(p.get("hours")).replace("; ", "
") or "—"), ("Place ID", f'{_esc(p.get("place_id"))}'), ("Feature ID", f'{_esc(p.get("data_id"))}'), ] specs = "".join(f'
{k}
{v}
' for k, v in rows) maps = _safe_url(p.get("maps_url")) button = f'Open in Google Maps' if maps else "" extra = f'
{bars}
' if bars else "" extra += f'
{attrs}
' if attrs else "" return (f'
{_esc(p.get("name"))}
' f'
{specs}
{extra}{button}
') def render_reviews(reviews: List[Dict[str, Any]]) -> str: items = [] for r in reviews: reply = f'
Owner reply {_esc(r.get("owner_reply"))}
' if r.get("owner_reply") else "" guide = ' Local Guide' if r.get("local_guide") else "" items.append(f'
{_esc(r.get("author"))}{guide}' f'{_stars(r.get("rating"))} {_esc(r.get("date"))}
' f'
{_esc(r.get("text")) or "(rating only)"}
{reply}
') if not items: items.append('
No reviews came back.
') return f'
{"".join(items)}
' # ---------------------------------------------------------------- handlers def run_search(token: str, query: str, location: str, page: float): tool = _tool(token) empty = gr.Dataframe(value=[], headers=PLACE_HEADERS) hidden = gr.Dropdown(choices=[], value=None, visible=False) if tool is None: return NO_TOKEN_MD, "", empty, {}, None, hidden data = tool.search(query, location, int(page or 1)) if data.get("status") != "success": return _error_md(data), "", empty, data, None, hidden places = data["results"] phones = sum(1 for p in places if p.get("phone")) sites = sum(1 for p in places if p.get("website")) summary = (f"**{len(places)}** places on page {data['page']} · **{phones}** with a phone · **{sites}** with a website" f"\n\n1 request · {data['credits_used']} credits. Pick a place below to send it to the Place and Reviews tabs.") table = gr.Dataframe(value=[[p["name"], p["category"], p["rating"], p["reviews"], p["phone"], p["website"], p["address"], p["hours"], p["place_id"]] for p in places], headers=PLACE_HEADERS) choices = [(f'{p["name"]} · {p["address"]}', p["place_id"] or p["data_id"]) for p in places if p.get("place_id") or p.get("data_id")] return summary, render_places(places), table, data, _write_csv(places, "google-maps-places"), gr.Dropdown(choices=choices, value=None, visible=bool(choices)) def send_place(picked: Optional[str], p_cur: str, r_cur: str) -> Tuple[str, str, str]: if not picked: return p_cur, r_cur, "" return picked, picked, "Sent. Open the **Place** or **Reviews** tab and press the button." def run_place(token: str, ref: str): tool = _tool(token) if tool is None: return NO_TOKEN_MD, "", {}, None if not (ref or "").strip(): return "Paste a place ID or Google Maps link, or pick a place in the Search tab.", "", {}, None data = tool.place(ref) if data.get("status") != "success": return _error_md(data), "", data, None p = data["place"] return f"1 request · {data['credits_used']} credits", render_place(p), data, _write_csv([p], "google-maps-place") def run_reviews(token: str, ref: str, sort_label: str, pages: float): tool = _tool(token) if tool is None: return NO_TOKEN_MD, "", {}, None if not (ref or "").strip(): return "Paste a place ID or feature ID, or pick a place in the Search tab.", "", {}, None sort_by = next((k for k, v in SORT_LABELS.items() if v == sort_label), "newest") data = tool.reviews(ref, sort_by, int(pages or 1)) if data.get("status") != "success": return _error_md(data), "", data, None reviews = data["reviews"] replies = sum(1 for r in reviews if r.get("owner_reply")) topics = ", ".join(f'{t["keyword"]} ({t["mentions"]})' for t in data.get("topics") or [] if t.get("keyword")) summary = (f"**{len(reviews)}** reviews · **{replies}** with an owner reply" + (f"\n\nTopics: {topics}" if topics else "") + f"\n\n{data['credits_used']} credits used") return summary, render_reviews(reviews), data, _write_csv(reviews, "google-maps-reviews") # ----------------------------------------------------------------------- UI STYLE = """ """ HERO = f"""

Google Maps Leads Scraper

Search a category around any point and get every business as a lead. Name, phone, website, address, rating, review count, hours and coordinates, then full place details and reviews with owner replies.

Google Maps has no data in its HTML and answers scripts with consent walls and CAPTCHAs. This Space uses the Scrape.do Google Maps API, which returns parsed JSON.

Get a free API token →
""" CREDIT_NOTE = """
Every call is 10 Scrape.do credits: a search page returns 20 places, a place lookup is one place, a reviews page is about 10 reviews. One query stops at about 120 places (6 pages); to cover a whole city, search again around other points. Reviews carry the names of the people who wrote them: store only what you need and follow the privacy rules that apply to you.
""" FOOTER_MD = f""" --- ### Use it as a smolagents Tool ```python from smolagents import CodeAgent, InferenceClientModel from tool import ScrapeDoGoogleMapsTool agent = CodeAgent( tools=[ScrapeDoGoogleMapsTool(api_token="YOUR_SCRAPEDO_TOKEN")], model=InferenceClientModel(), ) agent.run("Find dentists around 30.2672,-97.7431 on Google Maps and list the ones without a website.") ``` Or set `SCRAPE_DO_API_TOKEN` in the environment and instantiate with no arguments. Prefer plain Python? `pip install google-maps-leads-scraper` ([GitHub](https://github.com/bugrahansss/google-maps-leads-scraper)) · No-code: [Apify actor](https://apify.com/scrapedo/google-maps-leads-scraper) · Guide: [Google Maps Scraper: How to Scrape Google Maps for Leads](https://scrape.do/blog/google-maps-scraping/?{UTM}) [Scrape.do](https://scrape.do/?{UTM}) · [Documentation](https://scrape.do/documentation/) · [Sign up free]({SCRAPE_DO_SIGNUP_URL}) """ def build_demo() -> gr.Blocks: with gr.Blocks(title="Google Maps Leads 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 call.") gr.HTML(CREDIT_NOTE) with gr.Tabs(): with gr.Tab("Search"): with gr.Row(): query = gr.Textbox(label="What to search", value="coffee shop", scale=3, info="As you would type it into Google Maps. You can add a place: 'dentist in Denver, CO'.") location = gr.Textbox(label="Around (lat,lng)", value="30.2672,-97.7431", scale=2, info="Optional. Leave empty to use the place in the query.") page = gr.Number(label="Page (1-6)", value=1, minimum=1, maximum=6, precision=0, scale=1) search_btn = gr.Button("Search Google Maps", variant="primary") search_summary = gr.Markdown() search_view = gr.HTML() search_table = gr.Dataframe(headers=PLACE_HEADERS, wrap=True, label="Places") search_csv = gr.File(label="Download leads as CSV") pick = gr.Dropdown(label="Send a place to the Place and Reviews tabs", choices=[], value=None, visible=False) pick_note = gr.Markdown() with gr.Accordion("Raw JSON response", open=False): search_json = gr.JSON() with gr.Tab("Place"): place_ref = gr.Textbox(label="Place ID, CID, feature ID or Google Maps link", value="", placeholder="ChIJ... or https://www.google.com/maps/place/...", info="Pick a place in the Search tab, or paste one.") place_btn = gr.Button("Get place details", variant="primary") place_summary = gr.Markdown() place_view = gr.HTML() place_csv = gr.File(label="Download as CSV") with gr.Accordion("Raw JSON response", open=False): place_json = gr.JSON() with gr.Tab("Reviews"): with gr.Row(): review_ref = gr.Textbox(label="Place ID or feature ID", value="", scale=3, placeholder="ChIJ... or 0x...:0x...") sort = gr.Dropdown(choices=[SORT_LABELS[s] for s in SORT_OPTIONS], value="Newest", label="Order", scale=1) rpages = gr.Number(label="Pages (about 10 each)", value=1, minimum=1, maximum=5, precision=0, scale=1) reviews_btn = gr.Button("Get reviews", variant="primary") reviews_summary = gr.Markdown() reviews_view = gr.HTML() reviews_csv = gr.File(label="Download reviews as CSV") with gr.Accordion("Raw JSON response", open=False): reviews_json = gr.JSON() s_in = [api_token, query, location, page] s_out = [search_summary, search_view, search_table, search_json, search_csv, pick] search_btn.click(fn=run_search, inputs=s_in, outputs=s_out) query.submit(fn=run_search, inputs=s_in, outputs=s_out) pick.change(fn=send_place, inputs=[pick, place_ref, review_ref], outputs=[place_ref, review_ref, pick_note]) p_out = [place_summary, place_view, place_json, place_csv] place_btn.click(fn=run_place, inputs=[api_token, place_ref], outputs=p_out) place_ref.submit(fn=run_place, inputs=[api_token, place_ref], outputs=p_out) r_out = [reviews_summary, reviews_view, reviews_json, reviews_csv] reviews_btn.click(fn=run_reviews, inputs=[api_token, review_ref, sort, rpages], outputs=r_out) 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)