diff --git a/.github/ISSUE_TEMPLATE/claim-review.yml b/.github/ISSUE_TEMPLATE/claim-review.yml new file mode 100644 index 00000000..9f774a37 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/claim-review.yml @@ -0,0 +1,59 @@ +name: 뉴스 주장 검토 기록 +description: 검색 화면의 '문장 검증' 결과를 실제 주장(기사·발표)의 검토 기록으로 남깁니다 → 답 페이지 팩트체크 마크업 +title: "[주장 검토] " +labels: ["claim-review"] +body: + - type: markdown + attributes: + value: | + 누군가 **실제로 한 주장**만 기록합니다. 검토자(작성자가 아닌 참여자)가 아래를 확인한 뒤 `catalog/projects.yaml` 의 + 그 케이스 `claims:` 에 한 줄을 추가하면 답 페이지에 schema.org ClaimReview 가 붙습니다. + 주장 문장은 원문 그대로, 짧게(한 문장) 적어 주세요. 기사 전문을 옮기지 마세요. + - type: input + id: claim + attributes: + label: 주장 문장 (원문 그대로 한 문장) + validations: + required: true + - type: input + id: by + attributes: + label: 누가 말했나 (기관·언론사·인물) + validations: + required: true + - type: input + id: url + attributes: + label: 주장이 실린 곳 (URL) + validations: + required: true + - type: input + id: date + attributes: + label: 주장 날짜 (YYYY-MM-DD) + - type: input + id: case + attributes: + label: 비교한 분석 (cases/ 폴더 이름) + validations: + required: true + - type: input + id: auto + attributes: + label: 자동 문장 검증 결과 + description: "뒷받침 · 범위 안 · 결과를 넘어섬 · 결과와 다름 — 검색 화면에서 채워집니다" + - type: dropdown + id: rating + attributes: + label: 검토자 평가 (projects.yaml claims.rating 에 그대로) + options: + - 결과와 맞음 + - 범위 안 + - 결과를 넘어섬 + - 결과와 다름 + validations: + required: true + - type: textarea + id: notes + attributes: + label: 검토 메모 — 주장과 분석의 지역·기간·지표가 같은가 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 384dfb28..5254d9e3 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -15,6 +15,7 @@ - [ ] `make check` (ruff + pytest)가 통과합니다 - [ ] 다른 사람의 폴더나 `core/`를 (합의 없이) 수정하지 않았습니다 - [ ] 원자료·가공 데이터 파일을 커밋하지 않았습니다 (시뮬레이션·조례 목록 제외) +- [ ] 결과 PR이면 작성자가 아닌 리뷰어가 [검토 체크리스트](docs/ops/review-checklist.md) 여덟 항목을 리뷰 댓글로 확인했습니다 ## 리뷰어에게 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 67d8cc45..57f2512c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,3 +56,27 @@ jobs: cases/_example_night_clinic/figures/ if-no-files-found: warn retention-days: 14 + + # PyWhy(DoWhy)·CausalML 연계 — 무거운 선택 설치라 따로 돈다 + causal: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + MPLBACKEND: Agg + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: pyproject.toml + - name: Install (causal extra) + run: | + python -m pip install --upgrade pip + pip install -e ".[dev,causal]" + - name: License check with causal extra + run: python scripts/check_licenses.py + - name: PyWhy·CausalML tests + run: pytest -q tests/test_causal.py + - name: Second opinion on the example case + run: python -m core.causal cases/_example_night_clinic --no-write diff --git a/.github/workflows/plan-agent.yml b/.github/workflows/plan-agent.yml new file mode 100644 index 00000000..f041bee3 --- /dev/null +++ b/.github/workflows/plan-agent.yml @@ -0,0 +1,76 @@ +name: Plan agent (작업 제안 → 가설·데이터 점검 → plan 초안 PR) + +# 작업 제안 이슈가 열리거나 고쳐지면: 가설·데이터 점검과 plan.yaml 초안을 댓글로 (하나의 댓글을 계속 고침) +# 메인테이너가 'plan-approved' 라벨을 붙이면: 그 초안으로 브랜치와 PR 을 연다 — 사람이 승인하는 관문 +# 이슈 본문은 믿지 않는 입력이라 셸에 넣지 않고 환경변수로만 파이썬에 넘긴다. +on: + issues: + types: [opened, edited, labeled] + +permissions: + contents: read + +jobs: + comment: + if: contains(github.event.issue.labels.*.name, 'case-proposal') && github.event.action != 'labeled' + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: pyproject.toml + - run: pip install -e . + - name: Feasibility comment + env: + ISSUE_TITLE: ${{ github.event.issue.title }} + ISSUE_BODY: ${{ github.event.issue.body }} + GH_TOKEN: ${{ github.token }} + NUM: ${{ github.event.issue.number }} + run: | + python -m core.causal.issue_agent comment > comment.md + id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" --paginate \ + --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(""))) | .id' | head -1) + if [ -n "$id" ]; then + gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -F body=@comment.md > /dev/null + else + gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" -F body=@comment.md > /dev/null + fi + + draft-pr: + if: github.event.action == 'labeled' && github.event.label.name == 'plan-approved' && contains(github.event.issue.labels.*.name, 'case-proposal') + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + issues: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: pyproject.toml + - run: pip install -e . + - name: Write plan draft and open PR + env: + ISSUE_TITLE: ${{ github.event.issue.title }} + ISSUE_BODY: ${{ github.event.issue.body }} + GH_TOKEN: ${{ github.token }} + NUM: ${{ github.event.issue.number }} + run: | + branch="agent/plan-issue-$NUM" + git switch -c "$branch" + case=$(python -m core.causal.issue_agent write) + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add "cases/$case/plan.yaml" + git commit -m "plan($case): 작업 제안 #$NUM 에서 만든 plan.yaml 초안 (TODO 를 채운 뒤 머지)" + git push origin "$branch" + printf '작업 제안 #%s 에서 `python -m core.causal.draft` 로 만든 초안입니다.\n\n- [ ] 데이터를 보기 **전에** TODO 를 모두 채웠습니다\n- [ ] 처치 시점·비교 대상 근거를 확인했습니다\n\n이 PR 을 머지하는 것이 사전 등록입니다. Closes #%s 는 결과 PR 에서 씁니다.\n' "$NUM" "$NUM" > pr.md + if ! gh pr create --head "$branch" --title "plan($case): 질문에서 만든 초안 (#$NUM)" --body-file pr.md; then + gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" -f body="초안 브랜치 \`$branch\` 를 만들었어요. 저장소 설정에서 Actions 의 PR 생성이 꺼져 있어 PR 은 직접 열어 주세요." > /dev/null + fi diff --git a/Makefile b/Makefile index 6ec5a887..2dadd898 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: install check lint test format app activity flow demo site lineage readme +.PHONY: install check lint test format app activity flow demo site lineage readme pywhy draft PY ?= python @@ -25,6 +25,15 @@ CASE ?= cases/_example_night_clinic flow: $(PY) -m core.agent $(CASE) +# 두 번째 의견: PyWhy(DoWhy) 식별·반박 검정 + CausalML 단위별 효과 → cases/<케이스>/pywhy_check.json +# 먼저 pip install -e ".[causal]" +pywhy: + $(PY) -m core.causal $(CASE) + +# 질문 한 줄 → 가설·데이터 점검 → plan.yaml 초안 (Q="질문", NEW=<내ID>-<주제> 를 주면 cases/ 에 저장) +draft: + $(PY) -m core.causal.draft "$(Q)" $(if $(NEW),--case $(NEW) --write,) + # 연습: 토지거래허가구역 예시를 _demo/ 에 복사해 돌린다. 레포 파일은 바뀌지 않는다. demo: rm -rf _demo && mkdir -p _demo && cp -r cases/t3-land-permit-2025 _demo/ diff --git a/README.md b/README.md index 4bd5e9e0..6b97ba71 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ "효과 있었다", "실패했다"는 말이 나올 때 **진짜 효과인지 확인하는 장치**입니다. 정책을 받은 동네와 안 받은 동네를 공공데이터로 비교하고, 데이터가 모르면 "판단 불가"라고 정직하게 말합니다. 질문부터 데이터·계보·분석·대시보드까지 전부 오픈소스입니다. -🔎 **[정책 이름으로 찾기](https://causalinferencelab.github.io/policy-effect-analytics-agent/search.html)** — 이미 확인한 결과와 판정, 쓸 수 있는 공공데이터, 데이터 계보가 한 번에 나옵니다. 결과가 없으면 그 자리에서 분석을 요청할 수 있습니다. +🔎 **[정책 이름으로 찾기](https://causalinferencelab.github.io/policy-effect-analytics-agent/search.html)** — 이미 확인한 결과와 판정, 쓸 수 있는 공공데이터, 데이터 계보가 한 번에 나옵니다. 결과가 없으면 그 자리에서 분석을 요청할 수 있습니다. **뉴스 문장을 통째로 붙여 넣으면** 그 문장이 결과로 뒷받침되는지(뒷받침 · 범위 안 · 결과를 넘어섬 · 결과와 다름) 보여 줍니다. [![사이트 열기](https://img.shields.io/badge/사이트-열기-1d4e89)](https://causalinferencelab.github.io/policy-effect-analytics-agent/) [![분석 결과](https://img.shields.io/badge/분석_결과-보기-1e6a4d)](https://causalinferencelab.github.io/policy-effect-analytics-agent/results.html) @@ -33,6 +33,7 @@ | **궁금한 시민** | [검색](https://causalinferencelab.github.io/policy-effect-analytics-agent/search.html)에 정책 이름 넣기, 또는 [사이트](https://causalinferencelab.github.io/policy-effect-analytics-agent/) 대화창에 물어보기. 주제·데이터·조심할 점을 같이 정리해 줍니다 | | **기자 · 공무원 · 연구자** | [분석 결과](https://causalinferencelab.github.io/policy-effect-analytics-agent/results.html)에서 판정과 그대로 가져다 써도 되는 인용문, 쓴 데이터, CSV를 받기 | | **분석가 · 개발자** | 아래 [5분 만에 돌려 보기](#5분-만에-돌려-보기) → [참여 가이드](docs/ops/mentee-guide.md). 공개 API(`api/*.json`)로 서비스를 만들어도 좋습니다 | +| **인과추론을 하는 사람** | `make draft Q="질문"`으로 가설·데이터 점검과 plan.yaml 초안, `make pywhy`로 [PyWhy(DoWhy)](https://github.com/py-why/dowhy)·[CausalML](https://github.com/uber/causalml) 두 번째 의견(식별·반박 검정·단위별 효과)을 붙이기 | ## 지금까지 만든 것 diff --git a/cases/t3-land-permit-2025/pywhy_check.json b/cases/t3-land-permit-2025/pywhy_check.json new file mode 100644 index 00000000..d3d81c8f --- /dev/null +++ b/cases/t3-land-permit-2025/pywhy_check.json @@ -0,0 +1,88 @@ +{ + "case": "t3-land-permit-2025", + "status": "ok", + "data": { + "path": "cases/t3-land-permit-2025/data/panel.csv", + "rows": 500 + }, + "outcome": { + "col": "log_trades", + "name": "아파트 매매 거래건수(로그)", + "unit": "log 건", + "expected": "decrease" + }, + "units": { + "treated": 4, + "control": 21 + }, + "did_2x2": -0.4395291160608205, + "baseline_estimate": -0.4033194212892391, + "same_direction_as_baseline": true, + "dowhy": { + "status": "ok", + "graph": { + "nodes": [ + "T", + "dy", + "y_pre" + ], + "edges": [ + [ + "T", + "dy" + ], + [ + "y_pre", + "T" + ], + [ + "y_pre", + "dy" + ] + ] + }, + "identification": { + "method": "backdoor", + "adjust_for": [ + "y_pre" + ] + }, + "estimate": -0.43955510446812324, + "ci": [ + -0.47734353202397894, + -0.40176667691226764 + ], + "refutations": [ + { + "method": "placebo_treatment_refuter", + "label": "가짜 처치(처치 순서 섞기)", + "rule": "가짜 처치의 효과는 0 근처여야 해요", + "new_effect": 0.012393113285063689, + "p_value": 0.94, + "status": "pass" + }, + { + "method": "random_common_cause", + "label": "무작위 공통 원인 추가", + "rule": "아무 관련 없는 변수를 넣어도 추정치가 거의 같아야 해요", + "new_effect": -0.4408768057224783, + "p_value": 0.76, + "status": "pass" + }, + { + "method": "data_subset_refuter", + "label": "80% 부분 표본", + "rule": "일부 단위를 빼도 추정치가 거의 같아야 해요", + "new_effect": -0.4389682781910143, + "p_value": 0.8799999999999999, + "status": "pass" + } + ], + "warning": "처치 단위가 4곳뿐이라 회귀 신뢰구간은 참고용입니다(기본 추정은 무작위화 추론을 씁니다)" + }, + "causalml": { + "status": "skipped", + "message": "처치 4곳 · 비교 21곳 — 단위별 효과는 각각 10곳 이상일 때만 봅니다" + }, + "note": "두 번째 의견입니다. 판정은 plan.yaml 과 기본 추정(make flow)이 냅니다." +} diff --git a/catalog/projects.yaml b/catalog/projects.yaml index d9583b71..3194bf7a 100644 --- a/catalog/projects.yaml +++ b/catalog/projects.yaml @@ -4,6 +4,10 @@ # plan.yaml → 계획 · fetch.py → 수집 · flow_log.json → 분석 · discussion.md(템플릿과 다르면) → 해석 # reproduced_by: [GitHub ID, ...] — 다른 참여자가 make flow 로 같은 판정을 얻었으면 재현 이슈를 확인하고 추가합니다. # 답 페이지의 '이 결과를 얼마나 믿을 수 있나'와 카드의 '교차 재현됨' 배지로 나옵니다. +# reviewed_by: [GitHub ID, ...] — 작성자가 아닌 사람이 docs/ops/review-checklist.md 여덟 항목을 확인했으면 추가합니다('검토됨' 배지). +# claims: 뉴스·발표에서 나온 구체적인 주장을 이 결과로 검토했을 때만 적습니다 → 답 페이지에 팩트체크 표준 마크업(ClaimReview) +# - text: "주장 문장 그대로" by: "말한 사람·기관" url: "주장이 실린 곳" date: YYYY-MM-DD +# rating: "결과와 맞음" | "범위 안" | "결과를 넘어섬" | "결과와 다름" (검토한 사람이 고름) version: 1 projects: - case: sgim49697-ops-gangnam-bus-2024 diff --git a/core/causal/__init__.py b/core/causal/__init__.py new file mode 100644 index 00000000..3f2e0fa2 --- /dev/null +++ b/core/causal/__init__.py @@ -0,0 +1,15 @@ +"""인과추론 라이브러리 연계 — PyWhy(DoWhy)와 CausalML. + +이 패키지는 기본 추정(core.estimators: 이중차분·이벤트 스터디·무작위화 추론)을 **대신하지 않습니다.** +판정은 여전히 plan.yaml 과 기본 추정이 냅니다. 여기서는 세 가지를 덧붙입니다. + +1. feasibility 가설·데이터 점검 (추가 설치 없음) + "이 질문을 지금 있는 공공데이터로 분석할 수 있나?" — 처치 시점 근거 · 결과 데이터 · 공통 원인(통제) 데이터 · + 공간×시간 단위가 맞는지를 카탈로그로 확인하고, PyWhy 식 인과 그래프(정책 → 결과, 공통 원인 → 둘 다)를 만든다. +2. pywhy DoWhy 로 같은 질문을 다시 묻기 (pip install -e ".[causal]") + 단위별 '정책 전후 변화'로 바꾼 표에서 인과 그래프 → 식별(뒷문 기준) → 추정 → 반박 검정 3종 + (가짜 처치 · 무작위 공통 원인 추가 · 부분 표본). 기본 추정과 방향이 같은지 본다. +3. hte CausalML 메타러너(T-러너)로 효과가 단위마다 달랐는지 (처치·비교 단위가 각각 10곳 이상일 때만) + +실행: python -m core.causal cases/<케이스> → cases/<케이스>/pywhy_check.json (사이트 답 페이지에 표시) +""" diff --git a/core/causal/__main__.py b/core/causal/__main__.py new file mode 100644 index 00000000..5ccac5fe --- /dev/null +++ b/core/causal/__main__.py @@ -0,0 +1,47 @@ +"""python -m core.causal cases/<케이스> [--data 분석용표.csv] [--no-write]""" + +from __future__ import annotations + +import argparse +import json +import sys + +from .pywhy import check_case, write + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description="PyWhy(DoWhy)·CausalML 두 번째 의견") + ap.add_argument("case") + ap.add_argument("--data", default=None) + ap.add_argument("--no-write", action="store_true") + a = ap.parse_args(argv) + r = check_case(a.case, a.data) + if r["status"] != "ok": + print(r.get("message", r["status"]), file=sys.stderr) + return 1 + dw, ml = r["dowhy"], r["causalml"] + print( + f"[{r['case']}] {r['outcome']['name']} · 처치 {r['units']['treated']} / 비교 {r['units']['control']}" + ) + print(f" 2×2 이중차분 {r['did_2x2']:+.4g} · 기본 추정 {r['baseline_estimate']}") + if dw["status"] == "ok": + print( + f" DoWhy 추정 {dw['estimate']:+.4g} (보정: {', '.join(dw['identification']['adjust_for'])})" + ) + for x in dw["refutations"]: + print(f" - {x['label']}: {x.get('status')} (새 추정 {x.get('new_effect')})") + else: + print(" DoWhy:", dw.get("message")) + print( + " CausalML:", + ml.get("message") or f"ATE {ml['ate']:+.4g}, 단위별 효과 p10~p90 {ml['cate_quantiles']}", + ) + if not a.no_write: + print(" 저장:", write(a.case, r)) + else: + print(json.dumps(r, ensure_ascii=False, indent=1, default=str)[:400]) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/core/causal/draft.py b/core/causal/draft.py new file mode 100644 index 00000000..d986ae8a --- /dev/null +++ b/core/causal/draft.py @@ -0,0 +1,196 @@ +"""질문 한 줄 → 가설·데이터 점검 → plan.yaml 초안 (사람이 승인하는 에이전트의 첫 단계). + + python -m core.causal.draft "서울 토허제 확대 뒤 옆 동네 집값이 올랐나" # 화면에만 + python -m core.causal.draft "…" --case gildong-ltp-spillover --write # cases/<케이스>/plan.yaml + +하는 일 + 1. 질문을 주제·지금 이슈에 맞춘다 (core.discovery.match — 키워드 점수, 지어내지 않음) + 2. 그 주제의 가설·데이터 점검(feasibility)을 붙인다 — 처치 시점 근거, 결과·통제 데이터, 단위 + 3. 스키마(core.schema.plan)를 통과하는 plan.yaml 초안을 만든다. 사람이 확인해야 할 칸은 'TODO' 주석. + 시행일은 지금 이슈(issues.yaml)의 공식 시행일만 쓰고, 없으면 TODO 로 남긴다. + 4. --write 는 새 폴더에만 쓴다(있으면 멈춤). 데이터는 받지 않는다 — fetch.py 는 사람이 쓴다. + +LLM 은 쓰지 않는다. 숫자·날짜·데이터 id 는 전부 카탈로그에서 온다. +""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +import yaml + +from core.discovery.catalog import ROOT, load_catalog, load_topics +from core.discovery.match import match_topic +from core.discovery.ontology import load_datasets, load_issues + +from .feasibility import topic_feasibility + +DESIGN_METHOD = { + "did_simultaneous": "event_study", + "did_staggered": "event_study", + "scm": "did", + "its": "its", +} + + +def _q(s: str) -> str: + return '"' + str(s).replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def draft(question: str, case_id: str = "gildong-topic", hint: str = "") -> dict: + """hint: 주제 id·이슈 id 처럼 매칭에만 쓰고 plan 에는 넣지 않는 글.""" + question = " ".join(str(question).split())[:300] # 한 줄로 — YAML 블록·주석을 깨지 않게 + topics = load_topics() + ids = {t.id: t for t in topics} + hint_ids = [x for x in re.split(r"[\s/,]+", hint or "") if x] + hinted = next((ids[x] for x in hint_ids if x in ids), None) + m = match_topic(question + " " + (hint or ""), topics, load_catalog()) + if hinted: + from core.discovery.match import TopicMatch + + m = [TopicMatch(hinted, 99.0, ["hint"])] + [x for x in m if x.topic.id != hinted.id] + if not m: + return { + "matched": False, + "message": "주제를 찾지 못했어요. 정책 이름·지역을 넣어 다시 물어보세요.", + } + topic = m[0].topic + datasets, issues = load_datasets(), load_issues() + feas = topic_feasibility(topic, datasets, issues) + my_issues = [i for i in issues if i.topic == topic.id] + qn = re.sub(r"\s+", "", question) + issue = next((i for i in my_issues if i.id in hint_ids), None) or max( + my_issues, + key=lambda i: sum(w in qn for w in re.findall(r"[가-힣A-Za-z0-9]{2,}", i.name)), + default=None, + ) + ds = [d for d in datasets if topic.id in d.topics] + outs = sorted( + [d for d in ds if "outcome" in d.roles], + key=lambda d: ( + d.id not in (issue.datasets if issue else []), + d.approval not in {"즉시", "자동승인", "없음"}, + ), + ) + covs = [d for d in ds if "covariate" in d.roles][:2] + when = issue.effective if issue else None + monthly = any(("월" in d.time) for d in outs[:1]) + t_col, freq = ("month", "month") if monthly else ("year", "year") + treat_time = (when[:7] if monthly else int(when[:4])) if when else None + expected = "unknown" + lines = [ + "# 질문에서 만든 plan.yaml 초안 (python -m core.causal.draft) — 데이터를 보기 전에 TODO 를 채우고 PR 로 사전 등록하세요.", + f"# 원래 질문: {question}", + f"# 가설·데이터 점검: {feas['label']} — " + + " · ".join(f"{c['label']} {c['status']}" for c in feas["checks"]), + f"case_id: {case_id}", + f"title: {_q((issue.name if issue else topic.name) + ' 효과 분석')}", + "question: >", + f" {question.strip()}", + "synthetic_data: false", + "", + "unit: {name: 시군구, id_col: region_id} # TODO: 결과 데이터의 공간 단위에 맞추기", + f"time: {{col: {t_col}, freq: {freq}, start: TODO, end: TODO}} # TODO: 정책 전 최소 3시점" + if not when + else f"time: {{col: {t_col}, freq: {freq}, start: {_q(str(int(when[:4]) - 3) + (when[4:7] if monthly else '')) if monthly else int(when[:4]) - 3}, end: {_q(when[:4] + '-12') if monthly else int(when[:4]) + 2}}} # TODO: 기간 확인", + "", + "treatment:", + f" definition: {_q(issue.treatment if issue else 'TODO: 정책을 받은 곳과 시점')}", + " group_col: treated", + f" treat_time: {_q(treat_time) if isinstance(treat_time, str) else treat_time if treat_time else 'TODO # 공식 시행일'}", + "control:", + f" definition: {_q(issue.control if issue else 'TODO: 같은 기간 정책을 받지 않은 곳')}", + ' rationale: "TODO: 정책 전 추세가 나란했다고 볼 이유 (결과를 보고 고르지 않기)"', + "", + "outcomes:", + f" - name: {_q(issue.outcomes[0] if issue and issue.outcomes else (outs[0].measures[0] if outs and outs[0].measures else '주요 결과 지표'))}", + " col: outcome", + ' definition: "TODO: 분자/분모/기간까지 조작적으로"', + " primary: true", + f" expected_direction: {expected} # TODO: increase | decrease (데이터 보기 전에)", + "", + "estimator:", + f" method: {DESIGN_METHOD.get(issue.design, 'event_study') if issue else 'event_study'}", + " cluster_col: region_id", + f" covariates: [] # 공통 원인 후보(인과 그래프): {', '.join(d.name for d in covs) or '없음'}", + "", + "assumptions:", + " - name: 평행추세", + ' description: "정책이 없었다면 두 집단의 추세는 같았을 것"', + " check: pretrend_test", + " - name: 동시 정책 없음", + f" description: {_q(issue.pitfalls[0] if issue and issue.pitfalls else '같은 시점에 결과에 영향을 준 다른 정책이 없음')}", + " check: manual", + "", + "refutations:", + " - kind: placebo_time", + " params: {shift: 2}", + "", + "abstention:", + " - when: pretrend_rejected", + " verdict: not_identified", + " - when: few_treated_clusters", + " verdict: conditional", + " - when: ci_crosses_zero", + " verdict: conditional", + "", + "data_sources:", + ] + for d in (outs[:2] + covs) or []: + lic = d.license if d.license.startswith("KOGL") or d.license == "other" else "other" + lines += [ + f" - name: {_q(d.name)}", + f" provider: {_q(d.provider)}", + f" url: {_q(d.url)}", + f" license: {lic} # 카탈로그: {d.license}", + f" notes: {_q('역할: ' + '/'.join(d.roles) + ' · 단위: ' + d.space + ' × ' + d.time)}", + ] + if not (outs or covs): + lines += [' - name: "TODO"', ' provider: "TODO"', " license: other"] + text = "\n".join(lines) + "\n" + return { + "matched": True, + "topic": topic.id, + "issue": issue.id if issue else None, + "feasibility": feas, + "plan_yaml": text, + "todo": text.count("TODO"), + } + + +def write(case_id: str, text: str) -> Path: + case = ROOT / "cases" / case_id + if case.exists(): + raise FileExistsError(f"{case} 가 이미 있어요. 다른 이름을 쓰세요") + case.mkdir(parents=True) + (case / "plan.yaml").write_text(text, encoding="utf-8") + return case / "plan.yaml" + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description="질문 → 가설·데이터 점검 → plan.yaml 초안") + ap.add_argument("question") + ap.add_argument("--case", default="gildong-topic") + ap.add_argument("--write", action="store_true") + a = ap.parse_args(argv) + r = draft(a.question, a.case) + if not r["matched"]: + print(r["message"], file=sys.stderr) + return 1 + f = r["feasibility"] + print(f"주제: {r['topic']} · 이슈: {r['issue'] or '없음'} · 판정: {f['label']}") + print(f"가설: {f['hypothesis']['sentence']}") + for c in f["checks"]: + print(f" [{c['status']:>4}] {c['label']} — {c['detail']}") + print(f"\n--- plan.yaml 초안 (TODO {r['todo']}곳) ---\n{r['plan_yaml']}") + if a.write: + print("저장:", write(a.case, r["plan_yaml"])) + yaml.safe_load(r["plan_yaml"]) # 최소한 YAML 로 읽혀야 한다 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/core/causal/feasibility.py b/core/causal/feasibility.py new file mode 100644 index 00000000..7375b4e7 --- /dev/null +++ b/core/causal/feasibility.py @@ -0,0 +1,206 @@ +"""가설·데이터 점검 — "이 질문, 지금 있는 데이터로 분석할 수 있나?" (추가 설치 없음). + +주제(topics.yaml) 하나를 받아 카탈로그만 보고 판단한다. 데이터를 받거나 숫자를 계산하지 않는다. + + 가설 정책(처치) ─▶ 결과 지표, 예상 방향 + 점검 6개 ① 언제(처치 시점 근거) ② 누가(받은 곳·안 받은 곳) ③ 결과 데이터 ④ 공통 원인(통제) 데이터 + ⑤ 공간 단위 ⑥ 시간 단위 — 처치 근거와 결과 데이터가 같은 단위로 만날 수 있나 + 판정 바로 분석 가능 · 데이터 한 가지 더 필요 · 아직 어려움 + +인과 그래프는 PyWhy(DoWhy)가 쓰는 모양(노드·화살표)으로 만든다: 정책 → 결과, 공통 원인 → 정책·결과. +공통 원인 데이터가 있으면 뒷문(backdoor) 경로를 막을 후보가 있다는 뜻이고, 없으면 이중차분의 +'정책 전 추세가 나란했다'는 가정에 더 기대야 한다는 뜻이다. +""" + +from __future__ import annotations + +import re + +READY = {"즉시", "자동승인", "없음"} +SPACE = [ # 굵은 단위 → 세밀한 단위 + ("전국", 0), + ("시도", 1), + ("시군구", 2), + ("자치구", 2), + ("시군", 2), + ("읍면동", 3), + ("법정동", 3), + ("행정동", 3), + ("상권", 4), + ("지점", 4), + ("도로", 4), + ("개별", 5), +] +SPACE_KO = {0: "전국", 1: "시도", 2: "시군구", 3: "읍면동", 4: "지점·상권", 5: "개별 건"} +TIME = [ + ("연", 0), + ("반기", 1), + ("분기", 1), + ("월", 2), + ("주", 3), + ("일", 4), + ("시간", 5), + ("실시간", 5), +] +TIME_KO = {0: "연", 1: "분기", 2: "월", 3: "주", 4: "일", 5: "시간"} +GATE_OK = {"pass": "ok", "check": "warn", "key": "warn", "fail": "miss"} + + +def space_level(text: str) -> int | None: + """데이터셋 space 글 → 단위 단계. 시군구(법정동)처럼 둘이면 더 세밀한 쪽.""" + hits = [lv for k, lv in SPACE if k in (text or "")] + return max(hits) if hits else None + + +def time_level(text: str) -> int | None: + t = text or "" + if "실시간" in t: + return 5 + hits = [lv for k, lv in TIME if re.search(rf"(^|[^가-힣]){k}($|[^가-힣])", t) or t == k] + return max(hits) if hits else None + + +def _ready(d) -> bool: + return d.approval in READY or "자동승인" in d.approval or d.approval.startswith("없음") + + +def topic_feasibility(topic, datasets, issues=(), n_results: int = 0) -> dict: + ds = [d for d in datasets if topic.id in d.topics] + by = {r: [d for d in ds if r in d.roles] for r in ("treatment", "outcome", "covariate")} + outs_ready = [d for d in by["outcome"] if _ready(d)] + my_issues = [i for i in issues if i.topic == topic.id] + legal = bool(topic.legal and (topic.legal.laws or topic.legal.admin_rules)) + events = list(getattr(topic, "events", []) or []) + + checks: list[dict] = [] + + def add(key, status, label, detail): + checks.append({"key": key, "status": status, "label": label, "detail": detail}) + + gates = topic.gates + when_src = [] + if my_issues: + when_src.append(f"지금 이슈 {len(my_issues)}개의 공식 시행일") + if legal: + when_src.append("법제처 법령·행정규칙 개정일") + if events: + when_src.append(f"정리된 정책 사건 {len(events)}개") + if by["treatment"]: + when_src.append(f"처치 데이터 {len(by['treatment'])}개") + g = gates.get("when") + st = GATE_OK.get(g.status, "warn") if g else ("ok" if when_src else "miss") + if not when_src: + st = "miss" + add( + "when", + st, + "언제 시작했나 (처치 시점)", + ", ".join(when_src) or "시행일 근거를 아직 못 찾았어요", + ) + g = gates.get("who") + add( + "who", + GATE_OK.get(g.status, "warn") if g else "warn", + "누가 받았고 누가 안 받았나 (비교 대상)", + (g.note if g and g.note else "받은 곳과 안 받은 곳을 나눌 기준을 확인해야 해요"), + ) + if outs_ready: + add( + "what", + "ok", + "무엇으로 재나 (결과 데이터)", + f"결과 데이터 {len(by['outcome'])}개 중 {len(outs_ready)}개는 오늘 받을 수 있어요", + ) + elif by["outcome"]: + add( + "what", + "warn", + "무엇으로 재나 (결과 데이터)", + f"결과 데이터 {len(by['outcome'])}개 — 키 발급·신청이 필요해요", + ) + else: + add( + "what", "miss", "무엇으로 재나 (결과 데이터)", "결과를 잴 공공데이터를 아직 못 찾았어요" + ) + add( + "confounders", + "ok" if by["covariate"] else "warn", + "공통 원인 (통제 데이터)", + f"인구·기상 같은 통제 데이터 {len(by['covariate'])}개 — 인과 그래프의 뒷문 경로를 막을 후보" + if by["covariate"] + else "통제 데이터가 없어요. '정책 전 추세가 나란했다'는 가정에 더 기대야 해요", + ) + # 단위: 결과 데이터가 처치 근거와 만날 수 있는 가장 세밀한 단위 + o_space = [lv for d in by["outcome"] if (lv := space_level(d.space)) is not None] + o_time = [lv for d in by["outcome"] if (lv := time_level(d.time)) is not None] + # 정책은 지역 단위로 배정된다 — 처치 자료가 개별 건이어도 읍면동보다 세밀하게 나누지 않는다 + t_space = [min(lv, 3) for d in by["treatment"] if (lv := space_level(d.space)) is not None] + t_time = [lv for d in by["treatment"] if (lv := time_level(d.time)) is not None] + if legal or my_issues: # 법령·고시·조례 시행일은 시군구·일 단위로 나뉜다고 본다 + t_space.append(2) + t_time.append(4) + space_common = min(max(o_space), max(t_space)) if o_space and t_space else None + time_common = min(max(o_time), max(t_time)) if o_time and t_time else None + add( + "space", + "ok" + if space_common is not None and space_common >= 2 + else "warn" + if space_common is not None + else "miss", + "공간 단위가 맞나", + f"{SPACE_KO[space_common]} 단위까지 처치와 결과를 맞출 수 있어요" + if space_common is not None + else "처치·결과 데이터의 공간 단위를 확인해야 해요", + ) + add( + "time", + "ok" + if time_common is not None and time_common >= 2 + else "warn" + if time_common is not None + else "miss", + "시간 단위가 맞나", + f"{TIME_KO[time_common]} 단위 전후 비교가 가능해요 (정책 전 최소 3시점 필요)" + if time_common is not None + else "결과 데이터의 시간 단위를 확인해야 해요", + ) + miss = sum(c["status"] == "miss" for c in checks) + warn = sum(c["status"] == "warn" for c in checks) + if miss == 0 and warn == 0: + verdict, label = "go", "바로 분석 가능" + elif miss == 0: + verdict, label = "warn", f"확인 {warn}가지 뒤 가능" + elif miss == 1: + verdict, label = "warn", "데이터 한 가지 더 필요" + else: + verdict, label = "stop", "아직 어려움" + outcome_name = (my_issues[0].outcomes[0] if my_issues and my_issues[0].outcomes else None) or ( + by["outcome"][0].measures[0] if by["outcome"] and by["outcome"][0].measures else "결과 지표" + ) + policy_name = my_issues[0].name if my_issues else f"{topic.name} 정책" + covs = [d.name for d in by["covariate"]][:4] + sentence = ( + f"'{policy_name}'(처치)이 '{outcome_name}'(결과)을 바꿨다 — 받은 곳과 안 받은 곳의 전후 변화 차이로 확인" + if my_issues + else f"{topic.question} — 정책을 받은 곳과 안 받은 곳의 전후 변화 차이로 확인 (결과 후보: {outcome_name})" + ) + return { + "topic": topic.id, + "hypothesis": { + "question": topic.question, + "treatment": policy_name, + "outcome": outcome_name, + "sentence": sentence, + }, + "checks": checks, + "verdict": verdict, + "label": label, + "n_results": n_results, + "graph": { # PyWhy(DoWhy) 그래프와 같은 모양: 노드 · 화살표 + "nodes": ["정책", "결과", *[f"공통 원인: {c}" for c in covs], "시간 추세"], + "edges": [["정책", "결과"], ["시간 추세", "결과"]] + + [[f"공통 원인: {c}", "정책"] for c in covs] + + [[f"공통 원인: {c}", "결과"] for c in covs], + }, + } diff --git a/core/causal/issue_agent.py b/core/causal/issue_agent.py new file mode 100644 index 00000000..008111b0 --- /dev/null +++ b/core/causal/issue_agent.py @@ -0,0 +1,120 @@ +"""작업 제안 이슈 → 가설·데이터 점검 댓글 → (사람이 승인하면) plan.yaml 초안 PR. + +.github/workflows/plan-agent.yml 이 부른다. 이슈 본문은 믿지 않는 입력이라 셸에 넣지 않고 환경변수로만 받는다. + + ISSUE_NUMBER, ISSUE_TITLE, ISSUE_BODY 환경변수 + python -m core.causal.issue_agent comment → 댓글 본문(markdown)을 표준출력으로 + python -m core.causal.issue_agent write → cases/<케이스>/plan.yaml 을 쓰고 케이스 이름을 출력 + +사람의 관문: 메인테이너가 이슈에 'plan-approved' 라벨을 붙여야 PR 을 만든다. PR 을 머지하는 것이 사전 등록이다. +""" + +from __future__ import annotations + +import os +import re +import sys + +from core.discovery.catalog import ROOT + +from .draft import draft, write + +MARK = "" +SECTION = re.compile(r"^###\s+(.+?)\s*$", re.M) +OWNER = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$") + + +def parse_form(body: str) -> dict[str, str]: + """GitHub 이슈 폼 본문(### 라벨 \\n\\n 값) → {라벨: 값}.""" + out: dict[str, str] = {} + parts = SECTION.split(body or "") + for label, value in zip(parts[1::2], parts[2::2], strict=False): + v = value.strip() + out[label.strip()] = "" if v in ("_No response_", "미정") else v + return out + + +def _field(form: dict, prefix: str) -> str: + return next((v for k, v in form.items() if k.startswith(prefix)), "") + + +def case_name(form: dict, topic_id: str | None) -> str | None: + owner = _field(form, "담당자").lstrip("@").strip() + if not OWNER.match(owner): + return None + slug = topic_id or "topic" + name = re.sub(r"[^a-z0-9-]+", "-", f"{owner}-{slug}".lower()).strip("-") + return name[:60] + + +def plan_for_issue(title: str, body: str) -> dict: + form = parse_form(body) + question = _field(form, "하려는 것") or re.sub(r"^\[작업\]\s*", "", title or "") + question = " ".join(question.split())[:300] + topic_hint = _field(form, "주제") + r = draft(question, "gildong-topic", hint=topic_hint) + topic = r.get("topic") if r.get("matched") else None + case = case_name(form, topic) + if r.get("matched") and case: + r = draft(question, case, hint=topic_hint) + return {"question": question, "case": case, "topic": topic, **r} + + +def comment(title: str, body: str) -> str: + r = plan_for_issue(title, body) + if not r.get("question"): + return f"{MARK}\n질문 칸이 비어 있어 가설·데이터 점검을 하지 못했어요. '하려는 것'에 한두 문장을 적어 주세요." + if not r.get("matched"): + return ( + f"{MARK}\n### 가설·데이터 점검 (자동)\n이 질문과 맞는 주제를 카탈로그에서 찾지 못했어요. " + "새 주제라면 `catalog/topics.yaml` 에 주제를 먼저 제안해 주세요. 정책 이름·지역을 넣으면 다시 확인합니다." + ) + f = r["feasibility"] + mark = {"ok": "✅", "warn": "⚠️", "miss": "❌"} + rows = "\n".join(f"| {mark[c['status']]} | {c['label']} | {c['detail']} |" for c in f["checks"]) + case = r["case"] or "<담당자ID>-<주제>" + return f"""{MARK} +### 가설·데이터 점검 (자동) — **{f["label"]}** + +**가설** {f["hypothesis"]["sentence"]} + +| | 점검 | 근거 | +|---|---|---| +{rows} + +주제 `{r["topic"]}` · 지금 이슈 `{r.get("issue") or "없음"}` · 인과 그래프(PyWhy 방식): 정책 → 결과, 공통 원인 → 정책·결과 + +
plan.yaml 초안 (TODO {r["todo"]}곳) — cases/{case}/plan.yaml + +```yaml +{r["plan_yaml"]}``` +
+ +메인테이너가 이 이슈에 `plan-approved` 라벨을 붙이면 이 초안으로 PR 을 엽니다. 데이터를 보기 전에 TODO 를 채워 PR 을 머지하는 것이 사전 등록입니다. +숫자·날짜·데이터는 전부 카탈로그에서 왔고 LLM 은 쓰지 않았어요. (`python -m core.causal.draft`)""" + + +def write_plan(title: str, body: str) -> str: + r = plan_for_issue(title, body) + if not (r.get("matched") and r.get("case")): + raise SystemExit("주제나 담당자 ID 를 확인할 수 없어 초안을 쓰지 않았어요") + write(r["case"], r["plan_yaml"]) + return r["case"] + + +def main(argv=None) -> int: + argv = argv if argv is not None else sys.argv[1:] + title, body = os.environ.get("ISSUE_TITLE", ""), os.environ.get("ISSUE_BODY", "") + if argv[:1] == ["comment"]: + print(comment(title, body)) + elif argv[:1] == ["write"]: + print(write_plan(title, body)) + else: + print(__doc__) + return 2 + return 0 + + +if __name__ == "__main__": + os.chdir(ROOT) + raise SystemExit(main()) diff --git a/core/causal/pywhy.py b/core/causal/pywhy.py new file mode 100644 index 00000000..a19e5f2a --- /dev/null +++ b/core/causal/pywhy.py @@ -0,0 +1,270 @@ +"""PyWhy(DoWhy)·CausalML 로 같은 질문을 다시 묻기 — 기본 추정의 '두 번째 의견'. + + 단위 × 시점 패널 ──▶ 단위별 정책 전후 변화(Δy) 표 + T = 처치 여부(0/1) + Δy = 정책 뒤 평균 − 정책 전 평균 (주 지표) + y_pre 와 plan 의 covariates(정책 전 평균) = 공통 원인 후보 + DoWhy 인과 그래프(공통 원인 → T, 공통 원인 → Δy, T → Δy) → 식별(뒷문 기준) → 선형 회귀 추정 + → 반박 검정 3종: 가짜 처치(순서 섞기) · 무작위 공통 원인 추가 · 80% 부분 표본 + CausalML T-러너로 단위별 효과(CATE) — 처치·비교가 각각 10곳 이상일 때만. 정책 전 수준(y_pre)별로 나눠 본다. + +Δy 의 처치-비교 차이는 2×2 이중차분과 같은 양이다(공통 원인을 넣지 않으면 정확히 같음). 그래서 기본 추정과 +방향·크기가 크게 다르면 그것 자체가 점검 신호다. 판정은 바꾸지 않는다. + +라이브러리는 선택 설치: pip install -e ".[causal]" (dowhy, causalml). 없으면 그 단계만 '설치 안 됨'으로 남긴다. +""" + +from __future__ import annotations + +import json +import math +import warnings +from pathlib import Path + +import numpy as np +import pandas as pd + +MIN_HTE_UNITS = 10 # CausalML 단위별 효과: 처치·비교 각각 이 수 이상일 때만 +N_SIM = 100 # 반박 검정 반복 수 + + +def _num(x): + try: + v = float(x) + except (TypeError, ValueError): + return None + return v if math.isfinite(v) else None + + +def _as_time(s: pd.Series): + """시점 열을 비교 가능한 값으로: 숫자면 숫자, 아니면 날짜.""" + num = pd.to_numeric(s, errors="coerce") + if num.notna().all(): + return num + return pd.to_datetime(s, errors="coerce") + + +def unit_changes(plan, df: pd.DataFrame, outcome_col: str | None = None) -> pd.DataFrame: + """패널 → 단위별 [T, dy, y_pre, <공변량 정책 전 평균>]. 처치 시점은 단위별 first_treat 또는 treat_time.""" + uid, tcol = plan.unit.id_col, plan.time.col + y = outcome_col or plan.primary_outcome.col + tr = plan.treatment + d = df[ + [c for c in {uid, tcol, tr.group_col, y, *(tr.first_treat_col or "",)} if c in df] + ].copy() + covs = [c for c in plan.estimator.covariates if c in df.columns] + for c in covs: + d[c] = df[c] + d["_t"] = _as_time(d[tcol]) + if tr.treat_time is not None: + cut = _as_time(pd.Series([tr.treat_time])).iloc[0] + d["_cut"] = cut + else: # 시차 도입: 처치 단위는 자기 시점, 비교 단위는 처치 시점들의 중앙값 + ft = _as_time(df[tr.first_treat_col]) + d["_cut"] = ft + med = ft.dropna().median() + d.loc[d["_cut"].isna(), "_cut"] = med + d["_post"] = d["_t"] >= d["_cut"] + g = d.groupby([uid, "_post"]) + pre = g[y].mean().xs(False, level="_post") + post = g[y].mean().xs(True, level="_post") + out = pd.DataFrame({"y_pre": pre, "dy": post - pre}).dropna() + out["T"] = d.groupby(uid)[tr.group_col].max().reindex(out.index).astype(int) + for c in covs: + out[c] = d[~d["_post"]].groupby(uid)[c].mean().reindex(out.index) + return out.dropna() + + +def dowhy_check(frame: pd.DataFrame, covariates: list[str], seed: int = 7) -> dict: + try: + import dowhy # noqa: F401 + from dowhy import CausalModel + except ImportError: + return { + "status": "not_installed", + "message": 'pip install -e ".[causal]" 로 dowhy 를 설치하세요', + } + common = ["y_pre", *covariates] + np.random.seed(seed) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + model = CausalModel(data=frame, treatment="T", outcome="dy", common_causes=common) + estimand = model.identify_effect(proceed_when_unidentifiable=True) + est = model.estimate_effect( + estimand, method_name="backdoor.linear_regression", test_significance=True + ) + base = _num(est.value) + refs = [] + for method, kw, label, rule in ( + ( + "placebo_treatment_refuter", + {"placebo_type": "permute", "num_simulations": N_SIM}, + "가짜 처치(처치 순서 섞기)", + "가짜 처치의 효과는 0 근처여야 해요", + ), + ( + "random_common_cause", + {"num_simulations": N_SIM}, + "무작위 공통 원인 추가", + "아무 관련 없는 변수를 넣어도 추정치가 거의 같아야 해요", + ), + ( + "data_subset_refuter", + {"subset_fraction": 0.8, "num_simulations": N_SIM}, + "80% 부분 표본", + "일부 단위를 빼도 추정치가 거의 같아야 해요", + ), + ): + try: + r = model.refute_estimate(estimand, est, method_name=method, random_seed=seed, **kw) + except Exception as ex: # 라이브러리 버전에 따라 일부 반박이 실패할 수 있다 + refs.append( + {"method": method, "label": label, "status": "error", "message": str(ex)[:160]} + ) + continue + new = _num(r.new_effect) + p = ( + _num((r.refutation_result or {}).get("p_value")) + if isinstance(r.refutation_result, dict) + else None + ) + if method == "placebo_treatment_refuter": + ok = new is not None and base is not None and abs(new) < max(abs(base), 1e-9) * 0.5 + else: + ok = ( + new is not None + and base is not None + and abs(new - base) <= max(abs(base) * 0.2, 1e-9) + ) + refs.append( + { + "method": method, + "label": label, + "rule": rule, + "new_effect": new, + "p_value": p, + "status": "pass" if ok else "warn", + } + ) + try: + backdoor = list(estimand.get_backdoor_variables()) + except Exception: + backdoor = common + try: + ci = [_num(v) for v in np.ravel(est.get_confidence_intervals())] + except Exception: + ci = None + return { + "status": "ok", + "graph": { + "nodes": ["T", "dy", *common], + "edges": [["T", "dy"], *[[c, "T"] for c in common], *[[c, "dy"] for c in common]], + }, + "identification": {"method": "backdoor", "adjust_for": backdoor}, + "estimate": base, + "ci": ci, + "refutations": refs, + } + + +def causalml_hte(frame: pd.DataFrame, covariates: list[str]) -> dict: + n_t, n_c = int(frame["T"].sum()), int((1 - frame["T"]).sum()) + if min(n_t, n_c) < MIN_HTE_UNITS: + return { + "status": "skipped", + "message": f"처치 {n_t}곳 · 비교 {n_c}곳 — 단위별 효과는 각각 {MIN_HTE_UNITS}곳 이상일 때만 봅니다", + } + try: + from causalml.inference.meta import BaseTRegressor + from sklearn.linear_model import LinearRegression + except ImportError: + return { + "status": "not_installed", + "message": 'pip install -e ".[causal]" 로 causalml 을 설치하세요', + } + feats = ["y_pre", *covariates] + X = frame[feats].to_numpy(dtype=float) + T = frame["T"].to_numpy() + y = frame["dy"].to_numpy(dtype=float) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + learner = BaseTRegressor(learner=LinearRegression(), control_name=0) + ate, lb, ub = learner.estimate_ate(X=X, treatment=T, y=y) + cate = np.ravel(learner.fit_predict(X=X, treatment=T, y=y)) + groups = [] + q = pd.qcut( + frame["y_pre"], 3, labels=["정책 전 낮음", "중간", "정책 전 높음"], duplicates="drop" + ) + for name, idx in frame.groupby(q, observed=True).groups.items(): + m = frame.index.isin(idx) + groups.append({"group": str(name), "n": int(m.sum()), "cate_mean": _num(cate[m].mean())}) + return { + "status": "ok", + "learner": "T-learner (LinearRegression)", + "features": feats, + "ate": _num(np.ravel([ate])[0]), + "ate_ci": [_num(np.ravel([lb])[0]), _num(np.ravel([ub])[0])], + "cate_quantiles": { + k: _num(np.quantile(cate, v)) for k, v in (("p10", 0.1), ("p50", 0.5), ("p90", 0.9)) + }, + "by_baseline": groups, + } + + +def check_case(case_dir: str | Path, data_path: str | Path | None = None) -> dict: + """케이스 하나: plan.yaml + 분석용 표 → DoWhy·CausalML 점검 결과 dict.""" + from core.schema.plan import load_plan + + case = Path(case_dir) + plan = load_plan(case / "plan.yaml") + path = Path(data_path) if data_path else case / plan.data_sources[0].path + if not path.exists(): + return { + "case": case.name, + "status": "no_data", + "message": f"{path} 가 없습니다. fetch.py 로 분석용 표를 만든 뒤 다시 실행하세요", + } + df = pd.read_csv(path) + o = plan.primary_outcome + frame = unit_changes(plan, df, o.col) + covs = [c for c in plan.estimator.covariates if c in frame.columns] + did = _num(frame.loc[frame["T"] == 1, "dy"].mean() - frame.loc[frame["T"] == 0, "dy"].mean()) + base = None + log = case / "flow_log.json" + if log.exists(): + try: + rows = json.loads(log.read_text(encoding="utf-8")).get("results") or [] + r = next((x for x in rows if x.get("outcome") == o.col), rows[0] if rows else None) + base = _num((r or {}).get("estimate")) + except (ValueError, AttributeError): + base = None + dw = dowhy_check(frame, covs) + n_t = int(frame["T"].sum()) + if dw.get("status") == "ok" and n_t < MIN_HTE_UNITS: + dw["warning"] = ( + f"처치 단위가 {n_t}곳뿐이라 회귀 신뢰구간은 참고용입니다(기본 추정은 무작위화 추론을 씁니다)" + ) + same_dir = None + if dw.get("estimate") is not None and base is not None: + same_dir = bool(np.sign(dw["estimate"]) == np.sign(base)) + return { + "case": case.name, + "status": "ok", + "data": {"path": str(path), "rows": int(len(df))}, + "outcome": {"col": o.col, "name": o.name, "unit": o.unit, "expected": o.expected_direction}, + "units": {"treated": int(frame["T"].sum()), "control": int((1 - frame["T"]).sum())}, + "did_2x2": did, + "baseline_estimate": base, + "same_direction_as_baseline": same_dir, + "dowhy": dw, + "causalml": causalml_hte(frame, covs), + "note": "두 번째 의견입니다. 판정은 plan.yaml 과 기본 추정(make flow)이 냅니다.", + } + + +def write(case_dir: str | Path, result: dict) -> Path: + out = Path(case_dir) / "pywhy_check.json" + out.write_text( + json.dumps(result, ensure_ascii=False, indent=1, default=str) + "\n", encoding="utf-8" + ) + return out diff --git a/docs/ops/review-checklist.md b/docs/ops/review-checklist.md new file mode 100644 index 00000000..de313cea --- /dev/null +++ b/docs/ops/review-checklist.md @@ -0,0 +1,30 @@ +# 결과 검토 체크리스트 + +사이트의 판정은 '이 데이터와 이 비교로는'이라는 조건이 붙은 답입니다. 작성자가 아닌 사람이 아래 여덟 가지를 확인하면 그 결과에 **검토됨** 배지가 붙습니다. +검토는 결과가 맞다는 보증이 아니라, 결과가 **자기 규칙을 지켰다**는 확인입니다. 숫자를 다시 돌려 보는 것은 [교차 재현](../../.github/ISSUE_TEMPLATE/reproduction.yml)이 따로 맡습니다. + +| # | 확인할 것 | 어디서 보나 | 통과 기준 | +|---|---|---|---| +| 1 | 계획이 결과보다 먼저인가 | 답 페이지 '이 결과를 얼마나 믿을 수 있나' · `git log -- cases/<케이스>/plan.yaml` | 계획 먼저 커밋, 또는 결과 뒤 수정 이유가 discussion.md '계획에서 바뀐 것'에 있음 | +| 2 | 처치 시점이 공식 문서로 확인되나 | plan.yaml `treatment.definition` · README | 법령·고시·보도자료·조례 중 하나의 링크 | +| 3 | 비교 대상이 결과를 보고 고른 것이 아닌가 | plan.yaml `control.rationale` · fetch.py | 선정 규칙이 코드나 문장으로 고정돼 있음 | +| 4 | 데이터 이용 조건이 공개에 맞나 | plan.yaml `data_sources[].license` | 공공누리 1유형·이용허락 제한 없음, 또는 원자료를 커밋하지 않음 | +| 5 | 원자료·개인정보·키가 레포에 없나 | PR 파일 목록 | `data/`·`.env`·키 없음 | +| 6 | 판정 문장이 판정을 넘지 않나 | discussion.md '결과를 한 문장으로' · README | '크기를 판별하지 못함'·'판단 불가'를 '효과 없음'으로 쓰지 않음, 인과 단정 없음 | +| 7 | 한계가 적혀 있나 | discussion.md · plan.yaml `cautions` | 동시에 일어난 다른 사건, 대조군 오염, 측정 문제 중 해당하는 것 | +| 8 | 지표 정의가 재현 가능한가 | plan.yaml `outcomes[].definition` · fetch.py | 다른 사람이 같은 표를 만들 수 있을 만큼 구체적임 | + +## 절차 + +검토 짝은 사이트 [참여](https://causalinferencelab.github.io/policy-effect-analytics-agent/projects.html#review) 화면의 '검토 짝'에 자동으로 제안됩니다(결과를 낸 다른 참여자를 돌아가며). + +1. 결과 PR에서 위 표를 복사해 PR 리뷰 댓글에 ✅/❌로 채웁니다. ❌가 있으면 작성자가 고친 뒤 다시 봅니다. +2. 여덟 개가 모두 ✅면 `catalog/projects.yaml`의 그 케이스에 `reviewed_by: [내 GitHub ID]`를 더하는 커밋을 같은 PR에 올립니다. +3. 사이트가 다시 빌드되면 결과 카드·검색 판정 패널에 **검토됨**, 답 페이지 신뢰 항목에 '검토 · 통과'가 나옵니다. + +작성자 본인은 자기 결과를 검토할 수 없습니다. 멘토 예시도 같은 규칙을 따릅니다. + +## 뉴스 주장 검토 기록 + +검색 화면에 뉴스 문장을 붙여 넣어 나온 판정은 '실제 기사·발표의 주장이면 검토 기록으로 남기기'로 [주장 검토 이슈](../../.github/ISSUE_TEMPLATE/claim-review.yml)가 됩니다. +검토자가 주장 원문·출처·날짜와 분석의 지역·기간·지표가 맞는지 확인한 뒤 `catalog/projects.yaml` 의 그 케이스 `claims:` 에 한 줄을 더하면, 답 페이지에 schema.org ClaimReview 가 붙습니다. diff --git a/docs/tracks/analysis.md b/docs/tracks/analysis.md index c3631f1e..d2a4cc1c 100644 --- a/docs/tracks/analysis.md +++ b/docs/tracks/analysis.md @@ -38,6 +38,25 @@ make demo # 예시로 한 바퀴 먼저 | 지역마다 시작일이 다름 | 시차 도입 이중차분 | 준비 중 — 그 전까지는 같은 날 시작한 지역만 골라 1차 추정 | | 정책 지역이 1~5곳 | 합성통제 | 준비 중 — 그 전까지는 무작위화 추론으로 1차 추정, 한계에 기록 | +## 질문에서 계획까지, 그리고 두 번째 의견 (PyWhy · CausalML) + +```bash +make draft Q="서울 토허제 전역 확대 뒤 집값이 잡혔나" # 가설·데이터 점검 + plan.yaml 초안 (화면에만) +make draft Q="…" NEW=<내ID>-<주제> # cases/<내ID>-<주제>/plan.yaml 로 저장 (새 폴더만) +pip install -e ".[causal]" && make pywhy CASE=cases/<내ID>-<주제> # make flow 뒤: DoWhy·CausalML 두 번째 의견 +``` + +| 단계 | 무엇을 하나 | 어디에 보이나 | +|---|---|---| +| 가설·데이터 점검 (`core/causal/feasibility.py`) | 주제마다 ① 처치 시점 근거 ② 비교 대상 ③ 결과 데이터 ④ 공통 원인(통제) 데이터 ⑤ 공간 ⑥ 시간 단위를 카탈로그로 확인. PyWhy 식 인과 그래프(정책 → 결과, 공통 원인 → 둘 다) | 이슈 보드 맨 위, 검색에서 결과가 없을 때 | +| 작업 제안 → 초안 PR (`.github/workflows/plan-agent.yml`) | 작업 제안 이슈가 열리면 가설·데이터 점검과 plan.yaml 초안을 **댓글**로 달고, 메인테이너가 `plan-approved` 라벨을 붙이면 그 초안으로 **PR**을 연다. 사람이 TODO 를 채워 머지하는 것이 사전 등록 | 이슈 댓글, PR | +| plan.yaml 초안 (`core/causal/draft.py`) | 질문 → 주제·이슈 매칭 → 스키마를 통과하는 초안. 시행일은 `issues.yaml`의 공식 날짜만, 모르는 칸은 `TODO` | 터미널, `cases/` | +| DoWhy (`core/causal/pywhy.py`) | 단위별 정책 전후 변화(Δy) 표 → 뒷문 기준 식별(정책 전 수준·공변량 보정) → 추정 → 반박 검정 3종(가짜 처치 · 무작위 공통 원인 · 80% 부분 표본) | 답 페이지 '두 번째 의견' | +| CausalML | T-러너로 단위별 효과(CATE), 정책 전 수준 셋으로 나눠 평균. 처치·비교가 각각 10곳 이상일 때만 | 답 페이지 '두 번째 의견' | + +판정은 바꾸지 않습니다. 기본 추정(`make flow`)과 방향이 다르거나 반박 검정이 '확인 필요'면 그 자체가 discussion.md 에 적을 점검 신호입니다. +결과는 `cases/<케이스>/pywhy_check.json` 으로 커밋하면 사이트에 나옵니다(예: `cases/t3-land-permit-2025`). + ## 비교군을 못 찾았을 때: 관측 통계로 공개하기 정책 지역과 비교할 곳을 끝내 고르지 못했거나 시작일이 확인되지 않으면 `make flow` 대신 **관측 통계**로 공개할 수 있습니다. diff --git a/pyproject.toml b/pyproject.toml index 1aa891b4..f835e9ff 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,7 @@ dependencies = [ [project.optional-dependencies] agent = ["langgraph>=0.2", "langchain-core>=0.3"] -causal = ["dowhy>=0.12"] +causal = ["dowhy>=0.12", "causalml>=0.15", "networkx<3.5"] # PyWhy·CausalML 두 번째 의견: python -m core.causal · networkx<3.5: causalml 0.18 이 고정하는 dowhy 0.12 가 nx.d_separated 를 씀 dev = ["pytest>=8", "ruff>=0.6", "pre-commit>=3.7"] app = ["streamlit>=1.35"] analysis = ["holidays>=0.50"] # 탐색 분석(공휴일 달력): scripts/explore_climate_card.py # 개발용 화면(선택). 공개 사이트는 site/ 의 정적 페이지 diff --git a/scripts/refresh_trends.py b/scripts/refresh_trends.py index 9bb3162d..510c9243 100644 --- a/scripts/refresh_trends.py +++ b/scripts/refresh_trends.py @@ -8,7 +8,9 @@ 새 키는 NCP 'NAVER API HUB'(Search Trend)에서 발급합니다(2026.7.30부터 개발자센터 신규 신청 중단). 개발자센터에서 전에 받은 키도 2027.6.30까지 쓸 수 있어, 두 주소를 차례로 시도합니다. 네이버 결과값은 네이버 소유이므로 사이트에는 값이 아니라 '순위'만 보여 줍니다. -둘 다 없으면 사이트는 '최근 시행·발표 순'으로 보여 주고 그렇게 표시한다. + 3. 뉴스 언급 — 구글 뉴스 RSS 검색(키 없음)에서 주제 키워드가 나온 최근 7일 기사 수. + 기사 제목·본문은 저장하지 않고 개수와 검색 링크만 남긴다. +셋 다 없으면 사이트는 '최근 시행·발표 순'으로 보여 주고 그렇게 표시한다. python scripts/refresh_trends.py """ @@ -161,6 +163,51 @@ def fetch_naver(topics) -> dict[str, float] | None: return combine_batches(batches, anchor["groupName"]) +# ─── 3. 뉴스 언급 (구글 뉴스 RSS, 키 없음) ────────────────────────────────────── +NEWS_RSS = "https://news.google.com/rss/search" +NEWS_DAYS = 7 + + +def news_query(t) -> str: + return " OR ".join(f'"{k}"' for k in t.keywords[:3]) + f" when:{NEWS_DAYS}d" + + +def news_link(t) -> str: + from urllib.parse import urlencode + + return "https://news.google.com/search?" + urlencode( + {"q": news_query(t), "hl": "ko", "gl": "KR", "ceid": "KR:ko"} + ) + + +def count_rss_items(xml_text: str) -> int: + import xml.etree.ElementTree as ET + + try: + return len(ET.fromstring(xml_text).findall("./channel/item")) + except ET.ParseError: + return 0 + + +def fetch_news(topics) -> dict[str, int] | None: + import time + + out: dict[str, int] = {} + for t in topics: + r = requests.get( + NEWS_RSS, + params={"q": news_query(t), "hl": "ko", "gl": "KR", "ceid": "KR:ko"}, + headers={ + "User-Agent": "policy-effect-analytics-agent (+https://github.com/CausalInferenceLab/policy-effect-analytics-agent)" + }, + timeout=20, + ) + r.raise_for_status() + out[t.id] = count_rss_items(r.text) + time.sleep(1) + return out + + def main() -> int: topics = load_topics() ids = {t.id for t in topics} @@ -195,6 +242,19 @@ def main() -> int: data["topics"].setdefault(t, {})["search"] = v print("네이버 데이터랩 검색 관심도 반영") + try: + news = fetch_news(topics) + except requests.RequestException as e: + print(f"뉴스 언급 수집 실패(건너뜀): {e}") + news = None + if news is not None and any(news.values()): + data["sources"].append("news") + for t in topics: + d = data["topics"].setdefault(t.id, {}) + d["news"] = news.get(t.id, 0) + d["news_url"] = news_link(t) + print("뉴스 언급 수 반영 (최근 7일)") + OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") print(f"→ {OUT.relative_to(ROOT)} (신호: {', '.join(data['sources']) or '없음'})") diff --git a/site/answers.py b/site/answers.py index 7a85bc63..f238e9f7 100644 --- a/site/answers.py +++ b/site/answers.py @@ -287,6 +287,69 @@ def reject(reason): } +def _read_json(path: Path) -> dict | None: + try: + d = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return d if isinstance(d, dict) and d.get("status") == "ok" else None + + +def _f(v, digits: int = 3) -> str: + return "-" if v is None else f"{v:+.{digits}g}" + + +def pywhy_block(e, a: dict) -> str: + """두 번째 의견: PyWhy(DoWhy) 식별·반박 검정, CausalML 단위별 효과 (python -m core.causal 결과).""" + r = a.get("pywhy") + if not r: + return ( + "

