geo-figure-mcp 0.2.8 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.8)
1
+ # geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.9)
2
2
 
3
3
  만든 사람: barkhan (지리 교사)
4
4
 
@@ -84,6 +84,18 @@ AI에게 "서울 자치구 주간 인구 지수 지도랑 산점도, 구 이름
84
84
 
85
85
  국내 기후는 `서울`, `강릉`, `대구`, `제주`처럼 한글 관측소 이름으로 조회합니다. 세계은행은 `years:true`로 국가별 연도별 값을, `year:2020`으로 한 해의 값을 조회합니다.
86
86
 
87
+ ## 기후 비교 그림과 원자료 표
88
+
89
+ “서울·강릉·대구·제주를 지도 기호 A~D로 표시하고 월별 기온·강수량 그래프 순서를 섞어 줘. 학생용 한글 파일과 교사용 원자료 CSV를 만들어 줘.”
90
+
91
+ 1. `find_data`에서 `source:"climate"`, `regions:["서울","강릉","대구","제주"]`, `asReference:true`로 자료를 조회합니다.
92
+ 2. `preview_figures`에 `{"climate":{"dataId":"자료 ID"}}`를 보냅니다. 기본값은 지도 기호 A~D, 그래프 기호 (가)~(라)입니다. 원하는 그래프 순서를 도시 이름으로 `chartOrder`에 지정할 수 있습니다.
93
+ 3. `get_source_table`에 `previewId`와 `audience:"teacher"` 또는 `"student"`를 보내 같은 그림의 표를 봅니다. 교사용에는 실제 지점·출처가, 학생용에는 그래프 기호별 월별 값이 나옵니다.
94
+ 4. 시안을 확인한 후 `make_figures`에 같은 ID, `confirmed:true`와 `formats:["hwpx"], audience:"student"`를 보내 학생용 그림을 저장합니다. 학생용 문서에는 정답이 들어가지 않습니다. HWPX 뒤에 표를 붙이려면 `appendTable:true`를 추가합니다.
95
+ 5. 같은 ID와 `formats:["csv"], audience:"teacher"`로 교사용 표를 따로 받습니다. CSV에는 기준 기간, 자료 유형, 출처 링크가 포함됩니다. 지역 통계 표에는 지도 전체 지역의 원값·지도 구간·순위와 막대에 실제 쓰인 값이 들어갑니다. `linked.digits`는 막대 값의 소수 자리만 정합니다.
96
+
97
+ 웹 연결에서 ‘figures 필수’가 뜨면 이전 도구 목록을 쓰고 있을 수 있습니다. 서버가 이 기능을 지원할 때 `preview_figures({"figures":[{"climate":{"dataId":"자료 ID"}}]})`와 `make_figures({"figures":[{"previewId":"시안 ID"}],"confirmed":true,"formats":["hwpx"],"audience":"student"})`로도 참조할 수 있습니다. 새 도구나 인자 자체가 보이지 않으면 클라이언트에서 연결의 도구 목록을 새로 불러오세요.
98
+
87
99
  ## 내장 통계와 지도 이름 맞추기
88
100
 
89
101
  - 지도와 그래프에 필요한 항목은 `bundle.items`, 지역은 `bundle.regions`(정확한 `mapName` 또는 통계표 지역명)로 고릅니다. 한 시·도의 지도용 시·군·구를 모두 받으려면 `bundle.within`을 씁니다. 예를 들어 `find_data`에 `{"source":"bundle","bundle":{"key":"daytime-population","period":"2020","items":["주간 인구 지수"],"within":["경기"]}}`를 보내면 경기도 시·군의 해당 지수만 받습니다.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "geo-figure-mcp",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "description": "지리 시험용 지도·그래프를 도형 하나하나 고칠 수 있는 PPTX·HWPX로 만드는 MCP 서버",
5
5
  "author": "barkhan",
6
6
  "mcpName": "io.github.skyblue3925-svg/geo-figure-mcp",
@@ -21,7 +21,7 @@
21
21
  "examples": "node examples/run.js",
22
22
  "start:remote": "node src/http.js",
23
23
  "demo": "node examples/demo.js",
24
- "test": "node tests/smoke.js && node tests/climate-worldbank.js && node tests/linked.js && node tests/references.js && node tests/remote-workflow.js"
24
+ "test": "node tests/smoke.js && node tests/climate-worldbank.js && node tests/linked.js && node tests/references.js && node tests/remote-workflow.js && node tests/source-workflow.js"
25
25
  },
