edgarodriguez commited on
Commit
083ab2a
·
verified ·
1 Parent(s): 6a2b479

Upload 6 files

Browse files
Files changed (6) hide show
  1. Dockerfile +57 -9
  2. README.md +38 -12
  3. assistant.R +343 -0
  4. depth_interactive_map_alpha.R +110 -28
  5. entrypoint.sh +24 -0
  6. styles.css +44 -0
Dockerfile CHANGED
@@ -4,29 +4,77 @@ FROM rocker/geospatial:4.4
4
 
5
  # DuckDB lives on the edgarodriguez/depth_alpha dataset (public); baked in at
6
  # build. Override with: docker build --build-arg DDB_URL=... -t depth-hf .
7
- # If the dataset is ever made PRIVATE, add a build secret instead of an ARG:
8
- # RUN --mount=type=secret,id=hf_token curl -H "Authorization: Bearer \
9
- # $(cat /run/secrets/hf_token)" -fL "${DDB_URL}" -o /app/depth_mexico.duckdb
10
  ARG DDB_URL=https://huggingface.co/datasets/edgarodriguez/depth_alpha/resolve/main/depth_mexico.duckdb
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  RUN install2.r --error --skipinstalled --ncpus 4 \
13
  shiny bslib DBI duckdb dplyr jsonlite htmltools glue writexl ggplot2 stringr httr2 \
 
14
  && R -e "install.packages('mapgl', repos = c('https://walkerke.r-universe.dev', 'https://cloud.r-project.org'))" \
15
- && R -e "library(mapgl); library(duckdb); library(sf); library(shiny); library(httr2)"
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  WORKDIR /app
18
- COPY depth_interactive_map_alpha.R helpers.R styles.css ./
19
 
20
- # Bake the DuckDB into the image (build-time download).
 
 
 
 
 
 
 
21
  RUN curl -fL "${DDB_URL}" -o /app/depth_mexico.duckdb \
22
  && test -s /app/depth_mexico.duckdb \
23
  && ls -lh /app/depth_mexico.duckdb
24
 
25
- # HF Spaces runs the container as a non-root user -- make /app world-readable.
26
- RUN chmod -R a+rX /app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  ENV DEPTH_DDB_PATH=/app/depth_mexico.duckdb \
29
  PORT=7860
30
 
31
  EXPOSE 7860
32
- CMD ["Rscript", "depth_interactive_map_alpha.R"]
 
4
 
5
  # DuckDB lives on the edgarodriguez/depth_alpha dataset (public); baked in at
6
  # build. Override with: docker build --build-arg DDB_URL=... -t depth-hf .
 
 
 
7
  ARG DDB_URL=https://huggingface.co/datasets/edgarodriguez/depth_alpha/resolve/main/depth_mexico.duckdb
8
 
9
+ # RAG index (corpus chunk text + local embeddings) for the AI assistant. The
10
+ # corpus is copyright-derived, so it lives on a PRIVATE dataset and is pulled
11
+ # with a BuildKit secret (id=hf_token) -- never from a public source. If the
12
+ # secret/dataset are absent the build still succeeds; the assistant just stays
13
+ # offline until rag_chunks.parquet is present.
14
+ ARG RAG_URL=https://huggingface.co/datasets/edgarodriguez/depth_rag/resolve/main/rag_chunks.parquet
15
+
16
+ # Small local models served in-container by Ollama (no external inference).
17
+ ARG CHAT_MODEL=qwen2.5:3b
18
+ ARG EMBED_MODEL=nomic-embed-text
19
+
20
+ ENV OLLAMA_MODELS=/app/.ollama \
21
+ DEPTH_OLLAMA_URL=http://127.0.0.1:11434 \
22
+ DEPTH_LLM_MODEL=${CHAT_MODEL} \
23
+ DEPTH_EMBED_MODEL=${EMBED_MODEL} \
24
+ DEPTH_RAG_PARQUET=/app/rag_chunks.parquet
25
+
26
+ # R packages. Adds ellmer (chat + tool calling), shinychat (streaming chat UI)
27
+ # and arrow (read the embeddings Parquet) on top of the map's deps.
28
  RUN install2.r --error --skipinstalled --ncpus 4 \
29
  shiny bslib DBI duckdb dplyr jsonlite htmltools glue writexl ggplot2 stringr httr2 \
30
+ ellmer shinychat arrow \
31
  && R -e "install.packages('mapgl', repos = c('https://walkerke.r-universe.dev', 'https://cloud.r-project.org'))" \
32
+ && R -e "library(mapgl); library(duckdb); library(sf); library(shiny); library(httr2); library(ellmer); library(shinychat)"
33
+
34
+ # Ollama runtime + bake the chat and embedding models into the image so the
35
+ # first request needs no network (HF runtime is effectively offline). This adds
36
+ # ~2.3GB to the image and a few minutes to the build.
37
+ RUN curl -fsSL https://ollama.com/install.sh | sh \
38
+ && mkdir -p "$OLLAMA_MODELS" \
39
+ && ( ollama serve & srv=$!; \
40
+ for i in $(seq 1 30); do curl -sf http://127.0.0.1:11434/api/tags >/dev/null 2>&1 && break; sleep 1; done; \
41
+ ollama pull "${CHAT_MODEL}" && ollama pull "${EMBED_MODEL}"; \
42
+ kill $srv ) \
43
+ && chmod -R a+rwX "$OLLAMA_MODELS"
44
 
45
  WORKDIR /app
 
46
 
47
+ # Pre-bake the DuckDB vss extension under the runtime HOME (/app) so the
48
+ # assistant's vector search works offline; the code falls back to core
49
+ # list_cosine_distance if it is ever missing.
50
+ RUN HOME=/app R -e "library(duckdb); con <- dbConnect(duckdb()); DBI::dbExecute(con, 'INSTALL vss; LOAD vss;'); DBI::dbDisconnect(con, shutdown=TRUE); cat('vss installed\n')"
51
+
52
+ COPY depth_interactive_map_alpha.R assistant.R helpers.R styles.css entrypoint.sh ./
53
+
54
+ # Bake the DuckDB map data (public dataset, build-time download).
55
  RUN curl -fL "${DDB_URL}" -o /app/depth_mexico.duckdb \
56
  && test -s /app/depth_mexico.duckdb \
57
  && ls -lh /app/depth_mexico.duckdb
58
 
