tmquan commited on
Commit
3d2cac2
·
verified ·
1 Parent(s): d0684b0

Refresh narrative docs

Browse files
Files changed (2) hide show
  1. docs/DATAANALYSIS.md +344 -0
  2. docs/DATAPROCESSING.md +227 -0
docs/DATAANALYSIS.md ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DATAANALYSIS — what the curated data actually says
2
+
3
+ This document is the analytical companion to the curated parquet bundle
4
+ produced by `geography-vn curate`. It walks through the 14-figure pack
5
+ under [`docs/figures/analysis/`](docs/figures/analysis/) (rendered by
6
+ `scripts/analyze.py` and embedded inline in
7
+ [`DATAANALYSIS.ipynb`](DATAANALYSIS.ipynb)) and tells the story of
8
+ **Vietnam after Resolution 202/2025/QH15** through the data alone.
9
+
10
+ > **Source:** every number below comes from
11
+ > `data/sapnhap-bando-vn/extracted/extracted.parquet` (6,712 rows = 34
12
+ > provinces + 3,321 communes + 3,357 commune people's-committee
13
+ > headquarters). The parquet was produced by the five-stage NeMo Curator
14
+ > pipeline described in [`DATAPROCESSING.md`](DATAPROCESSING.md).
15
+
16
+ ## TL;DR
17
+
18
+ | Stat | Value |
19
+ | ------------------------------------- | ----------------- |
20
+ | First-level units (post-merger) | **34** |
21
+ | Second-level units (post-merger) | **3,321** |
22
+ | People's-committee headquarters | **3,357** |
23
+ | Total Vietnam population (2024) | **113,571,926** |
24
+ | Total Vietnam land area (km²) | **331,325.62** |
25
+ | Largest province by population | TPHCM — **14,002,598** |
26
+ | Largest province by area | Lâm Đồng — **24,233 km²** |
27
+ | Densest province | Hà Nội — **2,621 / km²** |
28
+ | Most-merged commune | Phường Văn Miếu - Quốc Tử Giám — **16 predecessor wards** |
29
+ | Distinct authorising decrees | **37** |
30
+ | Provinces that kept their old borders | **11** out of 34 |
31
+
32
+ ## 1 — Inventory ([fig 01](docs/figures/analysis/01_admin_kind_donut.png))
33
+
34
+ The atlas publishes three entity kinds, in roughly equal sub-counts:
35
+
36
+ | Kind | Count | What it is |
37
+ | ----------- | ------- | ------------------------------------------------------- |
38
+ | `province` | 34 | First-level admin units (28 provinces + 6 cities) |
39
+ | `commune` | 3,321 | Second-level units (phường / xã / đặc khu after the merger) |
40
+ | `committee` | 3,357 | Commune people's-committee headquarters (point markers) |
41
+
42
+ The committee count slightly exceeds the commune count (3,357 > 3,321)
43
+ because some communes have multiple registered committee buildings (the
44
+ seat plus a satellite office) and a handful of pre-merger committees
45
+ remain marked on the map even after their parent commune dissolved.
46
+
47
+ ## 2 — Macro-region balance ([fig 02](docs/figures/analysis/02_macro_region_breakdown.png))
48
+
49
+ The 34 surviving provinces redistribute across the six GSO macro-regions
50
+ unevenly. The north (where the 2025 merger was the most aggressive) keeps
51
+ **10 + 5 = 15 provinces** under two macro-regions; the centre keeps
52
+ **8 + 3 = 11**; the south keeps **3 + 5 = 8**. Including the
53
+ people's-committee tier (which inherits its parent province's region):
54
+
55
+ | Macro-region (EN) | Provinces | Communes | Committees | Total |
56
+ | ------------------------------------------ | --------: | -------: | ---------: | ----: |
57
+ | Northern Midlands and Mountain Areas | **10** | 841 | 842 | 1,693 |
58
+ | Red River Delta | **5** | 527 | 502 | 1,034 |
59
+ | North Central and Central Coastal Areas | **8** | 738 | 737 | 1,483 |
60
+ | Central Highlands | **3** | 361 | 380 | 744 |
61
+ | Southeast | **3** | 359 | 358 | 720 |
62
+ | Mekong River Delta | **5** | 495 | 537 | 1,037 |
63
+ | (unknown — disputed-zone duplicates) | 0 | 0 | 1 | 1 |
64
+
65
+ Note that the **Northern Midlands** retains the highest *count* of
66
+ first-level units (10) despite being the region the merger consolidated
67
+ hardest — pre-merger it had 14 provinces. The **Southeast** ends up the
68
+ smallest by province count (3) because TPHCM swallowed both Bình Dương
69
+ and Bà Rịa-Vũng Tàu into a single mega-city.
70
+
71
+ ## 3 — Province population ([fig 03](docs/figures/analysis/03_province_population.png))
72
+
73
+ The top-five most populous provinces, after the merger:
74
+
75
+ | Rank | Province | Population | Area (km²) | Density (/km²) | Predecessors |
76
+ | ---- | ----------------------- | -----------: | ---------: | -------------: | -----------: |
77
+ | 1 | Thành Phố Hồ Chí Minh | 14,002,598 | 6,772.59 | 2,067.5 | 3 |
78
+ | 2 | Thủ Đô Hà Nội | 8,807,523 | 3,359.84 | 2,621.4 | 1 |
79
+ | 3 | Tỉnh An Giang | 4,952,238 | 9,888.91 | 500.8 | 2 |
80
+ | 4 | Thành Phố Hải Phòng | 4,664,124 | 3,194.72 | 1,460.0 | 2 |
81
+ | 5 | Thành phố Đồng Nai | 4,491,408 | 12,737.18 | 352.6 | 4 |
82
+
83
+ TPHCM's merger absorbed **Bình Dương** (industrial belt) and **Bà Rịa
84
+ - Vũng Tàu** (the southern coast & Côn Đảo) into one super-city, doubling
85
+ its population from ~7 M to **14 M** — now larger than New York's metro.
86
+
87
+ Đồng Nai is the only province in the country that absorbed **four**
88
+ predecessor units (the original Đồng Nai + Bình Phước + parts of two
89
+ neighbours), making it the largest-area populated unit in the south.
90
+
91
+ ## 4 — Province area ([fig 04](docs/figures/analysis/04_province_area.png))
92
+
93
+ The top-five largest provinces by km², all in the central highlands or
94
+ upper-central coast:
95
+
96
+ | Rank | Province | Area (km²) | Population | Density (/km²) | Predecessors |
97
+ | ---- | ----------------- | ----------: | ---------: | -------------: | -----------: |
98
+ | 1 | Tỉnh Lâm Đồng | 24,233.07 | 3,872,999 | 159.8 | 3 |
99
+ | 2 | Tỉnh Gia Lai | 21,576.53 | 3,583,693 | 166.1 | 2 |
100
+ | 3 | Tỉnh Đắk Lắk | 18,096.40 | 3,346,853 | 184.9 | 2 |
101
+ | 4 | Tỉnh Nghệ An | 16,486.50 | 3,831,694 | 232.4 | 1 |
102
+ | 5 | Tỉnh Quảng Ngãi | 14,832.55 | 2,161,755 | 145.7 | 2 |
103
+
104
+ Lâm Đồng is the merger's largest single creation: the old Lâm Đồng +
105
+ **Bình Thuận** (south-central coast) + **Đắk Nông** (Central Highlands)
106
+ fused into a 24,233 km² province that now stretches from the central
107
+ plateau to the South China Sea coast.
108
+
109
+ ## 5 — Province density ([fig 05](docs/figures/analysis/05_province_density.png))
110
+
111
+ | Rank | Province | Density (/km²) | Population | Area (km²) |
112
+ | ---- | ----------------------- | -------------: | ---------: | ---------: |
113
+ | 1 | Thủ Đô Hà Nội | 2,621.4 | 8,807,523 | 3,359.84 |
114
+ | 2 | Thành Phố Hồ Chí Minh | 2,067.5 | 14,002,598 | 6,772.59 |
115
+ | 3 | Thành Phố Hải Phòng | 1,460.0 | 4,664,124 | 3,194.72 |
116
+ | 4 | Tỉnh Hưng Yên | 1,418.8 | 3,567,943 | 2,514.81 |
117
+ | 5 | Tỉnh Ninh Bình | 1,119.1 | 4,412,264 | 3,942.62 |
118
+
119
+ Hà Nội remains the densest province even though it kept its pre-merger
120
+ borders unchanged (its `n_predecessors == 1`). Hưng Yên, **post-merger**
121
+ absorbing Thái Bình, jumps into the top 4 — the merged Red River Delta
122
+ provinces concentrate density there.
123
+
124
+ ## 6 — Communes per province ([fig 06](docs/figures/analysis/06_communes_per_province.png))
125
+
126
+ The lower-tier consolidation is more uneven:
127
+
128
+ * **Min**: 38 communes (Tỉnh Lai Châu — sparsely populated mountains)
129
+ * **Max**: 168 communes (Thành phố Hồ Chí Minh — mega-city)
130
+ * **Median**: 99 communes per province
131
+ * **Mean**: 97.7 communes per province
132
+
133
+ Bottom five (sparsest):
134
+
135
+ | Province | Communes |
136
+ | ------------------ | -------: |
137
+ | Tỉnh Lai Châu | 38 |
138
+ | Thành phố Huế | 40 |
139
+ | Tỉnh Điện Biên | 45 |
140
+ | Tỉnh Quảng Ninh | 54 |
141
+ | Tỉnh Cao Bằng | 56 |
142
+
143
+ Top five (densest):
144
+
145
+ | Province | Communes |
146
+ | -------------------------- | -------: |
147
+ | Thành phố Hồ Chí Minh | 168 |
148
+ | Tỉnh Thanh Hóa | 166 |
149
+ | Tỉnh Phú Thọ | 148 |
150
+ | Tỉnh Gia Lai | 135 |
151
+ | Tỉnh Nghệ An | 130 |
152
+
153
+ ## 7 — Province merger fanout ([fig 07](docs/figures/analysis/07_merger_fanout_provinces.png))
154
+
155
+ How many predecessor provinces fed each surviving first-level unit:
156
+
157
+ | n_predecessors | Provinces | Names |
158
+ | -------------- | --------: | -------------------------------------------------------------------------------------------------------- |
159
+ | **1** | **11** | Hà Nội, Huế, Cao Bằng, Điện Biên, Hà Tĩnh, Lai Châu, Lạng Sơn, Nghệ An, Quảng Ninh, Sơn La, Thanh Hóa |
160
+ | **2** | **16** | Đà Nẵng, Hải Phòng, An Giang, Bắc Ninh, Cà Mau, Đắk Lắk, Đồng Tháp, Gia Lai, Hưng Yên, Khánh Hòa, … |
161
+ | **3** | **6** | Cần Thơ, Hồ Chí Minh, Lâm Đồng, Ninh Bình, Phú Thọ, Vĩnh Long |
162
+ | **4** | **1** | Đồng Nai |
163
+
164
+ Eleven provinces kept their old borders — they were already large enough
165
+ or geographically isolated enough that the merger left them alone. The
166
+ modal merger absorbed exactly one neighbour. Đồng Nai is the singular
167
+ four-way merger.
168
+
169
+ ## 8 — Commune merger fanout ([fig 08](docs/figures/analysis/08_merger_fanout_communes.png))
170
+
171
+ The lower tier was consolidated much more aggressively. Of the 3,321
172
+ surviving communes:
173
+
174
+ | n_predecessors | Communes | % |
175
+ | -------------- | -------: | ----: |
176
+ | **1** | 139 | 4.2% |
177
+ | **2** | 758 | 22.8% |
178
+ | **3** | 1,498 | 45.1% |
179
+ | **4** | 559 | 16.8% |
180
+ | **5** | 179 | 5.4% |
181
+ | **6** | 78 | 2.3% |
182
+ | **7+** | 110 | 3.4% |
183
+ | **max** | 16 | |
184
+
185
+ The modal commune absorbed **3 predecessor wards/xã**. The mean fanout
186
+ is 3.4 (compared to ~1.6 for the first-level tier).
187
+
188
+ The **most-merged commune is Phường Văn Miếu - Quốc Tử Giám** in Hà
189
+ Nội, which fused **16 predecessor wards** into a single 4-character
190
+ neighbourhood. Hà Nội dominates the high-fanout extreme — 8 of the top
191
+ 15 communes by fanout are in Hà Nội, reflecting the post-merger desire
192
+ to flatten the dense old ward grid into larger, more administratively
193
+ manageable units. The other notable mega-mergers are coastal special
194
+ zones: **Đặc khu Cát Hải** (Hải Phòng, 12 preds), **Đặc khu Vân Đồn**
195
+ (Quảng Ninh, 12 preds).
196
+
197
+ ## 9 — Commune size distribution ([fig 09](docs/figures/analysis/09_commune_size_distribution.png))
198
+
199
+ A log-log scatter of commune area vs population reveals three regimes:
200
+
201
+ * **Special administrative zones (Đặc khu)** — sit in the bottom-left:
202
+ tiny populations on tiny islands. Hoàng Sa (the Paracels — 0
203
+ registered population, 350 km²), Trường Sa (Spratly — 153 people,
204
+ 496 km²), Cồn Cỏ (139 people, 2.3 km²), Bạch Long Vĩ (686 people,
205
+ 3.07 km²). All have ambiguous-to-disputed sovereignty status and
206
+ serve mainly as markers of national territory.
207
+ * **Highland xã** — the upper-left band: tens of thousands of
208
+ inhabitants spread across 200-1100 km² of mountain terrain. Buôn Đôn
209
+ (Đắk Lắk, 1,114 km², 6.6K people) is the largest by area in the entire
210
+ set. The Trường Sơn cordillera communes in Quảng Trị (Thượng Trạch,
211
+ Trường Sơn, Kim Ngân) all exceed 800 km² each.
212
+ * **Urban phường** — the lower-right cluster: 50-130K people on a few
213
+ km² of city. Phường Hải Châu (Đà Nẵng, 7.58 km², 131K people) is the
214
+ densest by far.
215
+
216
+ ## 10 — Decree corpus ([fig 10](docs/figures/analysis/10_decree_map.png))
217
+
218
+ The merger is authorised by **37 distinct decrees**: 1 from the National
219
+ Assembly itself (`Nghị quyết số 202/2025/QH15`) and 34 follow-up
220
+ Standing Committee resolutions (`NQ-UBTVQH15`) of 16 June 2025 that flesh
221
+ out the lower-tier merger commune-by-commune. The top decrees by number
222
+ of units cited:
223
+
224
+ | Decree | Units cited |
225
+ | --------------------------------- | ----------: |
226
+ | `Nghị quyết số 1685/NQ-UBTVQH15` | 168 |
227
+ | `Nghị quyết số 1686/NQ-UBTVQH15` | 166 |
228
+ | `Nghị quyết số 1676/NQ-UBTVQH15` | 148 |
229
+ | `Nghị quyết số 1664/NQ-UBTVQH15` | 135 |
230
+ | `Nghị quyết số 1678/NQ-UBTVQH15` | 130 |
231
+ | `Nghị quyết số 1674/NQ-UBTVQH15` | 129 |
232
+ | `Nghị quyết số 1656/NQ-UBTVQH15` | 126 |
233
+ | … (30 more) | … |
234
+
235
+ Each `NQ-1656…1690` decree corresponds to one of the 34 surviving
236
+ provinces. The top decree (NQ-1685) authorises all 168 wards of TPHCM;
237
+ NQ-1686 covers the 166 communes of Thanh Hóa; etc. Every commune row in
238
+ the parquet has a `decree_url` column pointing to the official text at
239
+ `vanban.chinhphu.vn`.
240
+
241
+ ## 11 — Cartographic pack with dual-archipelago declaration
242
+
243
+ Geographic visualisations live in their own folder under
244
+ [`docs/figures/maps/`](docs/figures/maps/) — rendered standalone by
245
+ `python -m scripts.render_maps` because kaleido + Mapbox-GL crashes
246
+ inside a Jupyter kernel. Five figures total, each with the **actual
247
+ scraped province polygons** (not bubbles) and the standard
248
+ Vietnamese-atlas declaration of both offshore archipelagos:
249
+ * **Quần đảo Hoàng Sa** (Paracel Islands) — dashed bounding outline
250
+ ~15.45°N–17.20°N × 110.85°E–113.10°E with markers for Phú Lâm, Tri Tôn,
251
+ Linh Côn, Quang Hòa. Administered by **Thành phố Đà Nẵng** under the
252
+ post-2025 geography (Đặc khu Hoàng Sa).
253
+ * **Quần đảo Trường Sa** (Spratly Islands) — dashed bounding outline
254
+ ~7.40°N–11.85°N × 111.80°E–115.30°E with markers for Trường Sa Lớn,
255
+ Song Tử Tây, Sinh Tồn, Phan Vinh, An Bang, Nam Yết, Cô Lin, Sơn Ca.
256
+ Administered by **Tỉnh Khánh Hòa** (Đặc khu Trường Sa).
257
+
258
+ Each map additionally carries: ★ Thủ đô Hà Nội (capital), 7 secondary
259
+ cities (TP. Hồ Chí Minh / Đà Nẵng / Hải Phòng / Huế / Vinh / Cần Thơ /
260
+ Nha Trang) with leader-line labels into open sea, and 5 island callouts
261
+ (Đảo Phú Quốc / Cát Bà / Bạch Long Vĩ / Lý Sơn + Côn Đảo).
262
+
263
+ | File | Visualisation |
264
+ | ----------------------------------------------- | ------------------------------------------------------------ |
265
+ | `maps/01_provinces_population.png` | population choropleth (sequential NVIDIA-green) |
266
+ | `maps/02_provinces_density.png` | people / km² |
267
+ | `maps/03_provinces_area.png` | land area (km²) |
268
+ | `maps/04_communes_scatter.png` | 3,321 commune centroids by macro-region |
269
+ | `maps/05_committees_scatter.png` | 3,357 commune people's-committee headquarters by lat/lon |
270
+
271
+ The cartographic pack uses NVIDIA Sans typography on a square 1100 × 1100
272
+ canvas; the analytical pack above uses the LaTeX-serif `nvidia_latex`
273
+ template at 1200 × 900. Maps follow brand convention, charts follow
274
+ academic-paper convention.
275
+
276
+ ## 12 — Curator UMAP ([fig 11](docs/figures/analysis/11_curator_umap_kind.png), [fig 12](docs/figures/analysis/12_curator_umap_region.png))
277
+
278
+ A 2-D UMAP projection of the 6,712-point sentence-transformers
279
+ embedding of every entity's `embed_text` descriptor. Three observations:
280
+
281
+ 1. **Kind separation is partial.** Provinces and committees occupy
282
+ compact, well-separated tail regions of the map (provinces
283
+ because their descriptors include rich predecessor-province prose
284
+ that other entities do not; committees because every committee
285
+ description follows the standard "Ủy ban nhân dân …" template).
286
+ Communes fill the middle and overlap with both extremes.
287
+ 2. **Macro-region structure emerges.** Even though the embed text
288
+ does not explicitly mention macro-region, the UMAP × macro-region
289
+ colouring shows clean lobes for the Mekong Delta, the Northern
290
+ Midlands, and the Central Highlands — the model picks up on
291
+ regional naming conventions (`Đặc khu Phú Quốc` clusters with the
292
+ southern coast, `Xã Mường Khương` with the Northwest, etc.).
293
+ 3. **HDBSCAN finds ~30-50 dense subclusters** within the broader
294
+ regional structure. Most are sub-province-level: a single
295
+ province's communes cluster together because their descriptors
296
+ share a common `parent_ten` tag, the same parent decree, and
297
+ similar predecessor-name patterns ("Phường … và Phường … sau khi
298
+ sắp xếp"). The `cluster` column in `reduced.parquet` carries the
299
+ integer label per row, with `-1` reserved for low-density noise
300
+ points.
301
+
302
+ ## Caveats & known limits
303
+
304
+ * **`Đặc khu Hoàng Sa` has zero registered population.** The Paracel
305
+ Islands are administered by the People's Republic of China and have
306
+ not been physically Vietnamese-controlled since 1974. The Vietnamese
307
+ atlas marks them as a special administrative zone of Đà Nẵng with a
308
+ populations of zero — a sovereignty assertion, not a usable
309
+ demographic figure.
310
+ * **Population numbers are 2024 mid-year estimates** as published with
311
+ the merger decrees (rounded thousands at the commune level). They
312
+ predate the merger by 6–12 months and may not yet reflect intra-merger
313
+ population migration.
314
+ * **Two parent-province strings come back inconsistent:** "Thủ đô Hà Nội"
315
+ vs "Thủ Đô Hà Nội" (different `Đ`/`đ` capitalisation depending on the
316
+ endpoint). The `parent_ma` column normalises this — join on `parent_ma`
317
+ not on `parent_ten` for analysis.
318
+ * **3 communes carry the name "Xã Hoàng Hoa Thám"** (each in a different
319
+ province) and 1 carries "Đặc khu Phú Quốc". Use `id` (== feature id)
320
+ not `ten` as the primary key.
321
+ * **The committee macro-region** is derived from the GeoJSON
322
+ `properties.a04_tentinh` field, which can be missing for ~20 of the
323
+ 3,357 committees (mostly defunct pre-merger seats). Those rows show
324
+ `macro_region == "unknown"` in the parquet.
325
+
326
+ ## How to reproduce
327
+
328
+ ```bash
329
+ # 1) Download + curate (~35 min on first run, then cached)
330
+ geography-vn curate
331
+
332
+ # 2) Render the figure pack (~2 min)
333
+ python -m scripts.analyze
334
+
335
+ # 3) Re-execute the notebook (optional)
336
+ jupyter nbconvert --to notebook --execute --inplace DATAANALYSIS.ipynb
337
+
338
+ # 4) Stage and push the HF dataset
339
+ python -m scripts.upload_to_hf --no-upload
340
+ python -m scripts.upload_to_hf --repo <your-org>/sapnhap-bando-vn
341
+ ```
342
+
343
+ See [`DATAPROCESSING.md`](DATAPROCESSING.md) for the curator-pipeline
344
+ internals.
docs/DATAPROCESSING.md ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DATAPROCESSING — five-stage curator pipeline
2
+
3
+ This document walks through the five-stage NeMo-Curator-compatible pipeline
4
+ that turns the raw web responses from <https://sapnhap.bando.com.vn/> into
5
+ the typed, joinable, embedding-augmented parquet bundle that ships to
6
+ HuggingFace and feeds [`DATAANALYSIS.md`](DATAANALYSIS.md).
7
+
8
+ The five stages mirror the same layout used by ViLA's
9
+ [`packages/datasites/anle/`](https://github.com/tmquan/ViLA/tree/main/packages/datasites/anle)
10
+ and `personas-vn`'s
11
+ [`packages/curator/`](https://github.com/tmquan/personas-vn/tree/main/packages/curator):
12
+
13
+ ```
14
+ download → parse → extract → embed → reduce
15
+ ```
16
+
17
+ Each stage reads from the previous stage's output directory and writes to its
18
+ own. A failure inside one stage never destroys earlier work, and re-running a
19
+ single stage in isolation (`--only embed`, `--skip download`, …) is the
20
+ intended development loop.
21
+
22
+ ```
23
+ data/sapnhap-bando-vn/
24
+ ├── raw/ ← stage 1
25
+ │ ├── admin_units.json (one POST: 3,355 listings)
26
+ │ ├── committees.json (one POST: 3,357 committee markers)
27
+ │ ├── details/<malk>.json (~3,355 POSTs to p.co_dvhc_id)
28
+ │ ├── geom/<id>.geojson (~6,712 POSTs to pread_json)
29
+ │ └── _cache/ (per-URL HTTP cache; re-runs are free)
30
+ ├── parsed/ ← stage 2: parsed.jsonl + parsed.parquet
31
+ ├── extracted/ ← stage 3: extracted.jsonl + extracted.parquet
32
+ ├── embedded/ ← stage 4: embedded.parquet (n × 384-d vectors)
33
+ └── reduced/ ← stage 5: reduced.parquet (UMAP 2-D + cluster id)
34
+ ```
35
+
36
+ ## Source surface
37
+
38
+ The site at `sapnhap.bando.com.vn/` is a thin PHP front-end
39
+ (`D:\map34tinh\s.index.php`) over a QGIS Server WMS/WFS deployment. It
40
+ exposes four POST endpoints we care about — every one returns JSON, even
41
+ when the server lies in its `Content-Type` header:
42
+
43
+ | Endpoint | Form data | Returns |
44
+ | ----------------------- | ------------------------------- | ---------------------------------------------------- |
45
+ | `POST /p.co_dvhc` | `ma=0` | List of every admin unit (34 prov + 3,321 communes) |
46
+ | `POST /p.co_uyban` | `ma=0` | List of 3,357 commune people's-committee headquarters |
47
+ | `POST /p.co_dvhc_id` | `malk=<feature_id>` | Full attribute row (area, population, decree, …) |
48
+ | `POST /pread_json` | `id=<feature_id>` | GeoJSON FeatureCollection (Polygon / MultiPolygon / Point) |
49
+
50
+ Feature-id conventions:
51
+
52
+ * `diaphanhanhchinhcaptinh_sn.<n>` — province polygons (only 34 of the 132
53
+ pre-merger ids survive).
54
+ * `diaphanhanhchinhcapxa_2025.<n>` — commune polygons; 3,321 alive, the
55
+ rest dissolved into neighbours.
56
+ * `uybannhandancapxa_2025.<n>` — point markers for every commune
57
+ people's committee (n = 1 … 3,357).
58
+
59
+ The PHP front-end occasionally injects an HTML warning preamble before the
60
+ JSON body when QGIS Server is mid-restart — `packages.common.http` peels
61
+ that off transparently.
62
+
63
+ ## Stage 1 — download
64
+
65
+ ```python
66
+ DownloadStage(config.download, raw_dir).run()
67
+ ```
68
+
69
+ * **Two listing POSTs** capture the complete inventory in one shot each
70
+ (`/p.co_dvhc` and `/p.co_uyban`).
71
+ * **Per-unit detail walk** (~3,355 POSTs to `/p.co_dvhc_id`) pulls the rich
72
+ attribute row for every admin unit: area in km², population, capital,
73
+ predecessors prose, decree of authority, link to the official decree at
74
+ `vanban.chinhphu.vn`.
75
+ * **Per-feature geometry walk** (~6,712 POSTs to `/pread_json`) pulls the
76
+ polygon for every admin unit and the point marker for every committee.
77
+ * Every URL is cached on disk under `raw/_cache/`; re-runs hit the cache and
78
+ finish in seconds.
79
+ * `delay_between_requests_s: 0.10` keeps the crawl polite — ~10 req/s, no
80
+ hint of rate limiting from the server.
81
+ * Wall time on first run: ~12 minutes for the listings + details, plus
82
+ ~22 minutes for the geometries; ~35 minutes end-to-end on a home
83
+ broadband line.
84
+
85
+ The full crawl materialises **roughly 6,700 small JSON / GeoJSON files**
86
+ totaling ~120 MB.
87
+
88
+ ## Stage 2 — parse
89
+
90
+ ```python
91
+ ParseStage(config.parse, raw_dir, parsed_dir).run()
92
+ ```
93
+
94
+ Three jobs:
95
+
96
+ 1. **Normalise Vietnamese-formatted numbers.** The `p.co_dvhc_id` endpoint
97
+ uses Vietnamese locale (`"6.360,83"` = 6,360.83 km²); the GeoJSON
98
+ `properties` block uses English (`"575.29"` = 575.29 km²,
99
+ `"157629"` = 157,629 people). `parse_vi_decimal` and `parse_vi_int` in
100
+ `packages/scraper/sapnhap.py` cover both idioms.
101
+ 2. **Summarise GeoJSON.** Each FeatureCollection collapses to a single row
102
+ with `centroid_lon`, `centroid_lat`, `bbox`, `geom_type`, `n_vertices`,
103
+ and (when `parse.flatten_geojson=true`) a shapely-emitted WKT string.
104
+ We use shapely's true centroid for polygons; for the rare environments
105
+ without shapely, a ring-walk arithmetic-mean centroid is good enough for
106
+ plotting.
107
+ 3. **Stamp parent-province for every commune & committee.** The
108
+ `tentinh` attribute on `p.co_dvhc_id` and the `a04_tentinh` attribute on
109
+ the GeoJSON committee features carry the parent-province name; we
110
+ resolve it against the 34-row province list to attach a stable
111
+ `parent_ma` (NSO 2-digit province code).
112
+
113
+ Output is a single canonical row per entity (province, commune, or
114
+ committee), written as both `parsed.jsonl` and `parsed.parquet`. Schema:
115
+
116
+ | column | type | notes |
117
+ | --------------- | -------- | ------------------------------------------------------------- |
118
+ | `id` | str | feature id (`==` malk) |
119
+ | `kind` | str | `province` / `commune` / `committee` |
120
+ | `ma` | str | NSO 2-digit province code or 5-char commune code |
121
+ | `ten` | str | canonical Vietnamese name |
122
+ | `type` | str | `Tỉnh` / `Thành Phố` / `Phường` / `Xã` / `Đặc khu` / … |
123
+ | `ten_short` | str | `ten` with the type prefix stripped |
124
+ | `area_km2` | float | parsed via `parse_vi_decimal` |
125
+ | `population` | int | parsed via `parse_vi_int` |
126
+ | `density` | float | `population / area_km2` |
127
+ | `capital` | str? | `trungtamhc` (administrative-centre address) |
128
+ | `address` | str? | |
129
+ | `phone` | str? | |
130
+ | `decree` | str? | `cancu` (e.g. `Nghị quyết số 202/2025/QH15`) |
131
+ | `decree_url` | str? | usually a `vanban.chinhphu.vn` permalink |
132
+ | `predecessors` | str? | raw `truocsapnhap` prose |
133
+ | `parent_ma` | str? | NSO-code of the parent province (for communes & committees) |
134
+ | `parent_ten` | str? | |
135
+ | `centroid_lon/lat` | float? | from the geometry summary |
136
+ | `bbox` | list? | `[lon_min, lat_min, lon_max, lat_max]` |
137
+ | `geom_type` | str? | `Polygon` / `MultiPolygon` / `Point` |
138
+ | `wkt` | str? | shapely WKT (only when `flatten_geojson=true`) |
139
+
140
+ ## Stage 3 — extract
141
+
142
+ ```python
143
+ ExtractStage(config.extract, parsed_dir, extracted_dir).run()
144
+ ```
145
+
146
+ Adds the analytical columns the downstream notebook + the visualizer need:
147
+
148
+ * **`macro_region`** — every entity is mapped to one of the six GSO
149
+ macro-regions (`northern_midlands`, `red_river_delta`, `central_coast`,
150
+ `central_highlands`, `southeast`, `mekong_delta`). The mapping table
151
+ lives in `packages/curator/regions.py` and is hand-curated against the
152
+ post-merger 34-province list.
153
+ * **`predecessors_list`** — explodes the `truocsapnhap` Vietnamese prose
154
+ into a deduplicated list of predecessor names. Handles separators
155
+ (`,`, `và`, `cùng`, `;`), strips mereological qualifiers ("phần còn lại
156
+ của", "một phần"), and trims trailing "sau khi sắp xếp" clauses.
157
+ * **`n_predecessors`** — `len(predecessors_list)`.
158
+ * **`keywords`** — top-N TF-IDF unigrams + bigrams over the merger-lineage
159
+ prose; uses a Vietnamese-friendly token pattern
160
+ (`r"(?u)\b[\wÀ-ỹ]{3,}\b"`) so diacritics survive tokenisation.
161
+ * **`embed_text`** — single canonical Vietnamese descriptor (name + parent
162
+ + type + predecessors + capital + decree) that the embedding stage
163
+ consumes.
164
+
165
+ Output: `extracted.jsonl` + `extracted.parquet`.
166
+
167
+ ## Stage 4 — embed
168
+
169
+ ```python
170
+ EmbedStage(config.embed, extracted_dir, embedded_dir).run()
171
+ ```
172
+
173
+ Encodes every record's `embed_text` field with
174
+ [`sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2`](https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2)
175
+ on CPU (384-d, normalised, `batch_size=64`). The full corpus of ~6,700
176
+ short Vietnamese descriptors finishes in ~3 minutes on an M-series Mac.
177
+
178
+ For NIM-hosted embeddings (e.g. `nvidia/llama-3.2-nv-embedqa-1b-v2`)
179
+ the same backend abstraction used by `personas-vn` would slot in here —
180
+ set `embed.backend: nim` and a `PERSONAS_VN_LLM_API_KEY` env var.
181
+
182
+ Output: `embedded.parquet` with the meta columns plus a `vector`
183
+ column (list[float]).
184
+
185
+ ## Stage 5 — reduce
186
+
187
+ ```python
188
+ ReduceStage(config.reduce, embedded_dir, reduced_dir).run()
189
+ ```
190
+
191
+ * **UMAP** projection to 2-D with cosine metric (15 neighbours,
192
+ `min_dist=0.1`, `random_state=20260508`).
193
+ * **Density-based HDBSCAN** clustering (`min_cluster_size=⌊n/80⌋`),
194
+ emitting an integer `cluster` column with `-1` reserved for low-density
195
+ noise points.
196
+
197
+ Output: `reduced.parquet` — every meta column from the embed stage plus
198
+ `x`, `y`, and (when `reduce.cluster=true`) `cluster`. This is the parquet
199
+ that feeds the UMAP plots in [`DATAANALYSIS.ipynb`](DATAANALYSIS.ipynb)
200
+ and the curator-tab in any future Gradio visualizer.
201
+
202
+ ## NeMo Curator backend
203
+
204
+ Pass `--backend nemo_curator` to `geography-vn curate` and the same five
205
+ stage objects are wrapped as `nemo_curator.core.stage.ProcessingStage`
206
+ sub-classes and handed to a real `nemo_curator.core.pipeline.Pipeline`
207
+ running through `nemo_curator.backends.experimental.in_process.InProcessExecutor`.
208
+ The wire-shape on disk is identical, so the rest of the pipeline (HF
209
+ upload, analysis notebook) does not care which executor ran. To go
210
+ distributed, swap `InProcessExecutor` for
211
+ `XennaExecutor` / `RayDataExecutor` — no code changes needed to the
212
+ stages themselves.
213
+
214
+ ## Re-running individual stages
215
+
216
+ ```bash
217
+ # Re-run only the embed + reduce stages (cheap when the corpus stayed put
218
+ # but the model changed):
219
+ geography-vn curate --only embed reduce
220
+
221
+ # Re-run everything except the slow geometry crawl:
222
+ geography-vn curate --skip download # cached anyway, but explicit is faster
223
+ ```
224
+
225
+ The on-disk per-URL cache (`raw/_cache/`) means that even
226
+ `--only download` re-runs are near-instantaneous after the first crawl —
227
+ only newly-published feature ids hit the network.