Files
quality_analyse/scripts/analysis_query_visuals.py
T
lyun f1a2fbd494 统一:DSH 智能分析、Top100 与图表静默恢复
接入 DSH 专用运行时和对话界面,保留模型原始回答,支持会话分页、连续追问与显式报告。
补齐组合筛选、各维度 Top100、分组查询到排名图的转换,图表故障静默省略并基于保存数据自动恢复。
优化报告风格、图表顺序和表格换行,更新接入说明及构建输入。

验证:独立目录前后端构建通过;118 项 Java、102 项前端、102 项图表、14 项 DSH 应用和 13 项组合筛选检查通过。
仅提交相关源码、锁定依赖与测试;不包含凭据、会话、业务数据或本地产物。
2026-11-12 11:57:41 +08:00

90 lines
5.2 KiB
Python

"""Adapt grouped metric queries to the same charts as dedicated ranking tools.
Only saved, complete query rows are used. No model calls, business queries, rate
recalculation, or changes to the original answer are made here.
"""
from __future__ import annotations
import copy
import logging
import re
DIMENSIONS = {'department': '产业部', 'group': '业务分组', 'product': '产品'}
def grouped_metric_charts(document, task, turn_id):
from analysis_visuals import _chart, _chart_scope
from nao_agent_task import dimension_stages
from nao_quality_tools import _number, _row_composite_rate
from nao_weight_ranking import rank_response, ranking_chart
result = document.get('result', {})
dimension = result.get('view')
if (result.get('kind') != 'quality_metrics' or dimension not in DIMENSIONS
or dimension not in task.get('dimensions', [])
or task.get('comparisonRequired') or task.get('comparisonPeriod') or task.get('trendRequired')
or task.get('visualPreference') == 'none'):
return []
rows = result.get('rows')
if (not isinstance(rows, list) or not rows or result.get('rowsTruncated') is True
or result.get('rowCount') != len(rows) or result.get('rowsReturned', len(rows)) != len(rows)):
return []
keys = [row.get('key') for row in rows if isinstance(row, dict)]
if len(keys) != len(rows) or any(not isinstance(key, str) or not key for key in keys) or len(set(keys)) != len(keys):
return []
count = re.search(r'(?:top|前)\s*(\d+)', task.get('question', ''), re.I)
limit = task.get('limit', int(count[1]) if count else 100)
limit = min(100, max(1, limit)) if type(limit) is int else 100
period = result.get('period')
if not isinstance(period, dict):
return []
charts = []
for field in task.get('fields', []):
stages = dimension_stages(task, dimension, combined=False)
if field in ('rate', 'scrapRate'):
stages = task.get('stages') or ([None] if field == 'rate' else ['black', 'bright'])
for stage in stages:
try:
if field in ('totalWeight', 'scrapWeight'):
# The dedicated tool and a normal grouped query share all
# ranking, denominator, absent-stage and correction rules.
raw = {**result, 'context': {'rowCount': len(rows)}}
ranked = rank_response(raw, result.get('release') or {'id': result['releaseId']},
period, result.get('filters', {}), dimension, stage, field, limit)
chart = ranking_chart({**document, 'result': ranked}, turn_id, task)
if chart:
charts.append(chart)
continue
if field not in ('rate', 'scrapRate'):
continue
points = []
for row in rows[:limit]:
value = _row_composite_rate(row) if stage is None else _number((row.get(stage) or {}).get(field))
if value is None:
if stage and (row.get('coverage') or {}).get(stage + 'Rows') == 0:
points.append(None)
continue
raise ValueError('missing_published_rate')
if not 0 <= value <= 1:
raise ValueError('invalid_published_rate')
points.append(float(value))
if not any(value is not None for value in points):
continue
metric = ('composite_rate' if stage is None else stage + ('_rate' if field == 'rate' else '_scrap_rate'))
label = {None: '综合', 'black': '黑片', 'bright': '亮片'}[stage] + ('合格率' if field == 'rate' else '报废率')
required = (['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight']
if stage is None else [stage + ('_good_weight' if field == 'rate' else '_scrap_weight'), stage + '_total_weight'])
charts.append(_chart(turn_id=turn_id, chart_type='bar', title=DIMENSIONS[dimension] + label + '对照',
subtitle='同范围正式指标', unit='ratio',
categories=[{'key': row['key'], 'label': str(row.get('label') or row['key'])} for row in rows[:limit]],
series=[{'key': metric, 'label': label, 'values': points}], evidence_refs=[document['evidenceRef']],
required_fields=required, scope=_chart_scope(result.get('filters', {}), result['releaseId'], period, view=dimension, stage=stage),
period=copy.deepcopy(period), metric=metric, stage=stage, dimension=dimension, section_key=dimension,
coverage={'totalRows': len(rows), 'returnedRows': len(points), 'truncated': len(rows) > limit}))
except Exception as error:
# One broken optional series cannot discard healthy sibling
# charts. Log identifiers only, never source rows or secrets.
logging.getLogger(__name__).warning('query_chart_omitted dimension=%s field=%s stage=%s error=%s',
dimension, field, stage, type(error).__name__)
return charts