1313
1414실행: python book/prepare.py
1515"""
16+ import html
1617import json
1718import re
1819import shutil
20+ import urllib .request
1921from pathlib import Path
2022
2123ROOT = 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+
140166def 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+
206302def 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 ():
0 commit comments