qkrm commited on
Commit
b7e875d
·
verified ·
1 Parent(s): b6f14c9

feat: visitor counter + ping-exclusion in stats

Browse files
Files changed (3) hide show
  1. HANDOFF.md +97 -0
  2. index.html +14 -0
  3. server/main.py +25 -4
HANDOFF.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HANDOFF — 노? 신고합니다 (노 판독기)
2
+
3
+ 다른 컴퓨터에서 이 프로젝트를 이어받기 위한 문서. 2026-07-08 기준.
4
+
5
+ ## 1. 프로젝트가 뭔가
6
+
7
+ 동남 방언 의문형 어미(-노/-나/-고/-가)가 문법에 맞는지 판정하는 사이트.
8
+ '-노' 어미만 보고 일베로 몰아 신고하는 과잉 언어 검열을 풍자하기 위해 만들었다.
9
+ 제작자는 일베 이용자가 아니며, 사이트의 비판 대상은 "말투로 사람을 낙인찍는 행위"다.
10
+
11
+ **중요한 편집 방침** (바꾸지 말 것):
12
+ - 판정 로직은 "일베 판별기"가 아니다. 부정 판정 문구는 "표준 규칙과 다름" + 단서(방언 변이는 다양하고 이것만으로 사람을 판정할 수 없다) 톤 유지.
13
+ - "노무위키"라는 이름은 쓰지 않는다 (사용자가 명시적으로 거부함). 브랜드는 "노?신고합니다".
14
+
15
+ ## 2. 라이브 주소
16
+
17
+ | 용도 | 주소 |
18
+ |---|---|
19
+ | **메인 배포** (HF Space) | https://no-singo-web.hf.space |
20
+ | 예비 배포 (Render) | https://no-singo.onrender.com |
21
+ | 사용량 통계 | https://no-singo-web.hf.space/api/stats |
22
+ | GitHub 저장소 (private) | https://github.com/QKRM/no-singo |
23
+ | HF Space 저장소 | https://huggingface.co/spaces/no-singo/web |
24
+
25
+ 계정: GitHub `QKRM`, Hugging Face `qkrm` (org `no-singo`는 URL에서 닉네임 감추기 용도).
26
+
27
+ ## 3. 새 컴퓨터 세팅
28
+
29
+ 필요: Python 3.12+, git. (gh CLI, hf CLI는 배포 갱신할 때만)
30
+
31
+ ```powershell
32
+ git clone https://github.com/QKRM/no-singo.git # 또는 zip 압축 해제
33
+ cd no-singo\server
34
+ python -m venv .venv
35
+ .venv\Scripts\pip install -r requirements.txt
36
+ .venv\Scripts\uvicorn main:app --reload # http://localhost:8000
37
+ ```
38
+
39
+ 테스트 (수정 후 반드시):
40
+
41
+ ```powershell
42
+ # 저장소 루트에서
43
+ server\.venv\Scripts\python -m pytest tests -q # 22개 전부 통과해야 함
44
+ ```
45
+
46
+ ## 4. 구조
47
+
48
+ ```
49
+ ├─ index.html # 프런트 전체 (CSS/JS 인라인, 밈 이미지 base64 포함)
50
+ ├─ Dockerfile # HF Space용 (포트 7860)
51
+ ├─ render.yaml # Render용
52
+ ├─ README.md # 상단 YAML frontmatter = HF Space 메타데이터 (지우면 HF 배포 깨짐)
53
+ ├─ .github/workflows/keepalive.yml # 10분마다 두 배포 ping (저장소 60일 무커밋 시 자동 중지됨)
54
+ ├─ img/ # 밈 원본/절단본 (index.html은 base64라 런타임에 안 씀)
55
+ ├─ server/
56
+ │ ├─ main.py # FastAPI: /api/analyze, /api/singo, /api/stats + 정적 서빙
57
+ │ ├─ analyzer.py # 방언 정규화 → Kiwi 형태소 분석 → 규칙 판정
58
+ │ └─ dialects/gyeongnam.json # 방언→표준어 어절 사전 (지역 추가 = 새 json 파일)
59
+ └─ tests/test_analyzer.py # 골든 테스트
60
+ ```
61
+
62
+ 동작 원리 요점:
63
+ - 프런트는 백엔드 없이도 로컬 휴리스틱으로 즉시 판정, 백엔드 살아있으면 250ms 후 Kiwi 판정으로 업그레이드 ("판정 엔진" 표기 참고).
64
+ - analyzer.py 핵심 트릭: 어간에 '니'를 붙여 Kiwi 분석 (어간만 주면 단음절 동사 오분석), VCP(지정사)는 체언 취급.
65
+ - Kiwi 로드 옵션 `num_workers=1, load_typo_dict=False, load_multi_dict=False`는 Render 512MB OOM 방지용. HF에서는 불필요하지만 더 빠르므로 유지.
66
+
67
+ ## 5. 배포 갱신 방법
68
+
69
+ 코드 수정 → 테스트 통과 확인 후:
70
+
71
+ **Render** (자동): GitHub에 push하면 자동 재배포.
72
+
73
+ ```powershell
74
+ git add -A; git commit -m "..."; git push
75
+ ```
76
+
77
+ **HF Space** (수동 — GitHub push로 반영 안 됨!):
78
+
79
+ ```powershell
80
+ # 최초 1회: pip install huggingface_hub 후 hf auth login (Write 토큰 필요)
81
+ python -c "from huggingface_hub import HfApi; HfApi().upload_folder(folder_path='.', repo_id='no-singo/web', repo_type='space', ignore_patterns=['.git/**','server/.venv/**','server/stats.db','**/__pycache__/**','.pytest_cache/**','img/top_b64.txt','img/bottom_b64.txt','.github/**'])"
82
+ ```
83
+
84
+ 토큰은 https://huggingface.co/settings/tokens 에서 Write 권한으로 발급.
85
+ (2026-07-08에 채팅에 노출된 구 토큰은 revoke 대상 — 새 PC에서는 새로 발급할 것.)
86
+
87
+ ## 6. 사용자 분석
88
+
89
+ - 자체 집계: `GET /api/stats` — 방문·판정 수·판정 분포·신고 버튼 클릭·일별 30일. SQLite(server/stats.db)는 재배포 시 초기화됨.
90
+ - GA4 (선택): index.html 상단 주석 블록 해제 + 측정 ID 교체.
91
+
92
+ ## 7. 알려진 한계 / TODO 후보
93
+
94
+ - 감탄형("얼마나 좋노!")·인용("-라고 하노") 문형 오판 가능.
95
+ - 방언 사전은 경남 중심 — 전라/제주/강원 확장은 server/dialects/에 json 추가.
96
+ - stats 영구 보존하려면 외부 DB 필요.
97
+ - keep-alive는 저장소가 60일간 커밋 없으면 GitHub이 끔 → Actions 탭에서 수동 재활성화.
index.html CHANGED
@@ -349,6 +349,7 @@
349
  <h1 class="doc-title"><span class="no">노</span>?신고합니다.</h1>
