Esmaeilkiani commited on
Commit
d5b2220
1 Parent(s): 2d4b08f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -121
app.py CHANGED
@@ -1,125 +1,110 @@
1
- import streamlit as st
2
- import ee
3
- import geemap.foliumap as geemap
4
- import pandas as pd
5
- import datetime
6
- import matplotlib.pyplot as plt
7
- import geopandas as gpd
8
- import zipfile
9
- import os
10
- import requests
11
 
 
12
  # اعتبار سنجی و اتصال به Google Earth Engine
13
  service_account = 'earth-engine-service-account@ee-esmaeilkiani1387.iam.gserviceaccount.com'
14
  credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani1387-1b2c5e812a1d.json')
15
- ee.Initialize(credentials)
16
-
17
- # خواندن فایل CSV مزارع
18
- farms_data = pd.read_csv('Farm_Details_Export.csv')
19
-
20
- # تعریف ناحیه مورد مطالعه با مختصات جدید
21
- region = ee.Geometry.Polygon(
22
- [[[48.681879, 31.417603], [48.721447, 31.413209], [48.724279, 31.420826], [48.726768, 31.427418],
23
- [48.728228, 31.435694], [48.736382, 31.42837], [48.739557, 31.435657], [48.742261, 31.441772],
24
- [48.752303, 31.452243], [48.75226, 31.459784], [48.759127, 31.473657], [48.766809, 31.472413],
25
- [48.773203, 31.491188], [48.77758, 31.534579], [48.785563, 31.540797], [48.792601, 31.59696],
26
- [48.694668, 31.60756], [48.691921, 31.603466], [48.697586, 31.534067], [48.69381, 31.507727],
27
- [48.685226, 31.468496], [48.681879, 31.417603]]]
28
- )
29
-
30
- # تابع برای دانلود و استخراج شیپ‌فایل
31
- def download_and_extract_shapefile(zip_url, extract_to='.'):
32
- zip_path = os.path.join(extract_to, 'shapefile.zip')
33
-
34
- # دانلود فایل زیپ
35
- with requests.get(zip_url, stream=True) as r:
36
- r.raise_for_status()
37
- with open(zip_path, 'wb') as f:
38
- for chunk in r.iter_content(chunk_size=8192):
39
- f.write(chunk)
40
-
41
- # استخراج فایل زیپ
42
- with zipfile.ZipFile(zip_path, 'r') as zip_ref:
43
- zip_ref.extractall(extract_to)
44
-
45
- # یافتن فایل .shp
46
- for file in os.listdir(extract_to):
47
- if file.endswith('.shp'):
48
- return os.path.join(extract_to, file)
49
-
50
- return None
51
-
52
- # تابع برای خواندن و نمایش شیپ‌فایل
53
- def load_and_display_shapefile(shapefile_path):
54
- gdf = gpd.read_file(shapefile_path)
55
- geojson = gdf.to_json()
56
-
57
- map_ = geemap.Map(center=[31.5, 48.7], zoom=10)
58
- map_.add_geojson(geojson, layer_name="Shapefile Layer")
59
- map_.to_streamlit(height=600)
60
-
61
- # آدرس شیپ‌فایل آپلود شده در هاگینگ فیس (لینک مستقیم فایل زیپ)
62
- zip_url = 'https://huggingface.co/spaces/Esmaeilkiani/AppSugarcane/resolve/main/Dehkhodaa.rar'
63
-
64
- # دانلود و نمایش شیپ‌فایل
65
- shapefile_path = download_and_extract_shapefile(zip_url)
66
- if shapefile_path:
67
- st.write("شیپ‌فایل با موفقیت بارگذاری شد!")
68
- load_and_display_shapefile(shapefile_path)
69
- else:
70
- st.write("خطا در بارگذاری شیپ‌فایل.")
71
-
72
- # انتخاب بازه زمانی با کلیدهای یکتا
73
- start_date = st.date_input("تاریخ شروع", datetime.date(2023, 1, 1), key="start_date")
74
- end_date = st.date_input("تاریخ پایان", datetime.date(2023, 12, 31), key="end_date")
75
-
76
- # انتخاب شاخص
77
- index_option = st.selectbox("شاخص مورد نظر را انتخاب کنید:", ["NDVI", "NDMI", "NDRE"])
78
-
79
- # انتخاب مزرعه از فایل CSV
80
- farm_name = st.sidebar.selectbox("نام مزرعه را انتخاب کنید:", farms_data['farm_name'].unique())
81
-
82
- # پیدا کردن مختصات مزرعه انتخاب شده
83
- selected_farm = farms_data[farms_data['farm_name'] == farm_name]
84
- latitude = selected_farm['latitude'].values[0]
85
- longitude = selected_farm['longitude'].values[0]
86
- farm_age = selected_farm['age'].values[0]
87
- farm_variety = selected_farm['variety'].values[0]
88
-
89
- # دکمه برای نمایش نقشه
90
- if st.button("نمایش نقشه"):
91
- if index_option == "NDVI":
92
- index_map, vis_params = get_ndvi_map(start_date.isoformat(), end_date.isoformat())
93
- elif index_option == "NDMI":
94
- index_map, vis_params = get_ndmi_map(start_date.isoformat(), end_date.isoformat())
95
- else:
96
- index_map, vis_params = get_ndre_map(start_date.isoformat(), end_date.isoformat())
97
-
98
- # ایجاد نقشه با Geemap
99
- map_ = geemap.Map(center=[latitude, longitude], zoom=14)
100
- map_.addLayer(index_map.clip(region), vis_params, index_option)
101
- map_.add_colorbar(vis_params, label=index_option)
102
-
103
- # افزودن مزرعه به نقشه
104
- map_.add_marker([latitude, longitude], popup=f"نام: {farm_name}<br>سن: {farm_age}<br>واریته: {farm_variety}")
105
- map_.add_ee_layer(region, {'color': 'FF0000'}, 'منطقه مورد مطالعه')
106
-
107
- # نمایش نقشه در Streamlit
108
- map_.to_streamlit(height=600)
109
-
110
- # محاسبه NDRE میانگین
111
- ndre_image = get_ndre_map(start_date.isoformat(), end_date.isoformat())[0]
112
- mean_ndre = ndre_image.reduceRegion(reducer=ee.Reducer.mean(), geometry=region, scale=30).get('NDRE').getInfo()
113
-
114
- # نمودار تصمیم‌گیری برای برداشت
115
- fig, ax = plt.subplots()
116
- ax.bar(['NDRE', 'مناسب برای برداشت'], [mean_ndre, 0.5], color=['green', 'orange'])
117
- ax.set_ylim(0, 1)
118
- ax.set_title(f"شاخص NDRE برای مزرعه {farm_name}")
119
- st.pyplot(fig)
120
-
121
- # نمایش وضعیت برداشت
122
- if mean_ndre > 0.5:
123
- st.write(f"مزرعه {farm_name} به حد قابل قبول برای برداشت رسیده است (NDRE = {mean_ndre:.2f}).")
124
- else:
125
- st.write(f"مزرعه {farm_name} هنوز آماده برداشت نیست (NDRE = {mean_ndre:.2f}).")
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import joblib
4
+ import ee
5
+ import geemap
 
 
 
 
 
