describe.py
7.72 KB
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
"""用 LLM 批量起草表/列的业务描述与同义词。
为什么值得单独做一步:物理 schema 里写的是 `sum_ax_package`,业务同事嘴里说的是
「安心包卖了多少」。中间这层映射不补上,召回阶段就命中不了,后面再准也白搭。
三条硬规则:
1. **产出必须对照 manifest 校验**,模型编出来的列一律丢掉(抄 WrenAI 的 `output` 步骤,
便宜且必要 —— 让幻觉列进语义层比没有描述更糟)。
2. **不覆盖人工写过的内容**。只填空,除非显式 overwrite。
3. **分批**。一次一张表,表太宽就切片,避免一个超长 prompt 把质量拖垮。
写成生成器 yield 进度事件,交给 jobs/queue 跑 —— 十几张表几百列要几分钟。
"""
from __future__ import annotations
import json
import logging
from typing import Iterator
from ..core import llm
from . import semantic
log = logging.getLogger(__name__)
COLUMNS_PER_BATCH = 30 # 一批喂多少列。再多模型就开始偷懒漏列了
SYSTEM = """你是一名既懂数据仓库又懂汽车门店运营业务的数据分析师。
给你一张表的结构,请为每一列补充**业务同义词**,并在缺少说明时补一句业务含义。
同义词是这项工作的重点:物理列名是英文缩写,业务同事嘴里说的是中文口语。
比如 `sum_ax_package`(安心包成交总数)的同义词应该有「安心包」「安心包销量」「安心包成交数」「驾行安心包」。
目标是:用户随口怎么问,都能靠同义词命中这一列。
规则:
- 每列给 2~6 个同义词,**只给业务同义词,不要把列名本身或纯英文再写一遍**。
- 已有的列说明如果准确就不用改,`description` 留空串即可;只有原说明缺失或看不懂时才补写。
- 列说明里如果已经写了枚举含义(如「0=会员权益, 1=精品升级」),**必须在同义词里带上这些取值的中文词**。
- `role` 判断这列是维度还是度量:可求和求平均的数值填 "measure",用来分组过滤的填 "dimension"。
主键、ID、时间、名称一律 "dimension"。
- **只能输出给定的列,一个都不能多**。不确定的列就给空同义词数组,不要编。
只输出 JSON,不要任何解释:
{
"table_description": "整张表的一句话业务说明(原说明够用就填空串)",
"columns": [
{"name": "物理列名", "description": "", "synonyms": ["同义词1","同义词2"], "role": "dimension|measure"}
]
}"""
USER = """表名:{table}
表说明:{table_desc}
预估行数:{rows}
列(共 {n} 列):
{columns}
请输出 JSON。"""
def _fmt_columns(cols: list[dict]) -> str:
lines = []
for c in cols:
name = c["physical_column"] or c["name"]
parts = [f"- {name} 类型 {c['data_type']}"]
if c.get("description"):
parts.append(f" 现有说明:{c['description']}")
if c.get("sample_values"):
parts.append(" 取值示例:" + "、".join(str(v) for v in c["sample_values"][:8]))
lines.append("".join(parts))
return "\n".join(lines)
def draft_for_model(model: dict, overwrite: bool = False) -> dict:
"""给一张表起草。返回 {updated_columns, table_description, dropped}。"""
cols = [c for c in model.get("columns", []) if c.get("enabled", True)]
if not cols:
return {"updated_columns": 0, "table_description": "", "dropped": 0}
allowed = {(c["physical_column"] or c["name"]).lower(): c for c in cols}
updated = 0
dropped = 0
table_desc = ""
for i in range(0, len(cols), COLUMNS_PER_BATCH):
batch = cols[i:i + COLUMNS_PER_BATCH]
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": USER.format(
table=model["physical_table"] or model["name"],
table_desc=model.get("description") or "(无)",
rows=model.get("row_count_est") or 0,
n=len(batch), columns=_fmt_columns(batch))},
]
try:
out = llm.chat_json(messages, temperature=0.2)
except Exception as e: # noqa: BLE001
log.warning("起草 %s 第 %d 批失败:%s", model["physical_table"], i // COLUMNS_PER_BATCH, str(e)[:200])
continue
if not isinstance(out, dict):
continue
if not table_desc and isinstance(out.get("table_description"), str):
table_desc = out["table_description"].strip()
for item in out.get("columns") or []:
if not isinstance(item, dict):
continue
name = str(item.get("name") or "").lower()
col = allowed.get(name)
if col is None:
# 模型编出来的列。丢掉并记数 —— 让幻觉列进语义层比没描述更糟
dropped += 1
continue
fields: dict = {}
syn = [s.strip() for s in (item.get("synonyms") or [])
if isinstance(s, str) and s.strip()]
# 去掉把列名原样抄回来的"同义词",那是噪声
syn = [s for s in syn if s.lower() != name][:6]
if syn and (overwrite or not col.get("synonyms")):
fields["synonyms"] = syn
desc = str(item.get("description") or "").strip()
if desc and (overwrite or not (col.get("description") or "").strip()):
fields["description"] = desc[:1000]
role = str(item.get("role") or "").lower()
if role in ("measure", "dimension"):
is_measure = 1 if role == "measure" else 0
if bool(col.get("is_measure")) != bool(is_measure):
fields["is_measure"] = is_measure
fields["is_dimension"] = 0 if is_measure else 1
if fields:
semantic.update_column(col["id"], **fields)
updated += 1
if table_desc and (overwrite or not (model.get("description") or "").strip()):
semantic.update_model(model["id"], description=table_desc[:1000])
return {"updated_columns": updated, "table_description": table_desc, "dropped": dropped}
def run_describe(ds_id: int, overwrite: bool = False,
model_ids: list[int] | None = None) -> Iterator[dict]:
"""生成器:给 jobs/queue 用。默认只处理已启用的表。"""
models = semantic.models_with_columns(ds_id, enabled_only=True)
if model_ids:
wanted = set(model_ids)
models = [m for m in models if m["id"] in wanted]
if not models:
yield {"stage": "error", "error": "没有已启用的表。请先在建模页勾选要参与问答的表。"}
return
yield {"stage": "start", "progress": 2,
"message": f"准备为 {len(models)} 张表起草描述与同义词…"}
total_updated = 0
total_dropped = 0
for i, m in enumerate(models, 1):
res = draft_for_model(m, overwrite=overwrite)
total_updated += res["updated_columns"]
total_dropped += res["dropped"]
yield {"stage": "describe", "progress": 2 + int(i / len(models) * 96),
"i": i, "total": len(models),
"message": f"{m['physical_table']}:补了 {res['updated_columns']} 列"
+ (f"(丢弃 {res['dropped']} 个不存在的列)" if res["dropped"] else "")}
msg = f"起草完成:{len(models)} 张表,共补充 {total_updated} 列的说明与同义词。"
if total_dropped:
msg += f" 丢弃了 {total_dropped} 个模型编造的列。"
msg += " 建议到建模页抽查几列,改掉不准的地方。"
yield {"stage": "done", "progress": 100, "message": msg,
"stats": {"models": len(models), "updated": total_updated, "dropped": total_dropped}}