76 changed files with 5481 additions and 872 deletions

No files matched your search

+5 -1
View File
@@ -46,7 +46,7 @@ The exported workbook is not blank: it contains one `pre_item_master` sheet, 57
## What the app does
1. Upload `.xlsx` / `.xls` workbook.
1. Upload an `.xlsx` workbook.
2. Preview sheets before processing.
3. Recognize known workbook formats using fingerprints.
4. Analyze workbook structure with deterministic rules and optional LLM assistance.
@@ -56,6 +56,10 @@ The exported workbook is not blank: it contains one `pre_item_master` sheet, 57
8. Export a single-sheet Excel workbook named `pre_item_master_<timestamp>.xlsx`.
9. Optionally submit a Match Blueprint proposal for Admin review and future reuse.
Basic-user adjustments are bounded by `operator_review` settings and only change the current interpretation; they never edit the uploaded workbook, Type YAML, or SQL schema. Preview and Export are protected by a reviewed-snapshot hash, so any later Type, sheet, header, or mapping change requires fresh confirmation.
New workbook formats use a controlled learning workflow: privacy-safe evidence, explainable similarity scoring, full deterministic replay, Admin approval, version archive and rollback. See [Controlled Format Learning](docs/FORMAT_LEARNING.md).
## Architecture overview
```text
+1 -1
View File
@@ -46,7 +46,7 @@ kuji_bntw_2.xlsx -> type=kuji_tw, engine=hybrid, mappings=19, targets=14, rows=1
## App 功能
1. 上傳 `.xlsx` / `.xls` workbook。
1. 上傳 `.xlsx` workbook。
2. 處理前預覽 sheets。
3. 用 fingerprint 識別已知 workbook 格式。
4. 用 deterministic rules + optional LLM 分析 workbook 結構。
+26 -83
View File
@@ -14,7 +14,7 @@ import streamlit as st
# every user interaction, so all persistent values must live in session_state.
st.set_page_config(
page_title="NBD Pre-Item Master",
page_icon="📊",
page_icon=":material/table_view:",
layout="wide",
)
@@ -44,9 +44,9 @@ from ui.preview_page import render_preview_page
from ui.export_page import render_export_page
from ui.admin_page import render_admin_page
from ui.admin_auth import is_admin_unlocked, lock_admin, render_admin_unlock
from ui.app_chrome import apply_premium_theme, build_step_items, render_stepper
from ui.app_chrome import apply_premium_theme, render_stepper
from ui.copy import DEFAULT_LANGUAGE, t
from ui.workflow_state import initialize_workflow_state, reset_workflow_state
from ui.workflow_state import initialize_workflow_state, navigate_to, reset_workflow_state
apply_premium_theme()
@@ -54,43 +54,6 @@ apply_premium_theme()
if "config_manager" not in st.session_state:
st.session_state.config_manager = ConfigManager()
if "current_step" not in st.session_state:
st.session_state.current_step = "upload"
if "llm_status" not in st.session_state:
st.session_state.llm_status = None # None=unchecked, "online", "disabled", "unavailable"
def check_llm_status():
"""Check lightweight LLM reachability and update the sidebar badge."""
cm = st.session_state.config_manager
if not cm.get_llm_config().get("enabled", False):
st.session_state.llm_status = "disabled"
return
conn = cm.resolve_llm_connection_config()
if not conn:
st.session_state.llm_status = "unavailable"
return
try:
import requests
import urllib3
verify = conn.get("ssl_verify", False)
if not verify:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
url = conn["base_url"].rstrip("/") + "/models"
resp = requests.get(url, headers={
"Authorization": f"Bearer {conn['api_key']}",
}, timeout=5, verify=verify)
st.session_state.llm_status = "online" if resp.ok else "unavailable"
except Exception:
st.session_state.llm_status = "unavailable"
# Auto-check once on first load. The Recheck button below can refresh this later.
if st.session_state.llm_status is None:
check_llm_status()
# ── Session state keys used by the multi-page workflow ─────────────
initialize_workflow_state()
@@ -104,56 +67,39 @@ def reset_session():
lang = DEFAULT_LANGUAGE
workflow_busy = bool(st.session_state.get("ai_analysis_running"))
with st.sidebar:
st.markdown("### 📊 NBD Pre-Item Master")
st.markdown("### :material/table_view: NBD Pre-Item Master")
st.caption(t("sidebar.subtitle", lang))
active_step = st.session_state.current_step
if active_step == "upload" and st.session_state.get("parsed_workbook") is not None:
active_step = "type_select"
st.caption(t("sidebar.processing", lang))
for idx, item in enumerate(build_step_items(active_step, lang=lang), start=1):
state = item["state"]
icon = "●" if state == "current" else ("✓" if state == "done" else "○")
st.markdown(
f"<div class='nbd-wizard-item {state}'>"
f"<div class='nbd-wizard-title'>{icon} {idx}. {item['label']}</div>"
"</div>",
unsafe_allow_html=True,
)
st.divider()
cm = st.session_state.config_manager
if st.session_state.get("uploaded_file_name"):
st.badge("Workbook loaded", icon=":material/check_circle:", color="green")
st.caption(st.session_state.uploaded_file_name)
else:
st.badge("Waiting for upload", icon=":material/schedule:", color="gray")
if is_admin_unlocked():
status = st.session_state.llm_status
effective_llm = st.session_state.config_manager.resolve_llm_connection_config()
badges = {
"online": t("sidebar.llm_online", lang),
"disabled": t("sidebar.llm_disabled", lang),
"unavailable": t("sidebar.llm_unavailable", lang),
None: t("sidebar.llm_unknown", lang),
}
st.caption(f"🔐 {t('sidebar.admin_settings', lang)}")
st.markdown(f"**{badges.get(status, badges[None])}**")
effective_llm = cm.resolve_llm_connection_config()
st.caption(t("sidebar.admin_settings", lang))
st.badge(
"AI configured" if effective_llm else "AI not configured",
icon=":material/smart_toy:",
color="green" if effective_llm else "gray",
)
if effective_llm:
st.caption(t("sidebar.source_model", lang, model=effective_llm.get("model", "?")))
if st.button(t("sidebar.recheck", lang), key="llm_recheck", width="stretch", disabled=workflow_busy, icon=":material/refresh:"):
check_llm_status()
st.rerun()
if st.button(t("sidebar.type_config", lang), width="stretch", disabled=workflow_busy, icon=":material/category:"):
st.session_state.current_step = "admin_types"
navigate_to("admin_types")
st.rerun()
if st.button(t("sidebar.synonyms", lang), width="stretch", disabled=workflow_busy, icon=":material/dictionary:"):
st.session_state.current_step = "admin_synonyms"
navigate_to("admin_synonyms")
st.rerun()
if st.button(t("sidebar.ai_config", lang), width="stretch", disabled=workflow_busy, icon=":material/smart_toy:"):
st.session_state.current_step = "admin_llm"
navigate_to("admin_llm")
st.rerun()
if st.button(t("sidebar.blueprints", lang), width="stretch", disabled=workflow_busy, icon=":material/schema:"):
st.session_state.current_step = "admin_blueprints"
navigate_to("admin_blueprints")
st.rerun()
if st.button(t("sidebar.lock_admin", lang), width="stretch", disabled=workflow_busy, icon=":material/lock:"):
lock_admin()
st.session_state.current_step = "upload"
navigate_to("upload")
st.rerun()
elif render_admin_unlock(st.session_state.config_manager):
st.rerun()
@@ -167,25 +113,22 @@ with st.sidebar:
# ── Page router ───────────────────────────────────────────────────
def _optional_ai_route_available() -> bool:
"""Return True only when Optional AI pages may be entered."""
return (
st.session_state.llm_status == "online"
and st.session_state.config_manager.resolve_llm_connection_config() is not None
)
return st.session_state.config_manager.resolve_llm_connection_config() is not None
def _render_safe_review_or_upload() -> None:
"""Keep disabled AI routes from trapping the operator on an unreachable page."""
if st.session_state.get("parsed_workbook") is not None and st.session_state.get("basic_analysis_result") is not None:
st.session_state.current_step = "confirm"
navigate_to("confirm")
render_confirm_page()
else:
st.session_state.current_step = "upload"
navigate_to("upload")
render_upload_page()
step = st.session_state.current_step
if not step.startswith("admin_"):
render_stepper(active_step, lang=lang)
render_stepper(step, lang=lang)
st.space("small")
if step == "upload":
render_upload_page()
+30 -1
View File
@@ -10,6 +10,7 @@ fuzzy:
analysis:
low_confidence_warning_threshold: 40
require_confirmation_below_threshold: true
mapping_review_attention_threshold: 85
# AI-only mapping additions below this confidence are kept out of export mappings.
# They are not routed to any approval flow.
ai_auto_accept_mapping_threshold: 85
@@ -19,6 +20,32 @@ analysis:
enabled: true
dir: data/debug
max_string_chars: 12000
operator_review:
# Basic users only change the current interpretation; source files and YAML stay unchanged.
allow_sheet_selection: true
allow_type_override: true
allow_header_row_override: true
allow_column_mapping: true
allow_ignore_optional_fields: true
allow_restore_dropped_rows: true
# Use ["*"] for every SQL field, or list only fields operators may select.
mapping_target_allowlist:
- "*"
field_labels:
generated_barcode: Barcode / JAN code
sap: SAP item code
item_name_eng: English item name
item_name_jap: Japanese item name
package_size: Package size
pcs_ctn: Pieces per carton
learning:
enabled: true
evidence_dir: data/learning/evidence
retain_raw_samples: false
sample_dir: data/learning/samples
minimum_workbooks_for_promotion: 2
existing_variant_threshold: 85
admin_review_threshold: 60
llm:
enabled: false
active_profile: local
@@ -61,8 +88,10 @@ security:
admin_reauth_required_for_mutations: true
paths:
tmp_blueprints_dir: data/tmp_blueprints
export_audit_log: data/audit/export_quality.jsonl
learning_audit_log: data/audit/format_learning.jsonl
type_config_archive_dir: data/archive/config_versions
file:
max_upload_size_mb: 200
supported_formats:
- .xlsx
- .xls
+162 -37
View File
@@ -1,50 +1,140 @@
type_id: candy
label: CANDY
category: candy
sheet_selection:
recommended_patterns:
- Sheet1
- 案内リスト
# Candy suppliers use both an English planning template and Japanese BCL
# workbooks. Parser/mapping behavior stays data-driven here; Python only
# interprets these generic rules.
structure:
header_pattern:
keywords:
- Age
- Asst
- BATT
- CTN
- Case
- Country
- DP
- Grade
- Item
- JAN
- JPSRP
- Launch
- Manufacturer
- Name
- Origin
- PCS
- Item Name
- PKG
- Pack
- Piece
- SRP
- Type
- by
- calculate
- of
- tax
- type
- Age Grade
- Country of Origin
- 商品名
- 商品JAN CODE
- 対象年齢
- 発売日
- 発売月
strategy: max_keyword_match
data_start_offset: 1
sheet_rules:
- sheet_pattern: Sheet1
header_row: 1
data_start_row: 7
column_headers:
O: DP / CTN
P: PCS / DP
Q: PCS / CTN
- sheet_pattern: 貼り付け
header_row: 2
data_start_row: 5
column_headers:
Q: DP / CTN
S: PCS / DP
BL: 一次メーカー
- sheet_pattern: 案内リスト
header_row: 7
data_start_row: 8
column_headers:
V: DP / CTN
X: PCS / DP
Y: PCS / CTN
- sheet_pattern: ESHマスター
header_row: 2
data_start_row: 4
- sheet_pattern: BNA国別FCST
header_row: 4
data_start_row: 5
# Alternative signatures are scored independently. This avoids diluting the
# Candy score when a workbook contains only one of the supported layouts.
fingerprint_profiles:
- name: candy_toy_english
headers:
- JAN
- Item Name
- PKG Type
- Age Grade
- BATT type
- Country of Origin
- Manufacturer
- name: candy_bcl_paste
headers:
- JANコード
- 商品名
- PKG形態
- 対象年齢(歳以上)
- 電池の種別
- 生産国
- キャラクター
- name: candy_bcl_guide
headers:
- JAN
- アイテム名
- english
- PKG
- 対象年齢
- メーカー
- 工場
- name: candy_bcl_master
headers:
- 商品JAN CODE
- 商品名 (英語)
- 商品名 (日本語)
- Age Target
- Battery info.
- DP / CTN
- PCS / DP
- VENDOR
# Candy mappings must be explicitly approved in this file. Disabling fuzzy
# fallback prevents unrelated Japanese support sheets from creating plausible
# but incorrect automatic mappings.
matching:
fuzzy_enabled: false
mapping:
- source_patterns:
- JAN
- JANコード
- 商品JAN CODE
- 日本JAN
target: generated_barcode
fuzzy_weight: 1.0
required: true
description: Generated Barcode
- source_patterns:
- 品目コード
- 品目コード
- SAP
target: sap
fuzzy_weight: 1.0
required: false
description: SAP / item code
- source_patterns:
- Item Name
- 商品名
- english
- 商品名 (英語)
target: item_name_eng
fuzzy_weight: 1.0
required: true
description: Item Name ENG
- source_patterns:
- アイテム名
- 商品名 (日本語)
target: item_name_jap
fuzzy_weight: 1.0
required: false
description: Item Name JAP
- source_patterns:
- PKG
target: op_bl
@@ -53,91 +143,126 @@ mapping:
description: OP/BL
- source_patterns:
- PKG Type
- PKG形態
- PKG仕様
target: package_style
fuzzy_weight: 1.0
required: true
description: Package Style
- source_patterns:
- Piece
- 本体サイズ(mm)
target: package_size
fuzzy_weight: 1.0
required: true
description: Package Size
- source_patterns:
- calculate by DP / CTN X PCS / DP
- PCS / CTN
target: pcs_ctn
fuzzy_weight: 1.0
required: true
description: PCS / CTN
- source_patterns:
- Case Pack
- DP / CTN
target: dp_ctn
fuzzy_weight: 1.0
required: true
description: Order Set
description: Order Set / DP per carton
- source_patterns:
- Case Pack
- PCS / DP
target: pcs_dp
fuzzy_weight: 1.0
required: true
description: PCS / DP
- source_patterns:
- Asst.
- 種類数
target: no_of_asst
fuzzy_weight: 1.0
required: true
description: No of Asst
- source_patterns:
- Age Grade
- 対象年齢(歳以上)
- 対象年齢
- Age Target
target: age_grade
fuzzy_weight: 1.0
required: true
description: Age Grade
- source_patterns:
- BATT type
- 電池の種別
- Battery info.
target: battery
fuzzy_weight: 1.0
required: true
description: Battery
- source_patterns:
- Launch
- 発売日
- 日本発売日
- 発売月
- 日本発売月
target: jp_bai_launch
fuzzy_weight: 1.0
required: true
description: JP/BAI Launch
- source_patterns:
- JPSRP
- JP SRP
- 価格
target: with_tax
fuzzy_weight: 1.0
required: true
description: with tax
- source_patterns:
- SRP w/ tax
- 税込価格
- Retail Price JPY
- 上代
target: without_tax
fuzzy_weight: 1.0
required: true
description: without tax
- source_patterns:
- Country of Origin
- 生産国
target: country_of_origin
fuzzy_weight: 1.0
required: true
description: Country of Origin
- source_patterns:
- Manufacturer
- 一次メーカー
- VENDOR
- メーカー
target: vendor
fuzzy_weight: 1.0
required: true
description: Vendor
form_fields:
- source_patterns:
- JAN
target: generated_barcode
propagate: true
- 工場
target: factory
fuzzy_weight: 1.0
required: false
description: Factory
- source_patterns:
- Launch
target: jp_bai_launch
propagate: true
- Character
- キャラクター
target: character
fuzzy_weight: 1.0
required: false
description: Character
derived_fields:
- target: pcs_ctn
operation: multiply
sources:
- dp_ctn
- pcs_dp
when_missing: true
form_fields: []
sheet_combine:
strategy: join_on_form_fields
strategy: append_selected_sheets
sheet_relations: []
+13 -11
View File
@@ -8,20 +8,21 @@ This application converts supplier / offer Excel workbooks into a formal `pre_it
### Operator flow
1. **Upload workbook** — Basic users upload `.xlsx` / `.xls` files.
2. **Preview sheets** — The app shows extracted worksheet rows before any mapping decision.
3. **Detect workbook type** — Fingerprints and deterministic rules suggest the closest known type.
1. **Upload workbook** — Basic users upload `.xlsx` files.
2. **Detect workbook type** — The complete workbook fingerprint suggests the closest known type before sheet scoping.
3. **Preview and select sheets** — Configured recommendations are applied as editable defaults; the app shows selected sheets first.
4. **Confidence gate** — If confidence is below the configured threshold, the user must explicitly confirm before continuing.
5. **Basic analysis review** — The deterministic result shows sheets, join rules, and mappings.
6. **Optional AI analysis** — AI is user-triggered only. It is not required for normal browsing/export.
7. **Preview merged rows** — One output row per product is previewed against the `pre_item_master` columns.
6. **Optional AI Review branch** — AI is user-triggered only from Review. It is not required for normal browsing/export.
7. **Preview merged rows and quality gate** — One output row per product is previewed; missing/duplicate SQL keys block export until fixed or explicitly overridden by a reauthenticated Admin.
8. **Export** — User downloads `pre_item_master_<timestamp>.xlsx`.
9. **Blueprint proposal** — Basic users can submit a temporary Match Blueprint proposal. Admin reviews and merges it later.
### Roles
- **Basic user**: upload, review, export, and submit temporary blueprint proposals.
- **Admin**: unlock Admin area, maintain type configs, synonyms, AI settings, and merge proposals.
- **Admin**: unlock Admin area, maintain type configs, synonyms, AI settings, merge proposals, and audit exceptional quality overrides.
- **Controlled learning**: the app records privacy-safe evidence, classifies format similarity, replays the full deterministic pipeline, and waits for Admin promotion. It never self-writes production mappings.
- **Programmer / data team**: maintain parsing, schema, tests, and Docker deployment.
### Important business rules
@@ -39,13 +40,13 @@ This application converts supplier / offer Excel workbooks into a formal `pre_it
### 使用流程
1. **上傳 workbook** — Basic user 上傳 `.xlsx` / `.xls`。
2. **預覽 worksheet** — 系統先顯示已抽取嘅 sheet rows,方便檢查來源資料。
3. **偵測 workbook type** — 透過 fingerprint 同 deterministic rules 建議最接近嘅格式。
1. **上傳 workbook** — Basic user 上傳 `.xlsx`。
2. **偵測 workbook type** — 系統先用完整 workbook fingerprint 建議最接近嘅格式,再縮窄 sheet scope。
3. **預覽同選擇 worksheet** — Type config 推薦 sheets 會成為可修改預設;已選 sheets 優先顯示。
4. **信心分數閘口** — 如果信心分數低於設定 threshold,user 必須勾選確認先可以繼續。
5. **Basic analysis review** — 檢查 sheet、join rules、欄位 mapping。
6. **Optional AI analysis** — AI 只會喺 user 主動按掣時執行;正常 export 唔需要 AI。
7. **預覽合併 rows** — 以 `pre_item_master` 欄位顯示每個產品一行。
6. **Optional AI Review branch** — AI 只會喺 Review 入面由 user 主動按掣時執行;正常 export 唔需要 AI。
7. **預覽合併 rows 同 quality gate** — 以 `pre_item_master` 欄位顯示每個產品一行;SQL keys 缺失或重複會阻擋 export,除非修正或由重新驗證嘅 Admin 明確 override。
8. **匯出** — 下載 `pre_item_master_<timestamp>.xlsx`。
9. **Blueprint proposal** — Basic user 只可提交 temporary proposal,由 Admin review / merge。
@@ -53,6 +54,7 @@ This application converts supplier / offer Excel workbooks into a formal `pre_it
- **Basic user**:上傳、檢查、匯出、提交 temporary blueprint proposal。
- **Admin / 管理員**:unlock Admin area,維護 type configs、synonyms、AI settings、merge proposals。
- **受控學習**:系統建立 privacy-safe evidence、判斷格式相似度並重跑完整 deterministic pipeline;只有 Admin 審批後才可 promotion,系統不會自行改 production mapping。
- **Programmer / data team**:維護 parser、schema、tests、Docker deployment。
### 重要規則
+89
View File
@@ -20,11 +20,61 @@ Create `config/settings.yaml` from `config/settings.example.yaml` before deploym
Key sections:
- `analysis.low_confidence_warning_threshold`: default `40`; below this score Basic users must confirm before continuing.
- `analysis.mapping_review_attention_threshold`: default `85`; mappings below this confidence appear in **Needs attention**.
- `operator_review.*`: controls the bounded changes a Basic user may make to sheets, Type, header rows, mappings, and dropped-row restore.
- `operator_review.mapping_target_allowlist`: use `["*"]` for the full schema or list only SQL fields operators may choose.
- `operator_review.field_labels`: friendly names shown before technical SQL names in the mapping editor.
- `file.supported_formats`: currently only `.xlsx`; legacy binary `.xls` is not accepted by the parser.
- `file.max_upload_size_mb`: workbook size limit displayed and enforced on Upload.
- `llm.enabled`: optional AI switch. Default is `false`.
- `llm.active_profile`: selects `local` or `cloud` profile.
- `llm.profiles.<name>`: OpenAI-compatible `base_url`, `model`, `api_key`, timeout, SSL, and context-budget fields.
- `security.admin_password_hash`: salted hash for Admin unlock. Docker can override this with `ADMIN_PASSWORD_HASH`.
- `paths.tmp_blueprints_dir`: temporary proposal folder for Basic-user blueprint submissions.
- `learning.enabled`: enables privacy-safe format-learning evidence and proposals.
- `learning.evidence_dir`: JSON evidence directory; raw cell values are excluded.
- `learning.retain_raw_samples`: opt-in workbook retention for later replay; default `false`.
- `learning.minimum_workbooks_for_promotion`: recommended independent evidence count; default `2`.
- `learning.existing_variant_threshold` / `admin_review_threshold`: similarity classification thresholds.
- `paths.learning_audit_log`: redacted promotion/reject/rollback JSONL audit.
- `paths.type_config_archive_dir`: version archive used before promotion or rollback.
- `paths.export_audit_log`: JSONL audit path for Admin quality overrides; raw workbook cell values are never written.
Runtime YAML/JSON writes use same-directory atomic replacement, and audit JSONL uses a short exclusive lock. Proposal updates carry a revision number so a stale browser session cannot overwrite a newer Admin decision.
### Type-controlled parsing and mapping
Each tracked `config/types/<type_id>.yaml` can define the complete deterministic import policy without adding vendor-specific Python branches:
- `fingerprint_profiles`: alternative header signatures; each profile is scored independently and the best score is used.
- `sheet_selection.recommended_patterns`: optional case-insensitive glob patterns applied after full-workbook fingerprinting. Matches keep workbook order; missing/unmatched patterns fall back to all sheets.
- `structure.sheet_rules`: sheet-pattern rules for `header_row`, `data_start_row`, and `column_headers`. `column_headers` assigns stable logical names to blank or duplicated Excel columns by letter.
- `mapping[].source_patterns`: approved source-header aliases for a SQL target.
- `matching.fuzzy_enabled`: set to `false` when a type must only use explicitly approved mappings.
- `derived_fields`: safe SQL-target calculations. Supported operations are allow-listed; `multiply` can derive a missing target from two or more mapped targets.
Example:
```yaml
sheet_selection:
recommended_patterns:
- Sheet1
- 案内リスト
structure:
sheet_rules:
- sheet_pattern: Offer*
header_row: 2
data_start_row: 5
column_headers:
Q: DP / CTN
matching:
fuzzy_enabled: false
derived_fields:
- target: pcs_ctn
operation: multiply
sources: [dp_ctn, pcs_dp]
when_missing: true
```
### Admin password setup
@@ -61,11 +111,50 @@ Never commit real API keys, password hashes, or local runtime settings.
重要 sections:
- `analysis.low_confidence_warning_threshold`:預設 `40`;低於此分數要 Basic user 勾選確認。
- `analysis.mapping_review_attention_threshold`:預設 `85`;低於此 confidence 嘅 mapping 會列入 **Needs attention**。
- `llm.enabled`:optional AI 開關,預設 `false`。
- `llm.active_profile`:選擇 `local` 或 `cloud` profile。
- `llm.profiles.<name>`:OpenAI-compatible `base_url`、`model`、`api_key`、timeout、SSL、context budget。
- `security.admin_password_hash`:Admin unlock 用 salted hash;Docker 可用 `ADMIN_PASSWORD_HASH` override。
- `paths.tmp_blueprints_dir`:Basic user blueprint proposal 暫存 folder。
- `learning.*`:控制 privacy-safe evidence、是否保留原檔、promotion evidence 數量及相似度門檻。
- `paths.learning_audit_log`:promotion/reject/rollback 的 JSONL audit(不含 raw cell value)。
- `paths.type_config_archive_dir`:Type config promotion/rollback 前的版本備份目錄。
- `paths.export_audit_log`:Admin quality override 嘅 JSONL audit 路徑;不會記錄 workbook 原始 cell values。
### Type 控制嘅 parsing 同 mapping
每個 tracked `config/types/<type_id>.yaml` 都可以完整定義 deterministic import policy,毋須在 Python 加入 vendor-specific 分支:
- `fingerprint_profiles`:多個可替代 header signatures;每個 profile 獨立評分,使用最高分。
- `sheet_selection.recommended_patterns`:full-workbook fingerprint 後使用嘅 optional case-insensitive glob;按 workbook 原始順序選取,無設定或無 match 時 fallback 全選。
- `structure.sheet_rules`:按 sheet pattern 設定 `header_row`、`data_start_row` 同 `column_headers`;`column_headers` 可按 Excel 欄字母,為空白或重複 header 指定穩定 logical name。
- `mapping[].source_patterns`:每個 SQL target 已批准嘅來源 header aliases。
- `matching.fuzzy_enabled`:如該 Type 只准使用明確批准 mapping,可設為 `false`。
- `derived_fields`:安全 SQL target 計算;operation 使用 allow-list,`multiply` 可由兩個或以上已 mapping targets 補出缺失 target。
例子:
```yaml
sheet_selection:
recommended_patterns:
- Sheet1
- 案内リスト
structure:
sheet_rules:
- sheet_pattern: Offer*
header_row: 2
data_start_row: 5
column_headers:
Q: DP / CTN
matching:
fuzzy_enabled: false
derived_fields:
- target: pcs_ctn
operation: multiply
sources: [dp_ctn, pcs_dp]
when_missing: true
```
### Admin password 設定
+43
View File
@@ -0,0 +1,43 @@
# Controlled Format Learning / 受控格式學習
## English
The app can learn a new Excel format, but it never changes production mapping rules by itself. Learning is an evidence-driven proposal workflow:
1. Only when the operator confirms the final Preview does the app record a privacy-safe structural evidence file. It is bound to the reviewed Type, sheets, header rows, mappings, restored rows, quality issues, and override state.
2. It compares sheet names, header overlap/order, confirmed mappings, required keys, and fingerprint structure with known Types and pending proposals.
3. The result is classified as `existing_variant` (85%+), `needs_admin_review` (60–84%), or `new_type` (below 60%). Thresholds are configurable.
4. A Basic user may submit a candidate. The candidate contains only operator-confirmed mappings, exact observed sheet rules, fingerprint profiles, and conservative sheet recommendations. Fuzzy expansion and inferred derived fields are disabled.
5. Before the proposal is saved, the current workbook is replayed through parser, fingerprint, deterministic analyzer, merge, row-quality, and export checks. The `pre_item_master` sheet and configured SQL column order must remain intact.
6. Each proposal has a revision, candidate hash, evidence-set hash, and per-workbook replay matrix. Editing YAML or adding evidence invalidates stale replay rows. Admin reviews the explanation, YAML diff, replay matrix, and evidence count; validation errors cannot be overridden.
7. Promotion archives the previous Type YAML, writes an audit record, reloads Type configs immediately, and retains rollback history.
8. Later runs of an approved learned Type append a privacy-safe health result. Low recognition confidence or blocking quality issues are marked `needs_review`; the system never silently deletes or rewrites the Type.
### Privacy
By default, evidence stores workbook hash/name, sheet names and dimensions, detected headers, confirmed source-to-target mappings, row counts, issue codes/indexes, and whether an Admin quality override was used. It does not store cell samples or raw values. Proposal blueprints are also scrubbed of samples and shared cell values.
Set `learning.retain_raw_samples: true` only if the organization approves retaining uploaded workbooks for later replay. `data/` is gitignored but must still be protected by normal access controls and retention policy.
### Proposal states
`draft → validating → validated → approved → archived`, or `failed / rejected → archived`. Invalid reverse transitions and stale revision writes are rejected.
### Promotion and rollback
Admin mutations require password re-authentication and a reason of at least 10 characters. Promotion writes the previous config to `paths.type_config_archive_dir`; both promotion and rollback append redacted JSONL records to `paths.learning_audit_log`. Audit entries contain hashes and decision metadata, not source cell values.
## 繁體中文
系統可以學習新 Excel 格式,但不會自行直接改 production mapping。整個流程屬於「有證據、可審批、可回復」的受控學習:
1. 只有使用者在 Preview 作最後確認時,系統才建立不含 raw cell value 的結構證據;證據會綁定 reviewed Type、sheets、header rows、mappings、restore rows、quality issues 及 override 狀態。
2. 系統比較 sheet 名、header 重疊及次序、已確認 mapping、必要 key 與 fingerprint 結構。
3. 結果分為 `existing_variant`(85% 或以上)、`needs_admin_review`(60–84%)或 `new_type`(低於 60%);門檻可在 config 調整。
4. Basic user 只可提交 candidate。Candidate 只採用 operator 已確認 mapping、實際 sheet rule、fingerprint profile 及保守的 sheet recommendation;不會自行開 fuzzy expansion 或推斷 derived field。
5. 儲存 proposal 前,系統會用當前 Excel 重跑 parser、fingerprint、deterministic analyzer、merge、row quality 及 export contract;`pre_item_master` sheet 與 SQL column order 必須維持不變。
6. 每個 proposal 都有 revision、candidate hash、evidence-set hash 及逐 workbook replay matrix。修改 YAML 或加入 evidence 後,舊 replay 會失效;Admin 必須檢查完整 replay matrix,validation error 不可強行略過。
7. Promotion 前會備份舊 Type YAML,寫入 audit,立即 reload Type config,並保留 rollback 歷史。
8. 已批准 learned Type 之後每次使用都會記錄 privacy-safe health result;低辨認信心或 blocking issue 會標記為 `needs_review`,系統不會靜默刪除或改寫該 Type。
預設 evidence 只保存 workbook hash/name、sheet 結構、headers、confirmed mapping、row count、issue code/index 及 quality override 狀態,不保存 raw cell value。只有在機構已批准資料保留政策後,才應把 `learning.retain_raw_samples` 設為 `true`。
+10
View File
@@ -16,6 +16,8 @@ python -m streamlit run app.py --server.port=8501
3. Confirm Basic analysis confidence and preview rows.
4. Export an `.xlsx` and verify the sheet name is `pre_item_master`.
5. If a new format is useful, submit a blueprint proposal instead of changing config directly.
6. In Admin → Format Learning, review classification reasons, config diff, replay result, and evidence count. Re-authenticate and record a reason before approving or rejecting.
7. Use Type version history to rollback a bad promotion; runtime Type configs reload immediately.
### Admin tasks
@@ -37,6 +39,9 @@ Back up these paths before changes:
- `config/types/`
- `config/synonyms.yaml`
- `data/tmp_blueprints/`
- `data/learning/evidence/` (privacy-safe structure only by default)
- `data/audit/format_learning.jsonl`
- `data/archive/config_versions/`
## 繁體中文
@@ -54,6 +59,8 @@ python -m streamlit run app.py --server.port=8501
3. 檢查 Basic analysis confidence 同 preview rows。
4. 匯出 `.xlsx`,確認 sheet name 係 `pre_item_master`。
5. 如遇到有用新格式,提交 blueprint proposal,唔好由 Basic user 直接改 system config。
6. 到 Admin → Format Learning 檢查分類原因、config diff、replay result 同 evidence 數量;批准或拒絕前要重新驗證 Admin password 並填寫原因。
7. 如 promotion 有問題,用 Type version history rollback;runtime 會即時 reload。
### Admin / 管理員工作
@@ -75,3 +82,6 @@ PYTHONPATH=. python -m pytest -q
- `config/types/`
- `config/synonyms.yaml`
- `data/tmp_blueprints/`
- `data/learning/evidence/`(預設只保存 privacy-safe 結構)
- `data/audit/format_learning.jsonl`
- `data/archive/config_versions/`
+4 -4
View File
@@ -12,7 +12,7 @@ The application reduces manual column mapping, handles multi-sheet workbooks, pr
### In scope
- `.xlsx` / `.xls` upload through Streamlit.
- `.xlsx` upload through Streamlit.
- Workbook sheet preview.
- Known-format recognition by fingerprint.
- Workbook structure analysis.
@@ -70,7 +70,7 @@ Runtime app code reads only project-owned config/env. LLM settings must come fro
- Deterministic export for known formats.
- Full test suite must pass before commit.
- Export remains usable when LLM is unavailable.
- UI clearly shows LLM status and fallback behavior.
- UI shows whether Optional AI is configured; actual connectivity is checked only when the user starts an AI run, with deterministic fallback behavior.
- Generated artifacts and temporary files must not be committed.
## Data contract
@@ -91,7 +91,7 @@ Key fields used to keep/drop rows:
| Module | Responsibility |
|---|---|
| `app.py` | Streamlit app shell, sidebar, routing, LLM status |
| `app.py` | Streamlit app shell, four-step routing, sidebar app/Admin status |
| `ui/copy.py` | English-only runtime copy registry |
| `ui/upload_page.py` | Upload, sheet preview, fingerprint recognition |
| `ui/confirm_page.py` | Analysis blueprint and user confirmation |
@@ -119,7 +119,7 @@ Regression fixtures must export non-blank `pre_item_master` workbooks.
### 核心需求
1. 使用者上傳 `.xlsx`/`.xls`,選擇要分析的 sheets。
1. 使用者上傳 `.xlsx`,選擇要分析的 sheets。
2. 系統先以 fingerprint、type config 和 fuzzy matching 建立 deterministic `AnalysisResult`。
3. AI 只在使用者主動要求時執行;AI 不可覆蓋已驗證的 known-format row model。
4. 低於 configurable confidence threshold(預設 40%)時必須明確確認,但確認後可以繼續。
+2 -2
View File
@@ -4,7 +4,7 @@
### Upload cannot be read
- Confirm the file is `.xlsx` or `.xls`.
- Confirm the file is `.xlsx`.
- Open the workbook in Excel and save a clean copy.
- Check Docker/container logs or Streamlit terminal output.
@@ -36,7 +36,7 @@
### Upload 讀唔到
- 確認檔案係 `.xlsx` 或 `.xls`。
- 確認檔案係 `.xlsx`。
- 用 Excel 開啟並另存乾淨 copy。
- 查看 Docker/container logs 或 Streamlit terminal output。
+29 -26
View File
@@ -23,22 +23,23 @@ Open the Streamlit URL.
### 2. Upload workbook and preview extracted data
1. Click **Choose an Excel file**.
2. Select an `.xlsx` or `.xls` workbook.
2. Select an `.xlsx` workbook.
3. Review the extracted sheet preview.
The sidebar and page header show the five operator-facing steps:
The page header shows four operator-facing steps. The sidebar only shows app status, New upload, and Admin controls:
1. **Upload** — choose the Excel file, selected sheets, and detected type.
2. **Review** — review deterministic structure, joins, and mappings.
3. **Optional AI** — optionally run and review the model-assisted pass.
4. **Preview** — inspect final merged rows.
5. **Export** — download the workbook and optionally submit a blueprint proposal.
3. **Preview** — inspect final merged rows and resolve export-quality issues.
4. **Export** — download the workbook and optionally submit a blueprint proposal.
Optional AI is a secondary branch inside **Review**, not a required workflow step.
The app automatically runs deterministic **Basic analysis** after upload. No LLM call is made at this stage.
### 3. Basic analysis review
The Basic analysis page now keeps heavy sections collapsed by default. It shows the most important operator summary first, and the user can expand:
The Review page shows confirmed, needs-attention, unmapped, conflict, and selected-sheet counts first. It renders one header cursor at a time and defaults the mapping editor to **Needs attention**. The user can expand:
- structure summary;
- deterministic cross-sheet join rules;
@@ -46,11 +47,11 @@ The Basic analysis page now keeps heavy sections collapsed by default. It shows
The user may manually select a different **Type** on the Upload step. If the selected Type changes, the user must run **Basic analysis** again for that Type before continuing. If confidence is below the configurable warning threshold (40% by default), the user must explicitly acknowledge the warning before continuing.
### 4. Optional AI analysis run page
### 4. Optional AI Review branch
The AI analysis run page is intentionally minimal.
- Click **Run AI analysis** only when a model-assisted review is needed.
- Click **Run optional AI** from Review only when a model-assisted check is needed. The app does not perform a synchronous connection check on first load; connection happens when the run starts.
- The page shows one fixed **Prompt and AI response stream** console. It appends the prompt and visible model response stream for the current run without remounting the panel, so the latest stream stays visible.
- A compact run status card shows loading state, elapsed time, estimated remaining time, current stage, and progress percentage.
- It does not show empty-state conclusion cards, workbench tabs, or alert banners.
@@ -69,9 +70,9 @@ The AI summary page contains the review details that should not clutter the run
- **Type learning** — preview and explicitly save reusable Type Support Notes for future workbooks of the same Type.
- Fallback/warning messages appear as compact **Run notes** rows, not large alert banners.
### 6. Preview final output rows
### 6. Preview final output rows and quality gate
The Preview page displays rows in the final `pre_item_master` output column order. This lets the user inspect the export result before downloading.
The Preview page displays rows in the final `pre_item_master` output column order. It blocks Export when both item keys are empty, when a non-empty `generated_barcode` is duplicated, or when a non-empty `sap` is duplicated. Dropped rows are outside the gate until restored. Basic users must fix blocking issues; an unlocked Admin may reauthenticate, enter a reason, and create an audited override bound to the current workbook and issue signature.
### 7. Export
@@ -119,30 +120,32 @@ python -m pytest -q
## Mapping internals
1. `ExcelParser` loads workbook sheets.
2. `Fingerprint` recognizes known workbook types.
3. `WorkbookAnalyzer` builds a deterministic fallback result first.
4. Optional `LLMStages` runs only when the user clicks **Run AI analysis** on the dedicated AI step.
5. Known formats keep deterministic summaries/groups as row-model authority.
6. The mapping blueprint keeps at most one Excel source column/field for each SQL target; exact type mappings win over fuzzy or AI additions.
7. Optional Type Support Notes live under `config/type_notes/<type_id>.ai_notes.yaml` and are included in future Stage 3 mapping prompts only for the matching selected Type.
8. `MergeEngine` merges rows by confirmed cross-sheet groups.
9. `_build_merged_rows()` maps Excel headers to SQL target columns.
10. Schema-aware field transforms trim string outputs and remove whitespace from `generated_barcode`.
11. `ExportService` writes the formal workbook.
1. `ExcelParser` loads the complete workbook.
2. `Fingerprint` recognizes known workbook types before sheet scoping; the upload SHA-256 is the analysis cache identity.
3. Configured sheet recommendations are applied as editable defaults.
4. `WorkbookAnalyzer` builds a deterministic fallback result first.
5. Optional `LLMStages` runs only when the user clicks **Run optional AI** from Review.
6. Known formats keep deterministic summaries/groups as row-model authority.
7. The mapping blueprint keeps at most one Excel source column/field for each SQL target; exact type mappings win over fuzzy or AI additions.
8. Optional Type Support Notes live under `config/type_notes/<type_id>.ai_notes.yaml` and are included in future Stage 3 mapping prompts only for the matching selected Type.
9. `MergeEngine` merges rows by confirmed cross-sheet groups.
10. `_build_merged_rows()` maps Excel headers to SQL target columns.
11. Schema-aware field transforms trim string outputs and remove whitespace from `generated_barcode`.
12. `ExportService` writes the formal workbook only after the quality gate or a valid Admin override.
## Failure and fallback behavior
| Situation | Expected behavior |
|---|---|
| LLM disabled | Use known type config / fuzzy matching |
| LLM unavailable | Show fallback status, continue deterministic analysis |
| LLM unavailable | Return to the Basic Review result and continue deterministic analysis |
| Streaming unsupported | Retry as normal non-streaming completion; no UI error |
| Type changed | Require Basic analysis rerun before continuing |
| Confidence below configured threshold | Require explicit confirmation before continuing |
| Unknown workbook format | Use fuzzy matching and require user review |
| Known workbook format | Deterministic row model is authoritative |
| Duplicate SQL target candidates | Keep the first authoritative mapping and drop weaker duplicates |
| Duplicate SQL target mappings | Block Review until the operator resolves the conflict |
| Duplicate non-empty barcode or SAP rows | Block Export; only a reauthenticated Admin may provide an audited override |
| Export error | Show the error and do not produce a misleading file |
## Related files
@@ -161,11 +164,11 @@ python -m pytest -q
### 操作流程
1. 用 `run_app.bat` 啟動,或在 project `.venv` 執行 `python -m streamlit run app.py`。
2. 在 **Upload** 上傳 workbook、選擇要分析的 sheets,並確認偵測到的 Type。
2. 在 **Upload** 上傳 workbook;系統先用完整 workbook fingerprint 辨認 Type,再按 Type config 自動推薦 sheets。推薦只係預設,仍可手動加入其他 sheets。
3. 系統自動執行不呼叫 LLM 的 Basic analysis;在 **Review** 檢查 structure、join rules 和 Excel → SQL mappings。
4. 如果 Type 有改動,必須重新執行 Basic analysis。confidence 低於 configurable threshold(預設 40%)時,要勾選明確確認才可繼續。
5. **Optional AI** 只會在使用者按下 Run AI analysis 後執行;若 AI disabled、unavailable 或結果無效,繼續使用 deterministic result。
6. 在 **Preview** 檢查最終 `pre_item_master` column order、row quality 和 merged rows。
5. Optional AI 係 **Review** 內嘅 secondary branch,只會喺 user 按 **Run optional AI** 後連線;AI disabled、unavailable 或結果無效時繼續使用 deterministic result。
6. 在 **Preview** 檢查最終 `pre_item_master` column order、row quality 和 merged rows。兩個 item keys 同時缺失、非空 barcode 重複或非空 SAP 重複會阻擋 Export;Basic user 要返回修正,Admin 可重新驗證並留下 audit reason 後 override。
7. 在 **Export** 下載 `pre_item_master_<timestamp>.xlsx`。Workbook 只包含 `pre_item_master` sheet。
8. 如格式需要重用,Basic user 可提交 temporary Match Blueprint proposal;只有已驗證 Admin 可 review、merge 和 archive proposal。
-2
View File
@@ -1,6 +1,4 @@
[pytest]
asyncio_default_fixture_loop_scope = function
filterwarnings =
ignore::DeprecationWarning:pytest_asyncio.*
ignore::Warning:requests
ignore::Warning:urllib3
Binary file not shown.
Binary file not shown.
+110 -10
View File
@@ -10,10 +10,24 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import re
import uuid
import yaml
from services.learned_blueprint import build_learned_type_config
from services.validation_binding import hash_candidate_config, hash_evidence_set
from services.file_store import atomic_write_text, file_lock
PROPOSAL_STATUSES = {"draft", "validating", "validated", "failed", "approved", "rejected", "archived"}
ALLOWED_STATUS_TRANSITIONS = {
"draft": {"draft", "validating", "validated", "failed", "rejected"},
"validating": {"validated", "failed", "draft"},
"validated": {"validated", "validating", "draft", "approved", "rejected", "failed"},
"failed": {"failed", "validating", "draft", "rejected"},
"approved": {"approved", "archived"},
"rejected": {"rejected", "archived"},
"archived": {"archived"},
}
@dataclass(frozen=True)
@@ -26,6 +40,9 @@ class BlueprintProposalRef:
selected_type: str
analysis_engine: str
mappings: int
status: str = "draft"
classification: str = ""
evidence_count: int = 0
def _safe_slug(value: str) -> str:
@@ -54,23 +71,45 @@ def save_blueprint_proposal(
source_workbook_name: str,
selected_type: str | None,
analysis_engine: str | None,
evidence_ids: list[str] | None = None,
classification: str = "",
similarity: dict[str, Any] | None = None,
candidate_config: dict[str, Any] | None = None,
validation: dict[str, Any] | None = None,
retained_sample_path: str = "",
retained_sample_paths: dict[str, str] | None = None,
) -> BlueprintProposalRef:
"""Write a blueprint proposal YAML file and return its metadata ref."""
base = Path(base_dir)
base.mkdir(parents=True, exist_ok=True)
now = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
safe_name = _safe_slug(proposal_name)
path = base / f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{safe_name}.yaml"
path = base / f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{safe_name}_{uuid.uuid4().hex[:8]}.yaml"
evidence_ids = list(evidence_ids or [])
candidate_config = _as_plain(candidate_config or {})
payload = {
"proposal_version": 1,
"proposal_version": 3,
"proposal_id": path.stem,
"revision": 1,
"created_at": now,
"updated_at": now,
"source_workbook_name": source_workbook_name or "",
"selected_type": selected_type or "",
"analysis_engine": analysis_engine or "",
"intended_action": "admin_review_required",
"blueprint": _as_plain(blueprint or {}),
"status": "validated" if (validation or {}).get("status") == "validated" else "draft",
"classification": classification,
"similarity": _as_plain(similarity or {}),
"evidence_ids": evidence_ids,
"evidence_set_hash": hash_evidence_set(evidence_ids),
"candidate_config": candidate_config,
"candidate_config_hash": hash_candidate_config(candidate_config),
"validation": _as_plain(validation or {}),
"retained_sample_path": retained_sample_path or "",
"retained_sample_paths": _as_plain(retained_sample_paths or {}),
"blueprint": _privacy_safe_blueprint(blueprint or {}),
}
path.write_text(yaml.safe_dump(payload, allow_unicode=True, sort_keys=False), encoding="utf-8")
atomic_write_text(path, yaml.safe_dump(payload, allow_unicode=True, sort_keys=False))
return _ref_from_payload(path, payload)
@@ -92,16 +131,55 @@ def load_blueprint_proposal(path: Path | str) -> dict[str, Any]:
"""Load and minimally validate a blueprint proposal YAML file."""
p = Path(path)
payload = yaml.safe_load(p.read_text(encoding="utf-8")) or {}
if payload.get("proposal_version") != 1:
if payload.get("proposal_version") not in {1, 2, 3}:
raise ValueError("unsupported blueprint proposal version")
if not isinstance(payload.get("blueprint"), dict):
raise ValueError("proposal missing blueprint object")
return payload
def build_type_config_from_proposal(payload: dict[str, Any], type_name: str) -> dict[str, Any]:
"""Convert a loaded proposal payload into a normal reusable type config."""
return build_learned_type_config(type_name, payload.get("blueprint") or {})
def update_blueprint_proposal(
path: Path | str,
*,
expected_revision: int | None = None,
**changes: Any,
) -> dict[str, Any]:
"""Update lifecycle metadata without changing the captured blueprint."""
target = Path(path)
with file_lock(target):
payload = load_blueprint_proposal(target)
current_revision = int(payload.get("revision", 1) or 1)
if expected_revision is not None and int(expected_revision) != current_revision:
raise ValueError("proposal changed since it was opened; reload before saving")
allowed = {
"status", "classification", "similarity", "evidence_ids",
"candidate_config", "validation", "reviewed_at", "review_reason",
"retained_sample_path", "retained_sample_paths",
}
for key, value in changes.items():
if key not in allowed:
raise ValueError(f"unsupported proposal field: {key}")
if key == "status":
current_status = str(payload.get("status", "draft") or "draft")
next_status = str(value or "draft")
if next_status not in PROPOSAL_STATUSES:
raise ValueError(f"unsupported proposal status: {next_status}")
if next_status not in ALLOWED_STATUS_TRANSITIONS.get(current_status, set()):
raise ValueError(f"invalid proposal status transition: {current_status} -> {next_status}")
payload[key] = _as_plain(value)
candidate = payload.get("candidate_config") or {}
evidence_ids = payload.get("evidence_ids") or []
payload["candidate_config_hash"] = hash_candidate_config(candidate)
payload["evidence_set_hash"] = hash_evidence_set(evidence_ids)
payload["proposal_version"] = 3
payload["revision"] = current_revision + 1
payload["updated_at"] = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
atomic_write_text(
target,
yaml.safe_dump(payload, allow_unicode=True, sort_keys=False),
assume_locked=True,
)
return payload
def archive_blueprint_proposal(path: Path | str) -> Path:
@@ -110,7 +188,8 @@ def archive_blueprint_proposal(path: Path | str) -> Path:
archive_dir = p.parent / "archive"
archive_dir.mkdir(parents=True, exist_ok=True)
target = archive_dir / p.name
p.replace(target)
with file_lock(p):
p.replace(target)
return target
@@ -123,4 +202,25 @@ def _ref_from_payload(path: Path, payload: dict[str, Any]) -> BlueprintProposalR
selected_type=str(payload.get("selected_type", "")),
analysis_engine=str(payload.get("analysis_engine", "")),
mappings=len(blueprint.get("mappings") or []),
status=str(payload.get("status", "draft")),
classification=str(payload.get("classification", "")),
evidence_count=len(payload.get("evidence_ids", []) or []),
)
def _privacy_safe_blueprint(blueprint: dict[str, Any]) -> dict[str, Any]:
"""Keep structural decisions while removing workbook cell samples/values."""
plain = _as_plain(blueprint or {})
for summary in plain.get("summaries", []) or []:
for column in summary.get("columns", []) or []:
column.pop("samples", None)
for shared in summary.get("shared_values", []) or []:
shared.pop("value", None)
for mapping in plain.get("mappings", []) or []:
if "reason" in mapping:
mapping["reason"] = "Operator-confirmed mapping"
for group in plain.get("groups", []) or []:
for link in group.get("links", []) or []:
if "reason" in link:
link["reason"] = "Operator-confirmed relation"
return plain
+143
View File
@@ -0,0 +1,143 @@
"""Build conservative new-Type or existing-variant candidates for Admin review."""
from __future__ import annotations
from copy import deepcopy
import difflib
from typing import Any
import yaml
from services.learned_blueprint import build_learned_type_config
def build_candidate_type_config(
name: str,
blueprint: dict[str, Any],
evidence: dict[str, Any],
*,
existing_config: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Build a candidate using confirmed mappings and exact observed structure."""
learned = build_learned_type_config(name, blueprint)
_apply_evidence_structure(learned, evidence)
learned["matching"] = {"fuzzy_enabled": False}
learned["learning"] = {
"candidate": True,
"evidence_ids": [str(evidence.get("evidence_id", ""))],
"fuzzy_expansion": False,
"derived_fields_inferred": False,
}
if not existing_config:
return learned
merged = deepcopy(existing_config)
merged.setdefault("learning", {})
ids = list(merged["learning"].get("evidence_ids", []) or [])
evidence_id = str(evidence.get("evidence_id", ""))
if evidence_id and evidence_id not in ids:
ids.append(evidence_id)
merged["learning"].update({
"candidate": True,
"evidence_ids": ids,
"fuzzy_expansion": False,
"derived_fields_inferred": False,
})
merged.setdefault("matching", {}).setdefault("fuzzy_enabled", False)
_merge_profiles(merged, learned)
_merge_sheet_rules(merged, learned)
_merge_sheet_patterns(merged, learned)
_merge_mappings(merged, learned)
return merged
def render_config_diff(before: dict[str, Any] | None, after: dict[str, Any]) -> str:
"""Return a readable unified YAML diff for Admin review."""
old = yaml.safe_dump(before or {}, allow_unicode=True, sort_keys=False).splitlines()
new = yaml.safe_dump(after, allow_unicode=True, sort_keys=False).splitlines()
return "\n".join(difflib.unified_diff(old, new, fromfile="current", tofile="candidate", lineterm=""))
def _apply_evidence_structure(config: dict[str, Any], evidence: dict[str, Any]) -> None:
selected = set((evidence.get("sheet_selection") or {}).get("selected", []) or [])
observed = [sheet for sheet in evidence.get("sheets", []) or [] if sheet.get("name") in selected]
patterns = [str(sheet.get("name")) for sheet in observed if sheet.get("name")]
config["sheet_selection"] = {"recommended_patterns": _unique(patterns)}
config.setdefault("structure", {})["sheet_rules"] = [
{
"sheet_pattern": str(sheet.get("name")),
"header_row": int(sheet.get("header_row", 1) or 1),
"data_start_row": int(sheet.get("data_start_row", 2) or 2),
}
for sheet in observed
if sheet.get("name")
]
headers = _unique(
str(header)
for sheet in observed
for header in sheet.get("detected_headers", []) or []
)[:60]
config["fingerprint_profiles"] = [{
"name": f"evidence_{str(evidence.get('evidence_id', ''))[:8] or 'default'}",
"headers": headers,
}]
config["fingerprint_headers"] = headers
def _merge_profiles(target: dict, learned: dict) -> None:
profiles = target.setdefault("fingerprint_profiles", [])
known = {tuple(str(h).casefold() for h in (p.get("headers", []) or [])) for p in profiles if isinstance(p, dict)}
for profile in learned.get("fingerprint_profiles", []) or []:
signature = tuple(str(h).casefold() for h in profile.get("headers", []) or [])
if signature and signature not in known:
profiles.append(deepcopy(profile))
known.add(signature)
def _merge_sheet_rules(target: dict, learned: dict) -> None:
rules = target.setdefault("structure", {}).setdefault("sheet_rules", [])
known = {(str(r.get("sheet_pattern", "")).casefold(), int(r.get("header_row", 1) or 1)) for r in rules}
for rule in (learned.get("structure") or {}).get("sheet_rules", []) or []:
signature = (str(rule.get("sheet_pattern", "")).casefold(), int(rule.get("header_row", 1) or 1))
if signature not in known:
rules.append(deepcopy(rule))
known.add(signature)
def _merge_sheet_patterns(target: dict, learned: dict) -> None:
patterns = target.setdefault("sheet_selection", {}).setdefault("recommended_patterns", [])
seen = {str(pattern).casefold() for pattern in patterns}
for pattern in (learned.get("sheet_selection") or {}).get("recommended_patterns", []) or []:
if str(pattern).casefold() not in seen:
patterns.append(pattern)
seen.add(str(pattern).casefold())
def _merge_mappings(target: dict, learned: dict) -> None:
entries = target.setdefault("mapping", [])
by_target = {str(entry.get("target", "")): entry for entry in entries if entry.get("target")}
for learned_entry in learned.get("mapping", []) or []:
sql_target = str(learned_entry.get("target", ""))
if not sql_target:
continue
if sql_target not in by_target:
entries.append(deepcopy(learned_entry))
by_target[sql_target] = entries[-1]
continue
current = by_target[sql_target]
sources = current.setdefault("source_patterns", [])
seen = {str(source).casefold() for source in sources}
for source in learned_entry.get("source_patterns", []) or []:
if str(source).casefold() not in seen:
sources.append(source)
seen.add(str(source).casefold())
def _unique(values) -> list[str]:
result = []
seen = set()
for value in values:
text = str(value).strip()
if text and text.casefold() not in seen:
result.append(text)
seen.add(text.casefold())
return result
+136 -5
View File
@@ -4,6 +4,8 @@ from pathlib import Path
import yaml
from services.file_store import atomic_write_text
class ConfigManager:
"""Manages all config loading and saving for the NBD Pre-Item Master app."""
@@ -84,6 +86,7 @@ class ConfigManager:
def _load_type_configs(self):
"""Load every known workbook-type YAML definition."""
self._type_configs = {}
types_dir = self.config_dir / "types"
if types_dir.exists():
for type_file in types_dir.glob("*.yaml"):
@@ -92,6 +95,11 @@ class ConfigManager:
if cfg and "type_id" in cfg:
self._type_configs[cfg["type_id"]] = cfg
def reload_type_configs(self) -> list[str]:
"""Reload type YAML files without restarting Streamlit."""
self._load_type_configs()
return self.get_all_type_ids()
# ── Getters ──────────────────────────────────────────────
def get_db_schema(self) -> list[dict]:
@@ -185,6 +193,66 @@ class ConfigManager:
value = raw / 100.0 if raw > 1 else raw
return max(0.0, min(1.0, value))
def get_mapping_review_attention_threshold(self) -> float:
"""Return the Review attention threshold as a 0-1 fraction."""
raw = float(self.get_analysis_config().get("mapping_review_attention_threshold", 85) or 85)
value = raw / 100.0 if raw > 1 else raw
return max(0.0, min(1.0, value))
def get_operator_review_config(self) -> dict:
"""Return the bounded controls available to a Basic operator."""
raw = self.get_settings().get("operator_review", {}) or {}
allowlist = raw.get("mapping_target_allowlist", ["*"])
if not isinstance(allowlist, list):
allowlist = ["*"]
labels = raw.get("field_labels", {}) or {}
if not isinstance(labels, dict):
labels = {}
return {
"allow_sheet_selection": bool(raw.get("allow_sheet_selection", True)),
"allow_type_override": bool(raw.get("allow_type_override", True)),
"allow_header_row_override": bool(raw.get("allow_header_row_override", True)),
"allow_column_mapping": bool(raw.get("allow_column_mapping", True)),
"allow_ignore_optional_fields": bool(raw.get("allow_ignore_optional_fields", True)),
"allow_restore_dropped_rows": bool(raw.get("allow_restore_dropped_rows", True)),
"mapping_target_allowlist": [str(item) for item in allowlist],
"field_labels": {str(key): str(value) for key, value in labels.items()},
}
def get_operator_mapping_targets(self) -> list[str]:
"""Return schema targets exposed to the non-technical mapping editor."""
configured = self.get_operator_review_config()["mapping_target_allowlist"]
available = self.get_target_column_names()
if "*" in configured:
return available
allowed = set(configured)
return [name for name in available if name in allowed]
def get_operator_field_label(self, field_name: str) -> str:
"""Return friendly operator copy while keeping the SQL name traceable."""
labels = self.get_operator_review_config()["field_labels"]
if labels.get(field_name):
return labels[field_name]
schema = next((item for item in self.get_db_schema() if item.get("name") == field_name), {})
if schema.get("description"):
return str(schema["description"])
return str(field_name).replace("_", " ").title()
def get_supported_upload_extensions(self) -> list[str]:
"""Return normalized upload extensions; this parser supports OOXML only."""
configured = (self.get_settings().get("file", {}) or {}).get("supported_formats", [".xlsx"])
values = configured if isinstance(configured, list) else [configured]
normalized = [str(item).strip().lower() for item in values]
return [item for item in normalized if item == ".xlsx"] or [".xlsx"]
def get_max_upload_size_mb(self) -> int:
"""Return the configured per-workbook size limit."""
raw = (self.get_settings().get("file", {}) or {}).get("max_upload_size_mb", 200)
try:
return max(int(raw), 1)
except (TypeError, ValueError):
return 200
def get_security_config(self) -> dict:
"""Return admin/password security settings."""
return self.get_settings().get("security", {}) or {}
@@ -206,6 +274,58 @@ class ConfigManager:
path = Path(raw)
return path if path.is_absolute() else self.config_dir.parent / path
def get_export_audit_log_path(self) -> Path:
"""Return the Admin export-quality audit JSONL path."""
raw = str(
(self.get_settings().get("paths", {}) or {}).get(
"export_audit_log", "data/audit/export_quality.jsonl"
)
or "data/audit/export_quality.jsonl"
)
path = Path(raw)
return path if path.is_absolute() else self.config_dir.parent / path
def get_learning_config(self) -> dict:
"""Return privacy-safe format-learning settings with conservative defaults."""
raw = self.get_settings().get("learning", {}) or {}
return {
"enabled": bool(raw.get("enabled", True)),
"evidence_dir": str(raw.get("evidence_dir", "data/learning/evidence") or "data/learning/evidence"),
"retain_raw_samples": bool(raw.get("retain_raw_samples", False)),
"sample_dir": str(raw.get("sample_dir", "data/learning/samples") or "data/learning/samples"),
"minimum_workbooks_for_promotion": max(int(raw.get("minimum_workbooks_for_promotion", 2) or 2), 1),
"existing_variant_threshold": float(raw.get("existing_variant_threshold", 85) or 85),
"admin_review_threshold": float(raw.get("admin_review_threshold", 60) or 60),
}
def _resolve_project_path(self, raw: str) -> Path:
path = Path(str(raw))
return path if path.is_absolute() else self.config_dir.parent / path
def get_learning_evidence_dir(self) -> Path:
return self._resolve_project_path(self.get_learning_config()["evidence_dir"])
def get_learning_sample_dir(self) -> Path:
return self._resolve_project_path(self.get_learning_config()["sample_dir"])
def get_learning_audit_log_path(self) -> Path:
raw = str((self.get_settings().get("paths", {}) or {}).get(
"learning_audit_log", "data/audit/format_learning.jsonl"
) or "data/audit/format_learning.jsonl")
return self._resolve_project_path(raw)
def get_type_config_archive_dir(self) -> Path:
raw = str((self.get_settings().get("paths", {}) or {}).get(
"type_config_archive_dir", "data/archive/config_versions"
) or "data/archive/config_versions")
return self._resolve_project_path(raw)
def get_recommended_sheet_patterns(self, type_id: str | None) -> list[str]:
"""Return optional config-driven glob patterns for one workbook Type."""
cfg = self.get_type_config(type_id or "") or {}
raw = (cfg.get("sheet_selection", {}) or {}).get("recommended_patterns", []) or []
return [str(pattern).strip() for pattern in raw if str(pattern).strip()]
def get_fuzzy_threshold(self) -> int:
settings = self.get_settings()
@@ -337,15 +457,21 @@ class ConfigManager:
def save_type_config(self, type_id: str, config: dict) -> None:
"""Save a type config to its YAML file."""
if not type_id or self._safe_type_id(type_id) != type_id:
raise ValueError("type_id may contain only letters, numbers, underscore, and hyphen")
types_dir = self.config_dir / "types"
types_dir.mkdir(parents=True, exist_ok=True)
path = types_dir / f"{type_id}.yaml"
with open(path, "w", encoding="utf-8") as f:
yaml.dump(config, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
atomic_write_text(
path,
yaml.dump(config, allow_unicode=True, default_flow_style=False, sort_keys=False),
)
self._type_configs[type_id] = config
def delete_type_config(self, type_id: str) -> bool:
"""Delete a type config file. Returns True if deleted."""
if not type_id or self._safe_type_id(type_id) != type_id:
raise ValueError("invalid type_id")
path = self.config_dir / "types" / f"{type_id}.yaml"
if path.exists():
path.unlink()
@@ -356,8 +482,10 @@ class ConfigManager:
def save_synonyms(self, synonyms: dict[str, list[str]]) -> None:
"""Save synonym dictionary to synonyms.yaml."""
path = self.config_dir / "synonyms.yaml"
with open(path, "w", encoding="utf-8") as f:
yaml.dump({"synonyms": synonyms}, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
atomic_write_text(
path,
yaml.dump({"synonyms": synonyms}, allow_unicode=True, default_flow_style=False, sort_keys=False),
)
self._synonyms = synonyms
def load_type_support_notes(self, type_id: str) -> dict | None:
@@ -376,7 +504,10 @@ class ConfigManager:
payload = dict(notes or {})
payload["source_type"] = safe_type
path = notes_dir / f"{safe_type}.ai_notes.yaml"
path.write_text(yaml.dump(payload, allow_unicode=True, default_flow_style=False, sort_keys=False), encoding="utf-8")
atomic_write_text(
path,
yaml.dump(payload, allow_unicode=True, default_flow_style=False, sort_keys=False),
)
return path
@staticmethod
+47
View File
@@ -1,11 +1,13 @@
"""Validate type config before saving — catch errors early, prevent broken configs."""
from dataclasses import dataclass, field
import re
VALID_BASE_STRATEGIES = {"prefix", "suffix", "contains", "token_match", "exact", "pattern"}
VALID_STRATEGIES = VALID_BASE_STRATEGIES | {f"reverse_{s}" for s in VALID_BASE_STRATEGIES}
VALID_JOIN_TYPES = {"lookup", "inner"}
VALID_MULTIPLE = {"one_to_one", "one_to_many"}
VALID_DERIVED_OPERATIONS = {"multiply"}
@dataclass
@@ -26,12 +28,36 @@ class ConfigValidator:
def validate(self, config: dict) -> ValidationResult:
"""Run all validation checks. Returns ValidationResult."""
result = ValidationResult()
self._check_identity(config, result)
self._check_mapping_targets(config, result)
self._check_mapping_required(config, result)
self._check_derived_fields(config, result)
self._check_sheet_relations(config, result)
self._check_structure(config, result)
self._check_sheet_selection(config, result)
return result
def _check_identity(self, config: dict, result: ValidationResult):
"""Prevent unsafe or ambiguous Type config filenames."""
type_id = str(config.get("type_id", "") or "")
if type_id and not re.fullmatch(r"[A-Za-z0-9_-]+", type_id):
result.errors.append("type_id may contain only letters, numbers, underscore, and hyphen")
if "label" in config and not str(config.get("label", "") or "").strip():
result.errors.append("label is required")
def _check_sheet_selection(self, config: dict, result: ValidationResult):
"""Validate optional recommended sheet glob patterns."""
selection = config.get("sheet_selection", {}) or {}
patterns = selection.get("recommended_patterns", []) or []
if not isinstance(patterns, list):
result.errors.append("sheet_selection.recommended_patterns must be a list")
return
for index, pattern in enumerate(patterns):
if not isinstance(pattern, str) or not pattern.strip():
result.errors.append(
f"sheet_selection.recommended_patterns[{index}] must be a non-empty string"
)
def _check_mapping_targets(self, config: dict, result: ValidationResult):
"""Ensure every mapping points at an existing SQL column."""
for i, m in enumerate(config.get("mapping", [])):
@@ -52,6 +78,27 @@ class ConfigValidator:
f"column '{m.get('target')}' will never be auto-matched"
)
def _check_derived_fields(self, config: dict, result: ValidationResult):
"""Validate safe SQL-target derivation rules."""
for i, rule in enumerate(config.get("derived_fields", []) or []):
target = str(rule.get("target", "") or "").strip()
operation = str(rule.get("operation", "") or "").strip().lower()
sources = [str(source).strip() for source in rule.get("sources", []) if str(source).strip()]
if target not in self.valid_targets:
result.errors.append(f"Derived field[{i}]: target '{target}' is not a valid DB column")
if operation not in VALID_DERIVED_OPERATIONS:
result.errors.append(
f"Derived field[{i}]: unsupported operation '{operation}'. "
f"Valid: {', '.join(sorted(VALID_DERIVED_OPERATIONS))}"
)
if len(sources) < 2:
result.errors.append(f"Derived field[{i}]: at least two sources are required")
for source in sources:
if source not in self.valid_targets:
result.errors.append(
f"Derived field[{i}]: source '{source}' is not a valid DB column"
)
def _check_sheet_relations(self, config: dict, result: ValidationResult):
"""Validate cross-sheet relation shape and required fields."""
rels = config.get("sheet_relations", [])
+45
View File
@@ -0,0 +1,45 @@
"""Apply safe, config-defined derived output fields."""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
def apply_derived_fields(row: dict[str, Any], rules: list[dict] | None) -> dict[str, Any]:
"""Apply supported derivation rules to a mapped row in place.
Rules reference SQL target names, not vendor headers. Operations are an
explicit allow-list so type config remains auditable without evaluating
arbitrary expressions.
"""
for rule in rules or []:
if not isinstance(rule, dict):
continue
target = str(rule.get("target", "") or "").strip()
sources = [str(source).strip() for source in rule.get("sources", []) if str(source).strip()]
if not target or not sources:
continue
if rule.get("when_missing", True) and row.get(target) not in (None, ""):
continue
values = [row.get(source) for source in sources]
if any(value in (None, "") for value in values):
continue
if str(rule.get("operation", "")).strip().lower() == "multiply":
result = _multiply(values)
if result is not None:
row[target] = result
return row
def _multiply(values: list[Any]) -> int | float | None:
"""Multiply numeric values without accepting arbitrary expressions."""
product = Decimal("1")
try:
for value in values:
product *= Decimal(str(value).strip().replace(",", ""))
except (InvalidOperation, ValueError):
return None
if product == product.to_integral_value():
return int(product)
return float(product)
+90 -8
View File
@@ -1,9 +1,11 @@
"""Read Excel files, detect structure (header row, data region, form fields)."""
from dataclasses import dataclass, field
import fnmatch
from pathlib import Path
from typing import Any
import openpyxl
from openpyxl.utils.cell import column_index_from_string
from services.config_manager import ConfigManager
from utils.helpers import normalize_header
@@ -58,8 +60,13 @@ class ExcelParser:
type_config = self.cm.get_type_config(type_id) if type_id else None
keywords = []
form_patterns = []
sheet_rules: list[dict] = []
data_start_offset = 1
if type_config:
keywords = type_config.get("structure", {}).get("header_pattern", {}).get("keywords", [])
structure = type_config.get("structure", {}) or {}
keywords = structure.get("header_pattern", {}).get("keywords", [])
sheet_rules = structure.get("sheet_rules", []) or []
data_start_offset = max(int(structure.get("data_start_offset", 1) or 1), 1)
for ff in type_config.get("form_fields", []):
form_patterns.extend(ff.get("source_patterns", []))
@@ -69,16 +76,32 @@ class ExcelParser:
for sheet_name in wb.sheetnames:
ws = wb[sheet_name]
parsed = self._parse_sheet(ws, sheet_name, keywords, form_patterns, threshold)
parsed = self._parse_sheet(
ws,
sheet_name,
keywords,
form_patterns,
threshold,
sheet_rule=self._resolve_sheet_rule(sheet_name, sheet_rules),
data_start_offset=data_start_offset,
)
result.sheets.append(parsed)
wb.close()
return result
def _parse_sheet(
self, ws, name: str, keywords: list[str], form_patterns: list[str], threshold: int
self,
ws,
name: str,
keywords: list[str],
form_patterns: list[str],
threshold: int,
sheet_rule: dict | None = None,
data_start_offset: int = 1,
) -> ParsedSheet:
"""Detect structure for a single sheet."""
sheet_rule = sheet_rule or {}
max_row = ws.max_row or 0
max_col = ws.max_column or 0
@@ -105,7 +128,10 @@ class ExcelParser:
r for r in range(scan_limit)
if self._looks_like_header_row(all_data[r])
]
if keywords and header_candidates:
configured_header_row = self._bounded_row(sheet_rule.get("header_row"), max_row)
if configured_header_row is not None:
result.header_row = configured_header_row
elif keywords and header_candidates:
best_row = header_candidates[0]
best_score = -1
for r in header_candidates:
@@ -146,11 +172,26 @@ class ExcelParser:
detected_headers.append(header_text)
if header_text:
col_headers[c] = header_text
# Some vendor templates use merged/blank or duplicated column labels.
# Type YAML may assign stable logical headers by Excel column letter so
# the downstream mapping remains deterministic and reviewable.
for column, logical_header in (sheet_rule.get("column_headers", {}) or {}).items():
col_idx = self._column_index(column, max_col)
header_text = normalize_header(str(logical_header or ""))
if col_idx is None or not header_text:
continue
detected_headers[col_idx] = header_text
col_headers[col_idx] = header_text
result.detected_headers = detected_headers
result.col_headers = col_headers
# ── 3. Detect data region ──
result.data_start_row = result.header_row + 1
configured_data_start = self._bounded_row(sheet_rule.get("data_start_row"), max_row)
result.data_start_row = configured_data_start or min(
result.header_row + max(int(sheet_rule.get("data_start_offset", data_start_offset) or 1), 1),
max_row,
)
# Data ends at the last row with at least one non-empty cell
for r in range(max_row - 1, result.header_row - 1, -1):
@@ -168,8 +209,10 @@ class ExcelParser:
if form_patterns:
from rapidfuzz import fuzz
for r in range(max_row):
# Skip header row and data rows
if result.header_row <= r + 1 <= result.data_end_row:
# Skip the confirmed header and data rows. Helper/form rows
# between them remain eligible when config sets data_start_row.
row_number = r + 1
if row_number == result.header_row or result.data_start_row <= row_number <= result.data_end_row:
continue
# Collect all non-empty cells in this row
@@ -195,13 +238,52 @@ class ExcelParser:
result.form_fields.append(FormField(
label=label_text,
value=val_cell[1],
row=r + 1,
row=row_number,
col=val_cell[0] + 1,
))
break # one form field per row
return result
@staticmethod
def _resolve_sheet_rule(sheet_name: str, sheet_rules: list[dict]) -> dict:
"""Merge matching per-sheet parser rules in YAML order."""
resolved: dict = {}
for rule in sheet_rules:
if not isinstance(rule, dict):
continue
pattern = str(rule.get("sheet_pattern", "*") or "*")
if fnmatch.fnmatch(sheet_name, pattern):
headers = dict(resolved.get("column_headers", {}) or {})
headers.update(rule.get("column_headers", {}) or {})
resolved.update(rule)
if headers:
resolved["column_headers"] = headers
return resolved
@staticmethod
def _bounded_row(value: Any, max_row: int) -> int | None:
"""Return a valid 1-indexed configured row or None."""
if value in (None, ""):
return None
try:
row = int(value)
except (TypeError, ValueError):
return None
return max(1, min(row, max(max_row, 1)))
@staticmethod
def _column_index(value: Any, max_col: int) -> int | None:
"""Resolve a YAML Excel column letter/number to a zero-based index."""
try:
if isinstance(value, int) or str(value).strip().isdigit():
index = int(value) - 1
else:
index = column_index_from_string(str(value).strip().upper()) - 1
except (TypeError, ValueError):
return None
return index if 0 <= index < max_col else None
@staticmethod
def _looks_like_header_row(row: list) -> bool:
"""Heuristic: a header row is mostly text labels, not numbers/dates.
+82
View File
@@ -0,0 +1,82 @@
"""Admin quality-override signatures and privacy-safe JSONL audit records."""
from __future__ import annotations
from collections import Counter
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
from services.row_quality import RowQualityResult
from services.file_store import append_jsonl
def build_issue_signature(workbook_hash: str, quality: RowQualityResult) -> str:
"""Bind an override to one workbook and the exact current issue set."""
payload = {
"workbook_hash": str(workbook_hash or ""),
"issues": [
{
"code": issue.code,
"row_index": int(issue.row_index),
"field": issue.field,
"blocking": bool(issue.blocking),
}
for issue in [*quality.blocking_issues, *quality.warning_issues]
],
"export_indexes": [int(record.index) for record in quality.export_rows],
}
canonical = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def create_quality_override(workbook_hash: str, quality: RowQualityResult, reason: str) -> dict:
"""Create a validated in-session Admin override payload."""
clean_reason = str(reason or "").strip()
if len(clean_reason) < 10:
raise ValueError("Override reason must contain at least 10 characters.")
return {
"workbook_hash": str(workbook_hash or ""),
"issue_signature": build_issue_signature(workbook_hash, quality),
"reason": clean_reason,
"role": "Admin",
"created_at": datetime.now(timezone.utc).isoformat(),
}
def is_valid_quality_override(override: dict | None, workbook_hash: str, quality: RowQualityResult) -> bool:
"""Return True only for a matching Admin override with a valid reason."""
if not override or override.get("role") != "Admin":
return False
if str(override.get("workbook_hash") or "") != str(workbook_hash or ""):
return False
if len(str(override.get("reason") or "").strip()) < 10:
return False
return str(override.get("issue_signature") or "") == build_issue_signature(workbook_hash, quality)
def write_quality_override_audit(
path: Path,
*,
override: dict,
quality: RowQualityResult,
workbook_name: str,
selected_type: str,
selected_sheets: list[str],
) -> None:
"""Append a redacted JSONL record; never include source cell values."""
blocking = quality.blocking_issues
payload = {
"timestamp_utc": override.get("created_at") or datetime.now(timezone.utc).isoformat(),
"workbook_hash": override.get("workbook_hash", ""),
"workbook_name": str(workbook_name or ""),
"type": str(selected_type or ""),
"selected_sheets": [str(name) for name in selected_sheets],
"issue_codes": dict(sorted(Counter(issue.code for issue in blocking).items())),
"issue_count": len(blocking),
"row_indexes": sorted({int(issue.row_index) for issue in blocking}),
"role": "Admin",
"reason": str(override.get("reason") or ""),
"issue_signature": str(override.get("issue_signature") or ""),
}
append_jsonl(path, payload)
+5 -3
View File
@@ -2,10 +2,10 @@
from __future__ import annotations
import re
from datetime import date, datetime
from typing import Any
from services.config_manager import ConfigManager
from services.value_normalization import normalize_string_value
def transform_field_value(cm: ConfigManager, field_name: str, value: Any) -> Any:
@@ -16,7 +16,7 @@ def transform_field_value(cm: ConfigManager, field_name: str, value: Any) -> Any
- generated_barcode additionally removes all whitespace, because barcode
values must not contain spaces.
"""
if value is None or isinstance(value, (datetime, date, int, float)):
if value is None:
return value
schema_by_name = {col.get("name"): str(col.get("type", "")).lower() for col in cm.get_db_schema()}
@@ -24,7 +24,9 @@ def transform_field_value(cm: ConfigManager, field_name: str, value: Any) -> Any
if not _is_string_type(db_type) and field_name != "generated_barcode":
return value
text = str(value).strip()
text = normalize_string_value(value)
if text is None:
return None
if field_name == "generated_barcode":
text = re.sub(r"\s+", "", text)
return text
+81
View File
@@ -0,0 +1,81 @@
"""Small cross-platform primitives for atomic runtime/config file writes."""
from __future__ import annotations
from contextlib import contextmanager
import json
import os
from pathlib import Path
import time
import uuid
from typing import Any, Iterator
@contextmanager
def file_lock(path: Path | str, *, timeout_seconds: float = 5.0) -> Iterator[None]:
"""Acquire a short-lived exclusive lock using an adjacent create-only file."""
target = Path(path)
lock_path = target.with_name(target.name + ".lock")
lock_path.parent.mkdir(parents=True, exist_ok=True)
deadline = time.monotonic() + max(float(timeout_seconds), 0.1)
descriptor: int | None = None
while descriptor is None:
try:
descriptor = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
os.write(descriptor, f"{os.getpid()} {time.time()}".encode("ascii"))
except FileExistsError:
try:
if time.time() - lock_path.stat().st_mtime > 60:
lock_path.unlink(missing_ok=True)
continue
except OSError:
pass
if time.monotonic() >= deadline:
raise TimeoutError(f"Timed out waiting for file lock: {target}")
time.sleep(0.05)
try:
yield
finally:
if descriptor is not None:
os.close(descriptor)
lock_path.unlink(missing_ok=True)
def atomic_write_text(
path: Path | str,
text: str,
*,
encoding: str = "utf-8",
assume_locked: bool = False,
) -> None:
"""Write and fsync a same-directory temp file, then atomically replace target."""
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
def write() -> None:
temp = target.with_name(f".{target.name}.{uuid.uuid4().hex}.tmp")
try:
with temp.open("w", encoding=encoding, newline="") as handle:
handle.write(text)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp, target)
finally:
temp.unlink(missing_ok=True)
if assume_locked:
write()
else:
with file_lock(target):
write()
def append_jsonl(path: Path | str, payload: dict[str, Any]) -> None:
"""Append one complete JSON line while holding an exclusive file lock."""
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
line = json.dumps(payload, ensure_ascii=False, sort_keys=True) + "\n"
with file_lock(target):
with target.open("a", encoding="utf-8", newline="") as handle:
handle.write(line)
handle.flush()
os.fsync(handle.fileno())
+16 -3
View File
@@ -46,10 +46,10 @@ class Fingerprint:
results: list[FingerprintMatch] = []
for t in self.cm.get_type_list():
type_id = t["type_id"]
expected = self._expected_headers(type_id)
if not expected:
profiles = self._expected_header_profiles(type_id)
if not profiles:
continue
score = self._score(all_headers, expected)
score = max(self._score(all_headers, expected) for expected in profiles)
results.append(FingerprintMatch(
type_id=type_id, label=t["label"], score=score,
))
@@ -74,6 +74,19 @@ class Fingerprint:
hdrs.extend(m.get("source_patterns", []))
return hdrs
def _expected_header_profiles(self, type_id: str) -> list[list[str]]:
"""Return alternative config-defined header signatures for one type."""
cfg = self.cm.get_type_config(type_id)
if not cfg:
return []
profiles: list[list[str]] = []
for profile in cfg.get("fingerprint_profiles", []) or []:
raw_headers = profile.get("headers", []) if isinstance(profile, dict) else profile
headers = [str(h).strip() for h in (raw_headers or []) if str(h).strip()]
if headers:
profiles.append(headers)
return profiles or [self._expected_headers(type_id)]
@staticmethod
def _score(uploaded: list[str], expected: list[str]) -> float:
"""Average best fuzzy match of each expected header against uploaded."""
+146
View File
@@ -0,0 +1,146 @@
"""Explainable similarity scoring for workbook-format learning proposals."""
from __future__ import annotations
from dataclasses import dataclass, field
import fnmatch
from typing import Any
@dataclass(frozen=True)
class FormatSimilarity:
type_id: str
score: float
classification: str
reasons: list[str] = field(default_factory=list)
def compare_evidence_to_types(
evidence: dict[str, Any],
type_configs: list[dict[str, Any]],
*,
existing_variant_threshold: float = 85,
admin_review_threshold: float = 60,
) -> list[FormatSimilarity]:
"""Rank known types using sheets, headers, key mappings and structure."""
matches = [
compare_evidence_to_type(
evidence,
cfg,
existing_variant_threshold=existing_variant_threshold,
admin_review_threshold=admin_review_threshold,
)
for cfg in type_configs
if cfg and cfg.get("type_id")
]
return sorted(matches, key=lambda item: (-item.score, item.type_id))
def compare_evidence_to_type(
evidence: dict[str, Any],
config: dict[str, Any],
*,
existing_variant_threshold: float = 85,
admin_review_threshold: float = 60,
) -> FormatSimilarity:
observed_sheets = [str(v) for v in (evidence.get("sheet_selection") or {}).get("selected", [])]
configured_patterns = [
str(v) for v in (config.get("sheet_selection") or {}).get("recommended_patterns", [])
]
sheet_score = _pattern_coverage(observed_sheets, configured_patterns)
observed_headers = _ordered_unique(
header
for sheet in evidence.get("sheets", []) or []
if sheet.get("selected")
for header in sheet.get("detected_headers", []) or []
)
profiles = config.get("fingerprint_profiles", []) or []
profile_headers = [
[str(h) for h in ((profile.get("headers", []) if isinstance(profile, dict) else profile) or [])]
for profile in profiles
]
if not profile_headers:
profile_headers = [[str(h) for h in config.get("fingerprint_headers", []) or []]]
header_score = max((_header_similarity(observed_headers, expected) for expected in profile_headers), default=0.0)
observed_map = {
str(item.get("source", "")).casefold(): str(item.get("target", ""))
for item in (evidence.get("analysis") or {}).get("mappings", []) or []
}
configured_map = {
str(source).casefold(): str(item.get("target", ""))
for item in config.get("mapping", []) or []
for source in item.get("source_patterns", []) or []
}
mapping_score = _mapping_overlap(observed_map, configured_map)
key_targets = {"generated_barcode", "sap"}
observed_keys = {target for target in observed_map.values() if target in key_targets}
configured_keys = {target for target in configured_map.values() if target in key_targets}
key_score = 100.0 if observed_keys and observed_keys <= configured_keys else (50.0 if observed_keys & configured_keys else 0.0)
score = round(sheet_score * 0.20 + header_score * 0.45 + mapping_score * 0.25 + key_score * 0.10, 1)
if score >= existing_variant_threshold:
classification = "existing_variant"
elif score >= admin_review_threshold:
classification = "needs_admin_review"
else:
classification = "new_type"
reasons = [
f"Sheet pattern match {sheet_score:.0f}%",
f"Header similarity {header_score:.0f}%",
f"Confirmed mapping overlap {mapping_score:.0f}%",
f"Required key coverage {key_score:.0f}%",
]
return FormatSimilarity(str(config.get("type_id")), score, classification, reasons)
def _pattern_coverage(names: list[str], patterns: list[str]) -> float:
if not names or not patterns:
return 0.0
matched_names = sum(
any(fnmatch.fnmatch(name.casefold(), pattern.casefold()) for pattern in patterns)
for name in names
)
matched_patterns = sum(
any(fnmatch.fnmatch(name.casefold(), pattern.casefold()) for name in names)
for pattern in patterns
)
precision = matched_names / len(names)
recall = matched_patterns / len(patterns)
return _f1(precision, recall) * 100.0
def _header_similarity(observed: list[str], expected: list[str]) -> float:
if not observed or not expected:
return 0.0
obs = [value.casefold() for value in observed]
exp = [value.casefold() for value in expected]
common = set(obs) & set(exp)
overlap = _f1(len(common) / len(set(obs)), len(common) / len(set(exp)))
positions = [abs(obs.index(value) - exp.index(value)) for value in common]
order = 1.0 if not positions else max(0.0, 1.0 - sum(positions) / (len(positions) * max(len(obs), len(exp))))
return (overlap * 0.8 + order * overlap * 0.2) * 100.0
def _f1(precision: float, recall: float) -> float:
if precision + recall == 0:
return 0.0
return 2 * precision * recall / (precision + recall)
def _mapping_overlap(observed: dict[str, str], configured: dict[str, str]) -> float:
if not observed:
return 0.0
correct = sum(1 for source, target in observed.items() if configured.get(source) == target)
return correct / len(observed) * 100.0
def _ordered_unique(values) -> list[str]:
result = []
seen = set()
for value in values:
text = str(value).strip()
if text and text.casefold() not in seen:
seen.add(text.casefold())
result.append(text)
return result
+17 -1
View File
@@ -39,6 +39,10 @@ def build_learned_type_config(name: str, blueprint: dict[str, Any]) -> dict[str,
keywords = _collect_keywords(summaries, mappings)
fingerprint_headers = _collect_fingerprint_headers(summaries, mappings)
sheet_patterns = _unique([
str(_get(summary, "sheet_name", "") or "").strip()
for summary in summaries
])
mapping_entries = _build_mapping_entries(mappings)
shared_labels = _collect_shared_labels(summaries)
form_entries = [
@@ -61,6 +65,15 @@ def build_learned_type_config(name: str, blueprint: dict[str, Any]) -> dict[str,
"strategy": "max_keyword_match",
},
"data_start_offset": 1,
"sheet_rules": [
{
"sheet_pattern": str(_get(s, "sheet_name", "") or "").strip(),
"header_row": int(_get(s, "header_row", 1) or 1),
"data_start_row": int(_get(s, "data_start_row", int(_get(s, "header_row", 1) or 1) + 1) or 2),
}
for s in summaries
if str(_get(s, "sheet_name", "") or "").strip()
],
"sheets": [
{
"name": _get(s, "sheet_name", ""),
@@ -75,6 +88,9 @@ def build_learned_type_config(name: str, blueprint: dict[str, Any]) -> dict[str,
"form_fields": form_entries,
"sheet_combine": {"strategy": "merge_blueprint" if groups else "single_or_append"},
"fingerprint_headers": fingerprint_headers,
"fingerprint_profiles": [{"name": "learned_default", "headers": fingerprint_headers}],
"sheet_selection": {"recommended_patterns": sheet_patterns},
"learning": {"fuzzy_expansion": False, "derived_fields_inferred": False},
}
relations = _build_sheet_relations(groups)
@@ -146,7 +162,7 @@ def _build_mapping_entries(mappings: list[Any]) -> list[dict[str, Any]]:
"target": target,
"fuzzy_weight": round(max(0.0, min(1.0, confidence)), 2),
"required": confidence >= 0.9,
"description": str(_get(mapping, "reason", "") or target),
"description": f"Operator-confirmed mapping to {target}",
})
return entries
+181
View File
@@ -0,0 +1,181 @@
"""Privacy-safe evidence records for controlled workbook-format learning."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
from typing import Any
from services.file_store import atomic_write_text
@dataclass(frozen=True)
class LearningEvidenceRef:
path: Path
evidence_id: str
created_at: str
workbook_name: str
selected_type: str
mapping_count: int
def build_learning_evidence(
*,
workbook_hash: str,
workbook_name: str,
parsed: Any,
blueprint: dict[str, Any],
selected_type: str | None,
selected_sheets: list[str] | None,
recommended_sheets: list[str] | None,
matched_patterns: list[str] | None,
selection_source: str | None,
fingerprint_matches: list[Any] | None,
quality: Any = None,
export_row_count: int = 0,
analysis_engine: str | None = None,
admin_override_used: bool = False,
reviewed_snapshot_hash: str = "",
restored_row_indexes: list[int] | None = None,
) -> dict[str, Any]:
"""Build an evidence payload containing structure and decisions, never cell values."""
selected = set(selected_sheets or [])
sheets = []
for sheet in getattr(parsed, "sheets", []) or []:
sheets.append({
"name": str(getattr(sheet, "name", "") or ""),
"selected": getattr(sheet, "name", "") in selected,
"rows": int(getattr(sheet, "rows", 0) or 0),
"cols": int(getattr(sheet, "cols", 0) or 0),
"header_row": int(getattr(sheet, "header_row", 1) or 1),
"data_start_row": int(getattr(sheet, "data_start_row", 2) or 2),
"detected_headers": [str(h) for h in (getattr(sheet, "detected_headers", []) or []) if str(h).strip()],
})
mappings = []
for item in (blueprint or {}).get("mappings", []) or []:
source = str(_get(item, "excel_column", "") or "").strip()
target = str(_get(item, "sql_target", "") or "").strip()
if source and target:
mappings.append({
"source": source,
"target": target,
"confidence": round(float(_get(item, "confidence", 0) or 0), 4),
})
issue_rows = []
issue_codes: dict[str, int] = {}
for issue in [
*(getattr(quality, "blocking_issues", []) or []),
*(getattr(quality, "warning_issues", []) or []),
]:
code = str(getattr(issue, "code", "unknown") or "unknown")
issue_codes[code] = issue_codes.get(code, 0) + 1
issue_rows.append({"code": code, "row_index": int(getattr(issue, "row_index", -1))})
now = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
identity = {
"workbook_hash": workbook_hash,
"reviewed_snapshot_hash": reviewed_snapshot_hash,
"sheets": [{"name": s["name"], "headers": s["detected_headers"]} for s in sheets],
"mappings": mappings,
"issue_rows": issue_rows,
"restored_row_indexes": sorted(int(index) for index in (restored_row_indexes or [])),
"admin_override_used": bool(admin_override_used),
}
evidence_id = hashlib.sha256(
json.dumps(identity, ensure_ascii=False, sort_keys=True).encode("utf-8")
).hexdigest()[:24]
return {
"evidence_version": 2,
"evidence_id": evidence_id,
"created_at": now,
"privacy": {"contains_raw_cell_values": False},
"workbook": {"sha256": workbook_hash, "name": workbook_name},
"type": {
"selected": selected_type or "",
"fingerprint_matches": [
{
"type_id": str(_get(match, "type_id", "") or ""),
"score": float(_get(match, "score", 0) or 0),
}
for match in (fingerprint_matches or [])[:10]
],
},
"sheet_selection": {
"all": [s["name"] for s in sheets],
"selected": list(selected_sheets or []),
"recommended": list(recommended_sheets or []),
"matched_patterns": list(matched_patterns or []),
"source": selection_source or "",
},
"sheets": sheets,
"analysis": {
"engine": analysis_engine or "",
"mappings": mappings,
"mapping_count": len(mappings),
},
"review_confirmation": {
"reviewed_snapshot_hash": str(reviewed_snapshot_hash or ""),
"confirmed_at": now,
"restored_row_indexes": sorted(int(index) for index in (restored_row_indexes or [])),
},
"result": {
"export_row_count": int(export_row_count or 0),
"dropped_row_count": len(getattr(quality, "dropped", []) or []),
"can_export": bool(getattr(quality, "can_export", True)),
"issue_counts": issue_codes,
"issue_rows": issue_rows,
"admin_override_used": bool(admin_override_used),
},
}
def save_learning_evidence(base_dir: Path | str, evidence: dict[str, Any]) -> LearningEvidenceRef:
"""Persist one deduplicated evidence JSON document."""
base = Path(base_dir)
base.mkdir(parents=True, exist_ok=True)
evidence_id = str(evidence.get("evidence_id", "") or "").strip()
if not evidence_id:
raise ValueError("evidence_id is required")
path = base / f"{evidence_id}.json"
atomic_write_text(path, json.dumps(evidence, ensure_ascii=False, indent=2))
return _to_ref(path, evidence)
def load_learning_evidence(path: Path | str) -> dict[str, Any]:
payload = json.loads(Path(path).read_text(encoding="utf-8"))
if payload.get("evidence_version") not in {1, 2} or not payload.get("evidence_id"):
raise ValueError("unsupported or invalid learning evidence")
return payload
def retain_workbook_sample(base_dir: Path | str, evidence_id: str, file_name: str, data: bytes) -> Path:
"""Optionally retain a replay sample; callers must enforce the privacy setting."""
suffix = Path(file_name).suffix.lower()
if suffix != ".xlsx":
suffix = ".xlsx"
base = Path(base_dir)
base.mkdir(parents=True, exist_ok=True)
path = base / f"{evidence_id}{suffix}"
path.write_bytes(data)
return path
def _get(value: Any, key: str, default: Any = None) -> Any:
if isinstance(value, dict):
return value.get(key, default)
return getattr(value, key, default)
def _to_ref(path: Path, payload: dict[str, Any]) -> LearningEvidenceRef:
return LearningEvidenceRef(
path=path,
evidence_id=str(payload.get("evidence_id", "")),
created_at=str(payload.get("created_at", "")),
workbook_name=str((payload.get("workbook") or {}).get("name", "")),
selected_type=str((payload.get("type") or {}).get("selected", "")),
mapping_count=int((payload.get("analysis") or {}).get("mapping_count", 0) or 0),
)
+165
View File
@@ -0,0 +1,165 @@
"""Replay validation for format-learning candidates before promotion."""
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from io import BytesIO
from pathlib import Path
import shutil
import tempfile
import uuid
import openpyxl
import yaml
from services.config_manager import ConfigManager
from services.config_validator import ConfigValidator
from services.excel_parser import ExcelParser
from services.export_models import ProcessedData
from services.export_service import ExportService
from services.field_transformer import transform_field_value
from services.fingerprint import Fingerprint
from services.row_builder import build_merged_rows
from services.row_quality import split_rows_by_quality
from services.workbook_analyzer import WorkbookAnalyzer
from services.workbook_selection import filter_parsed_workbook_sheets, recommend_workbook_sheets
from services.validation_binding import hash_candidate_config, hash_evidence_set
@dataclass
class ReplayValidationResult:
status: str = "failed"
errors: list[str] = field(default_factory=list)
warnings: list[str] = field(default_factory=list)
recognized_type: str = ""
recognition_score: float = 0.0
selected_sheets: list[str] = field(default_factory=list)
mapped_targets: list[str] = field(default_factory=list)
export_row_count: int = 0
blocking_issue_count: int = 0
output_column_count: int = 0
output_sheet_name: str = ""
candidate_config_hash: str = ""
evidence_set_hash: str = ""
reviewed_snapshot_hash: str = ""
validated_at: str = ""
validation_run_id: str = ""
def to_dict(self) -> dict:
return asdict(self)
def validate_candidate_replay(
source_cm: ConfigManager,
candidate: dict,
workbook_bytes: bytes,
workbook_name: str,
evidence: dict | None = None,
) -> ReplayValidationResult:
"""Replay the deterministic pipeline using an isolated candidate config."""
evidence_id = str((evidence or {}).get("evidence_id", "") or "")
result = ReplayValidationResult(
status="validating",
candidate_config_hash=hash_candidate_config(candidate),
evidence_set_hash=hash_evidence_set([evidence_id] if evidence_id else []),
validated_at=datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
validation_run_id=str(uuid.uuid4()),
)
config_check = ConfigValidator(source_cm.get_target_column_names()).validate(candidate)
result.errors.extend(config_check.errors)
result.warnings.extend(config_check.warnings)
if not str(candidate.get("type_id", "") or "").strip():
result.errors.append("Candidate type_id is required.")
if not str(candidate.get("label", "") or "").strip():
result.errors.append("Candidate label is required.")
if result.errors:
result.status = "failed"
return result
suffix = Path(workbook_name).suffix.lower() or ".xlsx"
with tempfile.TemporaryDirectory(prefix="nbd_learning_") as temp_dir:
root = Path(temp_dir)
config_dir = root / "config"
shutil.copytree(source_cm.config_dir, config_dir)
types_dir = config_dir / "types"
types_dir.mkdir(parents=True, exist_ok=True)
type_id = str(candidate.get("type_id", "") or "")
(types_dir / f"{type_id}.yaml").write_text(
yaml.safe_dump(candidate, allow_unicode=True, sort_keys=False), encoding="utf-8"
)
workbook_path = root / f"sample{suffix}"
workbook_path.write_bytes(workbook_bytes)
cm = ConfigManager(config_dir)
parsed = ExcelParser(cm).parse(workbook_path, type_id=type_id)
fingerprint = Fingerprint(cm)
matches = fingerprint.recognize(fingerprint.compute_signature(parsed))
if matches:
result.recognized_type = matches[0].type_id
result.recognition_score = matches[0].score
if result.recognized_type != type_id:
result.errors.append(
f"Candidate was not the best fingerprint match (best: {result.recognized_type or 'none'})."
)
recommendation = recommend_workbook_sheets(
[sheet.name for sheet in parsed.sheets],
cm.get_recommended_sheet_patterns(type_id),
)
result.selected_sheets = recommendation.selected
scoped = filter_parsed_workbook_sheets(parsed, recommendation.selected)
if not scoped.sheets:
result.errors.append("Candidate selected no sheets.")
result.status = "failed"
return result
analysis = WorkbookAnalyzer(cm).analyze(scoped, preferred_type_id=type_id, use_llm=False)
result.mapped_targets = sorted({mapping.sql_target for mapping in analysis.mappings if mapping.sql_target})
expected_targets = {
str(item.get("target", ""))
for item in ((evidence or {}).get("analysis") or {}).get("mappings", []) or []
if item.get("target")
}
missing_targets = sorted(expected_targets - set(result.mapped_targets))
if missing_targets:
result.errors.append(f"Replay lost confirmed mappings: {', '.join(missing_targets)}")
blueprint = {
"summaries": analysis.summaries,
"groups": analysis.groups,
"mappings": analysis.mappings,
}
raw_rows = build_merged_rows(scoped, blueprint, candidate.get("derived_fields", []))
target_columns = cm.get_target_column_names()
rows = [
{column: transform_field_value(cm, column, row.get(column)) for column in target_columns}
for row in raw_rows
]
quality = split_rows_by_quality(rows, key_columns=_schema_key_columns(cm))
result.export_row_count = len(quality.export_rows)
result.blocking_issue_count = len(quality.blocking_issues)
expected_count = int(((evidence or {}).get("result") or {}).get("export_row_count", 0) or 0)
if expected_count and result.export_row_count != expected_count:
result.errors.append(
f"Replay row count changed from {expected_count} to {result.export_row_count}."
)
if quality.blocking_issues:
result.errors.append(f"Replay produced {len(quality.blocking_issues)} blocking quality issue(s).")
processed = ProcessedData(rows=[record.row for record in quality.export_rows], target_columns=target_columns)
output = ExportService().export_to_bytes(processed, sheet_name=cm.get_target_table_name())
workbook = openpyxl.load_workbook(BytesIO(output), read_only=True)
result.output_sheet_name = workbook.sheetnames[0] if workbook.sheetnames else ""
sheet = workbook[result.output_sheet_name]
result.output_column_count = int(sheet.max_column or 0)
workbook.close()
if result.output_sheet_name != cm.get_target_table_name():
result.errors.append("Export sheet contract changed during replay.")
if result.output_column_count != len(target_columns):
result.errors.append("Export column count/order contract changed during replay.")
result.status = "validated" if not result.errors else "failed"
return result
def _schema_key_columns(cm: ConfigManager) -> list[str]:
keys = [str(column.get("name")) for column in cm.get_db_schema() if column.get("is_key") and column.get("name")]
return keys or ["generated_barcode", "sap"]
+71
View File
@@ -0,0 +1,71 @@
"""Replay-matrix aggregation for multi-workbook format proposals."""
from __future__ import annotations
from typing import Any, Iterable
from services.validation_binding import bind_validation, hash_candidate_config
def combine_replay_validations(
previous: dict[str, Any] | None,
current_runs: Iterable[tuple[str, dict[str, Any], str]],
*,
candidate: dict[str, Any],
evidence_ids: list[str],
) -> dict[str, Any]:
"""Upsert replay results and require every evidence item to match the candidate."""
previous = previous or {}
matrix = {
str(item.get("evidence_id")): dict(item)
for item in (previous.get("replay_matrix") or [])
if item.get("evidence_id")
}
latest: dict[str, Any] = {}
for evidence_id, validation, snapshot_hash in current_runs:
evidence_id = str(evidence_id or "").strip()
if not evidence_id:
continue
latest = dict(validation or {})
matrix[evidence_id] = {
"evidence_id": evidence_id,
"status": str(latest.get("status", "failed")),
"candidate_config_hash": str(latest.get("candidate_config_hash", "")),
"reviewed_snapshot_hash": str(snapshot_hash or latest.get("reviewed_snapshot_hash", "")),
"validation_run_id": str(latest.get("validation_run_id", "")),
"validated_at": str(latest.get("validated_at", "")),
"errors": list(latest.get("errors", []) or []),
"warnings": list(latest.get("warnings", []) or []),
"export_row_count": int(latest.get("export_row_count", 0) or 0),
"blocking_issue_count": int(latest.get("blocking_issue_count", 0) or 0),
}
candidate_hash = hash_candidate_config(candidate)
required = [str(item) for item in evidence_ids if str(item)]
matrix_rows = [matrix[item] for item in required if item in matrix]
errors = [error for row in matrix_rows for error in (row.get("errors") or [])]
missing = [item for item in required if item not in matrix]
stale = [
row["evidence_id"] for row in matrix_rows
if row.get("candidate_config_hash") != candidate_hash
]
failed = [row["evidence_id"] for row in matrix_rows if row.get("status") != "validated"]
if missing:
errors.append("Missing replay evidence: " + ", ".join(missing))
if stale:
errors.append("Replay uses an older candidate for evidence: " + ", ".join(stale))
if failed:
errors.append("Replay failed for evidence: " + ", ".join(failed))
aggregate = dict(latest or previous)
aggregate["replay_matrix"] = matrix_rows
aggregate["matrix_required_count"] = len(required)
aggregate["matrix_valid_count"] = sum(
row.get("status") == "validated" and row.get("candidate_config_hash") == candidate_hash
for row in matrix_rows
)
aggregate["errors"] = list(dict.fromkeys(errors))
aggregate["warnings"] = list(dict.fromkeys(
warning for row in matrix_rows for warning in (row.get("warnings") or [])
))
aggregate["status"] = "validated" if required and not aggregate["errors"] and len(matrix_rows) == len(required) else "failed"
return bind_validation(aggregate, candidate, required)
+21 -5
View File
@@ -44,9 +44,25 @@ def build_column_mapping_result(result: AnalysisResult, manual_mappings: dict[st
Blank targets mean "ignore this Excel column". The output order follows the
operator-facing mapping table order.
"""
mappings = [
ColumnMapping(excel_column=str(excel), sql_target=str(target), confidence=1.0, reason="Manual review mapping")
for excel, target in manual_mappings.items()
if str(excel).strip() and str(target).strip()
]
original_by_source = {
str(mapping.excel_column): mapping
for mapping in result.mappings
if str(mapping.excel_column).strip()
}
mappings = []
for excel, target in manual_mappings.items():
excel_name = str(excel).strip()
target_name = str(target).strip()
if not excel_name or not target_name:
continue
original = original_by_source.get(excel_name)
if original is not None and str(original.sql_target) == target_name:
mappings.append(original)
else:
mappings.append(ColumnMapping(
excel_column=excel_name,
sql_target=target_name,
confidence=1.0,
reason="Manual review mapping",
))
return replace(result, mappings=mappings, engine="manual")
+105
View File
@@ -0,0 +1,105 @@
"""Deterministic mapping-review classification and continuation policy."""
from __future__ import annotations
from collections import Counter
from dataclasses import dataclass, field
@dataclass(frozen=True)
class MappingReviewItem:
excel_column: str
sql_target: str = ""
confidence: float = 0.0
reason: str = ""
status: str = "Unmapped"
needs_attention: bool = True
conflict: bool = False
@dataclass(frozen=True)
class ReviewGate:
blocking_reasons: list[str] = field(default_factory=list)
@property
def can_continue(self) -> bool:
return not self.blocking_reasons
def classify_mapping_review(
headers: list[str],
mappings,
*,
attention_threshold: float = 0.85,
operator_warnings: list[str] | None = None,
) -> list[MappingReviewItem]:
"""Return one review row per Excel header with attention/conflict status."""
threshold = float(attention_threshold)
if threshold > 1:
threshold /= 100.0
threshold = max(0.0, min(1.0, threshold))
by_source = {str(m.excel_column): m for m in mappings if str(getattr(m, "excel_column", "")).strip()}
targets = Counter(
str(m.sql_target)
for m in mappings
if str(getattr(m, "excel_column", "")).strip() and str(getattr(m, "sql_target", "")).strip()
)
warnings = "\n".join(str(item) for item in (operator_warnings or [])).casefold()
items: list[MappingReviewItem] = []
for raw_header in headers:
header = str(raw_header).strip()
mapping = by_source.get(header)
target = str(getattr(mapping, "sql_target", "") or "") if mapping else ""
confidence = float(getattr(mapping, "confidence", 0.0) or 0.0) if mapping else 0.0
reason = str(getattr(mapping, "reason", "") or "") if mapping else ""
conflict = bool(target and targets[target] > 1)
warned = bool(header and header.casefold() in warnings) or "warning" in reason.casefold()
low_confidence = bool(target and confidence < threshold)
needs_attention = not target or conflict or low_confidence or warned
if not target:
status = "Unmapped"
elif conflict:
status = "Conflict"
elif warned:
status = "Warning"
elif low_confidence:
status = "Low confidence"
else:
status = "Mapped"
items.append(MappingReviewItem(
excel_column=header,
sql_target=target,
confidence=confidence,
reason=reason,
status=status,
needs_attention=needs_attention,
conflict=conflict,
))
return items
def build_review_gate(parsed, mappings) -> ReviewGate:
"""Return blocking reasons for the operator Review step."""
reasons: list[str] = []
sheets = list(getattr(parsed, "sheets", []) or [])
if not sheets:
reasons.append("Select at least one sheet.")
if sheets and not any(
int(getattr(sheet, "header_row", 0) or 0) > 0
and any(str(header or "").strip() for header in getattr(sheet, "detected_headers", []) or [])
for sheet in sheets
):
reasons.append("Confirm at least one detected header row.")
targets = [
str(getattr(mapping, "sql_target", "") or "").strip()
for mapping in mappings
if str(getattr(mapping, "excel_column", "") or "").strip()
and str(getattr(mapping, "sql_target", "") or "").strip()
]
if not ({"generated_barcode", "sap"} & set(targets)):
reasons.append("Map at least one item key: generated_barcode or sap.")
duplicates = sorted(target for target, count in Counter(targets).items() if count > 1)
if duplicates:
reasons.append("Resolve duplicate database targets: " + ", ".join(duplicates) + ".")
return ReviewGate(blocking_reasons=reasons)
+97
View File
@@ -0,0 +1,97 @@
"""Immutable identity for the exact operator-reviewed workbook interpretation."""
from __future__ import annotations
from dataclasses import asdict, dataclass, is_dataclass
import hashlib
import json
from typing import Any
@dataclass(frozen=True)
class ReviewedSnapshot:
workbook_hash: str
workbook_name: str
selected_type: str
selected_sheets: tuple[str, ...]
header_rows: tuple[tuple[str, int], ...]
analysis_source: str
blueprint_hash: str
snapshot_hash: str
def build_reviewed_snapshot(
*,
workbook_hash: str,
workbook_name: str,
selected_type: str,
selected_sheets: list[str],
parsed: Any,
analysis_source: str,
blueprint: dict[str, Any],
) -> ReviewedSnapshot:
"""Create a frozen, content-addressed record for Preview and Export gates."""
header_rows = tuple(
(str(sheet.name), int(sheet.header_row or 0))
for sheet in (getattr(parsed, "sheets", []) or [])
)
blueprint_hash = _hash_payload(blueprint)
identity = {
"workbook_hash": str(workbook_hash or ""),
"workbook_name": str(workbook_name or ""),
"selected_type": str(selected_type or ""),
"selected_sheets": list(selected_sheets or []),
"header_rows": [list(item) for item in header_rows],
"analysis_source": str(analysis_source or "basic"),
"blueprint_hash": blueprint_hash,
}
return ReviewedSnapshot(
workbook_hash=identity["workbook_hash"],
workbook_name=identity["workbook_name"],
selected_type=identity["selected_type"],
selected_sheets=tuple(identity["selected_sheets"]),
header_rows=header_rows,
analysis_source=identity["analysis_source"],
blueprint_hash=blueprint_hash,
snapshot_hash=_hash_payload(identity),
)
def reviewed_snapshot_matches(
snapshot: ReviewedSnapshot | None,
*,
workbook_hash: str,
selected_type: str,
selected_sheets: list[str],
parsed: Any,
blueprint: dict[str, Any] | None,
) -> bool:
"""Return whether current state is still the exact reviewed interpretation."""
if snapshot is None or blueprint is None:
return False
current = build_reviewed_snapshot(
workbook_hash=workbook_hash,
workbook_name=snapshot.workbook_name,
selected_type=selected_type,
selected_sheets=selected_sheets,
parsed=parsed,
analysis_source=snapshot.analysis_source,
blueprint=blueprint,
)
return current.snapshot_hash == snapshot.snapshot_hash
def _hash_payload(value: Any) -> str:
encoded = json.dumps(_canonical(value), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
def _canonical(value: Any) -> Any:
if is_dataclass(value):
return _canonical(asdict(value))
if isinstance(value, dict):
return {str(key): _canonical(item) for key, item in value.items()}
if isinstance(value, (list, tuple, set)):
return [_canonical(item) for item in value]
if value is None or isinstance(value, (str, int, float, bool)):
return value
return str(value)
+110
View File
@@ -0,0 +1,110 @@
"""Build SQL-shaped candidate rows from a confirmed workbook blueprint."""
from __future__ import annotations
from services.derived_fields import apply_derived_fields
from services.merge_engine import MergeEngine
def build_merged_rows(
parsed,
blueprint: dict,
derived_fields: list[dict] | None = None,
*,
include_source_metadata: bool = False,
) -> list[dict]:
"""Merge selected sheets, propagate form values and apply confirmed mappings.
``include_source_metadata`` is UI-only. It adds the master sheet and
original Excel row to each candidate so Preview can point an operator back
to the source without changing the formal export schema.
"""
engine = MergeEngine()
summaries = blueprint["summaries"]
groups = blueprint["groups"]
mappings = blueprint["mappings"]
excel_to_sql = {_get(m, "excel_column", ""): _get(m, "sql_target", "") for m in mappings}
summary_by_name = {_get(s, "sheet_name", ""): s for s in summaries}
sheet_data = {}
for sheet in parsed.sheets:
summary = summary_by_name.get(sheet.name)
header_row = int(_get(summary, "header_row", sheet.header_row) or sheet.header_row)
headers = list(sheet.detected_headers)
if not headers and header_row - 1 < len(sheet.raw_data):
headers = [str(cell) if cell is not None else "" for cell in sheet.raw_data[header_row - 1]]
data_start = max(int(getattr(sheet, "data_start_row", header_row + 1) or header_row + 1) - 1, header_row)
rows = [list(row) for row in sheet.raw_data[data_start:sheet.data_end_row]] if data_start < len(sheet.raw_data) else []
sheet_data[sheet.name] = (headers, rows, data_start + 1)
merged_rows = []
merged_sources: list[dict] = []
if groups:
for group in groups:
master_name = _get(group, "master_sheet", "")
master = sheet_data.get(master_name)
if not master:
continue
master_headers, master_rows, master_start_row = master
group_sheets = _get(group, "sheets", []) or []
linked = {
name: sheet_data[name][:2]
for name in group_sheets
if name != master_name and name in sheet_data
}
group_rows = engine.merge(
master_rows,
master_headers,
linked,
_get(group, "links", []) or [],
)
merged_rows.extend(group_rows)
merged_sources.extend(
{
"__source_sheet": master_name,
"__source_row": master_start_row + index,
}
for index in range(len(group_rows))
)
else:
for sheet_name, (headers, rows, data_start_row) in sheet_data.items():
sheet_rows = [
{header: (row[index] if index < len(row) else None) for index, header in enumerate(headers)}
for row in rows
]
merged_rows.extend(sheet_rows)
merged_sources.extend(
{
"__source_sheet": sheet_name,
"__source_row": data_start_row + index,
}
for index in range(len(sheet_rows))
)
shared_values = [
value
for summary in summaries
for value in (_get(summary, "shared_values", []) or [])
]
mapped_rows = []
for row_index, row in enumerate(merged_rows):
for shared in shared_values:
label = _get(shared, "label", "")
value = _get(shared, "value", None)
if label and value not in (None, "") and row.get(label) in (None, ""):
row[label] = value
output = {}
for source, value in row.items():
target = excel_to_sql.get(source) or source
if target in output and output[target] not in (None, ""):
continue
output[target] = value
mapped = apply_derived_fields(output, derived_fields)
if include_source_metadata and row_index < len(merged_sources):
mapped.update(merged_sources[row_index])
mapped_rows.append(mapped)
return mapped_rows
def _get(value, name: str, default=None):
if isinstance(value, dict):
return value.get(name, default)
return getattr(value, name, default)
+98 -2
View File
@@ -1,9 +1,11 @@
"""Deterministic row-quality checks for export preview."""
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Iterable
from services.value_normalization import canonicalize_key_value
@dataclass(frozen=True)
class RowQualityRecord:
@@ -21,6 +23,21 @@ class RowQualityResult:
accepted: list[RowQualityRecord]
dropped: list[RowQualityRecord]
export_rows: list[RowQualityRecord]
blocking_issues: list["QualityIssue"] = field(default_factory=list)
warning_issues: list["QualityIssue"] = field(default_factory=list)
can_export: bool = True
@dataclass(frozen=True)
class QualityIssue:
"""One export-candidate issue without exposing raw cell values."""
code: str
row_index: int
field: str
issue: str
suggestion: str
blocking: bool = True
def _is_populated(value) -> bool:
@@ -36,6 +53,7 @@ def split_rows_by_quality(
key_columns: Iterable[str] | None = None,
restore_indexes: Iterable[int] | None = None,
sparse_threshold: int = 2,
numeric_key_sources: dict[int, list[str]] | None = None,
) -> RowQualityResult:
"""Split rows into accepted and suggested-dropped lists.
@@ -69,4 +87,82 @@ def split_rows_by_quality(
export_records.append(record)
export_records.sort(key=lambda item: item.index)
return RowQualityResult(accepted=accepted, dropped=dropped, export_rows=export_records)
blocking_issues = _find_blocking_key_issues(export_records)
if not export_records:
blocking_issues.append(QualityIssue(
code="no_export_candidates",
row_index=-1,
field="row",
issue="No product rows are available for export.",
suggestion="Return to Review and confirm the selected sheets, header rows, and mappings.",
))
warning_issues = [
QualityIssue(
code="restored_sparse_row",
row_index=record.index,
field="row",
issue=record.reason,
suggestion="Confirm that this restored sparse row is a real product row.",
blocking=False,
)
for record in export_records
if record.restored and record.reason
]
for record in export_records:
for field_name in (numeric_key_sources or {}).get(record.index, []):
warning_issues.append(QualityIssue(
code="numeric_item_key",
row_index=record.index,
field=field_name,
issue=f"{field_name} was stored as a number in Excel.",
suggestion="Confirm that Excel did not remove meaningful leading zeroes from this item key.",
blocking=False,
))
return RowQualityResult(
accepted=accepted,
dropped=dropped,
export_rows=export_records,
blocking_issues=blocking_issues,
warning_issues=warning_issues,
can_export=not blocking_issues,
)
def _find_blocking_key_issues(records: list[RowQualityRecord]) -> list[QualityIssue]:
issues: list[QualityIssue] = []
occurrences: dict[str, dict[str, list[int]]] = {
"generated_barcode": {},
"sap": {},
}
for record in records:
barcode = record.row.get("generated_barcode")
sap = record.row.get("sap")
if not _is_populated(barcode) and not _is_populated(sap):
issues.append(QualityIssue(
code="missing_both_item_keys",
row_index=record.index,
field="generated_barcode, sap",
issue="Both generated_barcode and sap are empty.",
suggestion="Map or enter at least one item key before export.",
))
for field_name, value in (("generated_barcode", barcode), ("sap", sap)):
if not _is_populated(value):
continue
normalized = canonicalize_key_value(value)
if normalized is None:
continue
occurrences[field_name].setdefault(normalized, []).append(record.index)
for field_name, grouped in occurrences.items():
for row_indexes in grouped.values():
if len(row_indexes) < 2:
continue
for row_index in row_indexes:
issues.append(QualityIssue(
code=f"duplicate_{field_name}",
row_index=row_index,
field=field_name,
issue=f"Duplicate non-empty {field_name} in this export batch.",
suggestion=f"Keep one unique {field_name} value per product row.",
))
return sorted(issues, key=lambda issue: (issue.row_index, issue.code))
+166
View File
@@ -0,0 +1,166 @@
"""Versioned promotion, audit and rollback for learned Type configurations."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
import shutil
from typing import Any
import yaml
from services.config_manager import ConfigManager
from services.config_validator import ConfigValidator
from services.validation_binding import hash_candidate_config, validation_binding_errors
from services.file_store import append_jsonl
@dataclass(frozen=True)
class TypeConfigVersion:
path: Path
type_id: str
created_at: str
config_hash: str
def promote_type_config(
cm: ConfigManager,
candidate: dict[str, Any],
*,
proposal_id: str,
evidence_ids: list[str],
reason: str,
validation: dict[str, Any],
forced: bool = False,
) -> Path | None:
"""Archive the current config, write the candidate, reload and append audit."""
type_id = str(candidate.get("type_id", "") or "").strip()
if not type_id:
raise ValueError("candidate type_id is required")
validation_check = ConfigValidator(cm.get_target_column_names()).validate(candidate)
if validation_check.errors:
raise ValueError("candidate config failed validation: " + "; ".join(validation_check.errors))
binding_errors = validation_binding_errors(validation, candidate, evidence_ids)
if binding_errors:
raise ValueError("candidate replay validation is stale: " + "; ".join(binding_errors))
candidate = dict(candidate)
learning = dict(candidate.get("learning", {}) or {})
learning.update({
"candidate": False,
"promoted_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
"promotion_evidence_count": len(evidence_ids),
})
candidate["learning"] = learning
before = cm.get_type_config(type_id)
archive_path = archive_current_type_config(cm, type_id) if before else None
before_hash = hash_config(before) if before else ""
after_hash = hash_config(candidate)
cm.save_type_config(type_id, candidate)
cm.reload_type_configs()
write_learning_audit(cm.get_learning_audit_log_path(), {
"action": "promote",
"admin_role": "admin",
"type_id": type_id,
"proposal_id": proposal_id,
"evidence_ids": list(evidence_ids),
"before_config_hash": before_hash,
"after_config_hash": after_hash,
"reason": reason,
"forced": bool(forced),
"validation": _validation_summary(validation),
"archive_path": str(archive_path) if archive_path else "",
})
return archive_path
def archive_current_type_config(cm: ConfigManager, type_id: str) -> Path | None:
source = cm.config_dir / "types" / f"{type_id}.yaml"
if not source.exists():
return None
timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S_%fZ")
destination = cm.get_type_config_archive_dir() / type_id / f"{timestamp}.yaml"
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
return destination
def list_type_config_versions(cm: ConfigManager, type_id: str) -> list[TypeConfigVersion]:
base = cm.get_type_config_archive_dir() / type_id
if not base.exists():
return []
versions = []
for path in sorted(base.glob("*.yaml"), reverse=True):
try:
payload = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
versions.append(TypeConfigVersion(
path=path,
type_id=type_id,
created_at=path.stem,
config_hash=hash_config(payload),
))
except (OSError, yaml.YAMLError):
continue
return versions
def rollback_type_config(
cm: ConfigManager,
version_path: Path | str,
*,
reason: str,
) -> Path | None:
"""Restore one archived config after preserving the currently active version."""
path = Path(version_path)
candidate = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
type_id = str(candidate.get("type_id", "") or "")
if not type_id:
raise ValueError("archive does not contain a type_id")
validation = ConfigValidator(cm.get_target_column_names()).validate(candidate)
if validation.errors:
raise ValueError("archived config failed validation: " + "; ".join(validation.errors))
before = cm.get_type_config(type_id)
preserved = archive_current_type_config(cm, type_id) if before else None
cm.save_type_config(type_id, candidate)
cm.reload_type_configs()
write_learning_audit(cm.get_learning_audit_log_path(), {
"action": "rollback",
"admin_role": "admin",
"type_id": type_id,
"source_version": path.name,
"before_config_hash": hash_config(before) if before else "",
"after_config_hash": hash_config(candidate),
"reason": reason,
"preserved_version": str(preserved) if preserved else "",
"validation": {
"status": "validated_config_only",
"error_count": 0,
"warning_count": len(validation.warnings),
},
})
return preserved
def write_learning_audit(path: Path | str, payload: dict[str, Any]) -> None:
record = {
"timestamp_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
**payload,
}
append_jsonl(path, record)
def hash_config(config: dict[str, Any] | None) -> str:
"""Backward-compatible public wrapper for the canonical config hash."""
return hash_candidate_config(config)
def _validation_summary(validation: dict[str, Any]) -> dict[str, Any]:
return {
"status": str(validation.get("status", "")),
"error_count": len(validation.get("errors", []) or []),
"warning_count": len(validation.get("warnings", []) or []),
"export_row_count": int(validation.get("export_row_count", 0) or 0),
"blocking_issue_count": int(validation.get("blocking_issue_count", 0) or 0),
"candidate_config_hash": str(validation.get("candidate_config_hash", "")),
"evidence_set_hash": str(validation.get("evidence_set_hash", "")),
"validation_run_id": str(validation.get("validation_run_id", "")),
}
-27
View File
@@ -2,11 +2,8 @@
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import yaml
from services.workbook_analyzer import AnalysisResult
_SECRET_WORDS = ("api_key", "apikey", "secret", "password", "bearer", "authorization")
@@ -86,30 +83,6 @@ def build_type_support_notes(
return _drop_secret_like_values(notes)
def save_type_support_notes(notes: dict[str, Any], config_dir: Path | str) -> Path:
"""Persist notes under config/type_notes/<type_id>.ai_notes.yaml."""
root = Path(config_dir)
type_id = _safe_type_id(str(notes.get("source_type") or "unknown"))
notes = dict(notes)
notes["source_type"] = type_id
notes_dir = root / "type_notes"
notes_dir.mkdir(parents=True, exist_ok=True)
path = notes_dir / f"{type_id}.ai_notes.yaml"
path.write_text(yaml.safe_dump(notes, allow_unicode=True, sort_keys=False), encoding="utf-8")
return path
def load_type_support_notes(type_id: str, config_dir: Path | str) -> dict[str, Any] | None:
"""Load notes for a type if present."""
path = Path(config_dir) / "type_notes" / f"{_safe_type_id(type_id)}.ai_notes.yaml"
if not path.exists():
return None
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
if not isinstance(data, dict):
return None
return _drop_secret_like_values(data)
def render_support_notes_for_prompt(notes: dict[str, Any] | None, limit: int = 2200) -> str:
"""Render compact type support notes for inclusion in an LLM prompt."""
if not notes:
+58
View File
@@ -0,0 +1,58 @@
"""Canonical hashes used to bind replay validation to reviewed inputs."""
from __future__ import annotations
import hashlib
from typing import Any, Iterable
import yaml
def hash_candidate_config(config: dict[str, Any] | None) -> str:
"""Return a stable SHA-256 for a Type config payload."""
serialized = yaml.safe_dump(config or {}, allow_unicode=True, sort_keys=True)
return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
def hash_evidence_set(evidence_ids: Iterable[str] | None) -> str:
"""Return an order-independent SHA-256 for the proposal evidence set."""
normalized = sorted({str(item).strip() for item in (evidence_ids or []) if str(item).strip()})
serialized = "\n".join(normalized)
return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
def bind_validation(
validation: dict[str, Any],
candidate: dict[str, Any],
evidence_ids: Iterable[str] | None,
*,
reviewed_snapshot_hash: str = "",
) -> dict[str, Any]:
"""Return a validation payload bound to its candidate and evidence inputs."""
bound = dict(validation)
bound["candidate_config_hash"] = hash_candidate_config(candidate)
bound["evidence_set_hash"] = hash_evidence_set(evidence_ids)
bound["reviewed_snapshot_hash"] = str(reviewed_snapshot_hash or "")
return bound
def validation_binding_errors(
validation: dict[str, Any] | None,
candidate: dict[str, Any] | None,
evidence_ids: Iterable[str] | None,
*,
reviewed_snapshot_hash: str | None = None,
) -> list[str]:
"""Explain why a stored replay result no longer matches current inputs."""
validation = validation or {}
errors: list[str] = []
if validation.get("status") != "validated":
errors.append("Replay validation has not passed.")
if validation.get("errors"):
errors.append("Replay validation contains errors.")
if validation.get("candidate_config_hash") != hash_candidate_config(candidate):
errors.append("Candidate YAML changed after replay validation.")
if validation.get("evidence_set_hash") != hash_evidence_set(evidence_ids):
errors.append("Proposal evidence changed after replay validation.")
if reviewed_snapshot_hash is not None and validation.get("reviewed_snapshot_hash", "") != reviewed_snapshot_hash:
errors.append("Reviewed workbook snapshot changed after replay validation.")
return errors
+46
View File
@@ -0,0 +1,46 @@
"""Pure value-normalization helpers shared by transforms and quality checks."""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
import math
from typing import Any
def normalize_string_value(value: Any) -> str | None:
"""Convert a spreadsheet value to a stable string without losing zero padding."""
if value is None:
return None
if isinstance(value, str):
text = value.strip()
return text or None
if isinstance(value, bool):
return "True" if value else "False"
if isinstance(value, int):
return str(value)
if isinstance(value, float):
if math.isnan(value):
return None
if math.isinf(value):
return str(value)
if value.is_integer():
return str(int(value))
return format(value, ".15g")
if isinstance(value, Decimal):
try:
if value.is_nan():
return None
normalized = format(value, "f")
return normalized.rstrip("0").rstrip(".") if "." in normalized else normalized
except (InvalidOperation, ValueError):
return str(value).strip() or None
if isinstance(value, (datetime, date)):
return value.isoformat()
text = str(value).strip()
return text or None
def canonicalize_key_value(value: Any) -> str | None:
"""Return the comparison form used by item-key quality rules."""
normalized = normalize_string_value(value)
return normalized.casefold() if normalized else None
+44 -35
View File
@@ -283,26 +283,27 @@ class WorkbookAnalyzer:
existing_targets = {m.sql_target for m in mappings if m.sql_target}
exact_sources = {m.excel_column for m in mappings if m.excel_column}
ordered_headers = self._collect_ordered_headers(parsed)
fuzzy_results = matcher.match(ordered_headers, type_id=type_id)
for r in fuzzy_results:
if not r.source_header or not r.matched_target:
continue
if r.source_header in exact_sources:
continue
if r.matched_target in existing_targets:
continue
key = (r.source_header, r.matched_target)
if key in existing:
continue
mappings.append(ColumnMapping(
excel_column=r.source_header,
sql_target=r.matched_target,
confidence=max(0.0, min(1.0, r.confidence / 100.0)),
reason=r.reason or (f"Known type: {type_label}" if type_id else "Fuzzy match"),
))
existing.add(key)
existing_targets.add(r.matched_target)
if self._type_fuzzy_enabled(type_id):
ordered_headers = self._collect_ordered_headers(parsed)
fuzzy_results = matcher.match(ordered_headers, type_id=type_id)
for r in fuzzy_results:
if not r.source_header or not r.matched_target:
continue
if r.source_header in exact_sources:
continue
if r.matched_target in existing_targets:
continue
key = (r.source_header, r.matched_target)
if key in existing:
continue
mappings.append(ColumnMapping(
excel_column=r.source_header,
sql_target=r.matched_target,
confidence=max(0.0, min(1.0, r.confidence / 100.0)),
reason=r.reason or (f"Known type: {type_label}" if type_id else "Fuzzy match"),
))
existing.add(key)
existing_targets.add(r.matched_target)
# Sheet-level form fields (e.g. SALES JAN CODE, Japan Launch Date) are
# not part of detected_headers, but they still need SQL targets and must
@@ -422,24 +423,32 @@ class WorkbookAnalyzer:
seen.add(key)
seen_targets.add(target)
matcher = FuzzyMatcher(self.cm)
for sheet in parsed.sheets:
for fm in matcher.match_form_fields(getattr(sheet, "form_fields", []), type_id=type_id):
if fm.label and fm.matched_target:
key = (fm.label, fm.matched_target)
if key in seen or fm.matched_target in seen_targets:
continue
mappings.append(ColumnMapping(
excel_column=fm.label,
sql_target=fm.matched_target,
confidence=max(0.0, min(1.0, fm.confidence / 100.0)),
reason="Fuzzy form field",
))
seen.add(key)
seen_targets.add(fm.matched_target)
if self._type_fuzzy_enabled(type_id):
matcher = FuzzyMatcher(self.cm)
for sheet in parsed.sheets:
for fm in matcher.match_form_fields(getattr(sheet, "form_fields", []), type_id=type_id):
if fm.label and fm.matched_target:
key = (fm.label, fm.matched_target)
if key in seen or fm.matched_target in seen_targets:
continue
mappings.append(ColumnMapping(
excel_column=fm.label,
sql_target=fm.matched_target,
confidence=max(0.0, min(1.0, fm.confidence / 100.0)),
reason="Fuzzy form field",
))
seen.add(key)
seen_targets.add(fm.matched_target)
return mappings
def _type_fuzzy_enabled(self, type_id: str | None) -> bool:
"""Return the type-configured deterministic fallback policy."""
if not type_id:
return True
cfg = self.cm.get_type_config(type_id) or {}
return bool((cfg.get("matching", {}) or {}).get("fuzzy_enabled", True))
def _choose_fallback_type(
self,
parsed: ParsedWorkbook,
+57 -1
View File
@@ -1,9 +1,65 @@
"""Helpers for operator-selected workbook sheet scope."""
"""Helpers for operator-selected workbook sheet scope and recommendations."""
from __future__ import annotations
from dataclasses import dataclass, field
import fnmatch
from services.excel_parser import ParsedWorkbook
@dataclass(frozen=True)
class SheetRecommendation:
"""Config-driven sheet recommendation in original workbook order."""
selected: list[str] = field(default_factory=list)
matched_patterns: list[str] = field(default_factory=list)
configured_patterns: list[str] = field(default_factory=list)
used_fallback: bool = False
@property
def reason(self) -> str:
if not self.configured_patterns:
return "This Type has no sheet recommendation, so all sheets remain selected."
if self.used_fallback:
return "No configured pattern matched, so all sheets remain selected."
if self.matched_patterns:
return "Matched the selected Type's recommended sheet patterns."
return "All configured recommendations were evaluated."
def recommend_workbook_sheets(
sheet_names: list[str] | tuple[str, ...],
patterns: list[str] | tuple[str, ...] | None,
) -> SheetRecommendation:
"""Match case-insensitive glob patterns while preserving workbook order."""
ordered_names = [str(name) for name in sheet_names]
configured = [str(pattern).strip() for pattern in (patterns or []) if str(pattern).strip()]
if not configured:
return SheetRecommendation(selected=ordered_names, used_fallback=True)
matched_patterns = [
pattern
for pattern in configured
if any(fnmatch.fnmatchcase(name.casefold(), pattern.casefold()) for name in ordered_names)
]
selected = [
name
for name in ordered_names
if any(fnmatch.fnmatchcase(name.casefold(), pattern.casefold()) for pattern in configured)
]
if not selected:
return SheetRecommendation(
selected=ordered_names,
configured_patterns=configured,
used_fallback=True,
)
return SheetRecommendation(
selected=selected,
matched_patterns=matched_patterns,
configured_patterns=configured,
)
def filter_parsed_workbook_sheets(
workbook: ParsedWorkbook,
selected_sheet_names: list[str] | tuple[str, ...] | set[str] | None,
-1
View File
@@ -10,7 +10,6 @@ import urllib.request
from pathlib import Path
import pytest
import yaml
from services.config_manager import ConfigManager
from services.security import hash_password
+8 -8
View File
@@ -10,30 +10,30 @@ def test_build_step_items_marks_done_current_and_pending():
items = build_step_items("preview", lang="en")
assert [i["key"] for i in items] == [
"upload", "confirm", "ai_analysis", "preview", "export",
"upload", "confirm", "preview", "export",
]
assert [i["state"] for i in items] == [
"done", "done", "done", "current", "pending",
"done", "done", "current", "pending",
]
assert items[3]["label"] == "Preview"
assert items[3]["icon"] == "👁️"
assert items[2]["label"] == "Preview"
assert items[2]["icon"] == ":material/preview:"
def test_build_step_items_render_english_copy():
items = build_step_items("confirm", lang="en")
assert [i["label"] for i in items] == [
"Upload", "Review", "Optional AI", "Preview", "Export",
"Upload", "Review", "Preview", "Export",
]
def test_build_step_items_unknown_step_keeps_all_pending():
items = build_step_items("admin_types")
assert [i["state"] for i in items] == ["pending"] * 5
assert [i["state"] for i in items] == ["pending"] * 4
def test_build_step_items_maps_internal_ai_summary_to_optional_ai_step():
def test_build_step_items_maps_internal_ai_summary_to_review_step():
items = build_step_items("ai_summary")
assert [i["state"] for i in items] == ["done", "done", "current", "pending", "pending"]
assert [i["state"] for i in items] == ["done", "current", "pending", "pending"]
+39 -12
View File
@@ -3,13 +3,11 @@ from __future__ import annotations
from pathlib import Path
import yaml
from services.blueprint_proposals import (
save_blueprint_proposal,
list_blueprint_proposals,
load_blueprint_proposal,
build_type_config_from_proposal,
update_blueprint_proposal,
)
@@ -33,29 +31,58 @@ def test_save_list_load_blueprint_proposal(tmp_path: Path):
analysis_engine="hybrid",
)
assert saved.path.parent == tmp_path
assert saved.path.name.endswith("odd_name.yaml")
assert "odd_name" in saved.path.name
assert saved.path.suffix == ".yaml"
assert ".." not in saved.path.name
proposals = list_blueprint_proposals(tmp_path)
assert [p.path for p in proposals] == [saved.path]
payload = load_blueprint_proposal(saved.path)
assert payload["proposal_version"] == 1
assert payload["proposal_version"] == 3
assert payload["revision"] == 1
assert payload["candidate_config_hash"]
assert payload["evidence_set_hash"]
assert payload["status"] == "draft"
assert payload["source_workbook_name"] == "offer.xlsx"
assert payload["blueprint"]["mappings"][0]["sql_target"] == "generated_barcode"
assert "samples" not in payload["blueprint"]["summaries"][0]["columns"][0]
def test_build_type_config_from_proposal(tmp_path: Path):
def test_proposal_revision_prevents_stale_admin_updates(tmp_path: Path):
saved = save_blueprint_proposal(
tmp_path,
blueprint=_sample_blueprint(),
proposal_name="My Learned Type",
proposal_name="Revision Test",
source_workbook_name="offer.xlsx",
selected_type="",
analysis_engine="fuzzy",
)
payload = load_blueprint_proposal(saved.path)
cfg = build_type_config_from_proposal(payload, "My Learned Type")
assert cfg["type_id"] == "my_learned_type"
assert cfg["mapping"][0]["target"] == "generated_barcode"
yaml.safe_dump(cfg)
first = update_blueprint_proposal(saved.path, expected_revision=1, status="validating")
assert first["revision"] == 2
try:
update_blueprint_proposal(saved.path, expected_revision=1, status="failed")
except ValueError as exc:
assert "changed since it was opened" in str(exc)
else:
raise AssertionError("stale proposal revision should be rejected")
def test_proposal_lifecycle_rejects_invalid_transition(tmp_path: Path):
saved = save_blueprint_proposal(
tmp_path,
blueprint=_sample_blueprint(),
proposal_name="Lifecycle Test",
source_workbook_name="offer.xlsx",
selected_type="",
analysis_engine="fuzzy",
)
update_blueprint_proposal(saved.path, expected_revision=1, status="rejected")
try:
update_blueprint_proposal(saved.path, expected_revision=2, status="validated")
except ValueError as exc:
assert "invalid proposal status transition" in str(exc)
else:
raise AssertionError("rejected proposal should not return to validated")
+148
View File
@@ -0,0 +1,148 @@
"""Regression tests for config-driven Candy workbook recognition and mapping."""
from pathlib import Path
from services.config_manager import ConfigManager
from services.excel_parser import ExcelParser
from services.fingerprint import Fingerprint
from services.row_quality import split_rows_by_quality
from services.workbook_analyzer import WorkbookAnalyzer
from services.workbook_selection import filter_parsed_workbook_sheets, recommend_workbook_sheets
from ui.preview_page import _build_merged_rows
CANDY_TOY = Path("ref_files/candy_toy.xlsx")
CANDY_BCL = Path("ref_files/candy_bcl.xlsx")
def _scoped_analysis(path: Path, sheet_index: int):
cm = ConfigManager()
parsed = ExcelParser(cm).parse(path, type_id="candy")
sheet_name = parsed.sheets[sheet_index].name
scoped = filter_parsed_workbook_sheets(parsed, [sheet_name])
analysis = WorkbookAnalyzer(cm).analyze(
scoped,
preferred_type_id="candy",
use_llm=False,
)
return cm, scoped, analysis
def _preview_rows(cm, parsed, analysis):
cfg = cm.get_type_config("candy") or {}
return _build_merged_rows(
parsed,
{
"summaries": analysis.summaries,
"groups": analysis.groups,
"mappings": analysis.mappings,
},
derived_fields=cfg.get("derived_fields", []),
)
def test_candy_fixtures_match_alternative_config_profiles_at_100_percent():
cm = ConfigManager()
parser = ExcelParser(cm)
fingerprint = Fingerprint(cm)
for fixture in (CANDY_TOY, CANDY_BCL):
assert fixture.exists(), fixture
parsed = parser.parse(fixture)
matches = fingerprint.recognize(fingerprint.compute_signature(parsed))
assert matches[0].type_id == "candy"
assert matches[0].score == 100.0
def test_candy_toy_uses_configured_logical_headers_and_data_start():
cm, parsed, analysis = _scoped_analysis(CANDY_TOY, 0)
sheet = parsed.sheets[0]
assert sheet.header_row == 1
assert sheet.data_start_row == 7
assert sheet.detected_headers[14:17] == ["DP / CTN", "PCS / DP", "PCS / CTN"]
mapping = {m.sql_target: m.excel_column for m in analysis.mappings}
assert mapping["generated_barcode"] == "JAN"
assert mapping["pcs_ctn"] == "PCS / CTN"
assert mapping["dp_ctn"] == "DP / CTN"
assert mapping["pcs_dp"] == "PCS / DP"
rows = _preview_rows(cm, parsed, analysis)
assert str(rows[0]["generated_barcode"]) == "4570117932342"
assert rows[0]["pcs_ctn"] == 200
assert rows[0]["dp_ctn"] == 200
assert rows[0]["pcs_dp"] == 1
def test_candy_bcl_paste_mapping_is_exact_and_derives_pcs_per_carton():
cm, parsed, analysis = _scoped_analysis(CANDY_BCL, 3)
sheet = parsed.sheets[0]
assert sheet.header_row == 2
assert sheet.data_start_row == 5
assert "DP / CTN" in sheet.detected_headers
assert "PCS / DP" in sheet.detected_headers
assert "一次メーカー" in sheet.detected_headers
mapping = {m.sql_target: m.excel_column for m in analysis.mappings}
assert mapping["generated_barcode"] == "JANコード"
assert mapping["sap"] == "品目コード"
assert mapping["item_name_eng"] == "商品名"
assert mapping["vendor"] == "一次メーカー"
assert all(m.confidence == 1.0 and m.reason.startswith("Exact type mapping") for m in analysis.mappings)
rows = _preview_rows(cm, parsed, analysis)
first = next(row for row in rows if str(row.get("generated_barcode")) == "4570117928949")
assert first["dp_ctn"] == 1
assert first["pcs_dp"] == 10
assert first["pcs_ctn"] == 10
def test_candy_bcl_guide_header_rule_prevents_first_data_row_becoming_header():
cm, parsed, analysis = _scoped_analysis(CANDY_BCL, 4)
sheet = parsed.sheets[0]
assert sheet.header_row == 7
assert sheet.data_start_row == 8
assert "JAN" in sheet.detected_headers
assert "english" in sheet.detected_headers
assert sheet.detected_headers[21:25] == ["DP / CTN", "×", "PCS / DP", "PCS / CTN"]
rows = _preview_rows(cm, parsed, analysis)
quality = split_rows_by_quality(rows, key_columns=["generated_barcode"])
assert len(quality.export_rows) == 38
assert any(issue.code == "duplicate_sap" for issue in quality.blocking_issues)
first = quality.export_rows[0].row
assert first["generated_barcode"] == "4570117931901"
assert first["item_name_eng"] == "ULTRAMAN SOFVI PACKAGE CHARM & CHOCO SNACKS"
assert first["pcs_ctn"] == 120
def test_candy_deterministic_analysis_only_uses_yaml_approved_sources():
cm, _, analysis = _scoped_analysis(CANDY_BCL, 3)
cfg = cm.get_type_config("candy") or {}
approved = {
str(pattern).strip()
for entry in cfg.get("mapping", [])
for pattern in entry.get("source_patterns", [])
if str(pattern).strip()
}
assert {m.excel_column for m in analysis.mappings}.issubset(approved)
assert ("BNA", "battery") not in {
(m.excel_column, m.sql_target) for m in analysis.mappings
}
def test_candy_config_recommends_toy_and_bcl_guide_sheets_without_forcing_paste_sheet():
cm = ConfigManager()
patterns = cm.get_recommended_sheet_patterns("candy")
parser = ExcelParser(cm)
toy = parser.parse(CANDY_TOY)
bcl = parser.parse(CANDY_BCL)
assert recommend_workbook_sheets([sheet.name for sheet in toy.sheets], patterns).selected == ["Sheet1"]
recommendation = recommend_workbook_sheets([sheet.name for sheet in bcl.sheets], patterns)
assert recommendation.selected == ["案内リスト"]
assert "貼り付け" not in recommendation.selected
+28
View File
@@ -159,6 +159,34 @@ class TestConfigManager:
settings = cm.get_settings()
assert settings["fuzzy"]["default_threshold"] == 75
def test_operator_quality_settings_have_safe_defaults(self, temp_config_dir):
cm = ConfigManager(config_dir=temp_config_dir)
assert cm.get_mapping_review_attention_threshold() == 0.85
assert cm.get_export_audit_log_path() == temp_config_dir.parent / "data" / "audit" / "export_quality.jsonl"
assert cm.get_recommended_sheet_patterns("test_type") == []
assert cm.get_supported_upload_extensions() == [".xlsx"]
assert cm.get_max_upload_size_mb() == 200
def test_operator_review_policy_limits_mapping_targets_and_labels(self, temp_config_dir):
settings_path = temp_config_dir / "settings.yaml"
settings = yaml.safe_load(settings_path.read_text(encoding="utf-8")) or {}
settings["operator_review"] = {
"allow_header_row_override": False,
"allow_restore_dropped_rows": False,
"mapping_target_allowlist": ["generated_barcode"],
"field_labels": {"generated_barcode": "Barcode / JAN code"},
}
settings_path.write_text(yaml.safe_dump(settings), encoding="utf-8")
cm = ConfigManager(config_dir=temp_config_dir)
assert cm.get_operator_review_config()["allow_header_row_override"] is False
assert cm.get_operator_review_config()["allow_restore_dropped_rows"] is False
assert cm.get_operator_mapping_targets() == ["generated_barcode"]
assert cm.get_operator_field_label("generated_barcode") == "Barcode / JAN code"
assert cm.get_operator_field_label("item_name_eng") == "Name EN"
def test_ai_debug_log_config_defaults_to_project_data_debug(self, temp_config_dir):
cm = ConfigManager(config_dir=temp_config_dir)
+39 -1
View File
@@ -4,7 +4,7 @@ import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import pytest
from services.config_validator import ConfigValidator, ValidationResult
from services.config_validator import ConfigValidator
@pytest.fixture
@@ -105,3 +105,41 @@ class TestConfigValidator:
}
result = validator.validate(cfg)
assert len(result.warnings) > 0
def test_valid_multiply_derived_field(self, validator):
cfg = {
"mapping": [],
"derived_fields": [{
"target": "generated_barcode",
"operation": "multiply",
"sources": ["jp_bai_launch", "item_name_eng"],
}],
}
result = validator.validate(cfg)
assert result.errors == []
def test_invalid_derived_field_operation_and_source(self, validator):
cfg = {
"mapping": [],
"derived_fields": [{
"target": "generated_barcode",
"operation": "python_eval",
"sources": ["item_name_eng", "not_a_column"],
}],
}
result = validator.validate(cfg)
assert any("unsupported operation" in error for error in result.errors)
assert any("not_a_column" in error for error in result.errors)
def test_recommended_sheet_patterns_must_be_non_empty_string_list(self, validator):
valid = validator.validate({
"mapping": [],
"sheet_selection": {"recommended_patterns": ["Sheet*", "案内リスト"]},
})
assert not any("recommended_patterns" in error for error in valid.errors)
invalid = validator.validate({
"mapping": [],
"sheet_selection": {"recommended_patterns": "Sheet*"},
})
assert any("must be a list" in error for error in invalid.errors)
-1
View File
@@ -1,7 +1,6 @@
"""End-to-end test using the real kuji_bntw.xlsx sample file."""
from pathlib import Path
from io import BytesIO
import os
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+1 -1
View File
@@ -7,7 +7,7 @@ import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from services.config_manager import ConfigManager
from services.excel_parser import ExcelParser, ParsedWorkbook, ParsedSheet, FormField
from services.excel_parser import ExcelParser, ParsedWorkbook
@pytest.fixture
+37 -1
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from pathlib import Path
from services.blueprint_proposals import load_blueprint_proposal
from ui.export_page import save_export_blueprint_proposal
from ui.export_page import save_export_blueprint_proposal, _combine_validation_runs
class _FakeConfig:
@@ -40,3 +40,39 @@ def test_export_save_writes_temporary_proposal_not_type_config(tmp_path: Path):
assert payload["source_workbook_name"] == "offer.xlsx"
assert payload["selected_type"] == "kuji_tw"
assert payload["blueprint"]["mappings"][0]["sql_target"] == "generated_barcode"
def test_multiple_workbook_replays_are_aggregated_for_promotion():
candidate = {"type_id": "learned", "label": "Learned"}
previous = {"status": "validated", "errors": [], "warnings": [], "export_row_count": 2}
current = {"status": "validated", "errors": [], "warnings": ["reviewed"], "export_row_count": 3}
combined = _combine_validation_runs(previous, current, candidate, ["one", "two"])
assert combined["status"] == "validated"
assert len(combined["replay_matrix"]) == 2
assert combined["matrix_valid_count"] == 2
assert combined["warnings"] == ["reviewed"]
assert combined["candidate_config_hash"]
assert combined["evidence_set_hash"]
def test_new_candidate_invalidates_older_replay_matrix_entries():
first_candidate = {"type_id": "learned", "label": "First"}
first = _combine_validation_runs(
{},
{"status": "validated", "errors": [], "warnings": [], "validation_run_id": "run-1"},
first_candidate,
["one"],
current_evidence_ids=["one"],
)
changed_candidate = {"type_id": "learned", "label": "Changed"}
combined = _combine_validation_runs(
first,
{"status": "validated", "errors": [], "warnings": [], "validation_run_id": "run-2"},
changed_candidate,
["one", "two"],
current_evidence_ids=["two"],
)
assert combined["status"] == "failed"
assert combined["matrix_valid_count"] == 1
assert any("older candidate" in error for error in combined["errors"])
+126
View File
@@ -0,0 +1,126 @@
"""Tests for export quality blocking and Admin override audit."""
from __future__ import annotations
import json
import pytest
from services.export_quality import (
build_issue_signature,
create_quality_override,
is_valid_quality_override,
write_quality_override_audit,
)
from services.row_quality import split_rows_by_quality
def test_quality_blocks_missing_both_keys_and_checks_each_unique_key_separately():
rows = [
{"generated_barcode": "111", "sap": "A", "item_name_eng": "One"},
{"generated_barcode": "111", "sap": "B", "item_name_eng": "Two"},
{"generated_barcode": "222", "sap": "B", "item_name_eng": "Three"},
{
"generated_barcode": "",
"sap": "",
"item_name_eng": "No key",
"package_size": "M",
"vendor": "Vendor",
},
]
quality = split_rows_by_quality(rows, key_columns=["generated_barcode", "sap"])
assert quality.can_export is False
assert [issue.code for issue in quality.blocking_issues].count("duplicate_generated_barcode") == 2
assert [issue.code for issue in quality.blocking_issues].count("duplicate_sap") == 2
assert [issue.code for issue in quality.blocking_issues].count("missing_both_item_keys") == 1
def test_empty_key_values_do_not_participate_in_duplicate_comparison():
rows = [
{"generated_barcode": "", "sap": "A", "item_name_eng": "One", "vendor": "V"},
{"generated_barcode": None, "sap": "B", "item_name_eng": "Two", "vendor": "V"},
]
quality = split_rows_by_quality(rows, key_columns=["generated_barcode", "sap"])
assert quality.can_export is True
assert quality.blocking_issues == []
def test_empty_export_is_blocked_with_a_workbook_level_issue():
quality = split_rows_by_quality([], key_columns=["generated_barcode", "sap"])
assert quality.can_export is False
assert [issue.code for issue in quality.blocking_issues] == ["no_export_candidates"]
assert quality.blocking_issues[0].row_index == -1
def test_numeric_and_string_keys_use_the_same_duplicate_comparison():
quality = split_rows_by_quality([
{"generated_barcode": 123.0, "sap": "A", "item_name_eng": "One"},
{"generated_barcode": "123", "sap": "B", "item_name_eng": "Two"},
])
assert quality.can_export is False
assert [issue.code for issue in quality.blocking_issues].count("duplicate_generated_barcode") == 2
def test_numeric_item_key_source_adds_leading_zero_warning():
quality = split_rows_by_quality(
[{"generated_barcode": "123", "sap": "A", "item_name_eng": "One"}],
numeric_key_sources={0: ["generated_barcode"]},
)
assert quality.can_export is True
assert [issue.code for issue in quality.warning_issues] == ["numeric_item_key"]
def test_unrestored_dropped_rows_do_not_block_but_restored_rows_are_checked():
rows = [
{"generated_barcode": "111", "sap": "A", "item_name_eng": "One"},
{"generated_barcode": "111"},
]
dropped = split_rows_by_quality(rows, key_columns=["generated_barcode", "sap"])
restored = split_rows_by_quality(rows, key_columns=["generated_barcode", "sap"], restore_indexes={1})
assert dropped.can_export is True
assert restored.can_export is False
assert any(issue.code == "duplicate_generated_barcode" for issue in restored.blocking_issues)
assert any(issue.code == "restored_sparse_row" for issue in restored.warning_issues)
def test_admin_override_requires_reason_and_invalidates_when_issue_signature_changes(tmp_path):
quality = split_rows_by_quality([
{"generated_barcode": "1", "sap": "A", "item_name_eng": "One"},
{"generated_barcode": "1", "sap": "B", "item_name_eng": "Two"},
])
with pytest.raises(ValueError):
create_quality_override("hash", quality, "too short")
override = create_quality_override("hash", quality, "Approved duplicate batch")
assert is_valid_quality_override(override, "hash", quality) is True
assert is_valid_quality_override(override, "different", quality) is False
changed = split_rows_by_quality([
{"generated_barcode": "1", "sap": "A", "item_name_eng": "One"},
])
assert build_issue_signature("hash", changed) != override["issue_signature"]
assert is_valid_quality_override(override, "hash", changed) is False
audit_path = tmp_path / "audit" / "quality.jsonl"
write_quality_override_audit(
audit_path,
override=override,
quality=quality,
workbook_name="sample.xlsx",
selected_type="candy",
selected_sheets=["Sheet1"],
)
payload = json.loads(audit_path.read_text(encoding="utf-8").strip())
assert payload["role"] == "Admin"
assert payload["issue_codes"] == {"duplicate_generated_barcode": 2}
assert payload["row_indexes"] == [0, 1]
assert "cell" not in json.dumps(payload).lower()
assert "One" not in json.dumps(payload)
+12
View File
@@ -16,3 +16,15 @@ def test_generated_barcode_removes_all_whitespace():
def test_string_schema_fields_are_trimmed_but_not_inner_spaced():
cm = ConfigManager()
assert transform_field_value(cm, "item_name_eng", " GRADE A: Figure ") == "GRADE A: Figure"
def test_numeric_item_keys_are_normalized_to_stable_strings():
cm = ConfigManager()
assert transform_field_value(cm, "generated_barcode", 4573102682116) == "4573102682116"
assert transform_field_value(cm, "generated_barcode", 123.0) == "123"
assert transform_field_value(cm, "sap", 90001) == "90001"
def test_non_string_schema_values_keep_their_native_type():
cm = ConfigManager()
assert transform_field_value(cm, "pcs_ctn", 12) == 12
+24
View File
@@ -0,0 +1,24 @@
"""Atomic-write and append-lock regression tests."""
from concurrent.futures import ThreadPoolExecutor
import json
from services.file_store import append_jsonl, atomic_write_text
def test_atomic_write_replaces_content_without_temp_residue(tmp_path):
path = tmp_path / "config.yaml"
atomic_write_text(path, "first")
atomic_write_text(path, "second")
assert path.read_text(encoding="utf-8") == "second"
assert list(tmp_path.glob("*.tmp")) == []
assert list(tmp_path.glob("*.lock")) == []
def test_concurrent_jsonl_appends_remain_complete(tmp_path):
path = tmp_path / "audit.jsonl"
with ThreadPoolExecutor(max_workers=6) as pool:
list(pool.map(lambda index: append_jsonl(path, {"index": index}), range(20)))
records = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]
assert sorted(record["index"] for record in records) == list(range(20))
+164
View File
@@ -0,0 +1,164 @@
"""Controlled format-learning service tests."""
from __future__ import annotations
from pathlib import Path
import openpyxl
from services.candidate_type_builder import build_candidate_type_config
from services.config_manager import ConfigManager
from services.format_similarity import compare_evidence_to_type
from services.learning_evidence import (
build_learning_evidence,
load_learning_evidence,
save_learning_evidence,
)
from services.proposal_validator import validate_candidate_replay
from services.row_quality import split_rows_by_quality
from services.excel_parser import ParsedSheet, ParsedWorkbook
def _blueprint():
return {
"summaries": [{
"sheet_name": "Sample",
"header_row": 1,
"sheet_type": "detail",
"columns": [
{"header": "LEARN_UNIQUE_BARCODE", "samples": ["secret-1"]},
{"header": "LEARN_UNIQUE_SAP", "samples": ["secret-2"]},
{"header": "LEARN_UNIQUE_ITEM", "samples": ["private name"]},
],
"shared_values": [{"label": "Private", "value": "secret"}],
}],
"groups": [],
"mappings": [
{"excel_column": "LEARN_UNIQUE_BARCODE", "sql_target": "generated_barcode", "confidence": 1.0, "reason": "confirmed"},
{"excel_column": "LEARN_UNIQUE_SAP", "sql_target": "sap", "confidence": 1.0, "reason": "confirmed"},
{"excel_column": "LEARN_UNIQUE_ITEM", "sql_target": "item_name_eng", "confidence": 0.95, "reason": "confirmed"},
],
}
def _parsed():
return ParsedWorkbook(file_name="private.xlsx", sheets=[ParsedSheet(
name="Sample", rows=3, cols=3, header_row=1, data_start_row=2, data_end_row=3,
detected_headers=["LEARN_UNIQUE_BARCODE", "LEARN_UNIQUE_SAP", "LEARN_UNIQUE_ITEM"],
)])
def _evidence(tmp_path: Path):
quality = split_rows_by_quality([
{"generated_barcode": "A", "sap": "S1", "item_name_eng": "One"},
{"generated_barcode": "B", "sap": "S2", "item_name_eng": "Two"},
], key_columns=["generated_barcode", "sap"])
evidence = build_learning_evidence(
workbook_hash="a" * 64,
workbook_name="private.xlsx",
parsed=_parsed(),
blueprint=_blueprint(),
selected_type="",
selected_sheets=["Sample"],
recommended_sheets=["Sample"],
matched_patterns=["Sample"],
selection_source="operator",
fingerprint_matches=[],
quality=quality,
export_row_count=2,
analysis_engine="yaml",
reviewed_snapshot_hash="snapshot-123",
restored_row_indexes=[7],
)
return evidence
def test_learning_evidence_is_privacy_safe_and_deduplicated(tmp_path: Path):
evidence = _evidence(tmp_path)
first = save_learning_evidence(tmp_path, evidence)
second = save_learning_evidence(tmp_path, evidence)
assert first.path == second.path
loaded = load_learning_evidence(first.path)
text = first.path.read_text(encoding="utf-8")
assert loaded["privacy"]["contains_raw_cell_values"] is False
assert "secret-1" not in text
assert "private name" not in text
assert loaded["analysis"]["mapping_count"] == 3
assert loaded["evidence_version"] == 2
assert loaded["review_confirmation"]["reviewed_snapshot_hash"] == "snapshot-123"
assert loaded["review_confirmation"]["restored_row_indexes"] == [7]
def test_similarity_classifies_existing_variant_with_explanations(tmp_path: Path):
evidence = _evidence(tmp_path)
config = build_candidate_type_config("Learned", _blueprint(), evidence)
result = compare_evidence_to_type(evidence, config)
assert result.classification == "existing_variant"
assert result.score == 100.0
assert len(result.reasons) == 4
def test_similarity_penalizes_unexplained_extra_headers_and_sheets(tmp_path: Path):
evidence = _evidence(tmp_path)
config = build_candidate_type_config("Learned", _blueprint(), evidence)
changed = {**evidence}
changed["sheet_selection"] = {
**evidence["sheet_selection"],
"selected": ["Sample", "Unexpected"],
}
changed["sheets"] = [
*evidence["sheets"],
{
"name": "Unexpected",
"selected": True,
"detected_headers": ["UNRELATED", "EXTRA"],
},
]
result = compare_evidence_to_type(changed, config)
assert result.score < 100
assert result.score > 0
def test_variant_builder_adds_profile_without_overwriting_existing_mapping(tmp_path: Path):
evidence = _evidence(tmp_path)
existing = {
"type_id": "learned",
"label": "Learned",
"structure": {"header_pattern": {"keywords": ["OLD"]}, "sheet_rules": []},
"sheet_selection": {"recommended_patterns": ["Old"]},
"fingerprint_profiles": [{"name": "old", "headers": ["OLD"]}],
"mapping": [{"source_patterns": ["OLD JAN"], "target": "generated_barcode"}],
}
candidate = build_candidate_type_config("Ignored", _blueprint(), evidence, existing_config=existing)
assert candidate["type_id"] == "learned"
barcode = next(item for item in candidate["mapping"] if item["target"] == "generated_barcode")
assert barcode["source_patterns"] == ["OLD JAN", "LEARN_UNIQUE_BARCODE"]
assert len(candidate["fingerprint_profiles"]) == 2
assert candidate["matching"]["fuzzy_enabled"] is False
def test_candidate_replay_preserves_export_contract(tmp_path: Path):
workbook_path = tmp_path / "learning.xlsx"
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = "Sample"
sheet.append(["LEARN_UNIQUE_BARCODE", "LEARN_UNIQUE_SAP", "LEARN_UNIQUE_ITEM"])
sheet.append(["A", "S1", "One"])
sheet.append(["B", "S2", "Two"])
workbook.save(workbook_path)
cm = ConfigManager()
evidence = _evidence(tmp_path)
candidate = build_candidate_type_config("Unique Learning Test", _blueprint(), evidence)
result = validate_candidate_replay(cm, candidate, workbook_path.read_bytes(), workbook_path.name, evidence)
assert result.status == "validated"
assert result.recognized_type == "unique_learning_test"
assert result.export_row_count == 2
assert result.blocking_issue_count == 0
assert result.output_sheet_name == "pre_item_master"
assert result.output_column_count == 57
assert result.candidate_config_hash
assert result.evidence_set_hash
assert result.validation_run_id
assert result.validated_at
+3
View File
@@ -75,6 +75,9 @@ def test_build_learned_type_config_matches_existing_type_schema():
assert cfg["structure"]["header_pattern"]["strategy"] == "max_keyword_match"
assert "Product contents" in cfg["structure"]["header_pattern"]["keywords"]
assert "fingerprint_headers" in cfg
assert cfg["fingerprint_profiles"][0]["headers"] == cfg["fingerprint_headers"]
assert cfg["sheet_selection"]["recommended_patterns"] == ["DISNEY", "Item detail"]
assert cfg["learning"]["fuzzy_expansion"] is False
assert "STYLE" in cfg["fingerprint_headers"]
assert "SALES JAN CODE" in cfg["fingerprint_headers"]
+1 -1
View File
@@ -7,7 +7,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import pytest
from services.config_manager import ConfigManager
from services.llm_stages import (
LLMStages, SheetSummary, MergeGroup, MergeLink, ColumnMapping,
LLMStages, SheetSummary, MergeGroup, ColumnMapping,
)
-1
View File
@@ -3,7 +3,6 @@ from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import pytest
from services.merge_engine import MergeEngine
from services.llm_stages import MergeLink
+5
View File
@@ -13,6 +13,7 @@ RETIRED_MARKERS = (
"services.value_matcher",
"ui.i18n",
"use_container_width",
"df.style",
)
@@ -27,6 +28,10 @@ def test_runtime_has_no_retired_imports_or_apis():
source = _runtime_python()
for marker in RETIRED_MARKERS:
assert marker not in source
assert "'/models'" not in source
assert '"/models"' not in source
assert "nbd-result-strip" not in source
assert "nbd-wizard-item" not in source
def test_retired_modules_are_absent():
+171 -17
View File
@@ -1,18 +1,31 @@
"""Tests for simplified Review-stage helpers."""
from __future__ import annotations
from services.excel_parser import ParsedSheet
from services.excel_parser import ParsedSheet, ParsedWorkbook
from services.llm_stages import ColumnMapping
from services.review_overrides import apply_header_row_override, build_column_mapping_result
from services.row_quality import split_rows_by_quality
from services.row_builder import build_merged_rows
from services.row_quality import QualityIssue, split_rows_by_quality
from services.review_policy import build_review_gate, classify_mapping_review
from services.workbook_analyzer import AnalysisResult
from ui.confirm_page import (
_build_mapping_editor_rows,
_build_sheet_cursor_preview,
_column_samples,
_operator_alert_warnings,
_review_rebuild_cache_key,
_sheet_review_signature,
build_ai_recommendation,
)
from ui.preview_page import resolve_preview_back_step
from ui.preview_page import _friendly_preview_frame, _quality_issue_rows
class _FriendlyFieldConfig:
@staticmethod
def get_operator_field_label(field_name: str) -> str:
return {
"generated_barcode": "Barcode / JAN code",
"sap": "SAP item code",
}.get(field_name, field_name.replace("_", " ").title())
def test_apply_header_row_override_rebuilds_headers_and_data_start():
@@ -65,19 +78,117 @@ def test_header_cursor_preview_marks_selected_dataframe_row():
assert preview.loc[1, "B"] == "JAN"
def test_mapping_rows_follow_current_headers_and_preserve_matching_manual_edits():
rows = _build_mapping_editor_rows(
headers=["STYLE", "JAN"],
existing={"STYLE": "package_style", "JAN": "generated_barcode"},
previous={"STYLE": "package_name"},
def test_column_samples_are_bounded_deduplicated_and_start_after_header():
parsed = ParsedWorkbook(sheets=[ParsedSheet(
name="Items",
header_row=2,
data_start_row=3,
data_end_row=6,
raw_data=[
["Report", None],
["JAN", "NAME"],
["111", "Prize A"],
["111", "Duplicate"],
["222", "Prize B"],
["333", "Prize C"],
],
detected_headers=["JAN", "NAME"],
col_headers={0: "JAN", 1: "NAME"},
)])
assert _column_samples(parsed, "JAN", limit=2) == "111 · 222"
assert _column_samples(parsed, "MISSING") == ""
def test_review_rebuild_cache_key_changes_only_with_review_inputs():
parsed = ParsedWorkbook(sheets=[ParsedSheet(
name="Items",
header_row=1,
detected_headers=["JAN", "NAME"],
)])
original = _review_rebuild_cache_key(parsed, "candy")
assert original == _review_rebuild_cache_key(parsed, "candy")
parsed.sheets[0].header_row = 2
assert original != _review_rebuild_cache_key(parsed, "candy")
def test_sheet_review_confirmation_signature_invalidates_after_header_change():
sheet = ParsedSheet(
name="Items",
header_row=1,
data_start_row=2,
detected_headers=["JAN", "NAME"],
)
assert rows == [
{"Excel Column": "STYLE", "Database Column": "package_name"},
{"Excel Column": "JAN", "Database Column": "generated_barcode"},
confirmed = _sheet_review_signature(sheet)
assert confirmed == _sheet_review_signature(sheet)
sheet.header_row = 2
sheet.data_start_row = 3
sheet.detected_headers = ["111", "Prize A"]
assert confirmed != _sheet_review_signature(sheet)
def test_row_builder_source_metadata_is_opt_in_and_tracks_excel_rows():
parsed = ParsedWorkbook(sheets=[ParsedSheet(
name="Items",
header_row=1,
data_start_row=2,
data_end_row=3,
raw_data=[
["JAN", "NAME"],
["111", "Prize A"],
["222", "Prize B"],
],
detected_headers=["JAN", "NAME"],
col_headers={0: "JAN", 1: "NAME"},
)])
blueprint = {
"summaries": [{"sheet_name": "Items", "header_row": 1, "shared_values": []}],
"groups": [],
"mappings": [
ColumnMapping("JAN", "generated_barcode", 1.0, "Exact"),
ColumnMapping("NAME", "item_name_eng", 1.0, "Exact"),
],
}
normal = build_merged_rows(parsed, blueprint)
traced = build_merged_rows(parsed, blueprint, include_source_metadata=True)
assert "__source_sheet" not in normal[0]
assert [(row["__source_sheet"], row["__source_row"]) for row in traced] == [
("Items", 2),
("Items", 3),
]
def test_preview_helpers_use_friendly_fields_and_original_source_location():
cm = _FriendlyFieldConfig()
frame = _friendly_preview_frame(
cm,
[{"generated_barcode": "111", "sap": "A"}],
["generated_barcode", "sap"],
)
issue_rows = _quality_issue_rows(
[QualityIssue(
code="duplicate_generated_barcode",
row_index=0,
field="generated_barcode",
issue="Duplicate non-empty generated_barcode in this export batch.",
suggestion="Keep one unique generated_barcode value per product row.",
)],
cm,
[{"sheet": "Items", "row": 12}],
)
assert frame.columns.tolist() == ["Barcode / JAN code", "SAP item code"]
assert issue_rows[0]["Source sheet"] == "Items"
assert issue_rows[0]["Excel row"] == 12
assert "generated_barcode" not in issue_rows[0]["Issue"]
def test_known_format_fallback_note_is_not_operator_alert():
warnings = [
"Using known format 'KUJI TW' as fallback",
@@ -87,11 +198,6 @@ def test_known_format_fallback_note_is_not_operator_alert():
assert _operator_alert_warnings(warnings) == ["Stage 1 failed for every sheet"]
def test_preview_back_to_review_never_routes_into_disabled_ai_page():
assert resolve_preview_back_step(has_ai_result=False, ai_available=False) == "confirm"
assert resolve_preview_back_step(has_ai_result=True, ai_available=True) == "confirm"
def test_build_column_mapping_result_uses_manual_targets_and_drops_blank_targets():
original = AnalysisResult(
mappings=[ColumnMapping("STYLE", "package_style", 1.0, "Known mapping")],
@@ -110,6 +216,18 @@ def test_build_column_mapping_result_uses_manual_targets_and_drops_blank_targets
assert updated.engine == "manual"
def test_build_column_mapping_result_preserves_unedited_confidence_for_attention_review():
original = AnalysisResult(
mappings=[ColumnMapping("SAP", "sap", 0.72, "Fuzzy mapping")],
engine="yaml",
)
updated = build_column_mapping_result(original, {"SAP": "sap"})
assert updated.mappings[0].confidence == 0.72
assert updated.mappings[0].reason == "Fuzzy mapping"
def test_split_rows_by_quality_drops_sparse_rows_and_can_restore_original_order():
rows = [
{"generated_barcode": "111", "item_name_eng": "Prize A", "package_size": "M"},
@@ -131,3 +249,39 @@ def test_build_ai_recommendation_only_suggests_ai_when_basic_review_needs_help()
assert build_ai_recommendation(strong, score=92.0, llm_enabled=True)["recommend"] is False
assert build_ai_recommendation(weak, score=55.0, llm_enabled=True)["recommend"] is True
assert build_ai_recommendation(weak, score=55.0, llm_enabled=False)["available"] is False
def test_mapping_attention_classifies_unmapped_low_confidence_and_duplicate_targets():
mappings = [
ColumnMapping("JAN", "generated_barcode", 0.95, "Exact"),
ColumnMapping("SAP A", "sap", 0.70, "Fuzzy"),
ColumnMapping("SAP B", "sap", 0.99, "Manual"),
]
items = classify_mapping_review(
["JAN", "SAP A", "SAP B", "NAME"], mappings, attention_threshold=85
)
by_header = {item.excel_column: item for item in items}
assert by_header["JAN"].needs_attention is False
assert by_header["SAP A"].status == "Conflict"
assert by_header["SAP B"].status == "Conflict"
assert by_header["NAME"].status == "Unmapped"
def test_review_gate_requires_header_key_mapping_and_unique_targets():
from services.excel_parser import ParsedWorkbook
parsed = ParsedWorkbook(file_name="book.xlsx", sheets=[ParsedSheet(
name="Items", header_row=1, detected_headers=["JAN", "SAP"]
)])
ready = build_review_gate(parsed, [ColumnMapping("JAN", "generated_barcode", 1.0, "Exact")])
assert ready.can_continue is True
blocked = build_review_gate(parsed, [
ColumnMapping("JAN", "item_name_eng", 1.0, "Manual"),
ColumnMapping("SAP", "item_name_eng", 1.0, "Manual"),
])
assert blocked.can_continue is False
assert any("item key" in reason for reason in blocked.blocking_reasons)
assert any("duplicate" in reason.lower() for reason in blocked.blocking_reasons)
+72
View File
@@ -0,0 +1,72 @@
"""Reviewed-snapshot immutability and invalidation tests."""
from services.excel_parser import ParsedSheet, ParsedWorkbook
from services.llm_stages import ColumnMapping
from services.review_snapshot import build_reviewed_snapshot, reviewed_snapshot_matches
def _parsed(header_row: int = 1):
return ParsedWorkbook(
file_name="book.xlsx",
sheets=[ParsedSheet(name="Items", header_row=header_row, detected_headers=["JAN", "SAP"])],
)
def _blueprint():
return {
"summaries": [],
"groups": [],
"mappings": [ColumnMapping("JAN", "generated_barcode", 1.0, "Reviewed")],
}
def test_reviewed_snapshot_matches_exact_reviewed_inputs():
parsed = _parsed()
blueprint = _blueprint()
snapshot = build_reviewed_snapshot(
workbook_hash="abc",
workbook_name="book.xlsx",
selected_type="candy",
selected_sheets=["Items"],
parsed=parsed,
analysis_source="basic",
blueprint=blueprint,
)
assert reviewed_snapshot_matches(
snapshot,
workbook_hash="abc",
selected_type="candy",
selected_sheets=["Items"],
parsed=parsed,
blueprint=blueprint,
)
def test_reviewed_snapshot_invalidates_on_header_mapping_sheet_or_type_change():
parsed = _parsed()
blueprint = _blueprint()
snapshot = build_reviewed_snapshot(
workbook_hash="abc",
workbook_name="book.xlsx",
selected_type="candy",
selected_sheets=["Items"],
parsed=parsed,
analysis_source="ai",
blueprint=blueprint,
)
parsed.sheets[0].header_row = 2
assert not reviewed_snapshot_matches(
snapshot, workbook_hash="abc", selected_type="candy",
selected_sheets=["Items"], parsed=parsed, blueprint=blueprint,
)
parsed.sheets[0].header_row = 1
blueprint["mappings"][0].sql_target = "sap"
assert not reviewed_snapshot_matches(
snapshot, workbook_hash="abc", selected_type="candy",
selected_sheets=["Items"], parsed=parsed, blueprint=blueprint,
)
assert not reviewed_snapshot_matches(
snapshot, workbook_hash="abc", selected_type="kuji_tw",
selected_sheets=["Items"], parsed=parsed, blueprint=_blueprint(),
)
-1
View File
@@ -3,7 +3,6 @@ from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import pytest
import yaml
+2
View File
@@ -16,6 +16,8 @@ def test_settings_example_exists_and_is_safe_template():
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
assert "llm" in data
assert data.get("security", {}).get("admin_password_hash", "") == ""
assert data.get("analysis", {}).get("mapping_review_attention_threshold") == 85
assert data.get("paths", {}).get("export_audit_log") == "data/audit/export_quality.jsonl"
for profile in (data.get("llm", {}).get("profiles") or {}).values():
assert str(profile.get("api_key", "")) == ""
text = path.read_text(encoding="utf-8")
+36 -26
View File
@@ -75,13 +75,15 @@ def _assert_layout_safe(page) -> None:
assert metrics["blockPaddingTop"] <= 40
def _assert_sidebar_wizard(page) -> None:
def _assert_four_step_workflow_without_sidebar_duplicate(page) -> None:
body = page.locator('body').inner_text()
assert '1. Upload' in body
assert '2. Review' in body
assert '3. Optional AI' in body
assert '4. Preview' in body
assert '5. Export' in body
assert 'Upload' in body
assert 'Review' in body
assert 'Preview' in body
assert 'Export' in body
assert 'Optional AI' not in body
assert '1. Upload' not in body
assert '2. Review' not in body
assert 'Select type' not in body
assert 'Join review' not in body
assert 'Mapping review' not in body
@@ -126,7 +128,7 @@ def test_streamlit_primary_buttons_do_not_raise_errors():
page.wait_for_selector('text=Upload a workbook', timeout=30000)
_assert_no_streamlit_error(page)
_assert_layout_safe(page)
_assert_sidebar_wizard(page)
_assert_four_step_workflow_without_sidebar_duplicate(page)
# Sidebar buttons / admin pages. Basic users should not see technical AI status controls.
assert 'Recheck AI' not in page.locator('body').inner_text()
@@ -166,36 +168,44 @@ def test_streamlit_primary_buttons_do_not_raise_errors():
# Main workbook flow.
page.locator('input[type="file"]').set_input_files(str(SAMPLE))
page.wait_for_selector('text=Basic type confidence', timeout=60000)
page.wait_for_selector('text=Continue to review', timeout=60000)
_assert_no_streamlit_error(page)
assert '100.0%' in page.locator('body').inner_text()
assert 'Recognised' in page.locator('body').inner_text()
page.locator('button').filter(has_text='Continue').first.click()
page.wait_for_selector('text=Analysis result', timeout=60000)
page.wait_for_selector('text=Column mapping to database', timeout=60000)
page.wait_for_selector('text=Review the workbook', timeout=60000)
page.wait_for_selector('text=Check output fields', timeout=60000)
for _ in range(20):
if 'All selected sheets are confirmed.' in page.locator('body').inner_text():
break
confirm_sheet = page.locator('button').filter(has_text='Confirm this sheet')
assert confirm_sheet.count() > 0
confirm_sheet.first.click()
page.wait_for_timeout(250)
assert 'All selected sheets are confirmed.' in page.locator('body').inner_text()
confirm_text = page.locator('body').inner_text()
assert 'Analysis result' in confirm_text
assert 'Review setup' in confirm_text
assert 'Header rows' in confirm_text
assert 'Cursor:' in confirm_text
assert 'Column mapping to database' in confirm_text
assert 'Use Basic Analysis' in confirm_text
assert 'Run Optional AI' in confirm_text
assert 'Review in progress' in confirm_text
assert 'Check the workbook setup' in confirm_text
assert 'Confirm the column names row' in confirm_text
assert 'Selected row:' in confirm_text
assert 'Check output fields' in confirm_text
assert 'Continue to preview' in confirm_text
assert 'Run optional AI' not in confirm_text
assert 'Continue to optional AI' not in confirm_text
assert "Using known format 'KUJI TW' as fallback" not in confirm_text
page.locator('button').filter(has_text='Use Basic Analysis').first.click()
page.wait_for_selector('text=Target sheet', timeout=60000)
page.locator('button').filter(has_text='Continue to preview').first.click()
page.wait_for_selector('text=Export sheet', timeout=60000)
preview_text = page.locator('body').inner_text()
assert 'Row quality check' in preview_text
_assert_no_streamlit_error(page)
assert 'generated_barcode' in page.locator('body').inner_text()
assert 'important fields' in preview_text
page.locator('button').filter(has_text='Back to review').first.click()
page.wait_for_selector('text=Review setup', timeout=60000)
page.wait_for_selector('text=Check the workbook setup', timeout=60000)
back_text = page.locator('body').inner_text()
assert 'Optional AI analysis' not in back_text
assert 'Review setup' in back_text
page.locator('button').filter(has_text='Use Basic Analysis').first.click()
page.wait_for_selector('text=Target sheet', timeout=60000)
page.locator('button').filter(has_text='Export').first.click()
assert 'Check the workbook setup' in back_text
page.locator('button').filter(has_text='Continue to preview').first.click()
page.wait_for_selector('text=Export sheet', timeout=60000)
page.locator('button').filter(has_text='Continue to export').first.click()
page.wait_for_selector('text=Workbook ready', timeout=60000)
_assert_no_streamlit_error(page)
+111
View File
@@ -0,0 +1,111 @@
"""Type config promotion and rollback safety tests."""
from __future__ import annotations
import json
from pathlib import Path
import shutil
import yaml
from services.config_manager import ConfigManager
from services.type_config_versions import (
list_type_config_versions,
promote_type_config,
rollback_type_config,
)
from services.validation_binding import bind_validation
def _isolated_config(tmp_path: Path) -> ConfigManager:
source = Path(__file__).resolve().parent.parent / "config"
target = tmp_path / "config"
shutil.copytree(source, target)
(target / "settings.yaml").write_text(
yaml.safe_dump({
"paths": {
"learning_audit_log": "runtime/audit.jsonl",
"type_config_archive_dir": "runtime/archive",
}
}),
encoding="utf-8",
)
return ConfigManager(target)
def test_promote_archives_current_config_reloads_and_redacts_audit(tmp_path: Path):
cm = _isolated_config(tmp_path)
type_id = cm.get_all_type_ids()[0]
before = dict(cm.get_type_config(type_id))
candidate = dict(before)
candidate["label"] = f"{before['label']} Updated"
validation = bind_validation(
{"status": "validated", "errors": [], "warnings": []},
candidate,
["evidence-1"],
)
archive = promote_type_config(
cm, candidate,
proposal_id="proposal-1",
evidence_ids=["evidence-1"],
reason="Validated operator format update",
validation=validation,
)
assert archive and archive.exists()
assert cm.get_type_config(type_id)["label"].endswith("Updated")
assert cm.get_type_config(type_id)["learning"]["candidate"] is False
assert cm.get_type_config(type_id)["learning"]["promotion_evidence_count"] == 1
audit = cm.get_learning_audit_log_path().read_text(encoding="utf-8")
assert "proposal-1" in audit
assert "raw_data" not in audit
assert len(list_type_config_versions(cm, type_id)) == 1
def test_rollback_preserves_active_version_and_restores_archive(tmp_path: Path):
cm = _isolated_config(tmp_path)
type_id = cm.get_all_type_ids()[0]
before_label = cm.get_type_config(type_id)["label"]
changed = dict(cm.get_type_config(type_id))
changed["label"] = "Changed label"
validation = bind_validation(
{"status": "validated", "errors": [], "warnings": []},
changed,
["evidence-2"],
)
archive = promote_type_config(
cm, changed,
proposal_id="proposal-2", evidence_ids=["evidence-2"],
reason="Create one version for rollback",
validation=validation,
)
rollback_type_config(cm, archive, reason="Restore verified previous configuration")
assert cm.get_type_config(type_id)["label"] == before_label
records = [json.loads(line) for line in cm.get_learning_audit_log_path().read_text(encoding="utf-8").splitlines()]
assert [record["action"] for record in records] == ["promote", "rollback"]
assert len(list_type_config_versions(cm, type_id)) == 2
def test_promote_rejects_replay_validation_for_an_edited_candidate(tmp_path: Path):
cm = _isolated_config(tmp_path)
type_id = cm.get_all_type_ids()[0]
candidate = dict(cm.get_type_config(type_id))
validation = bind_validation(
{"status": "validated", "errors": [], "warnings": []},
candidate,
["evidence-1"],
)
candidate["label"] = "Edited after replay"
try:
promote_type_config(
cm,
candidate,
proposal_id="stale-proposal",
evidence_ids=["evidence-1"],
reason="This replay result is intentionally stale",
validation=validation,
)
except ValueError as exc:
assert "stale" in str(exc)
assert "Candidate YAML changed" in str(exc)
else:
raise AssertionError("stale replay validation should block promotion")
-13
View File
@@ -1,15 +1,12 @@
"""Tests for AI-derived reusable type support notes."""
from __future__ import annotations
from pathlib import Path
import yaml
from services.llm_stages import SheetSummary, MergeGroup, MergeLink, ColumnMapping
from services.type_learning_notes import (
build_type_support_notes,
render_support_notes_for_prompt,
save_type_support_notes,
)
from services.workbook_analyzer import AnalysisResult
@@ -60,16 +57,6 @@ def test_build_type_support_notes_keeps_reusable_guidance_only():
assert "商品名/英語" in text
def test_save_type_support_notes_writes_type_scoped_yaml(tmp_path: Path):
notes = build_type_support_notes("kuji_tw", "sample.xlsx", _sample_result(), {"mapping_decisions": [], "join_decisions": []})
saved = save_type_support_notes(notes, tmp_path)
assert saved == tmp_path / "type_notes" / "kuji_tw.ai_notes.yaml"
loaded = yaml.safe_load(saved.read_text(encoding="utf-8"))
assert loaded["source_type"] == "kuji_tw"
def test_render_support_notes_for_prompt_is_compact_and_scoped():
notes = build_type_support_notes("kuji_tw", "sample.xlsx", _sample_result(), {
"mapping_decisions": [{"sql_target": "item_name_eng", "chosen_source": "商品名/英語", "reason": "Exact English name mapping"}],
+21 -1
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from services.excel_parser import ParsedSheet, ParsedWorkbook
from services.workbook_selection import filter_parsed_workbook_sheets
from services.workbook_selection import filter_parsed_workbook_sheets, recommend_workbook_sheets
def test_filter_parsed_workbook_sheets_keeps_workbook_order_and_metadata():
@@ -28,3 +28,23 @@ def test_filter_parsed_workbook_sheets_returns_all_when_selection_is_none():
filtered = filter_parsed_workbook_sheets(workbook, None)
assert [sheet.name for sheet in filtered.sheets] == ["A", "B"]
def test_recommended_patterns_are_case_insensitive_globs_in_workbook_order():
recommendation = recommend_workbook_sheets(
["Cover", "sheet1", "案内リスト", "貼り付け"],
["SHEET*", "案内*"],
)
assert recommendation.selected == ["sheet1", "案内リスト"]
assert recommendation.matched_patterns == ["SHEET*", "案内*"]
assert recommendation.used_fallback is False
def test_recommendation_falls_back_to_all_sheets_when_missing_or_unmatched():
names = ["Cover", "Items"]
assert recommend_workbook_sheets(names, None).selected == names
unmatched = recommend_workbook_sheets(names, ["Data*"])
assert unmatched.selected == names
assert unmatched.used_fallback is True
+278 -48
View File
@@ -1,82 +1,312 @@
"""Admin UI for reviewing temporary blueprint proposals."""
"""Admin review UI for controlled workbook-format learning."""
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
import streamlit as st
import yaml
from services.blueprint_proposals import (
archive_blueprint_proposal,
build_type_config_from_proposal,
list_blueprint_proposals,
load_blueprint_proposal,
update_blueprint_proposal,
)
from services.candidate_type_builder import build_candidate_type_config, render_config_diff
from services.config_manager import ConfigManager
from services.config_validator import ConfigValidator
from services.learned_blueprint import dump_learned_type_yaml, slugify_type_id
from services.learning_evidence import load_learning_evidence
from services.proposal_validator import validate_candidate_replay
from services.replay_matrix import combine_replay_validations
from services.type_config_versions import (
list_type_config_versions,
promote_type_config,
rollback_type_config,
write_learning_audit,
)
from services.validation_binding import validation_binding_errors
from ui.admin_guards import admin_reauth_ok, show_reauth_error
def render_blueprint_proposals(cm: ConfigManager) -> None:
"""Render pending blueprint proposal review/merge controls."""
st.subheader("🧩 Blueprint proposals")
st.caption("Basic users can save proposals here. Admin reviews, validates, then creates a new type or replaces an existing type.")
"""Render learning proposals, validation, promotion and rollback controls."""
st.subheader("Format Learning")
st.caption("Operator-confirmed formats remain proposals until an Admin reviews the evidence, replay result and config diff.")
settings = cm.get_learning_config()
with st.container(border=True, horizontal=True, vertical_alignment="center"):
st.badge("Enabled" if settings["enabled"] else "Disabled", color="green" if settings["enabled"] else "gray")
st.badge("Raw samples retained" if settings["retain_raw_samples"] else "No raw cell storage", color="orange" if settings["retain_raw_samples"] else "blue")
st.badge(f"{settings['minimum_workbooks_for_promotion']} evidence required", color="gray")
_render_pending(cm)
_render_history(cm)
def _render_pending(cm: ConfigManager) -> None:
st.markdown("#### Pending proposals")
proposal_dir = cm.get_tmp_blueprints_dir()
proposal_dir.mkdir(parents=True, exist_ok=True)
refs = list_blueprint_proposals(proposal_dir)
if not refs:
st.info(f"No pending proposals in {proposal_dir}.")
st.info("No pending learning proposals.")
return
labels = [f"{ref.path.name} · {ref.source_workbook_name or 'unknown workbook'} · {ref.mappings} mappings" for ref in refs]
idx = st.selectbox("Pending proposal", range(len(refs)), format_func=lambda i: labels[i])
ref = refs[int(idx)]
labels = [f"{ref.source_workbook_name or ref.path.name} · {ref.classification or 'unclassified'} · {ref.status}" for ref in refs]
index = st.selectbox("Proposal", range(len(refs)), format_func=lambda item: labels[item])
ref = refs[int(index)]
payload = load_blueprint_proposal(ref.path)
scope = ref.path.stem
similarity = payload.get("similarity") or {}
validation = payload.get("validation") or {}
st.markdown(
f"""
**Created:** `{payload.get('created_at', '')}`
**Workbook:** `{payload.get('source_workbook_name', '')}`
**Selected type:** `{payload.get('selected_type', '') or '(none)'}`
**Engine:** `{payload.get('analysis_engine', '')}`
"""
with st.container(border=True):
with st.container(horizontal=True, vertical_alignment="center"):
st.badge(str(payload.get("classification") or "unclassified").replace("_", " ").title(), color="blue")
st.badge(str(validation.get("status") or payload.get("status") or "draft").title(), color=_status_color(validation))
st.badge(f"{len(payload.get('evidence_ids') or [])} evidence", color="gray")
if similarity.get("best_type_id"):
st.badge(f"Closest: {similarity['best_type_id']} ({float(similarity.get('score', 0)):.1f}%)", color="gray")
st.caption(f"Workbook: {payload.get('source_workbook_name') or 'unknown'} · Engine: {payload.get('analysis_engine') or 'unknown'} · Created: {payload.get('created_at') or ''}")
st.caption(
f"Revision {int(payload.get('revision', 1) or 1)} · "
f"Candidate {str(payload.get('candidate_config_hash') or '')[:10]} · "
f"Evidence {str(payload.get('evidence_set_hash') or '')[:10]}"
)
for reason in similarity.get("reasons", []) or []:
st.caption(f"• {reason}")
evidence = _load_first_evidence(cm, payload)
original = payload.get("candidate_config") or {}
closest = str(similarity.get("best_type_id") or "")
options = ["(create new type)", *cm.get_all_type_ids()]
default = closest if payload.get("classification") == "existing_variant" and closest in options else "(create new type)"
target = st.selectbox("Promotion target", options, index=options.index(default), key=f"learning_target_{scope}")
type_name = st.text_input(
"Type label",
value=str(original.get("label") or Path(payload.get("source_workbook_name") or scope).stem.replace("_", " ").title()),
key=f"learning_label_{scope}",
)
default_name = Path(payload.get("source_workbook_name") or ref.path.stem).stem.replace("_", " ").title()
type_name = st.text_input("Type label for merge/create", value=default_name, key="proposal_type_label")
target_type = st.selectbox("Merge target", options=["(create new type)"] + cm.get_all_type_ids(), key="proposal_merge_target")
cfg = build_type_config_from_proposal(payload, type_name)
if target_type != "(create new type)":
cfg["type_id"] = target_type
cfg["label"] = cm.get_type_config(target_type).get("label", target_type) if cm.get_type_config(target_type) else target_type
if evidence:
base = cm.get_type_config(target) if target != "(create new type)" else (original or None)
candidate = build_candidate_type_config(type_name, payload.get("blueprint") or {}, evidence, existing_config=base)
else:
cfg["type_id"] = slugify_type_id(type_name)
candidate = dict(original)
if target != "(create new type)":
candidate["type_id"] = target
candidate["label"] = str((cm.get_type_config(target) or {}).get("label") or target)
else:
candidate["label"] = type_name.strip() or str(candidate.get("label") or candidate.get("type_id") or "Learned Type")
validator = ConfigValidator(valid_target_columns=cm.get_target_column_names())
validation = validator.validate(cfg)
col_a, col_b, col_c = st.columns(3)
with col_a:
st.metric("Mappings", len(cfg.get("mapping") or []))
with col_b:
st.metric("Relations", len(cfg.get("sheet_relations") or []))
with col_c:
st.metric("Validation errors", len(validation.errors))
candidate_text = st.text_area(
"Candidate Type YAML",
value=yaml.safe_dump(candidate, allow_unicode=True, sort_keys=False),
height=360,
key=f"learning_yaml_{scope}_{target}",
)
try:
edited = yaml.safe_load(candidate_text) or {}
if not isinstance(edited, dict):
raise ValueError("Candidate YAML must be an object.")
parse_error = ""
except (yaml.YAMLError, ValueError) as exc:
edited = {}
parse_error = str(exc)
st.error(f"Invalid candidate YAML: {exc}")
if validation.errors:
for error in validation.errors:
current = cm.get_type_config(str(edited.get("type_id") or "")) if edited else None
with st.expander("Config diff", expanded=True):
st.code(render_config_diff(current, edited), language="diff")
binding_errors = validation_binding_errors(
validation,
edited,
payload.get("evidence_ids") or [],
) if not parse_error else []
_render_validation(validation, binding_errors)
with st.container(horizontal=True, vertical_alignment="center"):
if st.button("Run replay validation", icon=":material/replay:", key=f"replay_{scope}", disabled=bool(parse_error)):
evidence_ids = list(payload.get("evidence_ids") or [])
runs = []
missing_samples = []
for evidence_id in evidence_ids:
evidence_item = _load_evidence(cm, evidence_id)
sample = _resolve_sample(payload, evidence_item, evidence_id)
if evidence_item is None or sample is None:
missing_samples.append(evidence_id)
continue
result = validate_candidate_replay(
cm,
edited,
sample,
str((evidence_item.get("workbook") or {}).get("name") or "sample.xlsx"),
evidence_item,
)
snapshot_hash = str(
(evidence_item.get("review_confirmation") or {}).get("reviewed_snapshot_hash", "")
)
runs.append((evidence_id, result.to_dict(), snapshot_hash))
bound = combine_replay_validations(
validation,
runs,
candidate=edited,
evidence_ids=evidence_ids,
)
if missing_samples:
bound["errors"] = [
*(bound.get("errors") or []),
"No replay sample is available for: " + ", ".join(missing_samples),
]
bound["status"] = "failed"
if not runs:
st.error("No retained sample is available. Re-submit this format from the current workbook to replay it.")
else:
update_blueprint_proposal(
ref.path,
expected_revision=int(payload.get("revision", 1) or 1),
candidate_config=edited,
validation=bound,
status=result.status,
)
st.rerun()
st.markdown("##### Admin decision")
reason = st.text_area("Decision reason", placeholder="Explain the decision (minimum 10 characters).", key=f"learning_reason_{scope}")
with st.container(horizontal=True, vertical_alignment="center"):
_render_promote(cm, ref.path, payload, edited, validation, binding_errors, parse_error, reason, scope)
_render_reject(cm, ref.path, payload, reason, scope)
def _render_validation(validation: dict, binding_errors: list[str]) -> None:
with st.expander("Replay validation", expanded=True):
cols = st.columns(4)
cols[0].metric("Status", str(validation.get("status") or "draft").title())
cols[1].metric("Rows", int(validation.get("export_row_count", 0) or 0))
cols[2].metric("Blocking", int(validation.get("blocking_issue_count", 0) or 0))
cols[3].metric("Columns", int(validation.get("output_column_count", 0) or 0))
if validation.get("matrix_required_count") is not None:
st.caption(
f"Replay matrix: {int(validation.get('matrix_valid_count', 0) or 0)} / "
f"{int(validation.get('matrix_required_count', 0) or 0)} evidence files valid for this candidate."
)
if validation.get("recognized_type"):
st.caption(f"Recognized as {validation['recognized_type']} at {float(validation.get('recognition_score', 0)):.1f}%")
for error in validation.get("errors", []) or []:
st.error(error)
for warning in validation.warnings:
st.warning(warning)
for warning in validation.get("warnings", []) or []:
st.warning(warning)
for error in binding_errors:
st.warning(error + " Run replay validation again.")
with st.expander("Preview generated type YAML", expanded=False):
st.code(dump_learned_type_yaml(cfg), language="yaml")
can_write = admin_reauth_ok(cm, "blueprint_merge", destructive=True)
if st.button("Merge proposal into type config", type="primary", disabled=bool(validation.errors)):
if not can_write:
def _render_promote(cm, path, payload, candidate, validation, binding_errors, parse_error, reason, scope) -> None:
required = cm.get_learning_config()["minimum_workbooks_for_promotion"]
evidence_count = len(payload.get("evidence_ids") or [])
force = st.checkbox(
"Approve with fewer evidence files",
disabled=evidence_count >= required,
key=f"learning_force_{scope}",
)
check = ConfigValidator(cm.get_target_column_names()).validate(candidate) if candidate else None
has_errors = bool(
parse_error
or not str(candidate.get("type_id", "") or "").strip()
or not str(candidate.get("label", "") or "").strip()
or validation.get("status") != "validated"
or validation.get("errors")
or binding_errors
or (check and check.errors)
)
reauth = admin_reauth_ok(cm, f"learning_promote_{scope}", destructive=True)
if st.button(
"Approve and promote",
type="primary",
icon=":material/publish:",
disabled=has_errors or not (evidence_count >= required or force) or len(reason.strip()) < 10,
key=f"learning_promote_button_{scope}",
):
if not reauth:
show_reauth_error()
return
cm.save_type_config(cfg["type_id"], cfg)
archived = archive_blueprint_proposal(ref.path)
st.success(f"Saved type '{cfg['type_id']}' and archived proposal to {archived}.")
promote_type_config(
cm, candidate,
proposal_id=str(payload.get("proposal_id") or path.stem),
evidence_ids=list(payload.get("evidence_ids") or []),
reason=reason.strip(), validation=validation, forced=force,
)
update_blueprint_proposal(
path, expected_revision=int(payload.get("revision", 1) or 1),
candidate_config=candidate, status="approved",
reviewed_at=datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
review_reason=reason.strip(),
)
archive_blueprint_proposal(path)
st.success(f"Type '{candidate['type_id']}' is active and reloaded.")
st.rerun()
def _render_reject(cm, path, payload, reason, scope) -> None:
reauth = admin_reauth_ok(cm, f"learning_reject_{scope}", destructive=True)
if st.button("Reject and archive", icon=":material/block:", disabled=len(reason.strip()) < 10, key=f"reject_{scope}"):
if not reauth:
show_reauth_error()
return
update_blueprint_proposal(
path, expected_revision=int(payload.get("revision", 1) or 1), status="rejected",
reviewed_at=datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
review_reason=reason.strip(),
)
write_learning_audit(cm.get_learning_audit_log_path(), {
"action": "reject", "admin_role": "admin",
"proposal_id": str(payload.get("proposal_id") or path.stem),
"evidence_ids": list(payload.get("evidence_ids") or []), "reason": reason.strip(),
})
archive_blueprint_proposal(path)
st.rerun()
def _render_history(cm: ConfigManager) -> None:
with st.expander("Type version history and rollback", expanded=False):
type_ids = cm.get_all_type_ids()
if not type_ids:
st.info("No Type configs are available.")
return
type_id = st.selectbox("Type", type_ids, key="learning_history_type")
versions = list_type_config_versions(cm, type_id)
if not versions:
st.info("No archived versions for this Type yet.")
return
version = st.selectbox("Archived version", versions, format_func=lambda item: f"{item.created_at} · {item.config_hash[:10]}", key="learning_history_version")
reason = st.text_area("Rollback reason", key="learning_rollback_reason")
reauth = admin_reauth_ok(cm, "learning_rollback", destructive=True)
if st.button("Rollback to this version", icon=":material/history:", disabled=len(reason.strip()) < 10):
if not reauth:
show_reauth_error()
return
rollback_type_config(cm, version.path, reason=reason.strip())
st.success(f"Type '{type_id}' was rolled back and reloaded.")
st.rerun()
def _load_first_evidence(cm: ConfigManager, payload: dict) -> dict | None:
ids = payload.get("evidence_ids") or []
path = cm.get_learning_evidence_dir() / f"{ids[0]}.json" if ids else None
return load_learning_evidence(path) if path and path.exists() else None
def _load_evidence(cm: ConfigManager, evidence_id: str) -> dict | None:
path = cm.get_learning_evidence_dir() / f"{evidence_id}.json"
return load_learning_evidence(path) if path.exists() else None
def _resolve_sample(payload: dict, evidence: dict | None, evidence_id: str = "") -> bytes | None:
retained = str((payload.get("retained_sample_paths") or {}).get(evidence_id) or "")
if not retained:
retained = str(payload.get("retained_sample_path") or "")
if retained and Path(retained).exists():
return Path(retained).read_bytes()
if evidence and st.session_state.get("workbook_file_hash") == (evidence.get("workbook") or {}).get("sha256"):
return st.session_state.get("uploaded_file_bytes")
return None
def _status_color(validation: dict) -> str:
return {"validated": "green", "failed": "red", "validating": "orange"}.get(str(validation.get("status") or "draft"), "gray")
+19 -11
View File
@@ -5,11 +5,14 @@ import re
import streamlit as st
import yaml
from services.file_store import atomic_write_text
from services.config_manager import ConfigManager
from services.config_validator import ConfigValidator, ValidationResult
from ui.admin_auth import require_admin_page
from ui.admin_blueprints import render_blueprint_proposals
from ui.admin_guards import admin_reauth_ok, show_reauth_error
from ui.workflow_state import navigate_to
# ── Public entry points ─────────────────────────────────────────────
@@ -18,12 +21,12 @@ def render_admin_page(tab: str = "types"):
cm: ConfigManager = st.session_state.config_manager
if not require_admin_page(cm):
return
st.title("⚙️ Admin")
if st.button("← Back to App", key=f"admin_back_top_{tab}"):
st.session_state.current_step = "upload"
st.title("Admin")
if st.button("Back to app", icon=":material/arrow_back:", key=f"admin_back_top_{tab}"):
navigate_to("upload")
st.rerun()
tab_options = ["📋 Type Config", "📖 Synonym Dictionary", "🤖 AI Configuration", "🧩 Blueprint Proposals"]
tab_options = ["Type Config", "Synonym Dictionary", "AI Configuration", "Format Learning"]
default_index = {"types": 0, "synonyms": 1, "llm": 2, "blueprints": 3}.get(tab, 0)
admin_tab = st.radio(
"Select admin section",
@@ -32,14 +35,16 @@ def render_admin_page(tab: str = "types"):
index=default_index,
)
if "📋 Type Config" in admin_tab:
selected_section = tab_options.index(admin_tab)
if selected_section == 0:
_render_type_config_hybrid()
elif "📖 Synonym" in admin_tab:
elif selected_section == 1:
_render_synonym_dict()
elif "🤖 AI" in admin_tab:
elif selected_section == 2:
_render_llm_config()
else:
render_blueprint_proposals(cm)
return
# ═══════════════════════════════════════════════════════════════════
@@ -164,7 +169,7 @@ def _render_type_config_hybrid():
st.rerun()
with col_d:
if st.button("← Back to App", width="stretch"):
st.session_state.current_step = "upload"
navigate_to("upload")
st.rerun()
@@ -427,7 +432,7 @@ def _render_synonym_dict():
st.rerun()
if st.button("← Back to App"):
st.session_state.current_step = "upload"
navigate_to("upload")
st.rerun()
@@ -601,7 +606,10 @@ def _render_llm_config():
"fingerprint_auto_threshold": cfg.get("fingerprint_auto_threshold", 80),
"fingerprint_suggest_threshold": cfg.get("fingerprint_suggest_threshold", 60),
}
settings_path.write_text(yaml.dump(settings, allow_unicode=True, default_flow_style=False, sort_keys=False), encoding="utf-8")
atomic_write_text(
settings_path,
yaml.dump(settings, allow_unicode=True, default_flow_style=False, sort_keys=False),
)
cm._load_settings()
st.session_state.llm_status = None
st.success("✅ Saved to config/settings.yaml")
@@ -613,7 +621,7 @@ def _render_llm_config():
_test_llm_connection(cm)
with col2:
if st.button("← Back to App", width="stretch"):
st.session_state.current_step = "upload"
navigate_to("upload")
st.rerun()
+10 -8
View File
@@ -25,6 +25,7 @@ from ui.confirm_page import (
_render_result_strip,
)
from ui.copy import current_language, t
from ui.workflow_state import navigate_to
from utils.helpers import safe_dataframe
@@ -42,7 +43,7 @@ def render_ai_analysis_page() -> None:
if parsed is None or basic is None:
st.caption(t("common.no_data", lang))
if st.button(t("common.back_upload", lang), width="stretch"):
st.session_state.current_step = "upload"
navigate_to("upload")
st.rerun()
return
@@ -85,7 +86,7 @@ def render_ai_analysis_page() -> None:
with st.container(horizontal=True, horizontal_alignment="distribute"):
if st.button(t("ai.back_basic", lang), disabled=busy, width="stretch"):
st.session_state.current_step = "confirm"
navigate_to("confirm")
st.rerun()
st.button(
t("confirm.run_ai", lang),
@@ -96,7 +97,7 @@ def render_ai_analysis_page() -> None:
width="stretch",
)
if st.button(t("ai.skip", lang), disabled=busy, width="stretch"):
_confirm_blueprint(st.session_state.get("analysis_result") or basic)
_confirm_blueprint(basic, source="basic")
st.rerun()
if st.session_state.get("ai_analysis_pending"):
@@ -107,7 +108,7 @@ def render_ai_analysis_page() -> None:
result,
used_ai=_result_used_ai(result),
)
st.session_state.current_step = "ai_summary"
navigate_to("ai_summary")
finally:
st.session_state.ai_analysis_pending = False
st.session_state.ai_analysis_running = False
@@ -125,7 +126,7 @@ def render_ai_summary_page() -> None:
if parsed is None or basic is None:
st.caption(t("common.no_data", lang))
if st.button(t("common.back_upload", lang), width="stretch"):
st.session_state.current_step = "upload"
navigate_to("upload")
st.rerun()
return
@@ -172,14 +173,14 @@ def render_ai_summary_page() -> None:
with st.container(horizontal=True, horizontal_alignment="distribute"):
if st.button(t("ai.back_run", lang), width="stretch"):
st.session_state.current_step = "ai_analysis"
navigate_to("ai_analysis")
st.rerun()
if st.button(t("confirm.run_ai", lang), width="stretch"):
_queue_ai_analysis()
st.session_state.current_step = "ai_analysis"
navigate_to("ai_analysis")
st.rerun()
if st.button(t("ai.use_summary", lang), type="primary", width="stretch"):
_confirm_blueprint(active_result)
_confirm_blueprint(active_result, source="ai" if ai_result is not None else "basic")
st.rerun()
@@ -247,6 +248,7 @@ def _run_llm_analysis_console(cm: ConfigManager, parsed, selected_type: str, con
use_llm=True,
)
st.session_state.analysis_result = result
st.session_state.active_analysis_source = "ai"
write_debug("run_complete", result=summarize_analysis_result(result), event_count=len(events))
except Exception as exc:
if debug_log is not None:
+8 -45
View File
@@ -4,16 +4,16 @@ from __future__ import annotations
from ui.copy import current_language, t
STEPS = [
("upload", "step.upload", "📤"),
("confirm", "step.confirm", "🧭"),
("ai_analysis", "step.ai_analysis", "🤖"),
("preview", "step.preview", "👁️"),
("export", "step.export", "📥"),
("upload", "step.upload", ":material/upload_file:"),
("confirm", "step.confirm", ":material/fact_check:"),
("preview", "step.preview", ":material/preview:"),
("export", "step.export", ":material/download:"),
]
STEP_ALIASES = {
"type_select": "upload",
"ai_summary": "ai_analysis",
"ai_analysis": "confirm",
"ai_summary": "confirm",
}
@@ -50,26 +50,6 @@ def apply_premium_theme() -> None:
padding-top: 1.5rem !important;
padding-bottom: 2rem !important;
}
.nbd-muted { color: #667085; }
.nbd-card {
padding: .85rem 1rem;
border-radius: .5rem;
border: 1px solid #e5e7eb;
background: #fff;
margin: .5rem 0;
}
.nbd-analysis-card { background: #f8fafc; }
.nbd-result-strip,
.nbd-blueprint-strip {
display: flex;
flex-wrap: wrap;
gap: .5rem 1rem;
align-items: center;
}
.nbd-result-strip span,
.nbd-blueprint-strip span { color: #667085; }
.nbd-result-strip b,
.nbd-blueprint-strip b { color: #111827; }
.nbd-conclusion-card {
border: 1px solid #dbeafe;
background: #eff6ff;
@@ -179,19 +159,6 @@ def apply_premium_theme() -> None:
font-size: .92rem;
line-height: 1.48;
}
.nbd-wizard-item {
padding: .55rem .65rem;
border-radius: .55rem;
margin: .25rem 0;
border: 1px solid transparent;
}
.nbd-wizard-item.current {
background: #eef2ff;
border-color: #c7d2fe;
}
.nbd-wizard-item.done { background: #f0fdf4; }
.nbd-wizard-item.pending { opacity: .72; }
.nbd-wizard-title { font-weight: 700; color: #111827; }
</style>
""",
unsafe_allow_html=True,
@@ -199,16 +166,12 @@ def apply_premium_theme() -> None:
def render_stepper(current_step: str, lang: str | None = None) -> None:
"""Render a compact four-step process indicator.
Kept for tests/utility use. The runtime shell currently shows progress in
the sidebar only, to avoid duplicate top chrome.
"""
"""Render the single top-level four-step process indicator."""
import streamlit as st
lang = lang or current_language()
items = build_step_items(current_step, lang=lang)
st.caption(" → ".join(f"{item['icon']} {item['label']}" for item in items))
st.markdown(" &nbsp; → &nbsp; ".join(f"{item['icon']} **{item['label']}**" for item in items))
def render_hero(title: str, subtitle: str) -> None:
+495 -110
View File
@@ -1,6 +1,7 @@
"""Basic analysis review page before the dedicated optional AI step."""
"""Operator-first review page with optional AI as a secondary check."""
from __future__ import annotations
from copy import deepcopy
import hashlib
import html
@@ -9,12 +10,16 @@ import streamlit as st
from openpyxl.utils import get_column_letter
from services.config_manager import ConfigManager
from services.llm_stages import ColumnMapping
from services.review_policy import build_review_gate, classify_mapping_review
from services.review_overrides import apply_header_row_override, build_column_mapping_result
from services.review_snapshot import build_reviewed_snapshot
from services.workbook_analyzer import AnalysisResult
from utils.helpers import safe_dataframe
from ui.app_chrome import render_hero
from ui.copy import current_language, t
from ui.workflow_state import navigate_to
def render_confirm_page():
@@ -28,64 +33,107 @@ def render_confirm_page():
if parsed is None or basic is None:
st.warning(t("common.no_data", lang))
if st.button(t("common.back_upload", lang)):
st.session_state.current_step = "upload"
navigate_to("upload")
st.rerun()
return
selected_type = st.session_state.get("selected_type") or ""
score = _active_basic_score()
active_result: AnalysisResult = basic
ai_result = st.session_state.get("analysis_result")
active_source = str(st.session_state.get("active_analysis_source") or "basic")
if ai_result is None:
active_source = "basic"
elif ai_result is not None:
active_source = st.segmented_control(
"Result to review",
options=["basic", "ai"],
format_func=lambda value: "Basic result" if value == "basic" else "AI-assisted result",
key="active_analysis_source",
) or active_source
active_result: AnalysisResult = ai_result if active_source == "ai" and ai_result is not None else basic
st.markdown(
f"""
<div class="nbd-card nbd-analysis-card">
<b>{html.escape(t("confirm.basic_result", lang))}</b>
<div class="nbd-muted">{t("confirm.manual_llm_body", lang)}</div>
</div>
""",
unsafe_allow_html=True,
)
with st.container(border=True):
st.badge("Review in progress", icon=":material/fact_check:", color="blue")
st.caption("Check only the highlighted items. Technical workbook details are optional.")
_render_result_strip(active_result, selected_type, score, lang)
_render_basic_source_header(cm, selected_type, active_result)
active_result = _render_operator_review_controls(cm, parsed, active_result, selected_type, lang)
st.session_state.basic_analysis_result = active_result
active_result = _render_operator_review_controls(
cm, parsed, active_result, selected_type, lang, analysis_source=active_source
)
if active_source == "ai" and st.session_state.get("analysis_result") is not None:
st.session_state.analysis_result = active_result
else:
st.session_state.basic_analysis_result = active_result
st.session_state.active_analysis_source = "basic"
_render_result_strip(active_result, selected_type, score, lang, parsed, cm)
for w in _operator_alert_warnings(active_result.warnings):
st.warning(w)
_render_review_sections(active_result, lang, expanded=False)
st.divider()
gate = build_review_gate(parsed, active_result.mappings)
unconfirmed_sheets = _unconfirmed_sheet_names(parsed)
blocking_reasons = list(gate.blocking_reasons)
if unconfirmed_sheets:
blocking_reasons.append(
"Confirm every selected sheet: " + ", ".join(unconfirmed_sheets) + "."
)
if blocking_reasons:
st.error(
"Complete these required checks before Preview:\n\n"
+ "\n".join(f"- {_friendly_gate_reason(cm, reason)}" for reason in blocking_reasons),
icon=":material/block:",
)
recommendation = build_ai_recommendation(active_result, score, _optional_ai_available(cm))
box_icon = "🤖" if recommendation["recommend"] else "✅"
st.info(f"{box_icon} **{recommendation['title']}** — {recommendation['detail']}")
if recommendation["available"]:
icon = ":material/auto_awesome:" if recommendation["recommend"] else ":material/info:"
st.info(f"**{recommendation['title']}** — {recommendation['detail']}", icon=icon)
left, middle, right = st.columns([1, 1.25, 1.25])
with left:
if st.button(t("common.back", lang), width="stretch"):
st.session_state.current_step = "upload"
with st.container(horizontal=True, horizontal_alignment="right", vertical_alignment="center"):
if st.button(t("common.back", lang), icon=":material/arrow_back:"):
navigate_to("upload")
st.rerun()
with middle:
if st.button("✅ Use Basic Analysis → Preview", width="stretch"):
_confirm_blueprint(active_result)
if recommendation["available"] and st.button(
"Run optional AI",
icon=":material/auto_awesome:",
help="Runs an extra AI check. Your Basic result remains available if AI fails.",
):
navigate_to("ai_analysis")
st.rerun()
with right:
if st.button("🤖 Run Optional AI", type="primary", width="stretch", disabled=not recommendation["available"]):
st.session_state.current_step = "ai_analysis"
if st.button(
"Continue to preview",
type="primary",
icon=":material/arrow_forward:",
disabled=bool(blocking_reasons),
):
_confirm_blueprint(active_result, source=active_source)
st.rerun()
def _confirm_blueprint(result: AnalysisResult) -> None:
st.session_state.confirmed_blueprint = {
def _confirm_blueprint(result: AnalysisResult, *, source: str = "basic") -> None:
blueprint = deepcopy({
"summaries": result.summaries,
"groups": result.groups,
"mappings": result.mappings,
}
})
snapshot = build_reviewed_snapshot(
workbook_hash=st.session_state.get("workbook_file_hash") or "",
workbook_name=st.session_state.get("uploaded_file_name") or "",
selected_type=st.session_state.get("selected_type") or "",
selected_sheets=st.session_state.get("selected_sheet_names") or [],
parsed=st.session_state.get("parsed_workbook"),
analysis_source=source,
blueprint=blueprint,
)
st.session_state.confirmed_blueprint = blueprint
st.session_state.reviewed_snapshot = snapshot
st.session_state.reviewed_snapshot_hash = snapshot.snapshot_hash
st.session_state.active_analysis_source = source
st.session_state.processed_rows = None
st.session_state.current_step = "preview"
st.session_state.export_quality_override = None
navigate_to("preview")
def _render_operator_review_controls(
@@ -94,23 +142,82 @@ def _render_operator_review_controls(
result: AnalysisResult,
selected_type: str,
lang: str,
analysis_source: str = "basic",
) -> AnalysisResult:
"""Render simple human review controls before optional AI/export."""
st.subheader("Review setup")
st.caption("Check header rows and map Excel columns to database columns. AI is optional after this review.")
st.subheader("Check the workbook setup")
st.caption("Confirm the row containing column names, then check how Excel columns are assigned to output fields.")
with st.expander("1. Header rows", expanded=True):
st.caption("Move the cursor to the row that should become the header. The preview and mapping table update on every cursor move.")
for sheet_index, sheet in enumerate(parsed.sheets):
_render_sheet_header_cursor(sheet, sheet_index)
operator_policy = cm.get_operator_review_config()
header_changed = False
with st.expander("1. Confirm the column names row", expanded=True, icon=":material/table_rows:"):
st.caption("Choose a sheet and confirm which Excel row contains names such as JAN, SAP, item name, or price.")
summary_rows = [
{
"Sheet": sheet.name,
"Column names row": int(sheet.header_row or 0),
"Columns found": len([header for header in sheet.detected_headers if header]),
"Status": (
"Confirmed"
if _is_sheet_review_confirmed(sheet)
else "Please confirm"
),
}
for sheet in parsed.sheets
]
st.dataframe(pd.DataFrame(summary_rows), width="stretch", hide_index=True)
sheet_names = [sheet.name for sheet in parsed.sheets]
if sheet_names and st.session_state.get("review_active_sheet") not in sheet_names:
st.session_state.review_active_sheet = sheet_names[0]
active_name = st.selectbox(
"Sheet to check",
options=sheet_names,
key="review_active_sheet",
) if sheet_names else None
if active_name:
sheet_index = sheet_names.index(active_name)
header_changed = _render_sheet_header_cursor(
parsed.sheets[sheet_index],
sheet_index,
editable=operator_policy["allow_header_row_override"],
)
active_sheet = parsed.sheets[sheet_index]
confirmed_count = len(_confirmed_sheet_names(parsed))
st.progress(
confirmed_count / max(len(sheet_names), 1),
text=f"{confirmed_count} of {len(sheet_names)} selected sheets confirmed",
)
if _is_sheet_review_confirmed(active_sheet):
st.success(
f"{active_sheet.name} is confirmed. Select another sheet if one still needs checking.",
icon=":material/check_circle:",
)
else:
st.button(
(
"Confirm this sheet and continue"
if confirmed_count < len(sheet_names) - 1
else "Confirm this sheet"
),
type="primary",
icon=":material/check_circle:",
on_click=_confirm_sheet_review,
args=(active_sheet, sheet_names),
)
if sheet_names and not _unconfirmed_sheet_names(parsed):
st.success("All selected sheets are confirmed.", icon=":material/done_all:")
# Rebuild the deterministic review result from the current cursor positions
# so Column mapping follows the selected header row immediately.
result = _rebuild_basic_result_for_review(cm, parsed, selected_type, result)
result = _rebuild_basic_result_for_review(
cm, parsed, selected_type, result,
preserve_result=analysis_source == "ai" and not header_changed,
)
with st.expander("2. Column mapping to database", expanded=True):
with st.expander("2. Check output fields", expanded=True, icon=":material/compare_arrows:"):
manual_mappings = _render_manual_mapping_editor(cm, parsed, result)
reviewed = build_column_mapping_result(result, manual_mappings)
_render_mapping_task_summary(cm, parsed, reviewed)
return reviewed
@@ -120,7 +227,7 @@ def _optional_ai_available(cm: ConfigManager) -> bool:
return False
if cm.resolve_llm_connection_config() is None:
return False
return st.session_state.get("llm_status") == "online"
return True
def _rebuild_basic_result_for_review(
@@ -128,14 +235,27 @@ def _rebuild_basic_result_for_review(
parsed,
selected_type: str,
fallback_result: AnalysisResult,
*,
preserve_result: bool = False,
) -> AnalysisResult:
"""Re-run deterministic analysis against the currently selected headers."""
if preserve_result:
return fallback_result
cache_key = _review_rebuild_cache_key(parsed, selected_type)
cache = st.session_state.get("review_rebuild_cache") or {}
if cache_key in cache:
return deepcopy(cache[cache_key])
try:
return WorkbookAnalyzer(cm).analyze(
rebuilt = WorkbookAnalyzer(cm).analyze(
parsed,
preferred_type_id=selected_type or None,
use_llm=False,
)
cache[cache_key] = deepcopy(rebuilt)
while len(cache) > 4:
cache.pop(next(iter(cache)), None)
st.session_state.review_rebuild_cache = cache
return rebuilt
except Exception:
# Keep the page usable if deterministic rebuild hits an unexpected config
# issue; the original result is still better than dropping the workflow.
@@ -143,7 +263,7 @@ def _rebuild_basic_result_for_review(
return fallback_result
def _render_sheet_header_cursor(sheet, sheet_index: int) -> None:
def _render_sheet_header_cursor(sheet, sheet_index: int, *, editable: bool = True) -> bool:
"""Render one sheet's cursor-controlled header-row preview."""
max_row = max(sheet.rows or len(sheet.raw_data), 1)
key = f"review_header_row_{sheet_index}_{sheet.name}"
@@ -152,49 +272,120 @@ def _render_sheet_header_cursor(sheet, sheet_index: int) -> None:
left, right = st.columns([1.05, 2.95], vertical_alignment="top")
with left:
st.markdown(f"**{sheet.name}**")
button_cols = st.columns(2)
with button_cols[0]:
with st.container(horizontal=True):
st.button(
"▲ Up",
"Previous row",
icon=":material/arrow_upward:",
key=f"{key}_up",
disabled=st.session_state[key] <= 1,
width="stretch",
on_click=_move_header_cursor,
args=(key, -1, max_row),
disabled=(not editable) or st.session_state[key] <= 1,
)
with button_cols[1]:
st.button(
"▼ Down",
"Next row",
icon=":material/arrow_downward:",
key=f"{key}_down",
disabled=st.session_state[key] >= max_row,
width="stretch",
disabled=(not editable) or st.session_state[key] >= max_row,
on_click=_move_header_cursor,
args=(key, 1, max_row),
)
chosen = st.number_input(
f"{sheet.name} header row",
"Column names row",
min_value=1,
max_value=max_row,
step=1,
key=key,
disabled=not editable,
)
previous = int(sheet.header_row or 1)
apply_header_row_override(sheet, int(chosen))
if previous != int(sheet.header_row or 1):
_invalidate_review_outputs()
preview_headers = [h for h in sheet.detected_headers if h][:12]
st.markdown(f"**Cursor:** row `{int(sheet.header_row)}`")
st.caption("Detected columns: " + (", ".join(preview_headers) if preview_headers else "No headers detected"))
st.markdown(f"**Selected row:** `{int(sheet.header_row)}`")
st.caption("Column names found: " + (", ".join(preview_headers) if preview_headers else "None — choose another row"))
with right:
preview = _build_sheet_cursor_preview(sheet, int(sheet.header_row))
st.dataframe(
_style_cursor_preview(preview),
preview,
width="stretch",
hide_index=True,
height=min(max(len(preview), 1) * 35 + 38, 430),
column_config={
"Row": st.column_config.NumberColumn("Row", width="small"),
"Cursor": st.column_config.TextColumn("Selected", width="small", pinned=True),
},
)
st.divider()
return previous != int(sheet.header_row or 1)
def _review_rebuild_cache_key(parsed, selected_type: str) -> str:
"""Return a stable per-session analysis key for the current header choices."""
parts = [str(selected_type or "")]
for sheet in getattr(parsed, "sheets", []) or []:
parts.extend([
str(sheet.name),
str(int(getattr(sheet, "header_row", 0) or 0)),
"\x1f".join(str(value or "") for value in getattr(sheet, "detected_headers", []) or []),
])
return hashlib.sha256("\x1e".join(parts).encode("utf-8")).hexdigest()
def _sheet_review_signature(sheet) -> str:
"""Bind one explicit operator confirmation to the current header choice."""
payload = "\x1e".join([
str(getattr(sheet, "name", "") or ""),
str(int(getattr(sheet, "header_row", 0) or 0)),
str(int(getattr(sheet, "data_start_row", 0) or 0)),
"\x1f".join(
str(value or "")
for value in (getattr(sheet, "detected_headers", []) or [])
),
])
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def _is_sheet_review_confirmed(sheet) -> bool:
confirmed = st.session_state.get("review_confirmed_sheet_signatures") or {}
return confirmed.get(str(getattr(sheet, "name", "") or "")) == _sheet_review_signature(sheet)
def _confirmed_sheet_names(parsed) -> list[str]:
return [
sheet.name
for sheet in (getattr(parsed, "sheets", []) or [])
if _is_sheet_review_confirmed(sheet)
]
def _unconfirmed_sheet_names(parsed) -> list[str]:
return [
sheet.name
for sheet in (getattr(parsed, "sheets", []) or [])
if not _is_sheet_review_confirmed(sheet)
]
def _confirm_sheet_review(sheet, sheet_names: list[str]) -> None:
"""Confirm the visible sheet and advance to the next unconfirmed sheet."""
confirmed = dict(st.session_state.get("review_confirmed_sheet_signatures") or {})
confirmed[sheet.name] = _sheet_review_signature(sheet)
st.session_state.review_confirmed_sheet_signatures = confirmed
_invalidate_review_outputs()
parsed = st.session_state.get("parsed_workbook")
by_name = {
item.name: item
for item in (getattr(parsed, "sheets", []) or [])
}
current_index = sheet_names.index(sheet.name) if sheet.name in sheet_names else -1
ordered = sheet_names[current_index + 1:] + sheet_names[:current_index + 1]
for name in ordered:
candidate = by_name.get(name)
if candidate is not None and not _is_sheet_review_confirmed(candidate):
st.session_state.review_active_sheet = name
break
def _clamp_header_row(value, max_row: int) -> int:
@@ -218,7 +409,13 @@ def _invalidate_review_outputs() -> None:
st.session_state.processed_rows = None
st.session_state.raw_processed_rows = None
st.session_state.all_processed_rows = None
st.session_state.processed_row_sources = None
st.session_state.row_quality_result = None
st.session_state.numeric_key_source_warnings = None
st.session_state.export_quality_override = None
st.session_state.confirmed_blueprint = None
st.session_state.reviewed_snapshot = None
st.session_state.reviewed_snapshot_hash = None
def _build_sheet_cursor_preview(
@@ -270,21 +467,6 @@ def _format_preview_cell(value) -> str:
return text if len(text) <= 80 else text[:77] + "…"
def _style_cursor_preview(df: pd.DataFrame):
"""Highlight the selected cursor row in the preview dataframe."""
if df.empty or "Cursor" not in df.columns:
return df
return df.style.apply(
lambda row: [
"background-color: #fff7ed; font-weight: 700;"
if str(row.get("Cursor") or "").strip()
else ""
for _ in row
],
axis=1,
)
def _sync_result_summaries_from_parsed(result: AnalysisResult, parsed) -> None:
"""Keep analysis summaries aligned with operator-selected header rows."""
by_name = {summary.sheet_name: summary for summary in result.summaries}
@@ -316,42 +498,193 @@ def _render_manual_mapping_editor(cm: ConfigManager, parsed, result: AnalysisRes
previous = _prune_mapping_state(previous_all, headers)
if previous != previous_all:
st.session_state.review_column_mappings = previous
targets = [""] + cm.get_target_column_names()
rows = _build_mapping_editor_rows(headers, existing, previous)
policy = cm.get_operator_review_config()
allowed_targets = cm.get_operator_mapping_targets()
option_by_target = _operator_target_options(cm, allowed_targets)
target_by_option = {label: target for target, label in option_by_target.items()}
blank_option = "Ignore this Excel column"
targets = [blank_option, *option_by_target.values()]
manual_base = {
header: previous.get(header, existing.get(header, ""))
for header in headers
}
original_by_source = {mapping.excel_column: mapping for mapping in result.mappings}
reviewed_for_filter = [
(
original_by_source[header]
if header in original_by_source
and original_by_source[header].sql_target == target
else ColumnMapping(header, target, 1.0, "Manual review mapping")
)
for header, target in manual_base.items()
if target
]
items = classify_mapping_review(
headers,
reviewed_for_filter,
attention_threshold=cm.get_mapping_review_attention_threshold(),
operator_warnings=_operator_alert_warnings(result.warnings),
)
view = st.segmented_control(
"Columns to show",
options=["Needs attention", "Mapped", "All"],
format_func=lambda value: {
"Needs attention": "Please check",
"Mapped": "Assigned",
"All": "All columns",
}[value],
key="review_mapping_view",
) or "Needs attention"
search = st.text_input(
"Search columns",
placeholder="Search an Excel column or output field",
icon=":material/search:",
key="review_mapping_search",
).strip().casefold()
visible = [
item
for item in items
if (view == "All" or (view == "Needs attention" and item.needs_attention) or (view == "Mapped" and item.sql_target))
and (
not search
or search in item.excel_column.casefold()
or search in item.sql_target.casefold()
or search in cm.get_operator_field_label(item.sql_target).casefold()
)
]
rows = [
{
"Excel Column": item.excel_column,
"Example values": _column_samples(parsed, item.excel_column),
"Database Column": option_by_target.get(manual_base.get(item.excel_column, ""), blank_option),
"Status": _friendly_mapping_status(item.status),
"Match": f"{item.confidence * 100:.0f}%" if item.sql_target else "",
"Why check": item.reason,
}
for item in visible
]
if not rows:
st.success("No columns match this view.", icon=":material/check_circle:")
st.caption(f"{sum(bool(target) for target in manual_base.values())} of {len(headers)} Excel columns are assigned.")
return manual_base
edited = st.data_editor(
pd.DataFrame(rows),
width="stretch",
hide_index=True,
num_rows="fixed",
column_config={
"Excel Column": st.column_config.TextColumn("Excel Column", disabled=True),
"Database Column": st.column_config.SelectboxColumn("Database Column", options=targets),
"Excel Column": st.column_config.TextColumn("Excel column", disabled=True, pinned=True),
"Example values": st.column_config.TextColumn(
"Example values",
disabled=True,
help="Up to three non-empty examples from the selected workbook sheets.",
),
"Database Column": st.column_config.SelectboxColumn(
"Output field",
options=targets,
disabled=not policy["allow_column_mapping"],
help="Choose where this Excel column should appear in the exported workbook.",
),
"Status": st.column_config.TextColumn("Status", disabled=True),
"Match": st.column_config.TextColumn("Match", disabled=True),
"Why check": st.column_config.TextColumn("Why check", disabled=True),
},
key=_mapping_editor_key(parsed),
key=f"{_mapping_editor_key(parsed)}_{view.replace(' ', '_')}_{hashlib.sha1(search.encode()).hexdigest()[:6]}",
disabled=not policy["allow_column_mapping"],
)
manual = {
str(row["Excel Column"]): str(row["Database Column"] or "")
for row in edited.to_dict("records")
if str(row.get("Excel Column") or "").strip()
}
manual = dict(manual_base)
for row in edited.to_dict("records"):
header = str(row.get("Excel Column") or "").strip()
if header:
manual[header] = target_by_option.get(str(row.get("Database Column") or ""), "")
if manual != previous:
st.session_state.review_column_mappings = manual
_invalidate_review_outputs()
mapped_count = sum(1 for target in manual.values() if target)
st.caption(f"Mapped {mapped_count} of {len(headers)} detected columns. Blank target means ignore this Excel column.")
st.caption(f"{mapped_count} of {len(headers)} Excel columns are assigned. “Ignore this Excel column” keeps it out of the export.")
return manual
def _build_mapping_editor_rows(
headers: list[str],
existing: dict[str, str],
previous: dict[str, str],
) -> list[dict[str, str]]:
"""Build mapping table rows from the current header cursor state."""
return [
{"Excel Column": header, "Database Column": previous.get(header, existing.get(header, ""))}
for header in headers
]
def _operator_target_options(cm: ConfigManager, targets: list[str]) -> dict[str, str]:
"""Build friendly, unique select options while hiding technical names by default."""
labels = {target: cm.get_operator_field_label(target) for target in targets}
counts: dict[str, int] = {}
for label in labels.values():
counts[label] = counts.get(label, 0) + 1
return {
target: label if counts[label] == 1 else f"{label} · {target}"
for target, label in labels.items()
}
def _column_samples(parsed, header: str, *, limit: int = 3, max_length: int = 36) -> str:
"""Return bounded, de-duplicated sample values for one detected header."""
samples: list[str] = []
seen: set[str] = set()
wanted = str(header or "").strip()
if not wanted:
return ""
for sheet in getattr(parsed, "sheets", []) or []:
column_indexes = [
index
for index, value in (getattr(sheet, "col_headers", {}) or {}).items()
if str(value or "").strip() == wanted
]
if not column_indexes:
column_indexes = [
index
for index, value in enumerate(getattr(sheet, "detected_headers", []) or [])
if str(value or "").strip() == wanted
]
start = max(int(getattr(sheet, "data_start_row", 1) or 1) - 1, 0)
end = int(getattr(sheet, "data_end_row", 0) or len(getattr(sheet, "raw_data", []) or []))
for row in (getattr(sheet, "raw_data", []) or [])[start:end]:
for column_index in column_indexes:
value = row[column_index] if column_index < len(row) else None
text = str(value).strip() if value not in (None, "") else ""
if not text or text.casefold() in seen:
continue
seen.add(text.casefold())
samples.append(text if len(text) <= max_length else text[: max_length - 1] + "…")
if len(samples) >= limit:
return " · ".join(samples)
return " · ".join(samples)
def _friendly_mapping_status(status: str) -> str:
return {
"Mapped": "Ready",
"Unmapped": "Not assigned",
"Conflict": "Used more than once",
"Low confidence": "Please confirm",
"Warning": "Please check",
}.get(str(status), str(status))
def _render_mapping_task_summary(cm: ConfigManager, parsed, result: AnalysisResult) -> None:
"""Show one clear completion message after the mapping editor."""
items = classify_mapping_review(
_ordered_headers(parsed),
result.mappings,
attention_threshold=cm.get_mapping_review_attention_threshold(),
operator_warnings=_operator_alert_warnings(result.warnings),
)
attention = [item for item in items if item.needs_attention]
conflicts = [item for item in items if item.conflict]
if conflicts:
fields = ", ".join(item.excel_column for item in conflicts[:5])
st.error(
f"An output field is assigned more than once. Check: {fields}.",
icon=":material/content_copy:",
)
elif attention:
st.info(
f"{len(attention)} column{'s' if len(attention) != 1 else ''} still need confirmation. "
"Unassigned optional columns do not block Preview.",
icon=":material/rule:",
)
else:
st.success("All detected columns have been checked.", icon=":material/check_circle:")
def _prune_mapping_state(previous: dict[str, str], headers: list[str]) -> dict[str, str]:
@@ -374,18 +707,45 @@ def _mapping_editor_key(parsed) -> str:
return f"review_column_mapping_editor_{digest}"
def _render_result_strip(result: AnalysisResult, selected_type: str, score: float, lang: str) -> None:
status = "Ready for review" if result.mappings else "Review needed"
st.markdown(
f"""
<div class="nbd-card nbd-result-strip">
<span><b>{t("confirm.selected_type", lang)}</b> <code>{html.escape(selected_type or '-')}</code></span>
<span><b>{t("confirm.type_confidence", lang)}</b> {score:.1f}%</span>
<span><b>Status:</b> {html.escape(status)}</span>
</div>
""",
unsafe_allow_html=True,
def _render_result_strip(
result: AnalysisResult,
selected_type: str,
score: float,
lang: str,
parsed=None,
cm: ConfigManager | None = None,
) -> None:
parsed = parsed or st.session_state.get("parsed_workbook")
cm = cm or st.session_state.config_manager
items = classify_mapping_review(
_ordered_headers(parsed),
result.mappings,
attention_threshold=cm.get_mapping_review_attention_threshold(),
operator_warnings=_operator_alert_warnings(result.warnings),
)
mapped = sum(bool(item.sql_target) for item in items)
needs_attention = sum(item.needs_attention for item in items)
unmapped = sum(not item.sql_target for item in items)
conflicts = sum(item.conflict for item in items)
with st.container(border=True):
with st.container(horizontal=True, vertical_alignment="center"):
cfg = cm.get_type_config(selected_type) or {}
st.badge(str(cfg.get("label") or selected_type or "Format not recognised"), color="blue")
st.badge(
"Format recognised" if score >= 80 else "Format needs confirmation",
color="green" if score >= 80 else "orange",
)
st.badge(
f"{len(_confirmed_sheet_names(parsed))}/{len(parsed.sheets)} sheets confirmed",
color="green" if not _unconfirmed_sheet_names(parsed) else "orange",
)
metrics = st.columns(4)
metrics[0].metric("Fields assigned", mapped)
metrics[1].metric("Please check", needs_attention)
metrics[2].metric("Not assigned", unmapped)
metrics[3].metric("Used twice", conflicts)
with st.expander("Technical detection details", expanded=False):
st.caption(f"Format ID: {selected_type or 'none'} · match score: {score:.1f}%")
def _render_basic_source_header(cm: ConfigManager, selected_type: str, result: AnalysisResult) -> None:
@@ -393,9 +753,27 @@ def _render_basic_source_header(cm: ConfigManager, selected_type: str, result: A
if selected_type:
cfg = cm.get_type_config(selected_type) or {}
label = str(cfg.get("label") or selected_type)
st.markdown(f"**Known format:** `{html.escape(label)}` · Basic deterministic mapping is selected for review.")
st.markdown(f"**Workbook format:** `{html.escape(label)}` · Standard configured rules are selected.")
elif result.engine == "fuzzy":
st.markdown("**Mapping source:** Basic string matching. Review the header cursor and mappings before preview.")
st.markdown("**Workbook format:** Not recognised · Check the suggested output fields before Preview.")
def _friendly_gate_reason(cm: ConfigManager, reason: str) -> str:
"""Translate technical review-gate details into operator-facing actions."""
text = str(reason)
if "item key" in text:
return "Assign at least one product key: Barcode / JAN code or SAP item code."
if "duplicate database targets:" in text:
technical = text.split(":", 1)[-1].strip().rstrip(".")
labels = [
cm.get_operator_field_label(field.strip())
for field in technical.split(",")
if field.strip()
]
return "Each output field can only be used once. Check: " + ", ".join(labels) + "."
if "header row" in text:
return "Confirm at least one row containing Excel column names."
return text
def _operator_alert_warnings(warnings: list[str]) -> list[str]:
@@ -489,8 +867,15 @@ def _render_mapping(result: AnalysisResult, lang: str) -> None:
def _active_basic_score() -> float:
active_type = st.session_state.get("selected_type")
cache = st.session_state.get("basic_analysis_cache") or {}
entry = cache.get(active_type or "")
return float(entry.get("score", 0.0)) if entry else 0.0
selected_sheets = list(st.session_state.get("selected_sheet_names") or [])
for entry in reversed(list(cache.values())):
if entry.get("type_id") != active_type:
continue
parsed = entry.get("parsed")
entry_sheets = [sheet.name for sheet in (getattr(parsed, "sheets", []) or [])]
if entry_sheets == selected_sheets:
return float(entry.get("score", 0.0))
return 0.0
def build_ai_recommendation(result: AnalysisResult, score: float, llm_enabled: bool) -> dict:
+27 -27
View File
@@ -57,35 +57,35 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"step.current": "Now",
"step.pending": "Next",
"upload.title": "🏠 Upload Excel",
"upload.subtitle": "Upload an Excel workbook. The app reads every sheet, detects its structure, and prepares a mapping blueprint.",
"upload.subtitle": "Upload an Excel workbook, check the recommended product sheets, and confirm its format.",
"upload.file_label": "Choose an Excel file",
"upload.empty": "👆 Upload an Excel file to get started.",
"upload.sheet_preview": "📋 Sheet preview",
"upload.extracted_preview": "📋 Upload Excel & preview extracted data",
"upload.basic_title": "🧭 Basic analysis",
"upload.basic_spinner": "Running basic deterministic analysis...",
"upload.basic_spinner": "Checking workbook structure and column rules...",
"upload.show_type_matches": "Show all type confidence scores",
"upload.no_type_matches": "No known type matched this workbook. Select a type and run basic analysis manually.",
"upload.type_select": "Workbook type",
"upload.type_none": "Select type",
"upload.type_changed": "Type changed to {type}. Run basic analysis again before continuing.",
"upload.rerun_basic": "Run basic analysis for selected type",
"upload.no_type_matches": "This workbook format was not recognised. Select the closest format before continuing.",
"upload.type_select": "Workbook format",
"upload.type_none": "Select a format",
"upload.type_changed": "Format changed to {type}. Apply the format before continuing.",
"upload.rerun_basic": "Apply selected format",
"upload.selected_type": "Selected type:",
"upload.basic_confidence": "Confidence:",
"upload.basic_progress": "Basic type confidence: {score:.1f}%",
"upload.select_type_first": "Select a workbook type before continuing.",
"upload.select_type_first": "Select a workbook format before continuing.",
"upload.confidence_too_low": "Confidence is {score:.1f}%. At least {min:.0f}% is recommended before continuing.",
"upload.low_confidence_warning": "⚠️ Low confidence: {score:.1f}%. This is below the {threshold:.0f}% warning threshold. Confirm before continuing if you intentionally want to review this mapping.",
"upload.low_confidence_confirm": "I understand the confidence is low and want to continue to review.",
"upload.low_confidence_warning": "The workbook format match is {score:.1f}%, below the {threshold:.0f}% review threshold. Please confirm the format before continuing.",
"upload.low_confidence_confirm": "I checked the workbook format and want to continue to Review.",
"upload.continue": "Continue → basic analysis review",
"upload.show_rows": "Show rows",
"upload.cannot_read": "❌ Cannot read file: {error}",
"upload.cannot_read": "Cannot read file: {error}",
"common.no_data": "⚠️ No data. Please upload first.",
"common.back_upload": "← Back to upload",
"common.back": "← Back",
"confirm.hero_title": "🧭 Review result",
"confirm.hero_subtitle": "Check the result, then continue with the current analysis or run optional AI if needed.",
"common.no_data": "No workbook data is available. Please upload a file first.",
"common.back_upload": "Back to upload",
"common.back": "Back",
"confirm.hero_title": "Review the workbook",
"confirm.hero_subtitle": "Check the highlighted setup items, then continue to the output preview.",
"confirm.manual_llm_body": "Use this result now, or run optional AI analysis if the mapping needs extra checking.",
"confirm.basic_result": "Analysis result",
"confirm.ai_result": "AI-enhanced analysis result",
@@ -134,26 +134,26 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"ai.back_basic": "← Back to basic analysis",
"ai.back_run": "← Back to AI run",
"ai.details": "Technical details for Admin / programmer",
"preview.hero_title": "👁️ Merged preview",
"preview.hero_subtitle": "Preview the final pre_item_master output format before downloading.",
"preview.hero_title": "Preview the output",
"preview.hero_subtitle": "Check important product fields and resolve any required data-quality issues.",
"preview.spinner": "Merging rows...",
"preview.rows": "Merged rows",
"preview.target_sheet": "Target sheet",
"preview.no_rows": "No data rows. Please go back and confirm the blueprint.",
"preview.output_columns": "Output columns ({count}): {columns}",
"preview.show_raw": "Show raw merged columns",
"preview.back_confirm": "← Back to review",
"preview.next_export": "Next → Export",
"export.hero_title": "📥 Formal export",
"export.hero_subtitle": "Download the reviewed workbook, and optionally save this mapping as a reusable blueprint.",
"preview.back_confirm": "Back to review",
"preview.next_export": "Continue to export",
"export.hero_title": "Download the workbook",
"export.hero_subtitle": "Download the reviewed pre_item_master workbook.",
"export.rows": "Export rows",
"export.sql_columns": "SQL columns",
"export.sheet": "Sheet",
"export.contract_title": "✅ Export contract",
"export.contract_body": "Output contains one sheet named <code>pre_item_master</code>. Header names and order come from <code>db_schema.yaml</code> / SQL schema.",
"export.failed": "❌ Export failed: {error}",
"export.failed": "Export failed: {error}",
"export.ready": "Workbook ready — download the formal pre_item_master file below.",
"export.download": "📥 Download pre_item_master_{ts}.xlsx",
"export.download": "Download pre_item_master_{ts}.xlsx",
"export.save_mapping": "💾 Optional: submit Match Blueprint proposal",
"export.save_mapping_help": "Save the confirmed result as a temporary proposal. Basic users do not change system type config directly; Admin reviews and merges proposals later.",
"export.blueprint_summary": "Blueprint summary",
@@ -165,9 +165,9 @@ TRANSLATIONS: dict[str, dict[str, str]] = {
"export.format_name": "Blueprint name",
"export.save": "Submit proposal for admin review",
"export.saved_as": "✅ Saved as '{name}'",
"export.proposal_saved": "✅ Proposal saved for Admin review: {file}",
"export.back_preview": "← Back to preview",
"export.new_upload": "🔄 New upload",
"export.proposal_saved": "Proposal saved for Admin review: {file}",
"export.back_preview": "Back to preview",
"export.new_upload": "New upload",
},
}
+259 -45
View File
@@ -1,7 +1,6 @@
"""Formal export page for reviewed, SQL-shaped workbook rows."""
from __future__ import annotations
import html
from datetime import datetime
from pathlib import Path
@@ -11,16 +10,31 @@ from services.config_manager import ConfigManager
from services.export_service import ExportService
from services.export_models import ProcessedData
from services.field_transformer import transform_field_value
from services.blueprint_proposals import save_blueprint_proposal, BlueprintProposalRef
from services.blueprint_proposals import (
save_blueprint_proposal,
BlueprintProposalRef,
list_blueprint_proposals,
load_blueprint_proposal,
update_blueprint_proposal,
)
from services.candidate_type_builder import build_candidate_type_config
from services.format_similarity import compare_evidence_to_types
from services.learning_evidence import load_learning_evidence, retain_workbook_sample
from services.proposal_validator import validate_candidate_replay
from services.validation_binding import bind_validation
from services.replay_matrix import combine_replay_validations
from services.learned_blueprint import (
build_blueprint_summary,
build_learned_type_config,
dump_learned_type_yaml,
slugify_type_id,
)
from services.export_quality import is_valid_quality_override
from services.review_snapshot import reviewed_snapshot_matches
from ui.app_chrome import render_hero
from ui.admin_auth import is_admin_unlocked
from ui.copy import current_language, t
from ui.workflow_state import reset_workflow_state
from ui.workflow_state import navigate_to, reset_workflow_state
def render_export_page():
@@ -28,28 +42,58 @@ def render_export_page():
lang = current_language()
render_hero(t("export.hero_title", lang), t("export.hero_subtitle", lang))
cm: ConfigManager = st.session_state.config_manager
parsed = st.session_state.get("parsed_workbook")
blueprint = st.session_state.get("confirmed_blueprint")
if not reviewed_snapshot_matches(
st.session_state.get("reviewed_snapshot"),
workbook_hash=st.session_state.get("workbook_file_hash") or "",
selected_type=st.session_state.get("selected_type") or "",
selected_sheets=st.session_state.get("selected_sheet_names") or [],
parsed=parsed,
blueprint=blueprint,
):
st.error("Export is blocked because the reviewed setup is missing or stale.", icon=":material/block:")
if st.button("Back to review", icon=":material/arrow_back:"):
navigate_to("confirm")
st.rerun()
return
rows = st.session_state.get("processed_rows") or []
quality = st.session_state.get("row_quality_result")
override_valid = bool(
quality
and is_valid_quality_override(
st.session_state.get("export_quality_override"),
st.session_state.get("workbook_file_hash") or "",
quality,
)
)
if quality is None or (not quality.can_export and not override_valid):
st.error(
"Export is blocked by the current data-quality result. Return to Preview to review the issues.",
icon=":material/block:",
)
if st.button("Back to preview", icon=":material/arrow_back:"):
navigate_to("preview")
st.rerun()
return
schema_fields = cm.get_db_schema() or cm.get_schema_fields()
target_cols = [f["name"] for f in schema_fields]
st.markdown(
f"""
<div class="nbd-card nbd-result-strip">
<span><b>{t("export.rows", lang)}</b> {len(rows)}</span>
<span><b>{t("export.sql_columns", lang)}</b> {len(target_cols)}</span>
<span><b>{t("export.sheet", lang)}</b> <code>{html.escape(cm.get_target_table_name())}</code></span>
</div>
""",
unsafe_allow_html=True,
)
with st.container(border=True):
with st.container(horizontal=True, vertical_alignment="center"):
st.badge(f"{len(rows)} rows", color="green")
st.badge(f"{len(target_cols)} output fields", color="blue")
st.badge(f"Sheet: {cm.get_target_table_name()}", color="gray")
if override_valid:
st.badge("Admin override", icon=":material/admin_panel_settings:", color="orange")
if rows:
st.markdown(f"""
<div class="nbd-card">
<b>{t("export.contract_title", lang)}</b><br/>
<span class="nbd-muted">{t("export.contract_body", lang)}</span>
</div>
""", unsafe_allow_html=True)
with st.container(border=True):
st.markdown("**Ready to download**")
st.caption(
"The workbook contains the reviewed rows in the required pre_item_master format. "
"Your uploaded source file has not been changed."
)
filled = []
for r in rows:
row_dict = {c: transform_field_value(cm, c, r.get(c)) for c in target_cols}
@@ -76,18 +120,17 @@ def render_export_page():
file_name=f"pre_item_master_{ts}.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
type="primary",
width="stretch",
icon=":material/download:",
)
_render_save_blueprint(cm, lang)
st.divider()
col1, col2 = st.columns([1, 1])
with col1:
if st.button(t("export.back_preview", lang)):
st.session_state.current_step = "preview"
with st.container(horizontal=True, horizontal_alignment="right"):
if st.button(t("export.back_preview", lang), icon=":material/arrow_back:"):
navigate_to("preview")
st.rerun()
with col2:
if st.button(t("export.new_upload", lang)):
if st.button(t("export.new_upload", lang), icon=":material/note_add:"):
reset_workflow_state()
st.rerun()
@@ -99,8 +142,52 @@ def save_export_blueprint_proposal(
source_workbook_name: str,
selected_type: str | None,
analysis_engine: str | None,
evidence_ids: list[str] | None = None,
classification: str = "",
similarity: dict | None = None,
candidate_config: dict | None = None,
validation: dict | None = None,
retained_sample_path: str = "",
existing_proposal_path: Path | None = None,
reviewed_snapshot_hash: str = "",
) -> BlueprintProposalRef:
"""Save a Basic-user blueprint as a temporary admin-review proposal."""
if existing_proposal_path is not None:
previous = load_blueprint_proposal(existing_proposal_path)
combined_ids = list(previous.get("evidence_ids") or [])
for evidence_id in evidence_ids or []:
if evidence_id not in combined_ids:
combined_ids.append(evidence_id)
current_ids = [item for item in (evidence_ids or []) if item]
combined_validation = _combine_validation_runs(
previous.get("validation") or {},
validation or {},
candidate_config or {},
combined_ids,
reviewed_snapshot_hash=reviewed_snapshot_hash,
current_evidence_ids=current_ids,
)
sample_paths = dict(previous.get("retained_sample_paths") or {})
for evidence_id in current_ids:
if retained_sample_path:
sample_paths[evidence_id] = retained_sample_path
update_blueprint_proposal(
existing_proposal_path,
evidence_ids=combined_ids,
classification=classification,
similarity=similarity or {},
candidate_config=candidate_config or {},
validation=combined_validation,
retained_sample_path=retained_sample_path or previous.get("retained_sample_path", ""),
retained_sample_paths=sample_paths,
status=combined_validation.get("status", "draft"),
)
return next(ref for ref in list_blueprint_proposals(cm.get_tmp_blueprints_dir()) if ref.path == existing_proposal_path)
bound_validation = _combine_validation_runs(
{}, validation or {}, candidate_config or {}, evidence_ids or [],
reviewed_snapshot_hash=reviewed_snapshot_hash,
current_evidence_ids=evidence_ids or [],
) if validation else {}
return save_blueprint_proposal(
cm.get_tmp_blueprints_dir(),
blueprint=blueprint,
@@ -108,45 +195,93 @@ def save_export_blueprint_proposal(
source_workbook_name=source_workbook_name,
selected_type=selected_type,
analysis_engine=analysis_engine,
evidence_ids=evidence_ids,
classification=classification,
similarity=similarity,
candidate_config=candidate_config,
validation=bound_validation,
retained_sample_path=retained_sample_path,
retained_sample_paths={
evidence_id: retained_sample_path
for evidence_id in (evidence_ids or [])
if evidence_id and retained_sample_path
},
)
def _render_save_blueprint(cm: ConfigManager, lang: str) -> None:
"""Render the optional learned non-LLM Match Blueprint save panel."""
st.divider()
blueprint = st.session_state.get("confirmed_blueprint")
with st.expander(t("export.save_mapping", lang), expanded=False):
st.caption(t("export.save_mapping_help", lang))
if not cm.get_learning_config()["enabled"] or not _should_offer_format_learning():
return
with st.expander(
"Help recognise this workbook format next time",
expanded=False,
icon=":material/school:",
):
st.caption(
"Submit this reviewed setup for Admin approval. "
"It will not change system rules automatically."
)
if not blueprint:
st.info(t("export.no_blueprint", lang))
st.info("No reviewed setup is available.")
return
summary = build_blueprint_summary(blueprint)
st.markdown(
f"""
<div class="nbd-blueprint-strip">
<span><b>{t("export.blueprint_sheets", lang)}</b> {summary["sheets"]}</span>
<span><b>{t("export.blueprint_links", lang)}</b> {summary["links"]}</span>
<span><b>{t("export.blueprint_mappings", lang)}</b> {summary["mappings"]}</span>
</div>
""",
unsafe_allow_html=True,
)
with st.container(horizontal=True, vertical_alignment="center"):
st.badge(f"{summary['sheets']} sheets", color="gray")
st.badge(f"{summary['mappings']} fields assigned", color="blue")
default_name = _default_blueprint_name()
name = st.text_input(
t("export.format_name", lang),
"Name for this workbook format",
value=st.session_state.get("save_blueprint_name") or default_name,
key="save_blueprint_name",
)
cfg = build_learned_type_config(name, blueprint)
st.caption(f"type_id: `{cfg['type_id']}`")
with st.expander(t("export.preview_yaml", lang), expanded=False):
st.code(dump_learned_type_yaml(cfg), language="yaml")
if is_admin_unlocked():
with st.expander("Admin technical preview", expanded=False):
st.caption(f"Format ID: `{cfg['type_id']}`")
st.code(dump_learned_type_yaml(cfg), language="yaml")
if st.button(t("export.save", lang), type="primary"):
if st.button("Submit for Admin review", icon=":material/send:"):
parsed = st.session_state.get("parsed_workbook")
analysis = st.session_state.get("analysis_result") or st.session_state.get("basic_analysis_result")
evidence_id = str(st.session_state.get("learning_evidence_id") or "")
evidence_path = cm.get_learning_evidence_dir() / f"{evidence_id}.json"
if not evidence_id or not evidence_path.exists():
st.error("Learning evidence is not ready. Return to Preview once, then try again.")
return
evidence = load_learning_evidence(evidence_path)
learning = cm.get_learning_config()
similarities = compare_evidence_to_types(
evidence,
[cm.get_type_config(type_id) for type_id in cm.get_all_type_ids()],
existing_variant_threshold=learning["existing_variant_threshold"],
admin_review_threshold=learning["admin_review_threshold"],
)
best = similarities[0] if similarities else None
pending_ref, pending_payload, pending_match = _find_matching_pending_proposal(cm, evidence)
if pending_payload and pending_match and pending_match.score >= learning["existing_variant_threshold"]:
existing = pending_payload.get("candidate_config") or None
else:
pending_ref, pending_payload, pending_match = None, None, None
existing = cm.get_type_config(best.type_id) if best and best.classification == "existing_variant" else None
candidate = build_candidate_type_config(name, blueprint, evidence, existing_config=existing)
validation = validate_candidate_replay(
cm,
candidate,
st.session_state.get("uploaded_file_bytes") or b"",
st.session_state.get("uploaded_file_name") or "sample.xlsx",
evidence,
)
retained_path = ""
if learning["retain_raw_samples"]:
retained_path = str(retain_workbook_sample(
cm.get_learning_sample_dir(), evidence_id,
st.session_state.get("uploaded_file_name") or "sample.xlsx",
st.session_state.get("uploaded_file_bytes") or b"",
))
ref = save_export_blueprint_proposal(
cm,
blueprint=blueprint,
@@ -154,13 +289,92 @@ def _render_save_blueprint(cm: ConfigManager, lang: str) -> None:
source_workbook_name=getattr(parsed, "file_name", "") if parsed is not None else "",
selected_type=st.session_state.get("selected_type") or "",
analysis_engine=getattr(analysis, "engine", "") if analysis is not None else "",
evidence_ids=[evidence_id],
classification=best.classification if best else "new_type",
similarity={
"best_type_id": best.type_id if best else "",
"score": best.score if best else 0,
"reasons": best.reasons if best else ["No known Type produced a comparable signature."],
},
candidate_config=candidate,
validation=validation.to_dict(),
retained_sample_path=retained_path,
existing_proposal_path=pending_ref.path if pending_ref else None,
reviewed_snapshot_hash=st.session_state.get("reviewed_snapshot_hash") or "",
)
st.success(t("export.proposal_saved", lang, file=ref.path.name))
st.rerun()
def _should_offer_format_learning() -> bool:
"""Offer learning only for unknown, low-match, or already-learned formats."""
selected_type = str(st.session_state.get("selected_type") or "")
matches = st.session_state.get("fingerprint_matches") or []
selected_match = next(
(match for match in matches if str(getattr(match, "type_id", "")) == selected_type),
None,
)
score = float(getattr(selected_match, "score", 0.0) or 0.0)
cm: ConfigManager = st.session_state.config_manager
learned = (cm.get_type_config(selected_type) or {}).get("learning", {}) or {}
return not selected_type or score < 80.0 or bool(learned.get("evidence_ids"))
def _default_blueprint_name() -> str:
parsed = st.session_state.get("parsed_workbook")
file_name = getattr(parsed, "file_name", "") if parsed is not None else ""
stem = Path(file_name).stem if file_name else "learned_format"
return slugify_type_id(stem).replace("_", " ").title()
def _find_matching_pending_proposal(cm: ConfigManager, evidence: dict):
learning = cm.get_learning_config()
candidates = []
payload_by_type = {}
ref_by_type = {}
for ref in list_blueprint_proposals(cm.get_tmp_blueprints_dir()):
payload = load_blueprint_proposal(ref.path)
candidate = payload.get("candidate_config") or {}
type_id = str(candidate.get("type_id") or "")
if not type_id:
continue
candidates.append(candidate)
payload_by_type[type_id] = payload
ref_by_type[type_id] = ref
matches = compare_evidence_to_types(
evidence, candidates,
existing_variant_threshold=learning["existing_variant_threshold"],
admin_review_threshold=learning["admin_review_threshold"],
)
if not matches:
return None, None, None
best = matches[0]
return ref_by_type.get(best.type_id), payload_by_type.get(best.type_id), best
def _combine_validation_runs(
previous: dict,
current: dict,
candidate_config: dict | None = None,
evidence_ids: list[str] | None = None,
*,
reviewed_snapshot_hash: str = "",
current_evidence_ids: list[str] | None = None,
) -> dict:
current_ids = current_evidence_ids or (evidence_ids or [])
current_runs = [
(evidence_id, bind_validation(
current,
candidate_config or {},
[evidence_id],
reviewed_snapshot_hash=reviewed_snapshot_hash,
), reviewed_snapshot_hash)
for evidence_id in current_ids
if current and evidence_id
]
return combine_replay_validations(
previous,
current_runs,
candidate=candidate_config or {},
evidence_ids=evidence_ids or [],
)
+417 -113
View File
@@ -1,19 +1,48 @@
"""Preview merged output rows before formal export."""
from __future__ import annotations
import html
import pandas as pd
import streamlit as st
from services.config_manager import ConfigManager
from services.merge_engine import MergeEngine
from services.field_transformer import transform_field_value
from services.row_quality import RowQualityResult, split_rows_by_quality
from services.row_builder import build_merged_rows
from services.learning_evidence import (
build_learning_evidence,
retain_workbook_sample,
save_learning_evidence,
)
from services.type_config_versions import write_learning_audit
from services.export_quality import (
create_quality_override,
is_valid_quality_override,
write_quality_override_audit,
)
from services.security import verify_password
from services.review_snapshot import reviewed_snapshot_matches
from utils.helpers import safe_dataframe
from ui.app_chrome import render_hero
from ui.copy import current_language, t
from ui.admin_auth import is_admin_unlocked
from ui.workflow_state import navigate_to
IMPORTANT_PREVIEW_FIELDS = (
"generated_barcode",
"sap",
"item_name_eng",
"item_name_jap",
"with_tax",
"without_tax",
"pcs_ctn",
"pcs_dp",
"package_size",
"jp_bai_launch",
)
SOURCE_SHEET_KEY = "__source_sheet"
SOURCE_ROW_KEY = "__source_row"
def render_preview_page():
@@ -27,15 +56,65 @@ def render_preview_page():
if parsed is None or blueprint is None:
st.warning(t("common.no_data", lang))
if st.button(t("common.back_upload", lang)):
st.session_state.current_step = "upload"
navigate_to("upload")
st.rerun()
return
if not reviewed_snapshot_matches(
st.session_state.get("reviewed_snapshot"),
workbook_hash=st.session_state.get("workbook_file_hash") or "",
selected_type=st.session_state.get("selected_type") or "",
selected_sheets=st.session_state.get("selected_sheet_names") or [],
parsed=parsed,
blueprint=blueprint,
):
st.error(
"The workbook setup changed after Review. Return to Review and confirm it again.",
icon=":material/lock_reset:",
)
if st.button("Back to review", icon=":material/arrow_back:"):
navigate_to("confirm")
st.rerun()
return
if st.session_state.processed_rows is None:
with st.spinner(t("preview.spinner", lang)):
raw_rows = _build_merged_rows(parsed, blueprint)
selected_type = st.session_state.get("selected_type") or ""
type_config = cm.get_type_config(selected_type) or {}
built_rows = _build_merged_rows(
parsed,
blueprint,
derived_fields=type_config.get("derived_fields", []),
include_source_metadata=True,
)
st.session_state.processed_row_sources = [
{
"sheet": str(row.get(SOURCE_SHEET_KEY) or ""),
"row": int(row.get(SOURCE_ROW_KEY) or 0),
}
for row in built_rows
]
raw_rows = [
{
key: value
for key, value in row.items()
if key not in {SOURCE_SHEET_KEY, SOURCE_ROW_KEY}
}
for row in built_rows
]
target_cols = cm.get_target_column_names()
st.session_state.raw_processed_rows = raw_rows
key_fields = set(_schema_key_columns(cm))
st.session_state.numeric_key_source_warnings = {
index: [
field for field in key_fields
if isinstance(row.get(field), (int, float)) and not isinstance(row.get(field), bool)
]
for index, row in enumerate(raw_rows)
if any(
isinstance(row.get(field), (int, float)) and not isinstance(row.get(field), bool)
for field in key_fields
)
}
st.session_state.all_processed_rows = [
{c: transform_field_value(cm, c, row.get(c)) for c in target_cols}
for row in raw_rows
@@ -45,25 +124,39 @@ def render_preview_page():
quality = _refresh_processed_rows_from_quality(cm)
rows = st.session_state.processed_rows
st.markdown(
f"""
<div class="nbd-card nbd-result-strip">
<span><b>{t("preview.rows", lang)}</b> {len(rows)}</span>
<span><b>{t("preview.target_sheet", lang)}</b> <code>{html.escape(cm.get_target_table_name())}</code></span>
<span><b>{t("export.sql_columns", lang)}</b> {len(cm.get_target_column_names())}</span>
</div>
""",
unsafe_allow_html=True,
_render_quality_summary(quality)
st.caption(
f"Export sheet: {cm.get_target_table_name()} · "
f"{len(cm.get_target_column_names())} output fields"
)
_render_row_quality_review(quality, cm)
quality = st.session_state.row_quality_result or quality
override_valid = _has_valid_quality_override(quality)
if rows:
target_cols = cm.get_target_column_names()
st.caption(t("preview.output_columns", lang, count=len(target_cols), columns=", ".join(target_cols[:8]) + ("..." if len(target_cols) > 8 else "")))
df = pd.DataFrame(rows, columns=target_cols)
st.dataframe(safe_dataframe(df), width="stretch", hide_index=True,
height=min(len(rows) * 35 + 38, 600))
view = st.segmented_control(
"Preview columns",
options=["Important fields", "All output fields"],
key="preview_column_view",
) or "Important fields"
if view == "Important fields":
visible_columns = [column for column in IMPORTANT_PREVIEW_FIELDS if column in target_cols]
preview_df = _friendly_preview_frame(cm, rows, visible_columns)
st.caption(
f"Showing {len(visible_columns)} important fields. "
f"The downloaded workbook still contains all {len(target_cols)} output fields."
)
else:
preview_df = pd.DataFrame(rows, columns=target_cols)
st.caption(f"Showing all {len(target_cols)} output fields in export order.")
st.dataframe(
safe_dataframe(preview_df),
width="stretch",
hide_index=True,
height=min(len(rows) * 35 + 38, 600),
)
raw_rows = st.session_state.get("raw_processed_rows") or []
extra_cols = sorted({k for row in raw_rows for k in row.keys()} - set(target_cols))
if extra_cols:
@@ -72,88 +165,64 @@ def render_preview_page():
else:
st.warning(t("preview.no_rows", lang))
col1, col2 = st.columns([1, 1], vertical_alignment="center")
if quality.blocking_issues and not override_valid:
st.error(
"Export is blocked until the key issues are fixed or an Admin approves an override.",
icon=":material/block:",
)
if is_admin_unlocked() and st.button(
"Request Admin override",
icon=":material/admin_panel_settings:",
):
_render_quality_override_dialog(cm, quality)
elif override_valid:
st.warning(
"Admin override is active for this exact workbook and issue set.",
icon=":material/admin_panel_settings:",
)
with col1:
if st.button(t("preview.back_confirm", lang), width="stretch", icon=":material/arrow_back:"):
st.session_state.current_step = resolve_preview_back_step(
has_ai_result=bool(st.session_state.get("analysis_result")),
ai_available=st.session_state.get("llm_status") == "online",
)
with st.container(horizontal=True, horizontal_alignment="right", vertical_alignment="center"):
if st.button(t("preview.back_confirm", lang), icon=":material/arrow_back:"):
navigate_to("confirm")
st.rerun()
with col2:
if st.button(t("preview.next_export", lang), type="primary", width="stretch", icon=":material/arrow_forward:"):
st.session_state.current_step = "export"
if st.button(
t("preview.next_export", lang),
type="primary",
icon=":material/arrow_forward:",
disabled=not (quality.can_export or override_valid),
):
_capture_learning_evidence(cm, parsed, blueprint, quality)
navigate_to("export")
st.rerun()
def resolve_preview_back_step(has_ai_result: bool = False, ai_available: bool = False) -> str:
"""Return the safe destination for Preview → Back to review.
The button label is "Back to review", so the default destination must be the
human Review setup page. Optional AI pages are not reachable when AI is not
connected, and even after an AI run the operator can review the basic setup
before previewing again.
"""
return "confirm"
def _build_merged_rows(parsed, blueprint) -> list[dict]:
def _build_merged_rows(
parsed,
blueprint,
derived_fields: list[dict] | None = None,
*,
include_source_metadata: bool = False,
) -> list[dict]:
"""Merge source sheets, propagate shared values, and rename Excel headers to SQL columns."""
engine = MergeEngine()
summaries = blueprint["summaries"]
groups = blueprint["groups"]
mappings = blueprint["mappings"]
return build_merged_rows(
parsed,
blueprint,
derived_fields,
include_source_metadata=include_source_metadata,
)
excel_to_sql = {m.excel_column: m.sql_target for m in mappings}
summary_by_name = {s.sheet_name: s for s in summaries}
sheet_data = {}
for s in parsed.sheets:
summary = summary_by_name.get(s.name)
hr = summary.header_row if summary else s.header_row
headers = ([str(c) if c is not None else "" for c in s.raw_data[hr - 1]]
if hr - 1 < len(s.raw_data) else s.detected_headers)
ds = hr
data_rows = [list(r) for r in s.raw_data[ds:s.data_end_row]] if ds < len(s.raw_data) else []
sheet_data[s.name] = (headers, data_rows)
all_merged = []
if groups:
for g in groups:
master = sheet_data.get(g.master_sheet)
if not master:
continue
mh, mr = master
from_sheets = {name: sheet_data[name] for name in g.sheets
if name != g.master_sheet and name in sheet_data}
merged = engine.merge(mr, mh, from_sheets, g.links)
all_merged.extend(merged)
else:
for name, (headers, data_rows) in sheet_data.items():
all_merged.extend([{h: (r[i] if i < len(r) else None) for i, h in enumerate(headers)}
for r in data_rows])
mapped_rows = []
shared_values = []
for summary in summaries:
shared_values.extend(getattr(summary, "shared_values", []) or [])
for row in all_merged:
for shared in shared_values:
label = shared.get("label", "") if isinstance(shared, dict) else ""
value = shared.get("value") if isinstance(shared, dict) else None
if label and value not in (None, "") and row.get(label) in (None, ""):
row[label] = value
new_row = {}
for k, v in row.items():
sql = excel_to_sql.get(k)
tk = sql if sql else k
if tk in new_row and new_row[tk] not in (None, ""):
continue
new_row[tk] = v
mapped_rows.append(new_row)
return mapped_rows
def _friendly_preview_frame(cm: ConfigManager, rows: list[dict], columns: list[str]) -> pd.DataFrame:
"""Return an operator-facing preview without changing stored export keys."""
labels = {column: cm.get_operator_field_label(column) for column in columns}
counts: dict[str, int] = {}
for label in labels.values():
counts[label] = counts.get(label, 0) + 1
renamed = {
column: label if counts[label] == 1 else f"{label} · {column}"
for column, label in labels.items()
}
return pd.DataFrame(rows, columns=columns).rename(columns=renamed)
def _schema_key_columns(cm: ConfigManager) -> list[str]:
@@ -167,38 +236,273 @@ def _refresh_processed_rows_from_quality(cm: ConfigManager) -> RowQualityResult:
all_rows = st.session_state.get("processed_rows") or []
st.session_state.all_processed_rows = all_rows
restored = st.session_state.get("row_quality_restored_indexes") or set()
quality = split_rows_by_quality(all_rows, key_columns=_schema_key_columns(cm), restore_indexes=restored)
quality = split_rows_by_quality(
all_rows,
key_columns=_schema_key_columns(cm),
restore_indexes=restored,
numeric_key_sources=st.session_state.get("numeric_key_source_warnings") or {},
)
st.session_state.row_quality_result = quality
st.session_state.processed_rows = [record.row for record in quality.export_rows]
if not _has_valid_quality_override(quality):
st.session_state.export_quality_override = None
return quality
def _render_row_quality_review(quality: RowQualityResult, cm: ConfigManager) -> None:
sources = st.session_state.get("processed_row_sources") or []
_render_quality_issues(quality, cm, sources)
dropped = quality.dropped
if not dropped:
st.success("Row quality check: no sparse rows were moved to the dropped list.")
st.success("Row quality check passed. No rows were excluded.")
return
st.warning(f"Row quality check moved {len(dropped)} sparse row(s) to the dropped list. Restore any row that should be exported.")
with st.expander("Dropped rows — review / restore", expanded=True):
current = set(st.session_state.get("row_quality_restored_indexes") or set())
selected = st.multiselect(
"Restore dropped row indexes",
options=[record.index for record in dropped],
default=sorted(current),
format_func=lambda idx: f"Row {idx + 1}",
key="row_quality_restore_choices",
st.warning(
f"{len(dropped)} sparse row(s) were excluded. "
"Restore a row only when it represents a real product."
)
if not cm.get_operator_review_config()["allow_restore_dropped_rows"]:
st.info("Restoring excluded rows is disabled by Admin policy.")
st.dataframe(
safe_dataframe(pd.DataFrame([
{
"Source sheet": _source_for_index(sources, record.index)["sheet"],
"Excel row": _source_for_index(sources, record.index)["row"] or record.index + 1,
"Reason": record.reason,
}
for record in dropped
])),
width="stretch",
hide_index=True,
)
selected_set = set(selected)
return
with st.expander("Excluded rows — review or restore", expanded=True, icon=":material/playlist_remove:"):
current = set(st.session_state.get("row_quality_restored_indexes") or set())
target_cols = cm.get_target_column_names()
table_rows = []
for record in dropped:
source = _source_for_index(sources, record.index)
row = {
"Restore": record.index in current,
"Source sheet": source["sheet"],
"Excel row": source["row"] or record.index + 1,
"Reason": record.reason,
}
row.update({
col: record.row.get(col)
for col in target_cols
if record.row.get(col) not in (None, "")
})
table_rows.append(row)
edited = st.data_editor(
safe_dataframe(pd.DataFrame(table_rows)),
width="stretch",
hide_index=True,
num_rows="fixed",
column_config={
"Restore": st.column_config.CheckboxColumn("Restore", help="Include this row in export quality checks."),
"Source sheet": st.column_config.TextColumn("Source sheet", disabled=True, pinned=True),
"Excel row": st.column_config.NumberColumn("Excel row", disabled=True),
"Reason": st.column_config.TextColumn("Reason", disabled=True),
},
disabled=[column for column in table_rows[0] if column != "Restore"],
key="row_quality_restore_table",
)
selected_set = {
dropped[index].index
for index, restore in enumerate(edited["Restore"].tolist())
if bool(restore)
}
if selected_set != current:
st.session_state.row_quality_restored_indexes = selected_set
quality = _refresh_processed_rows_from_quality(cm)
dropped = quality.dropped
st.session_state.export_quality_override = None
_refresh_processed_rows_from_quality(cm)
st.rerun()
target_cols = cm.get_target_column_names()
dropped_rows = []
for record in dropped:
row = {"Original row": record.index + 1, "Reason": record.reason, "Restored": "Yes" if record.restored else "No"}
row.update({col: record.row.get(col) for col in target_cols if record.row.get(col) not in (None, "")})
dropped_rows.append(row)
st.dataframe(safe_dataframe(pd.DataFrame(dropped_rows)), width="stretch", hide_index=True)
def _render_quality_summary(quality: RowQualityResult) -> None:
blocked_rows = {issue.row_index for issue in quality.blocking_issues}
valid = max(len(quality.export_rows) - len(blocked_rows), 0)
metrics = st.columns(4)
metrics[0].metric("Ready rows", valid)
metrics[1].metric("Must fix", len(quality.blocking_issues))
metrics[2].metric("Please check", len(quality.warning_issues))
metrics[3].metric("Excluded rows", len(quality.dropped))
def _render_quality_issues(
quality: RowQualityResult,
cm: ConfigManager,
sources: list[dict],
) -> None:
issues = [*quality.blocking_issues, *quality.warning_issues]
if not issues:
st.success("Row quality check passed.", icon=":material/check_circle:")
return
rows = _quality_issue_rows(issues, cm, sources)
st.dataframe(pd.DataFrame(rows), width="stretch", hide_index=True)
def _quality_issue_rows(issues, cm: ConfigManager, sources: list[dict]) -> list[dict]:
"""Build issue rows that point back to the original workbook location."""
rows = []
for issue in issues:
source = _source_for_index(sources, issue.row_index)
field_names = [
cm.get_operator_field_label(name.strip())
for name in str(issue.field).split(",")
if name.strip() and name.strip() != "row"
]
rows.append({
"Source sheet": source["sheet"] or ("All sheets" if issue.row_index < 0 else "Unknown"),
"Excel row": source["row"] or ("All" if issue.row_index < 0 else issue.row_index + 1),
"Output field": ", ".join(field_names) or "Whole row",
"Required action": "Must fix" if issue.blocking else "Please check",
"Issue": _friendly_quality_issue(issue.issue),
"Suggested fix": _friendly_quality_issue(issue.suggestion),
})
return rows
def _source_for_index(sources: list[dict], row_index: int) -> dict:
if 0 <= int(row_index) < len(sources):
source = sources[int(row_index)] or {}
return {"sheet": str(source.get("sheet") or ""), "row": int(source.get("row") or 0)}
return {"sheet": "", "row": 0}
def _friendly_quality_issue(text: str) -> str:
replacements = {
"generated_barcode": "Barcode / JAN code",
"sap": "SAP item code",
"export batch": "this workbook",
}
result = str(text)
for old, new in replacements.items():
result = result.replace(old, new)
return result
def _has_valid_quality_override(quality: RowQualityResult) -> bool:
return is_valid_quality_override(
st.session_state.get("export_quality_override"),
st.session_state.get("workbook_file_hash") or "",
quality,
)
def _capture_learning_evidence(cm: ConfigManager, parsed, blueprint: dict, quality: RowQualityResult) -> None:
"""Persist one privacy-safe evidence record for this reviewed result."""
learning = cm.get_learning_config()
if not learning["enabled"]:
return
mappings = blueprint.get("mappings", []) or []
signature = "|".join([
str(st.session_state.get("workbook_file_hash") or ""),
str(st.session_state.get("reviewed_snapshot_hash") or ""),
",".join(st.session_state.get("selected_sheet_names") or []),
",".join(sorted(f"{getattr(m, 'excel_column', '')}>{getattr(m, 'sql_target', '')}" for m in mappings)),
",".join(f"{issue.code}:{issue.row_index}" for issue in quality.blocking_issues),
",".join(f"{issue.code}:{issue.row_index}" for issue in quality.warning_issues),
",".join(str(record.index) for record in quality.export_rows if record.restored),
str(_has_valid_quality_override(quality)),
])
if st.session_state.get("learning_evidence_signature") == signature:
return
analysis = st.session_state.get("analysis_result") or st.session_state.get("basic_analysis_result")
evidence = build_learning_evidence(
workbook_hash=st.session_state.get("workbook_file_hash") or "",
workbook_name=st.session_state.get("uploaded_file_name") or getattr(parsed, "file_name", ""),
parsed=parsed,
blueprint=blueprint,
selected_type=st.session_state.get("selected_type"),
selected_sheets=st.session_state.get("selected_sheet_names") or [],
recommended_sheets=st.session_state.get("recommended_sheet_names") or [],
matched_patterns=st.session_state.get("matched_sheet_patterns") or [],
selection_source=st.session_state.get("sheet_selection_source"),
fingerprint_matches=st.session_state.get("fingerprint_matches") or [],
quality=quality,
export_row_count=len(quality.export_rows),
analysis_engine=getattr(analysis, "engine", "") if analysis is not None else "",
admin_override_used=_has_valid_quality_override(quality),
reviewed_snapshot_hash=st.session_state.get("reviewed_snapshot_hash") or "",
restored_row_indexes=[record.index for record in quality.export_rows if record.restored],
)
ref = save_learning_evidence(cm.get_learning_evidence_dir(), evidence)
if learning["retain_raw_samples"] and st.session_state.get("uploaded_file_bytes"):
retain_workbook_sample(
cm.get_learning_sample_dir(), ref.evidence_id,
st.session_state.get("uploaded_file_name") or "sample.xlsx",
st.session_state.uploaded_file_bytes,
)
st.session_state.learning_evidence_id = ref.evidence_id
st.session_state.learning_evidence_signature = signature
_record_learned_type_outcome(cm, evidence, quality)
def _record_learned_type_outcome(cm: ConfigManager, evidence: dict, quality: RowQualityResult) -> None:
"""Monitor promoted learned Types without auto-editing or deleting config."""
type_id = str(st.session_state.get("selected_type") or "")
config = cm.get_type_config(type_id) or {}
metadata = config.get("learning", {}) or {}
if not metadata.get("evidence_ids"):
return
matches = (evidence.get("type") or {}).get("fingerprint_matches", []) or []
selected_match = next((match for match in matches if match.get("type_id") == type_id), {})
score = float(selected_match.get("score", 0) or 0)
_, review_threshold = cm.get_fingerprint_thresholds()
needs_review = bool(quality.blocking_issues or score < review_threshold)
issue_counts = {}
for issue in [*quality.blocking_issues, *quality.warning_issues]:
issue_counts[issue.code] = issue_counts.get(issue.code, 0) + 1
write_learning_audit(cm.get_learning_audit_log_path(), {
"action": "runtime_monitor",
"type_id": type_id,
"status": "needs_review" if needs_review else "healthy",
"workbook_hash": (evidence.get("workbook") or {}).get("sha256", ""),
"evidence_id": evidence.get("evidence_id", ""),
"recognition_score": score,
"issue_counts": issue_counts,
})
@st.dialog("Admin quality override", icon=":material/admin_panel_settings:")
def _render_quality_override_dialog(cm: ConfigManager, quality: RowQualityResult) -> None:
"""Require an unlocked Admin to reauthenticate and justify the override."""
st.warning(
"This permits export despite blocking key issues. The approval is invalidated by any data or mapping change.",
icon=":material/warning:",
)
password = st.text_input("Admin password", type="password", key="quality_override_password")
reason = st.text_area(
"Override reason",
placeholder="Explain why this export is safe to continue (minimum 10 characters).",
key="quality_override_reason",
)
if st.button(
"Approve override",
type="primary",
icon=":material/admin_panel_settings:",
disabled=len(reason.strip()) < 10,
):
if not is_admin_unlocked():
st.error("Admin mode is no longer unlocked.")
return
if not verify_password(password, cm.get_admin_password_hash()):
st.error("Admin password verification failed.")
return
override = create_quality_override(
st.session_state.get("workbook_file_hash") or "",
quality,
reason,
)
write_quality_override_audit(
cm.get_export_audit_log_path(),
override=override,
quality=quality,
workbook_name=st.session_state.get("uploaded_file_name") or "",
selected_type=st.session_state.get("selected_type") or "",
selected_sheets=st.session_state.get("selected_sheet_names") or [],
)
st.session_state.export_quality_override = override
st.rerun()
+302 -83
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
from io import BytesIO
from pathlib import Path
import hashlib
import tempfile
import openpyxl
@@ -12,11 +13,16 @@ import streamlit as st
from services.config_manager import ConfigManager
from services.excel_parser import ExcelParser
from services.fingerprint import Fingerprint, FingerprintMatch
from services.workbook_selection import filter_parsed_workbook_sheets
from services.workbook_selection import (
SheetRecommendation,
filter_parsed_workbook_sheets,
recommend_workbook_sheets,
)
from services.workbook_analyzer import WorkbookAnalyzer, AnalysisResult
from utils.helpers import safe_dataframe
from ui.copy import current_language, t
from ui.workflow_state import clear_workbook_analysis
from ui.workflow_state import navigate_to
DEFAULT_LOW_CONFIDENCE_WARNING_THRESHOLD = 40.0
@@ -28,35 +34,55 @@ def render_upload_page():
st.caption(t("upload.subtitle", lang))
cm: ConfigManager = st.session_state.config_manager
allowed_extensions = cm.get_supported_upload_extensions()
allowed_widget_types = [item.lstrip(".") for item in allowed_extensions]
upload_key = f"excel_upload_{st.session_state.get('upload_widget_nonce', 0)}"
with st.container(border=True):
st.subheader("Choose the source file")
st.caption("Accepted formats: .xlsx and .xls. Your original file is not modified.")
st.caption(
f"Accepted format: {', '.join(allowed_extensions)}. "
f"Maximum size: {cm.get_max_upload_size_mb()} MB. Your original file is not modified."
)
uploaded_file = st.file_uploader(
t("upload.file_label", lang), type=["xlsx", "xls"], key=upload_key,
t("upload.file_label", lang), type=allowed_widget_types, key=upload_key,
label_visibility="collapsed",
)
if uploaded_file is None:
st.info("Upload a workbook to begin structure detection and mapping.", icon=":material/upload_file:")
st.info(
"Upload a workbook, check the recommended sheets, then confirm the detected format.",
icon=":material/upload_file:",
)
return
if Path(uploaded_file.name).suffix.lower() not in allowed_extensions:
st.error("This file type is not supported. Please save the workbook as .xlsx.")
return
file_bytes = uploaded_file.getvalue()
token = f"{uploaded_file.name}:{len(file_bytes)}"
if len(file_bytes) > cm.get_max_upload_size_mb() * 1024 * 1024:
st.error(f"This workbook exceeds the {cm.get_max_upload_size_mb()} MB upload limit.")
return
token = hashlib.sha256(file_bytes).hexdigest()
if st.session_state.get("upload_token") != token:
_reset_for_new_upload(uploaded_file.name, file_bytes, token)
if st.session_state.get("workbook_discovery_hash") != token:
with st.spinner("Inspecting workbook structure..."):
_run_workbook_discovery(cm, file_bytes, token)
selected_sheet_names = _render_sheet_preview(file_bytes, lang)
if not selected_sheet_names:
st.warning("Select at least one sheet before analysis.")
return
analysis_token = f"{token}:{'|'.join(selected_sheet_names)}"
analysis_token = _analysis_cache_key(
st.session_state.get("selected_type"), selected_sheet_names
)
if st.session_state.get("basic_analysis_selection_token") != analysis_token:
with st.spinner(t("upload.basic_spinner", lang)):
_run_basic_analysis(
cm,
file_bytes,
requested_type=None,
requested_type=st.session_state.get("selected_type"),
selected_sheet_names=selected_sheet_names,
)
st.session_state.basic_analysis_selection_token = analysis_token
@@ -70,16 +96,17 @@ def _reset_for_new_upload(file_name: str, file_bytes: bytes, token: str) -> None
st.session_state.uploaded_file_name = file_name
st.session_state.uploaded_file_bytes = file_bytes
st.session_state.upload_token = token
st.session_state.workbook_file_hash = token
st.session_state.basic_analysis_cache = {}
st.session_state.pop("upload_type_choice", None)
def _render_sheet_preview(file_bytes: bytes, lang: str) -> list[str]:
"""Show the extracted workbook data before any mapping decision."""
st.subheader("Choose sheets")
st.caption("Only selected sheets continue to analysis, preview, and export.")
st.subheader("Choose the sheets to use")
st.caption("The app recommends the most likely product sheets. You can change the selection before continuing.")
try:
wb = openpyxl.load_workbook(BytesIO(file_bytes), data_only=True)
wb = openpyxl.load_workbook(BytesIO(file_bytes), data_only=True, read_only=True)
except Exception as e:
st.error(t("upload.cannot_read", lang, error=e))
return []
@@ -91,52 +118,126 @@ def _render_sheet_preview(file_bytes: bytes, lang: str) -> list[str]:
default_selected = available_sheet_names
else:
default_selected = [name for name in previous if name in available_sheet_names]
widget_key = f"selected_sheets_{st.session_state.get('workbook_file_hash', '')[:12]}"
if widget_key not in st.session_state:
st.session_state[widget_key] = default_selected
selected_sheet_names = st.multiselect(
"Sheets to analyse",
"Sheets included in this upload",
options=available_sheet_names,
default=default_selected,
help="Only selected sheets continue to header detection, mapping, AI, preview, and export.",
key=f"selected_sheets_{st.session_state.get('upload_widget_nonce', 0)}",
help="Only these sheets continue to Review, Preview, and Export.",
key=widget_key,
on_change=_mark_sheet_selection_touched,
args=(widget_key,),
disabled=not st.session_state.config_manager.get_operator_review_config()["allow_sheet_selection"],
)
st.session_state.selected_sheet_names = selected_sheet_names
for sheet_name in wb.sheetnames:
ws = wb[sheet_name]
scope_icon = "✅" if sheet_name in selected_sheet_names else "⏭️"
with st.expander(f"{scope_icon} {sheet_name} ({ws.max_row} rows × {ws.max_column} cols)"):
n = st.number_input(
t("upload.show_rows", lang),
min_value=1,
max_value=max(ws.max_row, 1),
value=min(ws.max_row, 30),
key=f"up_rows_{sheet_name}",
_render_sheet_recommendation_summary(available_sheet_names, selected_sheet_names)
if selected_sheet_names:
preview_key = f"upload_preview_sheet_{st.session_state.get('workbook_file_hash', '')[:12]}"
if st.session_state.get(preview_key) not in selected_sheet_names:
st.session_state[preview_key] = selected_sheet_names[0]
preview_name = st.selectbox(
"Sheet preview",
options=selected_sheet_names,
key=preview_key,
help="Preview one selected sheet at a time.",
)
ws = wb[preview_name]
with st.container(border=True):
st.caption(f"{ws.max_row} rows · {ws.max_column} columns")
_render_worksheet_preview(ws, preview_name, lang)
other_sheet_names = [name for name in available_sheet_names if name not in selected_sheet_names]
if other_sheet_names:
with st.expander(f"Other sheets not included ({len(other_sheet_names)})", expanded=False):
st.dataframe(
pd.DataFrame([
{
"Sheet": sheet_name,
"Rows": wb[sheet_name].max_row,
"Columns": wb[sheet_name].max_column,
}
for sheet_name in other_sheet_names
]),
width="stretch",
hide_index=True,
)
data = []
for row in ws.iter_rows(min_row=1, max_row=min(ws.max_row, n), values_only=True):
data.append([str(c)[:80] if c is not None else "" for c in row])
if data:
st.dataframe(
safe_dataframe(pd.DataFrame(data)),
width="stretch",
hide_index=True,
height=min(len(data) * 35 + 38, 480),
)
wb.close()
return selected_sheet_names
def _render_worksheet_preview(ws, sheet_name: str, lang: str, default_rows: int = 30) -> None:
"""Render a bounded worksheet preview using native table components."""
n = st.number_input(
t("upload.show_rows", lang),
min_value=1,
max_value=max(ws.max_row, 1),
value=min(ws.max_row, default_rows),
key=f"up_rows_{sheet_name}",
)
data = [
[str(cell)[:80] if cell is not None else "" for cell in row]
for row in ws.iter_rows(min_row=1, max_row=min(ws.max_row, n), values_only=True)
]
if data:
st.dataframe(
safe_dataframe(pd.DataFrame(data)),
width="stretch",
hide_index=True,
height=min(len(data) * 35 + 38, 480),
)
def _mark_sheet_selection_touched(widget_key: str) -> None:
st.session_state.selected_sheet_names = list(st.session_state.get(widget_key) or [])
st.session_state.sheet_selection_touched = True
st.session_state.sheet_selection_source = "manual"
_invalidate_sheet_scoped_outputs()
def _render_sheet_recommendation_summary(
available_sheet_names: list[str], selected_sheet_names: list[str]
) -> None:
selected_type_id = st.session_state.get("selected_type") or ""
cm: ConfigManager = st.session_state.config_manager
selected_type = str(
(cm.get_type_config(selected_type_id) or {}).get("label")
or selected_type_id
or "Not recognised"
)
patterns = st.session_state.get("recommended_sheet_patterns") or []
matched = st.session_state.get("matched_sheet_patterns") or []
reason = st.session_state.get("sheet_recommendation_reason") or "All sheets remain available."
with st.container(border=True):
with st.container(horizontal=True, vertical_alignment="center"):
st.badge(f"Format: {selected_type}", color="blue")
st.badge(f"{len(selected_sheet_names)} included", color="green")
st.badge(f"{len(available_sheet_names) - len(selected_sheet_names)} not included", color="gray")
if st.session_state.get("sheet_selection_source") == "manual":
st.badge("Selection changed", color="orange")
st.caption(reason)
if patterns:
with st.expander("Technical recommendation details", expanded=False):
st.caption(
"Configured patterns: " + ", ".join(patterns)
+ (" · Matches: " + ", ".join(matched) if matched else "")
)
def _render_basic_analysis_panel(cm: ConfigManager, file_bytes: bytes, lang: str) -> None:
"""Render confidence, type override, and continue gate for basic analysis."""
st.subheader("Confirm workbook type")
st.caption("Review the detected type before continuing to mapping review.")
st.subheader("Confirm the workbook format")
st.caption("Confirm the format so the app can apply the correct column rules.")
matches: list[FingerprintMatch] = st.session_state.get("fingerprint_matches") or []
if matches:
match_rows = [{"Type": m.label, "Type ID": m.type_id, "Confidence": f"{m.score:.1f}%"} for m in matches]
with st.expander(t("upload.show_type_matches", lang), expanded=False):
match_rows = [{"Format": m.label, "Format ID": m.type_id, "Match score": f"{m.score:.1f}%"} for m in matches]
with st.expander("Technical format matches", expanded=False):
st.dataframe(safe_dataframe(pd.DataFrame(match_rows)), width="stretch", hide_index=True)
else:
st.warning(t("upload.no_type_matches", lang))
st.warning("This workbook format was not recognised. Choose the closest format before continuing.")
type_options = [t["type_id"] for t in cm.get_type_list()]
label_by_id = {t["type_id"]: t["label"] for t in cm.get_type_list()}
@@ -144,20 +245,38 @@ def _render_basic_analysis_panel(cm: ConfigManager, file_bytes: bytes, lang: str
select_options = [""] + type_options
default_idx = select_options.index(active_type) if active_type in select_options else 0
chosen_type = st.selectbox(
t("upload.type_select", lang),
"Workbook format",
options=select_options,
format_func=lambda tid: t("upload.type_none", lang) if not tid else f"{label_by_id.get(tid, tid)} ({tid})",
format_func=lambda tid: "Select a format" if not tid else label_by_id.get(tid, tid),
index=default_idx,
key=f"upload_type_choice_{st.session_state.get('upload_widget_nonce', 0)}",
disabled=not cm.get_operator_review_config()["allow_type_override"],
)
learned = (cm.get_type_config(chosen_type or active_type or "") or {}).get("learning", {}) or {}
if learned.get("evidence_ids"):
st.caption(
f"Admin-approved learned format · confirmed with "
f"{len(learned.get('evidence_ids') or [])} previous workbook(s)"
)
cache: dict = st.session_state.get("basic_analysis_cache") or {}
if chosen_type and chosen_type != active_type:
if chosen_type in cache:
_activate_basic_analysis(chosen_type)
cache_key = _analysis_cache_key(
chosen_type, st.session_state.get("selected_sheet_names") or []
)
if cache_key in cache:
_activate_basic_analysis(cache_key)
active_type = chosen_type
else:
st.session_state.basic_pending_type = chosen_type
recommendation = _recommendation_for_type(cm, chosen_type)
current_selection = list(st.session_state.get("selected_sheet_names") or [])
if (
not st.session_state.get("sheet_selection_touched")
and recommendation.selected != current_selection
):
_apply_sheet_recommendation(recommendation, chosen_type)
st.rerun()
pending_type = st.session_state.get("basic_pending_type")
if pending_type and pending_type == active_type:
@@ -173,7 +292,21 @@ def _render_basic_analysis_panel(cm: ConfigManager, file_bytes: bytes, lang: str
if pending_type:
st.warning(t("upload.type_changed", lang, type=label_by_id.get(pending_type, pending_type)))
if st.button(t("upload.rerun_basic", lang), type="primary", width="stretch", icon=":material/refresh:"):
recommendation = _recommendation_for_type(cm, pending_type)
if recommendation.selected != list(st.session_state.get("selected_sheet_names") or []):
st.caption(
"Recommended sheets for this format: "
+ ", ".join(recommendation.selected)
+ ". Your current manual selection will not be replaced automatically."
)
if st.button(
"Apply recommended sheets",
width="stretch",
icon=":material/auto_awesome:",
):
_apply_sheet_recommendation(recommendation, pending_type)
st.rerun()
if st.button("Apply this format", type="primary", width="stretch", icon=":material/refresh:"):
with st.spinner(t("upload.basic_spinner", lang)):
_run_basic_analysis(
cm,
@@ -196,32 +329,38 @@ def _render_basic_analysis_panel(cm: ConfigManager, file_bytes: bytes, lang: str
)
can_continue = _can_continue_basic(active_type, result, cm, active_score, confirmed_low_confidence)
if st.button("Continue to mapping review", type="primary", width="stretch", disabled=not can_continue, icon=":material/arrow_forward:"):
if st.button("Continue to review", type="primary", width="stretch", disabled=not can_continue, icon=":material/arrow_forward:"):
st.session_state.analysis_result = None
st.session_state.analysis_trace = []
st.session_state.confirmed_blueprint = None
st.session_state.processed_rows = None
st.session_state.current_step = "confirm"
st.session_state.active_analysis_source = "basic"
navigate_to("confirm")
st.rerun()
def _render_basic_status(type_id: str, score: float, result: AnalysisResult, lang: str) -> None:
"""Show current basic-analysis result and continuation confidence."""
status_threshold = DEFAULT_LOW_CONFIDENCE_WARNING_THRESHOLD
status = "🟢" if score >= 80 else ("🟡" if score >= status_threshold else "🔴")
st.markdown(
f"""
<div class="nbd-card nbd-result-strip">
<span><b>{t("upload.selected_type", lang)}</b> <code>{type_id}</code></span>
<span><b>{t("upload.basic_confidence", lang)}</b> {status} {score:.1f}%</span>
<span><b>{t("confirm.sheets", lang)}</b> {len(result.summaries)}</span>
<span><b>{t("confirm.links_count", lang)}</b> {sum(len(g.links) for g in result.groups)}</span>
<span><b>{t("confirm.mappings_count", lang)}</b> {len(result.mappings)}</span>
</div>
""",
unsafe_allow_html=True,
)
st.progress(min(max(score / 100.0, 0.0), 1.0), text=t("upload.basic_progress", lang, score=score))
color = "green" if score >= 80 else ("orange" if score >= status_threshold else "red")
status = "Recognised" if score >= 80 else ("Please confirm" if score >= status_threshold else "Low match")
cm: ConfigManager = st.session_state.config_manager
format_label = str((cm.get_type_config(type_id) or {}).get("label") or type_id)
with st.container(border=True):
with st.container(horizontal=True, vertical_alignment="center"):
st.badge(format_label, color="blue")
st.badge(status, color=color)
st.badge(f"{len(result.summaries)} sheets", color="gray")
st.badge(f"{len(result.mappings)} fields assigned", color="gray")
st.caption("The format decision can still be changed before Review.")
with st.expander("Technical detection details", expanded=False):
st.progress(
min(max(score / 100.0, 0.0), 1.0),
text=f"Format match score: {score:.1f}%",
)
st.caption(
f"{sum(len(group.links) for group in result.groups)} cross-sheet links detected."
)
def _run_basic_analysis(
@@ -238,57 +377,53 @@ def _run_basic_analysis(
temp_path = Path(tmp.name)
parser = ExcelParser(cm)
fingerprint = Fingerprint(cm)
parsed_initial = filter_parsed_workbook_sheets(parser.parse(temp_path), selected_sheet_names)
matches = fingerprint.recognize(fingerprint.compute_signature(parsed_initial))
st.session_state.fingerprint_matches = matches
matches = st.session_state.get("fingerprint_matches") or []
selected_type = requested_type or (matches[0].type_id if matches else None)
score = _score_for_type(matches, selected_type)
parsed = (
filter_parsed_workbook_sheets(parser.parse(temp_path, type_id=selected_type), selected_sheet_names)
if selected_type else parsed_initial
)
full_parsed = parser.parse(temp_path, type_id=selected_type) if selected_type else parser.parse(temp_path)
parsed = filter_parsed_workbook_sheets(full_parsed, selected_sheet_names)
analysis = WorkbookAnalyzer(cm).analyze(parsed, preferred_type_id=selected_type, use_llm=False)
cache = st.session_state.get("basic_analysis_cache") or {}
cache[selected_type or ""] = {
cache_key = _analysis_cache_key(selected_type, selected_sheet_names or [])
cache[cache_key] = {
"type_id": selected_type,
"score": score,
"parsed": parsed,
"analysis": analysis,
}
# Keep a small per-session working set; each entry can contain a full
# parsed workbook and must not grow without bound as operators experiment.
while len(cache) > 3:
oldest_key = next(iter(cache))
if oldest_key == cache_key and len(cache) > 1:
oldest_key = next(key for key in cache if key != cache_key)
cache.pop(oldest_key, None)
st.session_state.basic_analysis_cache = cache
_activate_basic_analysis(selected_type or "")
_activate_basic_analysis(cache_key)
st.session_state.basic_pending_type = None
finally:
if temp_path is not None:
temp_path.unlink(missing_ok=True)
def _activate_basic_analysis(type_key: str) -> None:
def _activate_basic_analysis(cache_key: str) -> None:
"""Make a cached deterministic analysis the active upload decision."""
cache = st.session_state.get("basic_analysis_cache") or {}
entry = cache.get(type_key)
entry = cache.get(cache_key)
if not entry:
return
st.session_state.selected_type = entry["type_id"]
st.session_state.parsed_workbook = entry["parsed"]
st.session_state.basic_analysis_result = entry["analysis"]
st.session_state.analysis_result = None
st.session_state.active_analysis_source = "basic"
st.session_state.confirmed_blueprint = None
st.session_state.reviewed_snapshot = None
st.session_state.reviewed_snapshot_hash = None
st.session_state.processed_rows = None
def _score_for_type(matches: list[FingerprintMatch], type_id: str | None) -> float:
if not type_id:
return 0.0
for match in matches:
if match.type_id == type_id:
return float(match.score)
return 0.0
def _needs_low_confidence_confirmation(cm: ConfigManager, score: float) -> bool:
"""Return True when score is below the configurable warning threshold."""
threshold = cm.get_low_confidence_warning_threshold()
@@ -313,5 +448,89 @@ def _can_continue_basic(
def _active_score() -> float:
active_type = st.session_state.get("selected_type")
cache = st.session_state.get("basic_analysis_cache") or {}
entry = cache.get(active_type or "")
entry = cache.get(
_analysis_cache_key(active_type, st.session_state.get("selected_sheet_names") or [])
)
return float(entry.get("score", 0.0)) if entry else 0.0
def _score_for_type(matches: list[FingerprintMatch], type_id: str | None) -> float:
match = next((item for item in matches if item.type_id == type_id), None)
return float(match.score) if match is not None else 0.0
def _run_workbook_discovery(cm: ConfigManager, file_bytes: bytes, file_hash: str) -> None:
"""Fingerprint the complete workbook before applying any sheet scope."""
temp_path = None
try:
with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as tmp:
tmp.write(file_bytes)
temp_path = Path(tmp.name)
parsed = ExcelParser(cm).parse(temp_path)
matches = Fingerprint(cm).recognize(Fingerprint(cm).compute_signature(parsed))
selected_type = matches[0].type_id if matches else None
st.session_state.fingerprint_matches = matches
st.session_state.selected_type = selected_type
st.session_state.available_sheet_names = [sheet.name for sheet in parsed.sheets]
st.session_state.workbook_discovery_hash = file_hash
recommendation = _recommendation_for_type(cm, selected_type)
_apply_sheet_recommendation(recommendation, selected_type)
finally:
if temp_path is not None:
temp_path.unlink(missing_ok=True)
def _recommendation_for_type(cm: ConfigManager, type_id: str | None) -> SheetRecommendation:
return recommend_workbook_sheets(
st.session_state.get("available_sheet_names") or [],
cm.get_recommended_sheet_patterns(type_id),
)
def _apply_sheet_recommendation(
recommendation: SheetRecommendation, type_id: str | None
) -> None:
"""Apply one recommendation and synchronize its widget/session metadata."""
selected = list(recommendation.selected)
st.session_state.selected_sheet_names = selected
st.session_state.recommended_sheet_names = selected
st.session_state.recommended_sheet_patterns = list(recommendation.configured_patterns)
st.session_state.matched_sheet_patterns = list(recommendation.matched_patterns)
st.session_state.sheet_recommendation_reason = recommendation.reason
st.session_state.sheet_selection_source = (
"fallback_all" if recommendation.used_fallback else "recommended"
)
st.session_state.sheet_selection_touched = False
widget_key = f"selected_sheets_{st.session_state.get('workbook_file_hash', '')[:12]}"
st.session_state[widget_key] = selected
_invalidate_sheet_scoped_outputs()
def _invalidate_sheet_scoped_outputs() -> None:
for key in (
"basic_analysis_selection_token",
"analysis_result",
"confirmed_blueprint",
"reviewed_snapshot",
"reviewed_snapshot_hash",
"processed_rows",
"raw_processed_rows",
"all_processed_rows",
"processed_row_sources",
"review_rebuild_cache",
"review_confirmed_sheet_signatures",
"row_quality_result",
"numeric_key_source_warnings",
"export_quality_override",
):
st.session_state[key] = None
def _analysis_cache_key(type_id: str | None, selected_sheet_names: list[str]) -> str:
return ":".join(
[
str(st.session_state.get("workbook_file_hash") or ""),
str(type_id or ""),
"|".join(str(name) for name in selected_sheet_names),
]
)
+67 -29
View File
@@ -1,56 +1,94 @@
"""Shared session-state contract for the five-step workbook workflow."""
"""Central session-state contract for the four-step workbook workflow."""
from __future__ import annotations
import streamlit as st
WORKFLOW_STATE_KEYS = (
"uploaded_file_name",
"uploaded_file_bytes",
"upload_token",
"selected_type",
"parsed_workbook",
"basic_analysis_result",
"basic_analysis_cache",
"basic_pending_type",
"analysis_result",
"analysis_trace",
"confirmed_blueprint",
"processed_rows",
"raw_processed_rows",
"fingerprint_matches",
"selected_sheet_names",
"available_sheet_names",
"basic_analysis_selection_token",
"review_column_mappings",
"all_processed_rows",
"row_quality_restored_indexes",
"row_quality_result",
)
WORKFLOW_DEFAULTS = {
"current_step": "upload",
"uploaded_file_name": None,
"uploaded_file_bytes": None,
"upload_token": None,
"workbook_file_hash": None,
"workbook_discovery_hash": None,
"selected_type": None,
"parsed_workbook": None,
"basic_analysis_result": None,
"basic_analysis_cache": None,
"basic_pending_type": None,
"analysis_result": None,
"active_analysis_source": "basic",
"analysis_trace": None,
"confirmed_blueprint": None,
"reviewed_snapshot": None,
"reviewed_snapshot_hash": None,
"processed_rows": None,
"raw_processed_rows": None,
"fingerprint_matches": None,
"selected_sheet_names": None,
"available_sheet_names": None,
"recommended_sheet_names": None,
"recommended_sheet_patterns": None,
"matched_sheet_patterns": None,
"sheet_recommendation_reason": None,
"sheet_selection_source": None,
"sheet_selection_touched": False,
"basic_analysis_selection_token": None,
"review_column_mappings": None,
"review_active_sheet": None,
"review_confirmed_sheet_signatures": None,
"review_mapping_view": "Needs attention",
"review_mapping_search": "",
"review_rebuild_cache": None,
"all_processed_rows": None,
"processed_row_sources": None,
"preview_column_view": "Important fields",
"row_quality_restored_indexes": None,
"row_quality_result": None,
"numeric_key_source_warnings": None,
"export_quality_override": None,
"learning_evidence_id": None,
"learning_evidence_signature": None,
}
WORKFLOW_STATE_KEYS = tuple(WORKFLOW_DEFAULTS)
WORKFLOW_ROUTES = {
"upload", "confirm", "ai_analysis", "ai_summary", "preview", "export",
"admin_types", "admin_synonyms", "admin_llm", "admin_blueprints",
}
WORKBOOK_ANALYSIS_KEYS = tuple(
key
for key in WORKFLOW_STATE_KEYS
if key not in {"uploaded_file_name", "uploaded_file_bytes", "upload_token"}
if key not in {"current_step", "uploaded_file_name", "uploaded_file_bytes", "upload_token"}
)
def initialize_workflow_state() -> None:
"""Initialize every non-widget workflow value in one place."""
for key in WORKFLOW_STATE_KEYS:
st.session_state.setdefault(key, None)
for key, default in WORKFLOW_DEFAULTS.items():
st.session_state.setdefault(key, default)
st.session_state.setdefault("upload_widget_nonce", 0)
def clear_workbook_analysis() -> None:
"""Clear derived state before analyzing a newly uploaded workbook."""
for key in WORKBOOK_ANALYSIS_KEYS:
st.session_state[key] = None
st.session_state[key] = WORKFLOW_DEFAULTS[key]
def reset_workflow_state() -> None:
"""Clear the workflow and force a fresh upload widget instance."""
for key in WORKFLOW_STATE_KEYS:
st.session_state[key] = None
st.session_state[key] = WORKFLOW_DEFAULTS[key]
st.session_state.upload_widget_nonce = int(st.session_state.get("upload_widget_nonce", 0)) + 1
st.session_state.current_step = "upload"
def navigate_to(step: str) -> None:
"""Set one canonical application route through a single validation point."""
route = str(step or "upload")
if route not in WORKFLOW_ROUTES:
raise ValueError(f"Unknown workflow route: {route}")
st.session_state.current_step = route