350
  <div class="doc-meta">
351
  <span>최근 수정 시각: 방금 전 (당신이 '노'를 쓰는 순간 갱신됨)</span>
 
352
  </div>
353
 
354
  <section id="checker">
@@ -766,6 +767,19 @@
766
  });
767
  modal.addEventListener('click', e => { if (e.target === modal) closeSingo(); });
768
  document.addEventListener('keydown', e => { if (e.key === 'Escape' && !modal.hidden) closeSingo(); });
 
 
 
 
 
 
 
 
 
 
 
 
 
769
  </script>
770
  </body>
771
  </html>
 
349
  <h1 class="doc-title"><span class="no">노</span>?신고합니다.</h1>
350
  <div class="doc-meta">
351
  <span>최근 수정 시각: 방금 전 (당신이 '노'를 쓰는 순간 갱신됨)</span>
352
+ <span id="visitCounter" hidden></span>
353
  </div>
354
 
355
  <section id="checker">
 
767
  });
768
  modal.addEventListener('click', e => { if (e.target === modal) closeSingo(); });
769
  document.addEventListener('keydown', e => { if (e.key === 'Escape' && !modal.hidden) closeSingo(); });
770
+
771
+ // ── 방문자 수 (백엔드 있을 때만 표시) ──
772
+ (async () => {
773
+ try {
774
+ const res = await fetch('/api/stats');
775
+ if (!res.ok) return;
776
+ const s = await res.json();
777
+ if (typeof s.total_visits !== 'number') return;
778
+ const el = $('visitCounter');
779
+ el.textContent = `이 사이트는 오늘 ${s.today_visits.toLocaleString()}명, 전체 ${s.total_visits.toLocaleString()}명이 방문했습니다.`;
780
+ el.hidden = false;
781
+ } catch (e) { /* 백엔드 없음 → 표시 안 함 */ }
782
+ })();
783
  </script>
