优化:按分析章节整合图表解读与完整报告导出
This commit is contained in:
+290
-67
@@ -17,7 +17,7 @@ from typing import Any
|
||||
|
||||
|
||||
VISUAL_SCHEMA_VERSION = 1
|
||||
MAX_VISUALS = 3
|
||||
MAX_VISUALS = 12
|
||||
MAX_BODY_BYTES = 256 * 1024
|
||||
MAX_RANK_ROWS = 10
|
||||
MAX_TREND_POINTS = 36
|
||||
@@ -51,7 +51,7 @@ _CONTROL = re.compile(r"[\x00-\x1f\x7f]")
|
||||
_EXPLICIT_CHART = re.compile(
|
||||
r"图表|画图|绘图|可视化|趋势图|柱状图|柱形图|竖向柱|纵向柱|折线图|条形图|横条图|"
|
||||
r"横向柱|水平柱|面积图|面积趋势|热力图|热图|环状图|环形图|环状|环形|甜甜圈|饼图|"
|
||||
r"构成|占比|排名图|柏拉图|帕累托|pareto"
|
||||
r"构成|占比|排名图|柏拉图|帕累托|pareto|瀑布图|waterfall"
|
||||
)
|
||||
_NO_CHART = re.compile(r"不画图|不要(?:绘图|图表?|可视化|配图)|不需要(?:绘图|图表?|可视化|配图)|无需(?:绘图|图表|配图)|只要(?:文字|文本)|仅需(?:文字|文本)")
|
||||
_HORIZONTAL_BAR = re.compile(r"横向条形图|横条图|横向柱|水平条形图|水平柱|horizontal\s+bar", re.IGNORECASE)
|
||||
@@ -60,6 +60,7 @@ _AREA_CHART = re.compile(r"面积图|面积趋势|area\s+chart", re.IGNORECASE)
|
||||
_HEATMAP_CHART = re.compile(r"热力图|热图|heat\s*map", re.IGNORECASE)
|
||||
_DONUT_CHART = re.compile(r"环状图|环形图|环状|环形|甜甜圈|饼图|构成|占比|donut|doughnut|pie\s+chart", re.IGNORECASE)
|
||||
_PARETO_CHART = re.compile(r"柏拉图|帕累托|pareto", re.IGNORECASE)
|
||||
_WATERFALL_CHART = re.compile(r"瀑布图|waterfall", re.IGNORECASE)
|
||||
_LINE_CHART = re.compile(r"折线图|折线趋势|line\s+chart", re.IGNORECASE)
|
||||
_BAR_CHART = re.compile(r"条形图|bar\s+chart", re.IGNORECASE)
|
||||
_NEGATED_STYLE_PREFIX = re.compile(r"(?:不要|不用|无需|不需要|不画|不想要)\s*(?:使用|用|画)?\s*$")
|
||||
@@ -211,6 +212,18 @@ def _chart_scope(filters: dict[str, Any], release_id: str, period: dict[str, Any
|
||||
return clean
|
||||
|
||||
|
||||
def _scope_caption(scope: dict[str, Any]) -> str | None:
|
||||
labels = (("department", "产业部"), ("group", "业务分组"), ("product", "产品"),
|
||||
("category", "类别"), ("defect", "具体缺陷"))
|
||||
parts = []
|
||||
for key, label in labels:
|
||||
value = _safe_text(scope.get(key), limit=80)
|
||||
if value:
|
||||
parts.append(f"{label}:{value}")
|
||||
caption = ",".join(parts)
|
||||
return caption[:200] if caption else None
|
||||
|
||||
|
||||
def _period(value: Any) -> tuple[dict[str, int] | None, str | None, tuple[int, int, int] | None]:
|
||||
if not isinstance(value, dict):
|
||||
return None, None, None
|
||||
@@ -298,6 +311,8 @@ def _chart(
|
||||
metric: str,
|
||||
coverage: dict[str, Any],
|
||||
note: str | None = None,
|
||||
section_key: str | None = None,
|
||||
dimension: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
chart: dict[str, Any] = {
|
||||
"type": chart_type,
|
||||
@@ -319,6 +334,11 @@ def _chart(
|
||||
chart["comparisonPeriod"] = comparison_period
|
||||
if stage in ("black", "bright"):
|
||||
chart["stage"] = stage
|
||||
if section_key in {"overview", "stage", "department", "group", "product", "category_black",
|
||||
"category_bright", "defect_black", "defect_bright", "trend", "composition"}:
|
||||
chart["sectionKey"] = section_key
|
||||
if dimension in {"department", "group", "product", "category", "defect"}:
|
||||
chart["dimension"] = dimension
|
||||
if note:
|
||||
chart["note"] = note[:240]
|
||||
identity = dict(chart)
|
||||
@@ -388,16 +408,18 @@ def _comparison_charts(document: dict[str, Any], result: dict[str, Any], turn_id
|
||||
{"key": "comparison", "label": comparison_label},
|
||||
{"key": "current", "label": current_label},
|
||||
]
|
||||
asked_black, asked_bright = "黑片" in question, "亮片" in question
|
||||
explicit_stage_only = (asked_black or asked_bright) and not re.search(r"综合|总体", question)
|
||||
asked_black = bool(re.search(r"黑片.{0,8}(?:合格率|不良率|率)|(?:合格率|不良率|率).{0,8}黑片", question))
|
||||
asked_bright = bool(re.search(r"亮片.{0,8}(?:合格率|不良率|率)|(?:合格率|不良率|率).{0,8}亮片", question))
|
||||
broad_overall = bool(re.search(r"原因|整体分析|总体分析|整体|总体|不良率|综合质量", question))
|
||||
explicit_stage_only = (asked_black or asked_bright) and not re.search(r"综合|总体|整体", question)
|
||||
metrics: list[tuple[str, str | None, str, Any, Any, str]] = []
|
||||
if not explicit_stage_only:
|
||||
metrics.append(("composite_rate", None, "综合合格率", comparison.get("compositeRate"), current.get("compositeRate"), "composite_rate"))
|
||||
stage_changes = result.get("stageRateChangesPP")
|
||||
requested_stages = []
|
||||
if asked_black:
|
||||
if asked_black or broad_overall and not explicit_stage_only:
|
||||
requested_stages.append(("black", "黑片合格率", "black_rate"))
|
||||
if asked_bright:
|
||||
if asked_bright or broad_overall and not explicit_stage_only:
|
||||
requested_stages.append(("bright", "亮片合格率", "bright_rate"))
|
||||
for stage, label, metric in requested_stages:
|
||||
old_side, now_side = comparison.get(stage), current.get(stage)
|
||||
@@ -433,6 +455,136 @@ def _comparison_charts(document: dict[str, Any], result: dict[str, Any], turn_id
|
||||
stage=stage,
|
||||
metric=metric,
|
||||
coverage={"totalRows": 2, "returnedRows": 2, "truncated": False},
|
||||
section_key="overview" if metric == "composite_rate" else "stage",
|
||||
))
|
||||
return charts
|
||||
|
||||
|
||||
def _comparison_waterfall(document: dict[str, Any], result: dict[str, Any], turn_id: str,
|
||||
question: str) -> dict[str, Any] | None:
|
||||
"""Use the service's balanced decomposition for math-only attribution."""
|
||||
if result.get("kind") != "quality_comparison" or not re.search(
|
||||
r"原因|整体分析|总体分析|拆解|分解|归因|为什么", question):
|
||||
return None
|
||||
release_id = _release_id(document, result)
|
||||
scope, _ = _scope(result.get("filterBinding"))
|
||||
current, comparison = result.get("current"), result.get("comparison")
|
||||
delta, decomposition = result.get("delta"), result.get("stageDecomposition")
|
||||
if (release_id is None or scope is None or not isinstance(current, dict)
|
||||
or not isinstance(comparison, dict) or not isinstance(delta, dict)
|
||||
or delta.get("available") is not True or not isinstance(decomposition, dict)
|
||||
or decomposition.get("status") != "available"):
|
||||
return None
|
||||
period, current_label, _ = _period(current.get("period"))
|
||||
comparison_period, comparison_label, _ = _period(comparison.get("period"))
|
||||
if (period is None or comparison_period is None or period == comparison_period
|
||||
or not _scope_compatible(scope, release_id, period=period)):
|
||||
return None
|
||||
values = []
|
||||
for field in ("blackContributionToCompositePP", "brightContributionToCompositePP", "sumPP"):
|
||||
value, valid = _finite_number(decomposition.get(field))
|
||||
if not valid or value is None or abs(value) > 100:
|
||||
return None
|
||||
values.append(value)
|
||||
reported_delta, delta_valid = _finite_number(delta.get("percentagePoints"))
|
||||
if not delta_valid or reported_delta is None or abs(reported_delta) > 100:
|
||||
return None
|
||||
if not math.isclose(values[0] + values[1], values[2], rel_tol=1e-10, abs_tol=1e-6):
|
||||
return None
|
||||
if not math.isclose(values[2], reported_delta, rel_tol=1e-10, abs_tol=1e-6):
|
||||
return None
|
||||
refs = [_evidence_ref(document)] if _evidence_ref(document) else []
|
||||
return _chart(
|
||||
turn_id=turn_id,
|
||||
chart_type="waterfall",
|
||||
title="综合合格率变化的数学影响拆解",
|
||||
subtitle=f"{comparison_label} → {current_label};展示两阶段对正式综合率变化的数学影响。",
|
||||
unit="pp",
|
||||
categories=[
|
||||
{"key": "black", "label": "黑片数学影响"},
|
||||
{"key": "bright", "label": "亮片数学影响"},
|
||||
{"key": "total", "label": "合计"},
|
||||
],
|
||||
series=[{"key": "composite_impact_pp", "label": "对综合合格率变化的数学影响(pp)", "values": values}],
|
||||
evidence_refs=refs,
|
||||
required_fields=["black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight"],
|
||||
scope=_chart_scope(scope, release_id, period),
|
||||
period=period,
|
||||
comparison_period=comparison_period,
|
||||
metric="composite_impact_pp",
|
||||
coverage={"totalRows": 3, "returnedRows": 3, "truncated": False},
|
||||
note="仅为正式合格率变化的数学拆解,不代表生产根因。",
|
||||
section_key="overview",
|
||||
)
|
||||
|
||||
|
||||
def _comparison_category_delta_charts(document: dict[str, Any], result: dict[str, Any], turn_id: str,
|
||||
question: str) -> list[dict[str, Any]]:
|
||||
if (result.get("kind") != "quality_comparison"
|
||||
or not re.search(r"原因|整体分析|总体分析|报废类别|类别增减|正式类别", question)):
|
||||
return []
|
||||
release_id = _release_id(document, result)
|
||||
scope, _ = _scope(result.get("filterBinding"))
|
||||
current, comparison = result.get("current"), result.get("comparison")
|
||||
if release_id is None or scope is None or not isinstance(current, dict) or not isinstance(comparison, dict):
|
||||
return []
|
||||
current_period, current_label, _ = _period(current.get("period"))
|
||||
comparison_period, comparison_label, _ = _period(comparison.get("period"))
|
||||
if (current_period is None or comparison_period is None or current_period == comparison_period
|
||||
or scope.get("category") not in (None, "") or scope.get("defect") not in (None, "")):
|
||||
return []
|
||||
charts: list[dict[str, Any]] = []
|
||||
for stage in ("black", "bright"):
|
||||
if not _scope_compatible(scope, release_id, period=current_period, stage=stage):
|
||||
continue
|
||||
now_side, old_side = current.get(stage), comparison.get(stage)
|
||||
if not isinstance(now_side, dict) or not isinstance(old_side, dict):
|
||||
continue
|
||||
now_defs, old_defs = now_side.get("defects"), old_side.get("defects")
|
||||
expected = _DEFECT_FIELDS[stage]
|
||||
if not isinstance(now_defs, list) or not isinstance(old_defs, list):
|
||||
continue
|
||||
|
||||
def read_formal(items: list[Any]) -> dict[str, float] | None:
|
||||
parsed: dict[str, float] = {}
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
label = _safe_text(item.get("name"), limit=80)
|
||||
field = expected.get(label) if label is not None else None
|
||||
weight, valid = _valid_weight(item.get("weight"))
|
||||
if field is None or not valid or weight is None or field in parsed:
|
||||
return None
|
||||
parsed[field] = weight
|
||||
return parsed
|
||||
|
||||
now_values, old_values = read_formal(now_defs), read_formal(old_defs)
|
||||
if (now_values is None or old_values is None or set(now_values) != set(expected.values())
|
||||
or set(old_values) != set(expected.values()) or sum(now_values.values()) + sum(old_values.values()) <= 0):
|
||||
continue
|
||||
ordered = list(expected.items())
|
||||
labels, fields = [item[0] for item in ordered], [item[1] for item in ordered]
|
||||
values = [now_values[field] - old_values[field] for field in fields]
|
||||
stage_label = "黑片" if stage == "black" else "亮片"
|
||||
charts.append(_chart(
|
||||
turn_id=turn_id,
|
||||
chart_type="bar",
|
||||
title=f"{stage_label}正式报废类别重量增减",
|
||||
subtitle=f"{comparison_label} → {current_label};按正式类别逐项相减,正负方向均保留。",
|
||||
unit="kg",
|
||||
categories=[{"key": field, "label": label} for field, label in zip(fields, labels)],
|
||||
series=[{"key": "source_defect_delta_weight", "label": "报废重量增减(kg)", "values": values}],
|
||||
evidence_refs=[_evidence_ref(document)] if _evidence_ref(document) else [],
|
||||
required_fields=fields,
|
||||
scope=_chart_scope(scope, release_id, current_period, view="overall", stage=stage),
|
||||
period=current_period,
|
||||
comparison_period=comparison_period,
|
||||
stage=stage,
|
||||
metric="source_defect_delta_weight",
|
||||
coverage={"totalRows": len(fields), "returnedRows": len(fields), "truncated": False},
|
||||
note="展示正式报废类别各自的期间增减,不代表总体合格率贡献。",
|
||||
section_key=f"category_{stage}",
|
||||
dimension="category",
|
||||
))
|
||||
return charts
|
||||
|
||||
@@ -501,6 +653,8 @@ def _formal_donut_chart(
|
||||
coverage={"totalRows": count, "returnedRows": count, "truncated": False,
|
||||
"shareBasis": "displayed_categories"},
|
||||
note="占比按本图已列类别重量合计计算,不代表正式报废总量占比。",
|
||||
section_key="composition",
|
||||
dimension="category",
|
||||
)
|
||||
|
||||
|
||||
@@ -592,6 +746,8 @@ def _share_chart_from_top_chart(chart: dict[str, Any], document: dict[str, Any],
|
||||
result_chart["requiredFields"] = [category["key"] for category in categories]
|
||||
result_chart["coverage"] = {"totalRows": len(categories), "returnedRows": len(categories),
|
||||
"truncated": False, "shareBasis": "displayed_categories"}
|
||||
result_chart["sectionKey"] = "composition"
|
||||
result_chart["dimension"] = "category"
|
||||
result_chart.pop("id", None)
|
||||
result_chart["id"] = _visual_id(turn_id, result_chart)
|
||||
return result_chart
|
||||
@@ -718,11 +874,13 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
|
||||
"returnedRows": len(selected),
|
||||
"truncated": truncated or len(selected) < len(row_info),
|
||||
}
|
||||
scope_caption = _scope_caption(scope)
|
||||
return _chart(
|
||||
turn_id=turn_id,
|
||||
chart_type="bar",
|
||||
title=title,
|
||||
subtitle=f"{comparison_label} → {current_label};按接口返回排名,展示前 {len(selected)} 项。",
|
||||
subtitle=(f"范围 {scope_caption};" if scope_caption else "")
|
||||
+ f"{comparison_label} → {current_label};按接口返回排名,展示前 {len(selected)} 项。",
|
||||
unit=unit,
|
||||
categories=categories,
|
||||
series=[{"key": metric, "label": label, "values": values}],
|
||||
@@ -736,6 +894,8 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
|
||||
metric=metric,
|
||||
coverage=coverage,
|
||||
note=note,
|
||||
section_key={"product": "product", "group": "group", "department": "department"}[result["dimension"]],
|
||||
dimension=result["dimension"],
|
||||
)
|
||||
|
||||
|
||||
@@ -967,6 +1127,10 @@ def _top_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str) -
|
||||
coverage={"totalRows": groups, "returnedRows": selected,
|
||||
"truncated": len(categories) < groups or len(categories) > MAX_RANK_ROWS},
|
||||
note=note,
|
||||
section_key=(f"category_{stage}" if dimension == "category" else
|
||||
{"product": "product", "group": "group", "department": "department"}.get(dimension, "group")),
|
||||
dimension=("group" if dimension == "projectGroup" else
|
||||
dimension if dimension in ("product", "group", "department", "category") else None),
|
||||
)
|
||||
|
||||
|
||||
@@ -1156,11 +1320,13 @@ def _fine_defect_chart(document: dict[str, Any], result: dict[str, Any], turn_id
|
||||
"returnedRows": len(categories),
|
||||
"truncated": truncated or len(categories) < len(source_rows),
|
||||
}
|
||||
scope_caption = _scope_caption(scope)
|
||||
return _chart(
|
||||
turn_id=turn_id,
|
||||
chart_type="bar",
|
||||
title=f"{stage_label}{title}",
|
||||
subtitle=(f"{comparison_label} → {period_label};" if comparison_label else f"{period_label};")
|
||||
subtitle=(f"范围 {scope_caption};" if scope_caption else "")
|
||||
+ (f"{comparison_label} → {period_label};" if comparison_label else f"{period_label};")
|
||||
+ "按来源字段排序,缺失增量保留为空。",
|
||||
unit=unit,
|
||||
categories=categories[:MAX_RANK_ROWS],
|
||||
@@ -1176,6 +1342,8 @@ def _fine_defect_chart(document: dict[str, Any], result: dict[str, Any], turn_id
|
||||
coverage={**coverage, "returnedRows": min(len(categories), MAX_RANK_ROWS),
|
||||
"truncated": coverage["truncated"] or len(categories) > MAX_RANK_ROWS},
|
||||
note=note,
|
||||
section_key=f"defect_{result['stage']}",
|
||||
dimension="defect",
|
||||
)
|
||||
|
||||
|
||||
@@ -1289,6 +1457,7 @@ def _trend_chart_from_points(
|
||||
stage=stage,
|
||||
metric=metric,
|
||||
coverage={"totalRows": len(expanded), "returnedRows": len(expanded), "truncated": False},
|
||||
section_key="trend",
|
||||
))
|
||||
if re.search(r"重量|报废|废品|kg|公斤", question, re.IGNORECASE):
|
||||
weight_stages = [("black", "黑片报废重量"), ("bright", "亮片报废重量")]
|
||||
@@ -1326,6 +1495,7 @@ def _trend_chart_from_points(
|
||||
metric=metric,
|
||||
coverage={"totalRows": len(expanded), "returnedRows": len(expanded), "truncated": False},
|
||||
note="黑片与亮片分开;不合并为单阶段投入分母。",
|
||||
section_key="trend",
|
||||
))
|
||||
return charts
|
||||
|
||||
@@ -1437,6 +1607,7 @@ def _requested_chart_type(question: str) -> str | None:
|
||||
for pattern, chart_type in (
|
||||
(_COLUMN_CHART, "column"), (_AREA_CHART, "area"), (_HEATMAP_CHART, "heatmap"),
|
||||
(_DONUT_CHART, "donut"), (_LINE_CHART, "line"), (_BAR_CHART, "bar"),
|
||||
(_WATERFALL_CHART, "waterfall"),
|
||||
):
|
||||
match = first_unnegated(pattern)
|
||||
if match:
|
||||
@@ -1500,52 +1671,68 @@ def _chart_end_rank(chart: dict[str, Any]) -> tuple[int, int, int]:
|
||||
|
||||
|
||||
def _candidate_priority(chart: dict[str, Any], kind: str, dimension: str | None, question: str) -> int:
|
||||
wants_trend = "趋势" in question
|
||||
if chart.get("type") == "line":
|
||||
if re.search(r"重量|报废|废品|kg|公斤", question, re.IGNORECASE) and chart.get("metric") == "current_scrap_weight":
|
||||
return 0
|
||||
if not wants_trend:
|
||||
return 6
|
||||
return {"composite_rate": 0, "black_rate": 1, "bright_rate": 2}.get(chart.get("metric"), 6)
|
||||
if kind == "quality_comparison":
|
||||
# A stage mentioned as the scope of a defect question should not displace
|
||||
# the explicitly requested product and defect charts from the three slots.
|
||||
if (chart.get("metric") != "composite_rate"
|
||||
and re.search(r"综合|总体", question)
|
||||
and re.search(r"产品|规格", question)
|
||||
and re.search(r"缺陷", question)):
|
||||
return 8
|
||||
return 1 if wants_trend else (0 if chart.get("metric") == "composite_rate" else 1)
|
||||
if kind == "quality_changes":
|
||||
requested_dimension = None
|
||||
if re.search(r"产品|规格", question):
|
||||
requested_dimension = "product"
|
||||
elif "分组" in question:
|
||||
requested_dimension = "group"
|
||||
elif re.search(r"产业部|部门", question):
|
||||
requested_dimension = "department"
|
||||
base = {"product": 10, "group": 20, "department": 30}.get(dimension, 40)
|
||||
if requested_dimension == dimension:
|
||||
base = 4
|
||||
if re.search(r"合格率|降幅|下降", question) and chart.get("metric") == "rate_drop_pp":
|
||||
base -= 1
|
||||
if re.search(r"报废|增量|重量", question) and chart.get("metric") in ("scrap_delta", "current_scrap_weight"):
|
||||
base -= 1
|
||||
return base
|
||||
"""Choose chapter-relevant views without letting incidental rankings lead."""
|
||||
metric = chart.get("metric")
|
||||
section = chart.get("sectionKey")
|
||||
requested_dimension = None
|
||||
if re.search(r"产品|规格", question):
|
||||
requested_dimension = "product"
|
||||
elif "分组" in question:
|
||||
requested_dimension = "group"
|
||||
elif re.search(r"产业部|部门", question):
|
||||
requested_dimension = "department"
|
||||
broad_cause = bool(re.search(r"原因|分析|拆解|分解|归因", question))
|
||||
explicit_rate_rank = bool(re.search(r"率降幅|合格率变化排名|率下降排名|排名.*合格率", question))
|
||||
if metric == "current_scrap_weight" and re.search(r"重量|报废|废品|kg|公斤", question, re.IGNORECASE):
|
||||
return 0 if "趋势" in question else 3
|
||||
scope = chart.get("scope") if isinstance(chart.get("scope"), dict) else {}
|
||||
scope_specificity = sum(scope.get(key) not in (None, "", [], {}) for key in (
|
||||
"department", "group", "product", "category", "defect"
|
||||
))
|
||||
|
||||
if chart.get("type") in ("donut", "pareto") or section == "composition":
|
||||
return 0
|
||||
if chart.get("type") in ("line", "area", "heatmap") or section == "trend":
|
||||
if "趋势" in question:
|
||||
return {"composite_rate": 0, "black_rate": 1, "bright_rate": 2,
|
||||
"current_scrap_weight": 3}.get(metric, 5)
|
||||
return 8
|
||||
if metric == "composite_rate" and section == "overview":
|
||||
return 0
|
||||
if metric == "composite_impact_pp":
|
||||
return 1 if broad_cause else 5
|
||||
if section == "stage":
|
||||
return 2 if broad_cause or re.search(r"黑片|亮片|阶段", question) else 6
|
||||
if metric == "rate_drop_pp":
|
||||
if explicit_rate_rank:
|
||||
return 2
|
||||
if broad_cause:
|
||||
return {"department": 3, "group": 4}.get(section, 20)
|
||||
return {"department": 7, "group": 8}.get(section, 20)
|
||||
if section == "product" or kind == "quality_top" and dimension == "product":
|
||||
if requested_dimension == "product":
|
||||
return 3 if metric in ("scrap_delta", "current_scrap_weight") else 4
|
||||
return 4 if metric in ("scrap_delta", "current_scrap_weight") else 10
|
||||
if section == "department" or kind == "quality_top" and dimension == "department":
|
||||
return 4 if metric in ("scrap_delta", "current_scrap_weight") else 6
|
||||
if section == "group" or kind == "quality_top" and dimension in ("group", "projectGroup"):
|
||||
return 5 if metric in ("scrap_delta", "current_scrap_weight") else 7
|
||||
if section in ("category_black", "category_bright"):
|
||||
return 5 if broad_cause or re.search(r"报废类别|类别增减|正式类别", question) else 9
|
||||
if section in ("defect_black", "defect_bright"):
|
||||
# 优先阶段汇总;局部追查图保留自身筛选范围,仍可作为补充视图。
|
||||
return 6 + min(scope_specificity, 3) + (0 if broad_cause else 2)
|
||||
if kind == "quality_top":
|
||||
requested_dimension = None
|
||||
if re.search(r"产品|规格", question):
|
||||
requested_dimension = "product"
|
||||
elif "分组" in question:
|
||||
requested_dimension = "group"
|
||||
elif re.search(r"产业部|部门", question):
|
||||
requested_dimension = "department"
|
||||
elif "项目组" in question:
|
||||
requested_dimension = "projectGroup"
|
||||
return 4 if requested_dimension == dimension else 12
|
||||
if kind == "quality_fine_defects":
|
||||
return 5 if re.search(r"缺陷|责废|料废|外废|加工废|镀废", question) else 15
|
||||
return 25
|
||||
return 4 if requested_dimension == dimension else 10
|
||||
return 12
|
||||
|
||||
|
||||
def _chart_selection_key(chart: dict[str, Any]) -> str:
|
||||
semantic = {key: chart.get(key) for key in (
|
||||
"type", "sectionKey", "dimension", "metric", "stage", "scope", "period", "comparisonPeriod",
|
||||
"categories", "series",
|
||||
)}
|
||||
return json.dumps(semantic, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
|
||||
def _finalize(charts: list[dict[str, Any]], turn_id: str, *, unavailable: bool = False) -> dict[str, Any]:
|
||||
@@ -1581,7 +1768,7 @@ def _finalize(charts: list[dict[str, Any]], turn_id: str, *, unavailable: bool =
|
||||
|
||||
|
||||
def build_visuals(evidence: list[dict[str, Any]], question: str, turn_id: str) -> dict[str, Any]:
|
||||
"""Return up to three safe chart snapshots from full trusted evidence docs.
|
||||
"""Return up to twelve safe chart snapshots from full trusted evidence docs.
|
||||
|
||||
The function is intentionally non-fatal: exceptions return a short error state
|
||||
so a caller can preserve the already completed textual analysis.
|
||||
@@ -1610,6 +1797,11 @@ def build_visuals(evidence: list[dict[str, Any]], question: str, turn_id: str) -
|
||||
dimension = result.get("dimension") if isinstance(result.get("dimension"), str) else None
|
||||
for chart in _comparison_charts(document, result, safe_turn_id, text_question):
|
||||
candidates.append((_candidate_priority(chart, kind, dimension, text_question), kind, dimension, chart))
|
||||
waterfall = _comparison_waterfall(document, result, safe_turn_id, text_question)
|
||||
if waterfall is not None:
|
||||
candidates.append((_candidate_priority(waterfall, kind, dimension, text_question), kind, dimension, waterfall))
|
||||
for chart in _comparison_category_delta_charts(document, result, safe_turn_id, text_question):
|
||||
candidates.append((_candidate_priority(chart, kind, dimension, text_question), kind, dimension, chart))
|
||||
for chart in _comparison_category_charts(document, result, safe_turn_id, text_question):
|
||||
candidates.append((_candidate_priority(chart, kind, dimension, text_question), kind, dimension, chart))
|
||||
for chart in _metrics_category_charts(document, result, safe_turn_id, text_question):
|
||||
@@ -1641,31 +1833,62 @@ def build_visuals(evidence: list[dict[str, Any]], question: str, turn_id: str) -
|
||||
continue
|
||||
styled_candidates.append((priority, kind, dimension, chart))
|
||||
candidates = styled_candidates
|
||||
candidates.sort(key=lambda item: (item[0], tuple(-part for part in _chart_end_rank(item[3])), item[3].get("id", "")))
|
||||
stage_order = {"black": 0, "bright": 1, None: 2}
|
||||
metric_order = {"composite_rate": 0, "black_rate": 1, "bright_rate": 2,
|
||||
"scrap_delta": 3, "source_defect_delta_weight": 4}
|
||||
def scope_depth(chart):
|
||||
scope = chart.get("scope") if isinstance(chart.get("scope"), dict) else {}
|
||||
return sum(scope.get(key) not in (None, "", [], {}) for key in ("department", "group", "product", "category", "defect"))
|
||||
|
||||
comparisons = [chart for _, _, _, chart in candidates if chart.get("metric") == "composite_rate" and chart.get("sectionKey") == "overview"]
|
||||
primary_depth = min((scope_depth(chart) for chart in comparisons), default=0)
|
||||
def chapter_priority(item):
|
||||
chart = item[3]
|
||||
# 产品追查比较不能挤占主体分析的类别、组织和缺陷图。
|
||||
extra_scope = max(0, scope_depth(chart) - primary_depth)
|
||||
section = chart.get("sectionKey", "")
|
||||
penalty = 20 * extra_scope if section in ("overview", "stage") or section.startswith("category_") else 0
|
||||
return item[0] + penalty
|
||||
|
||||
candidates.sort(key=lambda item: (
|
||||
chapter_priority(item), tuple(-part for part in _chart_end_rank(item[3])),
|
||||
stage_order.get(item[3].get("stage"), 3),
|
||||
metric_order.get(item[3].get("metric"), 10),
|
||||
item[3].get("sectionKey", ""), item[3].get("id", ""),
|
||||
))
|
||||
primary_chapters = []
|
||||
additional_views = []
|
||||
chapter_keys = set()
|
||||
for item in candidates:
|
||||
chart = item[3]
|
||||
section = chart.get("sectionKey")
|
||||
chapter_key = (section, chart.get("metric") if section in ("overview", "stage", "trend") else None,
|
||||
chart.get("type") if section == "composition" else None,
|
||||
chart.get("stage") if section == "composition" else None)
|
||||
if chapter_key in chapter_keys:
|
||||
additional_views.append(item)
|
||||
else:
|
||||
chapter_keys.add(chapter_key)
|
||||
primary_chapters.append(item)
|
||||
# 先覆盖各个可用章节,再分配同章不同范围的补充视图。
|
||||
candidates = primary_chapters + additional_views
|
||||
charts: list[dict[str, Any]] = []
|
||||
selected_ids: set[str] = set()
|
||||
selected_dimensions: set[str] = set()
|
||||
selected_defect_stages: set[str] = set()
|
||||
selected_semantics: set[str] = set()
|
||||
selected_share_stages: set[tuple[str, str]] = set()
|
||||
for _, kind, dimension, chart in candidates:
|
||||
chart_id = chart.get("id")
|
||||
if not isinstance(chart_id, str) or chart_id in selected_ids:
|
||||
continue
|
||||
semantic_key = _chart_selection_key(chart)
|
||||
if semantic_key in selected_semantics:
|
||||
continue
|
||||
share_stage = (chart.get("type"), chart.get("stage"))
|
||||
if chart.get("type") in ("donut", "pareto") and share_stage in selected_share_stages:
|
||||
continue
|
||||
if kind == "quality_changes" and dimension in selected_dimensions:
|
||||
continue
|
||||
if kind == "quality_fine_defects":
|
||||
stage = chart.get("stage")
|
||||
if stage in selected_defect_stages:
|
||||
continue
|
||||
charts.append(chart)
|
||||
selected_ids.add(chart_id)
|
||||
if kind == "quality_changes" and dimension:
|
||||
selected_dimensions.add(dimension)
|
||||
if kind == "quality_fine_defects" and chart.get("stage"):
|
||||
selected_defect_stages.add(chart["stage"])
|
||||
selected_semantics.add(semantic_key)
|
||||
if chart.get("type") in ("donut", "pareto"):
|
||||
selected_share_stages.add(share_stage)
|
||||
if len(charts) >= MAX_VISUALS:
|
||||
|
||||
@@ -47,32 +47,39 @@ def build_report(evidence):
|
||||
def fact(label,text,evidence_ref,kind):
|
||||
row={'id':'F'+str(len(facts)+1),'kind':kind,'label':label,'text':text,'evidenceRef':evidence_ref}
|
||||
facts.append(row);return row
|
||||
def table(title,headers,rows,evidence_ref,notice=''):
|
||||
def bound_lead(entries):
|
||||
return ' '.join(item['text']+'['+item['evidenceRef']+']' for item in entries)
|
||||
def table(title,headers,rows,evidence_ref,notice='',lead=''):
|
||||
if not rows:return
|
||||
sections.append('### '+title+'\n\n| '+' | '.join(headers)+' |\n| '+' | '.join(['---']*len(headers))+' |\n'
|
||||
sections.append('### '+title+'\n\n'+(lead+'\n\n' if lead else '')+'| '+' | '.join(headers)+' |\n| '+' | '.join(['---']*len(headers))+' |\n'
|
||||
+'\n'.join('| '+' | '.join(cell(v) for v in row)+' |' for row in rows)+'\n\n['+evidence_ref+']'+(' '+notice if notice else ''))
|
||||
delta=(result.get('delta') or {}).get('percentagePoints')
|
||||
headline=f'综合合格率:{a}{shown(previous.get("compositeRate"),True)}→{b}{shown(current.get("compositeRate"),True)},{change_text(delta)}。[{ref}]'
|
||||
fact('综合合格率',headline.split('。[')[0]+'。',ref,'overall')
|
||||
rows=[['综合合格率',shown(previous.get('compositeRate'),True),shown(current.get('compositeRate'),True),shown(delta,signed=True)+' pp' if number(delta) is not None else '不可比']]
|
||||
stage_leads=[]
|
||||
for stage,label in (('black','黑片'),('bright','亮片')):
|
||||
now=current.get(stage) or {};before=previous.get(stage) or {};rate_delta=(result.get('stageRateChangesPP') or {}).get(stage)
|
||||
rows.append([label+'合格率',shown(before.get('rate'),True),shown(now.get('rate'),True),shown(rate_delta,signed=True)+' pp' if number(rate_delta) is not None else '不可比'])
|
||||
fact(label+'合格率',f'{label}合格率:{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)},{change_text(rate_delta)}。',ref,'stage')
|
||||
stage_fact=fact(label+'合格率',f'{label}合格率:{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)},{change_text(rate_delta)}。',ref,'stage')
|
||||
if all(number(value) is not None for value in (before.get('rate'),now.get('rate'),rate_delta)):stage_leads.append(stage_fact)
|
||||
for key,name in (('totalWeight','投入重量'),('scrapWeight','报废重量')):
|
||||
rows.append([label+name,shown(before.get(key)),shown(now.get(key)),shown(difference(now.get(key),before.get(key)),signed=True)])
|
||||
table('总体与阶段',['指标',a,b,'变化'],rows,ref,'重量单位:kg;率变化单位:百分点(pp)。')
|
||||
rows=[]
|
||||
table('总体与阶段',['指标',a,b,'变化'],rows,ref,'重量单位:kg;率变化单位:百分点(pp)。',bound_lead(stage_leads))
|
||||
rows=[];category_leads=[]
|
||||
for stage,label in (('black','黑片'),('bright','亮片')):
|
||||
candidates=[]
|
||||
now=current.get(stage) or {};before=previous.get(stage) or {}
|
||||
old={x['name']:x.get('weight') for x in before.get('defects',[])}
|
||||
for item in now.get('defects',[]):
|
||||
name=item['name'];weight=item.get('weight');delta=difference(weight,old.get(name))
|
||||
rows.append([label+'·'+name,shown(old.get(name)),shown(weight),shown(delta,signed=True)])
|
||||
fact(label+'·'+name,f'{label}{name}:{shown(old.get(name))}→{shown(weight)} kg,增减{shown(delta,signed=True)} kg。',ref,'category')
|
||||
entry=fact(label+'·'+name,f'{label}{name}:{shown(old.get(name))}→{shown(weight)} kg,增减{shown(delta,signed=True)} kg。',ref,'category')
|
||||
if number(delta) is not None:candidates.append((abs(number(delta)),entry))
|
||||
if stage=='bright' and now.get('headquartersScrapWeight') is not None:
|
||||
rows.append(['亮片·本部报废',shown(before.get('headquartersScrapWeight')),shown(now.get('headquartersScrapWeight')),shown(difference(now.get('headquartersScrapWeight'),before.get('headquartersScrapWeight')),signed=True)])
|
||||
table('正式报废类别',['类别',a+'(kg)',b+'(kg)','增减(kg)'],rows,ref)
|
||||
if candidates:category_leads.append(max(candidates,key=lambda item:item[0])[1])
|
||||
table('正式报废类别',['类别',a+'(kg)',b+'(kg)','增减(kg)'],rows,ref,lead=('本次已列类别的变化线索:'+bound_lead(category_leads)) if category_leads else '')
|
||||
for document in evidence:
|
||||
q=document['result'];reference=document['evidenceRef']
|
||||
if q.get('kind')!='quality_changes':continue
|
||||
@@ -82,23 +89,26 @@ def build_report(evidence):
|
||||
rate_name=stage_name+'合格率' if stage_name else '综合率'
|
||||
weight_name=stage_name+'报废增量' if stage_name else '两阶段报废增量'
|
||||
if dimension in ('group','department') and same:
|
||||
rows=[]
|
||||
rows=[];leaders=[]
|
||||
for item in q.get('rows',[]):
|
||||
now=item.get('current') or {};before=item.get('comparison') or {};drop=number(item.get('rateDrop'));delta=-drop*100 if drop is not None else None
|
||||
label=str(item.get('label') or item.get('key'))
|
||||
rows.append([label,shown(before.get('rate'),True)+'→'+shown(now.get('rate'),True),shown(delta,signed=True) if delta is not None else '不可比',shown(item.get('scrapDelta'),signed=True)])
|
||||
fact(label,f'{label}:{rate_name}{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)},{change_text(delta)};{weight_name}{shown(item.get("scrapDelta"),signed=True)} kg。',reference,'group')
|
||||
entry=fact(label,f'{label}:{rate_name}{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)},{change_text(delta)};{weight_name}{shown(item.get("scrapDelta"),signed=True)} kg。',reference,'group')
|
||||
if drop is not None:leaders.append((drop,entry))
|
||||
lead=bound_lead([max(leaders,key=lambda item:(item[0]>0,abs(item[0])))[1]]) if leaders else ''
|
||||
table(stage_name+('业务分组变化' if dimension=='group' else '产业部变化'),['范围',rate_name+':比较期→本期','变化(pp)',weight_name+'(kg)'],rows,reference,
|
||||
'报废重量为两阶段描述,不作为单一阶段投入。' if not stage_name else '')
|
||||
'报废重量为两阶段描述,不作为单一阶段投入。' if not stage_name else '',('本次返回的组织中,'+lead) if lead else '')
|
||||
elif dimension=='product' and same:
|
||||
rows=[]
|
||||
rows=[];product_leads=[]
|
||||
for item in q.get('rows',[])[:5]:
|
||||
now=item.get('current') or {};before=item.get('comparison') or {};label=str(item.get('label') or item.get('key'))
|
||||
rows.append([label,shown(now.get('scrapWeight')),shown(item.get('scrapDelta'),signed=True),shown(before.get('rate'),True)+'→'+shown(now.get('rate'),True)])
|
||||
fact(label,f'{label}:{stage_name}报废{shown(before.get("scrapWeight"))}→{shown(now.get("scrapWeight"))} kg,增量{shown(item.get("scrapDelta"),signed=True)} kg;{rate_name}{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)}。',reference,'product')
|
||||
entry=fact(label,f'{label}:{stage_name}报废{shown(before.get("scrapWeight"))}→{shown(now.get("scrapWeight"))} kg,增量{shown(item.get("scrapDelta"),signed=True)} kg;{rate_name}{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)}。',reference,'product')
|
||||
product_leads.append(entry)
|
||||
order={'scrap_delta':'报废增量','current_scrap':'当前报废重量','rate_drop':'合格率降幅'}.get(q.get('sort'),'接口排序')
|
||||
table(stage_name+'重点产品(按'+order+',本次返回前5)',['规格','本期报废(kg)','增量(kg)',rate_name+':比较期→本期'],rows,reference,
|
||||
f'查询共有{q.get("totalRows","未知")}个对象,本节展示所返回排名的前5项。')
|
||||
f'查询共有{q.get("totalRows","未知")}个对象,本节展示所返回排名的前5项。',bound_lead(product_leads[:1]))
|
||||
vcm=False;cross=[]
|
||||
for document in evidence:
|
||||
q=document['result'];reference=document['evidenceRef']
|
||||
@@ -113,11 +123,13 @@ def build_report(evidence):
|
||||
usable.sort(key=lambda row:number(row['currentWeight']),reverse=True)
|
||||
same=scope(q.get('filters'))==binding
|
||||
if same and q.get('dimension')=='defect':
|
||||
rows=[]
|
||||
rows=[];defect_leads=[]
|
||||
for item in usable[:5]:
|
||||
label=str(item.get('field'));rows.append([label,shown(item.get('comparisonWeight')),shown(item.get('currentWeight')),shown(item.get('deltaWeight'),signed=True) if item.get('deltaAvailable') is True else '不可比'])
|
||||
fact(stage+'·'+label,f'{stage}{label}:{shown(item.get("comparisonWeight"))}→{shown(item.get("currentWeight"))} kg,增量{shown(item.get("deltaWeight"),signed=True) if item.get("deltaAvailable") is True else "不可比"}。',reference,'defect')
|
||||
table(stage+'来源具体缺陷(按本期重量,前5)',['源字段',a+'(kg)',b+'(kg)','增量(kg)'],rows,reference)
|
||||
entry=fact(stage+'·'+label,f'{stage}{label}:{shown(item.get("comparisonWeight"))}→{shown(item.get("currentWeight"))} kg,增量{shown(item.get("deltaWeight"),signed=True) if item.get("deltaAvailable") is True else "不可比"}。',reference,'defect')
|
||||
if item.get('deltaAvailable') is True and number(item.get('deltaWeight')) is not None:defect_leads.append((abs(number(item['deltaWeight'])),entry))
|
||||
lead=bound_lead([max(defect_leads,key=lambda item:item[0])[1]]) if defect_leads else ''
|
||||
table(stage+'来源具体缺陷(按本期重量,前5)',['源字段',a+'(kg)',b+'(kg)','增量(kg)'],rows,reference,lead=lead)
|
||||
elif usable:
|
||||
details=scope(q.get('filters'));label_prefix='·'.join(str(v) for k,v in details.items() if k in ('group','product'))
|
||||
for item in usable[:2]:
|
||||
|
||||
Reference in New Issue
Block a user