Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304import gradio as grimport foliumfrom branca.element import Elementimport matplotlib.pyplot as pltimport matplotlib.patches as patchesimport pandas as pdimport iofrom PIL import Imageimport jsonimport requests# ---------------------------------------------------------------------------# DATA STORES & DATABASE SIMULATION (In-Memory for Hugging Face)# ---------------------------------------------------------------------------PERIOD_COLORS = {"Cambrian": "#7FA080", "Ordovician": "#00A88D", "Silurian": "#B3E1B6","Devonian": "#CB8C37", "Carboniferous": "#67A5A5", "Permian": "#F04028","Triassic": "#812990", "Jurassic": "#3492C7", "Cretaceous": "#8CBA22","Paleogene": "#FD9A52", "Neogene": "#FFE619", "Quaternary": "#FFF2AE"}# Sosyal Ağ & İhbar Veritabanlarısocial_posts = [{"user": "Dr. Ahmet Yılmaz (Hidrojeolog)","avatar": "👨🔬","title": "Konya Ovası Yeraltı Su Seviyesi Düşüşü","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.","location": "Konya / Karapınar","likes": 14,"comments": ["Harika bir saha çalışması.", "Sondaj derinlikleri kaç metreye ulaştı?"]}]fossil_reports = []# ---------------------------------------------------------------------------# HYDROGEOLOGY & STRATIGRAPHIC COLUMN GENERATOR# ---------------------------------------------------------------------------def generate_hydro_section(lat, lng, ada="--", parsel="--"):"""Seçilen koordinat veya parsel için Yeraltı Suyu Arama (Hydrogeological)Sondaj Kolon Kesiti ve Akifer Potansiyel Raporu üretir."""# Macrostrat API'den gerçek bölgesel litoloji çekmetry:res = requests.get(f"https://macrostrat.org/api/v2/geologic_units/map?lat={lat}&lng={lng}", timeout=4)data = res.json()if data.get("success") and data["success"].get("data"):unit = data["success"]["data"][0]surface_lith = unit.get("lith", "Alüvyon / Dere Yatağı")age_info = unit.get("age", "Senozoik")else:surface_lith = "Alüvyon Örtü / Toprak"age_info = "Kuvaterner"except Exception:surface_lith = "Alüvyon Ve Detritik Çökel"age_info = "Kuvaterner"# Kolon Kesit Tabakaları (Müteahhit/Çiftçi/Sondör için Yeraltı Suyu Analizi)layers = [{"top": 0, "bottom": 8, "name": f"Bitkisel Toprak & {surface_lith}", "type": "permeable", "color": "#d4ac0d", "hatch": "..."},{"top": 8, "bottom": 35, "name": "Geçirimsiz Kil / Killi Marllar (Geçirimsiz Katman)", "type": "impermeable", "color": "#a04000", "hatch": "///"},{"top": 35, "bottom": 95, "name": "Kırıklı/Kaviteli Kireçtaşı (Ana Akifer - Yeraltı Suyu Haznesi)", "type": "aquifer", "color": "#2e4053", "hatch": "OO"},{"top": 95, "bottom": 130, "name": "Taban Kayacı (Marn / Şist / Kristalen Temel)", "type": "bedrock", "color": "#7d6608", "hatch": "xx"}]# Matplotlib Kolon Kesit Çizimifig, ax = plt.subplots(figsize=(5, 8))ax.set_ylim(135, 0) # Derinlik aşağı doğru artarax.set_xlim(0, 10)for l in layers:height = l["bottom"] - l["top"]rect = patches.Rectangle((1, l["top"]), 8, height, linewidth=1.5, edgecolor='black',facecolor=l["color"], alpha=0.6, hatch=l["hatch"])ax.add_patch(rect)# Etiketlerax.text(5, l["top"] + height/2, f"{l['name']}\n({l['top']}-{l['bottom']}m)",ha='center', va='center', fontsize=9, fontweight='bold', color='black',bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="gray", lw=0.5, alpha=0.8))# Yeraltı Su Seviyesi Mavi Çizgisi (Statik Su Seviyesi)water_table_depth = 28.0ax.axhline(y=water_table_depth, color='blue', linestyle='--', linewidth=2.5, label=f'Statik Su Seviyesi (~{water_table_depth}m)')ax.set_ylabel("Derinlik (Metre - m)", fontsize=11, fontweight='bold')ax.set_title(f"Sondaj Kolon Kesiti & Akifer Analizi\n[Koordinat: {lat:.4f}, {lng:.4f} | Ada: {ada} / Parsel: {parsel}]", fontsize=10, fontweight='bold')ax.set_xticks([])ax.legend(loc='lower left')plt.tight_layout()# Rapor Metnireport = f"""### 💧 Yeraltı Suyu & Hidrojeoloji Arazi Değerlendirmesi* **Lokasyon / Parsel:** Enlem {lat:.4f}, Boylam {lng:.4f} (Ada: {ada}, Parsel: {parsel})* **Yüzey Jeolojisi / Formasyon:** {surface_lith} ({age_info})* **Tahmini Statik Su Seviyesi:** **{water_table_depth} Metre*** **Önerilen Sondaj Derinliği:** **80 - 110 Metre*** **Akifer Potansiyeli:** **YÜKSEK (Kireçtaşı Karstik Hazne)*** **Tahmini Debi:** **4.5 - 8.0 L/s (Litre/Saniye)*** **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."""return fig, report# ---------------------------------------------------------------------------# MAP BUILDER WITH TKGM PARCELS & GEOLOGY# ---------------------------------------------------------------------------def build_map():m = folium.Map(location=[38.97, 35.30], zoom_start=6, tiles="CartoDB positron")# 1. TKGM KADASTRO PARSEL KATMANI (WMS)folium.WmsTileLayer(url='https://cbs.tkgm.gov.tr/megsis/wms',layers='parsel',fmt='image/png',transparent=True,name='TKGM Kadastro Parsel Katmanı',overlay=True,control=True,attr='Tapu ve Kadastro Genel Müdürlüğü (TKGM)').add_to(m)# 2. MACROSTRAT JEOLOJİ KATMANIfolium.TileLayer(tiles='https://tiles.macrostrat.org/carto/{z}/{x}/{y}.png',attr='Macrostrat Geology',name='Jeolojik Formasyonlar (Litoloji)',overlay=True,control=True,opacity=0.6).add_to(m)folium.TileLayer("Esri WorldImagery", name="Uydu Görüntüsü").add_to(m)folium.TileLayer("OpenStreetMap", name="Sokak Haritası").add_to(m)folium.LayerControl().add_to(m)# Tıklama ile Koordinat ve Litoloji Yakalayan JSclick_js = """<script>(function() {var checkMap = setInterval(function() {for (var key in window) {if (key.startsWith('map_') && window[key] instanceof L.Map) {var myMap = window[key];if (!myMap._geoListener) {myMap._geoListener = true;myMap.on('click', function(e) {var lat = e.latlng.lat.toFixed(5);var lng = e.latlng.lng.toFixed(5);var popup = L.popup().setLatLng(e.latlng).setContent("<b>Seçilen Nokta:</b><br>Enlem: " + lat + "<br>Boylam: " + lng +"<br><br><i>💧 Su Arama Sekmesine Bu Koordinat Otomatik Aktarılabilir.</i>").openOn(myMap);});}}}}, 500);})();</script>"""m.get_root().html.add_child(Element(click_js))return m._repr_html_()# ---------------------------------------------------------------------------# SOCIAL PLATFORM & FOSSIL REPORTING LOGIC# ---------------------------------------------------------------------------def create_post(user_name, title, content, location):new_p = {"user": user_name or "Anonim Jeolog","avatar": "👤","title": title,"content": content,"location": location or "Belirtilmedi","likes": 0,"comments": []}social_posts.insert(0, new_p)return render_social_feed()def render_social_feed():html = "<div style='max-height: 500px; overflow-y: auto;'>"for p in social_posts:html += f"""<div style='border: 1px solid #ddd; border-radius: 8px; padding: 12px; margin-bottom: 12px; background: #fff;'><div style='display:flex; align-items:center; gap:8px;'><span style='font-size:1.5em;'>{p['avatar']}</span><div><b>{p['user']}</b> <span style='color:gray; font-size:0.8em;'>• {p['location']}</span></div></div><h4 style='margin:8px 0 4px 0; color:#2c3e50;'>{p['title']}</h4><p style='margin:0 0 8px 0;'>{p['content']}</p><div style='font-size:0.85em; color:#7f8c8d;'>❤️ {p['likes']} Beğeni | 💬 {len(p['comments'])} Yorum</div></div>"""html += "</div>"return htmldef submit_fossil_report(finder, species_type, lat, lng, city, photo):report_entry = {"finder": finder,"type": species_type,"coords": f"{lat}, {lng}","city": city,"status": "İncelemede (ENHA Müzesi)"}fossil_reports.append(report_entry)return f"✅ İhbar Başarıyla Alındı! Kayıt koda işlendi. Teşekkürler {finder}."# ---------------------------------------------------------------------------# GRADIO INTERFACE# ---------------------------------------------------------------------------with gr.Blocks(title="ENHA Jeoloji & TKGM Parsel Su Arama Platformu") as demo:gr.HTML("""<div style="text-align:center; padding:15px; background:linear-gradient(135deg, #1f4068, #162447); color:white; border-radius:8px;"><h2>🏛️ Türkiye Jeoloji, TKGM Parsel & Yeraltı Suyu Analiz Platformu</h2><p>Eurasia Natural History Association (ENHA) Portal</p></div>""")with gr.Tabs():# TAB 1: HARİTAwith gr.Tab("🗺️ İnteraktif Harita & TKGM Parsel Katmanı"):gr.Markdown("**TKGM Kadastro Parsel** katmanını ve **Jeolojik Formasyonları** sağ üst katman yöneticisinden aktifleştirebilirsiniz.")map_view = gr.HTML(value=build_map())# TAB 2: YERALTI SUYU & KOLON KESİTİwith gr.Tab("💧 Parsel Yeraltı Suyu & Kolon Kesit Analizi"):gr.Markdown("### 🌾 Müşteri/Arazi Parseli Yeraltı Suyu Arama Analizi")with gr.Row():with gr.Column(scale=1):in_lat = gr.Number(label="Enlem (Latitude)", value=38.42)in_lng = gr.Number(label="Boylam (Longitude)", value=32.15)in_ada = gr.Textbox(label="Ada No", value="102")in_parsel = gr.Textbox(label="Parsel No", value="14")btn_analyze = gr.Button("📊 Kolon Kesiti & Su Potansiyeli Üret", variant="primary")with gr.Column(scale=2):out_plot = gr.Plot(label="Sondaj Litoloji & Akifer Kolon Kesiti")out_report = gr.Markdown()btn_analyze.click(fn=generate_hydro_section,inputs=[in_lat, in_lng, in_ada, in_parsel],outputs=[out_plot, out_report])# TAB 3: SOSYAL AĞ & TOPLULUKwith gr.Tab("💬 ENHA Sosyal Jeoloji Ağ"):with gr.Row():with gr.Column(scale=1):gr.Markdown("### ✏️ Gönderi Paylaş")u_name = gr.Textbox(label="Adınız / Unvanınız")u_title = gr.Textbox(label="Başlık / Konu")u_loc = gr.Textbox(label="Konum / Bölge")u_content = gr.Textbox(label="Açıklama / Tartışma Metni", lines=3)btn_post = gr.Button("Paylaş", variant="primary")with gr.Column(scale=2):gr.Markdown("### 📰 Jeoloji & Arazi Akışı")feed_output = gr.HTML(value=render_social_feed())btn_post.click(fn=create_post,inputs=[u_name, u_title, u_content, u_loc],outputs=feed_output)# TAB 4: FOSİL İHBAR SİSTEMİwith gr.Tab("🦴 Fosil Buluntu İhbarı"):gr.Markdown("### 📢 Arazi Arama & Kazı Fosil İhbar Formu")with gr.Row():f_name = gr.Textbox(label="Bulunan Kişi / Kurum")f_type = gr.Dropdown(choices=["Omurgalı / Kemik", "Trilobit / Ammonit", "Bitki / Kömür Yaprağı", "Mikrofosil / Denizel"], label="Fosil Türü")f_lat = gr.Number(label="Enlem", value=39.5)f_lng = gr.Number(label="Boylam", value=32.8)f_city = gr.Textbox(label="İl / İlçe")f_img = gr.Image(label="Fosil Fotoğrafı Yükle", type="filepath")btn_fossil = gr.Button("İhbarı Gönder", variant="primary")fossil_out = gr.Textbox(label="Durum", interactive=False)btn_fossil.click(fn=submit_fossil_report,inputs=[f_name, f_type, f_lat, f_lng, f_city, f_img],outputs=fossil_out)if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546import streamlit as stimport pandas as pdimport numpy as npimport foliumfrom folium.plugins import HeatMap, Fullscreen, MeasureControl, MiniMapfrom streamlit_folium import st_foliumimport jsonimport mathimport ioimport plotly.express as pximport plotly.graph_objects as go# ==========================================# 1. PAGE CONFIGURATION & CUSTOM STYLING# ==========================================st.set_page_config(page_title="TKGM Parsel & PaleoDB Fosil Analiz Platformu",page_icon="🌍",layout="wide",initial_sidebar_state="expanded")# Custom CSS for UI Enhancementst.markdown("""<style>.main-header {font-size: 2.2rem;font-weight: 700;color: #1E3A8A;text-align: center;margin-bottom: 0.5rem;}.sub-header {font-size: 1.1rem;color: #4B5563;text-align: center;margin-bottom: 2rem;}.metric-card {background-color: #F3F4F6;border-radius: 10px;padding: 15px;box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);text-align: center;border-left: 5px solid #2563EB;}.metric-title {font-size: 0.9rem;color: #6B7280;font-weight: 600;text-transform: uppercase;}.metric-value {font-size: 1.8rem;font-weight: 700;color: #1F2937;}.stTabs [data-baseweb="tab-list"] {gap: 8px;}.stTabs [data-baseweb="tab"] {height: 50px;white-space: pre-wrap;border-radius: 8px 8px 0px 0px;padding-top: 10px;padding-bottom: 10px;}</style>""", unsafe_allow_html=True)# ==========================================# 2. HELPER SPATIAL & MATHEMATICAL FUNCTIONS# ==========================================def calculate_haversine(lat1, lon1, lat2, lon2):"""Calculates distance between two geographical points in km."""R = 6371.0dlat = math.radians(lat2 - lat1)dlon = math.radians(lon2 - lon1)a = (math.sin(dlat / 2) ** 2 +math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *math.sin(dlon / 2) ** 2)c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))return R * cdef extract_geojson_centroids(geojson_data):"""Extracts features, properties, and centroids from TKGM GeoJSON."""features_summary = []if "features" not in geojson_data:return features_summaryfor idx, feature in enumerate(geojson_data["features"]):geometry = feature.get("geometry", {})properties = feature.get("properties", {})geom_type = geometry.get("type", "")coords = geometry.get("coordinates", [])lat, lng = None, Noneif geom_type == "Point":lng, lat = coords[0], coords[1]elif geom_type == "Polygon":poly_coords = coords[0]lats = [pt[1] for pt in poly_coords]lngs = [pt[0] for pt in poly_coords]lat = sum(lats) / len(lats)lng = sum(lngs) / len(lngs)elif geom_type == "MultiPolygon":all_lats, all_lngs = [], []for poly in coords:for pt in poly[0]:all_lngs.append(pt[0])all_lats.append(pt[1])if all_lats:lat = sum(all_lats) / len(all_lats)lng = sum(all_lngs) / len(all_lngs)features_summary.append({"id": idx + 1,"mahalle": properties.get("mahalleAd", properties.get("MAHALLE", "Bilinmiyor")),"ada": properties.get("adaNo", properties.get("ADA", "-")),"parsel": properties.get("parselNo", properties.get("PARSEL", "-")),"nitelik": properties.get("nitelik", properties.get("NITELIK", "Belirtilmemiş")),"alan_m2": properties.get("alan", properties.get("ALAN", 0)),"lat": lat,"lng": lng,"raw_properties": properties})return features_summary# ==========================================# 3. DATA FETCHING & CACHING MODULE# ==========================================@st.cache_data(ttl=3600)def fetch_paleodb_data(country, taxon, limit, era):"""Fetches paleontological records from PaleoDB REST API."""base_url = "https://paleobiodb.org/data1.2/occs/list.csv"params = [f"country={country}","show=coords,phylo,loc,attr,time",f"limit={limit}"]if taxon:params.append(f"taxon_name={taxon}")if era:params.append(f"interval={era}")query_url = base_url + "?" + "&".join(params)try:df = pd.read_csv(query_url)df = df.dropna(subset=["lat", "lng"])return df, Noneexcept Exception as e:return pd.DataFrame(), str(e)# ==========================================# 4. SIDEBAR CONFIGURATION & USER INPUTS# ==========================================st.sidebar.image("https://img.icons8.com/color/96/dinosaur-skull.png", width=80)st.sidebar.title("Kontrol Paneli")st.sidebar.markdown("---")st.sidebar.subheader("📌 1. TKGM Parsel Yükleme")uploaded_parsel_file = st.sidebar.file_uploader("GeoJSON / JSON Dosyası Yükleyin:",type=["geojson", "json"],help="TKGM Portalı'ndan indirilen GeoJSON formatındaki parsel geometrisini sürükleyip bırakın.")st.sidebar.markdown("---")st.sidebar.subheader("🦖 2. PaleoDB Fosil Sorgusu")col_sb1, col_sb2 = st.sidebar.columns(2)with col_sb1:country_code = st.text_input("Ülke Kodu:", value="TUR")with col_sb2:record_limit = st.number_input("Max Kayıt:", min_value=50, max_value=5000, value=1000, step=100)selected_taxon = st.sidebar.text_input("Takson / Canlı Grubu Filtresi:",value="",placeholder="Örn: Mammalia, Dinosauria, Mollusca")selected_era = st.sidebar.selectbox("Jeolojik Zaman Dilimi:",options=["Tümü", "Cenozoic", "Mesozoic", "Paleozoic", "Quaternary", "Neogene", "Paleogene", "Cretaceous", "Jurassic", "Triassic"],index=0)if selected_era == "Tümü":selected_era = ""st.sidebar.markdown("---")st.sidebar.subheader("🗺️ 3. Harita Katman Ayarları")map_style = st.sidebar.selectbox("Altlık Harita Stili:",options=["OpenStreetMap", "CartoDB positron", "CartoDB dark_matter", "Esri Satellite"],index=0)show_heatmap = st.sidebar.checkbox("Fosil Yoğunluk Isı Haritası (Heatmap)", value=False)show_parsel_buffer = st.sidebar.checkbox("Parsel Etki Alanı (Buffer Ring)", value=True)buffer_radius_km = st.sidebar.slider("Buffer Yarıçapı (km):", min_value=1.0, max_value=50.0, value=10.0, step=1.0)# ==========================================# 5. DATA PROCESSING & INITIALIZATION# ==========================================df_fossils, fetch_error = fetch_paleodb_data(country_code, selected_taxon, record_limit, selected_era)parsel_features = []parsel_geojson_content = Noneif uploaded_parsel_file is not None:try:parsel_geojson_content = json.load(uploaded_parsel_file)parsel_features = extract_geojson_centroids(parsel_geojson_content)st.sidebar.success(f"✓ {len(parsel_features)} adet parsel başarıyla işlendi.")except Exception as e:st.sidebar.error(f"GeoJSON Okuma Hatası: {e}")# Main Headerst.markdown('<div class="main-header">TKGM Parsel ve PaleoDB Fosil Analiz Platformu</div>', unsafe_allow_html=True)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)# Metric Summary Cardscol_m1, col_m2, col_m3, col_m4 = st.columns(4)with col_m1:st.markdown(f"""<div class="metric-card"><div class="metric-title">Toplam Fosil Buluntusu</div><div class="metric-value">{len(df_fossils)}</div></div>""", unsafe_allow_html=True)with col_m2:st.markdown(f"""<div class="metric-card"><div class="metric-title">Yüklenen Parsel Sayısı</div><div class="metric-value">{len(parsel_features)}</div></div>""", unsafe_allow_html=True)with col_m3:unique_taxa = df_fossils['accepted_name'].nunique() if not df_fossils.empty and 'accepted_name' in df_fossils.columns else 0st.markdown(f"""<div class="metric-card"><div class="metric-title">Farklı Takson Türü</div><div class="metric-value">{unique_taxa}</div></div>""", unsafe_allow_html=True)with col_m4: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"st.markdown(f"""<div class="metric-card"><div class="metric-title">Baskın Dönem</div><div class="metric-value" style="font-size: 1.3rem;">{dominant_period}</div></div>""", unsafe_allow_html=True)st.write("")# ==========================================# 6. TABBED INTERFACE STRUCTURE# ==========================================tab_map, tab_analysis, tab_data, tab_docs = st.tabs(["🗺️ İnteraktif Mekânsal Harita","📊 Yanal Analiz & Yakınlık Sorgusu","📁 Veri Tabloları & Dışa Aktar","📖 Kullanım & Teknik Rehber"])# ------------------------------------------# TAB 1: INTERACTIVE MAP# ------------------------------------------with tab_map:initial_center = [39.0, 35.0]initial_zoom = 6if parsel_features and parsel_features[0]['lat'] is not None:initial_center = [parsel_features[0]['lat'], parsel_features[0]['lng']]initial_zoom = 12elif not df_fossils.empty and 'lat' in df_fossils.columns:initial_center = [df_fossils['lat'].mean(), df_fossils['lng'].mean()]tiles_arg = "OpenStreetMap"attr_arg = Noneif map_style == "CartoDB positron":tiles_arg = "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png"attr_arg = "© OpenStreetMap © CARTO"elif map_style == "CartoDB dark_matter":tiles_arg = "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"attr_arg = "© OpenStreetMap © CARTO"elif map_style == "Esri Satellite":tiles_arg = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"attr_arg = "Tiles © Esri"main_map = folium.Map(location=initial_center, zoom_start=initial_zoom, tiles=tiles_arg, attr=attr_arg)Fullscreen().add_to(main_map)MeasureControl(position='topleft', primary_length_unit='kilometers').add_to(main_map)MiniMap(toggle_display=True).add_to(main_map)fg_fossils = folium.FeatureGroup(name="PaleoDB Fosil Buluntuları")fg_parcels = folium.FeatureGroup(name="TKGM Parsel Geometrisi")fg_buffers = folium.FeatureGroup(name="Buffer Etki Alanları")if not df_fossils.empty:f_lats = df_fossils['lat'].tolist()f_lngs = df_fossils['lng'].tolist()if show_heatmap:heat_data = [[lat, lng] for lat, lng in zip(f_lats, f_lngs)]HeatMap(heat_data, radius=15, blur=10, max_zoom=10).add_to(main_map)for _, row in df_fossils.iterrows():taxon_name_disp = row.get('accepted_name', 'Bilinmiyor')interval_disp = row.get('early_interval', 'Bilinmiyor')class_disp = row.get('class', 'Belirtilmemiş')phylum_disp = row.get('phylum', 'Belirtilmemiş')loc_disp = row.get('state', row.get('county', 'Konum bilgisi yok'))popup_html = f"""<div style="font-family: Arial, sans-serif; width: 220px;"><h4 style="color: #990000; margin-bottom: 5px;">🦖 {taxon_name_disp}</h4><hr style="margin: 5px 0;"><b>Jeolojik Dönem:</b> {interval_disp}<br><b>Şube (Phylum):</b> {phylum_disp}<br><b>Sınıf (Class):</b> {class_disp}<br><b>Lokasyon:</b> {loc_disp}<br><b>Enlem/Boylam:</b> {row['lat']:.4f}, {row['lng']:.4f}</div>"""folium.CircleMarker(location=[row['lat'], row['lng']],radius=6,color="#8B0000",fill=True,fill_color="#FF4500",fill_opacity=0.8,popup=folium.Popup(popup_html, max_width=250),tooltip=f"Fosil: {taxon_name_disp} ({interval_disp})").add_to(fg_fossils)if parsel_geojson_content is not None:folium.GeoJson(parsel_geojson_content,name="TKGM Parsel Sınırları",style_function=lambda x: {'fillColor': '#0080FF','color': '#003366','weight': 2.5,'fillOpacity': 0.4,},highlight_function=lambda x: {'fillColor': '#FFFF00','color': '#FF0000','weight': 3,'fillOpacity': 0.7,},tooltip=folium.GeoJsonTooltip(fields=list(parsel_geojson_content['features'][0]['properties'].keys()) if 'features' in parsel_geojson_content and len(parsel_geojson_content['features']) > 0 else [],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 [])],localize=True)).add_to(fg_parcels)if show_parsel_buffer:for p in parsel_features:if p['lat'] is not None and p['lng'] is not None:folium.Circle(location=[p['lat'], p['lng']],radius=buffer_radius_km * 1000,color="#2563EB",weight=1.5,fill=True,fill_color="#3B82F6",fill_opacity=0.1,dash_array="5, 10",popup=f"Parsel Buffer ({buffer_radius_km} km)").add_to(fg_buffers)fg_fossils.add_to(main_map)fg_parcels.add_to(main_map)fg_buffers.add_to(main_map)folium.LayerControl(collapsed=False).add_to(main_map)st_folium(main_map, width="100%", height=650)# ------------------------------------------# TAB 2: SPATIAL ANALYSIS & PROXIMITY ENGINE# ------------------------------------------with tab_analysis:st.subheader("🔍 Yakınlık ve Çakıştırma Analiz Motoru")if not parsel_features:st.info("💡 Yakınlık analizi yapabilmek için lütfen sol menüden bir TKGM GeoJSON parsel dosyası yükleyin.")elif df_fossils.empty:st.warning("⚠️ Yakınlık analizi için PaleoDB fosil verisi bulunamadı.")else:st.write(f"Yüklenen **{len(parsel_features)}** adet parsel ile **{len(df_fossils)}** adet fosil buluntusu arasındaki mesafeler hesaplanıyor...")proximity_results = []for p in parsel_features:p_lat, p_lng = p['lat'], p['lng']if p_lat is None or p_lng is None:continuefor _, f in df_fossils.iterrows():f_lat, f_lng = f['lat'], f['lng']dist_km = calculate_haversine(p_lat, p_lng, f_lat, f_lng)if dist_km <= buffer_radius_km:proximity_results.append({"Parsel Ada/Parsel": f"{p['ada']}/{p['parsel']}","Parsel Mahalle": p['mahalle'],"Fosil Takson": f.get('accepted_name', 'Bilinmiyor'),"Jeolojik Dönem": f.get('early_interval', 'Bilinmiyor'),"Mesafe (km)": round(dist_km, 2),"Fosil Enlem": f_lat,"Fosil Boylam": f_lng,"Parsel Enlem": round(p_lat, 5),"Parsel Boylam": round(p_lng, 5)})df_prox = pd.DataFrame(proximity_results)if not df_prox.empty:st.success(f"🎯 Belirlenen {buffer_radius_km} km yarıçaplı etki alanı içinde **{len(df_prox)}** adet eşleşme bulundu!")st.dataframe(df_prox.sort_values(by="Mesafe (km)"), use_container_width=True)fig_dist = px.histogram(df_prox,x="Mesafe (km)",nbins=20,title="Buffer Alanı İçindeki Fosil Mesafeleri Dağılımı",color_discrete_sequence=['#2563EB'])st.plotly_chart(fig_dist, use_container_width=True)else:st.warning(f"Seçilen {buffer_radius_km} km yarıçapında parsel çevresinde fosil kaydı bulunamadı. Yarıçapı artırmayı deneyin.")st.markdown("---")st.subheader("📈 PaleoBiyolojik Taksonomi & İstatistik Grafikleri")col_chart1, col_chart2 = st.columns(2)with col_chart1:if not df_fossils.empty and 'early_interval' in df_fossils.columns:period_counts = df_fossils['early_interval'].value_counts().head(10).reset_index()period_counts.columns = ['Dönem', 'Adet']fig_period = px.pie(period_counts,names='Dönem',values='Adet',title='En Çok Veri Bulunan 10 Jeolojik Dönem',hole=0.4,color_discrete_sequence=px.colors.sequential.RdBu)st.plotly_chart(fig_period, use_container_width=True)with col_chart2:if not df_fossils.empty and 'phylum' in df_fossils.columns:phylum_counts = df_fossils['phylum'].value_counts().head(10).reset_index()phylum_counts.columns = ['Şube (Phylum)', 'Adet']fig_phylum = px.bar(phylum_counts,x='Adet',y='Şube (Phylum)',orientation='h',title='Şubelere (Phylum) Göre Buluntu Dağılımı',color='Adet',color_continuous_scale='Viridis')st.plotly_chart(fig_phylum, use_container_width=True)# ------------------------------------------# TAB 3: DATA TABLES & EXPORT CENTER# ------------------------------------------with tab_data:st.subheader("📥 Veri İnceleme ve Dışa Aktarım Merkezi")col_exp1, col_exp2 = st.columns(2)with col_exp1:st.markdown("##### 🦖 PaleoDB Fosil Kayıtları")if not df_fossils.empty:st.dataframe(df_fossils, height=350)csv_fossils = df_fossils.to_csv(index=False).encode('utf-8')st.download_button(label="📄 PaleoDB Verisini CSV İndir",data=csv_fossils,file_name="paleodb_fosil_verileri.csv",mime="text/csv")else:st.info("İndirilecek fosil verisi yok.")with col_exp2:st.markdown("##### 📐 TKGM Parsel Verileri")if parsel_features:df_parsel_summary = pd.DataFrame(parsel_features).drop(columns=['raw_properties'])st.dataframe(df_parsel_summary, height=350)csv_parsels = df_parsel_summary.to_csv(index=False).encode('utf-8')st.download_button(label="📄 Parsel Özeti CSV İndir",data=csv_parsels,file_name="tkgm_parsel_ozeti.csv",mime="text/csv")else:st.info("İndirilecek parsel verisi yok.")# ------------------------------------------# TAB 4: DOCUMENTATION & GUIDE# ------------------------------------------with tab_docs:st.subheader("📖 Kullanım ve Entegrasyon Rehberi")st.markdown("""### Sistem Mimari ve Veri Akışı1. **TKGM Parsel Sorgu Verileri:**- **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.- Kullanıcılar ilgili parseli haritadan aratıp **GeoJSON** veya **KML** formatında bilgisayarlarına indirdikten sonra bu platforma yükler.- Platform GeoJSON geometrilerini otomatik olarak parse eder, centroid (ağırlık merkezi) noktalarını ve parsel metadatasını çıkarır.2. **PaleoDB (Paleobiology Database) Entegrasyonu:**- PaleoDB açık veri servisleri REST API üzerinden dinamik olarak sorgulanır.- 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.3. **Spatial Proximity & Buffer Engine:**- Haversine formülü kullanılarak parsel merkezleri ile fosil buluntu lokasyonları arasındaki küresel mesafeler hesaplanır.- Belirlenen etki alanı (Buffer) dâhilindeki buluntular otomatik olarak raporlanır.""")# Footerst.markdown("---")st.markdown("<div style='text-align: center; color: #9CA3AF; font-size: 0.85rem;'>""TKGM & PaleoDB Bütünleşik Coğrafi Bilgi Sistemi Portalı""</div>",unsafe_allow_html=True)
app.py+536-294