59
+ # Bake the private RAG index (best-effort; never fails the build).
60
+ RUN --mount=type=secret,id=hf_token \
61
+ if [ -f /run/secrets/hf_token ]; then \
62
+ ( curl -fL -H "Authorization: Bearer $(cat /run/secrets/hf_token)" "${RAG_URL}" -o /app/rag_chunks.parquet \
63
+ && test -s /app/rag_chunks.parquet \
64
+ && echo "[build] RAG index baked: $(ls -lh /app/rag_chunks.parquet | awk '{print $5}')" ) \
65
+ || echo "[build] RAG fetch failed -> assistant offline until rag_chunks.parquet is provided"; \
66
+ else \
67
+ echo "[build] no hf_token secret -> assistant offline until rag_chunks.parquet is provided"; \
68
+ fi
69
+
70
+ # HF Spaces runs the container as a non-root user -- make /app world-readable,
71
+ # and the Ollama dir world-writable (runtime key generation + model cache).
72
+ RUN chmod +x /app/entrypoint.sh \
73
+ && chmod -R a+rX /app \
74
+ && chmod -R a+rwX /app/.ollama
75
 
76
  ENV DEPTH_DDB_PATH=/app/depth_mexico.duckdb \
77
  PORT=7860
78
 
79
  EXPOSE 7860
80
+ ENTRYPOINT ["/app/entrypoint.sh"]
README.md CHANGED
@@ -1,17 +1,18 @@
1
  ---
2
- title: DEPTH. Transit Migrant Risk Index
3
- emoji: 🌍
4
- colorFrom: gray
5
- colorTo: blue
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
- short_description: Prototype for spatial visualization tool for DEPTH projec
10
  ---
11
 
12
  # DEPTH Risk Map
13
 
14
- Interactive migration-risk map for Mexico (for prototype use only. data may contain errors)
 
 
15
 
16
  ## How this Space works
17
 
