Skip to content

Commit 159bd52

Browse files
authored
Merge pull request #88 from CausalInferenceLab/site/readme-analytics
Add glossary, upstream watch, improve search and navigation
2 parents df9fe40 + ae1c05b commit 159bd52

22 files changed

Lines changed: 771 additions & 17 deletions
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
name: 용어 제안
2+
description: 인과추론·온라인 실험 용어의 번역어를 제안하거나 고치자고 제안합니다.
3+
title: "[용어] "
4+
labels: ["glossary"]
5+
body:
6+
- type: markdown
7+
attributes:
8+
value: |
9+
제안해 주셔서 고맙습니다. 논의를 거쳐 정해진 용어는 번역 가이드의 용어표와 웹북 용어집에 함께 반영합니다.
10+
- type: input
11+
id: original
12+
attributes:
13+
label: 원어
14+
placeholder: "예: sample ratio mismatch (SRM)"
15+
validations:
16+
required: true
17+
- type: input
18+
id: proposal
19+
attributes:
20+
label: 제안하는 번역어
21+
placeholder: "예: 표본 비율 불일치(SRM)"
22+
validations:
23+
required: true
24+
- type: input
25+
id: current
26+
attributes:
27+
label: 지금 쓰는 표기 (있다면)
28+
placeholder: "예: 용어집에 없음 / 현재 '샘플 비율 불일치'"
29+
- type: textarea
30+
id: reason
31+
attributes:
32+
label: 제안 이유와 근거
33+
description: 다른 책, 논문, 업계에서 쓰는 예가 있으면 함께 적어 주세요.
34+
validations:
35+
required: true
36+
- type: textarea
37+
id: example
38+
attributes:
39+
label: 쓰임 예시
40+
placeholder: "예: 실험을 분석하기 전에 표본 비율 불일치(SRM)가 없는지 먼저 확인합니다."

‎.github/scripts/check_upstream.py‎

