from __future__ import annotations import csv import html import re import tempfile from typing import Any, Dict, List, Optional, Tuple from urllib.parse import quote, urlparse import gradio as gr from tool import COUNTRIES, MAX_REVIEWS, SCRAPE_DO_SIGNUP_URL, 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 COUNTRY_CHOICES = [(label, gl) for label, gl, _, _ in COUNTRIES] SORT_CHOICES = [ ("Most relevant", "relevance"), ("Newest", "newest"), ("Highest rating", "highest"), ("Lowest rating", "lowest"), ] DAY_ORDER = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] 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. Each Google Maps call costs 10 credits." ) # --------------------------------------------------------------------- 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(("http://", "https://")) else "" def _domain(url: Any) -> str: try: host = urlparse(str(url or "")).netloc.lower() except ValueError: return "" return host[4:] if host.startswith("www.") else host def _num(value: Any) -> Optional[float]: try: return float(str(value).replace(",", "")) except (TypeError, ValueError): return None def _fmt_int(value: Any) -> str: number = _num(value) return f"{int(number):,}" if number is not None else _esc(value) def _tool_or_none(token: str) -> Optional[ScrapeDoGoogleMapsTool]: if not token or not token.strip(): return None return ScrapeDoGoogleMapsTool(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) writer.writeheader() for row in rows: writer.writerow({key: row.get(key, "") for key in fieldnames}) 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 _maps_link(place: Dict[str, Any]) -> str: if place.get("place_id"): return "https://www.google.com/maps/place/?q=place_id:" + quote(str(place["place_id"])) if place.get("data_cid"): return f"https://maps.google.com/?cid={quote(str(place['data_cid']))}" gps = place.get("gps_coordinates") or {} if gps.get("latitude") is not None and gps.get("longitude") is not None: return f"https://www.google.com/maps/search/?api=1&query={gps['latitude']},{gps['longitude']}" return "" def _directions_link(place: Dict[str, Any]) -> str: gps = place.get("gps_coordinates") or {} if gps.get("latitude") is None or gps.get("longitude") is None: return "" link = f"https://www.google.com/maps/dir/?api=1&destination={gps['latitude']},{gps['longitude']}" if place.get("place_id"): link += "&destination_place_id=" + quote(str(place["place_id"])) return link def _tel(phone: Any) -> str: digits = re.sub(r"[^\d+]", "", str(phone or "")) return f"tel:{digits}" if digits else "" def _types(place: Dict[str, Any]) -> str: kind = place.get("type") if isinstance(kind, list): return " · ".join(str(k) for k in kind[:3]) return str(kind or "") def _open_class(text: Any) -> str: lowered = str(text or "").lower() if not lowered: return "" if "soon" in lowered or "yakında" in lowered: return "gm-soon" closed_words = ("closed", "kapalı", "geschlossen", "fermé", "cerrado", "chiuso", "gesloten", "fechado") if lowered.startswith(closed_words) or "permanently closed" in lowered or "temporarily closed" in lowered: return "gm-closed" return "gm-open" def _stars(rating: Any) -> str: value = _num(rating) if value is None: return "" full = max(0, min(5, int(round(value)))) return f'{"★" * full}{"★" * (5 - full)}' def _rating_line(rating: Any, count: Any) -> str: if _num(rating) is None: return '
No reviews yet
' count_html = f'({_fmt_int(count)})' if count not in (None, "") else "" return ( f'
{_num(rating):.1f}' f"{_stars(rating)}{count_html}
" ) def _button(label: str, href: str, primary: bool = False) -> str: if not href: return "" cls = "gm-btn gm-btn-primary" if primary else "gm-btn" target = "" if href.startswith("tel:") else ' target="_blank" rel="noopener noreferrer"' return f'{label}' def _img(src: Any, cls: str) -> str: link = _safe_link(src) if not link: return "" return ( f'' ) PIN_SVG = ( '' ) # ------------------------------------------------------------ search results def render_places(places: List[Dict[str, Any]]) -> str: if not places: return '
No places came back for this search.
' cards: List[str] = [] for place in places: meta = " · ".join(part for part in [_types(place), str(place.get("price") or "")] if part) open_state = place.get("open_state") or place.get("hours") open_html = ( f'
{_esc(open_state)}
' if open_state else "" ) desc = f'
{_esc(place.get("description"))}
' if place.get("description") else "" website = _safe_link(place.get("website")) actions = "".join( [ _button("Website", website, primary=True), _button(f"Call {_esc(place.get('phone'))}", _tel(place.get("phone"))), _button("Directions", _directions_link(place)), ] ) name_link = _maps_link(place) name_html = ( f'{_esc(place.get("title"))}' if name_link else f'{_esc(place.get("title"))}' ) cards.append( '
' '
' f'
{_esc(place.get("position"))}
{name_html}' f"{_rating_line(place.get('rating'), place.get('reviews'))}" + (f'
{_esc(meta)}
' if meta else "") + (f'
{_esc(place.get("address"))}
' if place.get("address") else "") + f"{open_html}{desc}
" f"{_img(place.get('thumbnail'), 'gm-thumb')}" "
" + (f'
{actions}
' if actions else "") + "
" ) return f'
{"".join(cards)}
' def _place_rows(places: List[Dict[str, Any]]) -> List[Dict[str, Any]]: rows = [] for place in places: gps = place.get("gps_coordinates") or {} rows.append( { "position": place.get("position"), "name": place.get("title"), "category": _types(place), "rating": place.get("rating"), "reviews": place.get("reviews"), "price": place.get("price"), "phone": place.get("phone"), "website": place.get("website"), "address": place.get("address"), "open_state": place.get("open_state") or place.get("hours"), "latitude": gps.get("latitude"), "longitude": gps.get("longitude"), "google_maps_url": _maps_link(place), "place_id": place.get("place_id"), "data_id": place.get("data_id"), "data_cid": place.get("data_cid"), } ) return rows # --------------------------------------------------------------- place card def _hours_html(hours: Any) -> str: if not isinstance(hours, dict) or not hours: return "" keys = [day for day in DAY_ORDER if day in hours] + [k for k in hours if k not in DAY_ORDER] rows = "".join( f'
{_esc(str(day).capitalize())}
{_esc(hours[day])}
' for day in keys ) return f'
Hours
{rows}
' def _rating_summary_html(summary: Any) -> str: if not isinstance(summary, list) or not summary: return "" amounts = [_num(item.get("amount")) or 0 for item in summary if isinstance(item, dict)] top = max(amounts) if amounts else 0 rows = "" for item in sorted( (i for i in summary if isinstance(i, dict)), key=lambda i: _num(i.get("stars")) or 0, reverse=True ): amount = _num(item.get("amount")) or 0 width = (amount / top * 100) if top else 0 rows += ( f'
{_esc(item.get("stars"))}' f'' f'{_fmt_int(amount)}
' ) return f'
Rating breakdown
{rows}
' def _popular_times_html(popular: Any) -> str: if isinstance(popular, dict) and isinstance(popular.get("graph_results"), dict): popular = popular["graph_results"] if not isinstance(popular, dict) or not popular: return "" keys = [day for day in DAY_ORDER if day in popular] + [ k for k in popular if k not in DAY_ORDER and isinstance(popular[k], list) ] rows = "" for day in keys: entries = popular.get(day) if not isinstance(entries, list): continue by_hour: Dict[int, float] = {} for entry in entries: if not isinstance(entry, dict): continue hour = entry.get("hour") if hour is None and entry.get("time"): match = re.match(r"(\d{1,2})\s*(AM|PM)?", str(entry["time"]), re.I) if match: hour = int(match.group(1)) % 12 + (12 if (match.group(2) or "").upper() == "PM" else 0) busy = _num(entry.get("busyness", entry.get("busyness_score"))) if hour is not None and busy is not None: by_hour[int(hour)] = busy if not by_hour: continue bars = "".join( f'' for h in range(6, 24) ) rows += f'
{_esc(str(day)[:3].capitalize())}{bars}
' if not rows: return "" axis = '
6am12pm6pm11pm
' return f'
Popular times
{rows}{axis}
' def _service_html(options: Any) -> str: if not isinstance(options, dict) or not options: return "" chips = "" for key, value in options.items(): label = str(key).replace("_", " ").capitalize() if value is False: chips += f'✕ {_esc(label)}' else: chips += f'✓ {_esc(label)}' return f'
Service options
{chips}
' def render_place(place: Dict[str, Any]) -> str: images = [img for img in (place.get("images") or []) if isinstance(img, dict)] banner_src = place.get("thumbnail") or (images[0].get("thumbnail") if images else None) banner = _img(banner_src, "gm-banner") kinds = place.get("type") kinds = kinds if isinstance(kinds, list) else ([kinds] if kinds else []) chips = "".join(f'{_esc(k)}' for k in kinds[:5]) if place.get("price"): chips += f'{_esc(place["price"])}' summary = place.get("summary") or place.get("description") menu = place.get("menu") if isinstance(place.get("menu"), dict) else {} actions = "".join( [ _button("Website", _safe_link(place.get("website")), primary=True), _button("Call", _tel(place.get("phone"))), _button("Directions", _directions_link(place)), _button("Menu", _safe_link(menu.get("link"))), _button("Open in Google Maps", _maps_link(place)), ] ) info_rows = [] if place.get("address"): info_rows.append(("📍", _esc(place["address"]))) open_state = place.get("open_state") or place.get("hours") if open_state and isinstance(open_state, str): info_rows.append(("🕒", f'{_esc(open_state)}')) if place.get("phone"): info_rows.append(("📞", _esc(place["phone"]))) website = _safe_link(place.get("website")) if website: info_rows.append( ("🌐", f'{_esc(_domain(website))}') ) if place.get("plus_code"): info_rows.append(("⊕", _esc(place["plus_code"]))) gps = place.get("gps_coordinates") or {} if gps.get("latitude") is not None: info_rows.append(("🧭", _esc(f"{gps.get('latitude')}, {gps.get('longitude')}"))) info = "".join(f'
{icon}{text}
' for icon, text in info_rows) highlights = [r for r in (place.get("user_reviews") or []) if isinstance(r, dict) and r.get("summary")] highlight_html = "" if highlights: items = "".join(f'
{_esc(r["summary"])}
' for r in highlights[:5]) highlight_html = f'
What people say
{items}
' gallery = "" thumbs = [img for img in images if _safe_link(img.get("thumbnail"))][:8] if thumbs: tiles = "".join( f'
{_img(img.get("thumbnail"), "gm-tile-img")}
{_esc(img.get("title"))}
' for img in thumbs ) gallery = f'
Photos
' left = _hours_html(place.get("operating_hours")) + _service_html(place.get("service_options")) right = _rating_summary_html(place.get("rating_summary")) + _popular_times_html(place.get("popular_times")) return ( '
' f"{banner}" '
' f'
{_esc(place.get("title"))}
' f"{_rating_line(place.get('rating'), place.get('reviews'))}" + (f'
{chips}
' if chips else "") + (f'
{_esc(summary)}
' if summary else "") + (f'
{actions}
' if actions else "") + (f'
{info}
' if info else "") + '
' f'
{left}
{right}
' "
" f"{highlight_html}{gallery}" "
" ) # ------------------------------------------------------------------ reviews def render_reviews(data: Dict[str, Any]) -> str: info = data.get("place_info") or {} header = "" if info.get("title"): header = ( '
' f'
{_esc(info.get("title"))}
' f"{_rating_line(info.get('rating'), info.get('reviews'))}" + (f'
{_esc(_types(info))}
' if info.get("type") else "") + (f'
{_esc(info.get("address"))}
' if info.get("address") else "") + "
" ) topics = [t for t in data.get("topics") or [] if isinstance(t, dict) and t.get("keyword")] topics_html = "" if topics: chips = "".join( f'{_esc(t["keyword"])} {_fmt_int(t.get("mentions"))}' for t in topics[:14] ) topics_html = f'
Mentioned most
{chips}
' cards: List[str] = [] for review in data.get("reviews") or []: user = review.get("user") or {} guide_bits = [] if user.get("local_guide"): guide_bits.append("Local Guide") if user.get("reviews") is not None: guide_bits.append(f"{_fmt_int(user['reviews'])} reviews") if user.get("photos"): guide_bits.append(f"{_fmt_int(user['photos'])} photos") initial = _esc((str(user.get("name") or "G").strip() or "G")[0].upper()) avatar = ( f'{initial}' f'{_img(user.get("thumbnail"), "gm-avatar")}' ) text = review.get("snippet") or (review.get("extracted_snippet") or {}).get("original") or "" text_html = _esc(text).replace("\n", "
") details = review.get("details") if isinstance(review.get("details"), dict) else {} detail_chips = "" for key, value in details.items(): label = str(key).replace("_", " ").capitalize() value_num = _num(value) shown = f"{int(value_num)}/5" if value_num is not None and 1 <= value_num <= 5 else str(value) detail_chips += f'{_esc(label)} {_esc(shown)}' photos = "".join(_img(src, "gm-rev-img") for src in (review.get("images") or [])[:4]) reply = review.get("response") or review.get("owner_response") reply_html = "" if isinstance(reply, dict) and (reply.get("snippet") or reply.get("text")): reply_html = ( '
Response from the owner' + (f' · {_esc(reply.get("date"))}' if reply.get("date") else "") + f'
{_esc(reply.get("snippet") or reply.get("text"))}
' ) likes = f'👍 {_fmt_int(review["likes"])}' if review.get("likes") else "" link = _safe_link(review.get("link")) view = ( f'View on Google' if link else "" ) cards.append( '
' f'
{avatar}
{_esc(user.get("name") or "Google user")}
' f'
{_esc(" · ".join(guide_bits))}
' f'
{_stars(review.get("rating"))}{_esc(review.get("date"))}
' + (f'
{text_html}
' if text_html else "") + (f'
{detail_chips}
' if detail_chips else "") + (f'
{photos}
' if photos else "") + reply_html + (f'
{likes}{view}
' if likes or view else "") + "
" ) if not cards: cards.append('
No reviews matched.
') return f'
{header}{topics_html}
{"".join(cards)}
' def _review_rows(reviews: List[Dict[str, Any]]) -> List[Dict[str, Any]]: rows = [] for review in reviews: user = review.get("user") or {} reply = review.get("response") or review.get("owner_response") or {} rows.append( { "position": review.get("position"), "rating": review.get("rating"), "date": review.get("date"), "iso_date": review.get("iso_date"), "reviewer": user.get("name"), "local_guide": user.get("local_guide"), "reviewer_reviews": user.get("reviews"), "text": review.get("snippet") or (review.get("extracted_snippet") or {}).get("original"), "likes": review.get("likes"), "photos": len(review.get("images") or []), "owner_response": reply.get("snippet") or reply.get("text") if isinstance(reply, dict) else "", "link": review.get("link"), } ) return rows # ---------------------------------------------------------------- handlers PLACE_TABLE_HEADERS = ["#", "Name", "Rating", "Reviews", "Category", "Phone", "Website", "Address"] REVIEW_TABLE_HEADERS = ["#", "Rating", "Date", "Reviewer", "Review"] def _picker(choices: List[Tuple[str, str]]) -> Any: return gr.Dropdown(choices=choices, value=None, visible=bool(choices)) def run_search( token: str, query: str, country: str, pages: float, location: str ) -> Tuple[str, str, List[List[Any]], Dict[str, Any], Optional[str], Any]: tool = _tool_or_none(token) if tool is None: return NO_TOKEN_MD, "", [], {}, None, _picker([]) if not query or not query.strip(): return "Type what you're looking for, e.g. `dentists in Kadıköy, Istanbul`.", "", [], {}, None, _picker([]) data = tool.search_places(query, country, int(pages or 1), location) if data.get("status") != "success": return _error_md(data), "", [], data, None, _picker([]) places = data.get("places") or [] rows = _place_rows(places) ratings = [_num(p.get("rating")) for p in places if _num(p.get("rating")) is not None] with_phone = sum(1 for p in places if p.get("phone")) with_site = sum(1 for p in places if p.get("website")) parts = [ f"**{len(places)}** places", f"**{with_phone}** with a phone number", f"**{with_site}** with a website", ] if ratings: parts.append(f"average rating **{sum(ratings) / len(ratings):.1f}**") summary = " · ".join(parts) + f"\n\n{data.get('pages_fetched')} page(s) · {data.get('credits_used')} credits used" if data.get("warnings"): summary += "\n\n" + "\n".join(f"- {w}" for w in data["warnings"]) table = [ [ r["position"], r["name"], r["rating"], r["reviews"], r["category"], r["phone"], _domain(r["website"]), r["address"], ] for r in rows ] choices = [] for place in places: ref = place.get("place_id") or place.get("data_id") or place.get("data_cid") if ref: label = f"{place.get('position')}. {place.get('title')}" if place.get("address"): label += f" — {str(place['address'])[:60]}" choices.append((label, str(ref))) csv_path = _write_csv(rows, "google-maps-places") return summary, render_places(places), table, data, csv_path, _picker(choices) def send_to_tabs(picked: Optional[str], place_ref: str, review_ref: str) -> Tuple[str, str, str]: if not picked: return place_ref, review_ref, "" return picked, picked, "Sent. Open the **Place details** or **Reviews** tab and press the button." def run_place(token: str, ref: str, country: str) -> Tuple[str, str, Dict[str, Any]]: tool = _tool_or_none(token) if tool is None: return NO_TOKEN_MD, "", {} if not ref or not ref.strip(): return "Paste a Google Maps link, a place ID, or type a business name.", "", {} data = tool.place_details(ref, country) if data.get("status") != "success": return _error_md(data), "", data lines = [] if data.get("note"): lines.append(data["note"]) lines.append(f"{data.get('credits_used')} credits used.") return "\n\n".join(lines), render_place(data.get("place") or {}), data def run_reviews( token: str, ref: str, country: str, max_reviews: float, sort_by: str, keyword: str ) -> Tuple[str, str, List[List[Any]], Dict[str, Any], Optional[str]]: tool = _tool_or_none(token) if tool is None: return NO_TOKEN_MD, "", [], {}, None if not ref or not ref.strip(): return "Paste a Google Maps link, a place ID, or type a business name.", "", [], {}, None data = tool.reviews(ref, country, int(max_reviews or 20), sort_by or None, keyword or None) if data.get("status") != "success": return _error_md(data), "", [], data, None reviews = data.get("reviews") or [] ratings = [_num(r.get("rating")) for r in reviews if _num(r.get("rating")) is not None] lines = [] if data.get("note"): lines.append(data["note"]) summary = f"**{len(reviews)}** reviews collected" if ratings: summary += f" · average of these **{sum(ratings) / len(ratings):.1f}★**" if keyword and keyword.strip(): summary += f" · mentioning “{keyword.strip()}”" lines.append(summary) lines.append(f"{data.get('pages_fetched')} call(s) · {data.get('credits_used')} credits used") if data.get("warnings"): lines.append("\n".join(f"- {w}" for w in data["warnings"])) rows = _review_rows(reviews) table = [ [r["position"], r["rating"], r["date"], r["reviewer"], (r["text"] or "")[:160]] for r in rows ] csv_path = _write_csv(rows, "google-maps-reviews") return "\n\n".join(lines), render_reviews(data), table, data, csv_path # ----------------------------------------------------------------------- UI STYLE = """ """ HERO = f"""
{PIN_SVG.format(size=64)}