@@ -19,21 +20,46 @@ Interactive migration-risk map for Mexico (for prototype use only. data may cont
19
  packages, and downloads `depth_mexico.duckdb` from the
20
  [`edgarodriguez/depth_alpha`](https://huggingface.co/datasets/edgarodriguez/depth_alpha)
21
  dataset at build time (baked into the image).
22
- - The Shiny app (`.R`) opens that DuckDB
23
- read-only and serves on `0.0.0.0:7860`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  ## Files
26
 
27
  | File | Role |
28
  |---|---|
29
- | `.R` | Shiny app (HF build) |
 
30
  | `helpers.R` | DuckDB connection + formatting helpers |
31
  | `styles.css` | App stylesheet |
32
- | `Dockerfile` | Image build + DuckDB bake-in |
 
33
 
34
  ## Updating
35
 
36
  The app database is not stored in this Space. To refresh data, update
37
  `depth_mexico.duckdb` in the `edgarodriguez/depth_alpha` dataset and rebuild
38
- (Factory rebuild). App-logic changes are made upstream in `v9`, then this file
39
- is regenerated from it.
 
 
1
  ---
2
+ title: DEPTH Risk Map
3
+ emoji: 🗺️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
 
9
  ---
10
 
11
  # DEPTH Risk Map
12
 
13
+ Interactive migration-risk map for Mexico, developed by the University of
14
+ Nottingham's Rights Lab. Humanitarian, violence and infrastructure indicators
15
+ overlaid on a rHEALPix hierarchical spatial grid.
16
 
17
  ## How this Space works
18
 
 
20
  packages, and downloads `depth_mexico.duckdb` from the
21
  [`edgarodriguez/depth_alpha`](https://huggingface.co/datasets/edgarodriguez/depth_alpha)
22
  dataset at build time (baked into the image).
23
+ - The Shiny app (`depth_interactive_map_alpha.R`) opens that DuckDB read-only
24
+ and serves on `0.0.0.0:7860`.
25
+ - A local AI assistant runs **entirely inside the container**: Ollama serves a
26
+ small model (`qwen2.5:3b` + `nomic-embed-text`), baked into the image. The app
27
+ answers questions grounded in the research corpus (RAG over a DuckDB vector
28
+ search) and the live map data (a few read-only tools). No prompt, document or
29
+ database row ever leaves the Space. `entrypoint.sh` starts Ollama, then Rscript.
30
+
31
+ ## AI assistant setup
32
+
33
+ The assistant needs a private RAG index (`rag_chunks.parquet`, corpus chunk
34
+ text + local embeddings). Because the corpus is copyright-derived it is **not**
35
+ in this Space and **not** on the public dataset:
36
+
37
+ 1. Build the index locally: `Rscript R/94_build_rag_embeddings.R` (with Ollama
38
+ running and `nomic-embed-text` pulled).
39
+ 2. Upload `rag_chunks.parquet` to a **private** HF dataset (e.g.
40
+ `edgarodriguez/depth_rag`).
41
+ 3. Add a Space **secret** named `hf_token` (a token that can read that dataset).
42
+ The Dockerfile pulls the index with `--mount=type=secret,id=hf_token`.
43
+
44
+ If the secret/dataset are absent the image still builds; the assistant simply
45
+ shows an "offline" state until `rag_chunks.parquet` is present. On the free
46
+ CPU Space, replies take ~10-40s -- upgrade to a GPU Space for speed.
47
 
48
  ## Files
49
 
50
  | File | Role |
51
  |---|---|
52
+ | `depth_interactive_map_alpha.R` | Shiny app (HF build of v9) |
53
+ | `assistant.R` | Local AI assistant: RAG search, system prompt, read-only tools |
54
  | `helpers.R` | DuckDB connection + formatting helpers |
55
  | `styles.css` | App stylesheet |
56
+ | `entrypoint.sh` | Starts Ollama, then the Shiny app |
57
+ | `Dockerfile` | Image build + DuckDB/RAG/model bake-in |
58
 
59
  ## Updating
60
 
61
  The app database is not stored in this Space. To refresh data, update
62
  `depth_mexico.duckdb` in the `edgarodriguez/depth_alpha` dataset and rebuild
63
+ (Factory rebuild). To refresh the assistant's corpus, rebuild
64
+ `rag_chunks.parquet` and re-upload it to the private dataset. App-logic changes
65
+ are made upstream in `v9`, then this file is regenerated from it.
assistant.R ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- Local AI assistant for the DEPTH map ------------------------------------
2
+ # Fully in-container: an Ollama-served small LLM (Qwen2.5) answers questions
3
+ # grounded in (a) the docs/md research corpus via local-embedding RAG over a
4
+ # DuckDB vector search, and (b) the live map data via a few constrained,
5
+ # read-only tools (ellmer tool calling). Nothing leaves the container.
6
+ #
7
+ # Sourced into the app's global env AFTER helpers.R and WEB_SPEC are defined.
8
+ # Defines functions only -- no side effects, no hard ellmer/shinychat import --
9
+ # so the app still runs when the AI stack is absent (panel shows a disabled
10
+ # state via assistant_available()).
11
+ # -----------------------------------------------------------------------------
12
+
13
+ `%||%` <- function(x, y) if (is.null(x) || length(x) == 0) y else x
14
+
15
+ # --- Config -------------------------------------------------------------------
16
+ assistant_config <- function() {
17
+ rag_default <- if (file.exists("/app/rag_chunks.parquet")) {
18
+ "/app/rag_chunks.parquet"
19
+ } else {
20
+ "data/export/web/rag_chunks.parquet"
21
+ }
22
+ list(
23
+ host = Sys.getenv("DEPTH_OLLAMA_URL", "http://127.0.0.1:11434"),
24
+ chat_model = Sys.getenv("DEPTH_LLM_MODEL", "qwen2.5:3b"),
25
+ embed_model = Sys.getenv("DEPTH_EMBED_MODEL", "nomic-embed-text"),
26
+ rag_path = Sys.getenv("DEPTH_RAG_PARQUET", rag_default)
27
+ )
28
+ }
29
+
30
+ # TRUE only when every piece is present: both packages, the baked index, and a
31
+ # reachable Ollama server. Used to gate the UI and the server wiring.
32
+ assistant_available <- function(cfg = assistant_config()) {
33
+ if (!requireNamespace("ellmer", quietly = TRUE)) return(FALSE)
34
+ if (!requireNamespace("shinychat", quietly = TRUE)) return(FALSE)
35
+ if (!file.exists(cfg$rag_path)) return(FALSE)
36
+ ok <- tryCatch(
37
+ httr2::request(cfg$host) |>
38
+ httr2::req_url_path("/api/tags") |>
39
+ httr2::req_timeout(3) |>
40
+ httr2::req_perform() |>
41
+ httr2::resp_status(),
42
+ error = function(e) NA_integer_
43
+ )
44
+ isTRUE(ok == 200L)
45
+ }
46
+
47
+ # --- Embedding + retrieval ----------------------------------------------------
48
+ ollama_embed <- function(text, cfg = assistant_config()) {
49
+ resp <- tryCatch(
50
+ httr2::request(cfg$host) |>
51
+ httr2::req_url_path("/api/embed") |>
52
+ httr2::req_body_json(list(model = cfg$embed_model, input = text)) |>
53
+ httr2::req_timeout(120) |>
54
+ httr2::req_perform(),
55
+ error = function(e) NULL
56
+ )
57
+ if (is.null(resp)) return(numeric(0))
58
+ out <- httr2::resp_body_json(resp, simplifyVector = FALSE)
59
+ if (is.null(out$embeddings) || length(out$embeddings) == 0) return(numeric(0))
60
+ as.numeric(unlist(out$embeddings[[1]]))
61
+ }
62
+
63
+ # Decide once whether the vss extension (array_cosine_distance) is available;
64
+ # fall back to DuckDB's core list_cosine_distance otherwise. Both are exact
65
+ # brute-force cosine -- fine for a few thousand chunks.
66
+ .assist_cache <- new.env(parent = emptyenv())
67
+
68
+ .rag_dist_clause <- function(con, vec_lit, d) {
69
+ mode <- .assist_cache$dist_mode
70
+ if (is.null(mode)) {
71
+ ok <- tryCatch({
72
+ DBI::dbExecute(con, "INSTALL vss; LOAD vss;")
73
+ DBI::dbGetQuery(con,
74
+ "SELECT array_cosine_distance(CAST([1.0,2.0] AS FLOAT[2]), CAST([1.0,2.0] AS FLOAT[2])) AS d")
75
+ TRUE
76
+ }, error = function(e) FALSE)
77
+ mode <- if (isTRUE(ok)) "vss" else "list"
78
+ .assist_cache$dist_mode <- mode
79
+ message("[assist] vector search mode: ", mode)
80
+ }
81
+ if (mode == "vss") {
82
+ glue::glue("array_cosine_distance(CAST(embedding AS FLOAT[{d}]), CAST({vec_lit} AS FLOAT[{d}]))")
83
+ } else {
84
+ glue::glue("list_cosine_distance(embedding, CAST({vec_lit} AS DOUBLE[]))")
85
+ }
86
+ }
87
+
88
+ # Embed the question (with the nomic query prefix) and return the top-k corpus
89
+ # passages as a single context string with [source] tags for citation.
90
+ rag_search <- function(con, query, cfg = assistant_config(), k = 5) {
91
+ if (is.null(con) || !file.exists(cfg$rag_path)) return("")
92
+ qvec <- ollama_embed(paste0("search_query: ", query), cfg)
93
+ if (length(qvec) == 0) return("")
94
+ vec_lit <- paste0("[", paste(format(qvec, scientific = FALSE, trim = TRUE),
95
+ collapse = ","), "]")
96
+ dist <- .rag_dist_clause(con, vec_lit, length(qvec))
97
+ sql <- glue::glue(
98
+ "SELECT source_title, folder, chunk_text, {dist} AS dist
99
+ FROM read_parquet('{path}')
100
+ ORDER BY dist ASC
101
+ LIMIT {k}",
102
+ path = cfg$rag_path, k = as.integer(k)
103
+ )
104
+ res <- tryCatch(DBI::dbGetQuery(con, sql), error = function(e) {
105
+ message("[assist] rag_search: ", conditionMessage(e)); NULL
106
+ })
107
+ if (is.null(res) || nrow(res) == 0) return("")
108
+ paste(sprintf("[%s] %s", res$source_title, res$chunk_text), collapse = "\n\n")
109
+ }
110
+
111
+ # --- Grounding text from WEB_SPEC --------------------------------------------
112
+ # Walk the accordion (label + tooltip + source) into a compact data dictionary
113
+ # the model can read. Stays in lockstep with the UI -- no separate codebook.
114
+ assistant_indicator_catalog_txt <- function() {
115
+ if (!exists("WEB_SPEC")) return("")
116
+ out <- character(0)
117
+ for (grp in WEB_SPEC$accordion) {
118
+ layer_items <- Filter(function(it) identical(it$kind, "layer"), grp$items)
119
+ if (length(layer_items) == 0) next
120
+ out <- c(out, paste0("## ", grp$label))
121
+ for (it in layer_items) {
122
+ tip <- it$tooltip
123
+ body <- if (is.list(tip)) paste(c(tip$body, tip$meta), collapse = " ")
124
+ else tip %||% ""
125
+ out <- c(out, sprintf("- %s: %s", it$label, body))
126
+ }
127
+ }
128
+ paste(out, collapse = "\n")
129
+ }
130
+
131
+ assistant_system_prompt <- function(catalog_txt) {
132
+ paste0(
133
+ "You are the research assistant for DEPTH, an interactive map of migration ",
134
+ "risk in Mexico built by the University of Nottingham Rights Lab. The map ",
135
+ "overlays humanitarian, violence and infrastructure indicators on a ",
136
+ "hierarchical grid of Mexico.\n\n",
137
+ "How to answer:\n",
138
+ "- For ANY number, ranking, count or aggregation you MUST call a tool. ",
139
+ "Never invent, estimate or recall figures from memory.\n",
140
+ "- When the user refers to 'the selection', 'this area', 'the area I drew', ",
141
+ "'here', or 'visible', call describe_selection first to learn the scope.\n",
142
+ "- Use the <context> document excerpts supplied with the user's message for ",
143
+ "background, definitions and qualitative explanation. Cite the document ",
144
+ "title in square brackets when you rely on it.\n",
145
+ "- If the data and documents do not cover the question, say so plainly. ",
146
+ "Do not speculate.\n",
147
+ "- Reply in the user's language (English or Spanish). Be concise: a few ",
148
+ "sentences or a short list.\n\n",
149
+ "Indicators available on the map (label: meaning and source):\n",
150
+ catalog_txt
151
+ )
152
+ }
153
+
154
+ # Prepend retrieved corpus context to the raw question (the UI still shows the
155
+ # raw question; only the model sees the augmented version).
156
+ assistant_user_turn <- function(question, context_txt) {
157
+ if (is.null(context_txt) || !nzchar(context_txt)) return(question)
158
+ paste0("<context>\n", context_txt, "\n</context>\n\n", question)
159
+ }
160
+
161
+ # --- Tool back-ends (operate on a plain snapshot env + read-only con) ---------
162
+ # `state` is a non-reactive environment the server keeps in sync with rv, so
163
+ # tools can be called outside a reactive context during async streaming.
164
+
165
+ .IND_LABELS <- c(
166
+ homicidio = "homicide rate (per 100k)",
167
+ robo = "robbery rate (per 100k)",
168
+ secuestro = "kidnapping rate (per 100k)",
169
+ trafico_menores = "child-trafficking rate (per 100k)",
170
+ trata_personas = "human-trafficking rate (per 100k)",
171
+ desap_n = "disappeared and not located (count)",
172
+ pam_n = "irregular-migration (PAM) events (count)"
173
+ )
174
+ .POINT_TO_COUNT <- c(migrants = "n_incidents", graves = "n_graves",
175
+ infra = "n_facilities", ocved = "ocved_n", ged = "n_ged")
176
+
177
+ assistant_selection_summary <- function(state) {
178
+ cnt <- state$counts %||% list()
179
+ scope <- if (isTRUE(state$is_national)) {
180
+ "No specific area is selected; national totals are in view."
181
+ } else {
182
+ glue::glue("Current selection: {cnt$n_mun %||% '0'} municipalities.")
183
+ }
184
+ glue::glue(
185
+ "{scope} ",
186
+ "Migrant-death incidents: {cnt$n_incidents %||% '0'} ",
187
+ "({cnt$n_fatalities %||% '0'} recorded deaths). ",
188
+ "Clandestine graves: {cnt$n_graves %||% '0'}. ",
189
+ "Support facilities: {cnt$n_facilities %||% '0'}. ",
190
+ "OCVED violence events: {cnt$ocved_n %||% '0'}. ",
191
+ "GED conflict events: {cnt$n_ged %||% '0'}. ",
192
+ "Disappeared (sum): {cnt$n_desap %||% '0'}. ",
193
+ "Irregular-migration (PAM) events: {cnt$n_pam %||% '0'}."
194
+ )
195
+ }
196
+
197
+ assistant_count_points <- function(state, layer) {
198
+ key <- .POINT_TO_COUNT[[layer]]
199
+ if (is.null(key)) return(paste0("Unknown layer: ", layer))
200
+ val <- state$counts[[key]] %||% "0"
201
+ scope <- if (isTRUE(state$is_national)) "across Mexico" else "in the current selection"
202
+ extra <- if (identical(layer, "migrants")) {
203
+ glue::glue(" ({state$counts$n_fatalities %||% '0'} recorded deaths)")
204
+ } else ""
205
+ glue::glue("{val} {layer} {scope}{extra}.")
206
+ }
207
+
208
+ assistant_aggregate <- function(con, state, indicator, statistic = "mean") {
209
+ if (!indicator %in% names(.IND_LABELS)) return(paste0("Unknown indicator: ", indicator))
210
+ if (!statistic %in% c("mean", "sum", "max", "min")) statistic <- "mean"
211
+ lab <- .IND_LABELS[[indicator]]
212
+
213
+ # Selection path: aggregate the in-memory municipalities (matches the sidebar).
214
+ if (!isTRUE(state$is_national) && !is.null(state$mun_df) &&
215
+ nrow(state$mun_df) > 0 && indicator %in% names(state$mun_df)) {
216
+ vals <- suppressWarnings(as.numeric(state$mun_df[[indicator]]))
217
+ vals <- vals[is.finite(vals)]
218
+ if (length(vals) == 0) return(glue::glue("No {lab} values in the current selection."))
219
+ res <- switch(statistic, mean = mean(vals), sum = sum(vals),
220
+ max = max(vals), min = min(vals))
221
+ return(glue::glue(
222
+ "{statistic} of {lab} across {nrow(state$mun_df)} selected municipalities: {round(res, 2)}."))
223
+ }
224
+
225
+ # National path: a single bounded aggregate query (indicator is allow-listed).
226
+ if (is.null(con)) return("No database connection available.")
227
+ if (indicator %in% c("desap_n", "pam_n")) {
228
+ inner_tbl <- if (indicator == "desap_n") "dim_desap_mun" else "dim_pam_mun"
229
+ inner_col <- if (indicator == "desap_n") "final_desap_nl" else "pam_n"
230
+ from_clause <- glue::glue("(SELECT CVEGEO, SUM({inner_col}) AS x FROM {inner_tbl} GROUP BY CVEGEO)")
231
+ col_expr <- "x"
232
+ } else {
233
+ from_clause <- "crime_mun"
234
+ col_expr <- glue::glue("CAST({indicator} AS DOUBLE)")
235
+ }
236
+ agg <- switch(statistic,
237
+ mean = glue::glue("AVG({col_expr})"), sum = glue::glue("SUM({col_expr})"),
238
+ max = glue::glue("MAX({col_expr})"), min = glue::glue("MIN({col_expr})"))
239
+ sql <- glue::glue("SELECT {agg} AS v, COUNT(*) AS n FROM {from_clause}")
240
+ r <- tryCatch(DBI::dbGetQuery(con, sql), error = function(e) NULL)
241
+ if (is.null(r) || nrow(r) == 0 || is.na(r$v[1]))
242
+ return(glue::glue("Could not compute {lab} nationally."))
243
+ glue::glue("{statistic} of {lab} across all {r$n[1]} municipalities in Mexico: {round(r$v[1], 2)}.")
244
+ }
245
+
246
+ assistant_top_municipalities <- function(con, state, indicator, n = 5) {
247
+ if (!indicator %in% names(.IND_LABELS)) return(paste0("Unknown indicator: ", indicator))
248
+ n <- max(1L, min(20L, as.integer(n)))
249
+ lab <- .IND_LABELS[[indicator]]
250
+
251
+ # Selection path: rank the in-memory municipalities.
252
+ if (!isTRUE(state$is_national) && !is.null(state$mun_df) &&
253
+ nrow(state$mun_df) > 0 && indicator %in% names(state$mun_df)) {
254
+ d <- state$mun_df
255
+ d$.v <- suppressWarnings(as.numeric(d[[indicator]]))
256
+ d <- d[is.finite(d$.v), , drop = FALSE]
257
+ if (nrow(d) == 0) return(glue::glue("No {lab} data in the current selection."))
258
+ d <- utils::head(d[order(-d$.v), , drop = FALSE], n)
259
+ items <- sprintf("%d. %s (%s): %s", seq_len(nrow(d)), d$municipio, d$entidad,
260
+ round(d$.v, 2))
261
+ return(paste0("Top municipalities by ", lab, " (current selection):\n",
262
+ paste(items, collapse = "\n")))
263
+ }
264
+
265
+ # National path.
266
+ if (is.null(con)) return("No database connection available.")
267
+ if (indicator %in% c("homicidio", "robo", "secuestro", "trafico_menores", "trata_personas")) {
268
+ sql <- glue::glue(
269
+ "SELECT municipio, entidad, CAST({indicator} AS DOUBLE) AS v
270
+ FROM crime_mun WHERE {indicator} IS NOT NULL
271
+ ORDER BY v DESC NULLS LAST LIMIT {n}")
272
+ } else {
273
+ inner_tbl <- if (indicator == "desap_n") "dim_desap_mun" else "dim_pam_mun"
274
+ inner_col <- if (indicator == "desap_n") "final_desap_nl" else "pam_n"
275
+ sql <- glue::glue(
276
+ "SELECT c.municipio, c.entidad, s.v AS v
277
+ FROM crime_mun c
278
+ JOIN (SELECT CVEGEO, SUM({inner_col}) AS v FROM {inner_tbl} GROUP BY CVEGEO) s
279
+ ON c.CVEGEO = s.CVEGEO
280
+ ORDER BY v DESC NULLS LAST LIMIT {n}")
281
+ }
282
+ r <- tryCatch(DBI::dbGetQuery(con, sql), error = function(e) NULL)
283
+ if (is.null(r) || nrow(r) == 0) return(glue::glue("Could not rank municipalities by {lab}."))
284
+ items <- sprintf("%d. %s (%s): %s", seq_len(nrow(r)), r$municipio, r$entidad, round(r$v, 2))
285
+ paste0("Top municipalities by ", lab, " (Mexico):\n", paste(items, collapse = "\n"))
286
+ }
287
+
288
+ # --- Assemble the per-session chat -------------------------------------------
289
+ # Returns a configured ellmer Chat with the constrained tools registered, or
290
+ # NULL if construction fails (e.g. Ollama dropped). Tools close over `con` and
291
+ # the live `state` snapshot env.
292
+ make_assistant <- function(con, state, cfg = assistant_config()) {
293
+ chat <- tryCatch(
294
+ ellmer::chat_ollama(
295
+ model = cfg$chat_model,
296
+ base_url = cfg$host,
297
+ system_prompt = assistant_system_prompt(assistant_indicator_catalog_txt()),
298
+ params = ellmer::params(temperature = 0.2)
299
+ ),
300
+ error = function(e) { message("[assist] chat_ollama: ", conditionMessage(e)); NULL }
301
+ )
302
+ if (is.null(chat)) return(NULL)
303
+
304
+ ind_enum <- ellmer::type_enum(names(.IND_LABELS), "Indicator column.")
305
+
306
+ list_indicators <- function() assistant_indicator_catalog_txt()
307
+ describe_selection <- function() assistant_selection_summary(state)
308
+ aggregate_indicator <- function(indicator, statistic = "mean")
309
+ assistant_aggregate(con, state, indicator, statistic)
310
+ top_municipalities <- function(indicator, n = 5)
311
+ assistant_top_municipalities(con, state, indicator, n)
312
+ count_points <- function(layer) assistant_count_points(state, layer)
313
+
314
+ chat$register_tool(ellmer::tool(list_indicators,
315
+ "List the indicators / data layers available in the DEPTH map, with their meaning and source. Call this when the user asks what data exists."))
316
+
317
+ chat$register_tool(ellmer::tool(describe_selection,
318
+ "Summarise the user's CURRENT map selection (drawn area, clicked municipality or state): how many municipalities and points of each type fall inside, plus key totals. Returns national totals if nothing is selected."))
319
+
320
+ chat$register_tool(ellmer::tool(aggregate_indicator,
321
+ "Aggregate one municipality indicator over the current selection (or nationally if nothing is selected). Use 'mean' for rate indicators and 'sum' for count indicators.",
322
+ arguments = list(
323
+ indicator = ind_enum,
324
+ statistic = ellmer::type_enum(c("mean", "sum", "max", "min"),
325
+ "Aggregation statistic.")
326
+ )))
327
+
328
+ chat$register_tool(ellmer::tool(top_municipalities,
329
+ "Rank municipalities by an indicator and return the top N (within the current selection if one is active, else nationally).",
330
+ arguments = list(
331
+ indicator = ind_enum,
332
+ n = ellmer::type_integer("How many municipalities to return (1-20).")
333
+ )))
334
+
335
+ chat$register_tool(ellmer::tool(count_points,
336
+ "Count point features for the current scope: migrant-death incidents, clandestine graves, support facilities, organised-crime violence events (OCVED) or armed-conflict events (GED).",
337
+ arguments = list(
338
+ layer = ellmer::type_enum(c("migrants", "graves", "infra", "ocved", "ged"),
339
+ "Which point layer to count.")
340
+ )))
341
+
342
+ chat
343
+ }
depth_interactive_map_alpha.R CHANGED
@@ -51,6 +51,9 @@ library(ggplot2)
51
  library(httr2)
52
 
53
  source("helpers.R")
 
 
 
54
 
55
  `%||%` <- function(x, y) if (is.null(x) || length(x) == 0) y else x
56
 
@@ -80,6 +83,17 @@ if (requireNamespace("showtext", quietly = TRUE) &&
80
  # Deployment edit (v10_HF): DuckDB path from env var, baked into the image.
81
  DB_PATH <- Sys.getenv("DEPTH_DDB_PATH", "/app/depth_mexico.duckdb")
82
 
 
 
 
 
 
 
 
 
 
 
 
83
  # --- Colour constants -----------------------------------------------------------
84
  # Recalibrated for Spatial UI light mode: saturation dropped ~10%, no neon,
85
  # all foreground/data colours stay AA-distinguishable on the near-white canvas.
@@ -1169,7 +1183,7 @@ WEB_SPEC <- list(
1169
  geom = "polygon", color = "envipe_step", value = "insecurity_perc",
1170
  opacity = 0.6, visible = FALSE),
1171
  list(id = "routes-lines", type = "line", src = "src_routes",
1172
- geom = "line", color = "#FFDF9E", opacity = 0.1, visible = FALSE),
1173
  list(id = "viaferrea-lines", type = "line", src = "src_via",
1174
  geom = "line", color = "#990f0f", opacity = 0.9, visible = FALSE,
1175
  dash = c(4, 2)),
@@ -1264,7 +1278,7 @@ WEB_SPEC <- list(
1264
  list(kind = "layer", value = "routes-lines",
1265
  label = "Main migration routes through Mexico",
1266
  tooltip = "Key routes migrants use to travel through Mexico towards the northern border.",
1267
- legend = list(type = "line", color = COL_AMBER, label = "Potential routes following national roads")),
1268
  list(kind = "layer", value = "viaferrea-lines",
1269
  label = "Railway network",
1270
  tooltip = "Railway lines used by migrants, including freight routes",
@@ -3237,7 +3251,7 @@ ui <- page_fillable(
3237
  tags$span(class = "side-panel-icon",
3238
  HTML('<i data-lucide="sparkles" style="width:18px;height:18px;stroke-width:2" aria-hidden="true"></i>')),
3239
  tags$h2(class = "side-panel-title", "Assistance"),
3240
- tags$span(class = "side-panel-tag", "Idea"),
3241
  tags$button(class = "side-panel-collapse",
3242
  type = "button",
3243
  onclick = "togglePanel('assist')",
@@ -3246,27 +3260,39 @@ ui <- page_fillable(
3246
  HTML('<i data-lucide="panel-right-close" style="width:16px;height:16px;stroke-width:2" aria-hidden="true"></i>'))
3247
  ),
3248
  div(class = "side-panel-body assist-body",
3249
- div(class = "assist-card",
3250
- tags$p(class = "assist-intro",
3251
- "An exploratory idea -- ", tags$em("may not ship."),
3252
- " The goal is to let researchers ask short questions about the visible data layers in natural language and get a grounded answer from the underlying DuckDB."
3253
- ),
3254
- tags$div(class = "assist-status",
3255
- HTML('<i data-lucide="flask-conical" style="width:12px;height:12px;stroke-width:2;color:var(--c-text-mid)" aria-hidden="true"></i>'),
3256
- tags$span("Research preview -- feasibility uncertain")
3257
- ),
3258
- tags$div(class = "assist-examples-label", "Example questions you'd ask"),
3259
- tags$ul(class = "assist-examples",
3260
- tags$li("Which municipalities in the visible area have the highest homicide rate?"),
3261
- tags$li("How many migrant shelters fall inside the current selection?"),
3262
- tags$li("Compare OCVED events over time for the area I drew.")
3263
- ),
3264
- tags$div(class = "assist-input-mock", role = "presentation",
3265
- HTML('<i data-lucide="message-circle" style="width:14px;height:14px;stroke-width:2;color:var(--c-text-dim)" aria-hidden="true"></i>'),
3266
- tags$span("Ask a question..."),
3267
- tags$span(class = "assist-soon-tag", "Soon")
3268
  )
3269
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3270
  )
3271
  )
3272
  ),
@@ -3853,6 +3879,62 @@ server <- function(input, output, session) {
3853
  )
3854
  }
3855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3856
  # Satellite fade-in expression helper
3857
  zoom_fade_in <- function(from_zoom, to_zoom) {
3858
  list("interpolate", list("linear"), list("zoom"), from_zoom, 0, to_zoom, 1)
@@ -4702,16 +4784,16 @@ server <- function(input, output, session) {
4702
  # tile the bottom row. Avoids the treemapify dependency.
4703
  # Re-toned to the muted Spatial data palette so the treemaps speak the same
4704
  # colour language as the map points (no Tailwind-bright sky / red / purple).
4705
- CAUSE_PAL <- c("Other / unknown" = "#3A4B5C", # neutral slate (COL_COUNT)
4706
  "Drowning" = "#1B9AAA", # teal-blue / water
4707
- "Harsh environment" = "#DDDBCB", # ochre / heat
4708
- "Vehicle accident" = "#F5F1E3", # mauve
4709
  "Violence" = "#9E2A3A") # brick red
4710
  # Demographics are nominal (not ordered) and carry no risk valence -- three
4711
  # distinct muted hues, avoiding the pink = female / blue = male cliche.
4712
- DEMO_PAL <- c(Children = "#DDDBCB", # ochre
4713
  Female = "#1B9AAA", # mauve
4714
- Male = "#3A4B5C") # slate
4715
 
4716
  # Stacked-bar layout: one horizontal row of segments, widths proportional
4717
  # to value. Returns the same shape as the treemap layout did (xmin/xmax/
 
51
  library(httr2)
52
 
53
  source("helpers.R")
54
+ # Local AI assistant (Ollama + RAG). Defines functions only; safe to source even
55
+ # when ellmer/shinychat/Ollama are absent -- the panel degrades gracefully.
56
+ source("assistant.R")
57
 
58
  `%||%` <- function(x, y) if (is.null(x) || length(x) == 0) y else x
59
 
 
83
  # Deployment edit (v10_HF): DuckDB path from env var, baked into the image.
84
  DB_PATH <- Sys.getenv("DEPTH_DDB_PATH", "/app/depth_mexico.duckdb")
85
 
86
+ # AI assistant availability, resolved once at startup (skipped in extract mode so
87
+ # the docs converter never pings Ollama). Gates both the UI and the server.
88
+ .ASSIST_CFG <- assistant_config()
89
+ .ASSIST_OK <- if (isTRUE(getOption("depth.extract_mode", FALSE))) {
90
+ FALSE
91
+ } else {
92
+ assistant_available(.ASSIST_CFG)
93
+ }
94
+ message("[assist] available: ", .ASSIST_OK,
95
+ " (model=", .ASSIST_CFG$chat_model, ", rag=", .ASSIST_CFG$rag_path, ")")
96
+
97
  # --- Colour constants -----------------------------------------------------------
98
  # Recalibrated for Spatial UI light mode: saturation dropped ~10%, no neon,
99
  # all foreground/data colours stay AA-distinguishable on the near-white canvas.
 
1183
  geom = "polygon", color = "envipe_step", value = "insecurity_perc",
1184
  opacity = 0.6, visible = FALSE),
1185
  list(id = "routes-lines", type = "line", src = "src_routes",
1186
+ geom = "line", color = "#FCA311", opacity = 0.1, visible = FALSE),
1187
  list(id = "viaferrea-lines", type = "line", src = "src_via",
1188
  geom = "line", color = "#990f0f", opacity = 0.9, visible = FALSE,
1189
  dash = c(4, 2)),
 
1278
  list(kind = "layer", value = "routes-lines",
1279
  label = "Main migration routes through Mexico",
1280
  tooltip = "Key routes migrants use to travel through Mexico towards the northern border.",
1281
+ legend = list(type = "line", color = "#FCA311", label = "Potential routes following national roads")),
1282
  list(kind = "layer", value = "viaferrea-lines",
1283
  label = "Railway network",
1284
  tooltip = "Railway lines used by migrants, including freight routes",
 
3251
  tags$span(class = "side-panel-icon",
3252
  HTML('<i data-lucide="sparkles" style="width:18px;height:18px;stroke-width:2" aria-hidden="true"></i>')),
3253
  tags$h2(class = "side-panel-title", "Assistance"),
3254
+ tags$span(class = "side-panel-tag", if (isTRUE(.ASSIST_OK)) "Local AI" else "Idea"),
3255
  tags$button(class = "side-panel-collapse",
3256
  type = "button",
3257
  onclick = "togglePanel('assist')",
 
3260
  HTML('<i data-lucide="panel-right-close" style="width:16px;height:16px;stroke-width:2" aria-hidden="true"></i>'))
3261
  ),
3262
  div(class = "side-panel-body assist-body",
3263
+ if (isTRUE(.ASSIST_OK)) {
3264
+ tagList(
3265
+ tags$p(class = "assist-intro",
3266
+ "Ask about the visible data layers in plain language. Answers are grounded in the project's research corpus and the live database, computed ",
3267
+ tags$strong("locally on this server"), " -- nothing leaves the container."
3268
+ ),
3269
+ tags$div(class = "assist-examples-label", "Try asking"),
3270
+ tags$ul(class = "assist-examples",
3271
+ tags$li("Which municipalities in my selection have the highest homicide rate?"),
3272
+ tags$li("How many migrant shelters fall inside the current selection?"),
3273
+ tags$li("What does the disappearances indicator measure?")
3274
+ ),
3275
+ shinychat::chat_ui("assist_chat",
3276
+ placeholder = "Ask a question about the map...",
3277
+ fill = TRUE)
 
 
 
 
3278
  )
3279
+ } else {
3280
+ div(class = "assist-card",
3281
+ tags$p(class = "assist-intro",
3282
+ "The local AI assistant is offline in this build."
3283
+ ),
3284
+ tags$div(class = "assist-status",
3285
+ HTML('<i data-lucide="flask-conical" style="width:12px;height:12px;stroke-width:2;color:var(--c-text-mid)" aria-hidden="true"></i>'),
3286
+ tags$span("Requires the in-container Ollama model and the embeddings index.")
3287
+ ),
3288
+ tags$div(class = "assist-examples-label", "When enabled, you could ask"),
3289
+ tags$ul(class = "assist-examples",
3290
+ tags$li("Which municipalities in the visible area have the highest homicide rate?"),
3291
+ tags$li("How many migrant shelters fall inside the current selection?"),
3292
+ tags$li("What does the disappearances indicator measure?")
3293
+ )
3294
+ )
3295
+ }
3296
  )
3297
  )
3298
  ),
 
3879
  )
3880
  }
3881
 
3882
+ # --- AI assistant (local Ollama + RAG + read-only tools) --------------------
3883
+ # Active only when the model, embeddings index and packages are all present
3884
+ # (.ASSIST_OK). Everything runs in-container; no data leaves the server.
3885
+ if (isTRUE(.ASSIST_OK)) {
3886
+ # Plain (non-reactive) snapshot of the current scope, kept in sync with rv so
3887
+ # the ellmer tools can read it during async streaming (outside reactive ctx).
3888
+ assist_state <- new.env(parent = emptyenv())
3889
+ assist_state$is_national <- TRUE
3890
+ assist_state$mun_df <- NULL
3891
+ assist_state$counts <- list()
3892
+ observe({
3893
+ assist_state$is_national <- isTRUE(rv$is_national)
3894
+ assist_state$mun_df <- rv$mun_df
3895
+ assist_state$counts <- list(
3896
+ n_mun = rv$n_mun, n_incidents = rv$n_incidents,
3897
+ n_fatalities = rv$n_fatalities,
3898
+ n_graves = rv$n_graves, n_facilities = rv$n_facilities,
3899
+ ocved_n = rv$ocved_n, n_ged = rv$n_ged,
3900
+ n_desap = rv$n_desap, n_pam = rv$n_pam,
3901
+ n_fosas = rv$n_fosas, n_cuerpos = rv$n_cuerpos
3902
+ )
3903
+ })
3904
+
3905
+ # One chat per session, built lazily on the first question so a slow model
3906
+ # load never blocks session startup.
3907
+ assist_chat <- NULL
3908
+ get_assist_chat <- function() {
3909
+ if (is.null(assist_chat)) {
3910
+ assist_chat <<- make_assistant(con, assist_state, .ASSIST_CFG)
3911
+ }
3912
+ assist_chat
3913
+ }
3914
+
3915
+ observeEvent(input$assist_chat_user_input, {
3916
+ q <- input$assist_chat_user_input
3917
+ if (is.null(q) || !nzchar(trimws(q))) return()
3918
+ chat <- get_assist_chat()
3919
+ if (is.null(chat)) {
3920
+ shinychat::chat_append("assist_chat",
3921
+ "Sorry -- the local model is unavailable right now.")
3922
+ return()
3923
+ }
3924
+ ctx <- tryCatch(rag_search(con, q, .ASSIST_CFG, k = 5),
3925
+ error = function(e) "")
3926
+ prompt <- assistant_user_turn(q, ctx)
3927
+ tryCatch(
3928
+ shinychat::chat_append("assist_chat", chat$stream_async(prompt)),
3929
+ error = function(e) {
3930
+ message("[assist] stream: ", conditionMessage(e))
3931
+ shinychat::chat_append("assist_chat",
3932
+ paste0("Sorry -- I hit an error answering that: ", conditionMessage(e)))
3933
+ }
3934
+ )
3935
+ })
3936
+ }
3937
+
3938
  # Satellite fade-in expression helper
3939
  zoom_fade_in <- function(from_zoom, to_zoom) {
3940
  list("interpolate", list("linear"), list("zoom"), from_zoom, 0, to_zoom, 1)
 
4784
  # tile the bottom row. Avoids the treemapify dependency.
4785
  # Re-toned to the muted Spatial data palette so the treemaps speak the same
4786
  # colour language as the map points (no Tailwind-bright sky / red / purple).
4787
+ CAUSE_PAL <- c("Other / unknown" = "#407076", # neutral slate (COL_COUNT)
4788
  "Drowning" = "#1B9AAA", # teal-blue / water
4789
+ "Harsh environment" = "#B49FCC", # ochre / heat
4790
+ "Accident" = "#92AA83", # mauve
4791
  "Violence" = "#9E2A3A") # brick red
4792
  # Demographics are nominal (not ordered) and carry no risk valence -- three
4793
  # distinct muted hues, avoiding the pink = female / blue = male cliche.
4794
+ DEMO_PAL <- c(Children = "#B49FCC", # ochre
4795
  Female = "#1B9AAA", # mauve
4796
+ Male = "#407076") # slate
4797
 
4798
  # Stacked-bar layout: one horizontal row of segments, widths proportional
4799
  # to value. Returns the same shape as the treemap layout did (xmin/xmax/
entrypoint.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Start the in-container Ollama server, then launch the Shiny app. Both run as
3
+ # the HF non-root user; nothing leaves the container.
4
+ set -euo pipefail
5
+
6
+ # Deterministic, writable home so Ollama can store its key + model cache.
7
+ export HOME=/app
8
+ export OLLAMA_MODELS="${OLLAMA_MODELS:-/app/.ollama}"
9
+ export OLLAMA_HOST="127.0.0.1:11434"
10
+
11
+ echo "[entrypoint] starting ollama serve (models in ${OLLAMA_MODELS})..."
12
+ ollama serve &
13
+
14
+ # Wait for the API to answer (model weights load lazily on first request).
15
+ for i in $(seq 1 60); do
16
+ if curl -sf "http://${OLLAMA_HOST}/api/tags" >/dev/null 2>&1; then
17
+ echo "[entrypoint] ollama is up."
18
+ break
19
+ fi
20
+ sleep 1
21
+ done
22
+
23
+ echo "[entrypoint] launching Shiny app..."
24
+ exec Rscript depth_interactive_map_alpha.R
styles.css CHANGED
@@ -2025,6 +2025,50 @@ button.mapbox-gl-draw_uncombine { display: none !important; }
2025
  padding: 2px 6px;
2026
  }
2027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2028
  /* ---- MapLibre popup (data layer hover tooltip) ---- */
2029
  .maplibregl-popup-content {
2030
  background: oklch(15% 0.012 250 / 0.94) !important;
 
2025
  padding: 2px 6px;
2026
  }
2027
 
2028
+ /* ---- Local AI assistant chat (shinychat) ---- */
2029
+ /* When the live chat is mounted, the body becomes a flex column so the message
2030
+ list scrolls and the input stays pinned at the bottom of the panel. */
2031
+ .assist-body:has(shiny-chat-container) {
2032
+ display: flex;
2033
+ flex-direction: column;
2034
+ gap: var(--space-2);
2035
+ min-height: 0;
2036
+ }
2037
+
2038
+ .assist-body shiny-chat-container {
2039
+ flex: 1 1 auto;
2040
+ min-height: 0;
2041
+ display: flex;
2042
+ flex-direction: column;
2043
+ gap: var(--space-2);
2044
+ font-family: var(--font-ui);
2045
+ }
2046
+
2047
+ .assist-body shiny-chat-messages {
2048
+ flex: 1 1 auto;
2049
+ overflow-y: auto;
2050
+ min-height: 120px;
2051
+ }
2052
+
2053
+ .assist-body shiny-chat-message {
2054
+ font-size: 12.5px;
2055
+ line-height: 1.55;
2056
+ color: var(--c-text);
2057
+ }
2058
+
2059
+ .assist-body shiny-chat-input textarea {
2060
+ font-family: var(--font-ui);
2061
+ font-size: 12.5px;
2062
+ border-radius: var(--radius-md);
2063
+ border: 1px solid var(--c-glass-stroke-strong);
2064
+ color: var(--c-text);
2065
+ }
2066
+
2067
+ .assist-body shiny-chat-input button {
2068
+ background: var(--c-accent);
2069
+ border-color: var(--c-accent);
2070
+ }
2071
+
2072
  /* ---- MapLibre popup (data layer hover tooltip) ---- */
2073
  .maplibregl-popup-content {
2074
  background: oklch(15% 0.012 250 / 0.94) !important;