File size: 12,249 Bytes
340bf36
 
 
 
 
 
 
0c1aca6
b79b7ed
73df89d
340bf36
 
 
 
9adb68a
6466238
340bf36
 
0c1aca6
 
 
340bf36
ad2b7fc
 
 
 
 
63069a3
688bb65
e5fda8d
ae37744
d3f808a
63069a3
 
688bb65
 
 
 
d3f808a
 
 
5dd5fea
d3f808a
 
c08d879
 
340bf36
 
 
 
 
 
 
 
 
 
 
 
e60c96a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d92cf6
9adb68a
340bf36
 
 
 
 
 
 
 
 
 
 
 
 
9adb68a
340bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
9adb68a
340bf36
 
 
 
 
 
 
 
 
9adb68a
340bf36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9adb68a
 
340bf36
 
2d92cf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87ac526
 
 
 
2d92cf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340bf36
 
02885ef
340bf36
 
 
 
 
 
 
02885ef
 
 
 
4a05666
ca3a50a
4a05666
 
 
 
 
 
 
2de87be
340bf36
2de87be
 
 
 
4a05666
2de87be
 
 
4a05666
2de87be
 
 
 
4a05666
2de87be
 
 
4a05666
2de87be
 
 
 
4a05666
2de87be
 
 
4a05666
2de87be
 
4a05666
 
 
 
2de87be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import ibis
from ibis import _
import ibis.selectors as s
from cng.utils import *
from cng.h3 import *
from minio import Minio
import streamlit as st
from datetime import datetime, timedelta
import streamlit
import re
duckdb_install_h3()

con = ibis.duckdb.connect(extensions = ["spatial", "h3"])
con.raw_sql("SET THREADS=100;")
set_secrets(con, "", "", "minio.carlboettiger.info")

# Get signed URLs to access license-controlled layers
key = st.secrets["MINIO_KEY"]
secret = st.secrets["MINIO_SECRET"]
client = Minio("minio.carlboettiger.info", key, secret)

pmtiles = "https://minio.carlboettiger.info/public-tpl-streamlit/nvme/public-tpl/conservation_almanac/tpl.pmtiles"
tpl_z8_url = "https://minio.carlboettiger.info/public-tpl-streamlit/nvme/public-tpl/conservation_almanac/z8/tpl_h3_z8.parquet"
landvote_z8_url = "https://minio.carlboettiger.info/public-tpl-streamlit/nvme/public-tpl/landvote/z8/landvote_z8.parquet"
tpl_table_url = "https://minio.carlboettiger.info/public-tpl-streamlit/nvme/public-tpl/conservation_almanac/tpl.parquet"
landvote_table_url = "https://minio.carlboettiger.info/public-tpl-streamlit/nvme/public-tpl/landvote/landvote_geom.parquet"
county_bounds_url = "https://minio.carlboettiger.info/public-census-streamlit/nvme/public-census/2024/county/2024_us_county.parquet"

mobi_z8_url ="https://s3-west.nrp-nautilus.io/public-mobi/mobi-species-richness-all/hex/h0=*/data_0.parquet"
svi_z8_url = "https://minio.carlboettiger.info/public-social-vulnerability/2022-tracts-h3-z8.parquet"
carbon_z8_url = "https://minio.carlboettiger.info/public-carbon/hex/us-tracts-vuln-total-carbon-2018-h8.parquet"
lower_chamber_z8_url = "s3://public-census-streamlit/nvme/public-census/2024/sld/lower/z8/**"
upper_chamber_z8_url = "s3://public-census-streamlit/nvme/public-census/2024/sld/upper/z8/**"

tpl_z8 = con.read_parquet(tpl_z8_url, table_name = 'conservation_almanac')
landvote_z8 = con.read_parquet(landvote_z8_url, table_name = 'landvote')
tpl_table = con.read_parquet(tpl_table_url)
landvote_table = con.read_parquet(landvote_table_url)
county_bounds = con.read_parquet(county_bounds_url)

# mobi_z8 = con.read_parquet(mobi_z8_url, table_name = 'mobi')
svi_z8 = con.read_parquet(svi_z8_url,table_name = 'svi')
carbon_z8 = con.read_parquet(carbon_z8_url, table_name = 'carbon')
lower_chamber_z8 = con.read_parquet(lower_chamber_z8_url, table_name = 'lower_chamber')
upper_chamber_z8 = con.read_parquet(upper_chamber_z8_url, table_name = 'upper_chamber')

states = (
    "All", "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut",
    "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
    "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan",
    "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire",
    "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
    "Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina",
    "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington",
    "West Virginia", "Wisconsin", "Wyoming"
)