Lines changed: 274 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
1+
"""원서 저장소의 변경을 확인해 한국어판 검토 이슈를 만들거나 갱신한다.
2+
3+
`.github/upstream.json`의 synced_sha(한국어판이 마지막으로 맞춘 원서 커밋)와 원서 브랜치 최신 커밋을 비교한다.
4+
5+
- 새 커밋이 있으면: 바뀐 장과 본문(마크다운 셀) 변경 요약을 담은 이슈를 만들고 검토자에게 배정한다.
6+
이미 열린 이슈가 있으면 본문을 최신으로 바꾸고, 새 커밋이 생겼을 때만 댓글로 알린다.
7+
- 새 커밋이 없는데 열린 이슈가 있으면(번역 반영 PR에서 synced_sha를 올린 경우) 이슈를 닫는다.
8+
9+
GitHub Actions에서는 GITHUB_TOKEN과 GITHUB_REPOSITORY를 쓴다.
10+
로컬 점검: python .github/scripts/check_upstream.py --git-dir <원서 clone> --dry-run
11+
"""
12+
import argparse
13+
import difflib
14+
import importlib.util
15+
import json
16+
import os
17+
import subprocess
18+
import sys
19+
import urllib.request
20+
from pathlib import Path
21+
22+
ROOT = Path(__file__).resolve().parents[2]
23+
CONFIG = json.loads((ROOT / ".github" / "upstream.json").read_text(encoding="utf-8"))
24+
MARKER = "<!-- upstream-sync -->"
25+
SITE = "https://causalinferencelab.github.io/Causal-Inference-with-Python"
26+
MAX_SNIPPET = 260
27+
28+
29+
def chapter_titles():
30+
spec = importlib.util.spec_from_file_location("prepare", ROOT / "book" / "prepare.py")
31+
mod = importlib.util.module_from_spec(spec)
32+
spec.loader.exec_module(mod)
33+
return mod.CHAPTERS
34+
35+
36+
# ---------- 원서 정보 가져오기 (API 또는 로컬 clone) ----------
37+
38+
class Api:
39+
def __init__(self, token):
40+
self.token = token
41+
42+
def request(self, method, url, data=None):
43+
headers = {"Accept": "application/vnd.github+json", "User-Agent": "upstream-sync"}
44+
if self.token:
45+
headers["Authorization"] = f"Bearer {self.token}"
46+
body = json.dumps(data).encode() if data is not None else None
47+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
48+
with urllib.request.urlopen(req) as res:
49+
text = res.read().decode()
50+
return json.loads(text) if text else None
51+
52+
def get(self, url):
53+
return self.request("GET", url)
54+
55+
56+
class Upstream:
57+
"""원서 저장소에서 비교 결과와 파일 내용을 읽는다."""
58+
59+
def __init__(self, api=None, git_dir=None):
60+
self.api, self.git_dir = api, git_dir
61+
self.repo = CONFIG["repo"]
62+
63+
def head(self):
64+
if self.git_dir:
65+
return self._git("rev-parse", f"origin/{CONFIG['branch']}")
66+
return self.api.get(f"https://api.github.com/repos/{self.repo}/commits/{CONFIG['branch']}")["sha"]
67+
68+
def compare(self, base, head):
69+
if self.git_dir:
70+
log = self._git("log", "--reverse", "--format=%H%x1f%an%x1f%ad%x1f%s", "--date=short", f"{base}..{head}")
71+
commits = [dict(zip(("sha", "author", "date", "message"), l.split("\x1f"))) for l in log.splitlines() if l]
72+
files = []
73+
for line in self._git("diff", "--name-status", base, head).splitlines():
74+
status, *paths = line.split("\t")
75+
files.append({"filename": paths[-1], "status": {"A": "added", "D": "removed"}.get(status[0], "modified")})
76+
return commits, files
77+
data = self.api.get(f"https://api.github.com/repos/{self.repo}/compare/{base}...{head}")
78+
commits = [{"sha": c["sha"], "author": c["commit"]["author"]["name"], "date": c["commit"]["author"]["date"][:10],
79+
"message": c["commit"]["message"].splitlines()[0]} for c in data["commits"]]
80+
files = [{"filename": f["filename"], "status": f["status"]} for f in data.get("files", [])]
81+
return commits, files
82+
83+
def read(self, sha, path):
84+
try:
85+
if self.git_dir:
86+
return self._git("show", f"{sha}:{path}")
87+
url = f"https://raw.githubusercontent.com/{self.repo}/{sha}/{path}"
88+
with urllib.request.urlopen(url) as res:
89+
return res.read().decode()
90+
except Exception:
91+
return None
92+
93+
def _git(self, *args):
94+
return subprocess.run(["git", "-C", self.git_dir, *args], check=True, capture_output=True, text=True).stdout.strip()
95+
96+
97+
# ---------- 노트북 본문 비교 ----------
98+
99+
def cells(text, kind):
100+
if not text:
101+
return []
102+
nb = json.loads(text)
103+
out = []
104+
for c in nb.get("cells", []):
105+
if c.get("cell_type") == kind:
106+
src = c.get("source", "")
107+
out.append("".join(src) if isinstance(src, list) else src)
108+
return out
109+
110+
111+
def short(text):
112+
one = " ".join(text.split())
113+
return one if len(one) <= MAX_SNIPPET else one[:MAX_SNIPPET] + "…"
114+
115+
116+
def word_diff(old, new, limit=3, ctx=6):
117+
"""두 문단에서 바뀐 부분만 앞뒤 몇 단어와 함께 `기존 → 변경`으로 보여 준다."""
118+
a, b = old.split(), new.split()
119+
out = []
120+
for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=b, autojunk=False).get_opcodes():
121+
if tag == "equal":
122+
continue
123+
before = " ".join(a[max(0, i1 - ctx):i1])
124+
after = " ".join(a[i2:i2 + ctx])
125+
removed, added = " ".join(a[i1:i2]), " ".join(b[j1:j2])
126+
out.append(f"…{before} ~~{removed or '∅'}~~ **{added or '∅'}** {after}…")
127+
if len(out) >= limit:
128+
break
129+
return out
130+
131+
132+
def notebook_changes(old, new):
133+
"""마크다운 셀 변경을 (셀 번호, 설명 줄 목록)으로, 코드 셀은 바뀐 개수만 돌려준다."""
134+
a, b = cells(old, "markdown"), cells(new, "markdown")
135+
changes = []
136+
for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=b, autojunk=False).get_opcodes():
137+
if tag == "equal":
138+
continue
139+
pairs = min(i2 - i1, j2 - j1) if tag == "replace" else 0
140+
for k in range(pairs):
141+
changes.append((j1 + k, word_diff(a[i1 + k], b[j1 + k])))
142+
for i in range(i1 + pairs, i2):
143+
changes.append((i, [f"삭제된 셀: {short(a[i])}"]))
144+
for j in range(j1 + pairs, j2):
145+
changes.append((j, [f"추가된 셀: {short(b[j])}"]))
146+
ca, cb = cells(old, "code"), cells(new, "code")
147+
code_changed = sum(max(i2 - i1, j2 - j1) for t, i1, i2, j1, j2 in
148+
difflib.SequenceMatcher(a=ca, b=cb, autojunk=False).get_opcodes() if t != "equal")
149+
return changes, code_changed
150+
151+
152+
# ---------- 보고서 ----------
153+
154+
def report(base, head, commits, files, upstream, titles):
155+
repo, path = CONFIG["repo"], CONFIG["path"]
156+
lines = [
157+
MARKER,
158+
f"원서 저장소 [{repo}](https://github.com/{repo})에 한국어판이 아직 반영하지 않은 변경이 있습니다.",
159+
"",
160+
f"- 한국어판 기준 커밋: [`{base[:7]}`](https://github.com/{repo}/commit/{base}) ({CONFIG.get('synced_at', '')})",
161+
f"- 원서 최신 커밋: [`{head[:7]}`](https://github.com/{repo}/commit/{head})",
162+
f"- 전체 비교: https://github.com/{repo}/compare/{base[:12]}...{head[:12]}",
163+
"",
164+
f"### 새 커밋 {len(commits)}개",
165+
"",
166+
]
167+
lines += [f"- [`{c['sha'][:7]}`](https://github.com/{repo}/commit/{c['sha']}) {c['date']} {c['message']} ({c['author']})" for c in commits]
168+
169+
book_files = [f for f in files if f["filename"].startswith(path + "/") and f["filename"].endswith(".ipynb")]
170+
other = [f for f in files if f not in book_files]
171+
lines += ["", f"### 바뀐 장 {len(book_files)}개", ""]
172+
if not book_files:
173+
lines.append("책 본문 노트북은 바뀌지 않았습니다. 아래 기타 파일만 확인하면 됩니다.")
174+
details = []
175+
for f in book_files:
176+
key = Path(f["filename"]).stem
177+
title = titles.get(key, key)
178+
old = upstream.read(base, f["filename"]) if f["status"] != "added" else None
179+
new = upstream.read(head, f["filename"]) if f["status"] != "removed" else None
180+
changes, code_changed = notebook_changes(old, new)
181+
diff_url = f"https://github.com/{repo}/compare/{base[:12]}...{head[:12]}"
182+
summary = f"본문 셀 {len(changes)}곳, 코드 셀 {code_changed}곳"
183+
if f["status"] == "added":
184+
summary = "새로 추가된 장"
185+
elif f["status"] == "removed":
186+
summary = "원서에서 삭제됨"
187+
lines.append(f"- [ ] **{title}** (`{key}`): {summary} · [웹북]({SITE}/{key}.html) · [원서 변경]({diff_url})")
188+
if changes:
189+
details += ["", f"<details><summary>{title}: 본문 변경</summary>", ""]
190+
for i, parts in changes[:20]:
191+
details.append(f"- 셀 {i}")
192+
details += [f" - {short(x)}" for x in parts]
193+
if len(changes) > 20:
194+
details.append(f"- …외 {len(changes) - 20}곳")
195+
details += ["", "</details>"]
196+
lines += details
197+
if other:
198+
lines += ["", "### 기타 파일", ""] + [f"- `{f['filename']}` ({f['status']})" for f in other[:50]]
199+
lines += [
200+
"",
201+
"### 반영 절차",
202+
"",
203+
"1. 위 목록에서 장별 변경을 확인하고, 번역에 반영할지 정합니다(오탈자·링크만 바뀐 경우는 건너뛰어도 됩니다).",
204+
"2. 반영할 장은 번역 가이드에 따라 고친 뒤 PR을 엽니다. PR에서 `.github/upstream.json`의 `synced_sha`를 이 이슈의 원서 최신 커밋으로, `synced_at`을 날짜로 바꿉니다.",
205+
"3. 메인테이너가 PR을 검토하고 머지하면 웹북에 배포되고, 다음 점검 때 이 이슈가 자동으로 닫힙니다.",
206+
"",
207+
"이 이슈는 `Upstream watch` 워크플로가 매월 1일 자동으로 갱신합니다.",
208+
]
209+
body = "\n".join(lines)
210+
return body[:60000]
211+
212+
213+
# ---------- 이슈 관리 ----------
214+
215+
def sync_issue(api, repo, body, head, ahead):
216+
label = CONFIG["label"]
217+
base_url = f"https://api.github.com/repos/{repo}"
218+
try:
219+
api.request("POST", f"{base_url}/labels", {"name": label, "color": "a996d6", "description": "원서 변경 반영 검토"})
220+
except Exception:
221+
pass # 이미 있음
222+
issues = api.get(f"{base_url}/issues?state=open&labels={label}&per_page=10")
223+
issue = next((i for i in issues if MARKER in (i.get("body") or "")), None)
224+
if not ahead:
225+
if issue:
226+
api.request("POST", f"{base_url}/issues/{issue['number']}/comments",
227+
{"body": "한국어판 기준 커밋이 원서 최신 커밋과 같아져서 이 이슈를 닫습니다."})
228+
api.request("PATCH", f"{base_url}/issues/{issue['number']}", {"state": "closed", "state_reason": "completed"})
229+
print(f"closed #{issue['number']}")
230+
return
231+
title = f"[원서 변경] 반영 검토 필요 ({head[:7]})"
232+
if issue:
233+
known = issue.get("title", "").endswith(f"({head[:7]})")
234+
api.request("PATCH", f"{base_url}/issues/{issue['number']}", {"title": title, "body": body})
235+
if not known:
236+
mention = " ".join(f"@{r}" for r in CONFIG.get("reviewers", []))
237+
api.request("POST", f"{base_url}/issues/{issue['number']}/comments",
238+
{"body": f"{mention} 원서에 새 커밋이 추가되어 이슈 내용을 갱신했습니다. 최신 커밋: `{head[:7]}`"})
239+
print(f"updated #{issue['number']}")
240+
else:
241+
new = api.request("POST", f"{base_url}/issues", {"title": title, "body": body, "labels": [label],
242+
"assignees": CONFIG.get("reviewers", [])})
243+
print(f"opened #{new['number']}")
244+
245+
246+
def main():
247+
parser = argparse.ArgumentParser()
248+
parser.add_argument("--git-dir", help="원서 저장소 로컬 clone (API 대신 사용)")
249+
parser.add_argument("--base", help="비교 기준 커밋 (기본: upstream.json의 synced_sha)")
250+
parser.add_argument("--dry-run", action="store_true", help="이슈를 만들지 않고 보고서만 출력")
251+
args = parser.parse_args()
252+
253+
token = os.environ.get("GITHUB_TOKEN", "")
254+
api = Api(token)
255+
upstream = Upstream(api=None if args.git_dir else api, git_dir=args.git_dir)
256+
base = args.base or CONFIG["synced_sha"]
257+
head = upstream.head()
258+
commits, files = ([], []) if head == base else upstream.compare(base, head)
259+
body = report(base, head, commits, files, upstream, chapter_titles()) if commits else ""
260+
261+
summary = os.environ.get("GITHUB_STEP_SUMMARY")
262+
if summary:
263+
Path(summary).write_text(body or f"원서 변경 없음 (기준 `{base[:7]}` = 최신 `{head[:7]}`)", encoding="utf-8")
264+
if args.dry_run:
265+
print(body or f"no upstream changes since {base[:7]}")
266+
return
267+
repo = os.environ.get("GITHUB_REPOSITORY")
268+
if not repo:
269+
sys.exit("GITHUB_REPOSITORY가 없습니다. 로컬에서는 --dry-run으로 실행하세요.")
270+
sync_issue(api, repo, body, head, bool(commits))
271+
272+
273+
if __name__ == "__main__":
274+
main()

