Spaces:
Running

File size: 14,986 Bytes
b146445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""์ •์ œ๋œ ๋ฌธํ•ญ JSONL -> Supabase `questions` ํ…Œ์ด๋ธ” ์ ์žฌ (Load ๋‹จ๊ณ„).

ETL(Extract, Transform, Load) ์˜ ๋งˆ์ง€๋ง‰ ๋‹จ๊ณ„์ž…๋‹ˆ๋‹ค. 04_normalize_aihub.py ๊ฐ€ ๋งŒ๋“  aihub_A.jsonl ์„ DB ์— ๋„ฃ์Šต๋‹ˆ๋‹ค.
ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋งŒ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ pip ์„ค์น˜๊ฐ€ ํ•„์š” ์—†์Šต๋‹ˆ๋‹ค.

์ ‘์† ์ •๋ณด๋Š” ํŒŒ์ผ์— ์ ์ง€ ์•Š๊ณ  'ํ™˜๊ฒฝ๋ณ€์ˆ˜'๋กœ๋งŒ ๋ฐ›์Šต๋‹ˆ๋‹ค. (PowerShell ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค)
    $env:SUPABASE_URL = "https://xxxxxxxx.supabase.co"
    $env:SUPABASE_SERVICE_KEY = "<service_role ๋˜๋Š” Secret key>"      # ์ ˆ๋Œ€ GitHub ์— ์˜ฌ๋ฆฌ์ง€ ๋งˆ์„ธ์š”

์‚ฌ์šฉ๋ฒ•
    # 1) ๋จผ์ € ์‹œํ—˜ (๋„คํŠธ์›Œํฌ ์‚ฌ์šฉ ์•ˆ ํ•จ: ํ˜•์‹ ๊ฒ€์‚ฌ์™€ ๊ฐœ์ˆ˜๋งŒ ํ™•์ธ)
    python scripts\\06_load_supabase.py --file data\\aihub_normalized\\aihub_A.jsonl --dry-run
    # 2) ์†Œ๋Ÿ‰ ์ ์žฌ
    python scripts\\06_load_supabase.py --file data\\aihub_normalized\\aihub_A.jsonl --limit 50
    # 3) ์ „์ฒด ์ ์žฌ
    python scripts\\06_load_supabase.py --file data\\aihub_normalized\\aihub_A.jsonl

๊ฐ™์€ ํŒŒ์ผ์„ ๋‹ค์‹œ ์˜ฌ๋ ค๋„ ์•ˆ์ „ํ•ฉ๋‹ˆ๋‹ค.
    ๊ธฐ๋ณธ(insert-only)  : ์ด๋ฏธ ์žˆ๋Š” ๋ฌธํ•ญ(source+source_ref ๊ฐ€ ๊ฐ™์€ ๊ฒƒ)์€ ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š๊ณ  ์ƒˆ ๋ฌธํ•ญ๋งŒ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
    --refresh          : ์ด๋ฏธ ์žˆ๋Š” ๋ฌธํ•ญ์˜ '๋‚ด์šฉ'(๋ฌธ์ œยท์„ ํƒ์ง€ยท์ •๋‹ตยท๋‹จ์› ๋“ฑ)๋งŒ ๊ฐฑ์‹ ํ•ฉ๋‹ˆ๋‹ค.
                         ๊ฒ€์ˆ˜ ๊ฒฐ๊ณผ(verified, status, rights_status, solution_md, intent, figure_path)๋Š” ์ ˆ๋Œ€ ๋ฎ์–ด์“ฐ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
    --refresh --with-solution : ์œ„ ๋‚ด์šฉ + ํ•ด์„ค(solution_md)๋„ ๊ฐฑ์‹  (EBSi ํ•ด์„ค ์›๋ณธ ๋Œ€์กฐ ์ˆ˜์ • ๋ฐ˜์˜์šฉ).