state_codes = {
    "Alabama": "AL",
    "Alaska": "AK",
    "Arizona": "AZ",
    "Arkansas": "AR",
    "California": "CA",
    "Colorado": "CO",
    "Connecticut": "CT",
    "Delaware": "DE",
    "Florida": "FL",
    "Georgia": "GA",
    "Hawaii": "HI",
    "Idaho": "ID",
    "Illinois": "IL",
    "Indiana": "IN",
    "Iowa": "IA",
    "Kansas": "KS",
    "Kentucky": "KY",
    "Louisiana": "LA",
    "Maine": "ME",
    "Maryland": "MD",
    "Massachusetts": "MA",
    "Michigan": "MI",
    "Minnesota": "MN",
    "Mississippi": "MS",
    "Missouri": "MO",
    "Montana": "MT",
    "Nebraska": "NE",
    "Nevada": "NV",
    "New Hampshire": "NH",
    "New Jersey": "NJ",
    "New Mexico": "NM",
    "New York": "NY",
    "North Carolina": "NC",
    "North Dakota": "ND",
    "Ohio": "OH",
    "Oklahoma": "OK",
    "Oregon": "OR",
    "Pennsylvania": "PA",
    "Puerto Rico": "PR",
    "Rhode Island": "RI",
    "South Carolina": "SC",
    "South Dakota": "SD",
    "Tennessee": "TN",
    "Texas": "TX",
    "Utah": "UT",
    "Vermont": "VT",
    "Virginia": "VA",
    "Washington": "WA",
    "West Virginia": "WV",
    "Wisconsin": "WI",
    "Wyoming": "WY",
}


# Define color hex codes
darkblue = "#00008B"
blue = "#0096FF"
lightblue = "#ADD8E6"
darkgreen = "#006400"
grey = "#c4c3c3"
dark_grey = "#5a5a5a"
green = "#008000"
purple = "#800080"
darkred = "#8B0000"
orange = "#FFA500"
red = "#e64242"
yellow = "#FFFF00"
pink = '#FFC0CB'

style_options = {
    "Acquisition Cost":  
            ["interpolate",
                ['exponential', 1], 
                # ['linear'], 
                ["get", "amount"],
                    0,	"#fde725",
                    36000,	"#b4de2c",
                    93000,	"#6ccd59",
                    156500,	"#35b779",
                    240000,	"#1f9e89",
                    335000,	"#26828e",
                    500000,	"#31688e",
                    796314,	"#3e4a89",
                    1634000,	"#482878",
                    308461380,	"#430154",
                    ] 
            ,
    "Manager Type":  {
            'property': 'manager_type',
            'type': 'categorical',
            'stops': [
                ['FED', darkblue],
                ['STAT', blue],
                ['LOC', lightblue],
                ['DIST', darkgreen],
                ['UNK', dark_grey],
                ['JNT', pink],
                ['TRIB', purple],
                ['PVT', darkred],
                ['NGO', orange]
            ]
            },
    "Access": {
        'property': 'access_type',
        'type': 'categorical',
        'stops': [
            ['OA', green],
            ['XA', red],
            ['UK', dark_grey],
            ['RA', orange]
        ]
    },
    "Purpose": {
        'property': 'purpose_type',
        'type': 'categorical',
        'stops': [
            ['FOR', green],
            ['HIST', red],
            ['UNK', dark_grey],
            ['OTH', grey],
            ['FARM', yellow],
            ['REC', blue],
            ['ENV', purple],
            ['SCE', orange],
            ['RAN', pink]
        ]
    },
}

style_choice_columns = {'Manager Type': style_options['Manager Type']['property'],
              'Access' : style_options['Access']['property'],
              'Purpose': style_options['Purpose']['property'],
                'Acquisition Cost': 'amount',
                'Measure Cost': 'conservation_funds_approved',
             }

basemaps = ['CartoDB.DarkMatter', 'CartoDB.DarkMatterNoLabels', 
            'CartoDB.DarkMatterOnlyLabels','CartoDB.Positron', 
            'CartoDB.PositronNoLabels', 'CartoDB.PositronOnlyLabels',
            'CartoDB.Voyager', 'CartoDB.VoyagerLabelsUnder', 'CartoDB.VoyagerNoLabels',
            'CartoDB.VoyagerOnlyLabels', 'CyclOSM', 'Esri.NatGeoWorldMap',
            'Esri.WorldGrayCanvas', 'Esri.WorldPhysical', 'Esri.WorldShadedRelief',
            'Esri.WorldStreetMap', 'Gaode.Normal', 'Gaode.Satellite',
            'NASAGIBS.ASTER_GDEM_Greyscale_Shaded_Relief', 'NASAGIBS.BlueMarble', 
            'NASAGIBS.ModisTerraBands367CR','NASAGIBS.ModisTerraTrueColorCR',
            'NLCD 2021 CONUS Land Cover', 'OPNVKarte',
            'OpenStreetMap', 'OpenTopoMap', 'SafeCast',
            'TopPlusOpen.Color', 'TopPlusOpen.Grey', 'UN.ClearMap',
            'USGS Hydrography', 'USGS.USImagery', 'USGS.USImageryTopo',
            'USGS.USTopo']

