File size: 77,191 Bytes
82676b8 |
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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
وحدة الخريطة التفاعلية مع عرض التضاريس ثلاثي الأبعاد
تتيح هذه الوحدة عرض مواقع المشاريع على خريطة تفاعلية مع إمكانية رؤية التضاريس بشكل ثلاثي الأبعاد
"""
import os
import sys
import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
import folium
from folium.plugins import MarkerCluster, HeatMap, MeasureControl
from streamlit_folium import folium_static
import requests
import json
import random
from typing import List, Dict, Any, Tuple, Optional
import tempfile
import base64
from PIL import Image
from io import BytesIO
# إضافة مسار النظام للوصول للملفات المشتركة
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
# استيراد مكونات واجهة المستخدم
from utils.components.header import render_header
from utils.components.credits import render_credits
from utils.helpers import format_number, format_currency, styled_button
class InteractiveMap:
"""فئة الخريطة التفاعلية مع عرض التضاريس ثلاثي الأبعاد"""
def __init__(self):
"""تهيئة وحدة الخريطة التفاعلية"""
# تهيئة مجلدات حفظ البيانات
self.data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../data/maps"))
os.makedirs(self.data_dir, exist_ok=True)
# مفاتيح API لخدمات الخرائط
self.mapbox_token = os.environ.get("MAPBOX_TOKEN", "")
self.opentopodata_api = "https://api.opentopodata.org/v1/srtm30m"
# تهيئة حالة الجلسة
if 'project_locations' not in st.session_state:
st.session_state.project_locations = []
if 'selected_location' not in st.session_state:
st.session_state.selected_location = None
if 'terrain_data' not in st.session_state:
st.session_state.terrain_data = None
# بيانات اختبارية للمشاريع (سيتم استبدالها بالبيانات الفعلية من قاعدة البيانات)
self._initialize_sample_projects()
def render(self):
"""عرض واجهة وحدة الخريطة التفاعلية"""
# عرض الشعار والعنوان الرئيسي
render_header("خريطة مواقع المشاريع التفاعلية")
# تبويبات الوحدة
tabs = st.tabs([
"الخريطة التفاعلية",
"عرض التضاريس ثلاثي الأبعاد",
"تحليل المواقع",
"إدارة المواقع"
])
# تبويب الخريطة التفاعلية
with tabs[0]:
self._render_interactive_map()
# تبويب عرض التضاريس ثلاثي الأبعاد
with tabs[1]:
self._render_3d_terrain()
# تبويب تحليل المواقع
with tabs[2]:
self._render_location_analysis()
# تبويب إدارة المواقع
with tabs[3]:
self._render_location_management()
# عرض حقوق النشر
render_credits()
def _render_interactive_map(self):
"""عرض الخريطة التفاعلية"""
st.markdown("""
<div class='custom-box info-box'>
<h3>🗺️ الخريطة التفاعلية لمواقع المشاريع</h3>
<p>خريطة تفاعلية تعرض مواقع جميع المشاريع مع إمكانية التكبير والتصغير والتحرك.</p>
<p>يمكنك النقر على أي موقع للحصول على تفاصيل المشروع.</p>
</div>
""", unsafe_allow_html=True)
# مربع البحث
search_query = st.text_input("البحث عن موقع أو مشروع", key="map_search")
# أزرار تحكم للخريطة
col1, col2, col3, col4 = st.columns(4)
with col1:
map_style = st.selectbox(
"نمط الخريطة",
options=["OpenStreetMap", "Stamen Terrain", "Stamen Toner", "CartoDB Positron"],
key="map_style"
)
with col2:
cluster_markers = st.checkbox("تجميع المواقع القريبة", value=True, key="cluster_markers")
with col3:
show_heatmap = st.checkbox("عرض خريطة حرارية للمواقع", value=False, key="show_heatmap")
with col4:
show_measurements = st.checkbox("أدوات القياس", value=False, key="show_measurements")
# إنشاء الخريطة
if len(st.session_state.project_locations) > 0:
# بيانات النقاط على الخريطة
locations = []
# تصفية المشاريع حسب البحث
filtered_projects = st.session_state.project_locations
if search_query:
filtered_projects = [
p for p in filtered_projects
if search_query.lower() in p.get("name", "").lower() or
search_query.lower() in p.get("description", "").lower() or
search_query.lower() in p.get("city", "").lower()
]
# عرض عدد النتائج
if search_query:
st.markdown(f"عدد النتائج: {len(filtered_projects)}")
# تحضير البيانات للخريطة
heat_data = []
for project in filtered_projects:
locations.append({
"lat": project.get("latitude"),
"lon": project.get("longitude"),
"name": project.get("name"),
"description": project.get("description"),
"city": project.get("city"),
"status": project.get("status"),
"project_id": project.get("project_id")
})
heat_data.append([project.get("latitude"), project.get("longitude"), 1])
# تعيين نقطة المركز والتكبير
if filtered_projects:
center_lat = sum(p.get("latitude", 0) for p in filtered_projects) / len(filtered_projects)
center_lon = sum(p.get("longitude", 0) for p in filtered_projects) / len(filtered_projects)
zoom_level = 6 # مستوى التكبير الافتراضي
else:
# مركز المملكة العربية السعودية
center_lat = 24.7136
center_lon = 46.6753
zoom_level = 5
# تحديد الإسناد (attribution) بناءً على نمط الخريطة
attribution = None
if map_style == "OpenStreetMap":
attribution = '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
elif map_style.startswith("Stamen"):
attribution = 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.'
elif map_style == "CartoDB Positron":
attribution = '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://cartodb.com/attributions">CartoDB</a>'
# إنشاء الخريطة
m = folium.Map(
location=[center_lat, center_lon],
zoom_start=zoom_level,
tiles=map_style,
attr=attribution # إضافة سمة الإسناد
)
# إضافة أدوات القياس إذا تم اختيارها
if show_measurements:
MeasureControl(position='topright', primary_length_unit='kilometers').add_to(m)
# إضافة النقاط إلى الخريطة
if cluster_markers:
# إنشاء مجموعة تجميع
marker_cluster = MarkerCluster(name="تجميع المشاريع").add_to(m)
# إضافة النقاط إلى المجموعة
for location in locations:
# إنشاء النافذة المنبثقة
popup_html = f"""
<div style='direction: rtl; text-align: right;'>
<h4>{location['name']}</h4>
<p><strong>الوصف:</strong> {location['description']}</p>
<p><strong>المدينة:</strong> {location['city']}</p>
<p><strong>الحالة:</strong> {location['status']}</p>
<p><strong>الإحداثيات:</strong> {location['lat']:.6f}, {location['lon']:.6f}</p>
<button onclick="window.open('/project/{location['project_id']}', '_self')">عرض تفاصيل المشروع</button>
</div>
"""
# تحديد لون العلامة حسب حالة المشروع
icon_color = 'green'
if location['status'] == 'قيد التنفيذ':
icon_color = 'orange'
elif location['status'] == 'متوقف':
icon_color = 'red'
elif location['status'] == 'مكتمل':
icon_color = 'blue'
# إضافة العلامة
folium.Marker(
location=[location['lat'], location['lon']],
popup=folium.Popup(popup_html, max_width=300),
tooltip=location['name'],
icon=folium.Icon(color=icon_color, icon='info-sign')
).add_to(marker_cluster)
else:
# إضافة النقاط مباشرة إلى الخريطة
for location in locations:
# إنشاء النافذة المنبثقة
popup_html = f"""
<div style='direction: rtl; text-align: right;'>
<h4>{location['name']}</h4>
<p><strong>الوصف:</strong> {location['description']}</p>
<p><strong>المدينة:</strong> {location['city']}</p>
<p><strong>الحالة:</strong> {location['status']}</p>
<p><strong>الإحداثيات:</strong> {location['lat']:.6f}, {location['lon']:.6f}</p>
<button onclick="window.open('/project/{location['project_id']}', '_self')">عرض تفاصيل المشروع</button>
</div>
"""
# تحديد لون العلامة حسب حالة المشروع
icon_color = 'green'
if location['status'] == 'قيد التنفيذ':
icon_color = 'orange'
elif location['status'] == 'متوقف':
icon_color = 'red'
elif location['status'] == 'مكتمل':
icon_color = 'blue'
# إضافة العلامة
folium.Marker(
location=[location['lat'], location['lon']],
popup=folium.Popup(popup_html, max_width=300),
tooltip=location['name'],
icon=folium.Icon(color=icon_color, icon='info-sign')
).add_to(m)
# إضافة خريطة حرارية إذا تم اختيارها
if show_heatmap and heat_data:
HeatMap(heat_data, radius=15).add_to(m)
# إضافة طبقات متنوعة للخريطة
folium.TileLayer('OpenStreetMap').add_to(m)
folium.TileLayer('Stamen Terrain').add_to(m)
folium.TileLayer('Stamen Toner').add_to(m)
folium.TileLayer('CartoDB positron').add_to(m)
folium.TileLayer('CartoDB dark_matter').add_to(m)
# إضافة أدوات التحكم بالطبقات
folium.LayerControl().add_to(m)
# عرض الخريطة
st_map = folium_static(m, width=1000, height=600)
# التفاعل مع النقر على الخريطة (سيتم تنفيذه عندما يتم دعم التفاعل)
# حاليًا لا يوجد دعم مباشر للتفاعل مع الخريطة في Streamlit
# عرض بيانات المشاريع في جدول
st.markdown("### قائمة المشاريع على الخريطة")
projects_df = pd.DataFrame(filtered_projects)
# إعادة تسمية الأعمدة بالعربية
renamed_columns = {
"name": "اسم المشروع",
"city": "المدينة",
"status": "الحالة",
"description": "الوصف",
"project_id": "معرف المشروع",
"latitude": "خط العرض",
"longitude": "خط الطول"
}
# تحديد الأعمدة للعرض
display_columns = ["name", "city", "status", "project_id"]
# إنشاء جدول للعرض
display_df = projects_df[display_columns].rename(columns=renamed_columns)
# عرض الجدول
st.dataframe(display_df, width=1000, height=400)
# زر لاختيار مشروع لعرض التضاريس
selected_project_id = st.selectbox(
"اختر مشروعًا لعرض التضاريس ثلاثية الأبعاد",
options=projects_df["project_id"].tolist(),
format_func=lambda x: next((p["name"] for p in filtered_projects if p["project_id"] == x), x),
key="select_project_for_terrain"
)
# زر عرض التضاريس
if styled_button("عرض التضاريس", key="show_terrain_btn", type="primary", icon="🏔️"):
# العثور على المشروع المحدد
selected_project = next((p for p in filtered_projects if p["project_id"] == selected_project_id), None)
if selected_project:
# تخزين الموقع المحدد في حالة الجلسة
st.session_state.selected_location = {
"latitude": selected_project["latitude"],
"longitude": selected_project["longitude"],
"name": selected_project["name"],
"project_id": selected_project["project_id"]
}
# جلب بيانات التضاريس
try:
terrain_data = self._fetch_terrain_data(
selected_project["latitude"],
selected_project["longitude"]
)
# تخزين بيانات التضاريس في حالة الجلسة
st.session_state.terrain_data = terrain_data
# الانتقال إلى تبويب عرض التضاريس
st.experimental_rerun()
except Exception as e:
st.error(f"حدث خطأ أثناء جلب بيانات التضاريس: {str(e)}")
else:
st.warning("لا توجد مواقع مشاريع متاحة. يرجى إضافة مواقع من تبويب 'إدارة المواقع'.")
def _render_3d_terrain(self):
"""عرض التضاريس ثلاثي الأبعاد"""
st.markdown("""
<div class='custom-box info-box'>
<h3>🏔️ عرض التضاريس ثلاثي الأبعاد</h3>
<p>عرض تفاعلي ثلاثي الأبعاد لتضاريس موقع المشروع المحدد.</p>
<p>يمكنك تدوير وتكبير العرض للحصول على رؤية أفضل للموقع.</p>
</div>
""", unsafe_allow_html=True)
# التحقق من وجود موقع محدد
if st.session_state.selected_location is None:
st.info("يرجى اختيار موقع من تبويب 'الخريطة التفاعلية' أولاً.")
# بديل: السماح بإدخال الإحداثيات يدوياً
st.markdown("### إدخال الإحداثيات يدوياً")
col1, col2 = st.columns(2)
with col1:
manual_lat = st.number_input("خط العرض", value=24.7136, step=0.0001, format="%.6f", key="manual_lat")
with col2:
manual_lon = st.number_input("خط الطول", value=46.6753, step=0.0001, format="%.6f", key="manual_lon")
if styled_button("عرض التضاريس", key="manual_terrain_btn", type="primary", icon="🏔️"):
try:
# جلب بيانات التضاريس
terrain_data = self._fetch_terrain_data(manual_lat, manual_lon)
# تخزين بيانات التضاريس والموقع في حالة الجلسة
st.session_state.terrain_data = terrain_data
st.session_state.selected_location = {
"latitude": manual_lat,
"longitude": manual_lon,
"name": "موقع مخصص",
"project_id": "custom"
}
st.success("تم جلب بيانات التضاريس بنجاح!")
st.experimental_rerun()
except Exception as e:
st.error(f"حدث خطأ أثناء جلب بيانات التضاريس: {str(e)}")
return
# عرض معلومات الموقع المحدد
location = st.session_state.selected_location
st.markdown(f"### عرض تضاريس موقع: {location['name']}")
st.markdown(f"**الإحداثيات:** {location['latitude']:.6f}, {location['longitude']:.6f}")
# تجهيز بيانات التضاريس
if st.session_state.terrain_data is None:
# محاولة جلب بيانات التضاريس
try:
terrain_data = self._fetch_terrain_data(
location["latitude"],
location["longitude"]
)
# تخزين بيانات التضاريس في حالة الجلسة
st.session_state.terrain_data = terrain_data
except Exception as e:
st.error(f"حدث خطأ أثناء جلب بيانات التضاريس: {str(e)}")
return
# استخدام بيانات التضاريس المخزنة
terrain_data = st.session_state.terrain_data
# عرض نطاق التضاريس وإعدادات الارتفاع
col1, col2, col3 = st.columns(3)
with col1:
elevation_scale = st.slider(
"مقياس الارتفاع",
min_value=1,
max_value=50,
value=15,
key="elevation_scale"
)
with col2:
radius = st.slider(
"نطاق العرض (كم)",
min_value=1,
max_value=20,
value=5,
key="terrain_radius"
)
with col3:
color_scheme = st.selectbox(
"نظام الألوان",
options=["terrain", "elevation", "custom"],
key="color_scheme"
)
# إنشاء نموذج PyDeck للعرض ثلاثي الأبعاد
try:
# تحويل بيانات التضاريس إلى DataFrame
terrain_df = pd.DataFrame(terrain_data)
# تعيين حجم الخلية بناءً على النطاق
cell_size = radius * 100 # تحويل الكيلومترات إلى أمتار وتقسيمها
# إنشاء طبقة التضاريس
terrain_layer = pdk.Layer(
"TerrainLayer",
data=None,
elevation_decoder={
"elevations": "elevation",
"bounds": terrain_df["bounds"].iloc[0]
},
texture=None,
elevation_data=terrain_df["terrain"].iloc[0],
elevation_scale=elevation_scale,
color_map=self._get_color_map(color_scheme),
wireframe=True,
pickable=True
)
# إنشاء طبقة النقطة المركزية
point_layer = pdk.Layer(
"ScatterplotLayer",
data=[{
"position": [location["longitude"], location["latitude"]],
"name": location["name"]
}],
get_position="position",
get_radius=100,
get_fill_color=[255, 0, 0, 200],
pickable=True
)
# إنشاء عرض PyDeck
INITIAL_VIEW_STATE = pdk.ViewState(
longitude=location["longitude"],
latitude=location["latitude"],
zoom=12,
max_zoom=20,
pitch=45,
bearing=0
)
deck = pdk.Deck(
map_style="mapbox://styles/mapbox/satellite-v9",
initial_view_state=INITIAL_VIEW_STATE,
api_keys={"mapbox": self.mapbox_token} if self.mapbox_token else None,
layers=[terrain_layer, point_layer],
tooltip={
"html": "<b>{name}</b>",
"style": {
"backgroundColor": "steelblue",
"color": "white"
}
}
)
# عرض النموذج ثلاثي الأبعاد
st.pydeck_chart(deck)
# عرض تحليل التضاريس
if "elevation_stats" in terrain_df:
elevation_stats = terrain_df["elevation_stats"].iloc[0]
st.markdown("### تحليل التضاريس")
stats_col1, stats_col2, stats_col3, stats_col4 = st.columns(4)
with stats_col1:
st.metric("أدنى ارتفاع", f"{elevation_stats['min']:.1f} م")
with stats_col2:
st.metric("أعلى ارتفاع", f"{elevation_stats['max']:.1f} م")
with stats_col3:
st.metric("متوسط الارتفاع", f"{elevation_stats['mean']:.1f} م")
with stats_col4:
st.metric("فرق الارتفاع", f"{elevation_stats['range']:.1f} م")
# عرض رسم بياني للارتفاعات
if "elevation_profile" in terrain_df:
elevation_profile = terrain_df["elevation_profile"].iloc[0]
# إنشاء DataFrame للرسم البياني
profile_df = pd.DataFrame(elevation_profile)
# عرض الرسم البياني
st.markdown("### مقطع الارتفاع")
# استخدام Plotly Express
import plotly.express as px
fig = px.line(
profile_df,
x="distance",
y="elevation",
title="مقطع الارتفاع عبر الموقع",
labels={"distance": "المسافة (كم)", "elevation": "الارتفاع (م)"}
)
fig.update_layout(
title_font_size=20,
font_family="Arial",
font_size=14,
height=400
)
st.plotly_chart(fig, use_container_width=True)
# أزرار التحكم الإضافية
col1, col2 = st.columns(2)
with col1:
if styled_button("إعادة تحميل بيانات التضاريس", key="reload_terrain", type="primary", icon="🔄"):
# حذف بيانات التضاريس الحالية
st.session_state.terrain_data = None
st.experimental_rerun()
with col2:
if styled_button("العودة للخريطة التفاعلية", key="back_to_map", type="secondary", icon="🗺️"):
# إعادة تعيين الموقع المحدد
st.session_state.selected_location = None
st.session_state.terrain_data = None
st.experimental_rerun()
except Exception as e:
st.error(f"حدث خطأ أثناء عرض التضاريس ثلاثي الأبعاد: {str(e)}")
def _render_location_analysis(self):
"""عرض تحليل المواقع"""
st.markdown("""
<div class='custom-box info-box'>
<h3>📊 تحليل المواقع</h3>
<p>تحليل لمواقع المشاريع وتوزيعها الجغرافي.</p>
<p>يمكنك عرض إحصائيات وتقارير متنوعة حول مواقع المشاريع.</p>
</div>
""", unsafe_allow_html=True)
# التحقق من وجود مواقع
if not st.session_state.project_locations:
st.warning("لا توجد مواقع مشاريع متاحة. يرجى إضافة مواقع من تبويب 'إدارة المواقع'.")
return
# تحويل بيانات المواقع إلى DataFrame
locations_df = pd.DataFrame(st.session_state.project_locations)
# عرض توزيع المشاريع حسب المدينة
st.markdown("### توزيع المشاريع حسب المدينة")
city_counts = locations_df["city"].value_counts().reset_index()
city_counts.columns = ["المدينة", "عدد المشاريع"]
# عرض الرسم البياني
import plotly.express as px
fig = px.bar(
city_counts,
x="المدينة",
y="عدد المشاريع",
title="توزيع المشاريع حسب المدينة",
color="عدد المشاريع",
color_continuous_scale="Viridis"
)
fig.update_layout(
title_font_size=20,
font_family="Arial",
font_size=14,
height=400
)
st.plotly_chart(fig, use_container_width=True)
# عرض توزيع المشاريع حسب الحالة
st.markdown("### توزيع المشاريع حسب الحالة")
status_counts = locations_df["status"].value_counts().reset_index()
status_counts.columns = ["الحالة", "عدد المشاريع"]
# عرض الرسم البياني
fig2 = px.pie(
status_counts,
values="عدد المشاريع",
names="الحالة",
title="توزيع المشاريع حسب الحالة",
color_discrete_sequence=px.colors.qualitative.Set3
)
fig2.update_layout(
title_font_size=20,
font_family="Arial",
font_size=14,
height=400
)
st.plotly_chart(fig2, use_container_width=True)
# عرض تحليل المسافات بين المشاريع
st.markdown("### تحليل المسافات بين المشاريع")
# حساب مصفوفة المسافات
if len(locations_df) > 1:
# اختيار مشروع كنقطة مرجعية
reference_project = st.selectbox(
"اختر مشروعًا كنقطة مرجعية",
options=locations_df["project_id"].tolist(),
format_func=lambda x: next((p["name"] for p in st.session_state.project_locations if p["project_id"] == x), x),
key="reference_project"
)
# العثور على المشروع المرجعي
ref_project_data = locations_df[locations_df["project_id"] == reference_project].iloc[0]
# حساب المسافات
distances = []
for _, project in locations_df.iterrows():
if project["project_id"] != reference_project:
distance = self._calculate_distance(
ref_project_data["latitude"], ref_project_data["longitude"],
project["latitude"], project["longitude"]
)
distances.append({
"project_id": project["project_id"],
"name": project["name"],
"city": project["city"],
"distance": distance
})
# تحويل البيانات إلى DataFrame
distances_df = pd.DataFrame(distances)
# ترتيب المشاريع حسب المسافة
distances_df = distances_df.sort_values("distance")
# عرض المسافات
st.markdown(f"المسافات من مشروع: **{ref_project_data['name']}**")
# إعادة تسمية الأعمدة
distances_df = distances_df.rename(columns={
"name": "اسم المشروع",
"city": "المدينة",
"distance": "المسافة (كم)"
})
# تنسيق المسافة
distances_df["المسافة (كم)"] = distances_df["المسافة (كم)"].round(2)
# عرض الجدول
st.dataframe(distances_df[["اسم المشروع", "المدينة", "المسافة (كم)"]], width=800)
# عرض رسم بياني للمسافات
fig3 = px.bar(
distances_df,
x="اسم المشروع",
y="المسافة (كم)",
title=f"المسافات من مشروع {ref_project_data['name']}",
color="المسافة (كم)",
color_continuous_scale="Viridis"
)
fig3.update_layout(
title_font_size=20,
font_family="Arial",
font_size=14,
height=400
)
st.plotly_chart(fig3, use_container_width=True)
# عرض المشاريع القريبة على خريطة
st.markdown("### المشاريع القريبة على الخريطة")
# إنشاء الخريطة
m2 = folium.Map(
location=[ref_project_data["latitude"], ref_project_data["longitude"]],
zoom_start=8,
tiles="OpenStreetMap",
attr='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
)
# إضافة المشروع المرجعي
folium.Marker(
location=[ref_project_data["latitude"], ref_project_data["longitude"]],
popup=ref_project_data["name"],
tooltip=ref_project_data["name"],
icon=folium.Icon(color='red', icon='star')
).add_to(m2)
# إضافة الدوائر
folium.Circle(
location=[ref_project_data["latitude"], ref_project_data["longitude"]],
radius=50000, # 50 كم
color='red',
fill=True,
fill_opacity=0.1,
popup="50 كم"
).add_to(m2)
folium.Circle(
location=[ref_project_data["latitude"], ref_project_data["longitude"]],
radius=100000, # 100 كم
color='orange',
fill=True,
fill_opacity=0.1,
popup="100 كم"
).add_to(m2)
folium.Circle(
location=[ref_project_data["latitude"], ref_project_data["longitude"]],
radius=200000, # 200 كم
color='blue',
fill=True,
fill_opacity=0.1,
popup="200 كم"
).add_to(m2)
# إضافة المشاريع الأخرى
for _, project in distances_df.iterrows():
project_data = locations_df[locations_df["project_id"] == project["project_id"]].iloc[0]
folium.Marker(
location=[project_data["latitude"], project_data["longitude"]],
popup=f"{project_data['name']} - {project['المسافة (كم)']} كم",
tooltip=project_data["name"],
icon=folium.Icon(color='green', icon='info-sign')
).add_to(m2)
# إضافة خط للربط
folium.PolyLine(
locations=[
[ref_project_data["latitude"], ref_project_data["longitude"]],
[project_data["latitude"], project_data["longitude"]]
],
color='gray',
weight=2,
opacity=0.5,
popup=f"{project['المسافة (كم)']} كم"
).add_to(m2)
# عرض الخريطة
folium_static(m2, width=800, height=500)
else:
st.info("يجب وجود أكثر من مشروع واحد لحساب المسافات.")
def _render_location_management(self):
"""عرض إدارة المواقع"""
st.markdown("""
<div class='custom-box info-box'>
<h3>⚙️ إدارة المواقع</h3>
<p>إضافة وتحرير وحذف مواقع المشاريع.</p>
<p>يمكنك إضافة مواقع جديدة أو تحديث المواقع الموجودة.</p>
</div>
""", unsafe_allow_html=True)
# تبويبات إدارة المواقع
management_tabs = st.tabs(["إضافة موقع جديد", "تحرير المواقع الموجودة", "استيراد وتصدير المواقع"])
# تبويب إضافة موقع جديد
with management_tabs[0]:
self._render_add_location()
# تبويب تحرير المواقع الموجودة
with management_tabs[1]:
self._render_edit_locations()
# تبويب استيراد وتصدير المواقع
with management_tabs[2]:
self._render_import_export_locations()
def _render_add_location(self):
"""عرض نموذج إضافة موقع جديد"""
st.markdown("### إضافة موقع مشروع جديد")
# البيانات الأساسية
project_name = st.text_input("اسم المشروع", key="new_project_name")
project_desc = st.text_area("وصف المشروع", key="new_project_desc")
col1, col2 = st.columns(2)
with col1:
project_city = st.text_input("المدينة", key="new_project_city")
project_status = st.selectbox(
"حالة المشروع",
options=["جديد", "قيد التنفيذ", "متوقف", "مكتمل"],
key="new_project_status"
)
with col2:
project_id = st.text_input("معرف المشروع (اختياري)", key="new_project_id", placeholder="سيتم إنشاؤه تلقائيًا إذا تُرك فارغًا")
# إدخال إحداثيات الموقع
st.markdown("#### إحداثيات الموقع")
location_method = st.radio(
"طريقة تحديد الموقع",
options=["إدخال يدوي", "اختيار من الخريطة"],
key="new_location_method"
)
# تحديد الموقع
if location_method == "إدخال يدوي":
loc_col1, loc_col2 = st.columns(2)
with loc_col1:
latitude = st.number_input("خط العرض", value=24.7136, step=0.0001, format="%.6f", key="new_latitude")
with loc_col2:
longitude = st.number_input("خط الطول", value=46.6753, step=0.0001, format="%.6f", key="new_longitude")
# عرض الموقع على خريطة صغيرة
mini_map = folium.Map(location=[latitude, longitude], zoom_start=10)
folium.Marker(location=[latitude, longitude], tooltip="الموقع المحدد").add_to(mini_map)
folium_static(mini_map, width=700, height=300)
else:
st.markdown("#### اختر الموقع من الخريطة")
st.info("انقر على الخريطة لتحديد الموقع.")
# إنشاء خريطة
m = folium.Map(location=[24.7136, 46.6753], zoom_start=6)
# إضافة محدد النقر
m.add_child(folium.ClickForMarker(popup="الموقع المحدد"))
# عرض الخريطة
map_data = folium_static(m, width=700, height=400)
# استخراج الإحداثيات المحددة (ليس مدعومًا حاليًا في Streamlit)
st.warning("ملاحظة: خاصية النقر على الخريطة غير مدعومة حاليًا في Streamlit. يرجى استخدام الإدخال اليدوي.")
latitude = st.number_input("خط العرض", value=24.7136, step=0.0001, format="%.6f", key="map_latitude")
longitude = st.number_input("خط الطول", value=46.6753, step=0.0001, format="%.6f", key="map_longitude")
# زر إضافة الموقع
if styled_button("إضافة الموقع", key="add_location", type="primary", icon="➕"):
if not project_name or not project_desc or not project_city:
st.error("يرجى تعبئة جميع الحقول المطلوبة.")
else:
# إنشاء معرف فريد للمشروع إذا لم يتم تحديده
if not project_id:
project_id = f"PRJ-{len(st.session_state.project_locations) + 1:04d}"
# إنشاء كائن الموقع
new_location = {
"name": project_name,
"description": project_desc,
"city": project_city,
"status": project_status,
"latitude": latitude,
"longitude": longitude,
"project_id": project_id,
"created_at": pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S"),
"updated_at": pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
}
# إضافة الموقع للقائمة
st.session_state.project_locations.append(new_location)
# حفظ البيانات
self._save_locations_data()
st.success(f"تمت إضافة موقع المشروع '{project_name}' بنجاح!")
st.balloons()
def _render_edit_locations(self):
"""عرض واجهة تحرير المواقع الموجودة"""
st.markdown("### تحرير أو حذف مواقع المشاريع")
# التحقق من وجود مواقع
if not st.session_state.project_locations:
st.warning("لا توجد مواقع مشاريع متاحة. يرجى إضافة مواقع أولاً.")
return
# اختيار المشروع للتحرير
selected_project_id = st.selectbox(
"اختر مشروعًا للتحرير",
options=[p["project_id"] for p in st.session_state.project_locations],
format_func=lambda x: next((p["name"] for p in st.session_state.project_locations if p["project_id"] == x), x),
key="edit_project_select"
)
# العثور على المشروع المحدد
selected_project = next((p for p in st.session_state.project_locations if p["project_id"] == selected_project_id), None)
if selected_project:
# عرض نموذج التحرير
st.markdown(f"### تحرير مشروع: {selected_project['name']}")
# البيانات الأساسية
project_name = st.text_input("اسم المشروع", value=selected_project["name"], key="edit_project_name")
project_desc = st.text_area("وصف المشروع", value=selected_project["description"], key="edit_project_desc")
col1, col2 = st.columns(2)
with col1:
project_city = st.text_input("المدينة", value=selected_project["city"], key="edit_project_city")
project_status = st.selectbox(
"حالة المشروع",
options=["جديد", "قيد التنفيذ", "متوقف", "مكتمل"],
index=["جديد", "قيد التنفيذ", "متوقف", "مكتمل"].index(selected_project["status"]),
key="edit_project_status"
)
with col2:
st.text_input("معرف المشروع", value=selected_project["project_id"], disabled=True, key="edit_project_id")
# إدخال إحداثيات الموقع
st.markdown("#### إحداثيات الموقع")
# تحديد الموقع
loc_col1, loc_col2 = st.columns(2)
with loc_col1:
latitude = st.number_input(
"خط العرض",
value=selected_project["latitude"],
step=0.0001,
format="%.6f",
key="edit_latitude"
)
with loc_col2:
longitude = st.number_input(
"خط الطول",
value=selected_project["longitude"],
step=0.0001,
format="%.6f",
key="edit_longitude"
)
# عرض الموقع على خريطة صغيرة
mini_map = folium.Map(location=[latitude, longitude], zoom_start=10)
folium.Marker(location=[latitude, longitude], tooltip="الموقع المحدد").add_to(mini_map)
folium_static(mini_map, width=700, height=300)
# أزرار الإجراءات
col1, col2 = st.columns(2)
with col1:
if styled_button("حفظ التغييرات", key="save_location_changes", type="primary", icon="💾"):
if not project_name or not project_desc or not project_city:
st.error("يرجى تعبئة جميع الحقول المطلوبة.")
else:
# تحديث بيانات المشروع
selected_project["name"] = project_name
selected_project["description"] = project_desc
selected_project["city"] = project_city
selected_project["status"] = project_status
selected_project["latitude"] = latitude
selected_project["longitude"] = longitude
selected_project["updated_at"] = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
# حفظ البيانات
self._save_locations_data()
st.success(f"تم تحديث بيانات المشروع '{project_name}' بنجاح!")
st.experimental_rerun()
with col2:
if styled_button("حذف المشروع", key="delete_location", type="danger", icon="🗑️"):
# تأكيد الحذف
st.warning(f"هل أنت متأكد من حذف المشروع '{selected_project['name']}'؟")
confirm_col1, confirm_col2 = st.columns(2)
with confirm_col1:
if styled_button("تأكيد الحذف", key="confirm_delete", type="danger", icon="✓"):
# إزالة المشروع من القائمة
st.session_state.project_locations.remove(selected_project)
# حفظ البيانات
self._save_locations_data()
st.success(f"تم حذف المشروع '{selected_project['name']}' بنجاح!")
st.experimental_rerun()
with confirm_col2:
if styled_button("إلغاء", key="cancel_delete", type="secondary", icon="❌"):
st.experimental_rerun()
def _render_import_export_locations(self):
"""عرض واجهة استيراد وتصدير المواقع"""
st.markdown("### استيراد وتصدير مواقع المشاريع")
col1, col2 = st.columns(2)
with col1:
st.markdown("#### تصدير المواقع")
export_format = st.selectbox(
"صيغة التصدير",
options=["CSV", "JSON", "GeoJSON"],
key="export_format"
)
if styled_button("تصدير المواقع", key="export_locations", type="primary", icon="📤"):
self._export_locations(export_format)
with col2:
st.markdown("#### استيراد المواقع")
import_format = st.selectbox(
"صيغة الاستيراد",
options=["CSV", "JSON", "GeoJSON"],
key="import_format"
)
uploaded_file = st.file_uploader(
"اختر ملف للاستيراد",
type=["csv", "json", "geojson"],
key="import_locations_file"
)
if uploaded_file is not None:
if styled_button("استيراد المواقع", key="import_locations", type="success", icon="📥"):
self._import_locations(uploaded_file, import_format)
# عرض إحصائيات البيانات
st.markdown("### إحصائيات البيانات")
stats_col1, stats_col2, stats_col3 = st.columns(3)
with stats_col1:
st.metric("عدد المشاريع", len(st.session_state.project_locations))
with stats_col2:
cities = set(p["city"] for p in st.session_state.project_locations)
st.metric("عدد المدن", len(cities))
with stats_col3:
statuses = {}
for p in st.session_state.project_locations:
statuses[p["status"]] = statuses.get(p["status"], 0) + 1
status_str = ", ".join([f"{k}: {v}" for k, v in statuses.items()])
st.metric("توزيع الحالات", status_str if statuses else "لا توجد بيانات")
# خيارات متقدمة
with st.expander("خيارات متقدمة"):
if styled_button("حذف جميع المواقع", key="clear_locations", type="danger", icon="🗑️"):
# تأكيد الحذف
st.warning("هل أنت متأكد من حذف جميع مواقع المشاريع؟ لا يمكن التراجع عن هذا الإجراء.")
confirm_col1, confirm_col2 = st.columns(2)
with confirm_col1:
if styled_button("تأكيد الحذف", key="confirm_clear", type="danger", icon="✓"):
# مسح القائمة
st.session_state.project_locations = []
# حفظ البيانات
self._save_locations_data()
st.success("تم حذف جميع مواقع المشاريع بنجاح!")
st.experimental_rerun()
with confirm_col2:
if styled_button("إلغاء", key="cancel_clear", type="secondary", icon="❌"):
st.experimental_rerun()
def _fetch_terrain_data(self, latitude, longitude, radius_km=5):
"""جلب بيانات التضاريس من واجهة برمجة التطبيقات"""
try:
# تحديث حالة الجلسة
import plotly.express as px
# تعيين الإحداثيات وحجم المنطقة
center_lat, center_lon = latitude, longitude
# تحويل نصف القطر من كم إلى درجات (تقريبي)
radius_deg = radius_km / 111.0 # تقريب: 1 درجة = 111 كم
# تحديد حدود المنطقة
min_lat = center_lat - radius_deg
max_lat = center_lat + radius_deg
min_lon = center_lon - radius_deg
max_lon = center_lon + radius_deg
# إنشاء شبكة من النقاط
resolution = 50 # عدد النقاط في كل اتجاه
lats = np.linspace(min_lat, max_lat, resolution)
lons = np.linspace(min_lon, max_lon, resolution)
# إنشاء مصفوفة للإحداثيات
grid_lats, grid_lons = np.meshgrid(lats, lons)
# تحويل الشبكة إلى قائمة من النقاط
points = []
for i in range(grid_lats.shape[0]):
for j in range(grid_lats.shape[1]):
points.append((grid_lats[i, j], grid_lons[i, j]))
# تقسيم النقاط إلى مجموعات لتقليل عدد الطلبات
batch_size = 100
batches = [points[i:i + batch_size] for i in range(0, len(points), batch_size)]
# إنشاء بيانات التضاريس
elevation_data = np.zeros((len(lats), len(lons)))
# محاكاة بيانات التضاريس (يمكن استبدالها بواجهة برمجة تطبيقات حقيقية)
for batch_idx, batch in enumerate(batches):
# في بيئة الإنتاج، سيتم استبدال هذا بطلب API حقيقي
# هنا نقوم بمحاكاة بيانات التضاريس لأغراض العرض
for point_idx, (lat, lon) in enumerate(batch):
# حساب المؤشر في مصفوفة الارتفاع
lat_idx = np.abs(lats - lat).argmin()
lon_idx = np.abs(lons - lon).argmin()
# محاكاة الارتفاع (في بيئة الإنتاج سيكون هذا من واجهة برمجة التطبيقات)
# هنا نصنع تضاريس اصطناعية باستخدام دالة جيبية
dist_from_center = np.sqrt(
(lat - center_lat) ** 2 + (lon - center_lon) ** 2
)
# إنشاء بعض التلال والوديان الاصطناعية
elevation = 500 + 200 * np.sin(dist_from_center * 100) + 100 * np.cos(lat * 30) + 150 * np.sin(lon * 40)
# إضافة بعض الضوضاء العشوائية
elevation += np.random.normal(0, 30)
# تخزين الارتفاع
elevation_data[lat_idx, lon_idx] = elevation
# حساب إحصائيات الارتفاع
elevation_stats = {
"min": float(np.min(elevation_data)),
"max": float(np.max(elevation_data)),
"mean": float(np.mean(elevation_data)),
"range": float(np.max(elevation_data) - np.min(elevation_data))
}
# إنشاء مقطع ارتفاع من الشمال إلى الجنوب عبر المركز
center_lon_idx = np.abs(lons - center_lon).argmin()
ns_profile = []
for i, lat in enumerate(lats):
ns_profile.append({
"distance": (lat - min_lat) * 111.0, # تحويل الدرجات إلى كم
"elevation": float(elevation_data[i, center_lon_idx])
})
# إنشاء مقطع ارتفاع من الشرق إلى الغرب عبر المركز
center_lat_idx = np.abs(lats - center_lat).argmin()
ew_profile = []
for i, lon in enumerate(lons):
ew_profile.append({
"distance": (lon - min_lon) * 111.0 * np.cos(np.radians(center_lat)), # تحويل الدرجات إلى كم مع تصحيح خط العرض
"elevation": float(elevation_data[center_lat_idx, i])
})
# دمج المقاطع
elevation_profile = ns_profile + ew_profile
# تحضير بيانات التضاريس للعرض ثلاثي الأبعاد
bounds = [min_lon, min_lat, max_lon, max_lat]
# تحويل مصفوفة الارتفاع إلى تنسيق مناسب لـ PyDeck
terrain_array = elevation_data.astype(np.float32)
# إنشاء كائن للتضاريس
terrain_data = [{
"bounds": bounds,
"terrain": terrain_array.tolist(),
"elevation_stats": elevation_stats,
"elevation_profile": elevation_profile
}]
return terrain_data
except Exception as e:
st.error(f"حدث خطأ أثناء جلب بيانات التضاريس: {str(e)}")
raise e
def _calculate_distance(self, lat1, lon1, lat2, lon2):
"""حساب المسافة بين نقطتين بالكيلومترات باستخدام صيغة هافرساين"""
import math
# تحويل الإحداثيات إلى راديان
lat1 = math.radians(lat1)
lon1 = math.radians(lon1)
lat2 = math.radians(lat2)
lon2 = math.radians(lon2)
# صيغة هافرساين
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
distance = 6371 * c # نصف قطر الأرض بالكيلومترات
return distance
def _get_color_map(self, scheme):
"""الحصول على خريطة الألوان حسب النظام المختار"""
if scheme == "terrain":
return [
[0, (0, 50, 0)],
[0.1, (0, 100, 0)],
[0.25, (0, 150, 0)],
[0.4, (200, 170, 0)],
[0.6, (150, 100, 0)],
[0.8, (100, 50, 0)],
[1, (200, 200, 200)]
]
elif scheme == "elevation":
return [
[0, (0, 0, 100)],
[0.2, (0, 100, 150)],
[0.4, (0, 150, 50)],
[0.6, (150, 150, 0)],
[0.8, (150, 50, 0)],
[1, (100, 0, 0)]
]
else: # custom
return [
[0, (30, 100, 200)],
[0.3, (60, 170, 250)],
[0.5, (200, 220, 150)],
[0.7, (180, 120, 60)],
[0.9, (110, 60, 30)],
[1, (80, 30, 10)]
]
def _export_locations(self, format):
"""تصدير مواقع المشاريع إلى ملف"""
try:
if not st.session_state.project_locations:
st.error("لا توجد مواقع مشاريع للتصدير.")
return
if format == "CSV":
# تصدير إلى CSV
df = pd.DataFrame(st.session_state.project_locations)
csv_data = df.to_csv(index=False)
st.download_button(
label="تنزيل ملف CSV",
data=csv_data,
file_name="project_locations.csv",
mime="text/csv"
)
elif format == "JSON":
# تصدير إلى JSON
json_data = json.dumps(st.session_state.project_locations, ensure_ascii=False, indent=2)
st.download_button(
label="تنزيل ملف JSON",
data=json_data,
file_name="project_locations.json",
mime="application/json"
)
elif format == "GeoJSON":
# تصدير إلى GeoJSON
features = []
for location in st.session_state.project_locations:
feature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [location["longitude"], location["latitude"]]
},
"properties": {
"name": location["name"],
"description": location["description"],
"city": location["city"],
"status": location["status"],
"project_id": location["project_id"],
"created_at": location.get("created_at", ""),
"updated_at": location.get("updated_at", "")
}
}
features.append(feature)
geojson = {
"type": "FeatureCollection",
"features": features
}
geojson_data = json.dumps(geojson, ensure_ascii=False, indent=2)
st.download_button(
label="تنزيل ملف GeoJSON",
data=geojson_data,
file_name="project_locations.geojson",
mime="application/geo+json"
)
st.success(f"تم تصدير {len(st.session_state.project_locations)} موقع بنجاح!")
except Exception as e:
st.error(f"حدث خطأ أثناء تصدير المواقع: {str(e)}")
def _import_locations(self, uploaded_file, format):
"""استيراد مواقع المشاريع من ملف"""
try:
if format == "CSV":
# استيراد من CSV
df = pd.read_csv(uploaded_file)
# التحقق من وجود الأعمدة المطلوبة
required_columns = ["name", "latitude", "longitude"]
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
st.error(f"الملف لا يحتوي على الأعمدة التالية: {', '.join(missing_columns)}")
return
# تحويل DataFrame إلى قائمة من القواميس
imported_locations = df.to_dict("records")
elif format == "JSON":
# استيراد من JSON
imported_locations = json.loads(uploaded_file.read())
elif format == "GeoJSON":
# استيراد من GeoJSON
geojson = json.loads(uploaded_file.read())
# التحقق من صحة التنسيق
if "type" not in geojson or geojson["type"] != "FeatureCollection" or "features" not in geojson:
st.error("تنسيق GeoJSON غير صحيح.")
return
# تحويل المميزات إلى مواقع
imported_locations = []
for feature in geojson["features"]:
if feature["type"] == "Feature" and feature["geometry"]["type"] == "Point":
coords = feature["geometry"]["coordinates"]
properties = feature["properties"]
location = {
"name": properties.get("name", ""),
"description": properties.get("description", ""),
"city": properties.get("city", ""),
"status": properties.get("status", "جديد"),
"longitude": coords[0],
"latitude": coords[1],
"project_id": properties.get("project_id", f"PRJ-{len(imported_locations)+1:04d}"),
"created_at": properties.get("created_at", pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")),
"updated_at": properties.get("updated_at", pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S"))
}
imported_locations.append(location)
# التحقق من وجود البيانات المطلوبة في الملف المستورد
valid_locations = []
for location in imported_locations:
# التحقق من وجود الحقول المطلوبة
if "name" not in location or "latitude" not in location or "longitude" not in location:
continue
# إضافة القيم الافتراضية إذا لم تكن موجودة
if "description" not in location:
location["description"] = ""
if "city" not in location:
location["city"] = ""
if "status" not in location:
location["status"] = "جديد"
if "project_id" not in location:
location["project_id"] = f"PRJ-{len(valid_locations)+1:04d}"
if "created_at" not in location:
location["created_at"] = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
if "updated_at" not in location:
location["updated_at"] = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
valid_locations.append(location)
if not valid_locations:
st.error("لم يتم العثور على مواقع صالحة في الملف.")
return
# سؤال المستخدم عن كيفية الاستيراد
import_mode = st.radio(
"كيفية الاستيراد",
options=["إضافة إلى المواقع الموجودة", "استبدال المواقع الموجودة"],
key="import_mode"
)
if styled_button("تأكيد الاستيراد", key="confirm_import", type="success", icon="✓"):
if import_mode == "إضافة إلى المواقع الموجودة":
# إضافة المواقع المستوردة إلى القائمة الحالية
st.session_state.project_locations.extend(valid_locations)
else:
# استبدال المواقع الموجودة بالمواقع المستوردة
st.session_state.project_locations = valid_locations
# حفظ البيانات
self._save_locations_data()
st.success(f"تم استيراد {len(valid_locations)} موقع بنجاح!")
st.experimental_rerun()
except Exception as e:
st.error(f"حدث خطأ أثناء استيراد المواقع: {str(e)}")
def _save_locations_data(self):
"""حفظ بيانات المواقع"""
try:
# التأكد من وجود المجلد
os.makedirs(self.data_dir, exist_ok=True)
# حفظ البيانات
locations_file = os.path.join(self.data_dir, "project_locations.json")
with open(locations_file, 'w', encoding='utf-8') as f:
json.dump(st.session_state.project_locations, f, ensure_ascii=False, indent=2)
except Exception as e:
st.error(f"حدث خطأ أثناء حفظ بيانات المواقع: {str(e)}")
def _load_locations_data(self):
"""تحميل بيانات المواقع"""
try:
# التحقق من وجود الملف
locations_file = os.path.join(self.data_dir, "project_locations.json")
if os.path.exists(locations_file):
with open(locations_file, 'r', encoding='utf-8') as f:
locations = json.load(f)
# تحديث حالة الجلسة
st.session_state.project_locations = locations
except Exception as e:
st.error(f"حدث خطأ أثناء تحميل بيانات المواقع: {str(e)}")
def _initialize_sample_projects(self):
"""تهيئة بيانات اختبارية للمشاريع"""
# التحقق من وجود بيانات محفوظة
locations_file = os.path.join(self.data_dir, "project_locations.json")
if os.path.exists(locations_file):
# تحميل البيانات المحفوظة
self._load_locations_data()
return
# إنشاء بيانات اختبارية إذا لم تكن هناك بيانات محفوظة
sample_projects = [
{
"name": "تطوير شبكة الطرق في منطقة الرياض",
"description": "مشروع تطوير وتوسعة شبكة الطرق الرئيسية في منطقة الرياض",
"city": "الرياض",
"status": "قيد التنفيذ",
"latitude": 24.7136,
"longitude": 46.6753,
"project_id": "PRJ-0001",
"created_at": "2025-01-15 10:30:00",
"updated_at": "2025-01-15 10:30:00"
},
{
"name": "إنشاء سد وادي حنيفة",
"description": "مشروع إنشاء سد لحجز مياه الأمطار في وادي حنيفة",
"city": "الرياض",
"status": "جديد",
"latitude": 24.6748,
"longitude": 46.5831,
"project_id": "PRJ-0002",
"created_at": "2025-02-01 14:45:00",
"updated_at": "2025-02-01 14:45:00"
},
{
"name": "تطوير ميناء جدة الإسلامي",
"description": "مشروع تطوير وتوسعة ميناء جدة الإسلامي لزيادة الطاقة الاستيعابية",
"city": "جدة",
"status": "قيد التنفيذ",
"latitude": 21.4858,
"longitude": 39.1925,
"project_id": "PRJ-0003",
"created_at": "2024-11-20 09:15:00",
"updated_at": "2024-11-20 09:15:00"
},
{
"name": "إنشاء مطار الدمام الجديد",
"description": "مشروع إنشاء مطار جديد في مدينة الدمام لتلبية الطلب المتزايد",
"city": "الدمام",
"status": "متوقف",
"latitude": 26.4207,
"longitude": 50.0888,
"project_id": "PRJ-0004",
"created_at": "2024-10-05 11:30:00",
"updated_at": "2024-10-05 11:30:00"
},
{
"name": "توسعة جامعة الملك فهد للبترول والمعادن",
"description": "مشروع توسعة مباني ومرافق جامعة الملك فهد للبترول والمعادن",
"city": "الظهران",
"status": "قيد التنفيذ",
"latitude": 26.3927,
"longitude": 50.1150,
"project_id": "PRJ-0005",
"created_at": "2025-01-10 08:00:00",
"updated_at": "2025-01-10 08:00:00"
},
{
"name": "إنشاء محطة تحلية مياه القنفذة",
"description": "مشروع إنشاء محطة تحلية مياه جديدة في محافظة القنفذة",
"city": "القنفذة",
"status": "جديد",
"latitude": 19.1299,
"longitude": 41.0825,
"project_id": "PRJ-0006",
"created_at": "2025-02-20 15:20:00",
"updated_at": "2025-02-20 15:20:00"
},
{
"name": "تطوير مجمع حكومي في حائل",
"description": "مشروع إنشاء وتطوير مجمع للدوائر الحكومية في مدينة حائل",
"city": "حائل",
"status": "مكتمل",
"latitude": 27.5114,
"longitude": 41.7208,
"project_id": "PRJ-0007",
"created_at": "2024-06-15 10:00:00",
"updated_at": "2024-12-10 14:30:00"
},
{
"name": "إنشاء مستشفى الإحساء العام",
"description": "مشروع إنشاء مستشفى عام جديد في محافظة الإحساء بسعة 500 سرير",
"city": "الإحساء",
"status": "قيد التنفيذ",
"latitude": 25.3753,
"longitude": 49.5873,
"project_id": "PRJ-0008",
"created_at": "2024-09-01 09:45:00",
"updated_at": "2024-09-01 09:45:00"
},
{
"name": "تطوير شبكة الصرف الصحي في أبها",
"description": "مشروع تطوير وتوسعة شبكة الصرف الصحي في مدينة أبها",
"city": "أبها",
"status": "جديد",
"latitude": 18.2164,
"longitude": 42.5053,
"project_id": "PRJ-0009",
"created_at": "2025-02-25 11:15:00",
"updated_at": "2025-02-25 11:15:00"
},
{
"name": "إنشاء مدينة صناعية في سكاكا",
"description": "مشروع إنشاء مدينة صناعية جديدة في منطقة سكاكا",
"city": "سكاكا",
"status": "متوقف",
"latitude": 29.9720,
"longitude": 40.2006,
"project_id": "PRJ-0010",
"created_at": "2024-07-20 13:30:00",
"updated_at": "2024-07-20 13:30:00"
}
]
# تحديث حالة الجلسة
st.session_state.project_locations = sample_projects
# حفظ البيانات
self._save_locations_data()
# فئة تحويل Folium إلى Streamlit
class folium_static:
"""فئة لعرض خرائط Folium في Streamlit"""
def __init__(self, fig, width=700, height=500):
"""عرض خريطة Folium في Streamlit"""
import streamlit.components.v1 as components
# تحويل خريطة Folium إلى HTML
fig_html = fig._repr_html_()
# إنشاء مكون HTML مخصص
components.html(fig_html, width=width, height=height)
# تشغيل الوحدة بشكل مستقل
def main():
"""تشغيل وحدة الخريطة التفاعلية مع عرض التضاريس ثلاثي الأبعاد بشكل مستقل"""
# تهيئة الواجهة
st.set_page_config(
page_title="الخريطة التفاعلية | WAHBi AI",
page_icon="🗺️",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'mailto:[email protected]',
'Report a bug': 'mailto:[email protected]',
'About': 'وحدة الخريطة التفاعلية مع عرض التضاريس ثلاثي الأبعاد - جزء من نظام WAHBi AI لتحليل المناقصات'
}
)
# تهيئة وحدة الخريطة التفاعلية
interactive_map = InteractiveMap()
# عرض واجهة الوحدة
interactive_map.render()
# تشغيل الوحدة عند استدعاء الملف مباشرة
if __name__ == "__main__":
main() |