File size: 7,976 Bytes
0c954a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import folium
import pandas as pd
from datetime import datetime, timedelta
import time
import os
import json

# Kandilli Rasathanesi API URL
KANDILLI_API_URL = "https://api.orhanaydogdu.com.tr/deprem/kandilli/live"
CACHE_DIR = os.path.join(os.path.dirname(__file__), "cache")
os.makedirs(CACHE_DIR, exist_ok=True)

def get_kandilli_data(hours=12, min_mag=1.0, use_cache=True, cache_max_age_minutes=15):
    """Kandilli Rasathanesi API'den son depremleri çek"""
    # Cache dosyası
    cache_file = os.path.join(CACHE_DIR, f"kandilli_data_{hours}h.json")
    
    # Önbellekten veri yükleme kontrolü
    if use_cache and os.path.exists(cache_file):
        file_age_minutes = (time.time() - os.path.getmtime(cache_file)) / 60
        if file_age_minutes < cache_max_age_minutes:
            try:
                with open(cache_file, 'r', encoding='utf-8') as f:
                    print(f"Loading cached data (age: {file_age_minutes:.1f} minutes)")
                    return json.load(f)
            except Exception as e:
                print(f"Cache loading error: {e}")
    
    # Zaman aralığını hesapla
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=hours)
    
    try:
        # API isteği gönder
        print(f"Fetching earthquake data from Kandilli API for the last {hours} hours...")
        response = requests.get(KANDILLI_API_URL, timeout=10)
        response.raise_for_status()  # Hata kontrolü
        
        # JSON verisini al
        data = response.json()
        
        # Zaman aralığına ve minimum büyüklüğe göre filtrele
        if "result" in data:
            filtered_results = []
            for quake in data["result"]:
                try:
                    # Tarih formatını kontrol et ve dönüştür
                    quake_time = datetime.strptime(quake.get("date", ""), "%Y.%m.%d %H:%M:%S")
                    if quake_time >= start_time and float(quake.get("mag", 0)) >= min_mag:
                        filtered_results.append(quake)
                except (ValueError, TypeError) as e:
                    print(f"Date conversion error: {e}")
                    continue
            
            data["result"] = filtered_results
        
        # Önbelleğe kaydet
        with open(cache_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False)
        
        return data
    except Exception as e:
        print(f"Kandilli API error: {e}")
        
        # API hatası durumunda önbellekteki veriyi kullanmayı dene
        if os.path.exists(cache_file):
            try:
                with open(cache_file, 'r', encoding='utf-8') as f:
                    print(f"Using cached data due to API error")
                    return json.load(f)
            except Exception as cache_error:
                print(f"Cache error: {cache_error}")
        
        # Hiçbir veri yoksa boş sonuç döndür
        return {"result": []}

