File size: 6,102 Bytes
d847043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""让老师模型照着建表语句造 (中文问题, SQLite 查询) 对。

    python scripts/teacher.py --schema schemas/school.sql --n 20

生成的 SQL 会真的丢进内存 SQLite 跑一遍(数据用 seed_suite 现生成),跑不过的直接扔掉;
只留单条 SELECT / WITH,DDL/DML 一律不要。结果追加到 data/new/<库名>.jsonl,
跑完用 verify.py 复核,再用 build_sft.py 拼进训练集。
"""

import argparse
import json
import os
import sqlite3
import sys
import time
from pathlib import Path

import httpx

from seed_suite import make_suite

# 包里脚本在 scripts/,schemas/ data/ 在上一级;GitHub 仓库是平铺的,两种都认
ROOT = Path(__file__).resolve().parent
if not (ROOT / "schemas").is_dir():
    ROOT = ROOT.parent
API = "https://api.deepseek.com/chat/completions"
# 测试库:出训练题时碰都不能碰,不然测试集就泄漏了
TEST_DBS = {"library", "gym", "hard_retail", "transit"}

PROMPT = """你在给一个中文 Text-to-SQLite 数据集出题。

下面是数据库的建表语句:

{ddl}

出 {n} 道中文问题,并为每题写一条 SQLite 查询。要求:

- 问题要像真人问的,口语化,可以有「上个月」「最多的前五个」这种自然表达
- 覆盖不同难度:简单筛选、聚合、分组、多表连接、子查询、排序取前几
- 只能用 SELECT,一条语句,不要解释、不要分号结尾以外的多余内容
- 表名和列名必须严格使用上面出现过的
- 不要问需要 INSERT/UPDATE/DELETE 的问题
- 大约五分之一的题要牵涉 CTE(WITH)、窗口函数或者日期计算,别全是简单查询
- 日期字段是 TEXT,格式 'YYYY-MM-DD' 或 'YYYY-MM-DD HH:MM:SS',用 SQLite 的 date()/strftime()
- 问题里不要出现表名、列名或 SQL 片段,全用业务说法;问「前几名」「最多的」要能有唯一答案
- 一对多连接后再 SUM 父表的金额会重复计算,这种要先在子查询/CTE 里聚合好再连

只输出 JSON,格式:
{{"items": [{{"question": "中文问题", "sql": "SELECT ..."}}]}}"""


def api_key() -> str:
    """DeepSeek 的 key 从环境变量 DEEPSEEK_API_KEY 读,不写进代码和仓库。"""
    key = os.environ.get("DEEPSEEK_API_KEY", "").strip()
    if not key:
        raise SystemExit("先设置环境变量 DEEPSEEK_API_KEY")
    return key


def post_with_retry(payload: dict, key: str, timeout: int = 180) -> str:
    """调 DeepSeek,返回回复正文。偶尔超时或 5xx,重试 3 次、一次比一次等得久;还不行就抛出去。"""
    for attempt in range(3):
        try:
            r = httpx.post(API, json=payload, timeout=timeout, headers={"Authorization": f"Bearer {key}"})
            r.raise_for_status()
            return r.json()["choices"][0]["message"]["content"]
        except (httpx.HTTPError, KeyError, ValueError) as exc:
            if attempt == 2:
                raise
            print(f"请求失败({exc}),{10 * (attempt + 1)} 秒后重试", file=sys.stderr)
            time.sleep(10 * (attempt + 1))
    raise AssertionError("unreachable")


def ask(ddl: str, n: int, key: str) -> list[dict]:
    payload = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "system", "content": "你只输出 JSON。"},
            {"role": "user", "content": PROMPT.format(ddl=ddl, n=n)},
        ],
        "temperature": 1.0,
        "max_tokens": 4000,
        "response_format": {"type": "json_object"},
    }
    try:
        return json.loads(post_with_retry(payload, key)).get("items") or []
    except json.JSONDecodeError:
        print("这一轮 JSON 坏了,跳过", file=sys.stderr)
        return []


def check(sql: str, conn: sqlite3.Connection) -> tuple[bool, str]:
    s = sql.strip().rstrip(";")
    # WITH 开头的是 CTE,也要留;以前只认 select,老师写的 CTE 全被扔了,训练集里一条 CTE 都没有
    if not s.lower().startswith(("select", "with")):
        return False, "不是 select"
    if ";" in s:
        return False, "多条语句"
    try:
        conn.execute(s).fetchall()
        return True, ""
    except Exception as exc:  # noqa: BLE001
        return False, str(exc)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--schema", required=True)
    ap.add_argument("--n", type=int, default=20)
    ap.add_argument("--rounds", type=int, default=1)
    ap.add_argument("--out", default="")
    args = ap.parse_args()

    schema_path = Path(args.schema) if Path(args.schema).exists() else ROOT / args.schema
    ddl = schema_path.read_text(encoding="utf-8")
    dbname = schema_path.stem
    if dbname in TEST_DBS:
        raise SystemExit(f"{dbname} 是测试库,不能拿来出训练题")
    conn = sqlite3.connect(":memory:")
    conn.executescript(ddl)
    conn.executescript(make_suite(dbname, [], 1)[0])
    conn.execute("PRAGMA query_only = ON")  # WITH ... DELETE 这种也别想改库

    key = api_key()
    out_path = Path(args.out) if args.out else ROOT / "data" / "new" / f"{dbname}.jsonl"
    out_path.parent.mkdir(parents=True, exist_ok=True)

    kept = bad = 0
    with out_path.open("a", encoding="utf-8") as f:
        for r in range(args.rounds):
            items = ask(ddl, args.n, key)
            for it in items:
                q = str(it.get("question") or "").strip()
                sql = str(it.get("sql") or "").strip()
                if not q or not sql:
                    continue
                ok, err = check(sql, conn)
                if not ok:
                    bad += 1
                    print(f"丢弃({err[:60]}):{sql[:80]}", file=sys.stderr)
                    continue
                f.write(json.dumps({"db": dbname, "question": q, "sql": sql.rstrip(";")},
                                   ensure_ascii=False) + "\n")
                kept += 1
            print(f"第 {r+1} 轮:累计保留 {kept},丢弃 {bad}", flush=True)

    print(f"完成:{out_path},保留 {kept} 条,丢弃 {bad} 条")


if __name__ == "__main__":
    main()