File size: 15,042 Bytes
b6c434f cc8a8da b6c434f cc8a8da b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f 414d659 b6c434f cc8a8da b6c434f |
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 |
import datetime as dt
from datetime import date, timedelta
import requests
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import streamlit as st
from streamlit_folium import st_folium
import folium
# ------------------------------
# Sayfa ayarları
# ------------------------------
st.set_page_config(
page_title="Open-Meteo • Haritadan Seç • Tahmin + Arşiv",
page_icon="⛅",
layout="wide"
)
st.title("⛅ Open‑Meteo • Haritadan Konum Seç • Tahmin + Arşiv (CPU‑only)")
st.caption(
"Haritaya tıklayıp konumu seçin. Lejand öğelerine tıklayarak izleri aç/kapatabilir, "
"yan menüden katmanları ve birimleri değiştirebilirsiniz. "
"Çift tıklama = yalnızca seçili iz."
)
# ------------------------------
# API uçları ve varsayılan değişkenler
# ------------------------------
FORECAST_BASE = "https://api.open-meteo.com/v1/forecast"
ARCHIVE_BASE = "https://archive-api.open-meteo.com/v1/archive"
HOURLY_VARS = [
"temperature_2m",
"relative_humidity_2m",
"precipitation",
"wind_speed_10m",
"wind_direction_10m",
"cloud_cover"
]
# Günlükte güneş doğuş/batışını her koşulda tutuyoruz (gece-gündüz gölgeleme için gerekli)
DAILY_VARS = [
"temperature_2m_max",
"temperature_2m_min",
"precipitation_sum",
"wind_speed_10m_max",
"sunrise",
"sunset"
]
# ------------------------------
# Yardımcılar
# ------------------------------
def fetch_openmeteo(mode, lat, lon, *, start=None, end=None, forecast_days=7,
temp_unit="celsius", wind_unit="kmh", precip_unit="mm"):
"""
Open-Meteo'dan veri çeker ve saatlik/günlük DataFrame döndürür.
temp_unit: celsius|fahrenheit
wind_unit: kmh|ms|mph|kn (Open-Meteo parametre adı: windspeed_unit)
precip_unit: mm|inch
"""
params = {
"latitude": lat,
"longitude": lon,
"timezone": "auto",
"hourly": ",".join(HOURLY_VARS),
"daily": ",".join(DAILY_VARS),
"temperature_unit": temp_unit,
"windspeed_unit": wind_unit, # <— DÜZELTİLDİ: windspeed_unit
"precipitation_unit": precip_unit,
}
if mode == "Tahmin":
params["forecast_days"] = int(forecast_days)
url = FORECAST_BASE
else:
params["start_date"] = start
params["end_date"] = end
url = ARCHIVE_BASE
r = requests.get(url, params=params, timeout=30)
r.raise_for_status()
data = r.json()
tz = data.get("timezone", "GMT")
# Saatlik DF
hourly = data.get("hourly", {})
df_h = None
if hourly.get("time"):
df_h = pd.DataFrame(hourly)
df_h["time"] = pd.to_datetime(df_h["time"])
df_h = df_h.set_index("time").sort_index()
# Günlük DF
daily = data.get("daily", {})
df_d = None
if daily.get("time"):
df_d = pd.DataFrame(daily)
df_d["time"] = pd.to_datetime(df_d["time"])
# sunrise/sunset kolonlarını datetime'a çevir
for col in ("sunrise", "sunset"):
if col in df_d.columns:
df_d[col] = pd.to_datetime(df_d[col], errors="coerce")
df_d = df_d.set_index("time").sort_index()
return tz, df_h, df_d, data
def add_night_shading(fig, df_d, df_h):
"""Gün doğumu/batımı kullanarak gece bölümlerini arkaya açık renk gölge olarak ekler."""
if df_d is None or df_h is None:
return fig
if not {"sunrise", "sunset"}.issubset(df_d.columns):
return fig
if df_h.empty or df_d.empty:
return fig
h_start = df_h.index.min()
h_end = df_h.index.max()
shapes = []
for _, row in df_d.iterrows():
sr, ss = row.get("sunrise"), row.get("sunset")
if pd.isna(sr) or pd.isna(ss):
continue
day_midnight = pd.Timestamp(sr.date())
next_midnight = day_midnight + pd.Timedelta(days=1)
# Gece 1: 00:00 -> Gün doğumu
left = max(day_midnight, h_start)
right = min(sr, h_end)
if left < right:
shapes.append(dict(
type="rect", xref="x", yref="paper",
x0=left, x1=right, y0=0, y1=1,
fillcolor="rgba(0,0,0,0.08)", line=dict(width=0), layer="below"
))
# Gece 2: Gün batımı -> 24:00
left = max(ss, h_start)
right = min(next_midnight, h_end)
if left < right:
shapes.append(dict(
type="rect", xref="x", yref="paper",
x0=left, x1=right, y0=0, y1=1,
fillcolor="rgba(0,0,0,0.08)", line=dict(width=0), layer="below"
))
if shapes:
fig.update_layout(shapes=shapes)
return fig
def fig_hourly(df_h, tz_name, *,
show_temp=True, show_precip=True, show_wind=True,
temp_label="°C", precip_label="mm", wind_label="km/sa",
smooth_window=1, df_d=None):
"""Saatlik grafik: sıcaklık, yağış, rüzgâr. İzleri checkbox ile seçilebilir; lejand tıklamasıyla aç/kapa."""
fig = make_subplots(specs=[[{"secondary_y": True}]])
dfp = df_h.copy()
# Yumuşatma (yalnız çizgi serilere)
if smooth_window and smooth_window > 1:
if "temperature_2m" in dfp.columns:
dfp["temperature_2m"] = dfp["temperature_2m"].rolling(smooth_window, min_periods=1).mean()
if "wind_speed_10m" in dfp.columns:
dfp["wind_speed_10m"] = dfp["wind_speed_10m"].rolling(smooth_window, min_periods=1).mean()
if show_temp and "temperature_2m" in dfp:
fig.add_trace(go.Scatter(
x=dfp.index, y=dfp["temperature_2m"], mode="lines",
name=f"Sıcaklık ({temp_label})"
), secondary_y=False)
if show_precip and "precipitation" in dfp:
fig.add_trace(go.Bar(
x=dfp.index, y=dfp["precipitation"], name=f"Yağış ({precip_label})", opacity=0.35
), secondary_y=True)
if show_wind and "wind_speed_10m" in dfp:
fig.add_trace(go.Scatter(
x=dfp.index, y=dfp["wind_speed_10m"], mode="lines",
name=f"Rüzgâr ({wind_label})"
), secondary_y=True)
fig.update_layout(
title=f"Saatlik Seri ({tz_name})",
margin=dict(l=10, r=10, t=40, b=10),
height=440,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0),
)
fig.update_xaxes(title_text="Zaman")
fig.update_yaxes(title_text=f"Sıcaklık ({temp_label})", secondary_y=False)
fig.update_yaxes(title_text=f"Yağış ({precip_label}) / Rüzgâr ({wind_label})", secondary_y=True)
# Gece-gündüz gölgeleme
fig = add_night_shading(fig, df_d, dfp)
return fig
def fig_daily(df_d, *, show_daily_precip=True, temp_label="°C", precip_label="mm"):
"""Günlük grafik: min‑max sıcaklık bandı + (opsiyonel) toplam yağış."""
fig = make_subplots(specs=[[{"secondary_y": True}]])
have_minmax = {"temperature_2m_min", "temperature_2m_max"}.issubset(df_d.columns)
if have_minmax:
fig.add_trace(go.Scatter(
x=df_d.index, y=df_d["temperature_2m_min"], mode="lines",
name=f"Günlük Min ({temp_label})"
), secondary_y=False)
fig.add_trace(go.Scatter(
x=df_d.index, y=df_d["temperature_2m_max"], mode="lines",
name=f"Günlük Max ({temp_label})", fill="tonexty"
), secondary_y=False)
if show_daily_precip and "precipitation_sum" in df_d:
fig.add_trace(go.Bar(
x=df_d.index, y=df_d["precipitation_sum"],
name=f"Toplam Yağış ({precip_label})", opacity=0.35
), secondary_y=True)
fig.update_layout(
title="Günlük Özet (Min‑Max Bandı & Yağış)",
margin=dict(l=10, r=10, t=40, b=10),
height=440,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0),
)
fig.update_xaxes(title_text="Tarih")
fig.update_yaxes(title_text=f"Sıcaklık ({temp_label})", secondary_y=False)
fig.update_yaxes(title_text=f"Yağış ({precip_label})", secondary_y=True)
return fig
def csv_bytes(df: pd.DataFrame) -> bytes:
return df.to_csv(index=True).encode("utf-8")
# ------------------------------
# Kenar çubuğu (ayarlar)
# ------------------------------
with st.sidebar:
st.header("⚙️ Ayarlar")
mode = st.radio("Veri tipi", ["Tahmin", "Geçmiş (Arşiv)"], horizontal=True)
if mode == "Tahmin":
forecast_days = st.slider("Tahmin günü", min_value=1, max_value=16, value=7)
else:
today = date.today()
default_start = today - timedelta(days=14)
default_end = today - timedelta(days=5) # arşiv birkaç gün gecikmeli olur
start_date = st.date_input("Başlangıç tarihi", value=default_start, max_value=today)
end_date = st.date_input("Bitiş tarihi", value=default_end, max_value=today)
if start_date > end_date:
st.error("Başlangıç tarihi, bitiş tarihinden büyük olamaz.")
st.markdown("---")
st.subheader("📊 Grafik katmanları")
show_temp = st.checkbox("Sıcaklık (saatlik)", value=True)
show_precip = st.checkbox("Yağış (saatlik)", value=True)
show_wind = st.checkbox("Rüzgâr hızı (saatlik)", value=True)
show_daily_precip = st.checkbox("Günlük toplam yağış", value=True)
st.markdown("---")
st.subheader("🧰 Görselleştirme seçenekleri")
smooth_window = st.slider("Saatlik çizgiler için yumuşatma (saat)", 1, 6, 1,
help="1 = yumuşatma yok. Sadece çizgi serilere uygulanır (sıcaklık, rüzgâr).")
st.markdown("---")
st.subheader("📏 Birimler")
colu1, colu2, colu3 = st.columns(3)
with colu1:
temp_choice = st.radio("Sıcaklık", ["°C", "°F"], horizontal=True, index=0)
with colu2:
wind_choice = st.radio("Rüzgâr", ["km/sa", "m/sn"], horizontal=True, index=0)
with colu3:
precip_choice = st.radio("Yağış", ["mm", "inç"], horizontal=True, index=0)
# UI -> API birim eşlemesi
temp_unit_api = "celsius" if temp_choice == "°C" else "fahrenheit"
wind_unit_api = "kmh" if wind_choice == "km/sa" else "ms"
precip_unit_api = "mm" if precip_choice == "mm" else "inch"
temp_label = "°C" if temp_unit_api == "celsius" else "°F"
wind_label = "km/sa" if wind_unit_api == "kmh" else "m/sn"
precip_label = "mm" if precip_unit_api == "mm" else "in"
# ------------------------------
# Harita (konum seçimi) + Favoriler
# ------------------------------
st.subheader("🗺️ Konum seç")
if "lat" not in st.session_state:
st.session_state.lat = 41.0082 # İstanbul
if "lon" not in st.session_state:
st.session_state.lon = 28.9784
if "favorites" not in st.session_state:
st.session_state.favorites = [] # {"name": str, "lat": float, "lon": float}
col_map, col_info = st.columns([2.2, 1.0], vertical_alignment="top")
with col_map:
m = folium.Map(location=[st.session_state.lat, st.session_state.lon], zoom_start=6, control_scale=True)
folium.Marker(location=[st.session_state.lat, st.session_state.lon],
tooltip="Seçili konum").add_to(m)
m.add_child(folium.LatLngPopup())
map_state = st_folium(m, use_container_width=True, height=460, returned_objects=["last_clicked"])
if map_state and map_state.get("last_clicked"):
st.session_state.lat = round(float(map_state["last_clicked"]["lat"]), 5)
st.session_state.lon = round(float(map_state["last_clicked"]["lng"]), 5)
with col_info:
st.write("**Seçili koordinatlar**")
st.metric("Enlem (lat)", st.session_state.lat)
st.metric("Boylam (lon)", st.session_state.lon)
st.markdown("**⭐ Favoriler**")
fav_name = st.text_input("Bu konumu isimlendir", placeholder="ör. İstanbul-Ofis")
add_btn = st.button("Bu konumu favorilere ekle")
if add_btn and fav_name.strip():
st.session_state.favorites.append({"name": fav_name.strip(),
"lat": st.session_state.lat,
"lon": st.session_state.lon})
st.success(f"“{fav_name}” eklendi.")
if st.session_state.favorites:
names = [f["name"] for f in st.session_state.favorites]
sel = st.selectbox("Favori konumu yükle", names, index=None, placeholder="Seçin…")
if sel:
f = next(x for x in st.session_state.favorites if x["name"] == sel)
if st.button("Seçili favoriye git"):
st.session_state.lat = f["lat"]
st.session_state.lon = f["lon"]
# ------------------------------
# Veri çekme + görselleştirme
# ------------------------------
st.subheader("📈 Grafikler ve İndirmeler")
try:
if mode == "Tahmin":
tz, df_h, df_d, raw = fetch_openmeteo(
mode="Tahmin",
lat=st.session_state.lat,
lon=st.session_state.lon,
forecast_days=forecast_days,
temp_unit=temp_unit_api,
wind_unit=wind_unit_api,
precip_unit=precip_unit_api
)
else:
tz, df_h, df_d, raw = fetch_openmeteo(
mode="Geçmiş",
lat=st.session_state.lat,
lon=st.session_state.lon,
start=start_date.isoformat(),
end=end_date.isoformat(),
temp_unit=temp_unit_api,
wind_unit=wind_unit_api,
precip_unit=precip_unit_api
)
cfg = {"displaylogo": False, "displayModeBar": True}
if df_h is not None and not df_h.empty:
st.plotly_chart(
fig_hourly(
df_h, tz_name=tz,
show_temp=show_temp,
show_precip=show_precip,
show_wind=show_wind,
temp_label=temp_label,
precip_label=precip_label,
wind_label=wind_label,
smooth_window=smooth_window,
df_d=df_d
),
use_container_width=True, config=cfg
)
st.download_button("Saatlik veriyi CSV indir", data=csv_bytes(df_h),
file_name="hourly.csv", mime="text/csv")
if df_d is not None and not df_d.empty:
st.plotly_chart(
fig_daily(
df_d,
show_daily_precip=show_daily_precip,
temp_label=temp_label,
precip_label=precip_label
),
use_container_width=True, config=cfg
)
st.download_button("Günlük veriyi CSV indir", data=csv_bytes(df_d),
file_name="daily.csv", mime="text/csv")
if (df_h is None or df_h.empty) and (df_d is None or df_d.empty):
st.info("Seçili aralık/konum için veri bulunamadı. Aralığı daraltmayı veya farklı konum seçmeyi deneyin.")
except requests.HTTPError as e:
st.error(f"Open‑Meteo isteği başarısız oldu: {e}")
except Exception as e:
st.error(f"Beklenmeyen bir hata oluştu: {e}")
|