Artkill24 commited on
Commit
7e2f695
Β·
1 Parent(s): 0476182

fix: load ALL 18222 cities on refresh - remove rotating group logic

Browse files
Files changed (1) hide show
  1. main.py +60 -10
main.py CHANGED
@@ -116,6 +116,56 @@ def get_best_source(lat, lon):
116
  # ─── OPEN-METEO BATCH FETCHER (free, no key, 1000 cities/call) ───────────────
117
  _weather_cache = {} # lat,lon -> weather data
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  def fetch_all_weather_batch(provinces):
120
  """Fetch weather for all provinces using Open-Meteo batch API"""
121
  global _weather_cache
@@ -243,18 +293,18 @@ def refresh_all():
243
  count = 0
244
  top_list = []
245
 
246
- # Fetch weather in small batches, saving progress
247
- logger.info("Fetching weather incrementally from Open-Meteo...")
248
- # Rotating cache: load different 500-city group each refresh
249
  import time
250
- batch_size = 750
251
  total = len(PROVINCES)
252
- num_groups = max(1, (total + batch_size - 1) // batch_size)
253
- group_idx = int(time.time() / 3600) % num_groups # rotates every hour
254
- start = group_idx * batch_size
255
- end = min(start + batch_size, total)
256
- logger.info(f"Loading group {group_idx+1}/{num_groups} ({start}-{end} of {total})")
257
- fetch_all_weather_batch(PROVINCES[start:end])
 
258
  logger.info(f"Weather cache loaded: {len(_weather_cache)} cities")
259
 
260
  for p in PROVINCES:
 
116
  # ─── OPEN-METEO BATCH FETCHER (free, no key, 1000 cities/call) ───────────────
117
  _weather_cache = {} # lat,lon -> weather data
118
 
119
+ def fetch_city_weather(lat, lon, country_code=""):
120
+ """Route to best free source based on geography"""
121
+
122
+ # MET Norway β€” Europa (lat 35-72, lon -25 to 45), illimitato
123
+ if 35 <= lat <= 72 and -25 <= lon <= 45:
124
+ try:
125
+ r = req_lib.get(
126
+ f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={lat:.2f}&lon={lon:.2f}",
127
+ headers={"User-Agent": "WeatherArb/2.0 contact@weatherarb.com"},
128
+ timeout=5)
129
+ if r.status_code == 200:
130
+ ts = r.json()['properties']['timeseries'][0]['data']['instant']['details']
131
+ prec = r.json()['properties']['timeseries'][0]['data'].get('next_1_hours',{}).get('details',{}).get('precipitation_amount',0)
132
+ return {
133
+ "temperature_c": ts.get('air_temperature'),
134
+ "humidity_pct": ts.get('relative_humidity'),
135
+ "wind_kmh": round(ts.get('wind_speed',0)*3.6,1),
136
+ "precipitation_mm": prec or 0,
137
+ "cloud_cover_pct": ts.get('cloud_area_fraction',0),
138
+ "weather_code": 0,
139
+ "source": "met-norway"
140
+ }
141
+ except: pass
142
+
143
+ # NOAA NWS β€” solo US
144
+ if country_code == "US" or (24 <= lat <= 50 and -125 <= lon <= -66):
145
+ try:
146
+ r = req_lib.get(
147
+ f"https://api.weather.gov/points/{lat:.4f},{lon:.4f}",
148
+ headers={"User-Agent": "WeatherArb/2.0 contact@weatherarb.com"},
149
+ timeout=5)
150
+ if r.status_code == 200:
151
+ forecast_url = r.json()['properties']['forecastHourly']
152
+ r2 = req_lib.get(forecast_url, headers={"User-Agent": "WeatherArb/2.0"}, timeout=5)
153
+ if r2.status_code == 200:
154
+ period = r2.json()['properties']['periods'][0]
155
+ temp_c = round((period['temperature'] - 32) * 5/9, 1) if period.get('temperatureUnit') == 'F' else period['temperature']
156
+ return {
157
+ "temperature_c": temp_c,
158
+ "humidity_pct": period.get('relativeHumidity',{}).get('value'),
159
+ "wind_kmh": 0,
160
+ "precipitation_mm": 0,
161
+ "cloud_cover_pct": 0,
162
+ "weather_code": 0,
163
+ "source": "noaa-nws"
164
+ }
165
+ except: pass
166
+
167
+ return None # fallback to Open-Meteo batch
168
+
169
  def fetch_all_weather_batch(provinces):
170
  """Fetch weather for all provinces using Open-Meteo batch API"""
171
  global _weather_cache
 
293
  count = 0
294
  top_list = []
295
 
296
+ # Fetch ALL cities using multi-source routing
297
+ logger.info("Fetching weather for ALL provinces - multi-source...")
 
298
  import time
299
+ batch_size = 1000
300
  total = len(PROVINCES)
301
+ num_batches = max(1, (total + batch_size - 1) // batch_size)
302
+ logger.info(f"Loading all {total} provinces in {num_batches} batches of {batch_size}...")
303
+ for g in range(num_batches):
304
+ start = g * batch_size
305
+ end = min(start + batch_size, total)
306
+ fetch_all_weather_batch(PROVINCES[start:end])
307
+ logger.info(f"Batch {g+1}/{num_batches} done - cache size: {len(_weather_cache)}")
308
  logger.info(f"Weather cache loaded: {len(_weather_cache)} cities")
309
 
310
  for p in PROVINCES: