同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。 补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。 统一午夜黑及其他主题的控件细节、中文和业务数字字体。 排除本地业务数据、凭据、预览、发布与验收产物。 验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
"""A bounded grammar for formal metric questions, separate from evidence proof.
|
||||
|
||||
Only understood product/period/stage/field tokens produce a request. Unknown
|
||||
scope or analysis words leave the native analysis path in charge. This module
|
||||
never obtains metrics, interprets model prose, or reuses historical evidence.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from nao_evidence_report import _filters
|
||||
|
||||
_MONTH = re.compile(r'(?<!\d)(?:(\d{4})年)?(1[0-2]|0?[1-9])月')
|
||||
_FIELDS = {
|
||||
'rate': ('合格率',),
|
||||
'scrapRate': ('报废率',),
|
||||
'totalWeight': ('投入重量', '投入量', '投入'),
|
||||
'scrapWeight': ('报废重量', '报废量'),
|
||||
}
|
||||
_STAGES = {'black': ('黑片',), 'bright': ('亮片',)}
|
||||
_CONNECTORS = (
|
||||
'正式数据依据', '正式统计数据', '正式数据', '数据依据', '分别是多少', '是多少',
|
||||
'帮我查一下', '帮我查询', '请帮我', '重新查询', '重新分析', '再次查询', '再查询',
|
||||
'查一下', '查询', '比较', '对比', '查看', '看一下', '换成', '换为', '改成',
|
||||
'再看', '只看', '仅看', '仅针对', '针对', '该规格', '这个规格', '该产品', '这个产品',
|
||||
'同样期间', '相同期间', '这两期', '这两个月', '两期', '分别', '给我',
|
||||
'多少', '数据', '请', '附', '与', '和', '及', '的', '在', '呢', '那', '也', '再',
|
||||
)
|
||||
_REMAINDER = re.compile(r'(?:' + '|'.join(re.escape(token) for token in sorted(_CONNECTORS, key=len, reverse=True))
|
||||
+ r'|[,,;;。!?!?、::\s])*')
|
||||
_FRESH = re.compile(r'重新(?:查询|分析|查)|再次查询|再查询|再查(?:一下|一次)?|重查|刷新(?:数据|结果)')
|
||||
_RESTATE = re.compile(r'(?:请|帮我|把|将|刚才|上轮|上一轮|上次|的|结果|结论|回答|数据|再说一遍|再讲一遍|复述|总结|重复|一下|再|[,,。!?!?\s])+')
|
||||
_BARE_PRODUCT = re.compile(r'(?<![A-Za-z0-9])([A-Za-z0-9][A-Za-z0-9.+*/×_-]*)(?![A-Za-z0-9])')
|
||||
|
||||
|
||||
def requires_fresh_query(question: str) -> bool:
|
||||
return bool(_FRESH.search(question))
|
||||
|
||||
|
||||
def is_history_restatement(question: str) -> bool:
|
||||
return (not requires_fresh_query(question) and bool(re.search(r'再说一遍|再讲一遍|复述|总结|重复', question))
|
||||
and bool(_RESTATE.fullmatch(question.strip())))
|
||||
|
||||
|
||||
def frozen_metric_frame(context: Any) -> dict[str, Any]:
|
||||
"""Only user-visible query dimensions bind inheritance; prose is not state."""
|
||||
value = context if isinstance(context, dict) else {}
|
||||
selected = value.get('period') or value.get('currentPeriod') or value
|
||||
selected = selected if isinstance(selected, dict) else {}
|
||||
frame = {'filters': copy.deepcopy(_filters(value.get('filters') if isinstance(value.get('filters'), dict) else value))}
|
||||
bound_task = value.get('_agentTask')
|
||||
if isinstance(bound_task, dict) and isinstance(bound_task.get('filters'), dict) and 'columnFilters' in bound_task['filters']:
|
||||
frame['filters']['columnFilters'] = copy.deepcopy(bound_task['filters'].get('columnFilters') or [])
|
||||
elif isinstance(value.get('filters'), dict) and 'columnFilters' in value['filters']:
|
||||
frame['filters']['columnFilters'] = copy.deepcopy(value['filters'].get('columnFilters') or [])
|
||||
for name, period in (('period', selected), ('comparisonPeriod', value.get('comparisonPeriod'))):
|
||||
if isinstance(period, dict):
|
||||
parsed = {key: period[key] for key in ('year', 'month', 'quarter', 'monthStart', 'monthEnd') if period.get(key) is not None}
|
||||
if parsed: frame[name] = parsed
|
||||
if value.get('stage') in ('black', 'bright'): frame['stage'] = value['stage']
|
||||
if value.get('releaseId'): frame['releaseId'] = value['releaseId']
|
||||
return frame
|
||||
|
||||
|
||||
def _valid_request(value: Any) -> bool:
|
||||
if not isinstance(value, dict): return False
|
||||
periods = value.get('periods')
|
||||
return (isinstance(value.get('product'), str) and bool(value['product'])
|
||||
and isinstance(value.get('filters'), dict) and value['filters'].get('product') == value['product']
|
||||
and isinstance(periods, list) and len(periods) == 2 and periods[0] != periods[1]
|
||||
and all(isinstance(p, dict) and set(p) == {'year', 'month'}
|
||||
and type(p['year']) is int and 1900 <= p['year'] <= 2200
|
||||
and type(p['month']) is int and 1 <= p['month'] <= 12 for p in periods)
|
||||
and isinstance(value.get('stages'), list) and bool(value['stages'])
|
||||
and all(isinstance(item, str) for item in value['stages'])
|
||||
and set(value['stages']) <= set(_STAGES)
|
||||
and isinstance(value.get('fields'), list) and bool(value['fields'])
|
||||
and all(isinstance(item, str) for item in value['fields'])
|
||||
and set(value['fields']) <= set(_FIELDS))
|
||||
|
||||
|
||||
def resolve_metric_request(question: str, context: Any = None, previous: Any = None) -> dict[str, Any] | None:
|
||||
"""Resolve a complete request, optionally inheriting a verified prior intent.
|
||||
|
||||
The caller controls whether previous belongs to the same session and frozen
|
||||
input frame. Missing dimensions are not guessed from result rows or prose.
|
||||
"""
|
||||
if not isinstance(question, str) or is_history_restatement(question): return None
|
||||
text = question.strip()
|
||||
prior = previous if _valid_request(previous) else {}
|
||||
frozen = frozen_metric_frame(context)
|
||||
periods = []
|
||||
years = {p['year'] for p in prior.get('periods', [])}
|
||||
year = next(iter(years)) if len(years) == 1 else None
|
||||
if year is None and isinstance(frozen.get('period'), dict): year = frozen['period'].get('year')
|
||||
for match in _MONTH.finditer(text):
|
||||
year = int(match.group(1)) if match.group(1) else year
|
||||
if type(year) is not int or not 1900 <= year <= 2200: return None
|
||||
periods.append({'year': year, 'month': int(match.group(2))})
|
||||
text = _MONTH.sub('', text)
|
||||
text = re.sub(r'该规格|这个规格|该产品|这个产品', '', text)
|
||||
products = []
|
||||
# Explicit markers support Unicode names; bare identifiers support the usual
|
||||
# dimension/specification notation without treating arbitrary prose as a name.
|
||||
marked = re.compile(r'(?:只看|仅看|仅针对|针对|换成|换为|改成|规格|产品)\s*(?:规格|产品)?\s*'
|
||||
r'([A-Za-z0-9][A-Za-z0-9.+*/×_-]*|[「“\"]([^」”\"]+)[」”\"]|[^,,;;。!?!?、::\s的在]+)')
|
||||
def product_token(match):
|
||||
value = match.group(2) or match.group(1)
|
||||
# Reference words must inherit a verified intent, never become a product.
|
||||
if value in ('该规格', '这个规格', '该产品', '这个产品', '黑片', '亮片'):
|
||||
return match.group(0)
|
||||
products.append(value)
|
||||
return ''
|
||||
text = marked.sub(product_token, text)
|
||||
def bare_product(match):
|
||||
value = match.group(1)
|
||||
if not re.search(r'\d', value) or not re.search(r'[A-Za-z×]', value): return value
|
||||
products.append(value); return ''
|
||||
text = _BARE_PRODUCT.sub(bare_product, text)
|
||||
if len(products) > 1 or products and len(products[0]) > 100: return None
|
||||
product = products[0] if products else prior.get('product') or frozen['filters'].get('product')
|
||||
stages, fields = [], []
|
||||
for name, tokens in _STAGES.items():
|
||||
if any(token in text for token in tokens): stages.append(name)
|
||||
for token in tokens: text = text.replace(token, '')
|
||||
for name, tokens in _FIELDS.items():
|
||||
if any(token in text for token in tokens): fields.append(name)
|
||||
for token in tokens: text = text.replace(token, '')
|
||||
if not _REMAINDER.fullmatch(text): return None
|
||||
if not periods:
|
||||
if prior: periods = copy.deepcopy(prior['periods'])
|
||||
elif all(isinstance(frozen.get(key), dict) for key in ('period', 'comparisonPeriod')):
|
||||
periods = [frozen['period'], frozen['comparisonPeriod']]
|
||||
stages = stages or prior.get('stages') or ([frozen['stage']] if frozen.get('stage') else [])
|
||||
fields = fields or prior.get('fields') or []
|
||||
request = {'product': product, 'filters': {**frozen['filters'], 'product': product},
|
||||
'periods': periods, 'stages': list(stages), 'fields': list(fields)}
|
||||
if not _valid_request(request): return None
|
||||
request['periods'] = sorted(periods, key=lambda period: (period['year'], period['month']), reverse=True)
|
||||
return request
|
||||
|
||||
|
||||
def metric_request(question: str, context: Any = None) -> dict[str, Any] | None:
|
||||
"""Use a runtime-resolved intent only for its exact question and frame."""
|
||||
from nao_agent_task import task_from_context
|
||||
task = task_from_context(context, question)
|
||||
if task is not None:
|
||||
if task['kind'] != 'metrics': return None
|
||||
request = {'product': task['filters'].get('product'), 'filters': task['filters'],
|
||||
'periods': [task.get('period'), task.get('comparisonPeriod')],
|
||||
'stages': task['stages'], 'fields': task['fields']}
|
||||
return copy.deepcopy(request) if _valid_request(request) else None
|
||||
frozen = context if isinstance(context, dict) else {}
|
||||
resolved = frozen.get('_resolvedMetricRequest')
|
||||
if (isinstance(resolved, dict) and resolved.get('question') == question
|
||||
and resolved.get('frame') == frozen_metric_frame(frozen) and _valid_request(resolved.get('request'))):
|
||||
return copy.deepcopy(resolved['request'])
|
||||
return resolve_metric_request(question, context)
|
||||
|
||||
|
||||
def prepare_metric_context(question: str, context: Any, previous_record: Any = None) -> tuple[Any, dict[str, Any] | None]:
|
||||
"""Bind the current goal and only inherit across an unchanged input frame."""
|
||||
base = dict(context) if isinstance(context, dict) else {}
|
||||
base.pop('_resolvedMetricRequest', None)
|
||||
previous = previous_record if isinstance(previous_record, dict) else {}
|
||||
prior = previous.get('metricRequest') if previous.get('baseMetricFrame') == frozen_metric_frame(base) else None
|
||||
request = resolve_metric_request(question, base, prior)
|
||||
if not request: return context, None
|
||||
# An explicit new product/period is the current local goal; every other
|
||||
# frozen filter is retained. The release stays exactly as supplied.
|
||||
bound = {**base, 'period': request['periods'][0], 'comparisonPeriod': request['periods'][1],
|
||||
'filters': copy.deepcopy(request['filters'])}
|
||||
for key in ('year', 'month', 'quarter', 'monthStart', 'monthEnd', 'currentPeriod', 'stage'): bound.pop(key, None)
|
||||
if len(request['stages']) == 1: bound['stage'] = request['stages'][0]
|
||||
bound['_resolvedMetricRequest'] = {'question': question, 'frame': frozen_metric_frame(bound),
|
||||
'request': copy.deepcopy(request)}
|
||||
return bound, request
|
||||
Reference in New Issue
Block a user