{PIN_SVG.format(size=30)} Google Maps Scraper

Turn any Google Maps search into a clean list of businesses: names, ratings, phone numbers, websites, addresses, opening hours and coordinates, ready to download as CSV. Then open any place for its full profile and read its reviews.

Built on the Scrape.do Google Maps API, so there's no browser to run and nothing breaks when Google changes its page. Use it for lead lists, local market research, competitor tracking, or to give an AI agent live local data.

Get a free API token →
""" CREDIT_NOTE = """
Every call costs 10 credits: one page of 20 places, one place's full details, or up to 20 reviews. The free 1,000 credits cover about 100 calls. Typing a business name instead of pasting a link adds one search (10 credits) to find it.
""" 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("List the 10 best-rated coffee shops in Kadikoy, Istanbul that have a website, with their phone numbers.") ``` Or set `SCRAPE_DO_API_TOKEN` in the environment and instantiate with no arguments. Prefer to write the scraper yourself? The [Google Maps scraping guide](https://scrape.do/blog/google-maps-scraping/) walks through it in Python. [Scrape.do](https://scrape.do/) · [Google Maps API docs](https://scrape.do/documentation/google-scraper-api/maps/) · [Sign up free]({SCRAPE_DO_SIGNUP_URL}) """ def build_demo() -> gr.Blocks: with gr.Blocks(title="Google Maps Scraper — Scrape.do") as demo: gr.HTML(STYLE) gr.HTML(HERO) with gr.Row(): api_token = gr.Textbox( label="Scrape.do API token", placeholder="Paste your token here", type="password", info="Free tier: 1,000 credits a month, about 100 calls.", scale=3, ) country = gr.Dropdown( label="Country", choices=COUNTRY_CHOICES, value="us", info="Sets Google's domain and language.", scale=1, ) gr.HTML(CREDIT_NOTE) with gr.Tabs(): with gr.Tab("Find businesses"): with gr.Row(): query = gr.Textbox( label="What are you looking for?", placeholder="dentists in Kadıköy, Istanbul", info="Put the place in the search, the way you would in Google Maps.", scale=3, ) pages = gr.Slider( label="Pages", minimum=1, maximum=6, step=1, value=1, info="20 places per page, 10 credits each.", scale=1, ) with gr.Accordion("Center the map on exact coordinates (optional)", open=False): location = gr.Textbox( label="Latitude, longitude", placeholder="41.0082,28.9784", info="Add a zoom level as a third number if you like, e.g. 41.0082,28.9784,15", ) search_btn = gr.Button("Search Google Maps", variant="primary") search_summary = gr.Markdown() places_view = gr.HTML() places_table = gr.Dataframe(headers=PLACE_TABLE_HEADERS, wrap=True, label="Places") places_csv = gr.File(label="Download the full list as CSV") pick = gr.Dropdown( label="Open one of these places in the Details and Reviews tabs", choices=[], value=None, visible=False, ) pick_note = gr.Markdown() with gr.Accordion("Raw JSON response", open=False): places_json = gr.JSON() with gr.Tab("Place details"): place_ref = gr.Textbox( label="Google Maps link, place ID, or business name", placeholder="https://maps.app.goo.gl/… or Joe's Pizza Carmine St New York", ) place_btn = gr.Button("Get place details", variant="primary") place_summary = gr.Markdown() place_view = gr.HTML() with gr.Accordion("Raw JSON response", open=False): place_json = gr.JSON() with gr.Tab("Reviews"): review_ref = gr.Textbox( label="Google Maps link, place ID, or business name", placeholder="https://maps.app.goo.gl/… or Joe's Pizza Carmine St New York", ) with gr.Row(): max_reviews = gr.Slider( label="How many reviews", minimum=10, maximum=MAX_REVIEWS, step=10, value=20, info="Up to 20 per call, 10 credits each.", ) sort_by = gr.Dropdown(label="Sort by", choices=SORT_CHOICES, value="relevance") keyword = gr.Textbox(label="Only reviews mentioning (optional)", placeholder="parking") reviews_btn = gr.Button("Get reviews", variant="primary") reviews_summary = gr.Markdown() reviews_view = gr.HTML() reviews_table = gr.Dataframe(headers=REVIEW_TABLE_HEADERS, wrap=True, label="Reviews") reviews_csv = gr.File(label="Download reviews as CSV") with gr.Accordion("Raw JSON response", open=False): reviews_json = gr.JSON() search_inputs = [api_token, query, country, pages, location] search_outputs = [search_summary, places_view, places_table, places_json, places_csv, pick] search_btn.click(fn=run_search, inputs=search_inputs, outputs=search_outputs) query.submit(fn=run_search, inputs=search_inputs, outputs=search_outputs) pick.change(fn=send_to_tabs, inputs=[pick, place_ref, review_ref], outputs=[place_ref, review_ref, pick_note]) place_inputs = [api_token, place_ref, country] place_outputs = [place_summary, place_view, place_json] place_btn.click(fn=run_place, inputs=place_inputs, outputs=place_outputs) place_ref.submit(fn=run_place, inputs=place_inputs, outputs=place_outputs) review_inputs = [api_token, review_ref, country, max_reviews, sort_by, keyword] review_outputs = [reviews_summary, reviews_view, reviews_table, reviews_json, reviews_csv] reviews_btn.click(fn=run_reviews, inputs=review_inputs, outputs=review_outputs) review_ref.submit(fn=run_reviews, inputs=review_inputs, outputs=review_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.launch()