"""
from __future__ import annotations

import argparse
import base64
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter
from pathlib import Path

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")

TABLE = "questions"
QTYPES = {"multiple_choice", "short_answer"}
DIFFS = {"low", "mid", "high"}
GRADES = {"e3", "e4", "e5", "e6", "m1", "m2", "m3", "h1", "h2", "h3"}
RIGHTS = {"unreviewed", "cleared", "restricted"}

# ์‹ ๊ทœ ์ ์žฌ ๋•Œ ๋ณด๋‚ด๋Š” ์—ด (ํ‘œ์˜ ์—ด ์ด๋ฆ„๊ณผ ๊ฐ™์Œ)
ALL_COLS = ("source", "source_ref", "source_meta", "rights_status", "grade_code", "unit_id", "difficulty", "score",
            "qtype", "stem_md", "choices", "figure_description", "figure_path", "answer", "accepted_answers",
            "solution_md", "intent", "verified", "verify_note", "status")
# --refresh ๋•Œ ๋ณด๋‚ด๋Š” ์—ด: ๋‚ด์šฉ๋งŒ. ๊ฒ€์ˆ˜ยท๊ฒŒ์‹œ ์ƒํƒœ์™€ ํ•ด์„ค์€ ๋ณด๋‚ด์ง€ ์•Š์•„ ๊ธฐ์กด ๊ฐ’์ด ์œ ์ง€๋จ
CONTENT_COLS = ("source", "source_ref", "source_meta", "grade_code", "unit_id", "difficulty", "qtype", "stem_md",
                "choices", "figure_description", "answer", "accepted_answers")
# 005/006 SQL ๋กœ ์ถ”๊ฐ€๋˜๋Š” ์—ด (EBSi ๋“ฑ). ํŒŒ์ผ์˜ ํ–‰์— ์ด ์—ด์ด ์žˆ์„ ๋•Œ๋งŒ ๋ณด๋ƒ„ -> 005ยท006 ์„ ๋จผ์ € ์‹คํ–‰ํ•ด์•ผ ํ•จ
EXTRA_COLS = ("exam_year", "exam_month", "exam_number", "search_text", "figure_text", "item_image_path",
              "figure_paths", "embedding", "embedding_model")


def clean_str(v):
    """PostgreSQL ์€ ๊ธ€์ž ์† NUL(\\u0000)์„ ์ €์žฅํ•˜์ง€ ๋ชปํ•˜๋ฏ€๋กœ ์ œ๊ฑฐ."""
    if isinstance(v, str):
        return v.replace("\u0000", "")
    if isinstance(v, list):
        return [clean_str(x) for x in v]
    if isinstance(v, dict):
        return {k: clean_str(x) for k, x in v.items()}
    return v


def validate(row: dict) -> str | None:
    """DB ์ œ์•ฝ(CHECK)์— ๊ฑธ๋ฆด ํ–‰์„ ๋ฏธ๋ฆฌ ์ฐพ์•„ ์ด์œ ๋ฅผ ๋Œ๋ ค์ค€๋‹ค. ๋ฌธ์ œ ์—†์œผ๋ฉด None."""
    if not row.get("source") or not row.get("source_ref"):
        return "source/source_ref ์—†์Œ"
    if row.get("qtype") not in QTYPES:
        return f"qtype ์ด์ƒ: {row.get('qtype')!r}"
    if row.get("grade_code") not in GRADES:
        return f"grade_code ์ด์ƒ: {row.get('grade_code')!r}"
    if row.get("difficulty") is not None and row["difficulty"] not in DIFFS:
        return f"difficulty ์ด์ƒ: {row['difficulty']!r}"
    if row.get("rights_status", "unreviewed") not in RIGHTS:
        return f"rights_status ์ด์ƒ: {row.get('rights_status')!r}"
    if not str(row.get("stem_md") or "").strip():
        return "๋ฌธ์ œ ๋ณธ๋ฌธ(stem_md) ์—†์Œ"
    if not str(row.get("answer") or "").strip():
        return "์ •๋‹ต(answer) ์—†์Œ"
    if row["qtype"] == "multiple_choice" and len(row.get("choices") or []) < 2:
        return "๊ฐ๊ด€์‹์ธ๋ฐ ์„ ํƒ์ง€๊ฐ€ 2๊ฐœ ๋ฏธ๋งŒ"
    if row.get("status", "draft") == "published":
        return "published ์ƒํƒœ๋Š” ์ ์žฌ ์Šคํฌ๋ฆฝํŠธ์—์„œ ์˜ฌ๋ฆฌ์ง€ ์•Š์Œ (๊ฒ€์ฆยท์ด์šฉํ—ˆ๋ฝ ํ™•์ธ ํ›„ ๋”ฐ๋กœ ๊ฒŒ์‹œ)"
    return None


def read_rows(paths: list[Path], limit: int | None):
    n = 0
    for p in paths:
        with p.open(encoding="utf-8") as f:
            for ln, line in enumerate(f, 1):
                line = line.strip()
                if not line:
                    continue
                try:
                    yield p, ln, json.loads(line)
                except json.JSONDecodeError:
                    yield p, ln, None
                n += 1
                if limit and n >= limit:
                    return


def check_key(key: str) -> None:
    """๊ณต๊ฐœ์šฉ(anon/publishable) ํ‚ค๋ฅผ ์‹ค์ˆ˜๋กœ ๋„ฃ์—ˆ๋Š”์ง€ ํ™•์ธ."""
    if key.startswith("sb_publishable_"):
        sys.exit("[์ค‘๋‹จ] publishable ํ‚ค์ž…๋‹ˆ๋‹ค. Secret key ๋˜๋Š” service_role ํ‚ค๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. (Settings > API Keys)")
    if key.count(".") == 2:      # ์˜ˆ์ „ ๋ฐฉ์‹ JWT ํ‚ค: ๊ฐ€์šด๋ฐ ์กฐ๊ฐ์—์„œ role ์„ ์ฝ๋Š”๋‹ค
        try:
            mid = key.split(".")[1]
            role = json.loads(base64.urlsafe_b64decode(mid + "=" * (-len(mid) % 4))).get("role")
            if role != "service_role":
                sys.exit(f"[์ค‘๋‹จ] ์ด ํ‚ค์˜ role ์ด '{role}' ์ž…๋‹ˆ๋‹ค. service_role ํ‚ค๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.")
        except (ValueError, KeyError):
            pass


class Client:
    def __init__(self, url: str, key: str):
        self.base = url.rstrip("/") + "/rest/v1"
        self.key = key

    def _headers(self, extra: dict | None = None) -> dict:
        h = {"apikey": self.key, "Content-Type": "application/json"}
        if self.key.count(".") == 2:          # ์˜ˆ์ „ JWT ํ‚ค๋งŒ Authorization ์— ๊ฐ™์ด ๋ณด๋‚ธ๋‹ค (์ƒˆ Secret key ๋Š” apikey ๋งŒ)
            h["Authorization"] = f"Bearer {self.key}"
        h.update(extra or {})
        return h

    def post_rows(self, rows: list[dict], refresh: bool, retries: int = 3) -> None:
        prefer = "resolution=merge-duplicates,return=minimal" if refresh else "resolution=ignore-duplicates,return=minimal"
        qs = urllib.parse.urlencode({"on_conflict": "source,source_ref"})
        req_url = f"{self.base}/{TABLE}?{qs}"
        data = json.dumps(rows, ensure_ascii=False).encode("utf-8")
        for attempt in range(1, retries + 1):
            req = urllib.request.Request(req_url, data=data, method="POST", headers=self._headers({"Prefer": prefer}))
            try:
                with urllib.request.urlopen(req, timeout=60):
                    return
            except urllib.error.HTTPError as e:
                body = e.read().decode("utf-8", "replace")[:600]
                if e.code in (429, 500, 502, 503, 504) and attempt < retries:
                    time.sleep(2 * attempt)
                    continue
                raise RuntimeError(f"HTTP {e.code}: {body}") from None
            except (urllib.error.URLError, TimeoutError) as e:
                if attempt < retries:
                    time.sleep(2 * attempt)
                    continue
                raise RuntimeError(f"์—ฐ๊ฒฐ ์‹คํŒจ: {e}") from None

    def count(self, source: str) -> int | None:
        qs = urllib.parse.urlencode({"select": "id", "source": f"eq.{source}"})
        req = urllib.request.Request(f"{self.base}/{TABLE}?{qs}", method="GET",
                                     headers=self._headers({"Prefer": "count=exact", "Range": "0-0"}))
        try:
            with urllib.request.urlopen(req, timeout=60) as r:
                cr = r.headers.get("Content-Range", "")
                return int(cr.split("/")[-1]) if "/" in cr and cr.split("/")[-1].isdigit() else None
        except Exception:
            return None


def main() -> None:
    ap = argparse.ArgumentParser(description="์ •์ œ JSONL -> Supabase questions ์ ์žฌ")
    ap.add_argument("--file", type=Path, nargs="+", required=True, help="์ ์žฌํ•  JSONL (์˜ˆ: aihub_A.jsonl)")
    ap.add_argument("--dry-run", action="store_true", help="๋„คํŠธ์›Œํฌ ์—†์ด ํ˜•์‹ ๊ฒ€์‚ฌ์™€ ๊ฐœ์ˆ˜๋งŒ ํ™•์ธ")
    ap.add_argument("--refresh", action="store_true", help="์ด๋ฏธ ์žˆ๋Š” ๋ฌธํ•ญ์˜ ๋‚ด์šฉ๋งŒ ๊ฐฑ์‹  (๊ฒ€์ˆ˜ ๊ฒฐ๊ณผ๋Š” ๋ณด์กด)")
    ap.add_argument("--with-solution", action="store_true",
                    help="--refresh ์™€ ํ•จ๊ป˜: ํ•ด์„ค(solution_md)๋„ ๊ฐฑ์‹  (๊ฒ€์ˆ˜ยท๊ฒŒ์‹œ ์ƒํƒœ๋Š” ๊ทธ๋Œ€๋กœ ๋ณด์กด)")
    ap.add_argument("--limit", type=int, help="์•ž์—์„œ ์ด ๊ฐœ์ˆ˜๋งŒ ์ฒ˜๋ฆฌ")
    ap.add_argument("--batch", type=int, default=200, help="ํ•œ ๋ฒˆ์— ๋ณด๋‚ด๋Š” ํ–‰ ์ˆ˜ (๊ธฐ๋ณธ 200)")
    ap.add_argument("--failed-out", type=Path, default=Path("load_failed.jsonl"), help="์‹คํŒจํ•œ ํ–‰์„ ์ €์žฅํ•  ํŒŒ์ผ")
    a = ap.parse_args()

    for p in a.file:
        if not p.exists():
            sys.exit(f"[์ค‘๋‹จ] ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค: {p}")

    if a.with_solution and not a.refresh:
        sys.exit("[์ค‘๋‹จ] --with-solution ์€ --refresh ์™€ ํ•จ๊ป˜ ์“ฐ์„ธ์š”")
    cols = (CONTENT_COLS + (("solution_md",) if a.with_solution else ())) if a.refresh else ALL_COLS
    good: list[dict] = []
    bad: list[dict] = []
    why = Counter()
    seen: set[tuple] = set()
    dup = 0
    extra_cols: tuple | None = None
    for p, ln, row in read_rows(a.file, a.limit):
        if row is None:
            why["JSON ํ•ด์„ ์‹คํŒจ"] += 1
            bad.append({"file": str(p), "line": ln, "reason": "JSON ํ•ด์„ ์‹คํŒจ"})
            continue
        row = clean_str(row)
        row.setdefault("rights_status", "unreviewed")
        row.setdefault("status", "draft")
        r = validate(row)
        if r:
            why[r] += 1
            bad.append({"file": str(p), "line": ln, "source_ref": row.get("source_ref"), "reason": r})
            continue
        k = (row["source"], row["source_ref"])
        if k in seen:
            dup += 1
            continue
        seen.add(k)
        row["choices"] = row.get("choices") or []
        row["accepted_answers"] = row.get("accepted_answers") or []
        row["source_meta"] = row.get("source_meta") or {}
        if "figure_paths" in row:
            row["figure_paths"] = row.get("figure_paths") or []
        extra = tuple(c for c in EXTRA_COLS if c in row)
        if extra_cols is None:
            extra_cols = extra
        elif extra != extra_cols:
            why["์ถ”๊ฐ€ ์—ด ๊ตฌ์„ฑ์ด ๋‹ค๋ฅธ ํ–‰๊ณผ ๋‹ค๋ฆ„"] += 1
            bad.append({"file": str(p), "line": ln, "source_ref": row.get("source_ref"), "reason": "์ถ”๊ฐ€ ์—ด ๊ตฌ์„ฑ ๋ถˆ์ผ์น˜"})
            continue
        good.append({c: row.get(c) for c in cols + extra_cols})   # ๋ชจ๋“  ํ–‰์ด ๊ฐ™์€ ์—ด์„ ๊ฐ€์ง€๋„๋ก (PostgREST ์š”๊ตฌ์‚ฌํ•ญ)

    by_grade = Counter(r.get("grade_code") for r in good)
    by_diff = Counter(r.get("difficulty") for r in good)
    sources = sorted({r["source"] for r in good})
    print(f"์ฝ์Œ: ์ ์žฌ ๋Œ€์ƒ {len(good)}๊ฐœ / ์ œ์™ธ {len(bad)}๊ฐœ / ํŒŒ์ผ ์•ˆ ์ค‘๋ณต {dup}๊ฐœ")
    print(f"  ์ถœ์ฒ˜: {sources}  ํ•™๋…„: {dict(by_grade)}  ๋‚œ์ด๋„: {dict(by_diff)}")
    if extra_cols:
        print(f"  ์ถ”๊ฐ€ ์—ด(005/006 SQL ํ•„์š”): {', '.join(extra_cols)}")
        if "embedding" in extra_cols:
            dims = {len(str(r['embedding']).strip('[]').split(',')) for r in good if r.get('embedding')}
            print(f"  ์ž„๋ฒ ๋”ฉ ์ฐจ์›: {sorted(dims)}  (006 SQL ์˜ vector(1024) ์™€ ๊ฐ™์•„์•ผ ํ•จ)")
            if a.batch > 50:
                print("  โ€ป ์ž„๋ฒ ๋”ฉ์ด ์žˆ์–ด ํ•œ ์ค„์ด ํฝ๋‹ˆ๋‹ค. --batch 50 ์ดํ•˜๋ฅผ ๊ถŒ์žฅํ•ฉ๋‹ˆ๋‹ค.")
    for k, v in why.most_common():
        print(f"  ์ œ์™ธ ์ด์œ  - {k}: {v}")
    if bad:
        with a.failed_out.open("w", encoding="utf-8") as f:
            for b in bad:
                f.write(json.dumps(b, ensure_ascii=False) + "\n")
        print(f"  ์ œ์™ธ๋œ ํ–‰ ๋ชฉ๋ก: {a.failed_out}")

    if a.dry_run:
        print("[dry-run] ๋„คํŠธ์›Œํฌ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ์ด์ƒ์ด ์—†์œผ๋ฉด --dry-run ์„ ๋นผ๊ณ  ์‹คํ–‰ํ•˜์„ธ์š”.")
        return
    if not good:
        sys.exit("[์ค‘๋‹จ] ์ ์žฌํ•  ํ–‰์ด ์—†์Šต๋‹ˆ๋‹ค.")

    url, key = os.environ.get("SUPABASE_URL", "").strip(), os.environ.get("SUPABASE_SERVICE_KEY", "").strip()
    if not url or not key:
        sys.exit("[์ค‘๋‹จ] ํ™˜๊ฒฝ๋ณ€์ˆ˜ SUPABASE_URL, SUPABASE_SERVICE_KEY ๋ฅผ ๋จผ์ € ์„ค์ •ํ•˜์„ธ์š”. (ํŒŒ์ผ ๋งจ ์œ„ ์„ค๋ช… ์ฐธ๊ณ )")
    if not (url.startswith("https://") or url.startswith("http://127.0.0.1") or url.startswith("http://localhost")):
        sys.exit("[์ค‘๋‹จ] SUPABASE_URL ์€ https://<ํ”„๋กœ์ ํŠธ>.supabase.co ํ˜•์‹์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.")
    check_key(key)

    cli = Client(url, key)
    src = sources[0] if len(sources) == 1 else None
    before = cli.count(src) if src else None
    print(f"์ ์žฌ ์ „ DB ์˜ {src or 'ํ•ด๋‹น'} ๋ฌธํ•ญ ์ˆ˜: {before if before is not None else 'ํ™•์ธ ๋ชป ํ•จ'}")
    sent = failed = 0
    fails: list[dict] = []
    for i in range(0, len(good), a.batch):
        chunk = good[i:i + a.batch]
        try:
            cli.post_rows(chunk, a.refresh)
            sent += len(chunk)
        except RuntimeError as e:
            # ๋ฌถ์Œ์ด ์‹คํŒจํ•˜๋ฉด ํ•œ ์ค„์”ฉ ๋‹ค์‹œ ๋ณด๋‚ด ๋ฌธ์ œ ํ–‰๋งŒ ๊ณจ๋ผ๋‚ธ๋‹ค
            print(f"  ๋ฌถ์Œ {i + 1}~{i + len(chunk)} ์‹คํŒจ -> ํ•œ ์ค„์”ฉ ์žฌ์‹œ๋„ ({str(e)[:120]})")
            for r in chunk:
                try:
                    cli.post_rows([r], a.refresh, retries=2)
                    sent += 1
                except RuntimeError as e2:
                    failed += 1
                    fails.append({"source_ref": r.get("source_ref"), "error": str(e2)[:300]})
        print(f"  ... {min(i + a.batch, len(good))}/{len(good)} ์ „์†ก")
    if fails:
        with a.failed_out.open("a", encoding="utf-8") as f:
            for x in fails:
                f.write(json.dumps(x, ensure_ascii=False) + "\n")
    after = cli.count(src) if src else None
    print(f"์™„๋ฃŒ: ์ „์†ก ์„ฑ๊ณต {sent}๊ฐœ / ์‹คํŒจ {failed}๊ฐœ")
    print(f"์ ์žฌ ํ›„ DB ์˜ {src or 'ํ•ด๋‹น'} ๋ฌธํ•ญ ์ˆ˜: {after if after is not None else 'ํ™•์ธ ๋ชป ํ•จ'}"
          + (f"  (์ด๋ฒˆ์— ์ƒˆ๋กœ ๋Š˜์–ด๋‚œ ์ˆ˜ {after - before})" if before is not None and after is not None else ""))
    if not a.refresh:
        print("โ€ป ๊ธฐ๋ณธ ๋ชจ๋“œ๋Š” ์ด๋ฏธ ์žˆ๋Š” ๋ฌธํ•ญ์„ ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. '์ „์†ก ์„ฑ๊ณต'์ด ์ƒˆ๋กœ ๋Š˜์–ด๋‚œ ์ˆ˜๋ณด๋‹ค ํด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
    if failed:
        print(f"์‹คํŒจํ•œ ํ–‰: {a.failed_out} (์ด ํŒŒ์ผ์„ ๋ณด๋‚ด ์ฃผ์‹œ๋ฉด ์›์ธ์„ ๋ด…๋‹ˆ๋‹ค)")


if __name__ == "__main__":
    main()