26
26
  "keywords": [
27
27
  "mcp",
package/server.json CHANGED
@@ -4,12 +4,12 @@
4
4
  "title": "Geo Figure (지리 시험 지도·그래프)",
5
5
  "description": "지리 시험용 지도·그래프를 실제 통계로, 도형 하나하나 고칠 수 있는 PPTX·HWPX로 만든다.",
6
6
  "repository": { "url": "https://github.com/skyblue3925-svg/geo-figure-mcp", "source": "github" },
7
- "version": "0.2.8",
7
+ "version": "0.2.9",
8
8
  "packages": [
9
9
  {
10
10
  "registryType": "npm",
11
11
  "identifier": "geo-figure-mcp",
12
- "version": "0.2.8",
12
+ "version": "0.2.9",
13
13
  "transport": { "type": "stdio" },
14
14
  "environmentVariables": [
15
15
  { "name": "GEO_FIGURE_OUT", "description": "만든 파일을 저장할 폴더 (기본: 문서/지리시험자료)", "isRequired": false, "isSecret": false }
package/src/build.js CHANGED
@@ -63,11 +63,11 @@ export async function makeFigure(spec, st = loadStyle()) {
63
63
  return withFooter(figure({ title: spec.title, items: placed, source, notes: spec.notes }), st);
64
64
  }
65
65
 
66
- export function exportFigures(figs, { outDir, name = '지리자료', formats = ['pptx', 'hwpx'], answerKey, style } = {}) {
66
+ export function exportFigures(figs, { outDir, name = '지리자료', formats = ['pptx', 'hwpx'], answerKey, style, tables } = {}) {
67
67
  const st = style || loadStyle();
68
68
  fs.mkdirSync(outDir, { recursive: true });
69
69
  const files = [];
70
70
  if (formats.includes('pptx')) { const f = path.join(outDir, `${name}.pptx`); fs.writeFileSync(f, buildPptx(figs, { style: st, keyText: answerKey })); files.push(f); }
71
- if (formats.includes('hwpx')) { const f = path.join(outDir, `${name}.hwpx`); fs.writeFileSync(f, buildHwpx(figs, { style: st, keyText: answerKey })); files.push(f); }
71
+ if (formats.includes('hwpx')) { const f = path.join(outDir, `${name}.hwpx`); fs.writeFileSync(f, buildHwpx(figs, { style: st, keyText: answerKey, tables })); files.push(f); }
72
72
  return files;
73
73
  }
package/src/charts.js CHANGED
@@ -115,7 +115,7 @@ export function climateChart(spec, st = DEFAULT_STYLE) {
115
115
  const bw = (R - L) / 12;
116
116
  const bars = s.precip.map((p, m) => S.rect(L + bw * m + bw * 0.15, sp(p), bw * 0.7, B - sp(p), { fill: { k: 'solid', gray: '#BFBFBF' }, stroke: 0.15, name: `${m + 1}월 강수` }));
117
117
  g.push(S.group('강수량 막대', bars));
118
- g.push(S.line(s.temp.map((t, m) => [L + bw * m + bw / 2, sy(t)]), { stroke: 0.45, name: '기온 선' }));
118
+ g.push({ ...S.line(s.temp.map((t, m) => [L + bw * m + bw / 2, sy(t)]), { stroke: 0.45, name: '기온 선' }), keepVertices: true });
119
119
  [1, 4, 7, 10, 12].forEach((m) => g.push(S.text(L + bw * (m - 1) + bw / 2, B + 2.4, String(m), { size: st.small - 1, name: '월' })));
120
120
  items.push(S.group(`기후 그래프 ${s.label}`, g));
121
121
  });
@@ -0,0 +1,144 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ const MAP_LABELS = ['A', 'B', 'C', 'D'];
4
+ const CHART_LABELS = ['(가)', '(나)', '(다)', '(라)'];
5
+
6
+ const SOURCES = {
7
+ wmo: ['WMO 기후평년값', 'https://doi.org/10.25921/800j-vn07', 'observation'],
8
+ noaa: ['NOAA GHCN-Daily', 'https://www.ncei.noaa.gov/products/land-based-station/global-historical-climatology-network-daily', 'observation'],
9
+ beck: ['Beck et al.(2023) 0.1° 격자 추정값', 'https://doi.org/10.6084/m9.figshare.21789074', 'grid-estimate'],
10
+ };
11
+
12
+ function sourceFor(row, data, period) {
13
+ const cite = row.cite || data.cite;
14
+ const source = /^Beck/.test(cite) ? SOURCES.beck : /^NOAA GHCN-Daily/.test(cite) ? SOURCES.noaa : /^WMO/.test(cite) ? SOURCES.wmo : undefined;
15
+ if (!source) throw new Error(row.name + '의 기후 자료 출처를 확인할 수 없습니다.');
16
+ // NOAA citations include station identifiers. Use the dataset name on the question.
17
+ const caption = source[0] + (period ? ' (' + period + (source === SOURCES.noaa ? ' 중 관측 기록' : '') + ')' : '');
18
+ return { cite: row.cite || caption, caption, sourceUrl: row.sourceUrl || (source === SOURCES.wmo ? data.sourceUrl : undefined) || source[1], dataType: row.dataType || source[2] };
19
+ }
20
+
21
+ function isKoreanStation({ country, lat, lon }) {
22
+ return country === 'Rep._Korea' || (!country && lat >= 32.9 && lat <= 38.7 && lon >= 124.5 && lon <= 132);
23
+ }
24
+
25
+ function monthly(values, min) {
26
+ return Array.isArray(values) && values.length === 12 &&
27
+ [...values].every((value) => Number.isFinite(value) && value >= min);
28
+ }
29
+
30
+ function chartOrderFor(stations, order) {
31
+ const names = stations.map((station) => station.name);
32
+ if (order !== undefined) {
33
+ if (!Array.isArray(order) || order.length !== names.length || new Set(order).size !== names.length ||
34
+ order.some((name) => !names.includes(name))) {
35
+ throw new Error('chartOrder에는 모든 기후 지점의 이름을 중복 없이 한 번씩 지정하세요.');
36
+ }
37
+ return order;
38
+ }
39
+ if (names.length < 2) return names;
40
+ // Choose a reproducible non-zero rotation for these stations.
41
+ const seed = createHash('sha256').update(JSON.stringify(names)).digest()[0];
42
+ const offset = 1 + seed % (names.length - 1);
43
+ return [...names.slice(offset), ...names.slice(0, offset)];
44
+ }
45
+
46
+ function updateLabels(stations, labels) {
47
+ if (!labels || typeof labels !== 'object' || Array.isArray(labels)) {
48
+ throw new Error('labels는 기후 지점 이름과 지도 기호를 짝지은 객체여야 합니다.');
49
+ }
50
+ for (const name of Object.keys(labels)) {
51
+ if (!stations.some((station) => station.name === name)) throw new Error('기호를 지정할 기후 지점이 없습니다: ' + name);
52
+ }
53
+ const result = stations.map((station) => {
54
+ if (!Object.hasOwn(labels, station.name)) return station;
55
+ const raw = labels[station.name];
56
+ const mapLabel = typeof raw === 'string' && !/[\r\n]/.test(raw) ? raw.trim() : '';
57
+ if (!mapLabel) throw new Error('지도 기호를 비워 두거나 여러 줄로 입력할 수 없습니다.');
58
+ if (CHART_LABELS.includes(mapLabel)) throw new Error('지도와 기후 그래프에는 다른 기호를 지정하세요.');
59
+ return { ...station, mapLabel };
60
+ });
61
+ if (new Set(result.map((station) => station.mapLabel)).size !== stations.length) {
62
+ throw new Error('지도 기호가 중복됩니다. 지점마다 서로 다른 기호를 지정하세요.');
63
+ }
64
+ return result;
65
+ }
66
+
67
+ const mapPoints = (stations) => stations.map(({ lat, lon, mapLabel }) => ({ lat, lon, label: mapLabel }));
68
+
69
+ export function makeClimateFigure(data, { region, labels = {}, chartOrder, title } = {}) {
70
+ if (!Array.isArray(data?.rows) || data.rows.length < 1 || data.rows.length > MAP_LABELS.length) {
71
+ throw new Error('기후 지점을 1~4곳 지정하세요.');
72
+ }
73
+ const period = String(data.year ?? '');
74
+ const positions = new Set();
75
+ const names = new Set();
76
+ const ids = new Set();
77
+ const stations = updateLabels(data.rows.map((row, index) => {
78
+ const { id, name, station, lat, lon, warn, country, distanceKm, height, stationId, observationYears, cellLat, cellLon } = row;
79
+ if (!name || !id || names.has(name) || ids.has(id)) throw new Error('기후 지점 이름 또는 ID가 비어 있거나 중복됩니다.');
80
+ const point = lat + ',' + lon;
81
+ if (!Number.isFinite(lat) || Math.abs(lat) > 90 || !Number.isFinite(lon) || Math.abs(lon) > 180) {
82
+ throw new Error(name + '의 위도·경도를 확인할 수 없습니다.');
83
+ }
84
+ if (positions.has(point)) throw new Error('같은 좌표의 기후 지점을 둘 이상 표시할 수 없습니다: ' + name);
85
+ const { temp, precip } = row.values || {};
86
+ if (!monthly(temp, -Infinity) || !monthly(precip, 0)) {
87
+ throw new Error(name + '의 월별 기온과 강수량이 각각 12개 필요합니다.');
88
+ }
89
+ names.add(name);
90
+ ids.add(id);
91
+ positions.add(point);
92
+ return { id, name, station, lat, lon, country, warn: warn ?? null, distanceKm, height, stationId, observationYears, cellLat, cellLon, period: row.period ?? period,
93
+ mapLabel: MAP_LABELS[index], temp: [...temp], precip: [...precip], ...sourceFor(row, data, period) };
94
+ }), labels);
95
+
96
+ const korean = stations.every(isKoreanStation);
97
+ const mapRegion = region ?? (korean ? 'korea' : 'world');
98
+ if (!['korea', 'world'].includes(mapRegion)) throw new Error('region은 korea 또는 world를 지정하세요.');
99
+ if (mapRegion === 'korea' && !korean) throw new Error('국외 기후 지점을 포함할 때는 world 지도를 지정하세요.');
100
+
101
+ const order = chartOrderFor(stations, chartOrder);
102
+ for (const station of stations) station.chartLabel = CHART_LABELS[order.indexOf(station.name)];
103
+ const chartStations = order.map((name) => {
104
+ const { chartLabel, temp, precip } = stations.find((station) => station.name === name);
105
+ return { label: chartLabel, temp, precip };
106
+ });
107
+ const cites = [...new Set(stations.map((station) => station.caption))];
108
+ const cite = cites.join('; ');
109
+ const sourceUrls = [...new Set(stations.map((station) => station.sourceUrl))];
110
+
111
+ return {
112
+ title: title || '기후 지점과 월별 기온·강수량',
113
+ source: cite,
114
+ layout: 'column',
115
+ parts: [
116
+ { map: { region: mapRegion, width: 143, height: mapRegion === 'korea' ? 111 : 72, points: mapPoints(stations) } },
117
+ { chart: { type: 'climate', width: order.length > 1 ? 143 : 82.5, cellHeight: 40, stations: chartStations } },
118
+ ],
119
+ link: { version: 1, kind: 'climate', period, mapPart: 0, chartPart: 1, stations,
120
+ metadata: { period, cite, sourceUrls, ...(sourceUrls.length === 1 ? { sourceUrl: sourceUrls[0] } : {}) } },
121
+ };
122
+ }
123
+
124
+ export function relabelClimateFigure(figure, { partIndex, labels }) {
125
+ const { link, parts } = figure;
126
+ if (link.version !== 1 || link.mapPart !== partIndex || !Array.isArray(link.stations) ||
127
+ !Array.isArray(parts?.[partIndex]?.map?.points)) throw new Error('기호를 수정할 기후 지점이 없습니다.');
128
+ const stations = updateLabels(link.stations, labels);
129
+ return {
130
+ ...figure,
131
+ parts: parts.map((part, index) => index === partIndex
132
+ ? { ...part, map: { ...part.map, points: mapPoints(stations) } } : part),
133
+ link: { ...link, stations },
134
+ };
135
+ }
136
+
137
+ export function climateAnswerEntries(link) {
138
+ return [...link.stations].sort((a, b) => a.mapLabel.localeCompare(b.mapLabel, 'ko', { numeric: true })).map((station) => {
139
+ const place = station.station && station.station !== station.name ? station.name + ' (' + station.station + ')' : station.name;
140
+ const line = station.mapLabel + ' = ' + station.chartLabel + ' = ' + place;
141
+ const detail = [station.cite, station.warn].filter(Boolean).join(' · ');
142
+ return detail ? line + ' — ' + detail : line;
143
+ });
144
+ }
package/src/data.js CHANGED
@@ -105,7 +105,7 @@ export async function findData({ source, indicators = [], regions = [], year, ye
105
105
  const columns = d.columns.map((name, i) => [name, i])
106
106
  .filter(([name]) => !requested.size || requested.has(name));
107
107
  const pick = regions.length ? regions : Object.keys(d.rows).filter((k) => k !== '서울특별시');
108
- return { title: '서울 자치구 상주·주간 인구', unit: '명, 지수', cite: SOURCES['seoul-daytime'].cite, year: '2020', rows: pick.map((n) => {
108
+ return { title: '서울 자치구 상주·주간 인구', unit: '명, 지수', cite: d.source, sourceUrl: kosisTableUrl('101', 'DT_1PA2020'), year: '2020', rows: pick.map((n) => {
109
109
  const v = d.rows[n];
110
110
  if (!v) throw new Error(`없는 자치구: ${n}`);
111
111
  return { id: n, name: n, values: Object.fromEntries(columns.map(([name, i]) => [name, v[i]])) };
@@ -205,6 +205,7 @@ export function nearestStations(lat, lon, n = 3) {
205
205
  }
206
206
  function climateRow(q) {
207
207
  const W = wmo();
208
+ const period = '1991~2020';
208
209
  const spot = examSpots().find((x) => x.name === q);
209
210
  let lat, lon, station, exam = null;
210
211
  if (spot) {
@@ -215,7 +216,18 @@ function climateRow(q) {
215
216
  const c = spot.climate;
216
217
  const isGrid = c.source === 'Beck-0.1';
217
218
  const warn = isGrid ? '관측소 자료가 부족해 0.1°(약 11km) 격자 추정값(Beck 외 2023, CC BY 4.0)을 씀 — 관측값이 아님' : c.tier === 2 ? `기록이 짧은 관측소(${c.years}년, ${c.distanceKm}km) — 값이 불안정할 수 있음 [확인 필요]` : c.distanceKm > 50 ? `관측소가 ${c.distanceKm}km 떨어짐 [확인 필요]` : null;
218
- return { id: q, name: q, station: c.station, country: '', distanceKm: c.distanceKm, lat, lon, height: c.elev, exam, warn, cite: isGrid ? 'Beck et al.(2023) 0.1° 기후 자료(1991~2020)' : `NOAA GHCN-Daily ${c.station}(1991~2020 중 ${c.years}년)`, values: { temp: c.temp, precip: c.precip } };
219
+ const provenance = isGrid ? {
220
+ dataType: 'Beck 외 0.1° 격자 추정값',
221
+ sourceUrl: 'https://doi.org/10.6084/m9.figshare.21789074',
222
+ cite: 'Beck et al.(2023) 0.1° 기후 자료(1991~2020)',
223
+ } : {
224
+ dataType: 'NOAA GHCN-Daily 일별 관측 집계',
225
+ stationId: c.id,
226
+ observationYears: c.years,
227
+ sourceUrl: `https://www.ncei.noaa.gov/data/global-historical-climatology-network-daily/access/${c.id}.csv`,
228
+ cite: `NOAA GHCN-Daily ${c.station}(1991~2020 중 ${c.years}년)`,
229
+ };
230
+ return { id: q, name: q, station: c.station, country: '', distanceKm: c.distanceKm, lat, lon, height: c.elev, exam, warn, period, ...provenance, values: { temp: c.temp, precip: c.precip } };
219
231
  }
220
232
  } else if (/^-?\d+(\.\d+)?\s*,\s*-?\d+(\.\d+)?$/.test(q)) {
221
233
  [lat, lon] = q.split(',').map(Number);
@@ -232,7 +244,12 @@ function climateRow(q) {
232
244
  }
233
245
  const { s, d } = station ? { s: station, d: 0 } : nearestStations(lat, lon, 1)[0];
234
246
  const warn = d > 50 ? `가장 가까운 관측소가 ${Math.round(d)}km 떨어져 있음 — 값이 실제 지점과 다를 수 있음 [확인 필요]` : null;
235
- return { id: q, name: q, station: s[1], country: s[2].trim(), distanceKm: Math.round(d), lat: s[3], lon: s[4], height: s[5], exam, warn, values: { temp: s[6], precip: s[7] } };
247
+ return {
248
+ id: q, name: q, station: s[1], stationId: s[0], country: s[2].trim(), distanceKm: Math.round(d),
249
+ lat: s[3], lon: s[4], height: s[5], exam, warn, period,
250
+ cite: SOURCES.climate.cite, dataType: 'WMO 관측 평년값', sourceUrl: 'https://doi.org/10.25921/800j-vn07',
251
+ values: { temp: s[6], precip: s[7] },
252
+ };
236
253
  }
237
254
 
238
255
  // ---- KOSIS 공유서비스(OpenAPI) ----
@@ -275,6 +292,7 @@ export async function kosisItems({ orgId, tblId }) {
275
292
  }
276
293
  // 수록 주기 한글 → API 코드
277
294
  const PRD_CODE = { 년: 'Y', 반기: 'H', 분기: 'Q', 월: 'M', 일: 'D', 부정기: 'IR', '2년': 'F', '3년': 'F', '4년': 'F', '5년': 'F', '10년': 'F' };
295
+ const kosisTableUrl = (orgId, tblId) => `https://kosis.kr/statHtml/statHtml.do?${new URLSearchParams({ orgId, tblId })}`;
278
296
  // kosis: { orgId, tblId, itmId:'T1' 또는 'T1+T2', objL1:'ALL', objL2, …, prdSe:'Y', year:2020 (또는 start,end) }
279
297
  async function kosisData(q) {
280
298
  if (!q.orgId || !q.tblId || !q.itmId) throw new Error('kosis 에 orgId·tblId·itmId 가 필요합니다 (kosis_search → kosis_items 로 확인).');
@@ -306,7 +324,7 @@ async function kosisData(q) {
306
324
  r.year = x.PRD_DE;
307
325
  }
308
326
  const yrs = [...new Set(Object.values(rows).map((r) => r.year))];
309
- return { title, unit, cite: `${q.orgId === "101" ? "국가데이터처(통계청)" : "KOSIS"}, 「${title}」`, year: yrs.join('·'), rows: Object.values(rows) };
327
+ return { title, unit, cite: `${q.orgId === "101" ? "국가데이터처(통계청)" : "KOSIS"}, 「${title}」`, sourceUrl: kosisTableUrl(q.orgId, q.tblId), year: yrs.join('·'), rows: Object.values(rows) };
310
328
  }
311
329
 
312
330
  // ---- 내장 KOSIS 통계 묶음(data/kosis): 인증키 없이 쓴다 ----
@@ -393,7 +411,7 @@ export function bundleData(q) {
393
411
  const missing = [...provinces].filter((name) => !matchedProvinces.has(name))
394
412
  .concat([...regionNames].filter((name) => !matchedRegions.has(name)));
395
413
  if (missing.length) throw new Error('선택한 표·기간·분류에 없는 지역: ' + missing.join(', '));
396
- return { title: o.title, unit: o.units, cite: o.cite, year: period, fixed, rows: selected, mapEdition, note: `내장 KOSIS 자료(받은 날 ${o.retrieved}). 고정한 분류: ${JSON.stringify(fixed)}. 지도에는 mapName 과 map.edition='${mapEdition}' 을 쓴다(일반구는 null — 시 합계 행을 쓴다)` };
414
+ return { title: o.title, unit: o.units, cite: o.cite, sourceUrl: o.sourceUrl, year: period, fixed, rows: selected, mapEdition, note: `내장 KOSIS 자료(받은 날 ${o.retrieved}). 고정한 분류: ${JSON.stringify(fixed)}. 지도에는 mapName 과 map.edition='${mapEdition}' 을 쓴다(일반구는 null — 시 합계 행을 쓴다)` };
397
415
  }
398
416
 
399
417
  // 지도 지역 이름(시·도 짧은 이름, '시도 시군구') — 내장 자료와 이름 맞추기용
package/src/http.js CHANGED
@@ -70,7 +70,7 @@ const server = http.createServer(async (req, res) => {
70
70
  if (rel.length !== 2 || !/^[0-9a-f]{24}$/.test(rel[0]) || rel[1].includes('..') || rel[1].includes('/') || rel[1].includes('\\')) return send(res, 404, { error: 'not found' });
71
71
  const p = path.join(FILES, rel[0], rel[1]);
72
72
  if (!fs.existsSync(p)) return send(res, 404, { error: '파일이 없습니다(이미 받았거나 보관 시간이 지나 지워졌습니다).' });
73
- const type = p.endsWith('.pptx') ? 'application/vnd.openxmlformats-officedocument.presentationml.presentation' : p.endsWith('.hwpx') ? 'application/hwp+zip' : 'application/octet-stream';
73
+ const type = p.endsWith('.pptx') ? 'application/vnd.openxmlformats-officedocument.presentationml.presentation' : p.endsWith('.hwpx') ? 'application/hwp+zip' : p.endsWith('.csv') ? 'text/csv; charset=utf-8' : 'application/octet-stream';
74
74
  res.writeHead(200, { 'Content-Type': type, 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(rel[1])}`, 'Access-Control-Allow-Origin': '*' });
75
75
  const st = fs.createReadStream(p);
76
76
  st.on('end', () => { try { fs.rmSync(p, { force: true }); const d = path.dirname(p); if (!fs.readdirSync(d).length) fs.rmSync(d, { recursive: true, force: true }); } catch {} });
@@ -0,0 +1,116 @@
1
+ // Native HWPX tables. Split at row boundaries so each page begins with the column headings.
2
+ const BODY_SIZE = 9;
3
+ const NOTE_SIZE = 9;
4
+ const CELL_PAD_X = 280;
5
+ const CELL_PAD_Y = 175;
6
+
7
+ const glyphWidth = (ch) => /[ -~]/.test(ch) ? 0.8 : 1.1;
8
+ const linesOf = (value) => String(value ?? '').split(/\r\n|[\r\n]/);
9
+ const textLength = (line) => [...line].reduce((sum, ch) => sum + glyphWidth(ch), 0);
10
+
11
+ function lineCount(value, width, size) {
12
+ // Break using the same per-character wrapping as the appendix paragraph style.
13
+ const capacity = width / (size * 100);
14
+ return linesOf(value).reduce((total, line) => {
15
+ let lines = 1;
16
+ let used = 0;
17
+ for (const ch of line) {
18
+ const next = glyphWidth(ch);
19
+ if (used > 0 && used + next > capacity) {
20
+ lines++;
21
+ used = 0;
22
+ }
23
+ used += next;
24
+ }
25
+ return total + lines;
26
+ }, 0);
27
+ }
28
+
29
+ function columnWidths(columns, rows, width) {
30
+ const weights = columns.map((column, i) => {
31
+ const longest = [column, ...rows.map((row) => row[i])]
32
+ .reduce((max, value) => Math.max(max, ...linesOf(value).map(textLength)), 0);
33
+ // Preserve space for short headings even if another column has lengthy values.
34
+ return Math.min(24, Math.max(5, longest + 1));
35
+ });
36
+ const total = weights.reduce((sum, value) => sum + value, 0);
37
+ const widths = weights.map((value) => Math.floor(width * value / total));
38
+ widths[widths.length - 1] += width - widths.reduce((sum, value) => sum + value, 0);
39
+ return widths;
40
+ }
41
+
42
+ function rowHeight(row, widths) {
43
+ const lines = Math.max(...widths.map((width, i) =>
44
+ lineCount(row[i], width - 2 * CELL_PAD_X, BODY_SIZE)));
45
+ return lines * BODY_SIZE * 150 + 2 * CELL_PAD_Y;
46
+ }
47
+
48
+ const margin = `left="${CELL_PAD_X}" right="${CELL_PAD_X}" top="${CELL_PAD_Y}" bottom="${CELL_PAD_Y}"`;
49
+
50
+ function tableXml(rows, heights, widths, { width, next, plain, cellPara, cellText }) {
51
+ const height = heights.reduce((sum, value) => sum + value, 0);
52
+ const table = `<hp:tbl id="${next()}" zOrder="0" numberingType="TABLE" textWrap="TOP_AND_BOTTOM" textFlow="BOTH_SIDES" lock="0" dropcapstyle="None" pageBreak="CELL" repeatHeader="1" rowCnt="${rows.length}" colCnt="${widths.length}" cellSpacing="0" borderFillIDRef="3" noAdjust="0">`
53
+ + `<hp:sz width="${width}" widthRelTo="ABSOLUTE" height="${height}" heightRelTo="ABSOLUTE" protect="0"/>`
54
+ + '<hp:pos treatAsChar="1" affectLSpacing="0" flowWithText="1" allowOverlap="0" holdAnchorAndSO="0" vertRelTo="PARA" horzRelTo="COLUMN" vertAlign="TOP" horzAlign="LEFT" vertOffset="0" horzOffset="0"/>'
55
+ + '<hp:outMargin left="0" right="0" top="0" bottom="0"/>'
56
+ + `<hp:inMargin ${margin}/>`;
57
+ const grid = rows.map((row, ri) => {
58
+ const isHeader = ri === 0;
59
+ const cells = widths.map((w, ci) => {
60
+ const value = row[ci] ?? '';
61
+ const align = isHeader ? 'CENTER' : typeof value === 'number' ? 'RIGHT' : 'LEFT';
62
+ return `<hp:tc name="" header="${isHeader ? 1 : 0}" hasMargin="0" protect="0" editable="0" dirty="0" borderFillIDRef="3">`
63
+ + '<hp:subList id="" textDirection="HORIZONTAL" lineWrap="BREAK" vertAlign="CENTER" linkListIDRef="0" linkListNextIDRef="0" textWidth="0" textHeight="0" hasTextRef="0" hasNumRef="0">'
64
+ + plain(cellText(value), BODY_SIZE, isHeader, cellPara(align))
65
+ + '</hp:subList>'
66
+ + `<hp:cellAddr colAddr="${ci}" rowAddr="${ri}"/><hp:cellSpan colSpan="1" rowSpan="1"/>`
67
+ + `<hp:cellSz width="${w}" height="${heights[ri]}"/><hp:cellMargin ${margin}/></hp:tc>`;
68
+ });
69
+ return `<hp:tr>${cells.join('')}</hp:tr>`;
70
+ });
71
+ return table + grid.join('') + '</hp:tbl>';
72
+ }
73
+
74
+ export function tableAppendix(tables, { width, usable, next, P, charPr, paraPr, esc, firstSection = '' }) {
75
+ const text = (value) => linesOf(value).map((line) => esc(line
76
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF\p{Surrogate}]/gu, '�'))).join('<hp:lineBreak/>');
77
+ const plain = (content, size, bold, pp, pageBreak = false, beforeText = '') =>
78
+ P(`<hp:run charPrIDRef="${charPr(size, bold)}">${beforeText}<hp:t>${content}</hp:t></hp:run>`, pp, pageBreak);
79
+ const cellPara = (align) => paraPr(align, 125, 0, 0, true);
80
+ const notePara = () => paraPr('LEFT', 135, 200, 0, true);
81
+ const result = [];
82
+
83
+ for (const { title, columns, rows, notes = [] } of tables) {
84
+ const widths = columnWidths(columns, rows, width);
85
+ const headerHeight = rowHeight(columns, widths);
86
+ const firstNoteHeight = notes.length ? lineCount(notes[0], width, NOTE_SIZE) * NOTE_SIZE * 150 + 200 : 0;
87
+ // Keep room for the title, the paragraph holding the inline table, and the first note.
88
+ const limit = usable - lineCount(`${title} (계속)`, width, 11) * 1700 - 2400
89
+ - Math.min(firstNoteHeight, 6500);
90
+ let chunk = [columns];
91
+ let heights = [headerHeight];
92
+ let total = headerHeight;
93
+ let page = 0;
94
+ const flush = () => {
95
+ const label = page++ === 0 ? title : `${title} (계속)`;
96
+ const section = result.length === 0 ? firstSection : '';
97
+ result.push(plain(text(label), 11, true, paraPr('LEFT', 130, 450, 0, true), !section, section));
98
+ result.push(P(`<hp:run charPrIDRef="${charPr(BODY_SIZE, false)}">`
99
+ + tableXml(chunk, heights, widths, { width, next, plain, cellPara, cellText: text })
100
+ + '<hp:t/></hp:run>', paraPr('LEFT', 100, 480)));
101
+ chunk = [columns];
102
+ heights = [headerHeight];
103
+ total = headerHeight;
104
+ };
105
+ for (const row of rows) {
106
+ const height = rowHeight(row, widths);
107
+ if (chunk.length > 1 && total + height > limit) flush();
108
+ chunk.push(row);
109
+ heights.push(height);
110
+ total += height;
111
+ }
112
+ flush();
113
+ notes.forEach((note) => result.push(plain(text(note), NOTE_SIZE, false, notePara())));
114
+ }
115
+ return result;
116
+ }
package/src/hwpx.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { tableAppendix } from './hwpx-table.js';
1
2
  // 장면 → HWPX. 그림 한 장 = 한글 '묶음 개체' 하나. 안의 다각형·선·글상자는 묶음을 풀면 하나씩 고칠 수 있다.
2
3
  // 글꼴은 한글 기본 글꼴(함초롬)을 기본으로 써서 어느 PC 에서도 바뀌지 않게 한다.
3
4
  import fs from 'node:fs';
@@ -64,13 +65,13 @@ export function buildHwpx(figs, opts = {}) {
64
65
  };
65
66
  const PP = new Map();
66
67
  // fixed: 줄 높이를 HWPUNIT 로 고정(그림 자리 비우기)
67
- const paraPr = (align, line = 100, next = 0, fixed = 0) => {
68
- const k = `${align}|${line}|${next}|${fixed}`;
68
+ const paraPr = (align, line = 100, next = 0, fixed = 0, wrapWords = false) => {
69
+ const k = `${align}|${line}|${next}|${fixed}|${wrapWords}`;
69
70
  if (PP.has(k)) return PP.get(k);
70
71
  const m = header.match(/<hh:paraProperties itemCnt="(\d+)">/);
71
72
  const id = +m[1];
72
73
  const mg = (s) => `<hh:margin><hc:intent value="0" unit="HWPUNIT"/><hc:left value="0" unit="HWPUNIT"/><hc:right value="0" unit="HWPUNIT"/><hc:prev value="0" unit="HWPUNIT"/><hc:next value="${next * s}" unit="HWPUNIT"/></hh:margin>${fixed ? `<hh:lineSpacing type="FIXED" value="${fixed * s}" unit="HWPUNIT"/>` : `<hh:lineSpacing type="PERCENT" value="${line}" unit="HWPUNIT"/>`}`;
73
- const xml = `<hh:paraPr id="${id}" tabPrIDRef="0" condense="0" fontLineHeight="0" snapToGrid="0" suppressLineNumbers="0" checked="0" textDir="LTR"><hh:align horizontal="${align}" vertical="BASELINE"/><hh:heading type="NONE" idRef="0" level="0"/><hh:breakSetting breakLatinWord="KEEP_WORD" breakNonLatinWord="KEEP_WORD" widowOrphan="0" keepWithNext="0" keepLines="0" pageBreakBefore="0" lineWrap="BREAK"/><hh:autoSpacing eAsianEng="0" eAsianNum="0"/><hp:switch><hp:case hp:required-namespace="http://www.hancom.co.kr/hwpml/2016/HwpUnitChar">${mg(1)}</hp:case><hp:default>${mg(2)}</hp:default></hp:switch><hh:border borderFillIDRef="2" offsetLeft="0" offsetRight="0" offsetTop="0" offsetBottom="0" connect="0" ignoreMargin="0"/></hh:paraPr>`;
74
+ const xml = `<hh:paraPr id="${id}" tabPrIDRef="0" condense="0" fontLineHeight="0" snapToGrid="0" suppressLineNumbers="0" checked="0" textDir="LTR"><hh:align horizontal="${align}" vertical="BASELINE"/><hh:heading type="NONE" idRef="0" level="0"/><hh:breakSetting breakLatinWord="${wrapWords ? 'BREAK_WORD' : 'KEEP_WORD'}" breakNonLatinWord="${wrapWords ? 'BREAK_WORD' : 'KEEP_WORD'}" widowOrphan="0" keepWithNext="0" keepLines="0" pageBreakBefore="0" lineWrap="BREAK"/><hh:autoSpacing eAsianEng="0" eAsianNum="0"/><hp:switch><hp:case hp:required-namespace="http://www.hancom.co.kr/hwpml/2016/HwpUnitChar">${mg(1)}</hp:case><hp:default>${mg(2)}</hp:default></hp:switch><hh:border borderFillIDRef="2" offsetLeft="0" offsetRight="0" offsetTop="0" offsetBottom="0" connect="0" ignoreMargin="0"/></hh:paraPr>`;
74
75
  header = header.replace(m[0], `<hh:paraProperties itemCnt="${id + 1}">`).replace('</hh:paraProperties>', xml + '</hh:paraProperties>');
75
76
  PP.set(k, id);
76
77
  return id;
@@ -162,7 +163,7 @@ export function buildHwpx(figs, opts = {}) {
162
163
  }
163
164
  if (it.t === 'poly') return it.rings.filter((r, i) => !it.rings.some((o, j) => j !== i && ringArea(o) > ringArea(r) && inside(r[0], o))).forEach((r) => objs.push(polygon(r, it.fill, it.stroke, it.name)));
164
165
  if (it.t === 'line') {
165
- const pts = simplifyLine(it.pts);
166
+ const pts = it.keepVertices ? it.pts : simplifyLine(it.pts);
166
167
  for (let i = 1; i < pts.length; i++) objs.push(seg(pts[i - 1], pts[i], { ...it, arrow: it.arrow && i === pts.length - 1 }));
167
168
  return;
168
169
  }
@@ -172,7 +173,7 @@ export function buildHwpx(figs, opts = {}) {
172
173
  if (it.t === 'text') objs.push(text(it));
173
174
  }
174
175
 
175
- const P = (inner, pp) => `<hp:p id="0" paraPrIDRef="${pp}" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">${inner}</hp:p>`;
176
+ const P = (inner, pp, pageBreak = false) => `<hp:p id="0" paraPrIDRef="${pp}" styleIDRef="0" pageBreak="${Number(pageBreak)}" columnBreak="0" merged="0">${inner}</hp:p>`;
176
177
  const cTitle = charPr(10, true), cBody = charPr(10, false);
177
178
  const drawings = figs.map((f, k) => {
178
179
  // 개체가 묶음 밖으로 나가면 한글이 묶음을 줄여 버린다 → 실제 범위를 재고, 음수면 옮겨서 다시 만든다
@@ -205,6 +206,10 @@ export function buildHwpx(figs, opts = {}) {
205
206
  // 그림은 '글 앞으로' 띄우고, 그림 높이만큼 고정 높이 문단으로 자리를 비운다 → 묶음을 풀어도 조각이 밀리지 않는다
206
207
  body.push(P(`<hp:run charPrIDRef="${cBody}">${cont}<hp:t/></hp:run>`, paraPr('LEFT', 100, u(8), H)));
207
208
  });
209
+ if (opts.tables?.length) {
210
+ body.push(...tableAppendix(opts.tables, { width: (landscape ? PAGE_H : PAGE_W) - 2 * ML,
211
+ usable, next, P, charPr, paraPr, esc, firstSection: drawings.length ? '' : secPr(landscape) }));
212
+ }
208
213
  if (opts.keyText) {
209
214
  opts.keyText.split('\n').forEach((l, i) => body.push(`<hp:p id="0" paraPrIDRef="${paraPr('LEFT', 150)}" styleIDRef="0" pageBreak="${i === 0 ? 1 : 0}" columnBreak="0" merged="0"><hp:run charPrIDRef="${i === 0 ? cTitle : cBody}"><hp:t>${esc(l)}</hp:t></hp:run></hp:p>`));
210
215
  }
package/src/linked.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { listRegions } from './maps.js';
2
2
  import { CLASS_FILLS } from './scene.js';
3
+ import { climateAnswerEntries, relabelClimateFigure } from './climate-linked.js';
4
+
5
+ export { makeClimateFigure } from './climate-linked.js';
3
6
 
4
7
  function text(value) {
5
8
  return typeof value === 'string' ? value.trim() : '';
@@ -38,13 +41,16 @@ function categoryLabels(chartRegions, regions, labels) {
38
41
  return categories;
39
42
  }
40
43
 
41
- export function makeLinkedFigure(data, { indicator, within, breaks, top, labels = {}, title } = {}) {
44
+ export function makeLinkedFigure(data, { indicator, within, breaks, top, labels = {}, title, digits } = {}) {
42
45
  if (!text(indicator)) throw new Error('indicator에 자료의 지표 이름을 지정하세요.');
43
46
  if (!Array.isArray(breaks) || breaks.length < 1 || breaks.length >= CLASS_FILLS.length ||
44
47
  breaks.some((value, i) => !Number.isFinite(value) || (i > 0 && value <= breaks[i - 1]))) {
45
48
  throw new Error('breaks에는 유한한 숫자 1~' + (CLASS_FILLS.length - 1) + '개를 오름차순으로 지정하세요.');
46
49
  }
47
50
  if (top !== undefined && (!Number.isSafeInteger(top) || top < 1)) throw new Error('top에는 양의 정수를 지정하세요.');
51
+ if (digits !== undefined && (!Number.isInteger(digits) || digits < 0 || digits > 6)) {
52
+ throw new Error('digits에는 0~6 사이 정수를 지정하세요.');
53
+ }
48
54
  if (!Array.isArray(data?.rows) || !data.rows.length) throw new Error('자료에 지역 행이 없습니다.');
49
55
 
50
56
  const seoulDaytime = data.title === '서울 자치구 상주·주간 인구' && String(data.year) === '2020';
@@ -102,16 +108,18 @@ export function makeLinkedFigure(data, { indicator, within, breaks, top, labels
102
108
  const chart = {
103
109
  type: 'bar',
104
110
  categories: categoryLabels(chartRegions, regions, symbols),
105
- series: [{ name: indicator, values: plotted.map((r) => r.value) }],
111
+ series: [{ name: indicator, values: plotted.map((r) => digits === undefined ? r.value : Number(r.value.toFixed(digits))) }],
106
112
  unit,
107
113
  };
108
114
  const cite = text(data.cite);
115
+ const sourceUrl = text(data.sourceUrl);
109
116
  const source = [cite, period && !cite.includes(period) ? period : ''].filter(Boolean).join(', ');
110
117
  return {
111
118
  title: text(title) || text(data.title) || indicator,
112
119
  source,
113
120
  parts: [{ map }, { chart }],
114
- link: { version: 1, mapPart: 0, chartPart: 1, indicator, unit, regions, chartRegions },
121
+ link: { version: 1, mapPart: 0, chartPart: 1, indicator, unit, regions, chartRegions,
122
+ ...(digits === undefined ? {} : { digits }), metadata: { period, cite, ...(sourceUrl ? { sourceUrl } : {}) } },
115
123
  };
116
124
  }
117
125
 
@@ -137,6 +145,7 @@ function chartLabels(chart) {
137
145
  }
138
146
 
139
147
  export function relabelFigure(figure, { partIndex = 0, labels }) {
148
+ if (figure.link?.kind === 'climate') return relabelClimateFigure(figure, { partIndex, labels });
140
149
  const parts = figure.parts || [figure];
141
150
  const map = parts[partIndex]?.map;
142
151
  if (!map) throw new Error('기호를 수정할 지도 부분이 없습니다.');
@@ -177,6 +186,11 @@ export function figureAnswerKey(figures) {
177
186
  const sections = [];
178
187
  for (const [i, figure] of figures.entries()) {
179
188
  const link = figure.link?.version === 1 ? figure.link : undefined;
189
+ const heading = figures.length > 1 ? [(i + 1) + '. ' + (figure.title || '그림')] : [];
190
+ if (link?.kind === 'climate') {
191
+ sections.push([...heading, ...climateAnswerEntries(link)].join('\n'));
192
+ continue;
193
+ }
180
194
  const map = figure.parts?.[link?.mapPart ?? figure.legacyLabelMapPart]?.map;
181
195
  if (!map?.labels) continue;
182
196
  const labels = Object.entries(map.labels).sort(([, a], [, b]) => a.localeCompare(b, 'ko', { numeric: true }));
@@ -185,7 +199,7 @@ export function figureAnswerKey(figures) {
185
199
  const region = link?.regions.find((r) => r.mapName === name);
186
200
  return symbol + ' = ' + name + (region ? ' (' + link.indicator + ' ' + region.value + ' ' + link.unit + ')' : '');
187
201
  });
188
- sections.push([...(figures.length > 1 ? [(i + 1) + '. ' + (figure.title || '그림')] : []), ...entries].join('\n'));
202
+ sections.push([...heading, ...entries].join('\n'));
189
203
  }
190
204
  return sections.length ? ['정답표', ...sections].join('\n') : undefined;
191
205
  }
@@ -0,0 +1,117 @@
1
+ function detail(label, value) {
2
+ return value == null || value === '' ? '' : label + ' ' + value;
3
+ }
4
+
5
+ function regionTable(figure, teacher) {
6
+ const { link } = figure;
7
+ const map = figure.parts?.[link.mapPart]?.map;
8
+ const chart = figure.parts?.[link.chartPart]?.chart;
9
+ const plottedValues = chart?.series?.[0]?.values;
10
+ if (!Array.isArray(link.regions) || !Array.isArray(link.chartRegions) || !map || !Array.isArray(plottedValues)) return undefined;
11
+
12
+ const metadata = link.metadata ?? {};
13
+ const hasLabels = Object.keys(map.labels ?? {}).length > 0;
14
+ const chartIndex = new Map(link.chartRegions.map((name, i) => [name, i]));
15
+ const regions = [...link.regions].sort((a, b) => b.value - a.value);
16
+ const suffix = link.unit ? ' (' + link.unit + ')' : '';
17
+ const notes = [
18
+ detail('지표', link.indicator),
19
+ detail('자료 시기', metadata.period),
20
+ detail('출처', metadata.cite ?? figure.source),
21
+ detail('원자료', metadata.sourceUrl),
22
+ '순위는 원값이 큰 순서입니다. 원값이 같으면 같은 순위를 표시합니다.',
23
+ ].filter(Boolean);
24
+ if (Number.isInteger(link.digits)) notes.push('그래프 값은 소수 ' + link.digits + '자리까지 반올림한 값입니다.');
25
+ if (hasLabels) notes.push('기호 없음은 지도나 그래프에 지역 기호가 표시되지 않은 경우입니다.');
26
+
27
+ let rank = 0;
28
+ const rows = regions.map((region, i) => {
29
+ if (i === 0 || region.value !== regions[i - 1].value) rank = i + 1;
30
+ const index = chartIndex.get(region.mapName);
31
+ const included = index !== undefined;
32
+ const mapLabel = Object.hasOwn(map.labels ?? {}, region.mapName) ? map.labels[region.mapName] : '';
33
+ const label = mapLabel || (hasLabels ? '기호 없음' : chart.categories?.[index] || region.mapName);
34
+ const classLabel = map.legend?.[map.classes?.[region.mapName]] ?? '';
35
+ return [...(teacher ? [region.mapName, mapLabel || '기호 없음'] : [label]),
36
+ region.value, included ? plottedValues[index] ?? '' : '', classLabel, rank, included ? '포함' : '미포함'];
37
+ });
38
+ return {
39
+ title: '그림에 사용한 자료 · 지역 통계',
40
+ columns: [...(teacher ? ['지역명', '지도 기호'] : [hasLabels ? '지역 기호' : '지역']),
41
+ '원값' + suffix, '그래프 값' + suffix, '지도 범례', '순위', '그래프 포함'],
42
+ rows,
43
+ notes,
44
+ };
45
+ }
46
+
47
+ function climateTable(figure, teacher) {
48
+ const { link } = figure;
49
+ if (!Array.isArray(link.stations)) return undefined;
50
+ const chartStations = figure.parts?.[link.chartPart]?.chart?.stations;
51
+ if (!Array.isArray(chartStations)) return undefined;
52
+
53
+ const period = link.period ?? link.metadata?.period;
54
+ const columns = [...(teacher ? ['지도 기호', '그래프 기호', '실제 지점'] : ['그래프 기호']),
55
+ '월', '월평균 기온 (℃)', '월 강수량 (mm)', ...(teacher ? ['자료 출처 번호'] : [])];
56
+ const rows = [];
57
+ const notes = [detail('자료 기준 기간', period)].filter(Boolean);
58
+ if (teacher) {
59
+ for (const [index, station] of link.stations.entries()) {
60
+ const sourceNumber = index + 1;
61
+ for (let month = 0; month < 12; month++) {
62
+ rows.push([station.mapLabel, station.chartLabel, station.name, month + 1, station.temp[month], station.precip[month], sourceNumber]);
63
+ }
64
+ const provenance = [
65
+ station.name, station.station, detail('관측소 ID', station.stationId),
66
+ station.dataType, detail('자료 기준 기간', station.period ?? period),
67
+ detail('최소 집계 연수', station.observationYears), station.cite, station.sourceUrl, station.warn,
68
+ ].filter(Boolean);
69
+ notes.push(sourceNumber + '. ' + provenance.join(' · '));
70
+ }
71
+ } else {
72
+ for (const station of chartStations) {
73
+ for (let month = 0; month < 12; month++) {
74
+ rows.push([station.label, month + 1, station.temp[month], station.precip[month]]);
75
+ }
76
+ }
77
+ notes.push('지점별 월평균 기온과 월 강수량입니다.');
78
+ }
79
+ return { title: '그림에 사용한 자료 · 월별 기후', columns, rows, notes };
80
+ }
81
+
82
+ export function sourceTable(figure, audience) {
83
+ if (audience !== 'teacher' && audience !== 'student') throw new Error('audience에는 teacher 또는 student를 지정하세요.');
84
+ const linked = figure?.link;
85
+ const table = linked?.version === 1 && (linked.kind === 'climate'
86
+ ? climateTable(figure, audience === 'teacher') : regionTable(figure, audience === 'teacher'));
87
+ if (!table) throw new Error('이 그림에는 원자료 연결이 없습니다. 통계 dataId로 시안을 먼저 만드세요.');
88
+ return table;
89
+ }
90
+
91
+ function csvCell(value) {
92
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
93
+ const text = value == null ? '' : String(value);
94
+ // Quoting alone does not prevent Excel from evaluating a text cell as a formula.
95
+ const safe = /^(?:[\s\u200B\uFEFF]*[=+\-@=+-@]|[\t\r\n])/u.test(text) ? "'" + text : text;
96
+ return '"' + safe.replaceAll('"', '""') + '"';
97
+ }
98
+
99
+ export function tableCsv(table, figure, audience) {
100
+ const { link } = figure;
101
+ const teacher = audience === 'teacher';
102
+ const columns = [...table.columns, '자료 기간'];
103
+ const period = link.metadata?.period || link.period || '';
104
+ let rows;
105
+ if (link.kind === 'climate' && teacher) {
106
+ columns.push('관측소·격자 이름', '관측소 ID', '자료 유형', '출처', '원자료 URL', '참고');
107
+ rows = table.rows.map(row => {
108
+ const station = link.stations[row.at(-1) - 1];
109
+ return [...row, station.period || period, station.station, station.stationId, station.dataType,
110
+ station.cite, station.sourceUrl, station.warn];
111
+ });
112
+ } else {
113
+ columns.push('출처', '원자료 URL');
114
+ rows = table.rows.map(row => [...row, period, link.metadata?.cite || figure.source, link.metadata?.sourceUrl || '']);
115
+ }
116
+ return '\uFEFF' + [columns, ...rows].map(row => row.map(csvCell).join(',')).join('\r\n') + '\r\n';
117
+ }
package/src/tools.js CHANGED
@@ -3,7 +3,8 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { createReferences } from './references.js';
6
- import { makeLinkedFigure, relabelFigure, figureAnswerKey } from './linked.js';
6
+ import { sourceTable, tableCsv } from './source-table.js';
7
+ import { makeLinkedFigure, makeClimateFigure, relabelFigure, figureAnswerKey } from './linked.js';
7
8
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
9
  import { z } from 'zod';
9
10
  import { SOURCES, findData, transform, round, assignLabels, suggestRegions, examSpots, kosisSearch, kosisItems, setKosisKey, bundleList, withKosisKey } from './data.js';
@@ -50,6 +51,7 @@ const INSTRUCTIONS = [
50
51
  '기호를 비교할 때만 4종 시안을 요청한다. 명세가 같으면 previewId를 재사용한다.',
51
52
  '행정구역 판은 자료 연도에 맞춘다. 정답표는 로컬 파일 마지막 장 또는 원격 응답에 둔다.',
52
53
  '내장 한국 통계 지도+막대는 find_data(asReference:true) → preview_figures(linked) → make_figures(previewId). 시안 기호는 preview_figures(edit)로 바꾼다.',
54
+ '기후는 find_data(asReference:true), preview_figures(climate:{dataId})를 쓴다. 원자료 표는 요청 시에만 get_source_table(previewId,audience)로 본다.',
53
55
  '필요할 때 guide의 topic으로 workflow 또는 spec을 선택한다.',
54
56
  ].join('\n');
55
57
  const MAX_DATA_BYTES = 256 * 1024;
@@ -80,11 +82,34 @@ const linkedFigure = z.strictObject({
80
82
  indicator: z.string(),
81
83
  within: z.array(z.string()).min(1).optional().describe('시·군·구 지도 범위. 생략하면 전국 시·도(서울 전용 자료는 서울 자치구)'),
82
84
  breaks: z.array(z.number()).min(1).max(5).describe('단계 하한값 목록(오름차순). 예: [100]'),
85
+ digits: z.number().int().min(0).max(6).optional().describe('막대 값의 소수 자리. 순위와 지도 구간은 원표 값 기준'),
83
86
  top: z.number().int().positive().optional().describe('막대만 상위 N곳으로 제한'),
84
87
  labels: z.record(z.string(), z.string().min(1)).optional().describe('mapName별 기호'),
85
88
  title: z.string().optional(),
86
89
  });
87
90
 
91
+ const climateFigure = z.strictObject({
92
+ dataId: z.string(),
93
+ region: z.enum(['korea', 'world']).optional(),
94
+ labels: z.record(z.string(), z.string().min(1)).optional().describe('도시별 지도 기호'),
95
+ chartOrder: z.array(z.string()).optional().describe('그래프에 표시할 도시 순서. 생략하면 자동 배치'),
96
+ title: z.string().optional(),
97
+ });
98
+ const tableAudience = z.enum(['teacher', 'student']);
99
+
100
+ // Some older clients validate against a cached schema that requires figures.
101
+ // A single reference inside that array carries the same operation and validation.
102
+ function acceptFigureReference(args, schemas) {
103
+ if (args.figures?.length !== 1) return args;
104
+ const item = args.figures[0];
105
+ for (const [key, schema] of Object.entries(schemas)) {
106
+ if (!Object.hasOwn(item, key)) continue;
107
+ if (Object.keys(item).length !== 1 || args[key] !== undefined) throw new Error('참조와 그림 명세를 함께 지정할 수 없습니다.');
108
+ return { ...args, figures: undefined, [key]: schema.parse(item[key]) };
109
+ }
110
+ return args;
111
+ }
112
+
88
113
  function editSavedMap(edit) {
89
114
  const { name, path: file } = edit;
90
115
  if ((name === undefined) === (file === undefined)) throw new Error('name 또는 path 하나를 지정하세요.');
@@ -154,16 +179,16 @@ server.tool('find_data', '실제 통계를 찾는다. 결과에 출처(cite)와
154
179
  }).passthrough().optional().describe('source가 bundle일 때 사용. 지도와 그래프에 필요한 항목과 지역만 요청한다.'),
155
180
  year: z.number().optional().describe('특정 연도. 비우면 가장 최근'),
156
181
  years: z.boolean().optional().describe('true 면 연도별 전체(시계열)'),
157
- asReference: z.boolean().optional().describe('내장 시·도·시군구 또는 서울 통계로 지도+막대를 만들 때 true. 행 대신 dataId를 반환'),
182
+ asReference: z.boolean().optional().describe('한국 통계 또는 기후 자료를 지도·그래프에 연결할 때 true. 행 대신 dataId를 반환'),
158
183
  }, wrap(async (a) => {
159
184
  if (remote && a.source === 'kosis') throw new Error('원격 서버에서는 내장 자료 bundle을 쓰세요. KOSIS 직접 조회는 로컬에서 가능합니다.');
160
- if (a.asReference && !['bundle', 'seoul-daytime'].includes(a.source)) throw new Error('dataId는 bundle 또는 seoul-daytime 통계에서 지원합니다.');
185
+ if (a.asReference && !['bundle', 'seoul-daytime', 'climate'].includes(a.source)) throw new Error('dataId는 bundle, seoul-daytime, climate 통계에서 지원합니다.');
161
186
  const data = await findData(a);
162
187
  if (!a.asReference) return data;
163
188
  if (!data.rows.length) throw new Error('선택한 조건에 통계 행이 없습니다.');
164
189
  if (Buffer.byteLength(JSON.stringify(data)) > MAX_DATA_BYTES) throw new Error('참조할 통계가 너무 큽니다. 지표·지역을 좁혀 주세요.');
165
190
  const { title, year, unit, cite, mapEdition } = data;
166
- return { dataId: datasets.put(data), rowCount: data.rows.length, title, year, unit, cite, mapEdition, indicators: Object.keys(data.rows[0].values) };
191
+ return { dataId: datasets.put({ source: a.source, data }), rowCount: data.rows.length, title, year, unit, cite, mapEdition, indicators: Object.keys(data.rows[0].values) };
167
192
  }));
168
193
 
169
194
  server.tool('list_exam_climate_spots', '평가원 기후 기출 지점. 후보 이름과 기후 기호만 필요하면 summary:true를 쓴다.', {
@@ -235,18 +260,34 @@ server.tool('assign_labels', '지역 이름을 A~E 또는 (가)~(마) 기호로
235
260
  seed: z.number().optional(),
236
261
  }, wrap((a) => assignLabels(a.names, a)));
237
262
 
263
+ server.tool('get_source_table', '같은 시안의 그림에 사용한 자료표를 본다. 교사용은 지명·출처, 학생용은 그림 기호를 사용한다.', {
264
+ previewId: z.string(),
265
+ audience: tableAudience,
266
+ figure: z.number().int().positive().optional().describe('여러 그림 중 번호(1부터)'),
267
+ }, wrap(({ previewId, audience, figure }) => {
268
+ const preview = previews.get(previewId);
269
+ if (!preview) throw new Error('시안 ID가 없거나 만료되었습니다. 시안을 다시 만드세요.');
270
+ if (!figure && preview.figures.length !== 1) throw new Error('자료표를 볼 그림 번호(figure)를 지정하세요.');
271
+ const spec = preview.figures[(figure || 1) - 1];
272
+ if (!spec) throw new Error('해당 그림 번호가 없습니다.');
273
+ return sourceTable(spec, audience);
274
+ }));
275
+
238
276
  server.tool('make_figures', '그림 명세로 PPTX·HWPX 파일을 만든다. 만들기 전에 교사에게 계획 요약을 보여 주고 확인을 받았는지 먼저 확인한다. 명세 작성법은 guide.', {
239
277
  figures: figureSpecs.optional().describe('그림 명세 목록. guide의 spec 참고'),
240
278
  previewId: z.string().optional().describe('확인한 시안 ID. figures 대신 사용'),
241
279
  labelStyle: z.enum(['halo', 'plain', 'box', 'circle']).optional().describe('기호 비교 시안에서 교사가 선택한 스타일'),
242
280
  name: z.string().default('지리자료').describe('파일 이름(확장자 제외)'),
243
- formats: z.array(z.enum(['pptx', 'hwpx'])).default(['pptx', 'hwpx']),
281
+ formats: z.array(z.enum(['pptx', 'hwpx', 'csv'])).min(1).default(['pptx', 'hwpx']),
282
+ appendTable: z.boolean().optional().describe('HWPX에 그림에 사용한 자료표를 덧붙인다'),
283
+ audience: tableAudience.optional().describe('학생용 문서는 정답을 분리한다. 표 기본값은 student. teacher는 지명·출처·기호 대응을 공개한다'),
244
284
  answerKey: z.string().optional().describe(remote ? '정답표 — 원격 서버에서는 파일에 넣지 않고 대화창에만 돌려준다(시험 보안)' : '정답표 — 파일 마지막 장에 들어간다. 첫 줄은 제목'),
245
285
  ...(remote ? {} : { outDir: z.string().optional().describe(`저장 폴더(기본 ${OUT})`) }),
246
286
  style: figureStyle.optional().describe('이번 파일에만 쓸 글꼴·크기(학교 양식)'),
247
287
  confirmed: z.boolean().describe('교사가 계획 요약을 보고 "예"라고 했으면 true'),
248
288
  }, wrap(async (a) => {
249
289
  if (!a.confirmed) throw new Error('먼저 계획 요약(지표·연도·지역·가공·기호 순서·출력·출처)을 교사에게 보여 주고 확인을 받으세요.');
290
+ a = acceptFigureReference(a, { previewId: z.string().min(1) });
250
291
  let { figures, style } = a;
251
292
  let st;
252
293
  if (a.previewId !== undefined) {
@@ -263,37 +304,62 @@ server.tool('make_figures', '그림 명세로 PPTX·HWPX 파일을 만든다.
263
304
  throw new Error('figures 또는 previewId를 보내세요. labelStyle은 지도 명세 안에 지정할 수 있습니다.');
264
305
  }
265
306
  if (remote && figures.length > 12) throw new Error('한 번에 그림은 12장까지 만들 수 있습니다.');
307
+ if (a.appendTable && !a.formats.includes('hwpx')) throw new Error('자료표를 붙이려면 formats에 hwpx를 포함하세요.');
308
+ const wantsCsv = a.formats.includes('csv');
309
+ const wantsTable = wantsCsv || a.appendTable;
310
+ const audience = a.audience || 'student';
311
+ const tables = wantsTable ? figures.map(f => sourceTable(f, audience)) : [];
266
312
  st ??= { ...loadStyle(), ...style };
267
313
  const figs = [];
268
- for (const f of figures) figs.push(await makeFigure(f, st));
269
- const safe = String(a.name || '지리자료').replace(/[\/:*?"<>|]/g, '_').slice(0, 60);
314
+ const documentFormats = a.formats.filter(format => format !== 'csv');
315
+ if (documentFormats.length) {
316
+ for (const f of figures) figs.push(await makeFigure(f, st));
317
+ }
318
+ const safe = String(a.name || '지리자료').replace(/[\\/:*?"<>|]/g, '_').slice(0, 60);
319
+ const suffix = audience === 'teacher' ? '교사용' : '학생용';
320
+ const docName = a.appendTable || a.audience ? safe + '_' + suffix : safe;
270
321
  const dir = remote ? publish.newDir() : (a.outDir || OUT);
271
322
  const answerKey = [a.answerKey, figureAnswerKey(figures)].filter(Boolean).join('\n') || undefined;
272
- const paths = exportFigures(figs, { outDir: dir, name: safe, formats: a.formats, answerKey: remote ? undefined : answerKey, style: st });
323
+ const keepKeyInChat = remote || ((wantsTable || a.audience) && audience === 'student');
324
+ const paths = exportFigures(figs, { outDir: dir, name: docName, formats: documentFormats,
325
+ answerKey: keepKeyInChat ? undefined : answerKey, tables: a.appendTable ? tables : undefined, style: st });
326
+ if (wantsCsv) {
327
+ tables.forEach((table, i) => {
328
+ const index = tables.length > 1 ? '_' + (i + 1) : '';
329
+ const file = path.join(dir, safe + '_자료표_' + suffix + index + '.csv');
330
+ fs.writeFileSync(file, tableCsv(table, figures[i], audience), 'utf8');
331
+ paths.push(file);
332
+ });
333
+ }
273
334
  const files = remote ? paths.map((p) => publish.url(p)) : paths;
274
- // 고치기용 설계도: 같은 폴더에 <이름>.geo-figure.json — 나중에 open_figure_spec 으로 읽어 일부만 바꿔 다시 만든다
275
335
  let specFile = null;
276
- if (!remote) { specFile = path.join(dir, `${safe}.geo-figure.json`); fs.writeFileSync(specFile, JSON.stringify({ name: safe, formats: a.formats, style, answerKey: a.answerKey, figures }, null, 1)); }
277
- return { files, ...(updateNotice() ? { update: updateNotice() } : {}), ...(remote ? { expires: `내려받기 주소는 ${publish.keepText} 동안, 한 번만 열립니다(받으면 서버에서 바로 지움). 꼭 내려받아 저장하세요.`, ...(answerKey ? { answerKey, answerKeyNote: '시험 보안을 위해 정답표는 파일에 넣지 않았습니다. 이 내용을 교사에게 그대로 보여 주세요.' } : {}) } : {}), sizes_mm: figs.map((f) => ({ title: f.title, w: round(f.w), h: round(f.h) })), ...(specFile ? { specFile } : {}), note: '그림마다 묶음 하나 — PPTX는 그룹 해제, HWPX는 개체 풀기를 한 번만 하면 시군구·기호·선·범례가 모두 따로 움직인다(도형 이름이 지역 이름). 범례 칸과 지역은 같은 무늬라 서식 복사로 단계를 바꿀 수 있다. 시안의 범례·기호는 preview_figures의 edit로 바꿀 수 있다.' };
336
+ if (!remote && documentFormats.length) {
337
+ specFile = path.join(dir, docName + '.geo-figure.json');
338
+ fs.writeFileSync(specFile, JSON.stringify({ name: docName, formats: documentFormats, style, answerKey: a.answerKey, figures }, null, 1));
339
+ }
340
+ return { files, ...(updateNotice() ? { update: updateNotice() } : {}), ...(remote ? { expires: `내려받기 주소는 ${publish.keepText} 동안, 한 번만 열립니다(받으면 서버에서 바로 지움). 꼭 내려받아 저장하세요.` } : {}), ...(keepKeyInChat && answerKey ? { answerKey, answerKeyNote: '교사용 정답표입니다.' } : {}), sizes_mm: figs.map((f) => ({ title: f.title, w: round(f.w), h: round(f.h) })), ...(specFile ? { specFile } : {}), note: '그림마다 묶음 하나 — PPTX는 그룹 해제, HWPX는 개체 풀기를 한 번만 하면 시군구·기호·선·범례가 모두 따로 움직인다(도형 이름이 지역 이름). 범례 칸과 지역은 같은 무늬라 서식 복사로 단계를 바꿀 수 있다. 시안의 범례·기호는 preview_figures의 edit로 바꿀 수 있다.' };
278
341
  }));
279
342
 
280
343
  server.tool('preview_figures', '파일을 만들기 전 PNG 시안을 보여 준다. 기호 비교가 필요하면 compareLabelStyles:true를 쓴다. previewId는 make_figures에서 재사용할 수 있다.', {
281
344
  figures: figureSpecs.optional().describe('make_figures와 같은 그림 명세'),
282
345
  linked: linkedFigure.optional().describe('find_data의 dataId로 같은 통계의 지도와 막대를 함께 생성'),
346
+ climate: climateFigure.optional().describe('기후 dataId로 지점 지도와 월별 기온·강수량 비교 그래프 생성'),
283
347
  edit: editFields.extend({ previewId: z.string() }).optional().describe('기존 시안의 범례·기호를 수정한다'),
284
348
  ...(remote ? {} : { saved: savedEdit.optional().describe('로컬 설계도에서 범례·기호만 수정. figures 대신 사용') }),
285
349
  compareLabelStyles: z.boolean().optional().describe('true면 첫 지도에 기호 스타일 4개를 비교'),
286
350
  style: figureStyle.optional(),
287
351
  }, async (a) => {
288
352
  try {
353
+ a = acceptFigureReference(a, { linked: linkedFigure, climate: climateFigure });
289
354
  let { figures, style } = a;
290
355
  let savedIndex, inheritedStyle;
291
- const inputs = [figures, a.saved, a.linked, a.edit].filter(v => v !== undefined);
292
- if (inputs.length !== 1) throw new Error('figures, linked, edit 또는 로컬 saved 중 하나만 지정하세요.');
293
- if (a.linked) {
294
- const data = datasets.get(a.linked.dataId);
295
- if (!data) throw new Error('통계 ID가 만료되었거나 없습니다. find_data를 다시 호출하세요.');
296
- figures = [makeLinkedFigure(data, a.linked)];
356
+ const inputs = [figures, a.saved, a.linked, a.climate, a.edit].filter(v => v !== undefined);
357
+ if (inputs.length !== 1) throw new Error('figures, linked, climate, edit 또는 로컬 saved 중 하나만 지정하세요.');
358
+ if (a.linked || a.climate) {
359
+ const entry = datasets.get((a.linked || a.climate).dataId);
360
+ if (!entry) throw new Error('통계 ID가 만료되었거나 없습니다. find_data를 다시 호출하세요.');
361
+ if ((entry.source === 'climate') !== Boolean(a.climate)) throw new Error('기후 dataId는 climate, 지역 통계 dataId는 linked에 지정하세요.');
362
+ figures = [a.climate ? makeClimateFigure(entry.data, a.climate) : makeLinkedFigure(entry.data, a.linked)];
297
363
  }
298
364
  if (a.edit) {
299
365
  if (style || a.compareLabelStyles) throw new Error('edit는 style 또는 기호 비교와 함께 쓸 수 없습니다.');
@@ -325,7 +391,7 @@ server.tool('preview_figures', '파일을 만들기 전 PNG 시안을 보여 준
325
391
  const maxBytes = a.saved ? MAX_SAVED_SPEC_BYTES : MAX_PREVIEW_SPEC_BYTES;
326
392
  const canReuse = Buffer.byteLength(JSON.stringify({ figures, style })) <= maxBytes;
327
393
  if (a.saved && !canReuse) throw new Error('수정된 설계도가 너무 큽니다. open_figure_spec으로 수정하세요.');
328
- if ((a.linked || a.edit) && !canReuse) throw new Error('시안이 너무 큽니다. 지역 수를 줄여 다시 만드세요.');
394
+ if ((a.linked || a.climate || a.edit) && !canReuse) throw new Error('시안이 너무 큽니다. 지역 수를 줄여 다시 만드세요.');
329
395
  if (list.length && (savedIndex !== undefined || allFiguresShown) && canReuse) {
330
396
  const id = previews.put({ figures, style, st, compareIndex });
331
397
  how += '\npreviewId: ' + id + '\nmake_figures에 figures 대신 이 ID를 보내세요.';