두 번째 의견 · PyWhy · CausalML

" + "

아직 돌리지 않았어요. 분석용 표가 있으면 " + f'pip install -e ".[causal]" 뒤 python -m core.causal cases/{e(a["case"])} 로 만들 수 있어요.

' + ) + dw, ml = r.get("dowhy") or {}, r.get("causalml") or {} + unit = (r.get("outcome") or {}).get("unit") or "" + same = r.get("same_direction_as_baseline") + same_b = ( + "기본 추정과 같은 방향" + if same + else "기본 추정과 방향이 다름" + if same is False + else "" + ) + refs = "".join( + f"
  • {'통과' if x.get('status') == 'pass' else '확인 필요'} " + f"{e(x.get('label', ''))} {e(x.get('rule', x.get('message', '')))} · 새 추정 {_f(x.get('new_effect'))}
  • " + for x in dw.get("refutations") or [] + ) + adj = ", ".join(dw.get("identification", {}).get("adjust_for") or []) or "없음" + adj = adj.replace("y_pre", "정책 전 수준(y_pre)") + ci = dw.get("ci") or [] + ci_txt = f" (95% 범위 {_f(ci[0])} ~ {_f(ci[1])})" if len(ci) == 2 and None not in ci else "" + if ml.get("status") == "ok": + rows = "".join( + f"{e(g['group'])}{g['n']}{_f(g['cate_mean'])} {e(unit)}" + for g in ml.get("by_baseline") or [] + ) + ml_html = ( + f"

    T-러너 평균 효과 {_f(ml.get('ate'))} {e(unit)}. 단위별 효과(10~90%): " + f"{_f(ml['cate_quantiles']['p10'])} ~ {_f(ml['cate_quantiles']['p90'])}

    " + f"
    {rows}
    정책 전 수준단위 수평균 효과
    " + ) + else: + ml_html = f"

    {e(ml.get('message', '돌리지 않음'))}

    " + warn = f"

    {e(dw['warning'])}

    " if dw.get("warning") else "" + return f"""

    두 번째 의견 · PyWhy · CausalML

    +

    같은 질문을 인과추론 오픈소스 라이브러리로 다시 물었어요. 판정은 바꾸지 않고, 기본 추정과 어긋나는지만 봅니다.

    +

    DoWhy (PyWhy) {same_b}

    +

    인과 그래프: 공통 원인 → 정책, 공통 원인 → 결과, 정책 → 결과. 뒷문 기준으로 보정한 공통 원인: {e(adj)}

    +

    단위별 정책 전후 변화로 추정 {_f(dw.get("estimate"))} {e(unit)}{e(ci_txt)} · 2×2 이중차분 {_f(r.get("did_2x2"))} · 기본 추정 {_f(r.get("baseline_estimate"))}

    +
      {refs}
    {warn}
    +

    CausalML · 효과가 곳마다 달랐나

    {ml_html}
    +

    처치 {r["units"]["treated"]}곳 · 비교 {r["units"]["control"]}곳 · 만든 명령 python -m core.causal cases/{e(a["case"])} · pywhy_check.json

    """ + + def load_answers() -> list[dict]: from projects import load_registry from quality import prereg @@ -381,7 +444,12 @@ def load_answers() -> list[dict]: )[:10], "page": f"answers/{case.name}.html", "reproduced_by": list(meta.get("reproduced_by") or []), + "reviewed_by": list(meta.get("reviewed_by") or []), + "claims": [ + c for c in meta.get("claims") or [] if isinstance(c, dict) and c.get("text") + ], "prereg": prereg(case), + "pywhy": _read_json(case / "pywhy_check.json"), **read_discussion(case), } ) @@ -569,6 +637,8 @@ def card(e, a: dict, topics_by_id: dict, up: str = "") -> str: tags.append('시뮬레이션 데이터 결과') if a["mentor"]: tags.append('멘토 예시') + if a.get("reviewed_by"): + tags.append('검토됨') if a.get("reproduced_by"): tags.append('교차 재현됨') if (a.get("prereg") or {}).get("level") == "go": @@ -634,7 +704,117 @@ def trust_block(e, a: dict) -> str:

    교차 재현을 하셨나요? 재현 기록 남기기

    """ -def _usage(e, a: dict) -> str: +def primary_range(a: dict) -> dict | None: + """주 지표의 추정치·95% 범위 (로그 지표는 % 로). 문장 검증·검색 패널이 쓴다.""" + r = next( + (x for x in a["results"] if x.get("est") is not None and x.get("lo") is not None), None + ) + if not r: + return None + col, unit = r.get("col") or "", r.get("unit") + pct = interpret.is_log(col, unit) + + def tx(v): + return round((math.exp(v) - 1) * 100 if pct else v, 4) + + return { + "name": r.get("name") or col, + "est": tx(r["est"]), + "lo": tx(r["lo"]), + "hi": tx(r["hi"]), + "unit": "%" if pct else (unit or ""), + } + + +def forest_svg(e, answers: list[dict], up: str = "") -> str: + """한 주제의 결과를 한 축(%)에: 효과를 합치지 않고(설계가 다름) 범위만 나란히 놓는다. + 판단 불가는 진단용이라 그리지 않는다.""" + rows = [] + skipped = [] + for a in answers: + if a.get("execution_kind") == "descriptive_only" or a["verdict"] == "not_identified": + skipped.append(a) + continue + pr = primary_range(a) + if not pr or pr["unit"] != "%": + skipped.append(a) + continue + rows.append((a, pr)) + if len(rows) < 2: + return "" + lo = min(min(pr["lo"], 0) for _, pr in rows) + hi = max(max(pr["hi"], 0) for _, pr in rows) + span = (hi - lo) or 1 + lo, hi = lo - span * 0.06, hi + span * 0.06 + W, L, R, RH, TOP = 720, 270, 24, 40, 26 + x = lambda v: L + (v - lo) / (hi - lo) * (W - L - R) # noqa: E731 + step = 5 if span <= 40 else 10 if span <= 100 else 25 + ticks = [t for t in range(int(lo // step * step), int(hi) + step, step) if lo <= t <= hi] + H = TOP + RH * len(rows) + 8 + out = [ + f"" + ] + for t in ticks: + out.append( + f"" + f"{f'{t:+d}%' if t else '0'}" + ) + out.append(f"") + for i, (a, pr) in enumerate(rows): + y = TOP + RH * i + RH / 2 + cls = {"identified": "go", "conditional": "warn"}.get(a["verdict"], "stop") + name = a["title"] if len(a["title"]) <= 26 else a["title"][:25] + "…" + label = f"{a['title']} — {pr['name']} {pr['est']:+.1f}% (95% 범위 {pr['lo']:+.1f}% ~ {pr['hi']:+.1f}%)" + out.append( + f"{e(label)}" + f"{e(name)}" + f"" + f"" + ) + out.append("") + note = ( + f"

    판단 불가·관측 통계·단위가 다른 결과 {len(skipped)}개는 함께 그리지 않았어요.

    " + if skipped + else "" + ) + return ( + "

    결과를 한 축에 놓고 보기

    " + "

    각 줄은 결과 하나의 주 지표 95% 범위(점은 추정치)예요. 설계·지역·기간이 달라 숫자를 합치지 않고 나란히만 놓았어요. " + "모든 막대가 0을 지나면 '이 주제에서 큰 효과는 아직 확인되지 않았다'까지만 말할 수 있어요.

    " + + "".join(out) + + note + + "
    " + ) + + +def takeaway(a: dict) -> dict | None: + """판정 바로 옆에 둘 한 줄: '모른다'만 남기지 않고 그래도 말할 수 있는 것을 앞에 둔다.""" + if a.get("execution_kind") == "descriptive_only": + return { + "head": "말할 수 있는 것", + "text": "연도별 관측값은 지역·연도·단위와 함께 인용할 수 있어요. 정책 효과는 추정하지 않았어요.", + } + v = a["verdict"] + if v == "conditional": + r = next((r for r in a["results"] if (r.get("said") or {}).get("rule_out")), None) + if r: + return {"head": "그래도 말할 수 있는 것", "text": r["said"]["rule_out"]} + return None + if v == "not_identified": + why = ", ".join(dict.fromkeys(w for r in a["results"] for w in r.get("why") or [])) + return {"head": "판단할 수 없는 이유", "text": why or "설계 조건을 채우지 못했어요"} + if v == "identified": + p = next(iter(a["results"]), None) + if p: + return { + "head": "말할 수 있는 것", + "text": f"{p['name']} {p['effect']} (95% 범위 {p['range']})", + } + return None + + +def usage_rules(a: dict) -> tuple[list[str], list[str]]: + """이렇게 쓰세요 / 이렇게 쓰면 안 됩니다 — 결과 페이지와 문장 검증이 같은 규칙을 쓴다.""" v = a["verdict"] p = next(iter(a["results"]), None) eff = "" @@ -672,6 +852,13 @@ def _usage(e, a: dict) -> str: ) do = [f'"이 설계로는 효과를 판단할 수 없다. 이유: {reasons}."'] dont = ["표의 숫자·p값 인용 — 진단용입니다", "'효과가 있다' 또는 '없다'"] + return do, dont + + +def _usage(e, a: dict) -> str: + v = a["verdict"] + descriptive = a.get("execution_kind") == "descriptive_only" + do, dont = usage_rules(a) cite = ( f"{a['title']} — 판정: {DESCRIPTIVE_LABEL if descriptive else VERDICT.get(v, (v,))[0]}. 출처: 정책 효과 분석 플랫폼" f"(가짜연구소 인과추론팀 오픈소스), {a['finished'] or '날짜 미상'} 실행, {SITE}/{a['page']} · 공식 평가 아님" @@ -739,7 +926,7 @@ def _descriptive_page(e, a: dict, topics_by_id: dict) -> str:

    {e(a["title"])}

    {e(a["question"])}

    {DESCRIPTIVE_LABEL} -

    연도별 관측값을 정리했습니다. 인과효과 추정은 실행하지 않아 정책 효과를 판단할 수 없습니다.

    {author}
    +

    연도별 관측값을 정리했습니다. 인과효과 추정은 실행하지 않아 정책 효과를 판단할 수 없습니다.

    {takeaway_html(e, a)}{author} {_usage(e, a)}

    관측 통계

    {changed}
    {figs}

    연도별 관측값

    {header}{rows}
    @@ -757,6 +944,99 @@ def _descriptive_page(e, a: dict, topics_by_id: dict) -> str: """ +CLAIM_RATINGS = {"결과와 맞음": 4, "범위 안": 3, "결과를 넘어섬": 2, "결과와 다름": 1} + + +def jsonld(a: dict) -> str: + """검색엔진용 구조화 데이터. 결과 표(CSV)는 Dataset 으로, 사람이 적은 claims 가 있을 때만 ClaimReview. + + ClaimReview 는 '누군가 실제로 한 주장'을 검토했을 때만 쓴다(질문을 주장처럼 꾸미지 않는다). + """ + org = { + "@type": "Organization", + "name": "가짜연구소 인과추론팀 (정책 효과 분석 플랫폼)", + "url": SITE, + } + lab = ( + DESCRIPTIVE_LABEL + if a.get("execution_kind") == "descriptive_only" + else VERDICT.get(a["verdict"], (a["verdict"] or "-",))[0] + ) + csv_name = ( + f"{a['case']}-descriptive.csv" + if a.get("execution_kind") == "descriptive_only" + else f"{a['case']}.csv" + ) + items = [ + { + "@context": "https://schema.org", + "@type": "Dataset", + "name": a["title"], + "description": f"{a['question'] or a['title']} — 판정: {lab}. 공공데이터로 정책을 받은 곳과 안 받은 곳을 비교한 결과표. 공식 평가가 아닙니다.", + "url": f"{SITE}/{a['page']}", + "creator": org, + "isAccessibleForFree": True, + "inLanguage": "ko", + "keywords": ["정책 효과", "공공데이터", "인과추론", lab], + "variableMeasured": [r["name"] for r in a["results"]][:6] or None, + "dateModified": a["finished"] or None, + "distribution": [ + { + "@type": "DataDownload", + "encodingFormat": "text/csv", + "contentUrl": f"{SITE}/answers/{csv_name}", + } + ], + } + ] + for c in a.get("claims") or []: + rating = c.get("rating") + if rating not in CLAIM_RATINGS: + continue + items.append( + { + "@context": "https://schema.org", + "@type": "ClaimReview", + "url": f"{SITE}/{a['page']}", + "claimReviewed": c["text"], + "author": org, + "datePublished": a["finished"] or None, + "itemReviewed": { + "@type": "Claim", + "author": {"@type": "Organization", "name": c.get("by", "")}, + "datePublished": c.get("date"), + "appearance": {"@type": "CreativeWork", "url": c.get("url")} + if c.get("url") + else None, + }, + "reviewRating": { + "@type": "Rating", + "ratingValue": CLAIM_RATINGS[rating], + "bestRating": 4, + "worstRating": 1, + "alternateName": rating, + }, + } + ) + + def clean(x): + if isinstance(x, dict): + return {k: clean(v) for k, v in x.items() if v not in (None, "", [])} + if isinstance(x, list): + return [clean(v) for v in x] + return x + + body = json.dumps(clean(items if len(items) > 1 else items[0]), ensure_ascii=False) + return '" + + +def takeaway_html(e, a: dict) -> str: + t = takeaway(a) + if not t: + return "" + return f'
    {e(t["head"])}

    {e(t["text"])}

    ' + + def page_body(e, a: dict, topics_by_id: dict, datasets_by_url: dict) -> str: if a.get("execution_kind") == "descriptive_only": return _descriptive_page(e, a, topics_by_id) @@ -831,6 +1111,7 @@ def page_body(e, a: dict, topics_by_id: dict, datasets_by_url: dict) -> str:
    {e(lab)}

    {e(VERDICT_PLAIN.get(a["verdict"], ""))}

    +{takeaway_html(e, a)} {author}
    파이프라인 자동 요약 보기

    {e(auto_summary(a))}

    {_usage(e, a)} @@ -841,6 +1122,7 @@ def page_body(e, a: dict, topics_by_id: dict, datasets_by_url: dict) -> str:
    {figs}
    {("

    작성자가 적은 한계

    " + cautions) if cautions else ""}
    {trust_block(e, a)} +{pywhy_block(e, a)}

    쓴 공공데이터

    {src_html}

    원자료는 레포에 올리지 않습니다. 아래 명령이 공개 창구에서 직접 받아 같은 결과를 만듭니다. 각 데이터의 단위·받는 법·키 필요 여부는 데이터 지도에 있습니다.

    diff --git a/site/build.py b/site/build.py index 37cf7d8a..16ccd4f8 100644 --- a/site/build.py +++ b/site/build.py @@ -122,6 +122,7 @@ def page( desc: str | None = None, path: str | None = None, image: str | None = None, + head: str = "", ) -> str: """공통 틀. path(사이트 안 경로)를 주면 공유 미리보기(Open Graph)용 주소·그림을 붙인다.""" up = "../" * depth @@ -149,7 +150,7 @@ def page( {e(title)} {og} - +{head} @@ -404,7 +405,7 @@ def rank_topics(topics, issues, trends: dict, today: str | None = None): ( t, tt.get(t.id, {}).get("questions", 0), - tt.get(t.id, {}).get("search", 0.0), + tt.get(t.id, {}).get("search", 0.0) + tt.get(t.id, {}).get("news", 0) / 1000, latest_event(t, issues, today), ) for t in topics @@ -412,10 +413,12 @@ def rank_topics(topics, issues, trends: dict, today: str | None = None): rows.sort(key=lambda r: (r[1], r[2], r[3]), reverse=True) srcs = set(trends.get("sources", [])) has_q = "site_questions" in srcs and any(r[1] for r in rows) - has_s = "naver_datalab" in srcs and any(r[2] for r in rows) + has_s = bool({"naver_datalab", "news"} & srcs) and any(r[2] for r in rows) if has_q or has_s: - parts = (["최근 30일 사이트 질문 수"] if has_q else []) + ( - ["네이버 검색 관심도"] if has_s else [] + parts = ( + (["최근 30일 사이트 질문 수"] if has_q else []) + + (["네이버 검색 관심도"] if "naver_datalab" in srcs else []) + + (["최근 7일 뉴스 언급"] if "news" in srcs else []) ) basis = f"{' · '.join(parts)} 기준 · {e(trends.get('updated', ''))} 갱신" else: @@ -436,6 +439,11 @@ def topic_rows(topics, issues, answers, trends: dict, datasets=(), lineages=()) side.append('지금 이슈') if has_q and q: side.append(f'질문 {q}') + nw = trends.get("topics", {}).get(t.id, {}) + if nw.get("news"): + side.append( + f'뉴스 {nw["news"]}' + ) if last: side.append(f'{last[:7].replace("-", ".")}') out.append((t, board.topic_stages(t, issues, datasets, lineages, answers), "".join(side))) @@ -451,7 +459,6 @@ def index_page(topics, policies, issues, datasets, projects=(), answers=(), line for x in HOME_EXAMPLES ) n_answers = sum(not a["mentor"] and not a["synthetic"] for a in answers) - n_people = len({p["owner"] for p in projects if not p["mentor"]}) topic_html, basis = topic_rows(topics, issues, answers, load_trends(), datasets, lineages) tot = board.totals(issues, datasets, lineages, answers) flow = board.flow_strip( @@ -466,17 +473,6 @@ def index_page(topics, policies, issues, datasets, projects=(), answers=(), line }, board.ready_count(datasets), ) - issue_rows = "".join( - f'{e(i.effective)}' - f"{e(i.name)}" - f'{DESIGN_SHORT[i.design]}' - for i in issues[:4] - ) - ready_rows = "".join( - f'{e(d.provider[:20])}{e(d.name)}' - f'{e(d.time)}{e(d.approval)}' - for d in [d for d in datasets if d.approval in board.READY and "outcome" in d.roles][:4] - ) body = f"""
    @@ -515,33 +511,14 @@ def index_page(topics, policies, issues, datasets, projects=(), answers=(), line
    -{proj.personas(e, n_answers, len(datasets))} - {proj.showcase(e, list(projects), list(answers), topics, proj.people(list(projects), lineages))} -

    이슈 보드

    +

    주제마다 이슈 → 공공데이터 → 계보 → 분석 → 대시보드가 어디까지 채워졌는지 보입니다. 칸의 숫자는 개수, 빈칸은 채울 곳입니다. {basis}

    {topic_html}
    - -
    -
    -

    논쟁 중인 정책을 어떤 비교로, 어떤 데이터로 볼 수 있는지 정리했습니다.

    -
    {issue_rows}
    -

    바로 받을 수 있는 데이터

    {len(datasets)}개 전체
    -

    정리한 공공데이터 {len(datasets)}개 중 {board.ready_count(datasets)}개는 키 발급 즉시 또는 키 없이 오늘 받을 수 있습니다. 데이터마다 단위·기간·받는 법·이용 조건을 적었습니다.

    -
    {ready_rows}
    -
    - -

    나는 몇 레벨 시민 데이터 과학자?

    -

    코딩을 몰라도 레벨 1부터 시작할 수 있어요. 한 칸씩 올라가 보세요.

    -
      -
    1. Lv.1궁금해하기대화창에 정책 하나 물어보기. 주제·데이터·조심할 점을 같이 정리해 드려요.
    2. -
    3. Lv.2읽고 가져가기결과 하나 열어 판정을 읽고, 인용문을 복사해 가기. 지금 {n_answers}개 있어요.
    4. -
    5. Lv.3데이터 만져 보기공공데이터 {len(datasets)}개 중 {board.ready_count(datasets)}개는 오늘 바로 받을 수 있어요. CSV로 같은 결과도 확인해 보기.
    6. -
    7. Lv.4같이 만들기우리 동네 정책으로 분석 제안하기. 이미 {n_people}명이 하고 있어요.
    8. -
    -

    이 사이트가 잘 쓰이고 있는지는 성과에서 매일 다시 세요.

    +{proj.personas(e, n_answers, len(datasets))} +

    이 사이트가 잘 쓰이고 있는지는 성과에서 매일 다시 셉니다.

    """ return page("정책 효과 분석 플랫폼", body, "index.html", path="index.html") @@ -874,6 +851,34 @@ def legal_block(t) -> str: ) +FEAS_MARK = {"ok": ("✓", "go"), "warn": ("!", "warn"), "miss": ("✕", "stop")} + + +def feasibility_card(t, datasets, issues, n_results: int) -> str: + """이 주제, 지금 있는 데이터로 분석할 수 있나 — 가설 한 줄 + 점검 6개 + PyWhy 식 인과 그래프.""" + from core.causal.feasibility import topic_feasibility + + f = topic_feasibility(t, datasets, issues, n_results) + items = "".join( + f"
  • " + f"{e(c['label'])}{e(c['detail'])}
  • " + for c in f["checks"] + ) + covs = [n.split(": ", 1)[1] for n in f["graph"]["nodes"] if n.startswith("공통 원인: ")] + cov_txt = ( + ", ".join(covs[:3]) + (" 등" if len(covs) > 3 else "") + if covs + else "없음 — 정책 전 추세 가정에 기댐" + ) + return f"""
    +
    이 주제, 지금 있는 데이터로 분석할 수 있나 +{e(f["label"])}
    +

    가설 {e(f["hypothesis"]["sentence"])}

    +
      {items}
    +

    인과 그래프(PyWhy 방식) 정책 → 결과 · 시간 추세 → 결과 · 공통 원인 → 정책·결과. 공통 원인 후보: {e(cov_txt)}. +분석용 표가 생기면 python -m core.causal cases/<케이스> 로 DoWhy 반박 검정과 CausalML 단위별 효과를 붙일 수 있어요.

    """ + + def topic_page(t, policies, issues, datasets, projects=(), answers=(), lineages=()) -> str: """이슈 보드: 이슈 → 공공데이터 → 계보 → 분석 → 대시보드 순서로 한 장에.""" import answers as ans @@ -893,6 +898,7 @@ def topic_page(t, policies, issues, datasets, projects=(), answers=(), lineages= f"
    " f"

    {e(t.name)}

    {e(t.question)}

    ", board.rail(e, st), + feasibility_card(t, datasets, issues, len(mine)), ] # 1. 이슈 body.append(f"
    {board.stage_head(e, 'issue')}") @@ -986,6 +992,7 @@ def topic_page(t, policies, issues, datasets, projects=(), answers=(), lineages= # 4. 분석 body.append(f"
    {board.stage_head(e, 'analysis')}") if mine: + body.append(ans.forest_svg(e, mine, up="../")) body.append( f'
    {"".join(ans.card(e, a, tb, up="../") for a in mine)}
    ' ) @@ -1059,6 +1066,21 @@ def topic_page(t, policies, issues, datasets, projects=(), answers=(), lineages= # ─── 빌드 ──────────────────────────────────────────────────────────────────── +def hot_topics(topics, answers, n: int = 5) -> list[dict]: + """최근 7일 뉴스에 많이 나온 주제 (refresh_trends 의 news 신호가 있을 때만).""" + tt = load_trends().get("topics", {}) + rows = [ + { + "name": t.name, + "id": t.id, + "news": tt.get(t.id, {}).get("news", 0), + "results": sum(a["topic"] == t.id for a in answers), + } + for t in topics + ] + return sorted([r for r in rows if r["news"]], key=lambda r: -r["news"])[:n] + + def answer_lineage(a: dict, lin, datasets) -> str: """답 페이지 아래: 이 숫자는 어디서 왔나 — 이슈·정책 → 데이터 → 가공 → 지표 → 이 분석.""" import board @@ -1158,6 +1180,7 @@ def main() -> None: desc=ans.share_text(a), path=a["page"], image=f"cases/{a['case']}/{fig}" if fig else None, + head=ans.jsonld(a), ), encoding="utf-8", ) @@ -1182,7 +1205,9 @@ def main() -> None: (OUT / "search.html").write_text( page( "검색 · 그 정책, 진짜 효과였나? · 정책 효과 분석 플랫폼", - search.body(e, len(items), sum(i["t"] == "result" for i in items)), + search.body( + e, len(items), sum(i["t"] == "result" for i in items), hot_topics(topics, answers) + ), "search.html", desc="정책 이름·지역·키워드로 분석 결과와 판정, 공공데이터, 데이터 계보를 한 번에 찾기", path="search.html", diff --git a/site/impact.py b/site/impact.py index d76b4378..7c2892a8 100644 --- a/site/impact.py +++ b/site/impact.py @@ -30,6 +30,8 @@ "search": "결과 검색", "home-search": "홈 검색창 사용", "search-propose": "검색 후 분석 요청", + "claim-check": "뉴스 문장 검증", + "claim-record": "문장 검증을 검토 기록으로 남기기", "reproduce": "재현 기록 열기", "flow-stage": "홈 흐름 띠의 단계 누름", } diff --git a/site/projects.py b/site/projects.py index 152f0879..6c9a102c 100644 --- a/site/projects.py +++ b/site/projects.py @@ -264,6 +264,31 @@ def lineage_list(e, lineages, topics_by_id) -> str: return "".join(items) +def review_pairs(e, mentee: list[dict]) -> str: + """검토 짝 제안: 결과가 있는데 아직 검토받지 않은 분석마다, 결과가 있는 다른 참여자 한 명을 돌아가며 붙인다.""" + reg = load_registry() + done = [p for p in mentee if p.get("has_flow")] + owners = sorted({p["owner"] for p in done}) + if len(owners) < 2: + return "" + rows = [] + for i, p in enumerate(sorted(done, key=lambda x: x["case"])): + if reg.get(p["case"], {}).get("reviewed_by"): + continue + others = [o for o in owners if o != p["owner"]] + who = others[i % len(others)] + rows.append( + f"{e(p['title'])}
    @{e(p['owner'])}
    " + f"@{e(who)}" + ) + if not rows: + return "" + return f"""

    검토 짝

    +

    결과가 있는데 아직 검토받지 않은 분석 {len(rows)}개입니다. 짝은 결과를 낸 다른 참여자 중에서 돌아가며 정했어요(바꿔도 됩니다). +검토 체크리스트 여덟 항목을 확인하면 catalog/projects.yaml에 reviewed_by를 더해 '검토됨' 배지를 붙입니다.

    +
    {"".join(rows)}
    분석제안 검토자
    """ + + def projects_body(e, projects, lineages, topics) -> str: tb = {t.id: t for t in topics} act = load_activity() @@ -307,6 +332,7 @@ def projects_body(e, projects, lineages, topics) -> str:
    {cards or "

    아직 없습니다.

    "}
    +{review_pairs(e, mentee)}

    데이터 계보 (트랙 A)

    이슈 → 정책 → 데이터 → 가공 → 지표의 길입니다. 빈칸은 아직 없는 데이터, 채울 곳입니다.

    {lin_cards or "

    아직 없습니다.

    "}
    @@ -397,53 +423,41 @@ def people(projects, lineages=(), activity: dict | None = None) -> list[str]: def showcase(e, projects, answers, topics, crew: list[str], limit: int = 6) -> str: - """홈 하이라이트: 그림이 있는 참여자 프로젝트 카드 + 함께 만든 사람들.""" + """홈: 최근 확인한 판정 — 같은 모양의 줄(판정 · 제목 · 그래도 말할 수 있는 것 · 95% 범위 그림).""" + from answers import DESCRIPTIVE_LABEL, VERDICT, card_line, range_glyph, takeaway + tb = {t.id: t for t in topics} - ans = {a["case"]: a for a in answers} - mentee = [p for p in projects if not p["mentor"]] - mentee.sort(key=lambda p: (p["case"] not in ans, not p["figures"], -p["stage"], p["title"])) - cards = [] - for p in mentee[:limit]: - t = tb.get(p["topic"]) - a = ans.get(p["case"]) - fig = next( - (f for f in THUMB_PREF if f in p["figures"]), p["figures"][0] if p["figures"] else None - ) - thumb = ( - f'' - if fig - else f'' + real = [a for a in answers if not a["mentor"] and not a["synthetic"]] + real.sort(key=lambda a: a.get("finished") or "", reverse=True) + rows = [] + for a in real[:limit]: + t = tb.get(a["topic"]) + lab, cls = ( + (DESCRIPTIVE_LABEL, "info") + if a.get("execution_kind") == "descriptive_only" + else VERDICT.get(a["verdict"], ("-", "warn")) ) - if a: - from answers import DESCRIPTIVE_LABEL, VERDICT - - lab, cls = ( - (DESCRIPTIVE_LABEL, "info") - if a.get("execution_kind") == "descriptive_only" - else VERDICT.get(a["verdict"], ("-", "warn")) - ) - state = f'{e(lab)}' - href = f"answers/{p['case']}.html" - else: - st = STAGE_KO[p["stage"]] if p["stage"] >= 0 else "준비" - state = f'{e(st)} 단계 진행 중' - href = f"{REPO}/tree/main/cases/{p['case']}" - cards.append( - f'{thumb}' - f'{avatar(e, p["owner"])}@{e(p["owner"])}' - f"{e(p['title'])}" - f'{state}{e(t.name) if t else "주제 미지정"}' + tk = takeaway(a) + line = f"{tk['head']}: {tk['text']}" if tk else card_line(a) + rows.append( + f'' + f'{e(lab)}' + f'{avatar(e, a["owner"])}@{e(a["owner"])}' + f'{e(t.name) if t else "주제 미지정"}' + f'{e(a["title"])}{e(line)}' + f'{range_glyph(e, a)}' ) + mentee = [p for p in projects if not p["mentor"]] faces = "".join( f'' f'@{e(n)}' for n in crew ) - return f"""

    시민 데이터 과학자들이 만든 것

    -프로젝트 {len(mentee)}개 모두
    -

    현업 개발자·분석가들이 각자 궁금했던 정책을 골라 공공데이터로 직접 비교했어요. 그림을 누르면 결과와 인용문, 따라 하는 법이 나와요.

    -
    {"".join(cards)}
    -
    {faces}

    함께 만든 사람 {len(crew)}명. 여러분 자리도 비워 뒀어요 → 참여하기

    """ + return f"""

    최근 확인한 판정

    +결과 {len(real)}개 모두
    +

    참여자가 공공데이터로 '받은 곳 vs 안 받은 곳'을 비교한 결과예요. 판정이 '모른다'여도 말할 수 있는 범위를 함께 적었어요.

    +
    {"".join(rows)}
    +
    {faces}

    시민 데이터 과학자 {len(crew)}명이 프로젝트 {len(mentee)}개를 함께 만들고 있어요. 참여하기

    """ def personas(e, n_answers: int, n_data: int) -> str: @@ -452,8 +466,8 @@ def personas(e, n_answers: int, n_data: int) -> str: ( "궁금한 시민", "뉴스에서 본 그 정책, 효과 있었는지 쉬운 말로 알고 싶어요", - "#ask", - "대화창에 물어보기", + "search.html", + "정책 이름으로 찾아보기", ), ( "기자 · 공무원 · 연구자", diff --git a/site/quality.py b/site/quality.py index 3c1f541e..d0beb237 100644 --- a/site/quality.py +++ b/site/quality.py @@ -8,6 +8,7 @@ 얕은 clone(Actions 기본)이면 기록이 없으므로 None (화면에서 빠진다). 2. 교차 재현: catalog/projects.yaml 의 reproduced_by (다른 참여자가 make flow 로 같은 판정을 얻었음). 3. 작성자 해석: discussion.md 에 '결과를 한 문장으로'가 있는가. +5. 검토: catalog/projects.yaml 의 reviewed_by (작성자 외의 사람이 검토 체크리스트로 확인했음). 4. 다음 할 일: 위 항목과 진행 단계로 참여자에게 보여 줄 할 일 목록. """ @@ -103,6 +104,24 @@ def checks(a: dict) -> list[tuple[str, str, str]]: out.append( ("info", "사전 등록 · 기록 확인 안 됨", "이 빌드에서는 git 기록을 읽지 못했습니다.") ) + rev = a.get("reviewed_by") or [] + if rev: + who = ", ".join(f"@{x}" for x in rev) + out.append( + ( + "go", + "검토 · 통과", + f"{who} 이(가) 검토 체크리스트(docs/ops/review-checklist.md)로 확인했습니다.", + ) + ) + else: + out.append( + ( + "warn", + "검토 · 아직 없음", + "작성자 외의 사람이 검토 체크리스트로 확인하지 않았습니다.", + ) + ) rep = a.get("reproduced_by") or [] if rep: who = ", ".join(f"@{x}" for x in rep) @@ -150,6 +169,8 @@ def next_steps(p: dict, a: dict | None, registered: bool) -> list[str]: if a is not None: if st[3] and not a.get("has_one_line"): todo.append("discussion.md 에 '## 결과를 한 문장으로' 추가") + if not a.get("reviewed_by"): + todo.append("검토 요청 (docs/ops/review-checklist.md)") if not a.get("reproduced_by"): todo.append("다른 참여자에게 교차 재현 요청") pr = a.get("prereg") diff --git a/site/search.js b/site/search.js index cd97e080..d610002a 100644 --- a/site/search.js +++ b/site/search.js @@ -59,6 +59,61 @@ (xs.length > 8 ? `
    ${xs.length - 8}개 더 보기
    ${xs.slice(8).map(draw).join("")}
    ` : "") + `
    `; } + // ─── 문장 검증: 뉴스 문장이 결과가 말할 수 있는 범위를 넘는지 (키워드 규칙) ─────────── + const NULL_RE = /효과\s*(가|는|도)?\s*없|변화\s*(가|는|도)?\s*없|아무\s*변화|그대로였|실패|소용\s*없|안\s*먹혔|못\s*했|못했|헛수고/; + const UP_RE = /늘었|늘어|증가|올랐|오르|상승|개선|좋아|활성|살아났|많아/; + const DOWN_RE = /줄었|줄어|감소|떨어|내렸|하락|잡혔|잡았|억제|낮아|안정|적어/; + const EFFECT_RE = /효과|덕분|때문|성공|먹혔|통했|영향/; + const PCT_RE = /([+-]?\d+(?:\.\d+)?)\s*%/; + function looksLikeClaim(q) { + const t = q.trim(); + return t.length >= 12 && /\s/.test(t) && (NULL_RE.test(t) || UP_RE.test(t) || DOWN_RE.test(t) || EFFECT_RE.test(t) || PCT_RE.test(t)); + } + const RANK = { ok: 0, inside: 1, beyond: 2, conflict: 3 }; + const MARK = { ok: ["뒷받침", "go"], inside: ["범위 안", "info"], beyond: ["결과를 넘어섬", "warn"], conflict: ["결과와 다름", "stop"] }; + function checkClaim(q, r) { + const parts = [], v = r.v, pr = r.pr; + const isNull = NULL_RE.test(q), up = UP_RE.test(q), down = DOWN_RE.test(q) && !up, dir = up ? 1 : down ? -1 : 0; + const effect = !isNull && (dir !== 0 || EFFECT_RE.test(q)); + if (isNull) { + if (v === "identified") parts.push(["conflict", "'효과가 없다'고 했지만, 이 분석은 효과 근거가 있다고 판정했어요."]); + else if (v === "conditional") parts.push(["beyond", "판별하지 못한 것과 효과가 없는 것은 달라요. 이 자료로는 있다·없다 모두 단정할 수 없어요."]); + else parts.push(["beyond", "이 분석은 효과를 판단하지 않았어요(판단 불가·관측 통계). '없다'고 말할 근거도 없어요."]); + } else if (effect) { + if (v === "identified" && pr) { + const sign = Math.sign(pr.est); + if (dir && dir !== sign) parts.push(["conflict", `방향이 반대예요. 분석의 추정치는 ${pr.est > 0 ? "증가" : "감소"} 쪽이에요.`]); + else parts.push(["ok", "효과가 있었다는 말은 이 분석의 판정과 맞아요. 같은 지역·기간·지표에 한정해서 쓰세요."]); + } else if (v === "conditional") parts.push(["beyond", "효과가 '있었다'고 말할 근거는 부족해요. 이 자료로는 효과가 있었는지 판별하지 못했어요."]); + else if (v === "descriptive") parts.push(["beyond", "관측값의 변화는 인용할 수 있지만, 정책 '때문'이라고 할 근거는 없어요(효과 미추정)."]); + else parts.push(["beyond", "이 설계로는 효과를 판단할 수 없었어요. 원인이라고 말할 근거가 없어요."]); + } + const m = q.match(PCT_RE); + if (m) { + let n = parseFloat(m[1]); + if (!/^[+-]/.test(m[1]) && down) n = -n; + if (!pr || pr.unit !== "%") parts.push(["beyond", v === "not_identified" ? "판단 불가 결과의 숫자는 진단용이라 비교하지 않아요." : "이 분석의 주 지표는 %로 비교할 수 없어요."]); + else if (n < pr.lo || n > pr.hi) parts.push(["conflict", `${n > 0 ? "+" : ""}${n}%는 이 자료의 95% 범위(${pr.lo.toFixed(1)}% ~ ${pr.hi.toFixed(1)}%) 밖이라 자료와 맞지 않아요.`]); + else parts.push(["inside", `${n > 0 ? "+" : ""}${n}%는 95% 범위(${pr.lo.toFixed(1)}% ~ ${pr.hi.toFixed(1)}%) 안이에요. ` + (v === "identified" ? "자료와 맞는 크기예요." : "자료와 어긋나지는 않지만, 그 크기로 판별된 것은 아니에요.")]); + } + if (!parts.length) parts.push(["inside", "문장에서 효과·방향·크기 주장을 찾지 못했어요. 아래 결과에서 직접 확인해 보세요."]); + const worst = parts.reduce((a, b) => (RANK[b[0]] > RANK[a[0]] ? b : a))[0]; + return { worst, parts }; + } + function renderClaim(q, results) { + const box = $("#claim"); + if (!looksLikeClaim(q) || !results.length) { box.hidden = true; return; } + const r = results[0], c = checkClaim(q, r), [lab, cls] = MARK[c.worst]; + box.className = "c-panel c-" + cls; + box.innerHTML = `
    이 문장, 분석 결과로 뒷받침되나요?${lab}
    ` + + `
    ${esc(q)}
    ` + + `` + + (r.rules && r.rules[0] && r.rules[0][0] ? `
    이렇게 쓰면 결과 안에서 말할 수 있어요

    ${esc(r.rules[0][0])}

    ` : "") + + `

    실제 기사·발표의 주장이면 검토 기록으로 남기기

    ` + + `

    비교한 분석: ${esc(r.title)}. 키워드 규칙으로 읽은 결과라, 문장의 지역·기간·지표가 이 분석과 같은지는 직접 확인하세요. 법률 자문이나 공식 팩트체크가 아니에요.

    `; + box.hidden = false; + if (window.track) window.track("claim-check"); + } function counts(hits) { document.querySelectorAll(".sf").forEach((b) => { const n = b.dataset.t ? hits.filter((it) => it.t === b.dataset.t).length : hits.length; @@ -69,29 +124,39 @@ function render(q) { const qn = norm(q), tks = tokens(q); idle.hidden = !!qn; - if (!qn) { res.innerHTML = ""; none.hidden = true; verdict.hidden = true; counts([]); return 0; } + if (!qn) { res.innerHTML = ""; none.hidden = true; verdict.hidden = true; $("#claim").hidden = true; counts([]); return 0; } const hits = items.map((it) => [it, score(it, tks, qn)]).filter(([, s]) => s > 0).sort((a, b) => b[1] - a[1]).map(([it]) => it); counts(hits); const shown = kind ? hits.filter((it) => it.t === kind) : hits; res.innerHTML = ORDER.map((t) => [t, shown.filter((it) => it.t === t)]).filter(([, xs]) => xs.length).map(([t, xs]) => group(t, xs)).join(""); const results = hits.filter((it) => it.t === "result"); + renderClaim(q, results); const propose = `${REPO}/issues/new?template=case-proposal.yml&title=${encodeURIComponent("[작업] " + q.trim().slice(0, 60))}`; $("#snone-propose").href = propose; if (results.length) { const top = results[0]; verdict.className = "v-panel v-" + top.cls; - verdict.innerHTML = `
    가장 가까운 분석의 판정${esc(top.badge)}
    ` + + verdict.innerHTML = `
    가장 가까운 분석의 판정${esc(top.badge)}` + + (top.rev ? `검토됨` : `검토 전`) + `
    ` + `

    ${esc(top.title)}

    ${esc(top.sub)}

    ` + `
    ${top.g || ""}
    ` + + (top.ro ? `
    ${esc(top.ro.head)}

    ${esc(top.ro.text)}

    ` : "") + `
    인용해도 되는 문장숫자가 나온 길` + `직접 돌려 보기` + (results.length > 1 ? `비슷한 분석 ${results.length - 1}개 더` : "") + `
    ` + `

    판정은 '이 데이터와 이 비교로는'이라는 조건이 붙은 답이에요.

    `; verdict.hidden = false; } else if (hits.length) { + const tp = hits.find((it) => it.t === "topic" && it.feas); + const MK = { ok: ["✓", "go"], warn: ["!", "warn"], miss: ["✕", "stop"] }; + const feas = tp ? `

    지금 있는 데이터로 분석할 수 있나 · ${esc(tp.title)}

    ` + + `

    ${esc(tp.feas.label)}

    ` + + `

    ${esc(tp.feas.hyp)}

    ` : ""; verdict.className = "v-panel v-none"; verdict.innerHTML = `
    판정아직 분석 없음
    ` + - `

    이 정책의 효과를 잰 분석은 아직 없어요. 아래 이슈·데이터·계보로 시작할 수 있어요.

    ` + + `

    이 정책의 효과를 잰 분석은 아직 없어요. 아래 이슈·데이터·계보로 시작할 수 있어요.

    ` + feas + `
    이 정책 분석 요청하기
    `; verdict.hidden = false; } else verdict.hidden = true; diff --git a/site/search.py b/site/search.py index a2d656a1..8579fede 100644 --- a/site/search.py +++ b/site/search.py @@ -38,7 +38,15 @@ def index(topics, issues, datasets, answers, projects, lineages) -> list[dict]: """검색 항목 목록. kw 는 찾는 데만 쓰는 글(화면에 안 보임).""" from html import escape - from answers import DESCRIPTIVE_LABEL, VERDICT, card_line, range_glyph + from answers import ( + DESCRIPTIVE_LABEL, + VERDICT, + card_line, + primary_range, + range_glyph, + takeaway, + usage_rules, + ) from core.discovery.links import dataset_users, is_auto @@ -60,6 +68,12 @@ def index(topics, issues, datasets, answers, projects, lineages) -> list[dict]: "cls": cls, "who": "멘토 예시" if a["mentor"] else f"@{a['owner']}", "g": range_glyph(escape, a), + # 판정 패널 · 문장 검증용 + "v": "descriptive" if desc else a["verdict"], + "ro": takeaway(a), + "pr": None if desc or a["verdict"] == "not_identified" else primary_range(a), + "rules": usage_rules(a), + "rev": bool(a.get("reviewed_by")), "kw": _j(a["question"], tname.get(a["topic"]), a["owner"], a["case"]), } ) @@ -89,9 +103,18 @@ def index(topics, issues, datasets, answers, projects, lineages) -> list[dict]: "kw": _j(i.treatment, " ".join(i.outcomes), tname.get(i.topic)), } ) + from core.causal.feasibility import topic_feasibility + for t in topics: + f = topic_feasibility(t, datasets, issues, sum(a["topic"] == t.id for a in answers)) out.append( { + "feas": { + "label": f["label"], + "verdict": f["verdict"], + "hyp": f["hypothesis"]["sentence"], + "checks": [[c["status"], c["label"], c["detail"]] for c in f["checks"]], + }, "t": "topic", "title": t.name, "sub": getattr(t, "question", "") or "", @@ -150,6 +173,26 @@ def write(out_dir, items: list[dict]) -> None: ) +CLAIM_EXAMPLE = "토지거래허가구역 지정 뒤 옆 동네 집값이 20% 넘게 올랐다" + + +def hot_html(e, hot: list[dict]) -> str: + if not hot: + return "" + rows = "".join( + f'
  • {e(h["name"])}' + f'뉴스 {h["news"]}건 · ' + + ( + f"분석 결과 {h['results']}개" + if h["results"] + else "아직 분석 없음 — 다음 분석 후보" + ) + + "
  • " + for h in hot + ) + return f'

    이번 주 뉴스에 많이 나온 주제

      {rows}
    ' + + EXAMPLES = [ ("토허제 풍선효과", "토허제 뒤 옆 동네 집값은?"), ("기후동행카드", "기후동행카드로 지하철 더 탔나?"), @@ -160,7 +203,7 @@ def write(out_dir, items: list[dict]) -> None: ] -def body(e, n_items: int, n_results: int) -> str: +def body(e, n_items: int, n_results: int, hot: list[dict] | None = None) -> str: chips = "".join( f'{e(label)}' for q, label in EXAMPLES @@ -179,10 +222,13 @@ def body(e, n_items: int, n_results: int) -> str: -
    {chips}
    +
    {chips}
    +

    뉴스 문장을 통째로 붙여 넣어도 돼요. 그 문장이 분석 결과로 뒷받침되는지 봐 드려요. +예: "{e(CLAIM_EXAMPLE)}"

    {filters}
    +
    -

    지금 찾을 수 있는 것: 분석 결과 {n_results}개를 포함해 이슈·법령·계보·공공데이터 {n_items}개.

    +

    지금 찾을 수 있는 것: 분석 결과 {n_results}개를 포함해 이슈·법령·계보·공공데이터 {n_items}개.

    {hot_html(e, hot or [])}

    검색은 이 브라우저 안에서만 합니다. 이용 통계가 켜진 경우에만 숫자·이메일·주소를 지운 30자 이내 검색어의 횟수를 쿠키 없이 셉니다(GoatCounter, '추적 안 함'을 따름). 결과가 없던 검색어는 성과에 공개되어 다음 분석 주제의 후보가 됩니다.

    diff --git a/site/style.css b/site/style.css index 737f4b4a..97051371 100644 --- a/site/style.css +++ b/site/style.css @@ -519,7 +519,7 @@ html.js:not(.calm) .lin-svg .edges path { transition: stroke-dashoffset 1.2s eas .show .who .avatar { width: 22px; height: 22px } .show-meta { margin-top: auto; display: flex; gap: 8px; align-items: center; flex-wrap: wrap } .crew { margin-top: 18px; display: flex; align-items: center; gap: 14px; flex-wrap: wrap } -.faces { display: flex } +.faces { display: flex; flex-wrap: wrap; row-gap: 6px; max-width: 100% } .faces a { margin-left: -8px } .faces a:first-child { margin-left: 0 } .faces img { width: 40px; height: 40px; border-radius: 50%; border: 3px solid var(--paper); background: var(--sunk); display: block } .faces a:hover img { transform: translateY(-3px) } @@ -639,3 +639,77 @@ details.ask > summary span { font-weight: 400; font-size: 14px; color: var(--mut .s-privacy { color: var(--muted); font-size: 13px; max-width: 74ch; margin-top: 40px; padding-top: 16px; border-top: 1px solid var(--hair) } .search-terms { display: flex; flex-wrap: wrap; gap: 6px } .search-terms .chip b { font-weight: 700; margin-left: 4px } + +/* 판정 옆 '그래도 말할 수 있는 것' */ +.takeaway { margin: 12px 0; padding: 12px 16px; border-radius: 12px; background: var(--sunk) } +.takeaway span { display: block; font-size: 13px; font-weight: 700; color: var(--ink2); margin-bottom: 2px } +.takeaway p { margin: 0; font-size: 15.5px; color: var(--ink); line-height: 1.6 } + +/* 문장 검증 패널 */ +.q-hint { font-size: 14px; color: var(--muted); margin: 14px 0 0 } +.q-hint a { color: var(--ink2) } +.c-panel { --c: var(--accent); background: var(--surface); border: 1px solid var(--hair); border-top: 6px solid var(--c); border-radius: 20px; padding: 20px 26px; margin: 0 0 18px; animation: v-in .22s ease-out } +.c-panel.c-go { --c: var(--go) } .c-panel.c-warn { --c: var(--warn) } .c-panel.c-stop { --c: var(--stop) } +.c-head { display: flex; gap: 14px; align-items: baseline; flex-wrap: wrap } +.c-stamp { font-size: clamp(22px, 3.2vw, 30px); font-weight: 800; letter-spacing: -.04em; color: var(--c) } +.c-panel blockquote { margin: 12px 0; padding: 4px 0 4px 14px; border-left: 3px solid var(--hair); font-size: 17px; color: var(--ink) } +.c-parts { list-style: none; padding: 0; margin: 0 0 6px; display: flex; flex-direction: column; gap: 8px } +.c-parts li { display: flex; gap: 10px; align-items: baseline; font-size: 15px; color: var(--ink2) } +.c-parts .badge { flex: none } +@media (prefers-reduced-motion: reduce) { .c-panel { animation: none } } + +/* 홈: 최근 확인한 판정 — 같은 모양의 줄. 표지는 95% 범위 그림 */ +.vboard { display: flex; flex-direction: column; border-top: 1px solid var(--hair) } +.vb-row { --v: var(--warn); display: grid; grid-template-columns: 190px minmax(0, 1fr) 200px; gap: 22px; align-items: center; + padding: 16px 6px 16px 14px; border-bottom: 1px solid var(--hair); text-decoration: none; color: inherit; position: relative } +.vb-row.v-go { --v: var(--go) } .vb-row.v-stop { --v: var(--stop) } .vb-row.v-info { --v: var(--accent) } +.vb-row::before { content: ""; position: absolute; left: 0; top: 16px; bottom: 16px; width: 3px; border-radius: 2px; background: var(--v) } +.vb-row:hover { background: var(--surface) } +.vb-row:hover b { color: var(--accent) } +.vb-side { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; min-width: 0 } +.vb-who { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--ink2) } +.vb-who img { width: 20px; height: 20px; border-radius: 50% } +.vb-topic { font-size: 12.5px; color: var(--muted) } +.vb-main { display: flex; flex-direction: column; gap: 4px; min-width: 0 } +.vb-main b { font-size: 16px; line-height: 1.45; color: var(--ink) } +.vb-main span { font-size: 14px; color: var(--ink2); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden } +.vb-glyph:empty { display: none } +@media (max-width: 760px) { + .vb-row { grid-template-columns: minmax(0, 1fr); gap: 8px; padding-left: 16px } + .vb-side { flex-direction: row; flex-wrap: wrap; align-items: center; gap: 6px 10px } + .vb-glyph { max-width: 240px } +} + +/* 주제별: 결과를 한 축에 */ +.forest-wrap { background: var(--surface); border: 1px solid var(--hair); border-radius: 16px; padding: 18px 20px; margin: 0 0 16px } +.forest-wrap h3 { margin: 0 0 4px } +.forest { width: 100%; height: auto; display: block; margin-top: 8px; overflow: visible } +.forest .tick { stroke: var(--hair); stroke-width: 1 } +.forest .tl { fill: var(--muted); font-size: 11px; text-anchor: middle } +.forest .zero { stroke: var(--ink); stroke-width: 1.5 } +.forest .fn { fill: var(--ink); font-size: 13px } +.forest .band { stroke-width: 7; stroke-linecap: round; stroke: var(--warn); opacity: .45 } +.forest .est { fill: var(--warn); stroke: var(--surface); stroke-width: 2 } +.forest .f-go .band { stroke: var(--go) } .forest .f-go .est { fill: var(--go) } +.forest a:hover .fn { fill: var(--accent); text-decoration: underline } + +/* 가설·데이터 점검 */ +.fz { --fz: var(--accent); background: var(--surface); border: 1px solid var(--hair); border-left: 6px solid var(--fz); border-radius: 18px; padding: 20px 24px; margin: 18px 0 8px } +.fz.go { --fz: var(--go) } .fz.warn { --fz: var(--warn) } .fz.stop { --fz: var(--stop) } +.fz-head > div { display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap } +.fz-stamp { font-size: clamp(20px, 2.8vw, 26px); font-weight: 800; letter-spacing: -.03em; color: var(--fz) } +.fz-hyp { margin: 8px 0 12px; color: var(--ink2) } +.fz-list { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); gap: 10px 22px } +.fz-list li { display: grid; grid-template-columns: 24px minmax(0, 1fr); gap: 10px; align-items: start } +.fz-list li > span:last-child { display: flex; flex-direction: column; gap: 2px } +.fz-mark { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-size: 12px; font-weight: 800; color: #fff; background: var(--go) } +.fz-warn .fz-mark { background: var(--warn) } .fz-miss .fz-mark { background: var(--stop) } +.fz-graph { margin: 14px 0 0; padding-top: 12px; border-top: 1px solid var(--hair) } +.v-feas { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--hair) } +.v-feas .v-label { margin: 0 } +.v-feas-stamp { font-size: 22px; font-weight: 800; letter-spacing: -.03em; margin: 2px 0 4px } +.v-feas-stamp.c-go { color: var(--go) } .v-feas-stamp.c-warn { color: var(--warn) } .v-feas-stamp.c-stop { color: var(--stop) } +.v-checks { list-style: none; padding: 0; margin: 8px 0 0; display: flex; flex-direction: column; gap: 6px; font-size: 14.5px } +.hot-h { font-size: 16px; margin: 22px 0 8px } +.hot { margin: 0; padding-left: 22px; display: flex; flex-direction: column; gap: 6px } +.hot li a { margin-right: 10px } diff --git a/tests/test_causal.py b/tests/test_causal.py new file mode 100644 index 00000000..ddca4ab9 --- /dev/null +++ b/tests/test_causal.py @@ -0,0 +1,181 @@ +"""PyWhy(DoWhy)·CausalML 연계와 가설·데이터 점검. + +feasibility·draft·unit_changes 는 추가 설치 없이, DoWhy·CausalML 단계는 설치돼 있을 때만 돈다(CI 의 causal 작업). +""" + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import yaml + +from core.causal.draft import draft +from core.causal.feasibility import space_level, time_level, topic_feasibility +from core.causal.pywhy import check_case, unit_changes +from core.discovery.catalog import load_topics +from core.discovery.ontology import load_datasets, load_issues +from core.schema.plan import Plan, load_plan + +ROOT = Path(__file__).resolve().parents[1] +EX = ROOT / "cases" / "_example_night_clinic" + + +def test_unit_levels(): + assert ( + space_level("시군구(법정동)") == 3 + and space_level("지점(역)") == 4 + and space_level("확인필요") is None + ) + assert time_level("월") == 2 and time_level("실시간") == 5 and time_level("수시") is None + + +def test_feasibility_for_every_topic_has_six_checks_and_graph(): + ds, iss = load_datasets(), load_issues() + for t in load_topics(): + f = topic_feasibility(t, ds, iss) + assert [c["key"] for c in f["checks"]] == [ + "when", + "who", + "what", + "confounders", + "space", + "time", + ] + assert f["verdict"] in {"go", "warn", "stop"} and f["label"] + assert ["정책", "결과"] in f["graph"]["edges"] + assert f["hypothesis"]["sentence"] + + +def test_draft_is_schema_valid_and_uses_official_date(): + r = draft("서울 토허제 전역 확대 뒤 집값이 잡혔나", "gildong-ltp") + assert r["matched"] and r["issue"] == "seoul-ltp-1015-2025" + plan = Plan.model_validate(yaml.safe_load(r["plan_yaml"])) + assert plan.treatment.treat_time == "2025-10" # issues.yaml 의 공식 시행일 2025-10-20 + assert r["todo"] > 0 # 사람이 채울 칸은 남긴다 + assert draft("반려동물 등록제 효과")["matched"] is False + + +def test_unit_changes_equals_two_by_two_did(): + plan = load_plan(EX / "plan.yaml") + df = pd.read_csv(EX / "data" / "panel.csv") + f = unit_changes(plan, df) + y = plan.primary_outcome.col + post = df[plan.time.col] >= plan.treatment.treat_time + m = df.groupby([plan.treatment.group_col, post])[y].mean() + did = (m[1, True] - m[1, False]) - (m[0, True] - m[0, False]) + est = f.loc[f["T"] == 1, "dy"].mean() - f.loc[f["T"] == 0, "dy"].mean() + assert np.isclose(est, did, atol=1e-9) + assert set(f.columns) >= {"T", "dy", "y_pre"} and f["T"].sum() == 30 + + +def test_check_case_without_data_says_so(tmp_path): + case = tmp_path / "c" + case.mkdir() + (case / "plan.yaml").write_text( + (EX / "plan.yaml").read_text(encoding="utf-8"), encoding="utf-8" + ) + assert check_case(case)["status"] == "no_data" + + +def test_dowhy_and_causalml_recover_the_synthetic_effect(): + pytest.importorskip("dowhy") + pytest.importorskip("causalml") + r = check_case(EX) + assert r["status"] == "ok" and r["same_direction_as_baseline"] is True + dw, ml = r["dowhy"], r["causalml"] + assert dw["status"] == "ok" and abs(dw["estimate"] - (-5.0)) < 0.6 # 합성 데이터의 참효과 -5.0 + assert {x["status"] for x in dw["refutations"]} == {"pass"} + assert "y_pre" in dw["identification"]["adjust_for"] + assert ml["status"] == "ok" and abs(ml["ate"] - (-5.0)) < 0.6 and len(ml["by_baseline"]) == 3 + + +def test_causalml_skips_with_few_treated_units(): + from core.causal.pywhy import causalml_hte + + f = pd.DataFrame({"T": [1] * 4 + [0] * 21, "dy": np.arange(25.0), "y_pre": np.arange(25.0)}) + assert causalml_hte(f, [])["status"] == "skipped" + + +def test_committed_second_opinion_renders_on_answer_page(): + import sys + from html import escape + + sys.path.insert(0, str(ROOT / "site")) + import answers as ans + + a = {x["case"]: x for x in ans.load_answers()}["t3-land-permit-2025"] + assert a["pywhy"] and a["pywhy"]["dowhy"]["status"] == "ok" + html = ans.pywhy_block(escape, a) + assert "DoWhy" in html and "CausalML" in html and "가짜 처치" in html + + +def test_news_rss_count_parses_items(): + import importlib.util + + spec = importlib.util.spec_from_file_location("rt", ROOT / "scripts" / "refresh_trends.py") + rt = importlib.util.module_from_spec(spec) + spec.loader.exec_module(rt) + xml = "ab" + assert rt.count_rss_items(xml) == 2 and rt.count_rss_items("not xml") == 0 + t = load_topics()[0] + assert "when:7d" in rt.news_query(t) and rt.news_link(t).startswith( + "https://news.google.com/search?" + ) + + +ISSUE_BODY = """### 담당자 GitHub ID + +gildong + +### 주제 · 이슈 + +housing-regulation / seoul-ltp-gangnam-2025 + +### 하려는 것 (한두 문장) + +강남3구 재지정 뒤 +가격 급등이 멈췄나 +""" + + +def test_issue_agent_comment_and_plan(): + from core.causal.issue_agent import MARK, comment, parse_form, plan_for_issue + + form = parse_form(ISSUE_BODY) + assert form["담당자 GitHub ID"] == "gildong" + r = plan_for_issue("[작업] x", ISSUE_BODY) + assert r["case"] == "gildong-housing-regulation" and r["issue"] == "seoul-ltp-gangnam-2025" + plan = Plan.model_validate(yaml.safe_load(r["plan_yaml"])) + assert ( + plan.question.strip() == "강남3구 재지정 뒤 가격 급등이 멈췄나" + ) # 힌트는 plan 에 들어가지 않는다 + assert plan.treatment.treat_time == "2025-03" + c = comment("[작업] x", ISSUE_BODY) + assert c.startswith(MARK) and "plan-approved" in c and "```yaml" in c + + +def test_issue_agent_rejects_unsafe_owner_and_multiline_injection(): + from core.causal.issue_agent import plan_for_issue + + bad = plan_for_issue( + "[작업] x", "### 담당자 GitHub ID\n\n$(rm -rf /)\n\n### 하려는 것 (한두 문장)\n\n토허제\n" + ) + assert bad["case"] is None + inj = plan_for_issue( + "[작업] x", + "### 담당자 GitHub ID\n\ngildong\n\n### 하려는 것 (한두 문장)\n\n토허제 효과\nsynthetic_data: true\ncase_id: evil\n", + ) + d = yaml.safe_load(inj["plan_yaml"]) + assert d["case_id"] == "gildong-housing-regulation" and d["synthetic_data"] is False + + +def test_plan_agent_workflow_keeps_issue_text_out_of_shell(): + wf = (ROOT / ".github" / "workflows" / "plan-agent.yml").read_text(encoding="utf-8") + assert "plan-approved" in wf and "ISSUE_BODY: ${{ github.event.issue.body }}" in wf + run_lines = [ + ln + for ln in wf.splitlines() + if "github.event.issue.body" in ln or "github.event.issue.title" in ln + ] + assert all(ln.strip().startswith(("ISSUE_BODY:", "ISSUE_TITLE:")) for ln in run_lines) diff --git a/tests/test_site_build.py b/tests/test_site_build.py index 9d7cd046..eae8c38d 100644 --- a/tests/test_site_build.py +++ b/tests/test_site_build.py @@ -224,15 +224,16 @@ def test_answer_pages_for_users(tmp_path, monkeypatch): .replace("<\\/", "= 3 and 'class="crew"' in home - assert 'id="next"' in home and 'class="levels"' in home and "impact.html" in home + assert home.count('class="vb-row') >= 3 and 'class="crew"' in home + assert "class='glyph" in home and "impact.html" in home and 'action="search.html"' in home + assert 'id="next"' not in home and 'id="data-ready"' not in home assert 'id="reuse"' in (out / "results.html").read_text(encoding="utf-8") # 주제 페이지(이슈 보드)에는 분석 단계가 있고, 결과 CSV는 엑셀용 BOM 을 붙인다 for t in (out / "topics").glob("*.html"): diff --git a/tests/test_trust_claims.py b/tests/test_trust_claims.py new file mode 100644 index 00000000..46abc8f6 --- /dev/null +++ b/tests/test_trust_claims.py @@ -0,0 +1,120 @@ +"""판정 옆 '말할 수 있는 것', 검토 배지, 구조화 데이터(Dataset · ClaimReview).""" + +import json +import re +import sys +from html import escape +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "site")) + +import answers as ans # noqa: E402 +from quality import checks, next_steps # noqa: E402 + +A = {a["case"]: a for a in ans.load_answers()} + + +def _ld(a): + m = re.search(r'', ans.jsonld(a), re.S) + return json.loads(m.group(1)) + + +def test_takeaway_never_leaves_only_dont_know(): + for a in A.values(): + t = ans.takeaway(a) + if a["verdict"] == "not_identified" or a.get("execution_kind") == "descriptive_only": + assert t and t["text"], a["case"] + hy = ans.takeaway(A["hyun2-land-permit-spillover-2020"]) + assert hy["head"] == "그래도 말할 수 있는 것" and "맞지 않습니다" in hy["text"] + + +def test_usage_rules_shared_with_page(): + a = A["hyun2-land-permit-spillover-2020"] + do, dont = ans.usage_rules(a) + page = ans.page_body(escape, a, {}, {}) + assert all(escape(x) in page for x in do + dont) + assert 'class="takeaway"' in page + + +def test_primary_range_in_percent_for_log_outcomes(): + pr = ans.primary_range(A["hyun2-land-permit-spillover-2020"]) + assert pr["unit"] == "%" and pr["lo"] < pr["est"] < pr["hi"] + + +def test_dataset_jsonld_and_no_claimreview_without_human_claims(): + a = A["hyun2-land-permit-spillover-2020"] + d = _ld({**a, "claims": []}) + assert d["@type"] == "Dataset" and d["distribution"][0]["contentUrl"].endswith(".csv") + + +def test_claimreview_only_with_valid_rating(): + a = A["hyun2-land-permit-spillover-2020"] + claim = { + "text": "토허제로 옆 동네 집값이 20% 올랐다", + "by": "어느 신문", + "url": "https://example.org/n", + "date": "2020-08-01", + } + d = _ld({**a, "claims": [claim | {"rating": "결과와 다름"}]}) + assert [x["@type"] for x in d] == ["Dataset", "ClaimReview"] + assert ( + d[1]["reviewRating"]["alternateName"] == "결과와 다름" + and d[1]["claimReviewed"] == claim["text"] + ) + d2 = _ld({**a, "claims": [claim | {"rating": "아마도"}]}) + assert d2["@type"] == "Dataset" + + +def test_review_status_shows_in_trust_and_todo(): + a = dict(A["hyun2-land-permit-spillover-2020"]) + assert any(h.startswith("검토 · 아직") for _, h, _ in checks(a | {"reviewed_by": []})) + assert any(h == "검토 · 통과" for _, h, _ in checks(a | {"reviewed_by": ["someone"]})) + p = {"stages": [True, True, True, True]} + assert any("검토 요청" in t for t in next_steps(p, a | {"reviewed_by": []}, True)) + card = ans.card(escape, a | {"reviewed_by": ["someone"]}, {}) + assert "검토됨" in card + + +def test_search_index_carries_claim_check_fields(tmp_path): + import projects as proj + import search + + from core.discovery.catalog import load_topics + from core.discovery.links import all_lineages + from core.discovery.ontology import load_datasets, load_issues + + items = search.index( + load_topics(), + load_issues(), + load_datasets(), + list(A.values()), + proj.load_projects(), + all_lineages(), + ) + res = [i for i in items if i["t"] == "result"] + assert all({"v", "ro", "pr", "rules", "rev"} <= i.keys() for i in res) + js = (ROOT / "site" / "search.js").read_text(encoding="utf-8") + assert "checkClaim" in js and "결과와 다름" in js and "공식 팩트체크가 아니에요" in js + + +def test_claim_record_link_and_template(): + js = (ROOT / "site" / "search.js").read_text(encoding="utf-8") + assert "template=claim-review.yml" in js and "&claim=" in js and "&case=" in js + tpl = (ROOT / ".github" / "ISSUE_TEMPLATE" / "claim-review.yml").read_text(encoding="utf-8") + for fid in ("id: claim", "id: url", "id: case", "id: auto", "id: rating"): + assert fid in tpl + for rating in ans.CLAIM_RATINGS: + assert rating in tpl + + +def test_review_pairs_never_assign_self(): + import projects as proj + + mentee = [p for p in proj.load_projects() if not p["mentor"]] + html = proj.review_pairs(escape, mentee) + assert 'id="review"' in html + for row in re.findall(r"(.*?)", html): + owner = re.search(r"
    @([^<]+)
    ", row).group(1) + reviewer = re.search(r"github.com/([^']+)'", row).group(1) + assert owner != reviewer