# legend_labels = {
#     "Acquisition Cost":  [],
#     "Manager Type":  
#                 ['Federal', 'State', 'Local','District','Unknown','Joint','Tribal','Private', 'NGO'],
#     "Access": 
#             ['Open Access', 'Closed','Unknown','Restricted'],
#     "Purpose": 
#     ['Forestry','Historical','Unknown','Other','Farming','Recreation','Environment','Scenic','RAN'],
# }

help_message = '''
- ❌ Safari/iOS not fully supported. For Safari/iOS users, change the **Leafmap module** from MapLibre to Folium in **(Map Settings)** below. 
- πŸ“Š Use this sidebar to color-code the map by different attributes **(Group by)**
'''

#maplibregl tooltip 
tooltip_cols = ['fid','state','site','sponsor','program','county','year','manager',
                'amount','acres']
tooltip_template = "<br>".join([f"{col}: {{{{ {col} }}}}" for col in tooltip_cols])


error_messages = {
    "bad_request": lambda llm, e, tb_str: f"""
**Error – LLM Unavailable** 

*The LLM you selected `{llm}` is no longer available. Please select a different model.*

**Error Details:**
`{type(e)}: {e}`

""",

    "internal_server_error": lambda llm, e, tb_str: f"""
**Error – LLM Temporarily Unavailable**

The LLM you selected `{llm}` is currently down due to maintenance or provider outages. It may remain offline for several hours.

**Please select a different model or try again later.**

**Error Details:**
`{type(e)}: {e}`

""",

    "unexpected_llm_error": lambda prompt, e, tb_str: f"""
🐞 **BUG: Unexpected Error in Application**

An error occurred while processing your query:

> "{prompt}"

**Error Details:**
`{type(e)}: {e}`

Traceback:

```{tb_str}```
---

🚨 **Help Us Improve!**

Please help us fix this issue by reporting it on GitHub:
[πŸ“„ Report this issue](https://github.com/boettiger-lab/CBN-taskforce/issues)

Include the query you ran and any other relevant details. Thanks!
""",

    "unexpected_error": lambda e, tb_str: f"""
🐞 **BUG: Unexpected Error in Application**


**Error Details:**
`{type(e)}: {e}`

Traceback:

```{tb_str}```

---

🚨 **Help Us Improve!**

Please help us fix this issue by reporting it on GitHub:
[πŸ“„ Report this issue](https://github.com/boettiger-lab/CBN-taskforce/issues)

Include the steps you took to get this message and any other details that might help us debug. Thanks!
"""
}

from langchain_openai import ChatOpenAI
import streamlit as st
from langchain_openai.chat_models.base import BaseChatOpenAI

## dockerized streamlit app wants to read from os.getenv(), otherwise use st.secrets
import os
api_key = os.getenv("NRP_API_KEY")
if api_key is None:
    api_key = st.secrets["NRP_API_KEY"]

openrouter_api = os.getenv("OPENROUTER_API_KEY")
if openrouter_api is None:
    openrouter_api = st.secrets["OPENROUTER_API_KEY"]

openrouter_endpoint="https://openrouter.ai/api/v1"
nrp_endpoint="https://ellm.nrp-nautilus.io/v1"
# don't use a provider that collects data
data_policy = {
    "provider": {
        "data_collection": "deny"
    }
}


llm_options = {
     "gemma-4-e4b-it": ChatOpenAI(
        model="gemma-4-e4b",
        api_key=api_key,
        base_url=nrp_endpoint,
        temperature=0,
        model_kwargs={
            "extra_body": {"chat_template_kwargs": {"thinking": False}}
        }
    ),
    "olmo-3.1-32b": ChatOpenAI(
        model="olmo",
        api_key=api_key,
        base_url=nrp_endpoint,
        temperature=0,
        model_kwargs={
            "extra_body": {"chat_template_kwargs": {"thinking": False}}
        }
    ),
    "gemma-4-31b-it": ChatOpenAI(
        model="gemma",
        api_key=api_key,
        base_url=nrp_endpoint,
        temperature=0,
        model_kwargs={
            "extra_body": {"chat_template_kwargs": {"thinking": False}}
        }
    ),
    "gpt-oss-120b": ChatOpenAI(
        model="gpt-oss",
        api_key=api_key,
        base_url=nrp_endpoint,
        temperature=0
    ),
    "minimax-m2": ChatOpenAI(
        model="minimax-m2",
        api_key=api_key,
        base_url=nrp_endpoint,
        temperature=0,
        model_kwargs={
            "extra_body": {"chat_template_kwargs": {"thinking": False}}
        }
    ),
    "kimi-k2.5": ChatOpenAI(
        model="kimi",
        api_key=api_key,
        base_url=nrp_endpoint,
        temperature=0,
        model_kwargs={
            "extra_body": {"chat_template_kwargs": {"thinking": False}}
        }
    ),
     "dolphin-mistral-24b-venice-edition:free": ChatOpenAI(
        model="cognitivecomputations/dolphin-mistral-24b-venice-edition:free",
        api_key=openrouter_api,
        base_url=openrouter_endpoint,
        temperature=0,
        extra_body=data_policy
    ),   
    }