Bora9 commited on
Commit
67383ba
·
verified ·
1 Parent(s): 426cd17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +536 -294
app.py CHANGED
@@ -1,304 +1,546 @@
1
- import gradio as gr
2
- import folium
3
- from branca.element import Element
4
- import matplotlib.pyplot as plt
5
- import matplotlib.patches as patches
6
  import pandas as pd
7
- import io
8
- from PIL import Image
 
 
9
  import json
10
- import requests
11
-
12
- # ---------------------------------------------------------------------------
13
- # DATA STORES & DATABASE SIMULATION (In-Memory for Hugging Face)
14
- # ---------------------------------------------------------------------------
15
-
16
- PERIOD_COLORS = {
17
- "Cambrian": "#7FA080", "Ordovician": "#00A88D", "Silurian": "#B3E1B6",
18
- "Devonian": "#CB8C37", "Carboniferous": "#67A5A5", "Permian": "#F04028",
19
- "Triassic": "#812990", "Jurassic": "#3492C7", "Cretaceous": "#8CBA22",
20
- "Paleogene": "#FD9A52", "Neogene": "#FFE619", "Quaternary": "#FFF2AE"
21
- }
22
-
23
- # Sosyal Ağ & İhbar Veritabanları
24
- social_posts = [
25
- {
26
- "user": "Dr. Ahmet Yılmaz (Hidrojeolog)",
27
- "avatar": "👨‍🔬",
28
- "title": "Konya Ovası Yeraltı Su Seviyesi Düşüşü",
29
- "content": "Karapınar bölgesindeki obruk oluşumları ve 120m altındaki akifer kireçtaşlarının statik su seviyesi değişimlerini sahada inceledik.",
30
- "location": "Konya / Karapınar",
31
- "likes": 14,
32
- "comments": ["Harika bir saha çalışması.", "Sondaj derinlikleri kaç metreye ulaştı?"]
 
33
  }
34
- ]
35
-
36
- fossil_reports = []
37
-
38
- # ---------------------------------------------------------------------------
39
- # HYDROGEOLOGY & STRATIGRAPHIC COLUMN GENERATOR
40
- # ---------------------------------------------------------------------------
41
-
42
- def generate_hydro_section(lat, lng, ada="--", parsel="--"):
43
- """
44
- Seçilen koordinat veya parsel için Yeraltı Suyu Arama (Hydrogeological)
45
- Sondaj Kolon Kesiti ve Akifer Potansiyel Raporu üretir.
46
- """
47
- # Macrostrat API'den gerçek bölgesel litoloji çekme
48
- try:
49
- res = requests.get(f"https://macrostrat.org/api/v2/geologic_units/map?lat={lat}&lng={lng}", timeout=4)
50
- data = res.json()
51
- if data.get("success") and data["success"].get("data"):
52
- unit = data["success"]["data"][0]
53
- surface_lith = unit.get("lith", "Alüvyon / Dere Yatağı")
54
- age_info = unit.get("age", "Senozoik")
55
- else:
56
- surface_lith = "Alüvyon Örtü / Toprak"
57
- age_info = "Kuvaterner"
58
- except Exception:
59
- surface_lith = "Alüvyon Ve Detritik Çökel"
60
- age_info = "Kuvaterner"
61
-
62
- # Kolon Kesit Tabakaları (Müteahhit/Çiftçi/Sondör için Yeraltı Suyu Analizi)
63
- layers = [
64
- {"top": 0, "bottom": 8, "name": f"Bitkisel Toprak & {surface_lith}", "type": "permeable", "color": "#d4ac0d", "hatch": "..."},
65
- {"top": 8, "bottom": 35, "name": "Geçirimsiz Kil / Killi Marllar (Geçirimsiz Katman)", "type": "impermeable", "color": "#a04000", "hatch": "///"},
66
- {"top": 35, "bottom": 95, "name": "Kırıklı/Kaviteli Kireçtaşı (Ana Akifer - Yeraltı Suyu Haznesi)", "type": "aquifer", "color": "#2e4053", "hatch": "OO"},
67
- {"top": 95, "bottom": 130, "name": "Taban Kayacı (Marn / Şist / Kristalen Temel)", "type": "bedrock", "color": "#7d6608", "hatch": "xx"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  ]
 
 
 
 
69
 
70
- # Matplotlib Kolon Kesit Çizimi
71
- fig, ax = plt.subplots(figsize=(5, 8))
72
- ax.set_ylim(135, 0) # Derinlik aşağı doğru artar
73
- ax.set_xlim(0, 10)
74
-
75
- for l in layers:
76
- height = l["bottom"] - l["top"]
77
- rect = patches.Rectangle((1, l["top"]), 8, height, linewidth=1.5, edgecolor='black',
78
- facecolor=l["color"], alpha=0.6, hatch=l["hatch"])
79
- ax.add_patch(rect)
80
- # Etiketler
81
- ax.text(5, l["top"] + height/2, f"{l['name']}\n({l['top']}-{l['bottom']}m)",
82
- ha='center', va='center', fontsize=9, fontweight='bold', color='black',
83
- bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", lw=0.5, alpha=0.8))
84
-
85
- # Yeraltı Su Seviyesi Mavi Çizgisi (Statik Su Seviyesi)
86
- water_table_depth = 28.0
87
- ax.axhline(y=water_table_depth, color='blue', linestyle='--', linewidth=2.5, label=f'Statik Su Seviyesi (~{water_table_depth}m)')
88
 
89
- ax.set_ylabel("Derinlik (Metre - m)", fontsize=11, fontweight='bold')
90
- ax.set_title(f"Sondaj Kolon Kesiti & Akifer Analizi\n[Koordinat: {lat:.4f}, {lng:.4f} | Ada: {ada} / Parsel: {parsel}]", fontsize=10, fontweight='bold')
91
- ax.set_xticks([])
92
- ax.legend(loc='lower left')
93
- plt.tight_layout()
94
-
95
- # Rapor Metni
96
- report = f"""
97
- ### 💧 Yeraltı Suyu & Hidrojeoloji Arazi Değerlendirmesi
98
- * **Lokasyon / Parsel:** Enlem {lat:.4f}, Boylam {lng:.4f} (Ada: {ada}, Parsel: {parsel})
99
- * **Yüzey Jeolojisi / Formasyon:** {surface_lith} ({age_info})
100
- * **Tahmini Statik Su Seviyesi:** **{water_table_depth} Metre**
101
- * **Önerilen Sondaj Derinliği:** **80 - 110 Metre**
102
- * **Akifer Potansiyeli:** **YÜKSEK (Kireçtaşı Karstik Hazne)**
103
- * **Tahmini Debi:** **4.5 - 8.0 L/s (Litre/Saniye)**
104
- * **Hidrojeolojik Tavsiye:** İlk 35 metrede killi kılıf borulaması yapılmalı, yüzey süzüntü suyunun kuyuya sızması engellenmelidir. 40-90m arasındaki kireçtaşı seviyesi filtreli boru ile geçilmelidir.
105
- """
106
-
107
- return fig, report
108
-
109
- # ---------------------------------------------------------------------------
110
- # MAP BUILDER WITH TKGM PARCELS & GEOLOGY
111
- # ---------------------------------------------------------------------------
112
-
113
- def build_map():
114
- m = folium.Map(location=[38.97, 35.30], zoom_start=6, tiles="CartoDB positron")
115
-
116
- # 1. TKGM KADASTRO PARSEL KATMANI (WMS)
117
- folium.WmsTileLayer(
118
- url='https://cbs.tkgm.gov.tr/megsis/wms',
119
- layers='parsel',
120
- fmt='image/png',
121
- transparent=True,
122
- name='TKGM Kadastro Parsel Katmanı',
123
- overlay=True,
124
- control=True,
125
- attr='Tapu ve Kadastro Genel Müdürlüğü (TKGM)'
126
- ).add_to(m)
127
-
128
- # 2. MACROSTRAT JEOLOJİ KATMANI
129
- folium.TileLayer(
130
- tiles='https://tiles.macrostrat.org/carto/{z}/{x}/{y}.png',
131
- attr='Macrostrat Geology',
132
- name='Jeolojik Formasyonlar (Litoloji)',
133
- overlay=True,
134
- control=True,
135
- opacity=0.6
136
- ).add_to(m)
137
-
138
- folium.TileLayer("Esri WorldImagery", name="Uydu Görüntüsü").add_to(m)
139
- folium.TileLayer("OpenStreetMap", name="Sokak Haritası").add_to(m)
140
-
141
- folium.LayerControl().add_to(m)
142
-
143
- # Tıklama ile Koordinat ve Litoloji Yakalayan JS
144
- click_js = """
145
- <script>
146
- (function() {
147
- var checkMap = setInterval(function() {
148
- for (var key in window) {
149
- if (key.startsWith('map_') && window[key] instanceof L.Map) {
150
- var myMap = window[key];
151
- if (!myMap._geoListener) {
152
- myMap._geoListener = true;
153
- myMap.on('click', function(e) {
154
- var lat = e.latlng.lat.toFixed(5);
155
- var lng = e.latlng.lng.toFixed(5);
156
- var popup = L.popup()
157
- .setLatLng(e.latlng)
158
- .setContent("<b>Seçilen Nokta:</b><br>Enlem: " + lat + "<br>Boylam: " + lng +
159
- "<br><br><i>💧 Su Arama Sekmesine Bu Koordinat Otomatik Aktarılabilir.</i>")
160
- .openOn(myMap);
161
- });
162
- }
163
- }
164
- }
165
- }, 500);
166
- })();
167
- </script>
168
- """
169
- m.get_root().html.add_child(Element(click_js))
170
- return m._repr_html_()
171
-
172
- # ---------------------------------------------------------------------------
173
- # SOCIAL PLATFORM & FOSSIL REPORTING LOGIC
174
- # ---------------------------------------------------------------------------
175
-
176
- def create_post(user_name, title, content, location):
177
- new_p = {
178
- "user": user_name or "Anonim Jeolog",
179
- "avatar": "👤",
180
- "title": title,
181
- "content": content,
182
- "location": location or "Belirtilmedi",
183
- "likes": 0,
184
- "comments": []
185
- }
186
- social_posts.insert(0, new_p)
187
- return render_social_feed()
188
-
189
- def render_social_feed():
190
- html = "<div style='max-height: 500px; overflow-y: auto;'>"
191
- for p in social_posts:
192
- html += f"""
193
- <div style='border: 1px solid #ddd; border-radius: 8px; padding: 12px; margin-bottom: 12px; background: #fff;'>
194
- <div style='display:flex; align-items:center; gap:8px;'>
195
- <span style='font-size:1.5em;'>{p['avatar']}</span>
196
- <div>
197
- <b>{p['user']}</b> <span style='color:gray; font-size:0.8em;'>• {p['location']}</span>
198
- </div>
199
- </div>
200
- <h4 style='margin:8px 0 4px 0; color:#2c3e50;'>{p['title']}</h4>
201
- <p style='margin:0 0 8px 0;'>{p['content']}</p>
202
- <div style='font-size:0.85em; color:#7f8c8d;'>
203
- ❤️ {p['likes']} Beğeni | 💬 {len(p['comments'])} Yorum
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  </div>
205
- </div>
206
- """
207
- html += "</div>"
208
- return html
209
-
210
- def submit_fossil_report(finder, species_type, lat, lng, city, photo):
211
- report_entry = {
212
- "finder": finder,
213
- "type": species_type,
214
- "coords": f"{lat}, {lng}",
215
- "city": city,
216
- "status": "İncelemede (ENHA Müzesi)"
217
- }
218
- fossil_reports.append(report_entry)
219
- return f"✅ İhbar Başarıyla Alındı! Kayıt koda işlendi. Teşekkürler {finder}."
220
-
221
- # ---------------------------------------------------------------------------
222
- # GRADIO INTERFACE
223
- # ---------------------------------------------------------------------------
224
-
225
- with gr.Blocks(title="ENHA Jeoloji & TKGM Parsel Su Arama Platformu") as demo:
226
- gr.HTML(
227
- """
228
- <div style="text-align:center; padding:15px; background:linear-gradient(135deg, #1f4068, #162447); color:white; border-radius:8px;">
229
- <h2>🏛️ Türkiye Jeoloji, TKGM Parsel & Yeraltı Suyu Analiz Platformu</h2>
230
- <p>Eurasia Natural History Association (ENHA) Portal</p>
231
- </div>
232
- """
233
- )
234
-
235
- with gr.Tabs():
236
- # TAB 1: HARİTA
237
- with gr.Tab("🗺️ İnteraktif Harita & TKGM Parsel Katmanı"):
238
- gr.Markdown("**TKGM Kadastro Parsel** katmanını ve **Jeolojik Formasyonları** sağ üst katman yöneticisinden aktifleştirebilirsiniz.")
239
- map_view = gr.HTML(value=build_map())
240
-
241
- # TAB 2: YERALTI SUYU & KOLON KESİTİ
242
- with gr.Tab("💧 Parsel Yeraltı Suyu & Kolon Kesit Analizi"):
243
- gr.Markdown("### 🌾 Müşteri/Arazi Parseli Yeraltı Suyu Arama Analizi")
244
- with gr.Row():
245
- with gr.Column(scale=1):
246
- in_lat = gr.Number(label="Enlem (Latitude)", value=38.42)
247
- in_lng = gr.Number(label="Boylam (Longitude)", value=32.15)
248
- in_ada = gr.Textbox(label="Ada No", value="102")
249
- in_parsel = gr.Textbox(label="Parsel No", value="14")
250
- btn_analyze = gr.Button("📊 Kolon Kesiti & Su Potansiyeli Üret", variant="primary")
251
-
252
- with gr.Column(scale=2):
253
- out_plot = gr.Plot(label="Sondaj Litoloji & Akifer Kolon Kesiti")
254
- out_report = gr.Markdown()
255
-
256
- btn_analyze.click(
257
- fn=generate_hydro_section,
258
- inputs=[in_lat, in_lng, in_ada, in_parsel],
259
- outputs=[out_plot, out_report]
260
  )
261
-
262
- # TAB 3: SOSYAL AĞ & TOPLULUK
263
- with gr.Tab("💬 ENHA Sosyal Jeoloji Ağ"):
264
- with gr.Row():
265
- with gr.Column(scale=1):
266
- gr.Markdown("### ✏️ Gönderi Paylaş")
267
- u_name = gr.Textbox(label="Adınız / Unvanınız")
268
- u_title = gr.Textbox(label="Başlık / Konu")
269
- u_loc = gr.Textbox(label="Konum / Bölge")
270
- u_content = gr.Textbox(label="Açıklama / Tartışma Metni", lines=3)
271
- btn_post = gr.Button("Paylaş", variant="primary")
272
-
273
- with gr.Column(scale=2):
274
- gr.Markdown("### 📰 Jeoloji & Arazi Akışı")
275
- feed_output = gr.HTML(value=render_social_feed())
276
-
277
- btn_post.click(
278
- fn=create_post,
279
- inputs=[u_name, u_title, u_content, u_loc],
280
- outputs=feed_output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  )
282
-
283
- # TAB 4: FOSİL İHBAR SİSTEMİ
284
- with gr.Tab("🦴 Fosil Buluntu İhbarı"):
285
- gr.Markdown("### 📢 Arazi Arama & Kazı Fosil İhbar Formu")
286
- with gr.Row():
287
- f_name = gr.Textbox(label="Bulunan Kişi / Kurum")
288
- f_type = gr.Dropdown(choices=["Omurgalı / Kemik", "Trilobit / Ammonit", "Bitki / Kömür Yaprağı", "Mikrofosil / Denizel"], label="Fosil Türü")
289
- f_lat = gr.Number(label="Enlem", value=39.5)
290
- f_lng = gr.Number(label="Boylam", value=32.8)
291
- f_city = gr.Textbox(label="İl / İlçe")
292
- f_img = gr.Image(label="Fosil Fotoğrafı Yükle", type="filepath")
293
-
294
- btn_fossil = gr.Button("İhbarı Gönder", variant="primary")
295
- fossil_out = gr.Textbox(label="Durum", interactive=False)
296
-
297
- btn_fossil.click(
298
- fn=submit_fossil_report,
299
- inputs=[f_name, f_type, f_lat, f_lng, f_city, f_img],
300
- outputs=fossil_out
 
301
  )
302
-
303
- if __name__ == "__main__":
304
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
 
 
 
 
2
  import pandas as pd
3
+ import numpy as np
4
+ import folium
5
+ from folium.plugins import HeatMap, Fullscreen, MeasureControl, MiniMap
6
+ from streamlit_folium import st_folium
7
  import json
8
+ import math
9
+ import io
10
+ import plotly.express as px
11
+ import plotly.graph_objects as go
12
+
13
+ # ==========================================
14
+ # 1. PAGE CONFIGURATION & CUSTOM STYLING
15
+ # ==========================================
16
+ st.set_page_config(
17
+ page_title="TKGM Parsel & PaleoDB Fosil Analiz Platformu",
18
+ page_icon="🌍",
19
+ layout="wide",
20
+ initial_sidebar_state="expanded"
21
+ )
22
+
23
+ # Custom CSS for UI Enhancement
24
+ st.markdown("""
25
+ <style>
26
+ .main-header {
27
+ font-size: 2.2rem;
28
+ font-weight: 700;
29
+ color: #1E3A8A;
30
+ text-align: center;
31
+ margin-bottom: 0.5rem;
32
  }
33
+ .sub-header {
34
+ font-size: 1.1rem;
35
+ color: #4B5563;
36
+ text-align: center;
37
+ margin-bottom: 2rem;
38
+ }
39
+ .metric-card {
40
+ background-color: #F3F4F6;
41
+ border-radius: 10px;
42
+ padding: 15px;
43
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
44
+ text-align: center;
45
+ border-left: 5px solid #2563EB;
46
+ }
47
+ .metric-title {
48
+ font-size: 0.9rem;
49
+ color: #6B7280;
50
+ font-weight: 600;
51
+ text-transform: uppercase;
52
+ }
53
+ .metric-value {
54
+ font-size: 1.8rem;
55
+ font-weight: 700;
56
+ color: #1F2937;
57
+ }
58
+ .stTabs [data-baseweb="tab-list"] {
59
+ gap: 8px;
60
+ }
61
+ .stTabs [data-baseweb="tab"] {
62
+ height: 50px;
63
+ white-space: pre-wrap;
64
+ border-radius: 8px 8px 0px 0px;
65
+ padding-top: 10px;
66
+ padding-bottom: 10px;
67
+ }
68
+ </style>
69
+ """, unsafe_allow_html=True)
70
+
71
+ # ==========================================
72
+ # 2. HELPER SPATIAL & MATHEMATICAL FUNCTIONS
73
+ # ==========================================
74
+ def calculate_haversine(lat1, lon1, lat2, lon2):
75
+ """Calculates distance between two geographical points in km."""
76
+ R = 6371.0
77
+ dlat = math.radians(lat2 - lat1)
78
+ dlon = math.radians(lon2 - lon1)
79
+ a = (math.sin(dlat / 2) ** 2 +
80
+ math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
81
+ math.sin(dlon / 2) ** 2)
82
+ c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
83
+ return R * c
84
+
85
+ def extract_geojson_centroids(geojson_data):
86
+ """Extracts features, properties, and centroids from TKGM GeoJSON."""
87
+ features_summary = []
88
+ if "features" not in geojson_data:
89
+ return features_summary
90
+
91
+ for idx, feature in enumerate(geojson_data["features"]):
92
+ geometry = feature.get("geometry", {})
93
+ properties = feature.get("properties", {})
94
+ geom_type = geometry.get("type", "")
95
+ coords = geometry.get("coordinates", [])
96
+
97
+ lat, lng = None, None
98
+
99
+ if geom_type == "Point":
100
+ lng, lat = coords[0], coords[1]
101
+ elif geom_type == "Polygon":
102
+ poly_coords = coords[0]
103
+ lats = [pt[1] for pt in poly_coords]
104
+ lngs = [pt[0] for pt in poly_coords]
105
+ lat = sum(lats) / len(lats)
106
+ lng = sum(lngs) / len(lngs)
107
+ elif geom_type == "MultiPolygon":
108
+ all_lats, all_lngs = [], []
109
+ for poly in coords:
110
+ for pt in poly[0]:
111
+ all_lngs.append(pt[0])
112
+ all_lats.append(pt[1])
113
+ if all_lats:
114
+ lat = sum(all_lats) / len(all_lats)
115
+ lng = sum(all_lngs) / len(all_lngs)
116
+
117
+ features_summary.append({
118
+ "id": idx + 1,
119
+ "mahalle": properties.get("mahalleAd", properties.get("MAHALLE", "Bilinmiyor")),
120
+ "ada": properties.get("adaNo", properties.get("ADA", "-")),
121
+ "parsel": properties.get("parselNo", properties.get("PARSEL", "-")),
122
+ "nitelik": properties.get("nitelik", properties.get("NITELIK", "Belirtilmemiş")),
123
+ "alan_m2": properties.get("alan", properties.get("ALAN", 0)),
124
+ "lat": lat,
125
+ "lng": lng,
126
+ "raw_properties": properties
127
+ })
128
+ return features_summary
129
+
130
+ # ==========================================
131
+ # 3. DATA FETCHING & CACHING MODULE
132
+ # ==========================================
133
+ @st.cache_data(ttl=3600)
134
+ def fetch_paleodb_data(country, taxon, limit, era):
135
+ """Fetches paleontological records from PaleoDB REST API."""
136
+ base_url = "https://paleobiodb.org/data1.2/occs/list.csv"
137
+ params = [
138
+ f"country={country}",
139
+ "show=coords,phylo,loc,attr,time",
140
+ f"limit={limit}"
141
  ]
142
+ if taxon:
143
+ params.append(f"taxon_name={taxon}")
144
+ if era:
145
+ params.append(f"interval={era}")
146
 
147
+ query_url = base_url + "?" + "&".join(params)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
+ try:
150
+ df = pd.read_csv(query_url)
151
+ df = df.dropna(subset=["lat", "lng"])
152
+ return df, None
153
+ except Exception as e:
154
+ return pd.DataFrame(), str(e)
155
+
156
+ # ==========================================
157
+ # 4. SIDEBAR CONFIGURATION & USER INPUTS
158
+ # ==========================================
159
+ st.sidebar.image("https://img.icons8.com/color/96/dinosaur-skull.png", width=80)
160
+ st.sidebar.title("Kontrol Paneli")
161
+
162
+ st.sidebar.markdown("---")
163
+ st.sidebar.subheader("📌 1. TKGM Parsel Yükleme")
164
+ uploaded_parsel_file = st.sidebar.file_uploader(
165
+ "GeoJSON / JSON Dosyası Yükleyin:",
166
+ type=["geojson", "json"],
167
+ help="TKGM Portalı'ndan indirilen GeoJSON formatındaki parsel geometrisini sürükleyip bırakın."
168
+ )
169
+
170
+ st.sidebar.markdown("---")
171
+ st.sidebar.subheader("🦖 2. PaleoDB Fosil Sorgusu")
172
+
173
+ col_sb1, col_sb2 = st.sidebar.columns(2)
174
+ with col_sb1:
175
+ country_code = st.text_input("Ülke Kodu:", value="TUR")
176
+ with col_sb2:
177
+ record_limit = st.number_input("Max Kayıt:", min_value=50, max_value=5000, value=1000, step=100)
178
+
179
+ selected_taxon = st.sidebar.text_input(
180
+ "Takson / Canlı Grubu Filtresi:",
181
+ value="",
182
+ placeholder="Örn: Mammalia, Dinosauria, Mollusca"
183
+ )
184
+
185
+ selected_era = st.sidebar.selectbox(
186
+ "Jeolojik Zaman Dilimi:",
187
+ options=["Tümü", "Cenozoic", "Mesozoic", "Paleozoic", "Quaternary", "Neogene", "Paleogene", "Cretaceous", "Jurassic", "Triassic"],
188
+ index=0
189
+ )
190
+ if selected_era == "Tümü":
191
+ selected_era = ""
192
+
193
+ st.sidebar.markdown("---")
194
+ st.sidebar.subheader("🗺️ 3. Harita Katman Ayarları")
195
+ map_style = st.sidebar.selectbox(
196
+ "Altlık Harita Stili:",
197
+ options=["OpenStreetMap", "CartoDB positron", "CartoDB dark_matter", "Esri Satellite"],
198
+ index=0
199
+ )
200
+
201
+ show_heatmap = st.sidebar.checkbox("Fosil Yoğunluk Isı Haritası (Heatmap)", value=False)
202
+ show_parsel_buffer = st.sidebar.checkbox("Parsel Etki Alanı (Buffer Ring)", value=True)
203
+ buffer_radius_km = st.sidebar.slider("Buffer Yarıçapı (km):", min_value=1.0, max_value=50.0, value=10.0, step=1.0)
204
+
205
+ # ==========================================
206
+ # 5. DATA PROCESSING & INITIALIZATION
207
+ # ==========================================
208
+ df_fossils, fetch_error = fetch_paleodb_data(country_code, selected_taxon, record_limit, selected_era)
209
+
210
+ parsel_features = []
211
+ parsel_geojson_content = None
212
+
213
+ if uploaded_parsel_file is not None:
214
+ try:
215
+ parsel_geojson_content = json.load(uploaded_parsel_file)
216
+ parsel_features = extract_geojson_centroids(parsel_geojson_content)
217
+ st.sidebar.success(f"✓ {len(parsel_features)} adet parsel başarıyla işlendi.")
218
+ except Exception as e:
219
+ st.sidebar.error(f"GeoJSON Okuma Hatası: {e}")
220
+
221
+ # Main Header
222
+ st.markdown('<div class="main-header">TKGM Parsel ve PaleoDB Fosil Analiz Platformu</div>', unsafe_allow_html=True)
223
+ st.markdown('<div class="sub-header">Arazi parsel geometrileri ile paleobiyolojik buluntuların mekânsal çakıştırma ve yakınlık analizi</div>', unsafe_allow_html=True)
224
+
225
+ # Metric Summary Cards
226
+ col_m1, col_m2, col_m3, col_m4 = st.columns(4)
227
+
228
+ with col_m1:
229
+ st.markdown(f"""
230
+ <div class="metric-card">
231
+ <div class="metric-title">Toplam Fosil Buluntusu</div>
232
+ <div class="metric-value">{len(df_fossils)}</div>
233
+ </div>
234
+ """, unsafe_allow_html=True)
235
+
236
+ with col_m2:
237
+ st.markdown(f"""
238
+ <div class="metric-card">
239
+ <div class="metric-title">Yüklenen Parsel Sayısı</div>
240
+ <div class="metric-value">{len(parsel_features)}</div>
241
+ </div>
242
+ """, unsafe_allow_html=True)
243
+
244
+ with col_m3:
245
+ unique_taxa = df_fossils['accepted_name'].nunique() if not df_fossils.empty and 'accepted_name' in df_fossils.columns else 0
246
+ st.markdown(f"""
247
+ <div class="metric-card">
248
+ <div class="metric-title">Farklı Takson Türü</div>
249
+ <div class="metric-value">{unique_taxa}</div>
250
+ </div>
251
+ """, unsafe_allow_html=True)
252
+
253
+ with col_m4:
254
+ dominant_period = df_fossils['early_interval'].mode()[0] if not df_fossils.empty and 'early_interval' in df_fossils.columns and not df_fossils['early_interval'].mode().empty else "N/A"
255
+ st.markdown(f"""
256
+ <div class="metric-card">
257
+ <div class="metric-title">Baskın Dönem</div>
258
+ <div class="metric-value" style="font-size: 1.3rem;">{dominant_period}</div>
259
+ </div>
260
+ """, unsafe_allow_html=True)
261
+
262
+ st.write("")
263
+
264
+ # ==========================================
265
+ # 6. TABBED INTERFACE STRUCTURE
266
+ # ==========================================
267
+ tab_map, tab_analysis, tab_data, tab_docs = st.tabs([
268
+ "🗺️ İnteraktif Mekânsal Harita",
269
+ "📊 Yanal Analiz & Yakınlık Sorgusu",
270
+ "📁 Veri Tabloları & Dışa Aktar",
271
+ "📖 Kullanım & Teknik Rehber"
272
+ ])
273
+
274
+ # ------------------------------------------
275
+ # TAB 1: INTERACTIVE MAP
276
+ # ------------------------------------------
277
+ with tab_map:
278
+ initial_center = [39.0, 35.0]
279
+ initial_zoom = 6
280
+
281
+ if parsel_features and parsel_features[0]['lat'] is not None:
282
+ initial_center = [parsel_features[0]['lat'], parsel_features[0]['lng']]
283
+ initial_zoom = 12
284
+ elif not df_fossils.empty and 'lat' in df_fossils.columns:
285
+ initial_center = [df_fossils['lat'].mean(), df_fossils['lng'].mean()]
286
+
287
+ tiles_arg = "OpenStreetMap"
288
+ attr_arg = None
289
+ if map_style == "CartoDB positron":
290
+ tiles_arg = "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png"
291
+ attr_arg = "&copy; OpenStreetMap &copy; CARTO"
292
+ elif map_style == "CartoDB dark_matter":
293
+ tiles_arg = "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
294
+ attr_arg = "&copy; OpenStreetMap &copy; CARTO"
295
+ elif map_style == "Esri Satellite":
296
+ tiles_arg = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
297
+ attr_arg = "Tiles &copy; Esri"
298
+
299
+ main_map = folium.Map(location=initial_center, zoom_start=initial_zoom, tiles=tiles_arg, attr=attr_arg)
300
+
301
+ Fullscreen().add_to(main_map)
302
+ MeasureControl(position='topleft', primary_length_unit='kilometers').add_to(main_map)
303
+ MiniMap(toggle_display=True).add_to(main_map)
304
+
305
+ fg_fossils = folium.FeatureGroup(name="PaleoDB Fosil Buluntuları")
306
+ fg_parcels = folium.FeatureGroup(name="TKGM Parsel Geometrisi")
307
+ fg_buffers = folium.FeatureGroup(name="Buffer Etki Alanları")
308
+
309
+ if not df_fossils.empty:
310
+ f_lats = df_fossils['lat'].tolist()
311
+ f_lngs = df_fossils['lng'].tolist()
312
+
313
+ if show_heatmap:
314
+ heat_data = [[lat, lng] for lat, lng in zip(f_lats, f_lngs)]
315
+ HeatMap(heat_data, radius=15, blur=10, max_zoom=10).add_to(main_map)
316
+
317
+ for _, row in df_fossils.iterrows():
318
+ taxon_name_disp = row.get('accepted_name', 'Bilinmiyor')
319
+ interval_disp = row.get('early_interval', 'Bilinmiyor')
320
+ class_disp = row.get('class', 'Belirtilmemiş')
321
+ phylum_disp = row.get('phylum', 'Belirtilmemiş')
322
+ loc_disp = row.get('state', row.get('county', 'Konum bilgisi yok'))
323
+
324
+ popup_html = f"""
325
+ <div style="font-family: Arial, sans-serif; width: 220px;">
326
+ <h4 style="color: #990000; margin-bottom: 5px;">🦖 {taxon_name_disp}</h4>
327
+ <hr style="margin: 5px 0;">
328
+ <b>Jeolojik Dönem:</b> {interval_disp}<br>
329
+ <b>Şube (Phylum):</b> {phylum_disp}<br>
330
+ <b>Sınıf (Class):</b> {class_disp}<br>
331
+ <b>Lokasyon:</b> {loc_disp}<br>
332
+ <b>Enlem/Boylam:</b> {row['lat']:.4f}, {row['lng']:.4f}
333
  </div>
334
+ """
335
+
336
+ folium.CircleMarker(
337
+ location=[row['lat'], row['lng']],
338
+ radius=6,
339
+ color="#8B0000",
340
+ fill=True,
341
+ fill_color="#FF4500",
342
+ fill_opacity=0.8,
343
+ popup=folium.Popup(popup_html, max_width=250),
344
+ tooltip=f"Fosil: {taxon_name_disp} ({interval_disp})"
345
+ ).add_to(fg_fossils)
346
+
347
+ if parsel_geojson_content is not None:
348
+ folium.GeoJson(
349
+ parsel_geojson_content,
350
+ name="TKGM Parsel Sınırları",
351
+ style_function=lambda x: {
352
+ 'fillColor': '#0080FF',
353
+ 'color': '#003366',
354
+ 'weight': 2.5,
355
+ 'fillOpacity': 0.4,
356
+ },
357
+ highlight_function=lambda x: {
358
+ 'fillColor': '#FFFF00',
359
+ 'color': '#FF0000',
360
+ 'weight': 3,
361
+ 'fillOpacity': 0.7,
362
+ },
363
+ tooltip=folium.GeoJsonTooltip(
364
+ fields=list(parsel_geojson_content['features'][0]['properties'].keys()) if 'features' in parsel_geojson_content and len(parsel_geojson_content['features']) > 0 else [],
365
+ aliases=[f"{k}:" for k in (parsel_geojson_content['features'][0]['properties'].keys() if 'features' in parsel_geojson_content and len(parsel_geojson_content['features']) > 0 else [])],
366
+ localize=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  )
368
+ ).add_to(fg_parcels)
369
+
370
+ if show_parsel_buffer:
371
+ for p in parsel_features:
372
+ if p['lat'] is not None and p['lng'] is not None:
373
+ folium.Circle(
374
+ location=[p['lat'], p['lng']],
375
+ radius=buffer_radius_km * 1000,
376
+ color="#2563EB",
377
+ weight=1.5,
378
+ fill=True,
379
+ fill_color="#3B82F6",
380
+ fill_opacity=0.1,
381
+ dash_array="5, 10",
382
+ popup=f"Parsel Buffer ({buffer_radius_km} km)"
383
+ ).add_to(fg_buffers)
384
+
385
+ fg_fossils.add_to(main_map)
386
+ fg_parcels.add_to(main_map)
387
+ fg_buffers.add_to(main_map)
388
+ folium.LayerControl(collapsed=False).add_to(main_map)
389
+
390
+ st_folium(main_map, width="100%", height=650)
391
+
392
+ # ------------------------------------------
393
+ # TAB 2: SPATIAL ANALYSIS & PROXIMITY ENGINE
394
+ # ------------------------------------------
395
+ with tab_analysis:
396
+ st.subheader("🔍 Yakınlık ve Çakıştırma Analiz Motoru")
397
+
398
+ if not parsel_features:
399
+ st.info("💡 Yakınlık analizi yapabilmek için lütfen sol menüden bir TKGM GeoJSON parsel dosyası yükleyin.")
400
+ elif df_fossils.empty:
401
+ st.warning("⚠️ Yakınlık analizi için PaleoDB fosil verisi bulunamadı.")
402
+ else:
403
+ st.write(f"Yüklenen **{len(parsel_features)}** adet parsel ile **{len(df_fossils)}** adet fosil buluntusu arasındaki mesafeler hesaplanıyor...")
404
+
405
+ proximity_results = []
406
+
407
+ for p in parsel_features:
408
+ p_lat, p_lng = p['lat'], p['lng']
409
+ if p_lat is None or p_lng is None:
410
+ continue
411
+
412
+ for _, f in df_fossils.iterrows():
413
+ f_lat, f_lng = f['lat'], f['lng']
414
+ dist_km = calculate_haversine(p_lat, p_lng, f_lat, f_lng)
415
+
416
+ if dist_km <= buffer_radius_km:
417
+ proximity_results.append({
418
+ "Parsel Ada/Parsel": f"{p['ada']}/{p['parsel']}",
419
+ "Parsel Mahalle": p['mahalle'],
420
+ "Fosil Takson": f.get('accepted_name', 'Bilinmiyor'),
421
+ "Jeolojik Dönem": f.get('early_interval', 'Bilinmiyor'),
422
+ "Mesafe (km)": round(dist_km, 2),
423
+ "Fosil Enlem": f_lat,
424
+ "Fosil Boylam": f_lng,
425
+ "Parsel Enlem": round(p_lat, 5),
426
+ "Parsel Boylam": round(p_lng, 5)
427
+ })
428
+
429
+ df_prox = pd.DataFrame(proximity_results)
430
+
431
+ if not df_prox.empty:
432
+ st.success(f"🎯 Belirlenen {buffer_radius_km} km yarıçaplı etki alanı içinde **{len(df_prox)}** adet eşleşme bulundu!")
433
+ st.dataframe(df_prox.sort_values(by="Mesafe (km)"), use_container_width=True)
434
+
435
+ fig_dist = px.histogram(
436
+ df_prox,
437
+ x="Mesafe (km)",
438
+ nbins=20,
439
+ title="Buffer Alanı İçindeki Fosil Mesafeleri Dağılımı",
440
+ color_discrete_sequence=['#2563EB']
441
  )
442
+ st.plotly_chart(fig_dist, use_container_width=True)
443
+ else:
444
+ st.warning(f"Seçilen {buffer_radius_km} km yarıçapında parsel çevresinde fosil kaydı bulunamadı. Yarıçapı artırmayı deneyin.")
445
+
446
+ st.markdown("---")
447
+ st.subheader("📈 PaleoBiyolojik Taksonomi & İstatistik Grafikleri")
448
+
449
+ col_chart1, col_chart2 = st.columns(2)
450
+
451
+ with col_chart1:
452
+ if not df_fossils.empty and 'early_interval' in df_fossils.columns:
453
+ period_counts = df_fossils['early_interval'].value_counts().head(10).reset_index()
454
+ period_counts.columns = ['Dönem', 'Adet']
455
+ fig_period = px.pie(
456
+ period_counts,
457
+ names='Dönem',
458
+ values='Adet',
459
+ title='En Çok Veri Bulunan 10 Jeolojik Dönem',
460
+ hole=0.4,
461
+ color_discrete_sequence=px.colors.sequential.RdBu
462
  )
463
+ st.plotly_chart(fig_period, use_container_width=True)
464
+
465
+ with col_chart2:
466
+ if not df_fossils.empty and 'phylum' in df_fossils.columns:
467
+ phylum_counts = df_fossils['phylum'].value_counts().head(10).reset_index()
468
+ phylum_counts.columns = ['Şube (Phylum)', 'Adet']
469
+ fig_phylum = px.bar(
470
+ phylum_counts,
471
+ x='Adet',
472
+ y='Şube (Phylum)',
473
+ orientation='h',
474
+ title='Şubelere (Phylum) Göre Buluntu Dağılımı',
475
+ color='Adet',
476
+ color_continuous_scale='Viridis'
477
+ )
478
+ st.plotly_chart(fig_phylum, use_container_width=True)
479
+
480
+ # ------------------------------------------
481
+ # TAB 3: DATA TABLES & EXPORT CENTER
482
+ # ------------------------------------------
483
+ with tab_data:
484
+ st.subheader("📥 Veri İnceleme ve Dışa Aktarım Merkezi")
485
+
486
+ col_exp1, col_exp2 = st.columns(2)
487
+
488
+ with col_exp1:
489
+ st.markdown("##### 🦖 PaleoDB Fosil Kayıtları")
490
+ if not df_fossils.empty:
491
+ st.dataframe(df_fossils, height=350)
492
+ csv_fossils = df_fossils.to_csv(index=False).encode('utf-8')
493
+ st.download_button(
494
+ label="📄 PaleoDB Verisini CSV İndir",
495
+ data=csv_fossils,
496
+ file_name="paleodb_fosil_verileri.csv",
497
+ mime="text/csv"
498
+ )
499
+ else:
500
+ st.info("İndirilecek fosil verisi yok.")
501
+
502
+ with col_exp2:
503
+ st.markdown("##### 📐 TKGM Parsel Verileri")
504
+ if parsel_features:
505
+ df_parsel_summary = pd.DataFrame(parsel_features).drop(columns=['raw_properties'])
506
+ st.dataframe(df_parsel_summary, height=350)
507
+ csv_parsels = df_parsel_summary.to_csv(index=False).encode('utf-8')
508
+ st.download_button(
509
+ label="📄 Parsel Özeti CSV İndir",
510
+ data=csv_parsels,
511
+ file_name="tkgm_parsel_ozeti.csv",
512
+ mime="text/csv"
513
+ )
514
+ else:
515
+ st.info("İndirilecek parsel verisi yok.")
516
+
517
+ # ------------------------------------------
518
+ # TAB 4: DOCUMENTATION & GUIDE
519
+ # ------------------------------------------
520
+ with tab_docs:
521
+ st.subheader("📖 Kullanım ve Entegrasyon Rehberi")
522
+ st.markdown("""
523
+ ### Sistem Mimari ve Veri Akışı
524
+
525
+ 1. **TKGM Parsel Sorgu Verileri:**
526
+ - **TKGM Parsel Sorgu** web uygulaması (`parselsorgu.tkgm.gov.tr`) güvenlik katmanları (CAPTCHA, Cloudflare) sebebiyle doğrudan dış REST API erişimine kapalıdır.
527
+ - Kullanıcılar ilgili parseli haritadan aratıp **GeoJSON** veya **KML** formatında bilgisayarlarına indirdikten sonra bu platforma yükler.
528
+ - Platform GeoJSON geometrilerini otomatik olarak parse eder, centroid (ağırlık merkezi) noktalarını ve parsel metadatasını çıkarır.
529
+
530
+ 2. **PaleoDB (Paleobiology Database) Entegrasyonu:**
531
+ - PaleoDB açık veri servisleri REST API üzerinden dinamik olarak sorgulanır.
532
+ - Parametreler (Ülke, Takson, Jeolojik Zaman) anlık API isteğine dönüştürülür ve harita üzerinde coğrafi katman olarak görselleştirilir.
533
+
534
+ 3. **Spatial Proximity & Buffer Engine:**
535
+ - Haversine formülü kullanılarak parsel merkezleri ile fosil buluntu lokasyonları arasındaki küresel mesafeler hesaplanır.
536
+ - Belirlenen etki alanı (Buffer) dâhilindeki buluntular otomatik olarak raporlanır.
537
+ """)
538
+
539
+ # Footer
540
+ st.markdown("---")
541
+ st.markdown(
542
+ "<div style='text-align: center; color: #9CA3AF; font-size: 0.85rem;'>"
543
+ "TKGM & PaleoDB Bütünleşik Coğrafi Bilgi Sistemi Portalı"
544
+ "</div>",
545
+ unsafe_allow_html=True
546
+ )