def create_quake_map(quake_data):
    """Deprem verilerini haritada göster"""
    # Boş veri kontrolü
    if not quake_data or "result" not in quake_data or not quake_data["result"]:
        # Boş harita döndür
        m = folium.Map(location=[39.0, 35.0], zoom_start=5)
        folium.Marker(
            [39.0, 35.0],
            popup="Deprem verisi bulunamadı",
            icon=folium.Icon(color="gray")
        ).add_to(m)
        return m
    
    # Deprem verilerini DataFrame'e dönüştür
    quakes = []
    for quake in quake_data["result"]:
        try:
            quakes.append({
                "id": quake.get("earthquake_id", ""),
                "time": quake.get("date", ""),
                "latitude": float(quake.get("geojson", {}).get("coordinates", [0, 0, 0])[1]),
                "longitude": float(quake.get("geojson", {}).get("coordinates", [0, 0, 0])[0]),
                "depth": float(quake.get("depth", 0)),
                "magnitude": float(quake.get("mag", 0)),
                "location": quake.get("title", ""),
                "type": quake.get("mag_type", "")
            })
        except (ValueError, TypeError, IndexError) as e:
            print(f"Data conversion error: {e}")
            continue
    
    df = pd.DataFrame(quakes)
    
    if df.empty:
        # Boş harita döndür
        m = folium.Map(location=[39.0, 35.0], zoom_start=5)
        folium.Marker(
            [39.0, 35.0],
            popup="Deprem verisi bulunamadı",
            icon=folium.Icon(color="gray")
        ).add_to(m)
        return m
    
    # Türkiye'nin merkezi
    center_lat = df["latitude"].mean()
    center_lon = df["longitude"].mean()
    
    # Harita oluştur
    m = folium.Map(location=[center_lat, center_lon], zoom_start=6)
    
    # Depremleri haritaya ekle
    for _, row in df.iterrows():
        # Büyüklüğe göre renk belirle
        if row["magnitude"] >= 5.0:
            color = "red"
        elif row["magnitude"] >= 4.0:
            color = "orange"
        elif row["magnitude"] >= 3.0:
            color = "yellow"
        else:
            color = "green"
        
        # Büyüklüğe göre çap belirle
        radius = row["magnitude"] * 5000
        
        # Popup içeriği
        popup_html = f"""
        <div style="font-family: Arial; width: 200px;">
            <h4>Deprem Bilgisi</h4>
            <b>Tarih:</b> {row["time"]}<br>
            <b>Büyüklük:</b> {row["magnitude"]}<br>
            <b>Derinlik:</b> {row["depth"]} km<br>
            <b>Konum:</b> {row["location"]}<br>
        </div>
        """
        
        # Dairesel işaret ekle
        folium.Circle(
            location=[row["latitude"], row["longitude"]],
            radius=radius,
            color=color,
            fill=True,
            fill_color=color,
            fill_opacity=0.4,
            popup=folium.Popup(popup_html, max_width=300)
        ).add_to(m)
        
        # Merkez noktası ekle
        folium.CircleMarker(
            location=[row["latitude"], row["longitude"]],
            radius=5,
            color=color,
            fill=True,
            fill_color="white",
            fill_opacity=0.7,
            popup=folium.Popup(popup_html, max_width=300)
        ).add_to(m)
    
    # Lejant ekle
    legend_html = """
    <div style="position: fixed; bottom: 50px; left: 50px; z-index: 1000; background-color: white; padding: 10px; border: 2px solid grey; border-radius: 5px;">
        <p><b>Deprem Büyüklüğü</b></p>
        <p><i class="fa fa-circle" style="color: red;"></i> ≥ 5.0</p>
        <p><i class="fa fa-circle" style="color: orange;"></i> 4.0 - 4.9</p>
        <p><i class="fa fa-circle" style="color: yellow;"></i> 3.0 - 3.9</p>
        <p><i class="fa fa-circle" style="color: green;"></i> < 3.0</p>
    </div>
    """
    m.get_root().html.add_child(folium.Element(legend_html))
    
    return m

def get_latest_quakes(hours=12, min_mag=1.0):
    """Son depremleri çek ve haritada göster"""
    # Verileri çek
    quake_data = get_kandilli_data(hours=hours, min_mag=min_mag)
    
    # Harita oluştur
    quake_map = create_quake_map(quake_data)
    
    # Son güncelleme bilgisi ekle
    timestamp = datetime.now().strftime("%d.%m.%Y %H:%M:%S")
    quake_map.get_root().html.add_child(folium.Element(
        f'<div style="position: fixed; top: 10px; right: 10px; z-index: 1000; background-color: white; padding: 5px; border-radius: 5px;">'
        f'Son Güncelleme: {timestamp}</div>'
    ))
    
    # HTML olarak döndür
    return quake_map._repr_html_()

# Test
if __name__ == "__main__":
    # Son depremleri çek
    quake_data = get_kandilli_data(hours=24)
    print(f"Fetched {len(quake_data.get('result', []))} earthquakes")
    
    # Haritayı oluştur
    quake_map = create_quake_map(quake_data)
    
    # Haritayı HTML olarak kaydet
    output_file = "son_depremler.html"
    quake_map.save(output_file)
    print(f"Map saved to {output_file}")