|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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." |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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" |
|
|
] |
|
|
|
|
|
|
|
|
DAILY_VARS = [ |
|
|
"temperature_2m_max", |
|
|
"temperature_2m_min", |
|
|
"precipitation_sum", |
|
|
"wind_speed_10m_max", |
|
|
"sunrise", |
|
|
"sunset" |
|
|
] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, |
|
|
"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") |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
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"]) |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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" |
|
|
)) |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
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) |
|
|
|
|
|
|
|
|
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" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
st.subheader("🗺️ Konum seç") |
|
|
if "lat" not in st.session_state: |
|
|
st.session_state.lat = 41.0082 |
|
|
if "lon" not in st.session_state: |
|
|
st.session_state.lon = 28.9784 |
|
|
if "favorites" not in st.session_state: |
|
|
st.session_state.favorites = [] |
|
|
|
|
|
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"] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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}") |
|
|
|