forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocation.py
More file actions
207 lines (180 loc) · 8.17 KB
/
Copy pathlocation.py
File metadata and controls
207 lines (180 loc) · 8.17 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
import json
import logging
import os
from typing import Optional
import httpx
from database.redis_db import r
from models.geolocation import Geolocation
from utils.executors import db_executor, run_blocking
from utils.http_client import get_maps_client, get_maps_semaphore
logger = logging.getLogger(__name__)
def get_google_maps_location(latitude: float, longitude: float) -> Optional[Geolocation]:
# Round to ~100m precision for cache key
rounded = f"{latitude:.3f},{longitude:.3f}"
cache_key = f"geocode:{rounded}"
# Check Redis cache
try:
cached = r.get(cache_key)
if cached:
data = json.loads(cached)
# The cache is rounded to ~100m and is shared across users. Keep
# the recording's exact coordinates instead of returning the first
# user's coordinates that populated this cell.
return Geolocation(**data).model_copy(update={'latitude': latitude, 'longitude': longitude})
except Exception as e:
logging.warning('Failed to read geocode cache error_type=%s', type(e).__name__)
key = os.getenv('GOOGLE_MAPS_API_KEY')
url = f"https://maps.googleapis.com/maps/api/geocode/json?latlng={latitude},{longitude}&key={key}"
try:
response = httpx.get(url, timeout=10.0)
data = response.json()
except Exception as e:
# Transport failure (timeout/connect) or a non-JSON body (e.g. a Google 5xx HTML error page).
# Return None like the async twin instead of 500ing conversation create/finalize.
logger.error('get_google_maps_location error_type=%s', type(e).__name__)
return None
if data.get('status') != 'OK' or not data.get('results'):
return None
place = data['results'][0]
if not place.get('place_id'):
return None
geo = Geolocation(
google_place_id=place['place_id'],
latitude=latitude,
longitude=longitude,
address=place.get('formatted_address'),
location_type=place['types'][0] if place.get('types') else None,
)
# Cache in Redis (48h TTL)
try:
r.set(cache_key, json.dumps(geo.model_dump()), ex=172800)
except Exception as e:
logging.warning('Failed to cache geocode error_type=%s', type(e).__name__)
return geo
def resolve_geolocation(geolocation: Optional[Geolocation]) -> Optional[Geolocation]:
"""Enrich a raw geolocation via Google Places, keeping the original coordinates when the lookup
misses (returns None) or errors, so a geocode miss/failure never drops the user's location.
Only a geolocation that has coordinates but no google_place_id yet is enriched; anything else is
returned unchanged. Callers should assign the return value once (do not overwrite it afterward).
"""
if not geolocation or geolocation.google_place_id:
return geolocation
try:
enriched = get_google_maps_location(geolocation.latitude, geolocation.longitude)
except Exception as e:
logger.error('resolve_geolocation enrichment failed error_type=%s', type(e).__name__)
return geolocation
if not enriched:
return geolocation
return enriched.model_copy(
update={
'latitude': geolocation.latitude,
'longitude': geolocation.longitude,
'captured_at': geolocation.captured_at,
'capture_source': geolocation.capture_source,
'accuracy': geolocation.accuracy,
'altitude': geolocation.altitude,
}
)
async def async_get_google_maps_location(latitude: float, longitude: float) -> Optional[Geolocation]:
"""Async version of get_google_maps_location using httpx.AsyncClient."""
# Round to ~100m precision for cache key
rounded = f"{latitude:.3f},{longitude:.3f}"
cache_key = f"geocode:{rounded}"
# Check Redis cache
try:
cached = await run_blocking(db_executor, r.get, cache_key)
if cached:
data = json.loads(cached)
# See the sync helper above: cache entries are rounded, but the
# coordinates belong to this recording, not the cache owner.
return Geolocation(**data).model_copy(update={'latitude': latitude, 'longitude': longitude})
except Exception as e:
logging.warning('Failed to read geocode cache error_type=%s', type(e).__name__)
key = os.getenv('GOOGLE_MAPS_API_KEY')
try:
async with get_maps_semaphore():
client = get_maps_client()
response = await client.get(
"https://maps.googleapis.com/maps/api/geocode/json",
params={"latlng": f"{latitude},{longitude}", "key": key},
)
data = response.json()
except Exception as e:
logger.error('async_get_google_maps_location error_type=%s', type(e).__name__)
return None
if data.get('status') != 'OK' or not data.get('results'):
return None
place = data['results'][0]
if not place.get('place_id'):
return None
geo = Geolocation(
google_place_id=place['place_id'],
latitude=latitude,
longitude=longitude,
address=place.get('formatted_address'),
location_type=place['types'][0] if place.get('types') else None,
)
# Cache in Redis (48h TTL)
try:
await run_blocking(db_executor, r.set, cache_key, json.dumps(geo.model_dump()), ex=172800)
except Exception as e:
logging.warning('Failed to cache geocode error_type=%s', type(e).__name__)
return geo
async def async_resolve_geolocation(geolocation: Optional[Geolocation]) -> Optional[Geolocation]:
"""Async variant of resolve_geolocation: enrich via async_get_google_maps_location, keeping the
original coordinates when the lookup misses (returns None) or errors."""
if not geolocation or geolocation.google_place_id:
return geolocation
try:
enriched = await async_get_google_maps_location(geolocation.latitude, geolocation.longitude)
except Exception as e:
logger.error('async_resolve_geolocation enrichment failed error_type=%s', type(e).__name__)
return geolocation
if not enriched:
return geolocation
return enriched.model_copy(
update={
'latitude': geolocation.latitude,
'longitude': geolocation.longitude,
'captured_at': geolocation.captured_at,
'capture_source': geolocation.capture_source,
'accuracy': geolocation.accuracy,
'altitude': geolocation.altitude,
}
)
async def async_get_google_maps_city(latitude: float, longitude: float) -> Optional[str]:
cache_key = f"geocode-city:{latitude:.3f},{longitude:.3f}"
try:
cached = await run_blocking(db_executor, r.get, cache_key)
if cached:
return cached.decode() if isinstance(cached, bytes) else str(cached)
except Exception as error:
logger.warning('Failed to read city geocode cache error_type=%s', type(error).__name__)
key = os.getenv('GOOGLE_MAPS_API_KEY')
try:
async with get_maps_semaphore():
response = await get_maps_client().get(
"https://maps.googleapis.com/maps/api/geocode/json",
params={"latlng": f"{latitude},{longitude}", "key": key},
)
data = response.json()
except Exception as error:
logger.error('City geocoding failed error_type=%s', type(error).__name__)
return None
if data.get('status') != 'OK' or not data.get('results'):
return None
parts = {}
for component in data['results'][0].get('address_components') or []:
for component_type in component.get('types') or []:
if component_type in {'locality', 'postal_town', 'administrative_area_level_1', 'country'}:
parts.setdefault(component_type, component.get('long_name'))
city = parts.get('locality') or parts.get('postal_town')
if not city:
return None
result = ', '.join(part for part in (city, parts.get('administrative_area_level_1'), parts.get('country')) if part)
try:
await run_blocking(db_executor, r.set, cache_key, result, ex=172800)
except Exception as error:
logger.warning('Failed to cache city geocode error_type=%s', type(error).__name__)
return result