‎.github/upstream.json‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"repo": "matheusfacure/python-causality-handbook",
3+
"branch": "master",
4+
"path": "causal-inference-for-the-brave-and-true",
5+
"synced_sha": "4df1445987d3b6f9824d508863a1a2f0a503e888",
6+
"synced_at": "2026-10-18",
7+
"reviewers": ["jsshin2022"],
8+
"label": "upstream-sync"
9+
}

‎.github/workflows/book.yml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ jobs:
2020
build:
2121
runs-on: ubuntu-latest
2222
steps:
23-
- uses: actions/checkout@v4
23+
- uses: actions/checkout@v7
2424

25-
- uses: actions/setup-python@v5
25+
- uses: actions/setup-python@v7
2626
with:
2727
python-version: "3.12"
2828

@@ -43,7 +43,7 @@ jobs:
4343

4444
- name: Upload preview
4545
if: github.event_name == 'pull_request'
46-
uses: actions/upload-artifact@v4
46+
uses: actions/upload-artifact@v7
4747
with:
4848
name: book-preview
4949
path: book/_book
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
name: Upstream watch
2+
3+
# 원서 저장소에 새 변경이 생기면 메인테이너에게 배정된 검토 이슈를 만든다.
4+
on:
5+
schedule:
6+
- cron: "17 0 1 * *" # 매월 1일 오전 9시 17분(KST)
7+
workflow_dispatch:
8+
push:
9+
branches: [main]
10+
paths: [".github/upstream.json"]
11+
12+
permissions:
13+
contents: read
14+
issues: write
15+
16+
concurrency:
17+
group: upstream-watch
18+
cancel-in-progress: false
19+
20+
jobs:
21+
check:
22+
runs-on: ubuntu-latest
23+
steps:
24+
- uses: actions/checkout@v7
25+
26+
- uses: actions/setup-python@v7
27+
with:
28+
python-version: "3.12"
29+
30+
- name: Compare with upstream and update review issue
31+
env:
32+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
33+
run: python .github/scripts/check_upstream.py

0 commit comments

Comments
 (0)