Spaces:
Sleeping
Sleeping
File size: 45,641 Bytes
3814b7e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 | 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'<span class="gm-stars">{"★" * full}<span class="gm-stars-off">{"★" * (5 - full)}</span></span>'
def _rating_line(rating: Any, count: Any) -> str:
if _num(rating) is None:
return '<div class="gm-rating"><span class="gm-muted">No reviews yet</span></div>'
count_html = f'<span class="gm-count">({_fmt_int(count)})</span>' if count not in (None, "") else ""
return (
f'<div class="gm-rating"><span class="gm-rating-num">{_num(rating):.1f}</span>'
f"{_stars(rating)}{count_html}</div>"
)
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'<a class="{cls}" href="{_esc(href)}"{target}>{label}</a>'
def _img(src: Any, cls: str) -> str:
link = _safe_link(src)
if not link:
return ""
return (
f'<img class="{cls}" src="{_esc(link)}" alt="" loading="lazy" referrerpolicy="no-referrer" '
'onerror="this.style.display=\'none\'">'
)
PIN_SVG = (
'<svg viewBox="0 0 24 24" width="{size}" height="{size}" aria-hidden="true">'
'<path fill="#EA4335" d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z"/>'
'<circle cx="12" cy="9" r="2.6" fill="#B31412"/></svg>'
)
# ------------------------------------------------------------ search results
def render_places(places: List[Dict[str, Any]]) -> str:
if not places:
return '<div class="gm-wrap"><div class="gm-empty">No places came back for this search.</div></div>'
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'<div class="gm-state {_open_class(open_state)}">{_esc(open_state)}</div>' if open_state else ""
)
desc = f'<div class="gm-desc">{_esc(place.get("description"))}</div>' 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'<a class="gm-name" href="{_esc(name_link)}" target="_blank" rel="noopener noreferrer">{_esc(place.get("title"))}</a>'
if name_link
else f'<span class="gm-name">{_esc(place.get("title"))}</span>'
)
cards.append(
'<div class="gm-card">'
'<div class="gm-card-main">'
f'<div class="gm-card-text"><div class="gm-pos">{_esc(place.get("position"))}</div>{name_html}'
f"{_rating_line(place.get('rating'), place.get('reviews'))}"
+ (f'<div class="gm-meta">{_esc(meta)}</div>' if meta else "")
+ (f'<div class="gm-meta">{_esc(place.get("address"))}</div>' if place.get("address") else "")
+ f"{open_html}{desc}</div>"
f"{_img(place.get('thumbnail'), 'gm-thumb')}"
"</div>"
+ (f'<div class="gm-actions">{actions}</div>' if actions else "")
+ "</div>"
)
return f'<div class="gm-wrap"><div class="gm-list">{"".join(cards)}</div></div>'
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'<div class="gm-hours-day">{_esc(str(day).capitalize())}</div><div class="gm-hours-time">{_esc(hours[day])}</div>'
for day in keys
)
return f'<div class="gm-section"><div class="gm-h">Hours</div><div class="gm-hours">{rows}</div></div>'
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'<div class="gm-bar-row"><span class="gm-bar-label">{_esc(item.get("stars"))}</span>'
f'<span class="gm-bar-track"><span class="gm-bar-fill" style="width:{width:.0f}%"></span></span>'
f'<span class="gm-bar-count">{_fmt_int(amount)}</span></div>'
)
return f'<div class="gm-section"><div class="gm-h">Rating breakdown</div>{rows}</div>'
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'<span class="gm-pt-bar" style="height:{max(3, min(100, by_hour.get(h, 0))):.0f}%" '
f'title="{h:02d}:00 · {by_hour.get(h, 0):.0f}% busy"></span>'
for h in range(6, 24)
)
rows += f'<div class="gm-pt-row"><span class="gm-pt-day">{_esc(str(day)[:3].capitalize())}</span><span class="gm-pt-bars">{bars}</span></div>'
if not rows:
return ""
axis = '<div class="gm-pt-axis"><span>6am</span><span>12pm</span><span>6pm</span><span>11pm</span></div>'
return f'<div class="gm-section"><div class="gm-h">Popular times</div>{rows}{axis}</div>'
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'<span class="gm-chip gm-chip-off">✕ {_esc(label)}</span>'
else:
chips += f'<span class="gm-chip gm-chip-on">✓ {_esc(label)}</span>'
return f'<div class="gm-section"><div class="gm-h">Service options</div><div class="gm-chips">{chips}</div></div>'
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'<span class="gm-chip">{_esc(k)}</span>' for k in kinds[:5])
if place.get("price"):
chips += f'<span class="gm-chip">{_esc(place["price"])}</span>'
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'<span class="gm-state {_open_class(open_state)}">{_esc(open_state)}</span>'))
if place.get("phone"):
info_rows.append(("📞", _esc(place["phone"])))
website = _safe_link(place.get("website"))
if website:
info_rows.append(
("🌐", f'<a class="gm-link" href="{_esc(website)}" target="_blank" rel="noopener noreferrer">{_esc(_domain(website))}</a>')
)
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'<div class="gm-info-row"><span class="gm-info-icon">{icon}</span><span>{text}</span></div>' 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'<div class="gm-quote">{_esc(r["summary"])}</div>' for r in highlights[:5])
highlight_html = f'<div class="gm-section"><div class="gm-h">What people say</div>{items}</div>'
gallery = ""
thumbs = [img for img in images if _safe_link(img.get("thumbnail"))][:8]
if thumbs:
tiles = "".join(
f'<figure class="gm-tile">{_img(img.get("thumbnail"), "gm-tile-img")}<figcaption>{_esc(img.get("title"))}</figcaption></figure>'
for img in thumbs
)
gallery = f'<div class="gm-section"><div class="gm-h">Photos</div><div class="gm-gallery">{tiles}</div></div>'
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 (
'<div class="gm-wrap"><div class="gm-detail">'
f"{banner}"
'<div class="gm-detail-body">'
f'<div class="gm-detail-title">{_esc(place.get("title"))}</div>'
f"{_rating_line(place.get('rating'), place.get('reviews'))}"
+ (f'<div class="gm-chips">{chips}</div>' if chips else "")
+ (f'<div class="gm-summary">{_esc(summary)}</div>' if summary else "")
+ (f'<div class="gm-actions">{actions}</div>' if actions else "")
+ (f'<div class="gm-info">{info}</div>' if info else "")
+ '<div class="gm-cols">'
f'<div class="gm-col">{left}</div><div class="gm-col">{right}</div>'
"</div>"
f"{highlight_html}{gallery}"
"</div></div></div>"
)
# ------------------------------------------------------------------ reviews
def render_reviews(data: Dict[str, Any]) -> str:
info = data.get("place_info") or {}
header = ""
if info.get("title"):
header = (
'<div class="gm-rev-head">'
f'<div class="gm-detail-title">{_esc(info.get("title"))}</div>'
f"{_rating_line(info.get('rating'), info.get('reviews'))}"
+ (f'<div class="gm-meta">{_esc(_types(info))}</div>' if info.get("type") else "")
+ (f'<div class="gm-meta">{_esc(info.get("address"))}</div>' if info.get("address") else "")
+ "</div>"
)
topics = [t for t in data.get("topics") or [] if isinstance(t, dict) and t.get("keyword")]
topics_html = ""
if topics:
chips = "".join(
f'<span class="gm-chip">{_esc(t["keyword"])} <b>{_fmt_int(t.get("mentions"))}</b></span>' for t in topics[:14]
)
topics_html = f'<div class="gm-section"><div class="gm-h">Mentioned most</div><div class="gm-chips">{chips}</div></div>'
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'<span class="gm-avatar-wrap"><span class="gm-avatar-initial">{initial}</span>'
f'{_img(user.get("thumbnail"), "gm-avatar")}</span>'
)
text = review.get("snippet") or (review.get("extracted_snippet") or {}).get("original") or ""
text_html = _esc(text).replace("\n", "<br>")
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'<span class="gm-chip gm-chip-sm">{_esc(label)} {_esc(shown)}</span>'
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 = (
'<div class="gm-reply"><div class="gm-reply-head">Response from the owner'
+ (f' · {_esc(reply.get("date"))}' if reply.get("date") else "")
+ f'</div>{_esc(reply.get("snippet") or reply.get("text"))}</div>'
)
likes = f'<span class="gm-muted">👍 {_fmt_int(review["likes"])}</span>' if review.get("likes") else ""
link = _safe_link(review.get("link"))
view = (
f'<a class="gm-link" href="{_esc(link)}" target="_blank" rel="noopener noreferrer">View on Google</a>' if link else ""
)
cards.append(
'<div class="gm-rev">'
f'<div class="gm-rev-user">{avatar}<div><div class="gm-rev-name">{_esc(user.get("name") or "Google user")}</div>'
f'<div class="gm-muted">{_esc(" · ".join(guide_bits))}</div></div></div>'
f'<div class="gm-rev-meta">{_stars(review.get("rating"))}<span class="gm-muted">{_esc(review.get("date"))}</span></div>'
+ (f'<div class="gm-rev-text">{text_html}</div>' if text_html else "")
+ (f'<div class="gm-chips">{detail_chips}</div>' if detail_chips else "")
+ (f'<div class="gm-rev-photos">{photos}</div>' if photos else "")
+ reply_html
+ (f'<div class="gm-rev-foot">{likes}{view}</div>' if likes or view else "")
+ "</div>"
)
if not cards:
cards.append('<div class="gm-empty">No reviews matched.</div>')
return f'<div class="gm-wrap">{header}{topics_html}<div class="gm-rev-list">{"".join(cards)}</div></div>'
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 = """
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');
.gradio-container, .gradio-container button, .gradio-container input,
.gradio-container textarea, .gradio-container select {
font-family: 'Roboto', Arial, sans-serif;
}
/* hero */
.gm-hero { font-family: 'Roboto', Arial, sans-serif; position: relative; overflow: hidden; background: #ffffff; border: 1px solid #dadce0;
border-radius: 16px; padding: 28px 32px 26px 32px; margin-bottom: 16px; }
.gm-hero::before { content: ""; position: absolute; right: -60px; top: -70px; width: 400px; height: 320px;
background:
linear-gradient(90deg, transparent 47%, #ffffff 47%, #ffffff 53%, transparent 53%),
linear-gradient(0deg, transparent 45%, #fde293 45%, #fde293 50%, transparent 50%),
linear-gradient(0deg, transparent 47%, #ffffff 47%, #ffffff 53%, transparent 53%),
linear-gradient(135deg, #ceead6 0%, #d2e3fc 100%);
background-size: 90px 90px, 180px 180px, 90px 90px, 100% 100%;
transform: rotate(-14deg); border-radius: 28px; opacity: 0.95; }
.gm-hero-pin { position: absolute; right: 120px; top: 44px; filter: drop-shadow(0 4px 6px rgba(0,0,0,.25)); }
.gm-hero-inner { position: relative; z-index: 1; max-width: 640px; }
.gm-hero h1 { color: #202124 !important; font-size: 2rem !important; font-weight: 500 !important;
margin: 0 0 10px 0 !important; letter-spacing: -0.01em; display: flex; align-items: center; gap: 10px; }
.gm-hero p { color: #3c4043 !important; margin: 0 0 8px 0 !important; font-size: 1rem !important; line-height: 1.55 !important; }
.gm-hero strong { color: #202124 !important; font-weight: 500 !important; }
.gm-hero a { color: #1a73e8 !important; }
.gm-hero a.gm-cta { display: inline-block; margin-top: 10px; padding: 11px 24px; background: #1a73e8 !important;
color: #ffffff !important; border-radius: 999px; font-weight: 500 !important; text-decoration: none !important; }
@media (max-width: 820px) { .gm-hero::before, .gm-hero-pin { display: none; } }
.gm-note { border-left: 3px solid #fbbc04; background: #fef7e0; padding: 12px 16px;
border-radius: 0 8px 8px 0; font-size: 0.9rem; margin-bottom: 12px; color: #202124 !important; }
.gradio-container .primary, .gradio-container button.primary,
.gradio-container button[variant="primary"] {
background: #1a73e8 !important; background-image: none !important; border-color: #1a73e8 !important;
color: #ffffff !important; border-radius: 999px !important; font-weight: 500 !important;
}
.gradio-container .primary:hover, .gradio-container button.primary:hover,
.gradio-container button[variant="primary"]:hover { background: #1765cc !important; }
.gradio-container .tab-nav button.selected { color: #1a73e8 !important; border-bottom-color: #1a73e8 !important; }
/* shared */
.gm-wrap { color: #202124 !important; font-family: 'Roboto', Arial, sans-serif; }
.gm-wrap img { margin: 0 !important; max-width: none; }
.gm-wrap figure { margin: 0 !important; }
.gm-muted { color: #70757a !important; font-size: 0.85rem; }
.gm-empty { background: #ffffff; border: 1px solid #dadce0; border-radius: 12px; padding: 20px; color: #5f6368 !important; }
.gm-rating { display: flex; align-items: center; gap: 5px; margin: 3px 0; font-size: 0.9rem; }
.gm-rating-num { color: #202124 !important; font-weight: 500; }
.gm-stars { color: #fbbc04 !important; letter-spacing: 1px; font-size: 0.95rem; }
.gm-stars-off { color: #dadce0 !important; }
.gm-count { color: #70757a !important; }
.gm-meta { color: #5f6368 !important; font-size: 0.88rem; line-height: 1.45; }
.gm-state { font-size: 0.88rem; font-weight: 500; margin-top: 2px; color: #5f6368 !important; }
.gm-state.gm-open { color: #188038 !important; }
.gm-state.gm-closed { color: #d93025 !important; }
.gm-state.gm-soon { color: #e37400 !important; }
.gm-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
.gm-btn { display: inline-flex; align-items: center; padding: 6px 14px; border: 1px solid #dadce0;
border-radius: 999px; font-size: 0.85rem; font-weight: 500; color: #1a73e8 !important;
background: #ffffff; text-decoration: none !important; }
.gm-btn:hover { background: #f1f6fe; }
.gm-btn-primary { background: #1a73e8 !important; border-color: #1a73e8; color: #ffffff !important; }
.gm-btn-primary:hover { background: #1765cc !important; }
.gm-chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0; }
.gm-chip { background: #f1f3f4; color: #3c4043 !important; border-radius: 999px; padding: 4px 11px; font-size: 0.82rem; }
.gm-chip b { color: #1a73e8 !important; font-weight: 500; }
.gm-chip-sm { font-size: 0.75rem; padding: 2px 9px; }
.gm-chip-on { background: #e6f4ea; color: #137333 !important; }
.gm-chip-off { background: #f1f3f4; color: #80868b !important; text-decoration: line-through; }
.gm-link { color: #1a73e8 !important; text-decoration: none !important; }
.gm-link:hover { text-decoration: underline !important; }
.gm-section { margin-top: 18px; }
.gm-h { font-size: 1rem; font-weight: 500; color: #202124 !important; margin-bottom: 8px; }
/* place list */
.gm-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(340px, 100%), 1fr)); gap: 12px; }
.gm-card { background: #ffffff; border: 1px solid #dadce0; border-radius: 12px; padding: 14px 16px;
display: flex; flex-direction: column; justify-content: space-between; }
.gm-card:hover { box-shadow: 0 1px 6px rgba(32,33,36,.18); }
.gm-card-main { display: flex; gap: 12px; justify-content: space-between; }
.gm-card-text { min-width: 0; }
.gm-pos { display: inline-block; background: #ea4335; color: #ffffff !important; font-size: 0.72rem; font-weight: 700;
border-radius: 999px; min-width: 20px; height: 20px; line-height: 20px; text-align: center; padding: 0 6px;
margin-right: 6px; vertical-align: 2px; }
.gm-name { color: #202124 !important; font-size: 1.05rem; font-weight: 500; text-decoration: none !important; }
a.gm-name:hover { color: #1a73e8 !important; text-decoration: underline !important; }
.gm-desc { color: #5f6368 !important; font-size: 0.85rem; margin-top: 6px; line-height: 1.45; }
.gm-thumb { width: 88px; height: 88px; object-fit: cover; border-radius: 8px; flex-shrink: 0; background: #f1f3f4; }
/* place detail */
.gm-detail { background: #ffffff; border: 1px solid #dadce0; border-radius: 16px; overflow: hidden; max-width: 900px; }
.gm-banner { width: 100%; height: 220px; object-fit: cover; display: block; background: #f1f3f4; }
.gm-detail-body { padding: 20px 24px 24px 24px; }
.gm-detail-title { font-size: 1.6rem; color: #202124 !important; font-weight: 400; line-height: 1.25; }
.gm-summary { color: #3c4043 !important; font-size: 0.95rem; line-height: 1.55; margin-top: 8px; }
.gm-info { border-top: 1px solid #e8eaed; margin-top: 16px; padding-top: 8px; }
.gm-info-row { display: flex; gap: 14px; padding: 7px 0; color: #202124 !important; font-size: 0.92rem; }
.gm-info-icon { width: 22px; text-align: center; flex-shrink: 0; }
.gm-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 28px; }
@media (max-width: 720px) { .gm-cols { grid-template-columns: 1fr; } }
.gm-hours { display: grid; grid-template-columns: 110px 1fr; row-gap: 5px; font-size: 0.9rem; }
.gm-hours-day { color: #202124 !important; }
.gm-hours-time { color: #5f6368 !important; }
.gm-bar-row { display: flex; align-items: center; gap: 8px; margin: 4px 0; font-size: 0.85rem; }
.gm-bar-label { width: 14px; color: #5f6368 !important; text-align: right; }
.gm-bar-track { flex: 1; height: 9px; background: #e8eaed; border-radius: 999px; overflow: hidden; }
.gm-bar-fill { display: block; height: 100%; background: #fbbc04; border-radius: 999px; }
.gm-bar-count { width: 56px; color: #70757a !important; font-size: 0.78rem; }
.gm-pt-row { display: flex; align-items: flex-end; gap: 8px; margin: 3px 0; }
.gm-pt-day { width: 32px; font-size: 0.78rem; color: #5f6368 !important; padding-bottom: 1px; }
.gm-pt-bars { flex: 1; display: flex; align-items: flex-end; gap: 2px; height: 30px; border-bottom: 1px solid #e8eaed; }
.gm-pt-bar { flex: 1; background: #8ab4f8; border-radius: 2px 2px 0 0; min-height: 2px; }
.gm-pt-axis { display: flex; justify-content: space-between; margin-left: 40px; font-size: 0.7rem; color: #80868b !important; }
.gm-quote { border-left: 3px solid #e8eaed; padding: 4px 12px; margin: 6px 0; color: #3c4043 !important; font-size: 0.9rem; font-style: italic; }
.gm-gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 8px; }
.gm-tile { position: relative; border-radius: 8px; overflow: hidden; }
.gm-tile-img { width: 100%; height: 100px; object-fit: cover; display: block; background: #f1f3f4; }
.gm-tile figcaption { position: absolute; left: 0; right: 0; bottom: 0; padding: 14px 8px 5px 8px; font-size: 0.75rem;
color: #ffffff !important; background: linear-gradient(transparent, rgba(0,0,0,.65)); }
/* reviews */
.gm-rev-head { background: #ffffff; border: 1px solid #dadce0; border-radius: 12px; padding: 16px 20px; margin-bottom: 4px; }
.gm-rev-list { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; max-width: 820px; }
.gm-rev { background: #ffffff; border: 1px solid #dadce0; border-radius: 12px; padding: 14px 18px; }
.gm-rev-user { display: flex; align-items: center; gap: 10px; }
.gm-avatar-wrap { position: relative; width: 36px; height: 36px; flex-shrink: 0; }
.gm-avatar-initial { position: absolute; inset: 0; border-radius: 50%; background: #1a73e8; color: #ffffff !important;
display: flex; align-items: center; justify-content: center; font-weight: 500; font-size: 0.95rem; }
.gm-avatar { position: absolute; inset: 0; width: 36px; height: 36px; border-radius: 50%; object-fit: cover; }
.gm-rev-name { color: #202124 !important; font-weight: 500; font-size: 0.92rem; }
.gm-rev-meta { display: flex; align-items: center; gap: 8px; margin: 8px 0 4px 0; }
.gm-rev-text { color: #202124 !important; font-size: 0.92rem; line-height: 1.55; }
.gm-rev-photos { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; }
.gm-rev-img { width: 84px; height: 84px; object-fit: cover; border-radius: 8px; background: #f1f3f4; }
.gm-reply { background: #f8f9fa; border-radius: 8px; padding: 10px 12px; margin-top: 10px; font-size: 0.88rem;
color: #3c4043 !important; line-height: 1.5; }
.gm-reply-head { font-weight: 500; color: #202124 !important; margin-bottom: 4px; }
.gm-rev-foot { display: flex; gap: 16px; align-items: center; margin-top: 10px; font-size: 0.85rem; }
footer { display: none !important; }
</style>
"""
HERO = f"""
<div class="gm-hero">
<div class="gm-hero-pin">{PIN_SVG.format(size=64)}</div>
<div class="gm-hero-inner">
<h1>{PIN_SVG.format(size=30)} Google Maps Scraper</h1>
<p><strong>Turn any Google Maps search into a clean list of businesses</strong>: 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.</p>
<p>Built on the <a href="https://scrape.do/documentation/google-scraper-api/maps/" target="_blank" rel="noopener noreferrer">Scrape.do Google Maps API</a>,
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.</p>
<a class="gm-cta" href="{SCRAPE_DO_SIGNUP_URL}" target="_blank" rel="noopener noreferrer">Get a free API token →</a>
</div>
</div>
"""
CREDIT_NOTE = """
<div class="gm-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.
</div>
"""
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()
|