Repository navigation
Expand file tree
/
Copy pathParser.py
More file actions
280 lines (208 loc) · 7.49 KB
/
Copy pathParser.py
File metadata and controls
280 lines (208 loc) · 7.49 KB
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
# ============================================================
# ArcGIS → Pandas → CSV → Amazon S3 Pipeline
# CSU Hackathon Fruit Fly / Trade Datasets
# ============================================================
# If needed, run once:
# !pip install requests pandas boto3
import os
import time
import json
import requests
import pandas as pd
import boto3
# ============================================================
# 1. CONFIGURATION
# ============================================================
# ArcGIS REST portal
PORTAL = "https://www.arcgis.com/sharing/rest"
# Your ArcGIS login
# Best practice: store these as environment variables instead of hardcoding
ARCGIS_USERNAME = "csuguest21"
ARCGIS_PASSWORD = "CSUguest21!#"
# Your S3 bucket
S3_BUCKET = "sagemaker-us-west-2-891377146031"
# S3 folder prefix
S3_PREFIX = "csu-hackathon/raw"
# ArcGIS FeatureServer URLs
FRUIT_FLY_URL = (
"https://services1.arcgis.com/KNdRU5cN6ENqCTjk/arcgis/rest/services/"
"PPQ%20Fruit%20Fly%20Detections%20Summary%20Feature%20Layer/FeatureServer"
)
DOMESTIC_URL = (
"https://services1.arcgis.com/KNdRU5cN6ENqCTjk/arcgis/rest/services/"
"PPQ%20Domestic%20Segments%20Feature%20Layer/FeatureServer"
)
INTERNATIONAL_URL = (
"https://services1.arcgis.com/KNdRU5cN6ENqCTjk/arcgis/rest/services/"
"PPQ%20International%20Segments%20Feature%20Layer/FeatureServer"
)
# Layer IDs are 0 based on your inspection
LAYER_ID = 0
# ArcGIS usually limits records per request
BATCH_SIZE = 2000
# ============================================================
# 2. GENERATE ARCGIS TOKEN
# ============================================================
def generate_token(username, password):
"""
Generates an ArcGIS token using username/password auth.
This token is required for private or group-shared Feature Services.
"""
url = f"{PORTAL}/generateToken"
params = {
"f": "json",
"username": username,
"password": password,
"client": "referer",
"referer": "https://www.arcgis.com",
"expiration": 120
}
response = requests.post(url, data=params, timeout=60)
data = response.json()
if "error" in data:
raise RuntimeError(f"Token generation failed: {data['error']}")
print("ArcGIS token generated successfully.")
return data["token"]
TOKEN = generate_token(ARCGIS_USERNAME, ARCGIS_PASSWORD)
# ============================================================
# 3. ARCGIS REQUEST HELPER
# ============================================================
def arcgis_get(url, params=None, timeout=120):
"""
Makes a GET request to ArcGIS REST API.
Automatically adds f=json and your ArcGIS token.
Raises a useful error if ArcGIS returns an error response.
"""
params = params.copy() if params else {}
params["f"] = "json"
params["token"] = TOKEN
response = requests.get(url, params=params, timeout=timeout)
response.raise_for_status()
try:
data = response.json()
except json.JSONDecodeError:
raise RuntimeError(f"ArcGIS returned non-JSON response: {response.text[:500]}")
if "error" in data:
raise RuntimeError(f"ArcGIS API error: {data['error']}")
return data
# ============================================================
# 4. INSPECT FEATURE SERVICE
# ============================================================
def inspect_service(name, service_url):
"""
Prints available layers/tables for a FeatureServer.
Useful for confirming layer IDs before downloading.
"""
print("\n" + "=" * 70)
print(f"Inspecting: {name}")
print("=" * 70)
info = arcgis_get(service_url)
print("Layers:")
for layer in info.get("layers", []):
print(f" {layer['id']} - {layer['name']}")
print("Tables:")
for table in info.get("tables", []):
print(f" {table['id']} - {table['name']}")
return info
# ============================================================
# 5. FETCH FEATURE LAYER INTO DATAFRAME
# ============================================================
def fetch_layer_to_df(service_url, layer_id=0, where="1=1", batch_size=2000):
"""
Downloads all records from an ArcGIS Feature Layer into a pandas DataFrame.
Uses pagination so it can handle large datasets.
"""
query_url = f"{service_url}/{layer_id}/query"
# First get total record count
count_data = arcgis_get(query_url, {
"where": where,
"returnCountOnly": "true"
})
total = count_data.get("count", 0)
print(f"Total records to fetch: {total:,}")
all_records = []
offset = 0
while offset < total:
data = arcgis_get(query_url, {
"where": where,
"outFields": "*",
"returnGeometry": "false",
"resultOffset": offset,
"resultRecordCount": batch_size,
"orderByFields": "OBJECTID"
})
features = data.get("features", [])
records = [feature["attributes"] for feature in features]
if not records:
print("No more records returned. Stopping.")
break
all_records.extend(records)
print(f"Fetched {len(all_records):,} / {total:,}")
offset += batch_size
time.sleep(0.2)
df = pd.DataFrame(all_records)
# Basic cleanup
df = df.dropna(axis=1, how="all")
df = df.convert_dtypes()
print(f"Final DataFrame shape: {df.shape[0]:,} rows × {df.shape[1]:,} columns")
return df
# ============================================================
# 6. SAVE LOCALLY AND UPLOAD TO S3
# ============================================================
def save_and_upload_df(df, local_filename, s3_bucket, s3_key):
"""
Saves a DataFrame as a local CSV and uploads it to Amazon S3.
"""
df.to_csv(local_filename, index=False)
print(f"Saved locally: {local_filename}")
s3 = boto3.client("s3")
s3.upload_file(local_filename, s3_bucket, s3_key)
print(f"Uploaded to: s3://{s3_bucket}/{s3_key}")
# ============================================================
# 7. RUN FULL PIPELINE
# ============================================================
datasets = {
"fruit_fly_detections": {
"url": FRUIT_FLY_URL,
"where": "1=1",
"filename": "fruit_fly_detections.csv"
},
"domestic_segments": {
"url": DOMESTIC_URL,
"where": "1=1",
"filename": "domestic_segments.csv"
},
# For fruit fly import risk, this filters to foreign → United States routes
"international_inbound_segments": {
"url": INTERNATIONAL_URL,
"where": "ORIGIN_COUNTRY <> 'US' AND DEST_COUNTRY = 'US'",
"filename": "international_inbound_segments.csv"
},
# Optional: full international dataset, both directions
"international_all_segments": {
"url": INTERNATIONAL_URL,
"where": "1=1",
"filename": "international_all_segments.csv"
}
}
all_dataframes = {}
for dataset_name, config in datasets.items():
print("\n" + "#" * 80)
print(f"STARTING DATASET: {dataset_name}")
print("#" * 80)
inspect_service(dataset_name, config["url"])
df = fetch_layer_to_df(
service_url=config["url"],
layer_id=LAYER_ID,
where=config["where"],
batch_size=BATCH_SIZE
)
all_dataframes[dataset_name] = df
s3_key = f"{S3_PREFIX}/{config['filename']}"
save_and_upload_df(
df=df,
local_filename=config["filename"],
s3_bucket=S3_BUCKET,
s3_key=s3_key
)
print("\n✅ All datasets downloaded and uploaded to S3.")