784
  </body>
785
  </html>
server/main.py CHANGED
@@ -6,7 +6,7 @@
6
  """
7
  import sqlite3
8
  import threading
9
- from datetime import datetime, timezone
10
  from pathlib import Path
11
 
12
  from fastapi import FastAPI, Request
@@ -45,8 +45,11 @@ def _db() -> sqlite3.Connection:
45
  return conn
46
 
47
 
 
 
 
48
  def _record(kind: str, verdict: str | None = None) -> None:
49
- now = datetime.now(timezone.utc)
50
  with _db_lock, _db() as conn:
51
  conn.execute(
52
  "INSERT INTO events (kind, verdict, day, ts) VALUES (?, ?, ?, ?)",
@@ -93,13 +96,31 @@ def stats_endpoint():
93
  " FROM events GROUP BY day ORDER BY day DESC LIMIT 30"
94
  ).fetchall()
95
  ]
96
- return {"totals": totals, "verdicts": verdicts, "daily": daily}
 
 
 
 
 
 
 
 
 
 
97
 
98
 
99
  @app.middleware("http")
100
  async def count_page_visits(request: Request, call_next):
101
  response = await call_next(request)
102
- if request.method == "GET" and request.url.path == "/" and response.status_code == 200:
 
 
 
 
 
 
 
 
103
  _record("visit")
104
  return response
105
 
 
6
  """
7
  import sqlite3
8
  import threading
9
+ from datetime import datetime, timedelta, timezone
10
  from pathlib import Path
11
 
12
  from fastapi import FastAPI, Request
 
45
  return conn
46
 
47
 
48
+ KST = timezone(timedelta(hours=9)) # 방문자 대부분이 한국이므로 일 단위는 KST 기준
49
+
50
+
51
  def _record(kind: str, verdict: str | None = None) -> None:
52
+ now = datetime.now(KST)
53
  with _db_lock, _db() as conn:
54
  conn.execute(
55
  "INSERT INTO events (kind, verdict, day, ts) VALUES (?, ?, ?, ?)",
 
96
  " FROM events GROUP BY day ORDER BY day DESC LIMIT 30"
97
  ).fetchall()
98
  ]
99
+ today = datetime.now(KST).strftime("%Y-%m-%d")
100
+ (today_visits,) = conn.execute(
101
+ "SELECT COUNT(*) FROM events WHERE kind = 'visit' AND day = ?", (today,)
102
+ ).fetchone()
103
+ return {
104
+ "totals": totals,
105
+ "verdicts": verdicts,
106
+ "daily": daily,
107
+ "today_visits": today_visits,
108
+ "total_visits": totals.get("visit", 0),
109
+ }
110
 
111
 
112
  @app.middleware("http")
113
  async def count_page_visits(request: Request, call_next):
114
  response = await call_next(request)
115
+ # keep-alive ping(curl)·봇은 방문 집계에서 제외
116
+ ua = request.headers.get("user-agent", "").lower()
117
+ is_bot = ua.startswith("curl") or "bot" in ua or ua == ""
118
+ if (
119
+ request.method == "GET"
120
+ and request.url.path == "/"
121
+ and response.status_code == 200
122
+ and not is_bot
123
+ ):
124
  _record("visit")
125
  return response
126