-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathgoogleMapsLib.py
More file actions
1873 lines (1590 loc) · 64.6 KB
/
Copy pathgoogleMapsLib.py
File metadata and controls
1873 lines (1590 loc) · 64.6 KB
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Google Maps Platform client for geeViz.
Provides functions for ground-truthing and enriching remote sensing
analysis using Google Maps Platform APIs:
- **Geocoding** — address to coordinates and reverse
- **Places** — search, nearby, details, photos
- **Street View** — static images, panoramas, AI interpretation
- **Elevation** — terrain height at any location
- **Static Maps** — basemap images for reports
- **Air Quality** — current AQI and pollutants
- **Solar** — rooftop solar potential
- **Roads** — snap GPS traces to nearest roads
**24 public functions:**
- **Geocoding**: ``geocode``, ``reverse_geocode``, ``validate_address``
- **Places**: ``search_places``, ``search_nearby``, ``get_place_photo``
- **Street View**: ``streetview_metadata``, ``streetview_image``,
``streetview_images_cardinal``, ``streetview_panorama``, ``streetview_html``
- **AI Analysis**: ``interpret_image``, ``label_streetview``,
``segment_image``, ``segment_streetview``
- **Elevation**: ``get_elevation``, ``get_elevations``,
``get_elevation_along_path``
- **Environment**: ``get_air_quality``, ``get_solar_insights``,
``get_timezone``
- **Maps**: ``get_static_map``
- **Roads**: ``snap_to_roads``, ``nearest_roads``
Quick start::
import geeViz.googleMapsLib as gm
# Geocode an address
result = gm.geocode("100 S 200 E, Salt Lake City, UT")
# Street View panorama + AI interpretation
pano = gm.streetview_panorama(-111.80, 40.68, fov=360)
analysis = gm.interpret_image(pano)
# Semantic segmentation (SegFormer)
seg = gm.segment_image(pano, model_variant="b4")
# Elevation, air quality, solar
elev = gm.get_elevation(-111.80, 40.68)
aq = gm.get_air_quality(-111.80, 40.68)
solar = gm.get_solar_insights(-111.80, 40.68)
Requires a ``GOOGLE_MAPS_PLATFORM_API_KEY`` in your environment or ``.env``
file. Gemini AI features use ``GEMINI_API_KEY``.
Copyright 2026 Ian Housman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
"""
from __future__ import annotations
import base64
import json
import os
import urllib.error
import urllib.parse
import urllib.request
from typing import Any
# ---------------------------------------------------------------------------
# API key resolution
# ---------------------------------------------------------------------------
_API_KEY: str | None = None
# Key names to check, in priority order
_KEY_NAMES = (
"GOOGLE_MAPS_PLATFORM_API_KEY",
"MAPS_PLATFORM_API_KEY",
"GOOGLE_API_KEY",
)
def _get_api_key() -> str:
"""Resolve the Google Maps Platform API key.
Checks environment variables and ``.env`` in priority order:
``MAPS_PLATFORM_API_KEY``, ``GOOGLE_API_KEY``.
"""
global _API_KEY
if _API_KEY:
return _API_KEY
# Parse .env file first (env vars may have a different project's key)
env_keys: dict[str, str] = {}
env_path = os.path.join(os.path.dirname(__file__), ".env")
if os.path.exists(env_path):
with open(env_path) as f:
for line in f:
line = line.strip()
if "=" in line and not line.startswith("#"):
k, v = line.split("=", 1)
env_keys[k.strip()] = v.strip().strip("'\"")
# Check each key name in priority order across both sources
for key_name in _KEY_NAMES:
for source in (env_keys, os.environ):
key = source.get(key_name)
if key:
_API_KEY = key
return key
raise RuntimeError(
"No Google Maps API key found. Set GOOGLE_MAPS_PLATFORM_API_KEY "
"in your environment or .env file."
)
def _fetch_json(url: str, params: dict | None = None,
method: str = "GET", body: dict | None = None,
headers: dict | None = None) -> dict:
"""HTTP request returning parsed JSON."""
if params:
url = url + "?" + urllib.parse.urlencode(params)
data = json.dumps(body).encode("utf-8") if body else None
hdrs = {"User-Agent": "geeViz/googleMaps"}
if headers:
hdrs.update(headers)
if data and "Content-Type" not in hdrs:
hdrs["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=hdrs, method=method)
with urllib.request.urlopen(req, timeout=20) as resp:
return json.loads(resp.read().decode("utf-8"))
def _fetch_bytes(url: str, params: dict | None = None) -> bytes:
"""HTTP GET returning raw bytes."""
if params:
url = url + "?" + urllib.parse.urlencode(params)
req = urllib.request.Request(url, headers={"User-Agent": "geeViz/googleMaps"})
with urllib.request.urlopen(req, timeout=20) as resp:
return resp.read()
###########################################################################
# Geocoding API
###########################################################################
_GEOCODE_URL = "https://maps.googleapis.com/maps/api/geocode/json"
def geocode(address: str) -> dict[str, Any] | None:
"""Geocode an address to coordinates using the Google Geocoding API.
Args:
address (str): Street address, place name, or location description.
Returns:
dict or None: Result with keys:
- ``lat`` (float): Latitude.
- ``lon`` (float): Longitude.
- ``formatted_address`` (str): Full formatted address.
- ``place_id`` (str): Google Place ID.
- ``location_type`` (str): Accuracy — ``"ROOFTOP"``,
``"RANGE_INTERPOLATED"``, ``"GEOMETRIC_CENTER"``, or
``"APPROXIMATE"``.
- ``address_components`` (list): Decomposed address parts.
Returns ``None`` if no results found.
Example:
>>> result = geocode("100 S 200 E, Salt Lake City, UT")
>>> if result:
... print(f"{result['lat']}, {result['lon']}")
"""
data = _fetch_json(_GEOCODE_URL, {
"address": address,
"key": _get_api_key(),
})
if data.get("status") != "OK" or not data.get("results"):
return None
r = data["results"][0]
loc = r["geometry"]["location"]
return {
"lat": loc["lat"],
"lon": loc["lng"],
"formatted_address": r.get("formatted_address", ""),
"place_id": r.get("place_id", ""),
"location_type": r["geometry"].get("location_type", ""),
"address_components": r.get("address_components", []),
}
###########################################################################
# Places API (New)
###########################################################################
_PLACES_BASE = "https://places.googleapis.com/v1"
def search_places(
query: str,
lat: float | None = None,
lon: float | None = None,
radius: float = 5000,
max_results: int = 10,
included_types: list[str] | None = None,
) -> list[dict[str, Any]]:
"""Search for places using the Google Places API (New) Text Search.
Args:
query (str): Search text (e.g. "coffee shops", "gas station",
"Yellowstone visitor center").
lat (float, optional): Latitude for location bias.
lon (float, optional): Longitude for location bias.
radius (float, optional): Bias radius in meters. Defaults to 5000.
max_results (int, optional): Maximum results (1-20). Defaults to 10.
included_types (list, optional): Place type filters (e.g.
``["restaurant"]``, ``["gas_station"]``).
Returns:
list of dict: Each dict has keys: ``name``, ``display_name``,
``address``, ``lat``, ``lon``, ``types``, ``rating``,
``place_id``, ``photo_name`` (first photo resource name, if any).
Example:
>>> places = search_places("fire station", lat=40.76, lon=-111.89)
>>> for p in places:
... print(f"{p['display_name']}: {p['address']}")
"""
body: dict[str, Any] = {
"textQuery": query,
"pageSize": min(max_results, 20),
"languageCode": "en",
}
if lat is not None and lon is not None:
body["locationBias"] = {
"circle": {
"center": {"latitude": lat, "longitude": lon},
"radius": radius,
}
}
if included_types:
body["includedType"] = included_types[0] # API accepts one type
field_mask = (
"places.id,places.displayName,places.formattedAddress,"
"places.location,places.types,places.rating,"
"places.userRatingCount,places.photos"
)
data = _fetch_json(
f"{_PLACES_BASE}/places:searchText",
method="POST",
body=body,
headers={
"X-Goog-Api-Key": _get_api_key(),
"X-Goog-FieldMask": field_mask,
},
)
results = []
for p in data.get("places", []):
loc = p.get("location", {})
photos = p.get("photos", [])
results.append({
"name": p.get("id", ""),
"display_name": p.get("displayName", {}).get("text", ""),
"address": p.get("formattedAddress", ""),
"lat": loc.get("latitude"),
"lon": loc.get("longitude"),
"types": p.get("types", []),
"rating": p.get("rating"),
"rating_count": p.get("userRatingCount"),
"place_id": p.get("id", ""),
"photo_name": photos[0].get("name") if photos else None,
})
return results
def search_nearby(
lat: float,
lon: float,
radius: float = 1000,
included_types: list[str] | None = None,
max_results: int = 10,
) -> list[dict[str, Any]]:
"""Search for places near a location using Nearby Search (New).
Args:
lat (float): Latitude.
lon (float): Longitude.
radius (float, optional): Search radius in meters (max 50000).
Defaults to 1000.
included_types (list, optional): Place type filters (e.g.
``["restaurant"]``).
max_results (int, optional): Maximum results (1-20). Defaults to 10.
Returns:
list of dict: Same format as :func:`search_places`.
Example:
>>> nearby = search_nearby(40.76, -111.89, radius=2000,
... included_types=["park"])
"""
body: dict[str, Any] = {
"locationRestriction": {
"circle": {
"center": {"latitude": lat, "longitude": lon},
"radius": min(radius, 50000),
}
},
"maxResultCount": min(max_results, 20),
"languageCode": "en",
}
if included_types:
body["includedTypes"] = included_types
field_mask = (
"places.id,places.displayName,places.formattedAddress,"
"places.location,places.types,places.rating,"
"places.userRatingCount,places.photos"
)
data = _fetch_json(
f"{_PLACES_BASE}/places:searchNearby",
method="POST",
body=body,
headers={
"X-Goog-Api-Key": _get_api_key(),
"X-Goog-FieldMask": field_mask,
},
)
results = []
for p in data.get("places", []):
loc = p.get("location", {})
photos = p.get("photos", [])
results.append({
"name": p.get("id", ""),
"display_name": p.get("displayName", {}).get("text", ""),
"address": p.get("formattedAddress", ""),
"lat": loc.get("latitude"),
"lon": loc.get("longitude"),
"types": p.get("types", []),
"rating": p.get("rating"),
"rating_count": p.get("userRatingCount"),
"place_id": p.get("id", ""),
"photo_name": photos[0].get("name") if photos else None,
})
return results
def get_place_photo(photo_name: str, max_width: int = 400,
max_height: int = 400) -> bytes | None:
"""Fetch a place photo by its resource name.
Photo names come from :func:`search_places` or :func:`search_nearby`
results (the ``photo_name`` field).
Args:
photo_name (str): Photo resource name from a Places API response.
max_width (int, optional): Maximum width in pixels (1-4800).
max_height (int, optional): Maximum height in pixels (1-4800).
Returns:
bytes or None: JPEG/PNG image bytes, or ``None`` on error.
Example:
>>> places = search_places("Arches National Park visitor center")
>>> if places and places[0]['photo_name']:
... photo = get_place_photo(places[0]['photo_name'])
"""
if not photo_name:
return None
try:
return _fetch_bytes(
f"{_PLACES_BASE}/{photo_name}/media",
{"key": _get_api_key(),
"maxWidthPx": str(max_width),
"maxHeightPx": str(max_height)},
)
except Exception:
return None
###########################################################################
# Street View Static API
###########################################################################
_SV_STATIC_URL = "https://maps.googleapis.com/maps/api/streetview"
_SV_METADATA_URL = "https://maps.googleapis.com/maps/api/streetview/metadata"
_SV_DEFAULT_SIZE = "640x480"
_SV_DEFAULT_FOV = 90
def streetview_metadata(
lon: float,
lat: float,
radius: int = 50,
source: str = "default",
) -> dict[str, Any]:
"""Check if Street View imagery exists at a location.
This is a free call (no quota consumed).
Args:
lon (float): Longitude in decimal degrees.
lat (float): Latitude in decimal degrees.
radius (int, optional): Search radius in meters. Defaults to 50.
source (str, optional): ``"default"`` or ``"outdoor"``.
Returns:
dict: Keys: ``status``, ``pano_id``, ``location``, ``date``,
``copyright``.
Example:
>>> meta = streetview_metadata(-111.89, 40.76)
>>> if meta['status'] == 'OK':
... print(f"Imagery from {meta['date']}")
"""
return _fetch_json(_SV_METADATA_URL, {
"location": f"{lat},{lon}",
"radius": str(radius),
"source": source,
"key": _get_api_key(),
})
def streetview_image(
lon: float,
lat: float,
heading: float = 0,
pitch: float = 0,
fov: float = _SV_DEFAULT_FOV,
size: str = _SV_DEFAULT_SIZE,
radius: int = 50,
source: str = "default",
) -> bytes | None:
"""Fetch a Street View static image as JPEG bytes.
Returns ``None`` if no imagery exists (checks metadata first).
Args:
lon (float): Longitude.
lat (float): Latitude.
heading (float, optional): Compass heading (0=N, 90=E, 180=S, 270=W).
pitch (float, optional): Camera pitch (positive=up).
fov (float, optional): Field of view (1-120). Defaults to 90.
size (str, optional): Image size. Defaults to ``"640x480"``.
radius (int, optional): Search radius. Defaults to 50.
source (str, optional): ``"default"`` or ``"outdoor"``.
Returns:
bytes or None: JPEG image bytes.
"""
meta = streetview_metadata(lon, lat, radius=radius, source=source)
if meta.get("status") != "OK":
return None
try:
return _fetch_bytes(_SV_STATIC_URL, {
"location": f"{lat},{lon}",
"size": size,
"heading": str(heading),
"pitch": str(pitch),
"fov": str(fov),
"radius": str(radius),
"source": source,
"return_error_code": "true",
"key": _get_api_key(),
})
except urllib.error.HTTPError:
return None
def streetview_images_cardinal(
lon: float,
lat: float,
pitch: float = 0,
fov: float = _SV_DEFAULT_FOV,
size: str = _SV_DEFAULT_SIZE,
radius: int = 50,
source: str = "default",
) -> dict[str, bytes] | None:
"""Fetch Street View images looking N, E, S, and W.
Returns ``None`` if no imagery exists.
Args:
lon, lat, pitch, fov, size, radius, source: See :func:`streetview_image`.
Returns:
dict or None: ``{"N": bytes, "E": bytes, "S": bytes, "W": bytes}``.
"""
meta = streetview_metadata(lon, lat, radius=radius, source=source)
if meta.get("status") != "OK":
return None
results = {}
for label, heading in {"N": 0, "E": 90, "S": 180, "W": 270}.items():
img = streetview_image(lon, lat, heading=heading, pitch=pitch, fov=fov,
size=size, radius=radius, source=source)
if img:
results[label] = img
return results if results else None
def streetview_panorama(
lon: float,
lat: float,
heading: float = 0,
fov: float = 360,
pitch: float = 0,
size: str = _SV_DEFAULT_SIZE,
radius: int = 50,
source: str = "default",
) -> bytes | None:
"""Fetch a wide-angle or full 360° Street View panorama as a stitched image.
The Google Street View Static API caps FOV at 120°. This function
automatically splits wider requests into multiple 120° frames and
stitches them horizontally using PIL.
Args:
lon (float): Longitude.
lat (float): Latitude.
heading (float, optional): Center compass heading of the panorama
(0=North). The panorama spans ``heading - fov/2`` to
``heading + fov/2``. Defaults to ``0``.
fov (float, optional): Total horizontal field of view in degrees
(1–360). Values ≤ 120 are handled in a single frame.
Defaults to ``360``.
pitch (float, optional): Camera pitch. Defaults to ``0``.
size (str, optional): Per-frame size as ``"WxH"``.
Defaults to ``"640x480"``.
radius (int, optional): Search radius. Defaults to ``50``.
source (str, optional): ``"default"`` or ``"outdoor"``.
Returns:
bytes or None: JPEG bytes of the stitched panorama, or ``None``
if no imagery exists.
Example:
>>> pano = streetview_panorama(-111.80, 40.68, heading=0, fov=360)
>>> if pano:
... with open("panorama_360.jpg", "wb") as f:
... f.write(pano)
"""
from PIL import Image
import io as _io
meta = streetview_metadata(lon, lat, radius=radius, source=source)
if meta.get("status") != "OK":
return None
fov = max(1, min(fov, 360))
# Single frame if within API limit
if fov <= 120:
return streetview_image(lon, lat, heading=heading, pitch=pitch,
fov=fov, size=size, radius=radius, source=source)
# Multiple frames: split into chunks ≤120°, fetch in parallel.
# Each frame's FOV = step size so the frames tile exactly.
# When pitch ≠ 0, we alpha-blend a thin seam zone to smooth
# exposure differences between adjacent frames.
import concurrent.futures
import numpy as np
_MAX_FRAME_FOV = 120
n_frames = max(2, -(-int(fov) // _MAX_FRAME_FOV)) # ceil division
frame_fov = fov / n_frames # per-frame FOV = angular step
start_heading = (heading - fov / 2 + frame_fov / 2) % 360
headings = [(start_heading + i * frame_fov) % 360 for i in range(n_frames)]
def _fetch_frame(h):
"""Fetch a single frame (metadata already verified)."""
try:
return _fetch_bytes(_SV_STATIC_URL, {
"location": f"{lat},{lon}",
"size": size,
"heading": str(h),
"pitch": str(pitch),
"fov": str(frame_fov),
"radius": str(radius),
"source": source,
"return_error_code": "true",
"key": _get_api_key(),
})
except Exception:
return None
# Fetch all frames simultaneously
with concurrent.futures.ThreadPoolExecutor(max_workers=n_frames) as pool:
raw_frames = list(pool.map(_fetch_frame, headings))
frames = []
for img_bytes in raw_frames:
if img_bytes:
frames.append(Image.open(_io.BytesIO(img_bytes)).convert("RGB"))
if not frames:
return None
# Blend width: proportional to |pitch|, 0 at pitch=0
# At pitch=30 ~8% of frame width, at pitch=45 ~12%
blend_px = int(frames[0].size[0] * min(0.15, abs(pitch) / 300.0)) if abs(pitch) > 5 else 0
fw, fh = frames[0].size
total_w = fw * len(frames)
pano = Image.new("RGB", (total_w, fh))
# Place first frame
pano.paste(frames[0], (0, 0))
for i in range(1, len(frames)):
x = fw * i
curr = frames[i]
if blend_px > 0:
# Alpha-blend a thin strip at the left seam of this frame
left_arr = np.array(pano.crop((x - blend_px, 0, x, fh))).astype(np.float32)
right_arr = np.array(curr.crop((0, 0, blend_px, fh))).astype(np.float32)
alpha = np.linspace(1, 0, blend_px).reshape(1, -1, 1)
blended = (left_arr * alpha + right_arr * (1 - alpha)).astype(np.uint8)
pano.paste(Image.fromarray(blended), (x - blend_px, 0))
# Paste remainder of frame after blend zone
pano.paste(curr.crop((blend_px, 0, curr.size[0], fh)), (x, 0))
else:
pano.paste(curr, (x, 0))
buf = _io.BytesIO()
pano.save(buf, format="JPEG", quality=90)
return buf.getvalue()
def interpret_image(
image_bytes: bytes,
prompt: str | None = None,
model: str = "gemini-3-flash-preview",
context: str | None = None,
) -> dict[str, Any]:
"""Interpret a Street View or satellite image using Google Gemini.
Sends the image to Gemini with instructions to identify and count
all notable features. Returns a structured description with a
tabular object inventory.
Args:
image_bytes (bytes): JPEG or PNG image bytes.
prompt (str, optional): Custom prompt to override the default.
When ``None``, uses a built-in prompt that asks for feature
identification and a tabular count.
model (str, optional): Gemini model name. Defaults to
``"gemini-3-flash-preview"``.
context (str, optional): Additional context to include in the
prompt (e.g. location, date, purpose). Defaults to ``None``.
Returns:
dict: Keys:
- ``description`` (str): Full text description of the image.
- ``object_counts`` (str): Markdown table of object counts.
- ``raw_response`` (str): Complete Gemini response text.
Example:
>>> img = streetview_image(-111.80, 40.68, heading=0)
>>> result = interpret_image(img)
>>> print(result['description'])
>>> print(result['object_counts'])
"""
from google import genai
from google.genai import types
api_key = _get_gemini_key()
client = genai.Client(api_key=api_key)
if prompt is None:
prompt = (
"This is a Google Street View image. Analyze it thoroughly.\n\n"
"1. **Description**: Describe the scene in 2-3 sentences — "
"the setting, land use, vegetation, infrastructure, and any "
"notable features.\n\n"
"2. **Object Inventory**: List every distinct object or feature "
"you can identify with a count. Format as a markdown table with "
"columns: | Object | Count | Notes |\n"
"Include items like: buildings, houses, vehicles, trees, signs, "
"driveways, fences, utility poles, sidewalks, mailboxes, etc. "
"Be specific (e.g. 'brick ranch house' not just 'building').\n\n"
"3. **Land Cover Assessment**: Estimate the approximate percentage "
"of the visible area that is: impervious surface (road, driveway, "
"roof), vegetation (lawn, trees), bare soil, sky."
)
if context:
prompt = f"Location context: {context}\n\n{prompt}"
image_part = types.Part.from_bytes(data=image_bytes, mime_type="image/jpeg")
response = client.models.generate_content(
model=model,
contents=[prompt, image_part],
config=types.GenerateContentConfig(temperature=0.2),
)
raw = response.text
# Parse out sections
description = ""
object_counts = ""
lines = raw.split("\n")
in_table = False
desc_lines = []
table_lines = []
for line in lines:
if "|" in line and ("Object" in line or "Count" in line or "---" in line):
in_table = True
if in_table:
if "|" in line:
table_lines.append(line)
elif line.strip() == "":
if table_lines:
in_table = False
else:
in_table = False
elif not line.strip().startswith("#") and not line.strip().startswith("**Object"):
desc_lines.append(line)
description = "\n".join(desc_lines).strip()
object_counts = "\n".join(table_lines).strip()
return {
"description": description,
"object_counts": object_counts,
"raw_response": raw,
}
def _get_gemini_key() -> str:
"""Get the Gemini API key, separate from Maps Platform key."""
_env = {}
_env_path = os.path.join(os.path.dirname(__file__), ".env")
if os.path.exists(_env_path):
with open(_env_path) as _f:
for _line in _f:
_line = _line.strip()
if "=" in _line and not _line.startswith("#"):
_k, _v = _line.split("=", 1)
_env[_k.strip()] = _v.strip().strip("'\"")
# Check Gemini-specific key first, then general Google key
for key_name in ("GEMINI_API_KEY", "GOOGLE_API_KEY"):
for source in (_env, os.environ):
val = source.get(key_name)
if val:
return val
return _get_api_key() # last resort: use Maps Platform key
def label_streetview(
lon: float,
lat: float,
prompt: str | None = None,
heading: float = 0,
fov: float = 360,
pitch: float = 0,
size: str = _SV_DEFAULT_SIZE,
radius: int = 50,
source: str = "default",
model: str = "gemini-3-flash-preview",
max_labels: int = 30,
font_size: int = 12,
) -> dict[str, Any] | None:
"""Fetch a Street View panorama and label detected objects with bounding boxes.
Uses Gemini's vision model to detect objects and return bounding
boxes, then draws labeled boxes on the panorama.
Args:
lon (float): Longitude.
lat (float): Latitude.
prompt (str, optional): Custom detection prompt. The location
context header and JSON format footer are always included.
heading (float, optional): Center heading. Defaults to ``0``.
fov (float, optional): Field of view (1-360). Defaults to ``360``.
pitch (float, optional): Camera pitch. Defaults to ``0``.
size (str, optional): Per-frame size. Defaults to ``"640x480"``.
radius (int, optional): Search radius. Defaults to ``50``.
source (str, optional): ``"default"`` or ``"outdoor"``.
model (str, optional): Gemini model. Defaults to
``"gemini-3-flash-preview"``.
max_labels (int, optional): Maximum objects. Defaults to ``30``.
font_size (int, optional): Label font size. Defaults to ``12``.
Returns:
dict or None: Keys: ``image``, ``detections``, ``summary``,
``original``, ``location``.
Example:
>>> result = label_streetview(-111.80, 40.68, fov=360)
>>> if result:
... with open("labeled.jpg", "wb") as f:
... f.write(result['image'])
... print(result['summary'])
"""
from PIL import Image, ImageDraw, ImageFont
import io as _io
from google import genai
from google.genai import types
# Fetch the panorama
pano_bytes = streetview_panorama(
lon, lat, heading=heading, fov=fov, pitch=pitch,
size=size, radius=radius, source=source,
)
if pano_bytes is None:
return None
pano_img = Image.open(_io.BytesIO(pano_bytes)).convert("RGB")
img_w, img_h = pano_img.size
# Get location info
meta = streetview_metadata(lon, lat, radius=radius, source=source)
location_str = ""
if meta.get("status") == "OK":
addr = reverse_geocode(lon, lat)
location_str = addr.get("formatted_address", "") if addr else f"({lat:.4f}, {lon:.4f})"
# Build prompt: header + body + footer
_header = f"This is a Google Street View panorama image at {location_str}.\n"
if prompt is None:
_body = (
f"Detect and label the {max_labels} most noteworthy features and objects.\n"
"Be specific with labels (e.g. 'white SUV' not just 'car').\n"
)
else:
_body = prompt + "\n"
_footer = (
"\nFor each detection, return the object label and its bounding box "
"as [y_min, x_min, y_max, x_max] normalized to 0-1000.\n"
"Do NOT identify or label Google watermarks, copyright text, or UI overlays.\n"
"Return ONLY valid JSON:\n"
'{"detections": [{"label": "object name", "box_2d": [y_min, x_min, y_max, x_max]}]}\n'
)
# Call Gemini
api_key = _get_gemini_key()
client = genai.Client(api_key=api_key)
image_part = types.Part.from_bytes(data=pano_bytes, mime_type="image/jpeg")
response = client.models.generate_content(
model=model,
contents=[_header + _body + _footer, image_part],
config=types.GenerateContentConfig(
temperature=0.1,
response_mime_type="application/json",
),
)
# Parse
import json as _json
try:
detections = _json.loads(response.text.strip()).get("detections", [])
except (_json.JSONDecodeError, AttributeError):
detections = []
# One color per unique label
import random as _rand, colorsys as _cs
_rand.seed(42)
unique_labels = list(dict.fromkeys(d.get("label", "?") for d in detections))
label_colors: dict[str, tuple] = {}
for i, lbl in enumerate(unique_labels):
hue = (i / max(len(unique_labels), 1) + _rand.uniform(-0.03, 0.03)) % 1.0
r, g, b = _cs.hsv_to_rgb(hue, 0.9, 0.95)
label_colors[lbl] = (int(r * 255), int(g * 255), int(b * 255))
# Draw boxes
draw = ImageDraw.Draw(pano_img)
try:
font = ImageFont.truetype("arial.ttf", font_size)
except (OSError, IOError):
try:
font = ImageFont.load_default(size=font_size)
except TypeError:
font = ImageFont.load_default()
parsed = []
for det in detections:
label = det.get("label", "?")
box = det.get("box_2d", [])
if len(box) != 4:
continue
color = label_colors.get(label, (0, 255, 100))
y0, x0, y1, x1 = box
px_x0 = int(x0 / 1000 * img_w)
px_y0 = int(y0 / 1000 * img_h)
px_x1 = int(x1 / 1000 * img_w)
px_y1 = int(y1 / 1000 * img_h)
# Dashed box
for edge in [[(px_x0,px_y0),(px_x1,px_y0)], [(px_x1,px_y0),(px_x1,px_y1)],
[(px_x1,px_y1),(px_x0,px_y1)], [(px_x0,px_y1),(px_x0,px_y0)]]:
(sx,sy),(ex,ey) = edge
dx, dy = ex-sx, ey-sy
length = max(1, (dx**2+dy**2)**0.5)
for d in range(int(length/13)+1):
sf = d*13/length
ef = min((d*13+8)/length, 1.0)
draw.line([(int(sx+dx*sf),int(sy+dy*sf)),
(int(sx+dx*ef),int(sy+dy*ef))], fill=color, width=2)
# Label
tb = draw.textbbox((0,0), label, font=font)
tw, th = tb[2]-tb[0], tb[3]-tb[1]
ly = max(0, px_y0-th-4)
draw.rectangle([px_x0, ly, px_x0+tw+6, ly+th+4], fill=(0,0,0))
draw.text((px_x0+3, ly+1), label, fill=color, font=font)
parsed.append({"label": label, "box": [px_x0,px_y0,px_x1,px_y1], "color": color})
# Summary
lines = ["| # | Object | Box |", "|---|---|---|"]
for i, d in enumerate(parsed):
b = d["box"]
lines.append(f"| {i+1} | {d['label']} | ({b[0]},{b[1]},{b[2]},{b[3]}) |")
buf = _io.BytesIO()
pano_img.save(buf, format="JPEG", quality=92)
return {
"image": buf.getvalue(),
"detections": parsed,
"summary": "\n".join(lines),
"original": pano_bytes,
"location": location_str,
}
def streetview_html(
lon: float,
lat: float,
headings: list[float] | None = None,
pitch: float = 0,
fov: float = _SV_DEFAULT_FOV,
size: str = "400x300",
radius: int = 50,
source: str = "default",
title: str | None = None,
) -> str | None:
"""Generate an HTML panel with embedded Street View images.
Args:
lon, lat: Coordinates.
headings (list, optional): Compass headings. Defaults to [0,90,180,270].
pitch, fov, size, radius, source: See :func:`streetview_image`.
title (str, optional): Title text. Auto-generated if None.
Returns:
str or None: Self-contained HTML string, or None if no imagery.
"""
meta = streetview_metadata(lon, lat, radius=radius, source=source)
if meta.get("status") != "OK":
return None
if headings is None:
headings = [0, 90, 180, 270]
dir_labels = {0: "N", 45: "NE", 90: "E", 135: "SE",
180: "S", 225: "SW", 270: "W", 315: "NW"}
if title is None:
loc = meta.get("location", {})
title = f"Street View at ({loc.get('lat', lat):.4f}, {loc.get('lng', lon):.4f}) — {meta.get('date', '?')}"
tags = []
for h in headings:
img = streetview_image(lon, lat, heading=h, pitch=pitch, fov=fov,
size=size, radius=radius, source=source)
if img:
b64 = base64.b64encode(img).decode("ascii")
label = dir_labels.get(int(h) % 360, f"{h}°")
tags.append(
f'<div style="text-align:center;margin:4px;">'
f'<img src="data:image/jpeg;base64,{b64}" style="border-radius:4px;max-width:100%;"/>'
f'<div style="font-size:12px;color:#aaa;">{label} ({h}°)</div></div>'
)
if not tags:
return None
cols = min(len(tags), 2)
return (
f'<div style="background:#1e1e1e;padding:12px;border-radius:8px;max-width:900px;font-family:sans-serif;">'
f'<div style="color:#eee;font-size:14px;font-weight:bold;margin-bottom:8px;">{title}</div>'
f'<div style="display:grid;grid-template-columns:repeat({cols},1fr);gap:6px;">{"".join(tags)}</div>'
f'<div style="color:#666;font-size:10px;margin-top:6px;">{meta.get("copyright", "© Google")}</div></div>'
)
###########################################################################
# Elevation API
###########################################################################
_ELEVATION_URL = "https://maps.googleapis.com/maps/api/elevation/json"