geo-figure-mcp 0.2.7 → 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 +27 -4
- package/package.json +2 -2
- package/server.json +2 -2
- package/src/build.js +2 -2
- package/src/charts.js +1 -1
- package/src/climate-linked.js +144 -0
- package/src/data.js +72 -19
- package/src/http.js +6 -2
- package/src/hwpx-table.js +116 -0
- package/src/hwpx.js +10 -5
- package/src/linked.js +205 -0
- package/src/references.js +35 -0
- package/src/source-table.js +117 -0
- package/src/tools.js +147 -41
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.
|
|
1
|
+
# geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.9)
|
|
2
2
|
|
|
3
3
|
만든 사람: barkhan (지리 교사)
|
|
4
4
|
|
|
@@ -28,8 +28,8 @@ AI에게 "서울 자치구 주간 인구 지수 지도랑 산점도, 구 이름
|
|
|
28
28
|
- 확대 지도엔 축척
|
|
29
29
|
- 정답표는 파일 마지막 장
|
|
30
30
|
- 만들기 전에 AI가 계획(지표·연도·지역·가공·기호 순서·출력)을 요약해 보여 주고 확인을 받습니다(확인 없이는 파일을 만들지 않음).
|
|
31
|
-
- **시안 먼저**: 파일을 만들기 전에 대화창에 미리보기 그림을 보여 줍니다. 지도 기호
|
|
32
|
-
- **필요한 정보만 조회**: 내장 통계는 list_bundled_data의 query로 검색하고 summary:true로 키와 주제만 볼 수 있습니다.
|
|
31
|
+
- **시안 먼저**: 파일을 만들기 전에 대화창에 미리보기 그림을 보여 줍니다. 기호 비교를 요청하면 지도 기호 모양 4가지(① 흰 테두리 ② 바탕 없음 ③ 네모 흰 바탕 ④ 작은 원 흰 바탕)를 나란히 보여 주고 고르게 합니다.
|
|
32
|
+
- **필요한 정보만 조회**: 내장 통계는 list_bundled_data의 query로 검색하고 summary:true로 키와 주제만 볼 수 있습니다. 로컬·원격 시안의 previewId가 있으면, 교사가 확인한 뒤 같은 그림 명세 대신 ID를 보내 파일을 만들 수 있습니다(최대 30분).
|
|
33
33
|
- **만든 뒤 고치기**: 그림과 함께 설계도(`<이름>.geo-figure.json`)를 저장합니다. "범례 바꿔 줘", "화성시 빼 줘", "기호 순서 바꿔 줘"라고 하면 통계를 다시 찾지 않고 그 부분만 고쳐 다시 만듭니다.
|
|
34
34
|
- **자동 업데이트**: 설정에 `geo-figure-mcp@latest` 를 쓰면 앱을 켤 때마다 최신 버전을 받습니다. 예전 버전이 돌고 있으면 AI가 "새 버전이 있다"고 알려 줍니다.
|
|
35
35
|
|
|
@@ -73,6 +73,29 @@ AI에게 "서울 자치구 주간 인구 지수 지도랑 산점도, 구 이름
|
|
|
73
73
|
- `npx` 를 못 찾는다고 나오면 `command` 에 `C:/Program Files/nodejs/npx.cmd` 처럼 전체 경로를 넣습니다.
|
|
74
74
|
- 원격 서버를 쓸 때는 `"serverUrl": "https://…/mcp?token=비밀번호"` 한 줄로 등록합니다(`url`·`httpUrl` 이 아님).
|
|
75
75
|
|
|
76
|
+
## 같은 통계로 지도와 막대그래프 만들기
|
|
77
|
+
|
|
78
|
+
“2020년 경기도 31개 시·군의 주간 인구 지수를 100 미만과 100 이상으로 나눈 지도를 그리고, 막대에는 상위 5곳만 보여 줘.”
|
|
79
|
+
|
|
80
|
+
1. `find_data`에 `{"source":"bundle","bundle":{"key":"daytime-population","period":"2020","items":["주간 인구 지수"],"within":["경기"]},"asReference":true}`를 보냅니다. 행 전체 대신 자료 ID, 지표, 지역 수, 연도, 출처를 받습니다.
|
|
81
|
+
2. `preview_figures`에 `{"linked":{"dataId":"받은 자료 ID","indicator":"주간 인구 지수","within":["경기"],"breaks":[100],"top":5}}`를 보냅니다. 막대를 모두 표시하려면 `top`을 생략합니다. `labels`로 지역에 기호를 붙일 수 있습니다.
|
|
82
|
+
3. 시안을 확인하면 `make_figures`에 `{"previewId":"받은 시안 ID","confirmed":true,"formats":["hwpx"]}`를 보냅니다. 기호를 바꾸려면 먼저 `preview_figures`에 `{"edit":{"previewId":"받은 시안 ID","labels":{"경기 화성시":"A"}}}`를 보내고 새 시안을 확인합니다.
|
|
83
|
+
4. 연결된 기호의 지역 대응표는 로컬에서는 파일 마지막 장, 원격에서는 대화에 제공됩니다. 자료·시안 ID는 공유받은 사람이 사용할 수 있습니다. 서버 재시작, 보관 개수 초과 또는 최대 30분 경과 후에는 다시 조회하거나 시안을 만드세요.
|
|
84
|
+
|
|
85
|
+
국내 기후는 `서울`, `강릉`, `대구`, `제주`처럼 한글 관측소 이름으로 조회합니다. 세계은행은 `years:true`로 국가별 연도별 값을, `year:2020`으로 한 해의 값을 조회합니다.
|
|
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
|
+
|
|
76
99
|
## 내장 통계와 지도 이름 맞추기
|
|
77
100
|
|
|
78
101
|
- 지도와 그래프에 필요한 항목은 `bundle.items`, 지역은 `bundle.regions`(정확한 `mapName` 또는 통계표 지역명)로 고릅니다. 한 시·도의 지도용 시·군·구를 모두 받으려면 `bundle.within`을 씁니다. 예를 들어 `find_data`에 `{"source":"bundle","bundle":{"key":"daytime-population","period":"2020","items":["주간 인구 지수"],"within":["경기"]}}`를 보내면 경기도 시·군의 해당 지수만 받습니다.
|
|
@@ -121,7 +144,7 @@ AI에게 "서울 자치구 주간 인구 지수 지도랑 산점도, 구 이름
|
|
|
121
144
|
- 단계를 손으로 바꿀 땐 범례 칸을 고르고 서식 복사(붓)로 지역에 칠하면 됩니다.
|
|
122
145
|
- **한글**: 그림 선택 → 마우스 오른쪽 → 개체 풀기 **한 번**. 조각이 제자리에 남습니다.
|
|
123
146
|
- 그림이 쪽에 다 안 들어가면 제목부터 다음 쪽으로 넘어갑니다(겹치지 않음).
|
|
124
|
-
- **범례·기호만 바꾸기**: 로컬에서 `preview_figures`에 `saved: {name, legend, labelStyle}`처럼 파일 이름과 바꿀 내용만 보냅니다. `labels`에는 기호를 바꿀 기존 지도 지역만 적습니다. 그림이나 지도가 여러 개라면 `figure`와 `part`로 대상을 지정할 수 있습니다(1부터). 수정 시안을 확인한 후 `make_figures`에 `previewId`, 새 이름, 출력 형식을 보냅니다.
|
|
147
|
+
- **범례·기호만 바꾸기**: 로컬에서 `preview_figures`에 `saved: {name, legend, labelStyle}`처럼 파일 이름과 바꿀 내용만 보냅니다. `labels`에는 기호를 바꿀 기존 지도 지역만 적습니다. 그림이나 지도가 여러 개라면 `figure`와 `part`로 대상을 지정할 수 있습니다(1부터). 수정 시안을 확인한 후 `make_figures`에 `previewId`, 새 이름, 출력 형식을 보냅니다. 통계에 연결한 그림은 지도, 막대 이름, 지역 대응표가 함께 바뀝니다. 기존 그림은 기호가 일대일로 대응되는 그래프만 자동으로 고칩니다. 직접 쓴 정답·해설은 수정본을 저장할 때 다시 지정합니다.
|
|
125
148
|
- **크게 바꿀 땐 AI에게 말로**: 설계도를 읽어 그 부분만 바꿔 다시 만듭니다(open_figure_spec).
|
|
126
149
|
- **글꼴**
|
|
127
150
|
- 한글 파일은 함초롬돋움(한글 기본 글꼴), PowerPoint 파일은 맑은 고딕(한국어 윈도 기본)을 씁니다.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "geo-figure-mcp",
|
|
3
|
-
"version": "0.2.
|
|
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"
|
|
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.
|
|
7
|
+
"version": "0.2.9",
|
|
8
8
|
"packages": [
|
|
9
9
|
{
|
|
10
10
|
"registryType": "npm",
|
|
11
11
|
"identifier": "geo-figure-mcp",
|
|
12
|
-
"version": "0.2.
|
|
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
|
@@ -9,7 +9,7 @@ export const SOURCES = {
|
|
|
9
9
|
worldbank: { name: '세계은행 WDI', cite: 'World Bank', license: 'CC BY 4.0', key: false, note: '지표 코드 예: SP.POP.TOTL(총인구), SP.URB.TOTL.IN.ZS(도시화율), SP.DYN.TFRT.IN(합계 출산율), SP.POP.65UP.TO.ZS(65세 이상 비율), NY.GDP.PCAP.CD(1인당 GDP)' },
|
|
10
10
|
'owid-energy': { name: 'Our World in Data 에너지', cite: 'Our World in Data(Energy Institute 등)', license: 'CC BY 4.0', key: false, note: '열 예: coal_share_elec, nuclear_share_elec, gas_share_elec, solar_share_elec, energy_per_capita' },
|
|
11
11
|
'owid-co2': { name: 'Our World in Data CO2', cite: 'Our World in Data(Global Carbon Project)', license: 'CC BY 4.0', key: false, note: '열 예: co2, co2_per_capita, cumulative_co2' },
|
|
12
|
-
climate: { name: 'WMO 기후평년값 1991~2020 (내장, 관측소 4,
|
|
12
|
+
climate: { name: 'WMO 기후평년값 1991~2020 (내장, 관측소 4,697곳)', cite: 'WMO 기후평년값(1991~2020)', license: '이용 제한 없음(출처 표시, NCEI doi:10.25921/800j-vn07)', key: false, note: '지점: 국내 관측소 한글 이름(예: 서울, 강릉, 대구, 제주) · 평가원 기출 기후 지점 이름(list_exam_climate_spots) · 관측소 영문 이름 · "위도,경도". 좌표로 조회하면 가장 가까운 관측소와 거리를 알려 준다.' },
|
|
13
13
|
'seoul-daytime': { name: '서울 자치구 주간 인구 2020 (내장)', cite: '통계청, 「2020 인구주택총조사」', license: '공공누리 제1유형', key: false, note: '열: 상주인구, 유입인구, 유출인구, 주간인구, 주간인구지수' },
|
|
14
14
|
bundle: { name: '내장 KOSIS 통계 묶음(인증키 불필요)', cite: '국가데이터처 등(KOSIS)', license: '공공누리 제1유형', key: false, note: 'list_bundled_data 로 목록을 보고 find_data(source:"bundle", bundle:{ key, items, period, where }) 로 꺼낸다. 인구 구조·피라미드·주간 인구·외국인 주민·출산율·인구 이동·도시화·GRDP·제조업·사업체·에너지·신재생·농가·작물 재배 면적.' },
|
|
15
15
|
kosis: { name: 'KOSIS 국가통계포털 (시·도·시·군·구 통계)', cite: '통계청 KOSIS', license: '공공누리 제1유형', key: true, note: 'kosis_search 로 통계표(orgId·tblId)를 찾고 kosis_items 로 항목·분류를 본 뒤 find_data(source:"kosis", kosis:{orgId,tblId,itmId,objL1,…,prdSe,year}) 로 받는다. 인증키: 환경 변수 KOSIS_API_KEY 또는 set_kosis_key.' },
|
|
@@ -20,6 +20,17 @@ async function getJson(url) {
|
|
|
20
20
|
if (!r.ok) throw new Error(`자료를 받지 못함 ${r.status}: ${url}`);
|
|
21
21
|
return r.json();
|
|
22
22
|
}
|
|
23
|
+
async function worldBankPages(url, notFound) {
|
|
24
|
+
const records = [];
|
|
25
|
+
let pages = 1;
|
|
26
|
+
for (let page = 1; page <= pages; page++) {
|
|
27
|
+
const result = await getJson(page === 1 ? url : `${url}&page=${page}`);
|
|
28
|
+
if (!Array.isArray(result?.[1])) throw new Error(notFound);
|
|
29
|
+
records.push(...result[1]);
|
|
30
|
+
pages = Number(result[0]?.pages ?? 1);
|
|
31
|
+
}
|
|
32
|
+
return records;
|
|
33
|
+
}
|
|
23
34
|
function csvLine(line) {
|
|
24
35
|
const out = []; let cur = '', q = false;
|
|
25
36
|
for (let i = 0; i < line.length; i++) {
|
|
@@ -36,21 +47,22 @@ const koName = new Intl.DisplayNames(['ko'], { type: 'region' });
|
|
|
36
47
|
// 결과 모양: { title, unit, cite, year, rows:[{ id, name, values:{ 열: 값 }, year }] }
|
|
37
48
|
export async function findData({ source, indicators = [], regions = [], year, years }) {
|
|
38
49
|
if (source === 'worldbank') {
|
|
39
|
-
const meta =
|
|
50
|
+
const meta = await worldBankPages('https://api.worldbank.org/v2/country?format=json&per_page=400', '세계은행 국가 목록을 읽지 못함');
|
|
40
51
|
const iso2 = Object.fromEntries(meta.map((c) => [c.id, c.iso2Code]));
|
|
41
52
|
const rows = {};
|
|
42
|
-
const range =
|
|
53
|
+
const range = year ?? (years === true ? null : years || `2000:${new Date().getUTCFullYear()}`);
|
|
54
|
+
const params = new URLSearchParams({ format: 'json', per_page: '1000' });
|
|
55
|
+
if (range !== null) params.set('date', String(range));
|
|
43
56
|
for (const ind of indicators) {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
for (const r of j[1]) {
|
|
57
|
+
const url = `https://api.worldbank.org/v2/country/${regions.map(encodeURIComponent).join(';')}/indicator/${encodeURIComponent(ind)}?${params}`;
|
|
58
|
+
for (const r of await worldBankPages(url, `세계은행에 없는 지표이거나 값이 없음: ${ind}`)) {
|
|
47
59
|
if (r.value == null) continue;
|
|
48
60
|
const id = r.countryiso3code || r.country.id;
|
|
49
61
|
const row = (rows[id] ||= { id, name: safeKo(iso2[id], r.country.value), byYear: {} });
|
|
50
62
|
(row.byYear[r.date] ||= {})[ind] = r.value;
|
|
51
63
|
}
|
|
52
64
|
}
|
|
53
|
-
return pack(rows, indicators, year, '세계은행', SOURCES.worldbank.cite);
|
|
65
|
+
return pack(rows, indicators, year, '세계은행', SOURCES.worldbank.cite, years === true);
|
|
54
66
|
}
|
|
55
67
|
if (source === 'owid-energy' || source === 'owid-co2') {
|
|
56
68
|
const url = source === 'owid-energy' ? 'https://raw.githubusercontent.com/owid/energy-data/master/owid-energy-data.csv' : 'https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.csv';
|
|
@@ -73,7 +85,7 @@ export async function findData({ source, indicators = [], regions = [], year, ye
|
|
|
73
85
|
return pack(rows, indicators, year, source, SOURCES[source].cite, years);
|
|
74
86
|
}
|
|
75
87
|
if (source === 'climate') {
|
|
76
|
-
//
|
|
88
|
+
// 국내·기출 지점 이름, 관측소 영문 이름 또는 좌표로 1991~2020 평년값 조회
|
|
77
89
|
if (!regions.length) throw new Error('지점을 주세요. 예: ["샌프란시스코","이르쿠츠크"] 또는 ["37.57,126.98"]. 기출 지점 목록은 list_exam_climate_spots');
|
|
78
90
|
const units = { temp: '℃', precip: 'mm' };
|
|
79
91
|
const requested = Object.keys(units).filter((name) => !indicators.length || indicators.includes(name));
|
|
@@ -93,7 +105,7 @@ export async function findData({ source, indicators = [], regions = [], year, ye
|
|
|
93
105
|
const columns = d.columns.map((name, i) => [name, i])
|
|
94
106
|
.filter(([name]) => !requested.size || requested.has(name));
|
|
95
107
|
const pick = regions.length ? regions : Object.keys(d.rows).filter((k) => k !== '서울특별시');
|
|
96
|
-
return { title: '서울 자치구 상주·주간 인구', unit: '명, 지수', cite:
|
|
108
|
+
return { title: '서울 자치구 상주·주간 인구', unit: '명, 지수', cite: d.source, sourceUrl: kosisTableUrl('101', 'DT_1PA2020'), year: '2020', rows: pick.map((n) => {
|
|
97
109
|
const v = d.rows[n];
|
|
98
110
|
if (!v) throw new Error(`없는 자치구: ${n}`);
|
|
99
111
|
return { id: n, name: n, values: Object.fromEntries(columns.map(([name, i]) => [name, v[i]])) };
|
|
@@ -167,14 +179,35 @@ export function suggestRegions(rows, indicators, k = 5) {
|
|
|
167
179
|
let WMO, SPOTS;
|
|
168
180
|
const wmo = () => (WMO ||= load('wmo-normals-1991-2020.json'));
|
|
169
181
|
export const examSpots = () => (SPOTS ||= load('exam-climate-spots.json')).spots;
|
|
182
|
+
// 내장 WMO 자료의 지점 번호(앞의 0 제외)로 대응시킨다.
|
|
183
|
+
const KOREAN_STATIONS = new Map(Object.entries({
|
|
184
|
+
속초: 47090, 철원: 47095, 동두천: 47098, 파주: 47099, 대관령: 47100,
|
|
185
|
+
춘천: 47101, 백령도: 47102, 강릉: 47105, 동해: 47106, 서울: 47108,
|
|
186
|
+
인천: 47112, 원주: 47114, 울릉도: 47115, 수원: 47119, 영월: 47121,
|
|
187
|
+
충주: 47127, 서산: 47129, 울진: 47130, 청주: 47131, 대전: 47133,
|
|
188
|
+
추풍령: 47135, 안동: 47136, 상주: 47137, 포항: 47138, 군산: 47140,
|
|
189
|
+
울산: 47152, 창원: 47155, 광주: 47156, 부산: 47159, 통영: 47162,
|
|
190
|
+
목포: 47165, 여수: 47168, 흑산도: 47169, 완도: 47170, 고창: 47172,
|
|
191
|
+
제주: 47184, 고산: 47185, 성산: 47188, 서귀포: 47189, 진주: 47192,
|
|
192
|
+
강화: 47201, 양평: 47202, 이천: 47203, 인제: 47211, 홍천: 47212,
|
|
193
|
+
태백: 47216, 정선: 47217, 제천: 47221, 보은: 47226, 천안: 47232,
|
|
194
|
+
보령: 47235, 부여: 47236, 금산: 47238, 부안: 47243, 임실: 47244,
|
|
195
|
+
정읍: 47245, 남원: 47247, 장수: 47248, 영광: 47252, 김해: 47253,
|
|
196
|
+
순창: 47254, 양산: 47257, 강진: 47259, 장흥: 47260, 해남: 47261,
|
|
197
|
+
고흥: 47262, 의령: 47263, 함양: 47264, 봉화: 47271, 영주: 47272,
|
|
198
|
+
문경: 47273, 청송: 47276, 영덕: 47277, 의성: 47278, 구미: 47279,
|
|
199
|
+
영천: 47281, 경주: 47283, 거창: 47284, 합천: 47285, 밀양: 47288,
|
|
200
|
+
산청: 47289, 거제: 47294, 남해: 47295, 대구: 47860, 전주: 47864,
|
|
201
|
+
}));
|
|
170
202
|
const hav = (a, b, c, d) => { const r = Math.PI / 180, x = Math.sin(((c - a) * r) / 2) ** 2 + Math.cos(a * r) * Math.cos(c * r) * Math.sin(((d - b) * r) / 2) ** 2; return 12742 * Math.asin(Math.sqrt(x)); };
|
|
171
203
|
export function nearestStations(lat, lon, n = 3) {
|
|
172
204
|
return wmo().stations.map((s) => ({ s, d: hav(lat, lon, s[3], s[4]) })).sort((a, b) => a.d - b.d).slice(0, n);
|
|
173
205
|
}
|
|
174
206
|
function climateRow(q) {
|
|
175
207
|
const W = wmo();
|
|
208
|
+
const period = '1991~2020';
|
|
176
209
|
const spot = examSpots().find((x) => x.name === q);
|
|
177
|
-
let lat, lon,
|
|
210
|
+
let lat, lon, station, exam = null;
|
|
178
211
|
if (spot) {
|
|
179
212
|
if (spot.lat == null) throw new Error(`'${q}'는 특정 지점이 아니라 좌표가 없습니다. 쓸 관측소 이름이나 "위도,경도"를 주세요.`);
|
|
180
213
|
({ lat, lon } = spot); exam = { code: spot.code, exams: spot.exams };
|
|
@@ -183,21 +216,40 @@ function climateRow(q) {
|
|
|
183
216
|
const c = spot.climate;
|
|
184
217
|
const isGrid = c.source === 'Beck-0.1';
|
|
185
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;
|
|
186
|
-
|
|
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 } };
|
|
187
231
|
}
|
|
188
232
|
} else if (/^-?\d+(\.\d+)?\s*,\s*-?\d+(\.\d+)?$/.test(q)) {
|
|
189
233
|
[lat, lon] = q.split(',').map(Number);
|
|
190
234
|
} else {
|
|
191
|
-
const
|
|
192
|
-
|
|
235
|
+
const stationName = q.normalize('NFC').trim();
|
|
236
|
+
const koreanId = KOREAN_STATIONS.get(stationName.replace(/(?:특별시|광역시|[시군])$/, ''));
|
|
237
|
+
station = koreanId
|
|
238
|
+
? W.stations.find((s) => s[2].trim() === 'Rep._Korea' && Number(s[0]) === koreanId)
|
|
239
|
+
: W.stations.find((s) => s[1].toLowerCase() === stationName.toLowerCase().replace(/\s+/g, ''));
|
|
240
|
+
if (!station) {
|
|
193
241
|
const near = W.stations.filter((s) => s[1].toLowerCase().includes(q.toLowerCase().slice(0, 4))).slice(0, 8).map((s) => `${s[1]}(${s[2].trim()})`);
|
|
194
|
-
throw new Error(`'${q}' 지점을 찾지 못함. 평가원 기출 지점
|
|
242
|
+
throw new Error(`'${q}' 지점을 찾지 못함. 국내 관측소 한글 이름, 평가원 기출 지점 이름, 관측소 영문 이름, 또는 "위도,경도"를 주세요.${near.length ? ' 비슷한 관측소: ' + near.join(', ') : ''}`);
|
|
195
243
|
}
|
|
196
|
-
[lat, lon] = [st[3], st[4]];
|
|
197
244
|
}
|
|
198
|
-
const
|
|
245
|
+
const { s, d } = station ? { s: station, d: 0 } : nearestStations(lat, lon, 1)[0];
|
|
199
246
|
const warn = d > 50 ? `가장 가까운 관측소가 ${Math.round(d)}km 떨어져 있음 — 값이 실제 지점과 다를 수 있음 [확인 필요]` : null;
|
|
200
|
-
return {
|
|
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
|
+
};
|
|
201
253
|
}
|
|
202
254
|
|
|
203
255
|
// ---- KOSIS 공유서비스(OpenAPI) ----
|
|
@@ -240,6 +292,7 @@ export async function kosisItems({ orgId, tblId }) {
|
|
|
240
292
|
}
|
|
241
293
|
// 수록 주기 한글 → API 코드
|
|
242
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 })}`;
|
|
243
296
|
// kosis: { orgId, tblId, itmId:'T1' 또는 'T1+T2', objL1:'ALL', objL2, …, prdSe:'Y', year:2020 (또는 start,end) }
|
|
244
297
|
async function kosisData(q) {
|
|
245
298
|
if (!q.orgId || !q.tblId || !q.itmId) throw new Error('kosis 에 orgId·tblId·itmId 가 필요합니다 (kosis_search → kosis_items 로 확인).');
|
|
@@ -271,7 +324,7 @@ async function kosisData(q) {
|
|
|
271
324
|
r.year = x.PRD_DE;
|
|
272
325
|
}
|
|
273
326
|
const yrs = [...new Set(Object.values(rows).map((r) => r.year))];
|
|
274
|
-
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) };
|
|
275
328
|
}
|
|
276
329
|
|
|
277
330
|
// ---- 내장 KOSIS 통계 묶음(data/kosis): 인증키 없이 쓴다 ----
|
|
@@ -358,7 +411,7 @@ export function bundleData(q) {
|
|
|
358
411
|
const missing = [...provinces].filter((name) => !matchedProvinces.has(name))
|
|
359
412
|
.concat([...regionNames].filter((name) => !matchedRegions.has(name)));
|
|
360
413
|
if (missing.length) throw new Error('선택한 표·기간·분류에 없는 지역: ' + missing.join(', '));
|
|
361
|
-
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 — 시 합계 행을 쓴다)` };
|
|
362
415
|
}
|
|
363
416
|
|
|
364
417
|
// 지도 지역 이름(시·도 짧은 이름, '시도 시군구') — 내장 자료와 이름 맞추기용
|
package/src/http.js
CHANGED
|
@@ -13,6 +13,7 @@ import path from 'node:path';
|
|
|
13
13
|
import crypto from 'node:crypto';
|
|
14
14
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
15
15
|
import { createServer } from './tools.js';
|
|
16
|
+
import { createReferences } from './references.js';
|
|
16
17
|
|
|
17
18
|
const PORT = +(process.env.PORT || 8787);
|
|
18
19
|
const PUBLIC_URL = (process.env.PUBLIC_URL || `http://localhost:${PORT}`).replace(/\/$/, '');
|
|
@@ -28,6 +29,7 @@ let day = '', dayCount = 0;
|
|
|
28
29
|
const dailyOver = () => { const d = new Date().toISOString().slice(0, 10); if (d !== day) { day = d; dayCount = 0; } return ++dayCount > DAILY_MAX; };
|
|
29
30
|
fs.mkdirSync(FILES, { recursive: true });
|
|
30
31
|
|
|
32
|
+
const references = createReferences(true);
|
|
31
33
|
const publish = {
|
|
32
34
|
newDir: () => { const d = path.join(FILES, crypto.randomBytes(12).toString('hex')); fs.mkdirSync(d, { recursive: true }); return d; },
|
|
33
35
|
keepText: KEEP_MIN >= 60 ? `${Math.round(KEEP_MIN / 60)}시간` : `${KEEP_MIN}분`,
|
|
@@ -36,6 +38,8 @@ const publish = {
|
|
|
36
38
|
|
|
37
39
|
// 오래된 파일 지우기(5분마다)
|
|
38
40
|
setInterval(() => {
|
|
41
|
+
references.previews.purge();
|
|
42
|
+
references.datasets.purge();
|
|
39
43
|
for (const d of fs.readdirSync(FILES)) {
|
|
40
44
|
const p = path.join(FILES, d);
|
|
41
45
|
try { if (Date.now() - fs.statSync(p).mtimeMs > KEEP_MS) fs.rmSync(p, { recursive: true, force: true }); } catch {}
|
|
@@ -66,7 +70,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
66
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' });
|
|
67
71
|
const p = path.join(FILES, rel[0], rel[1]);
|
|
68
72
|
if (!fs.existsSync(p)) return send(res, 404, { error: '파일이 없습니다(이미 받았거나 보관 시간이 지나 지워졌습니다).' });
|
|
69
|
-
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';
|
|
70
74
|
res.writeHead(200, { 'Content-Type': type, 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(rel[1])}`, 'Access-Control-Allow-Origin': '*' });
|
|
71
75
|
const st = fs.createReadStream(p);
|
|
72
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 {} });
|
|
@@ -88,7 +92,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
88
92
|
if (isMake && limited(ip, 'make', MAKE_PER_HOUR, 3600 * 1000)) return send(res, 429, { error: '같은 접속 IP에서는 최근 1시간에 ' + MAKE_PER_HOUR + '번까지 파일을 만들 수 있습니다.' });
|
|
89
93
|
if (isMake && dailyOver()) return send(res, 429, { error: '오늘 서버 전체 사용량을 다 썼습니다. 내일 다시 쓰거나 내 컴퓨터에 설치해 쓰세요.' });
|
|
90
94
|
try {
|
|
91
|
-
const mcp = createServer({ remote: true, publish });
|
|
95
|
+
const mcp = createServer({ remote: true, publish, references });
|
|
92
96
|
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
93
97
|
res.on('close', () => { transport.close(); mcp.close(); });
|
|
94
98
|
await mcp.connect(transport);
|
|
@@ -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
|
+
}
|