6
 
7
+ # Earth Engine Authentication (Replace with your actual authentication)
8
  # اعتبار سنجی و اتصال به Google Earth Engine
9
  service_account = 'earth-engine-service-account@ee-esmaeilkiani1387.iam.gserviceaccount.com'
10
  credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani1387-1b2c5e812a1d.json')
11
+ ee.Initialize(credentials)
12
+
13
+
14
+ # Load pre-trained model
15
+ model = joblib.load('updated_model.pkl') # Replace 'updated_model.pkl' with your actual model file
16
+
17
+ # Load farm data
18
+ farm_data = pd.read_csv('Farm_NDRE_TimeSeries.csv') # Replace 'Farm_NDRE_TimeSeries.csv' with your actual data file
19
+ farm_names = farm_data['Farm_Name'].tolist()
20
+
21
+ # Function to calculate NDRE
22
+ def calculate_ndre(coordinates, start_date, end_date):
23
+ try:
24
+ # Define the Earth Engine region of interest (ROI)
25
+ roi = ee.Geometry.Point(coordinates)
26
+
27
+ # Define the image collection (replace with your actual collection ID and bands)
28
+ imageCollection = ee.ImageCollection('COPERNICUS/S2_SR') \
29
+ .filterBounds(roi) \
30
+ .filterDate(start_date, end_date) \
31
+ .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20)) #Cloud filtering
32
+
33
+ # Function to compute NDRE
34
+ def ndre(image):
35
+ red_edge = image.select('B8A')
36
+ red = image.select('B4')
37
+ return image.addBands(red_edge.subtract(red).divide(red_edge.add(red)).rename('NDRE'))
38
+
39
+ #Apply NDRE to all images in collection, and reduce to median
40
+ ndre_image = imageCollection.map(ndre).median().select('NDRE')
41
+
42
+ # Get NDRE value at the point
43
+ ndre_value = ndre_image.reduceRegion(
44
+ reducer=ee.Reducer.first(),
45
+ geometry=roi,
46
+ scale=10
47
+ ).getInfo()
48
+
49
+ ndre_value = ndre_value.get('NDRE') #Extract from dictionary
50
+
51
+ return ndre_value
52
+
53
+ except Exception as e:
54
+ st.error(f"Error calculating NDRE: {e}")
55
+ return None
56
+
57
+
58
+ # Streamlit UI
59
+ st.title("Farm Parameter Prediction App")
60
+
61
+ # User input
62
+ selected_farm = st.selectbox("Select Farm", farm_names)
63
+ farm_age = st.number_input("Farm Age (years)", min_value=0)
64
+ farm_variety = st.text_input("Farm Variety")
65
+ start_date = st.date_input("Start Date")
66
+ end_date = st.date_input("End Date")
67
+
68
+
69
+ #Find Coordinates based on Farm Name Selection
70
+ selected_farm_data = farm_data[farm_data['Farm'] == selected_farm]
71
+ coordinates = (selected_farm_data['longitude'].iloc[0], selected_farm_data['latitude'].iloc[0])
72
+
73
+
74
+ if st.button("Calculate NDRE and Show Map"):
75
+ ndre_value = calculate_ndre(coordinates, start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))
76
+ if ndre_value is not None:
77
+ st.write(f"NDRE Value: {ndre_value}")
78
+ # Map Display (Replace with your actual map display logic)
79
+ Map = geemap.Map()
80
+ Map.centerObject(ee.Geometry.Point(coordinates), 12)
81
+
82
+ # Add NDRE layer
83
+ #This part requires more detailed specification of the image and display parameters.
84
+ #Example (Adapt according to your NDRE image and color scheme)
85
+ #vis_params = {'min': 0, 'max': 1, 'palette': ['blue', 'green', 'yellow', 'red']}
86
+ #Map.addLayer(ndre_image, vis_params, 'NDRE')
87
+
88
+ #Display Map
89
+ Map.to_streamlit(height=500)
90
+
91
+ if st.button("Predict"):
92
+ user_input = pd.DataFrame({
93
+ 'Farm_Name': [selected_farm],
94
+ 'Farm_Age': [farm_age],
95
+ 'Farm_Variety': [farm_variety],
96
+ 'NDRE': [ndre_value] if ndre_value is not None else [0] #Handle cases where ndre_value is None. Replace 0 with a more suitable default if needed.
97
+ })
98
+
99
+ # Feature Engineering might be needed here depending on your model's input features
100
+
101
+ prediction = model.predict(user_input)
102
+
103
+ st.write("Predictions:")
104
+ st.write(f"Brix: {prediction[0][0]}") #Assuming model outputs a list of lists
105
+ st.write(f"Pol: {prediction[0][1]}")
106
+ st.write(f"Purity: {prediction[0][2]}")
107
+ st.write(f"RS: {prediction[0][3]}")
108
+
109
+
110
+