-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_1_service_account.py
237 lines (195 loc) · 7 KB
/
example_1_service_account.py
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
import ee
import time
from google.oauth2 import service_account
from googleapiclient.discovery import build
from ee_lst.landsat_lst import fetch_landsat_collection
import io
from googleapiclient.http import MediaIoBaseDownload
service_account_file = ".gee-sa-priv-key.json"
folder_name = "python_lst_geotiffs"
local_download_path = "./downloads"
SCOPES = [
"https://www.googleapis.com/auth/earthengine",
"https://www.googleapis.com/auth/devstorage.full_control",
"https://www.googleapis.com/auth/drive",
]
def initialize_services(service_account_file):
"""Initialize Earth Engine and Google Drive services."""
credentials = service_account.Credentials.from_service_account_file(
service_account_file, scopes=SCOPES
)
ee.Initialize(credentials)
return build("drive", "v3", credentials=credentials)
def clean_folder(service, folder_name):
"""Delete all files in the specified Google Drive folder."""
# Search for the folder by its name
folder_results = (
service.files()
.list(
q=f"name='{folder_name}' and mimeType='application/vnd.google-apps.folder'",
fields="files(id)",
)
.execute()
)
folders = folder_results.get("files", [])
if not folders:
print(f"Folder {folder_name} not found.")
return
folder_id = folders[0]["id"]
# List all files in the folder
file_results = (
service.files()
.list(q=f"'{folder_id}' in parents", fields="files(id, name)")
.execute()
)
files = file_results.get("files", [])
# Delete each file
for file in files:
try:
service.files().delete(fileId=file["id"]).execute()
print(f"Deleted {file['name']} from {folder_name}")
except Exception as e:
print(f"Error deleting {file['name']} from {folder_name}: {e}")
def download_files(service, folder_name, download_path):
"""Download all files from the specified Google Drive folder to a local path."""
# Search for the folder by its name
folder_results = (
service.files()
.list(
q=f"name='{folder_name}' and mimeType='application/vnd.google-apps.folder'",
fields="files(id)",
)
.execute()
)
folders = folder_results.get("files", [])
if not folders:
print(f"Folder {folder_name} not found.")
return
folder_id = folders[0]["id"]
# List all files in the folder
file_results = (
service.files()
.list(q=f"'{folder_id}' in parents", fields="files(id, name, mimeType)")
.execute()
)
files = file_results.get("files", [])
# Download each file
for file in files:
request = service.files().get_media(fileId=file["id"])
file_name = file["name"]
fh = io.FileIO(f"{download_path}/{file_name}", "wb")
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
msg = "Downloaded "
msg += f"{int(status.progress() * 100)}% of {file_name}"
print(msg)
print(f"All files downloaded to {download_path}")
def kelvin_to_celsius(image):
"""Convert an LST image from Kelvin to Celsius."""
return image.subtract(273.15)
def process_data(drive_service, folder_name):
"""Process and export visualizations."""
try:
geometry = ee.Geometry.Rectangle([-8.91, 40.0, -8.3, 40.4])
satellite = "L8"
date_start = "2022-05-15"
date_end = "2022-05-31"
use_ndvi = True
landsat_coll = fetch_landsat_collection(
satellite, date_start, date_end, geometry, use_ndvi
)
ex_image = landsat_coll.first()
cmap1 = ["blue", "cyan", "green", "yellow", "red"]
cmap2 = ["F2F2F2", "EFC2B3", "ECB176", "E9BD3A", "E6E600", "63C600", "00A600"]
visualizations = [
{
"bands": ["TPW"],
"min": 0.0,
"max": 60.0,
"palette": cmap1,
"description": "TCWV",
},
{
"bands": ["TPWpos"],
"min": 0.0,
"max": 9.0,
"palette": cmap1,
"description": "TCWVpos",
},
{
"bands": ["FVC"],
"min": 0.0,
"max": 1.0,
"palette": cmap2,
"description": "FVC",
},
{
"bands": ["EM"],
"min": 0.9,
"max": 1.0,
"palette": cmap1,
"description": "Emissivity",
},
{
"bands": ["B10"],
"min": 290,
"max": 320,
"palette": cmap1,
"description": "TIR_BT",
},
{
"bands": ["LST"],
"min": 290,
"max": 320,
"palette": cmap1,
"description": "LST",
},
{"bands": ["LST"], "description": "LST_Celsius_Raw"},
{
"bands": ["SR_B4", "SR_B3", "SR_B2"],
"min": 0,
"max": 0.3,
"description": "RGB",
},
]
for vis in visualizations:
if "RGB" in vis["description"]:
# Special case for RGB. We don't need to apply a palette.
export_image = ex_image.select(vis["bands"])
elif vis["description"] == "LST_Celsius_Raw":
# Special case for raw LST in Celsius.
export_image = kelvin_to_celsius(ex_image.select(vis["bands"]))
else:
export_image = ex_image.visualize(
bands=vis["bands"],
min=vis["min"],
max=vis["max"],
palette=vis["palette"],
)
export_params = {
"image": export_image,
"description": vis["description"],
"scale": 30,
"region": geometry.getInfo()["coordinates"],
"fileFormat": "GeoTIFF",
"folder": folder_name,
"crs": "EPSG:4326",
"formatOptions": {"cloudOptimized": True},
}
task = ee.batch.Export.image.toDrive(**export_params)
task.start()
while task.status()["state"] in ["READY", "RUNNING"]:
print("Task status:", task.status())
time.sleep(30)
print("Task completed with state:", task.status()["state"])
except Exception as e:
print(f"Error processing and exporting data: {e}")
if __name__ == "__main__":
drive_service = initialize_services(service_account_file)
# Clean the folder in Google Drive
clean_folder(drive_service, folder_name)
process_data(drive_service, folder_name)
# Download files to the container
download_files(drive_service, folder_name, local_download_path)