Skip to content

Commit 1e67d79

Browse files
claudejsshin2022
authored andcommitted
Show the glossary as a table and add a comments section to chapters
The glossary lists each term with its original word and the chapters it appears in. Chapters get a comments section backed by GitHub Discussions through giscus; until the giscus app is installed it links to Discussions.
1 parent 586ee0f commit 1e67d79

3 files changed

Lines changed: 284 additions & 11 deletions

File tree

‎book/prepare.py‎

Lines changed: 108 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@
1313
1414
실행: python book/prepare.py
1515
"""
16+
import html
1617
import json
1718
import re
1819
import shutil
20+
import urllib.request
1921
from pathlib import Path
2022

2123
ROOT = Path(__file__).resolve().parent.parent
@@ -137,6 +139,30 @@ def label(key):
137139
}
138140

139141

142+
def chapter_chip(key):
143+
keys = list(CHAPTERS)
144+
i = keys.index(key)
145+
num = f"{i + 1}장" if i < 25 else f"부록 {chr(65 + i - 25)}"
146+
return (f'<a class="ch-chip" href="{key}.html" title="{html.escape(CHAPTERS[key])}">'
147+
f'<b>{num}</b> {html.escape(CHAPTERS[key])}</a>')
148+
149+
150+
def gloss_table(items):
151+
rows = []
152+
for anchor, ko, en, others, top in items:
153+
alias = (f'<span class="gloss-alias">다른 표기: {html.escape(", ".join(others))}</span>' if others else "")
154+
chips = "".join(chapter_chip(k) for k in top) or '<span class="gloss-none">이 책 밖의 용어</span>'
155+
rows.append(
156+
f'<tr id="{anchor}">'
157+
f'<td data-label="번역어"><a class="term-link" href="#{anchor}" aria-label="{html.escape(ko)} 링크">#</a>'
158+
f'<strong>{html.escape(ko)}</strong>{alias}</td>'
159+
f'<td data-label="원어" lang="en">{html.escape(en)}</td>'
160+
f'<td data-label="나오는 장">{chips}</td></tr>'
161+
)
162+
return ('<table class="gloss-table"><thead><tr><th>번역어</th><th>원어</th><th>주로 나오는 장</th></tr></thead><tbody>'
163+
+ "".join(rows) + "</tbody></table>")
164+
165+
140166
def build_glossary():
141167
"""번역 가이드 용어표로 용어집 페이지를 만든다."""
142168
guide = (ROOT / "TRANSLATION_GUIDE.md").read_text(encoding="utf-8")
@@ -153,8 +179,9 @@ def build_glossary():
153179
"번역어는 『실무로 통하는 인과추론 with 파이썬』을 기준으로 하고, 이 책에 나오지 않는 온라인 실험 용어는 "
154180
"가짜연구소 인과추론팀이 함께 정해 나가고 있습니다.",
155181
"",
156-
"용어마다 원어와 다른 표기, 그 용어를 주로 다루는 장을 붙였습니다. 다른 자료에서 본 표기(예: 처치군, 통제군)나 "
157-
"띄어 쓴 표기로 검색해도 이 페이지에서 찾을 수 있고, 용어 이름 옆 링크를 복사하면 그 용어로 바로 이동하는 주소가 됩니다.",
182+
"표마다 번역어, 원어(영어), 그 용어가 많이 나오는 장을 차례로 적었습니다. 장 이름을 누르면 그 장으로 이동합니다. "
183+
"다른 자료에서 본 표기(예: 처치군, 통제군)나 띄어 쓴 표기로 검색해도 이 페이지에서 찾을 수 있고, "
184+
"용어 앞의 `#`을 복사하면 그 용어로 바로 이동하는 주소가 됩니다.",
158185
"",
159186
f"::: {{.callout-tip appearance=\"simple\" title=\"용어 제안하기\"}}\n빠진 용어나 더 자연스러운 번역어가 있다면 [용어 제안 이슈]({propose})로 알려 주세요. 논의를 거쳐 번역 가이드와 이 용어집에 함께 반영합니다.\n:::",
160187
"",
@@ -183,26 +210,95 @@ def score(k):
183210
return n / max(len(text), 1) * 10000 + (5 if intro else 0)
184211

185212
scores = {k: score(k) for k in order}
186-
top = sorted((k for k in order if scores[k]), key=lambda k: -scores[k])[:3]
213+
top = sorted((k for k in order if scores[k]), key=lambda k: -scores[k])[:4]
187214
top.sort(key=order.index)
188215
others = [a for a in re.findall(r"`([^`]+)`", note) if "쓰지" in note]
189-
anchor = "term-" + re.sub(r"[^0-9A-Za-z가-힣]+", "-", ko).strip("-")
190-
line_out = f"- [**{ko}**]{{#{anchor}}} [#](#{anchor}){{.term-link aria-label=\"{ko} 링크\"}} · {en}"
191216
for w, spaced in SPACED.items():
192217
if w in ko:
193218
alias = re.sub(r"\s*\([^)]*\)", "", ko.replace(w, spaced)).strip()
194219
if alias not in others:
195220
others.append(alias)
196-
if others:
197-
line_out += f" · 다른 표기: {', '.join(others)}"
198-
if top:
199-
line_out += " · " + ", ".join(f"[{label(k)}]({k}.html)" for k in top)
200-
items.append(line_out)
221+
anchor = "term-" + re.sub(r"[^0-9A-Za-z가-힣]+", "-", ko).strip("-")
222+
items.append((anchor, ko, en, others, top))
201223
if items:
202-
out += [f"## {heading.strip()}", ""] + ([" ".join(intro), ""] if intro else []) + items + [""]
224+
out += [f"## {heading.strip()}", ""] + ([" ".join(intro), ""] if intro else [])
225+
out += ["```{=html}", gloss_table(items), "```", ""]
203226
(OUT / "glossary.qmd").write_text("\n".join(out), encoding="utf-8")
204227

205228

229+
REPO = "CausalInferenceLab/Causal-Inference-with-Python"
230+
REPO_ID = "R_kgDOHkGCqg"
231+
COMMENT_CATEGORIES = ("웹북 댓글", "Comments", "General")
232+
233+
234+
def giscus_category():
235+
"""giscus 앱이 설치되어 있으면 댓글을 모을 Discussions 카테고리 (이름, ID)를 돌려준다."""
236+
try:
237+
url = f"https://giscus.app/api/discussions/categories?repo={REPO}"
238+
with urllib.request.urlopen(url, timeout=15) as res:
239+
data = json.loads(res.read().decode())
240+
cats = {c["name"]: c["id"] for c in data.get("categories", [])}
241+
for name in COMMENT_CATEGORIES:
242+
if name in cats:
243+
return name, cats[name]
244+
except Exception:
245+
pass
246+
return None
247+
248+
249+
def build_comments():
250+
"""장마다 붙일 댓글 영역(include-after-body)을 만든다.
251+
252+
giscus(GitHub Discussions)가 준비되어 있으면 GitHub 로그인 댓글을, 아니면 Discussions로 가는 안내만 넣는다.
253+
"""
254+
cat = giscus_category()
255+
discussions = f"https://github.com/{REPO}/discussions"
256+
head = (
257+
'<section id="cil-comments" class="cil-comments" aria-label="댓글">'
258+
'<h2 class="cil-comments-title">의견 나누기</h2>'
259+
'<p class="cil-comments-lead">번역이 어색한 곳, 더 쉬운 설명, 궁금한 점을 남겨 주세요. '
260+
'GitHub 계정으로 로그인하면 댓글을 달 수 있고, 남긴 의견은 '
261+
f'<a href="{discussions}">GitHub Discussions</a>에 장별로 모입니다.</p>'
262+
)
263+
if cat:
264+
name, cid = cat
265+
body = (
266+
'<div class="giscus"></div>'
267+
'<script src="https://giscus.app/client.js"'
268+
f' data-repo="{REPO}" data-repo-id="{REPO_ID}"'
269+
f' data-category="{html.escape(name)}" data-category-id="{cid}"'
270+
' data-mapping="pathname" data-strict="1" data-reactions-enabled="1"'
271+
' data-emit-metadata="0" data-input-position="top" data-lang="ko" data-loading="lazy"'
272+
' data-theme="light" crossorigin="anonymous" async></script>'
273+
)
274+
else:
275+
body = (
276+
'<p class="cil-comments-fallback">'
277+
f'<a class="cil-comments-button" href="{discussions}">GitHub Discussions에서 의견 남기기</a> '
278+
f'<a href="https://github.com/{REPO}/issues/new">오류 제보하기</a></p>'
279+
)
280+
script = """<script>
281+
document.addEventListener("DOMContentLoaded", function () {
282+
var box = document.getElementById("cil-comments");
283+
var main = document.getElementById("quarto-document-content");
284+
if (!box || !main || document.querySelector(".hero") || location.pathname.endsWith("/404.html")) {
285+
if (box) box.remove();
286+
return;
287+
}
288+
main.appendChild(box);
289+
function theme() { return document.body.classList.contains("quarto-dark") ? "dark_dimmed" : "light"; }
290+
var s = box.querySelector("script[src*='giscus']");
291+
if (s) s.setAttribute("data-theme", theme());
292+
new MutationObserver(function () {
293+
var f = document.querySelector("iframe.giscus-frame");
294+
if (f) f.contentWindow.postMessage({ giscus: { setConfig: { theme: theme() } } }, "https://giscus.app");
295+
}).observe(document.body, { attributes: true, attributeFilter: ["class"] });
296+
});
297+
</script>"""
298+
(OUT / "comments.html").write_text(head + body + "</section>\n" + script + "\n", encoding="utf-8")
299+
print("comments:", f"giscus ({cat[0]})" if cat else "Discussions 링크 (giscus 미설치)")
300+
301+
206302
def prepare_notebook(key, title):
207303
nb = json.loads((SRC / f"{key}.ipynb").read_text(encoding="utf-8"))
208304
cells = nb["cells"]
@@ -235,6 +331,7 @@ def main():
235331
for key, title in CHAPTERS.items():
236332
prepare_notebook(key, title)
237333
build_glossary()
334+
build_comments()
238335
# 이미지·데이터와 노트북이 import하는 보조 모듈
239336
data = OUT / "data"
240337
if data.is_symlink() or data.exists():

‎book/styles-dark.scss‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,3 +128,19 @@ body {
128128
background: #1b1d2a;
129129
color: #eceaff;
130130
}
131+
132+
.gloss-table thead th {
133+
background: #14151f;
134+
color: #c9bcf5;
135+
}
136+
.gloss-table strong,
137+
.ch-chip {
138+
color: #eceaff !important;
139+
}
140+
.ch-chip {
141+
background: rgba(169, 150, 214, 0.12);
142+
border-color: rgba(169, 150, 214, 0.25);
143+
}
144+
.ch-chip b {
145+
color: #c9bcf5;
146+
}

‎book/styles.scss‎

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,3 +1084,163 @@ html.cil-search-open {
10841084
// 검색 미리보기의 수식은 평문이므로 줄바꿈이 자연스럽게
10851085
.cil-search-snippet { word-break: keep-all; overflow-wrap: anywhere; }
10861086
.cil-search-bar input::-webkit-search-cancel-button { -webkit-appearance: none; display: none; }
1087+
1088+
// 용어집 표
1089+
.gloss-table {
1090+
width: 100%;
1091+
margin: 0.6rem 0 2rem;
1092+
border-collapse: separate;
1093+
border-spacing: 0;
1094+
font-size: 0.93rem;
1095+
}
1096+
.gloss-table thead th {
1097+
position: sticky;
1098+
top: 0;
1099+
z-index: 1;
1100+
padding: 0.55rem 0.8rem;
1101+
border-bottom: 2px solid rgba($indigo, 0.25);
1102+
background: $body-bg;
1103+
color: $indigo;
1104+
font-size: 0.8rem;
1105+
font-weight: 700;
1106+
text-align: left;
1107+
}
1108+
.gloss-table td {
1109+
padding: 0.7rem 0.8rem;
1110+
border-bottom: 1px solid rgba($indigo, 0.1);
1111+
vertical-align: top;
1112+
}
1113+
.gloss-table td:nth-child(1) {
1114+
width: 24%;
1115+
}
1116+
.gloss-table td:nth-child(2) {
1117+
width: 22%;
1118+
color: rgba($body-color, 0.8);
1119+
}
1120+
.gloss-table tr:target td {
1121+
background: rgba($lavender, 0.18);
1122+
}
1123+
.gloss-table strong {
1124+
color: $navy;
1125+
}
1126+
.gloss-table .term-link {
1127+
margin-right: 0.35rem;
1128+
}
1129+
.gloss-alias {
1130+
display: block;
1131+
margin-top: 0.2rem;
1132+
color: rgba($body-color, 0.6);
1133+
font-size: 0.8rem;
1134+
}
1135+
.ch-chip {
1136+
display: inline-flex;
1137+
align-items: baseline;
1138+
gap: 0.3rem;
1139+
margin: 0 0.3rem 0.3rem 0;
1140+
padding: 0.15rem 0.55rem;
1141+
border: 1px solid rgba($indigo, 0.15);
1142+
border-radius: 999px;
1143+
background: $lavender-soft;
1144+
color: $navy !important;
1145+
font-size: 0.8rem;
1146+
text-decoration: none !important;
1147+
white-space: nowrap;
1148+
}
1149+
.ch-chip b {
1150+
color: $indigo;
1151+
}
1152+
.ch-chip:hover {
1153+
border-color: $indigo;
1154+
}
1155+
.gloss-none {
1156+
color: rgba($body-color, 0.45);
1157+
font-size: 0.8rem;
1158+
}
1159+
@media (max-width: 767.98px) {
1160+
.gloss-table thead {
1161+
display: none;
1162+
}
1163+
.gloss-table,
1164+
.gloss-table tbody,
1165+
.gloss-table tr,
1166+
.gloss-table td {
1167+
display: block;
1168+
width: 100% !important;
1169+
}
1170+
.gloss-table tr {
1171+
padding: 0.7rem 0;
1172+
border-bottom: 1px solid rgba($indigo, 0.12);
1173+
}
1174+
.gloss-table td {
1175+
padding: 0.15rem 0;
1176+
border: 0;
1177+
}
1178+
.gloss-table td:nth-child(2)::before,
1179+
.gloss-table td:nth-child(3)::before {
1180+
content: attr(data-label);
1181+
display: inline-block;
1182+
min-width: 4.5rem;
1183+
color: $lavender;
1184+
font-size: 0.75rem;
1185+
font-weight: 700;
1186+
}
1187+
.ch-chip {
1188+
white-space: normal;
1189+
}
1190+
}
1191+
1192+
// 왼쪽 목차: 장 사이 간격을 넉넉하게
1193+
#quarto-sidebar .sidebar-item .sidebar-item-container > a,
1194+
#quarto-sidebar .sidebar-item > .sidebar-link {
1195+
padding-top: 0.32rem;
1196+
padding-bottom: 0.32rem;
1197+
}
1198+
#quarto-sidebar .sidebar-item-section {
1199+
margin-top: 0.5rem;
1200+
}
1201+
#quarto-sidebar .sidebar-item .menu-text {
1202+
line-height: 1.45;
1203+
}
1204+
1205+
// 목차 맨 아래 용어집
1206+
#quarto-sidebar li.sidebar-glossary {
1207+
margin-top: 0.8rem;
1208+
padding-top: 0.6rem;
1209+
border-top: 1px solid rgba($indigo, 0.12);
1210+
}
1211+
#quarto-sidebar li.sidebar-glossary .menu-text {
1212+
font-weight: 700;
1213+
color: $navy;
1214+
}
1215+
#quarto-sidebar li.sidebar-glossary .chapter-number {
1216+
display: none;
1217+
}
1218+
1219+
// 장 끝 댓글
1220+
.cil-comments {
1221+
margin: 3rem 0 1rem;
1222+
padding-top: 1.5rem;
1223+
border-top: 1px solid rgba($indigo, 0.15);
1224+
}
1225+
.cil-comments-title {
1226+
margin-top: 0 !important;
1227+
}
1228+
.cil-comments-lead {
1229+
color: rgba($body-color, 0.75);
1230+
font-size: 0.92rem;
1231+
}
1232+
.cil-comments-fallback {
1233+
display: flex;
1234+
flex-wrap: wrap;
1235+
gap: 0.8rem;
1236+
align-items: center;
1237+
}
1238+
.cil-comments-button {
1239+
display: inline-block;
1240+
padding: 0.5rem 1rem;
1241+
border-radius: 999px;
1242+
background: $navy;
1243+
color: #fff !important;
1244+
font-weight: 600;
1245+
text-decoration: none !important;
1246+
}

0 commit comments

Comments
 (0)