Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e11f2be06c | ||
|
|
0e18176901 | ||
|
|
0af17818f0 | ||
|
|
6b16370275 | ||
|
|
11e0b8075f | ||
|
|
5378c4efbf | ||
|
|
8158578749 | ||
|
|
44275330dc | ||
|
|
5a208da71a | ||
|
|
c67ca42f50 | ||
|
|
9fe1433ee9 | ||
|
|
d4345125e4 | ||
|
|
2a2b06d13b | ||
|
|
2665179707 | ||
|
|
737cdd2c02 | ||
|
|
79e5fdbc24 | ||
|
|
8499947fc8 | ||
|
|
e768a0ad74 | ||
|
|
3e3a5fb04e | ||
|
|
4223dd2f8f | ||
|
|
8c1fdf32ab | ||
|
|
a5171d40cc | ||
|
|
2805d228c1 | ||
|
|
a5fc4cc662 | ||
|
|
88a0b61eda | ||
|
|
0556c85f67 | ||
|
|
307e77d13e | ||
|
|
55866de250 | ||
|
|
7e077460df | ||
|
|
4a651631cb | ||
|
|
b1721593b3 | ||
|
|
1e72241d1b | ||
|
|
be076c6518 |
No files matched your search
@@ -0,0 +1,29 @@
|
||||
# Source control / local tooling
|
||||
.git
|
||||
.gitignore
|
||||
.hermes/
|
||||
.venv/
|
||||
venv/
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
*.py[cod]
|
||||
|
||||
# Runtime data and local artifacts
|
||||
data/
|
||||
artifacts/
|
||||
test_e2e_diagnostics.txt
|
||||
*.log
|
||||
|
||||
# Runtime secrets/config: use docker-compose volumes/env instead
|
||||
.env
|
||||
*.env
|
||||
config/settings.yaml
|
||||
config/settings.local.yaml
|
||||
|
||||
# OS/editor noise
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
+6
-2
@@ -2,9 +2,13 @@ __pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
.pytest_cache/
|
||||
.streamlit/
|
||||
.streamlit/*
|
||||
!.streamlit/config.toml
|
||||
~$*.xlsx
|
||||
~$*.xls
|
||||
artifacts/
|
||||
data/
|
||||
config/settings.yaml
|
||||
config/settings.local.yaml
|
||||
config/fingerprints.json
|
||||
.hermes/
|
||||
.venv/
|
||||
@@ -0,0 +1,30 @@
|
||||
[theme]
|
||||
base = "light"
|
||||
primaryColor = "#18181B"
|
||||
backgroundColor = "#FFFFFF"
|
||||
secondaryBackgroundColor = "#FAFAFA"
|
||||
textColor = "#09090B"
|
||||
borderColor = "#E4E4E7"
|
||||
showWidgetBorder = true
|
||||
showSidebarBorder = true
|
||||
baseRadius = "8px"
|
||||
buttonRadius = "8px"
|
||||
font = "sans-serif"
|
||||
baseFontSize = 15
|
||||
headingFontSizes = ["34px", "27px", "22px", "18px", "16px", "14px"]
|
||||
headingFontWeights = [650, 650, 600, 600, 600, 600]
|
||||
linkUnderline = false
|
||||
blueColor = "#2563EB"
|
||||
greenColor = "#16A34A"
|
||||
redColor = "#DC2626"
|
||||
orangeColor = "#EA580C"
|
||||
grayColor = "#71717A"
|
||||
dataframeBorderColor = "#E4E4E7"
|
||||
dataframeHeaderBackgroundColor = "#FAFAFA"
|
||||
|
||||
[theme.sidebar]
|
||||
backgroundColor = "#FAFAFA"
|
||||
secondaryBackgroundColor = "#F4F4F5"
|
||||
textColor = "#09090B"
|
||||
borderColor = "#E4E4E7"
|
||||
primaryColor = "#18181B"
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
STREAMLIT_SERVER_ADDRESS=0.0.0.0 \
|
||||
STREAMLIT_SERVER_PORT=8501 \
|
||||
STREAMLIT_SERVER_HEADLESS=true \
|
||||
STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt ./
|
||||
RUN pip install --upgrade pip \
|
||||
&& pip install -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
RUN mkdir -p /app/data /app/data/tmp_blueprints
|
||||
|
||||
EXPOSE 8501
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD curl -fsS http://127.0.0.1:8501/_stcore/health || exit 1
|
||||
|
||||
CMD ["streamlit", "run", "app.py", "--server.address=0.0.0.0", "--server.port=8501", "--server.headless=true", "--browser.gatherUsageStats=false"]
|
||||
@@ -0,0 +1,163 @@
|
||||
# NBD Offer Pre-Item Master
|
||||
|
||||
NBD Offer Pre-Item Master is a Streamlit application that converts supplier / offer Excel workbooks into a formal one-sheet `pre_item_master` Excel export matching the SQL table schema.
|
||||
|
||||
It reads every workbook sheet, recognizes known formats, builds a merge blueprint, maps source columns to SQL columns, previews one row per product, and exports a deterministic `pre_item_master_YYYYMMDD_HHMMSS.xlsx` file.
|
||||
|
||||
## Language
|
||||
|
||||
- Runtime UI language: **English only**
|
||||
- Project documentation remains bilingual (English + Traditional Chinese)
|
||||
- Traditional Chinese README: [README_CHT.md](README_CHT.md)
|
||||
|
||||
## Direct documentation links
|
||||
|
||||
| Document | English | Traditional Chinese |
|
||||
|---|---|---|
|
||||
| Product / technical specification | [docs/SPEC.md](docs/SPEC.md) | same bilingual file |
|
||||
| User workflow | [docs/WORKFLOW.md](docs/WORKFLOW.md) | same bilingual file |
|
||||
| LLM specification | [docs/LLM_SPEC.md](docs/LLM_SPEC.md) | [docs/LLM_SPEC_CHT.md](docs/LLM_SPEC_CHT.md) |
|
||||
| SQL export schema | [config/db_schema.yaml](config/db_schema.yaml) | same |
|
||||
| LLM target schema | [config/schema.yaml](config/schema.yaml) | same |
|
||||
| Handover: business flow | [docs/BUSINESS_FLOW.md](docs/BUSINESS_FLOW.md) | same bilingual file |
|
||||
| Handover: config | [docs/CONFIG.md](docs/CONFIG.md) | same bilingual file |
|
||||
| Handover: operations | [docs/OPERATIONS.md](docs/OPERATIONS.md) | same bilingual file |
|
||||
| Handover: troubleshooting | [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) | same bilingual file |
|
||||
| Handover: deployment | [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) | same bilingual file |
|
||||
| Data dictionary | [docs/DATA_DICTIONARY.md](docs/DATA_DICTIONARY.md) | same bilingual file |
|
||||
| AI analysis tuning | [docs/AI_ANALYSIS_TUNING.md](docs/AI_ANALYSIS_TUNING.md) | same bilingual file |
|
||||
|
||||
## Verified status
|
||||
|
||||
Run the full verification suite before every merge:
|
||||
|
||||
```text
|
||||
python -m pytest -q
|
||||
```
|
||||
|
||||
Known Kuji workbook regression fixtures export successfully:
|
||||
|
||||
```text
|
||||
kuji_bntw.xlsx -> type=kuji_tw, engine=hybrid, mappings=20, targets=14, rows=15, cols=57, sheet=pre_item_master
|
||||
kuji_bntw_2.xlsx -> type=kuji_tw, engine=hybrid, mappings=19, targets=14, rows=12, cols=57, sheet=pre_item_master
|
||||
```
|
||||
|
||||
The exported workbook is not blank: it contains one `pre_item_master` sheet, 57 SQL columns, and non-empty data rows.
|
||||
|
||||
## What the app does
|
||||
|
||||
1. Upload `.xlsx` / `.xls` workbook.
|
||||
2. Preview sheets before processing.
|
||||
3. Recognize known workbook formats using fingerprints.
|
||||
4. Analyze workbook structure with deterministic rules and optional LLM assistance.
|
||||
5. Detect cross-sheet relations and merge product rows.
|
||||
6. Map source columns to SQL target columns.
|
||||
7. Preview merged rows.
|
||||
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.
|
||||
|
||||
## Architecture overview
|
||||
|
||||
```text
|
||||
app.py
|
||||
└─ ui/upload_page.py Upload + fingerprint recognition
|
||||
└─ ui/confirm_page.py Workbook analysis + blueprint confirmation
|
||||
└─ ui/preview_page.py Merge preview, one row per product
|
||||
└─ ui/export_page.py Formal SQL-shaped Excel export
|
||||
└─ ui/copy.py English-only UI copy registry
|
||||
|
||||
services/excel_parser.py Workbook parsing and known-format structure hints
|
||||
services/fingerprint.py Format recognition by workbook signature
|
||||
services/workbook_analyzer.py LLM + deterministic fallback orchestration
|
||||
services/llm_stages.py OpenAI-compatible LLM calls
|
||||
services/merge_engine.py Cross-sheet row merge
|
||||
services/export_service.py Excel writer
|
||||
services/config_manager.py settings.example.yaml + runtime settings.yaml overlay
|
||||
|
||||
config/settings.example.yaml Tracked safe settings template
|
||||
config/settings.yaml Runtime settings file, gitignored
|
||||
config/db_schema.yaml Formal SQL table export columns
|
||||
config/schema.yaml LLM target field list
|
||||
config/types/*.yaml Known workbook type definitions
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
git clone https://git.umis.moe/davidlo/NBD_Offer_PreItemMaster.git
|
||||
cd NBD_Offer_PreItemMaster
|
||||
python -m pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
python -m streamlit run app.py
|
||||
```
|
||||
|
||||
Open the URL printed by Streamlit, usually:
|
||||
|
||||
```text
|
||||
http://localhost:8501
|
||||
```
|
||||
|
||||
## Optional LLM setup
|
||||
|
||||
The application reads only project-owned configuration at runtime.
|
||||
|
||||
To enable AI matching, copy `config/settings.example.yaml` to `config/settings.yaml`, then edit the active profile:
|
||||
|
||||
```yaml
|
||||
llm:
|
||||
enabled: true
|
||||
active_profile: local
|
||||
profiles:
|
||||
local:
|
||||
label: "DGX Spark Local"
|
||||
base_url: "http://localhost:8000/v1"
|
||||
model: "local-model-name"
|
||||
api_key: "YOUR_LOCAL_API_KEY_OR_BLANK"
|
||||
stream_response: true
|
||||
mode: small
|
||||
max_sheet_rows: 80
|
||||
max_mapping_columns: 40
|
||||
cloud:
|
||||
label: "Cloud AI"
|
||||
base_url: "https://api.deepseek.com/v1"
|
||||
model: "deepseek-chat"
|
||||
api_key: "YOUR_CLOUD_API_KEY_OR_BLANK"
|
||||
stream_response: true
|
||||
mode: large
|
||||
max_sheet_rows: 200
|
||||
max_mapping_columns: 100
|
||||
```
|
||||
|
||||
Switch `active_profile` between `local` and `cloud` to change provider without code changes. Leave the active profile's `api_key` empty to keep optional LLM analysis unavailable. The app intentionally uses one credential field per profile. Keep `stream_response: true` for live AI analysis progress in the Streamlit trace panel. If a provider does not support OpenAI-compatible streaming, the app automatically switches that request to a normal non-streaming response, so the UI does not error; set it to `false` only if you want to skip the streaming attempt entirely.
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
python -m pytest -q
|
||||
```
|
||||
|
||||
Important regression coverage:
|
||||
|
||||
- `settings.example.yaml` defaults plus gitignored runtime `settings.yaml` overlay
|
||||
- AI request resolution from project config only
|
||||
- UI translation helper and bilingual stepper labels
|
||||
- known-format deterministic export behavior when LLM is online
|
||||
- Kuji fixture end-to-end export contract
|
||||
|
||||
## Security and portability rules
|
||||
|
||||
- No API key in tracked files.
|
||||
- Runtime app code reads only project config.
|
||||
- `config/settings.example.yaml` is the tracked template; `config/settings.yaml` is runtime-only and gitignored.
|
||||
- Known workbook formats keep deterministic row-model authority; LLM may add mappings but should not rewrite validated summaries/groups.
|
||||
- Export contract is defined by `config/db_schema.yaml`.
|
||||
|
||||
## Repository
|
||||
|
||||
- Repository: [https://git.umis.moe/davidlo/NBD_Offer_PreItemMaster](https://git.umis.moe/davidlo/NBD_Offer_PreItemMaster)
|
||||
- English README: [README.md](README.md)
|
||||
- Traditional Chinese README: [README_CHT.md](README_CHT.md)
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
# NBD Offer Pre-Item Master
|
||||
|
||||
NBD Offer Pre-Item Master 係一個 Streamlit app,用嚟將 supplier / offer Excel workbook 轉成正式單 sheet `pre_item_master` Excel 匯出檔,欄位跟 SQL table schema。
|
||||
|
||||
系統會讀取 workbook 內每個 sheet、識別已知格式、建立 merge blueprint、將來源欄位配對到 SQL 欄位、預覽每個產品一行嘅結果,最後匯出 deterministic 嘅 `pre_item_master_YYYYMMDD_HHMMSS.xlsx`。
|
||||
|
||||
## 語言
|
||||
|
||||
- Runtime UI 語言:**只保留英文**
|
||||
- Project 文檔維持雙語(English + 繁體中文)
|
||||
- English README: [README.md](README.md)
|
||||
|
||||
## 文件直連
|
||||
|
||||
| 文件 | English | 繁體中文 |
|
||||
|---|---|---|
|
||||
| 產品 / 技術規格 | [docs/SPEC.md](docs/SPEC.md) | same bilingual file |
|
||||
| 使用流程 | [docs/WORKFLOW.md](docs/WORKFLOW.md) | same bilingual file |
|
||||
| LLM 規格 | [docs/LLM_SPEC.md](docs/LLM_SPEC.md) | [docs/LLM_SPEC_CHT.md](docs/LLM_SPEC_CHT.md) |
|
||||
| SQL 匯出 schema | [config/db_schema.yaml](config/db_schema.yaml) | same |
|
||||
| LLM target schema | [config/schema.yaml](config/schema.yaml) | same |
|
||||
| 交接:業務流程 | [docs/BUSINESS_FLOW.md](docs/BUSINESS_FLOW.md) | same bilingual file |
|
||||
| 交接:設定 | [docs/CONFIG.md](docs/CONFIG.md) | same bilingual file |
|
||||
| 交接:維運 | [docs/OPERATIONS.md](docs/OPERATIONS.md) | same bilingual file |
|
||||
| 交接:疑難排解 | [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) | same bilingual file |
|
||||
| 交接:部署 | [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) | same bilingual file |
|
||||
| 數據字典 | [docs/DATA_DICTIONARY.md](docs/DATA_DICTIONARY.md) | same bilingual file |
|
||||
| AI 分析調校 | [docs/AI_ANALYSIS_TUNING.md](docs/AI_ANALYSIS_TUNING.md) | same bilingual file |
|
||||
|
||||
## 已驗證狀態
|
||||
|
||||
目前 local verification:
|
||||
|
||||
```text
|
||||
python -m pytest -q
|
||||
```
|
||||
|
||||
已知 Kuji workbook regression fixtures 可成功 mapping / export:
|
||||
|
||||
```text
|
||||
kuji_bntw.xlsx -> type=kuji_tw, engine=hybrid, mappings=20, targets=14, rows=15, cols=57, sheet=pre_item_master
|
||||
kuji_bntw_2.xlsx -> type=kuji_tw, engine=hybrid, mappings=19, targets=14, rows=12, cols=57, sheet=pre_item_master
|
||||
```
|
||||
|
||||
匯出 workbook 唔係空白:包含一個 `pre_item_master` sheet、57 個 SQL columns 同非空白 data rows。
|
||||
|
||||
## App 功能
|
||||
|
||||
1. 上傳 `.xlsx` / `.xls` workbook。
|
||||
2. 處理前預覽 sheets。
|
||||
3. 用 fingerprint 識別已知 workbook 格式。
|
||||
4. 用 deterministic rules + optional LLM 分析 workbook 結構。
|
||||
5. 偵測跨 sheet 關係並合併產品 rows。
|
||||
6. 將來源欄位配對到 SQL target columns。
|
||||
7. 預覽合併後每個產品一行。
|
||||
8. 匯出單 sheet Excel workbook:`pre_item_master_<timestamp>.xlsx`。
|
||||
9. 可選擇提交 Match Blueprint proposal,待 Admin review 後日後重用。
|
||||
|
||||
## 架構概覽
|
||||
|
||||
```text
|
||||
app.py
|
||||
└─ ui/upload_page.py 上傳 + fingerprint recognition
|
||||
└─ ui/confirm_page.py Workbook analysis + blueprint confirmation
|
||||
└─ ui/preview_page.py Merge preview,每個產品一行
|
||||
└─ ui/export_page.py 正式 SQL-shaped Excel export
|
||||
└─ ui/copy.py English-only UI copy registry
|
||||
|
||||
services/excel_parser.py Workbook parsing 同已知格式 structure hints
|
||||
services/fingerprint.py 用 workbook signature 識別格式
|
||||
services/workbook_analyzer.py LLM + deterministic fallback orchestration
|
||||
services/llm_stages.py OpenAI-compatible LLM calls
|
||||
services/merge_engine.py 跨 sheet row merge
|
||||
services/export_service.py Excel writer
|
||||
services/config_manager.py settings.example.yaml + runtime settings.yaml overlay
|
||||
|
||||
config/settings.example.yaml tracked safe settings template
|
||||
config/settings.yaml runtime settings file,gitignored
|
||||
config/db_schema.yaml 正式 SQL table 匯出欄位
|
||||
config/schema.yaml LLM target field list
|
||||
config/types/*.yaml 已知 workbook type definitions
|
||||
```
|
||||
|
||||
## 安裝
|
||||
|
||||
```bash
|
||||
git clone https://git.umis.moe/davidlo/NBD_Offer_PreItemMaster.git
|
||||
cd NBD_Offer_PreItemMaster
|
||||
python -m pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## 啟動
|
||||
|
||||
```bash
|
||||
python -m streamlit run app.py
|
||||
```
|
||||
|
||||
Streamlit 通常會開:
|
||||
|
||||
```text
|
||||
http://localhost:8501
|
||||
```
|
||||
|
||||
## Optional LLM 設定
|
||||
|
||||
App runtime 只讀 project 自己嘅 config。
|
||||
|
||||
要啟用 AI matching,先由 `config/settings.example.yaml` 複製成 `config/settings.yaml`,再改 active profile:
|
||||
|
||||
```yaml
|
||||
llm:
|
||||
enabled: true
|
||||
active_profile: local
|
||||
profiles:
|
||||
local:
|
||||
label: "DGX Spark Local"
|
||||
base_url: "http://localhost:8000/v1"
|
||||
model: "local-model-name"
|
||||
api_key: "YOUR_LOCAL_API_KEY_OR_BLANK"
|
||||
stream_response: true
|
||||
mode: small
|
||||
max_sheet_rows: 80
|
||||
max_mapping_columns: 40
|
||||
cloud:
|
||||
label: "Cloud AI"
|
||||
base_url: "https://api.deepseek.com/v1"
|
||||
model: "deepseek-chat"
|
||||
api_key: "YOUR_CLOUD_API_KEY_OR_BLANK"
|
||||
stream_response: true
|
||||
mode: large
|
||||
max_sheet_rows: 200
|
||||
max_mapping_columns: 100
|
||||
```
|
||||
|
||||
切換 `active_profile` 就可以喺 local / cloud provider 之間轉換,唔需要改 code。如 active profile 嘅 `api_key` 留空,optional LLM analysis 會保持 unavailable。App 每個 profile 只保留一個 credential 欄位。保持 `stream_response: true` 就會喺 Streamlit trace panel 即時顯示 AI analysis progress。如果 provider 不支援 OpenAI-compatible streaming,app 會自動改用普通 non-streaming response,UI 唔會 error;只有你想完全略過 streaming attempt 時先改做 `false`。
|
||||
|
||||
## 測試
|
||||
|
||||
```bash
|
||||
python -m pytest -q
|
||||
```
|
||||
|
||||
重要 regression coverage:
|
||||
|
||||
- `settings.example.yaml` defaults 加 gitignored runtime `settings.yaml` overlay
|
||||
- AI request 只由 project config resolve
|
||||
- UI translation helper 同 bilingual stepper labels
|
||||
- LLM online 時 known-format deterministic export 仍然穩定
|
||||
- Kuji fixture end-to-end export contract
|
||||
|
||||
## Security / portability 規則
|
||||
|
||||
- tracked files 不可有 API key。
|
||||
- Runtime app 只讀 project config。
|
||||
- `config/settings.example.yaml` 係 tracked template;`config/settings.yaml` 只係 runtime local file,已 gitignore。
|
||||
- 已知 workbook 格式以 deterministic row-model 為準;LLM 只可補 mapping,不可改已驗證 summaries/groups。
|
||||
- Export contract 由 `config/db_schema.yaml` 定義。
|
||||
|
||||
## Repository
|
||||
|
||||
- Repository: [https://git.umis.moe/davidlo/NBD_Offer_PreItemMaster](https://git.umis.moe/davidlo/NBD_Offer_PreItemMaster)
|
||||
- English README: [README.md](README.md)
|
||||
- 繁體中文 README: [README_CHT.md](README_CHT.md)
|
||||
@@ -1,27 +1,56 @@
|
||||
"""NBD Offer Pre-Item Master — Excel Upload WebApp with Intelligent Fuzzy Matching."""
|
||||
import streamlit as st
|
||||
from pathlib import Path
|
||||
"""NBD Offer Pre-Item Master Streamlit application.
|
||||
|
||||
# Page config must be the first Streamlit call
|
||||
This file is the app shell only: it owns Streamlit page setup, long-lived
|
||||
session state, sidebar controls, and route selection. Parsing, analysis,
|
||||
matching, merging, and export logic live under ``services/`` and ``ui/`` so the
|
||||
business logic can be tested without booting Streamlit.
|
||||
"""
|
||||
import logging
|
||||
import warnings
|
||||
|
||||
import streamlit as st
|
||||
|
||||
# Page config must be the first Streamlit call. Streamlit reruns this script on
|
||||
# every user interaction, so all persistent values must live in session_state.
|
||||
st.set_page_config(
|
||||
page_title="NBD Pre-Item Master",
|
||||
page_icon="📊",
|
||||
layout="wide",
|
||||
)
|
||||
|
||||
# Keep stale global Python environments from spamming operator logs. The project
|
||||
# .venv pins compatible versions; these filters only silence known false/noisy
|
||||
# startup warnings so the UI can show useful status instead of traceback-like log
|
||||
# noise when someone launches with a global interpreter.
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message=r"urllib3 .*doesn't match a supported version!",
|
||||
category=Warning,
|
||||
module=r"requests\.__init__",
|
||||
)
|
||||
|
||||
class _BoundaryNoiseFilter(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
return "Skipping data after last boundary" not in record.getMessage()
|
||||
|
||||
for _logger_name in ("python_multipart.multipart", "multipart.multipart", ""):
|
||||
logging.getLogger(_logger_name).addFilter(_BoundaryNoiseFilter())
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from ui.upload_page import render_upload_page
|
||||
from ui.confirm_page import render_confirm_page
|
||||
from ui.preview_page_v2 import render_preview_page_v2
|
||||
from ui.export_page_v2 import render_export_page_v2
|
||||
from ui.ai_analysis_page import render_ai_analysis_page, render_ai_summary_page
|
||||
from ui.preview_page import render_preview_page
|
||||
from ui.export_page import render_export_page
|
||||
from ui.admin_page import render_admin_page
|
||||
# Old pages kept as fallback (not in main flow, but importable)
|
||||
from ui.cross_sheet_page import render_cross_sheet_page
|
||||
from ui.data_preview import render_data_preview
|
||||
from ui.structure_review import render_structure_review
|
||||
from ui.mapping_review import render_mapping_review
|
||||
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.copy import DEFAULT_LANGUAGE, t
|
||||
from ui.workflow_state import initialize_workflow_state, reset_workflow_state
|
||||
|
||||
# ── Initialize app state ──
|
||||
apply_premium_theme()
|
||||
|
||||
# ── Initialize app state ───────────────────────────────────────────
|
||||
if "config_manager" not in st.session_state:
|
||||
st.session_state.config_manager = ConfigManager()
|
||||
|
||||
@@ -31,181 +60,156 @@ if "current_step" not in st.session_state:
|
||||
if "llm_status" not in st.session_state:
|
||||
st.session_state.llm_status = None # None=unchecked, "online", "disabled", "unavailable"
|
||||
|
||||
|
||||
def check_llm_status():
|
||||
"""Check LLM connectivity and set session_state.llm_status."""
|
||||
"""Check lightweight LLM reachability and update the sidebar badge."""
|
||||
cm = st.session_state.config_manager
|
||||
if not cm.is_llm_enabled():
|
||||
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, urllib3
|
||||
cfg = cm.get_llm_config()
|
||||
verify = cfg.get("ssl_verify", True)
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
verify = conn.get("ssl_verify", False)
|
||||
if not verify:
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
url = cfg["base_url"].rstrip("/") + "/models"
|
||||
url = conn["base_url"].rstrip("/") + "/models"
|
||||
resp = requests.get(url, headers={
|
||||
"Authorization": f"Bearer {cm.get_llm_api_key() or ''}",
|
||||
"Authorization": f"Bearer {conn['api_key']}",
|
||||
}, timeout=5, verify=verify)
|
||||
if resp.ok:
|
||||
st.session_state.llm_status = "online"
|
||||
else:
|
||||
st.session_state.llm_status = "unavailable"
|
||||
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
|
||||
|
||||
# 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 ──
|
||||
# uploaded_file: UploadedFile | None
|
||||
# selected_type: str
|
||||
# parsed_workbook: ParsedWorkbook | None
|
||||
# match_results: list[MatchResult] | None
|
||||
# form_matches: list[FormFieldMatch] | None
|
||||
# processed_data: ProcessedData | None
|
||||
|
||||
for key in ["uploaded_file", "selected_type", "parsed_workbook",
|
||||
"match_results", "form_matches", "processed_data",
|
||||
"type_config_modified", "synonyms_modified",
|
||||
"analysis_result", "confirmed_blueprint", "processed_rows",
|
||||
"fingerprint_matches", "recognition_msg"]:
|
||||
if key not in st.session_state:
|
||||
st.session_state[key] = None
|
||||
# ── Session state keys used by the multi-page workflow ─────────────
|
||||
initialize_workflow_state()
|
||||
|
||||
|
||||
def reset_session():
|
||||
"""Clear all processing state, keep config."""
|
||||
cm = st.session_state.config_manager
|
||||
for key in list(st.session_state.keys()):
|
||||
if key != "config_manager":
|
||||
st.session_state[key] = None
|
||||
st.session_state.config_manager = cm
|
||||
st.session_state.current_step = "upload"
|
||||
"""Clear workbook workflow state without touching Streamlit widget keys."""
|
||||
reset_workflow_state()
|
||||
|
||||
|
||||
# ── Sidebar Navigation ──
|
||||
# ── Sidebar navigation and settings ────────────────────────────────
|
||||
lang = DEFAULT_LANGUAGE
|
||||
workflow_busy = bool(st.session_state.get("ai_analysis_running"))
|
||||
with st.sidebar:
|
||||
st.title("📊 NBD Pre-Item Master")
|
||||
st.caption("Excel Upload with Fuzzy Matching")
|
||||
st.markdown("### 📊 NBD Pre-Item Master")
|
||||
st.caption(t("sidebar.subtitle", lang))
|
||||
|
||||
# ── LLM Status Indicator ──
|
||||
status = st.session_state.llm_status
|
||||
badges = {
|
||||
"online": "🟢 LLM 在線 — 智能配對可用",
|
||||
"disabled": "⚫ LLM 關閉 — 使用基本配對",
|
||||
"unavailable": "🔴 LLM 不可用 — 退返基本配對",
|
||||
None: "⏳ LLM 狀態未知",
|
||||
}
|
||||
st.caption(badges.get(status, badges[None]))
|
||||
if st.button("🔄 重新檢查", key="llm_recheck"):
|
||||
check_llm_status()
|
||||
st.rerun()
|
||||
st.divider()
|
||||
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"
|
||||
|
||||
step_labels = {
|
||||
"upload": "🏠 Upload",
|
||||
"confirm": "🔍 Confirm",
|
||||
"preview": "👁️ Preview",
|
||||
"export": "📥 Export",
|
||||
}
|
||||
|
||||
st.subheader("Processing")
|
||||
for step_key, step_label in step_labels.items():
|
||||
if st.session_state.current_step == step_key:
|
||||
st.markdown(f"**→ {step_label}**")
|
||||
else:
|
||||
st.caption(f" {step_label}")
|
||||
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()
|
||||
with st.expander("⚙️ 進階(管理設定)"):
|
||||
if st.button("格式設定(Type Config)"):
|
||||
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])}**")
|
||||
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"
|
||||
st.rerun()
|
||||
if st.button("同義詞字典"):
|
||||
if st.button(t("sidebar.synonyms", lang), width="stretch", disabled=workflow_busy, icon=":material/dictionary:"):
|
||||
st.session_state.current_step = "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"
|
||||
st.rerun()
|
||||
if st.button(t("sidebar.blueprints", lang), width="stretch", disabled=workflow_busy, icon=":material/schema:"):
|
||||
st.session_state.current_step = "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"
|
||||
st.rerun()
|
||||
elif render_admin_unlock(st.session_state.config_manager):
|
||||
st.rerun()
|
||||
|
||||
st.divider()
|
||||
with st.expander("🤖 LLM 設定"):
|
||||
cm = st.session_state.config_manager
|
||||
llm_cfg = cm.get_llm_config()
|
||||
with st.form("llm_settings_form"):
|
||||
st.checkbox("啟用 LLM 智能配對", value=llm_cfg.get("enabled", False), key="llm_enabled_cb")
|
||||
st.text_input("API Base URL", value=llm_cfg.get("base_url", ""), key="llm_base_url")
|
||||
st.text_input("Model", value=llm_cfg.get("model", "gemma4:latest"), key="llm_model")
|
||||
st.checkbox("驗證 SSL 憑證(內部自簽憑證請關閉)", value=llm_cfg.get("ssl_verify", True), key="llm_ssl_verify")
|
||||
has_env_key = cm.get_llm_api_key() is not None and not llm_cfg.get("api_key", "")
|
||||
st.text_input("API Key(直接填這裡)", type="password", value=llm_cfg.get("api_key", ""), key="llm_api_key_input",
|
||||
placeholder="留空則使用環境變數")
|
||||
st.caption(f"或設定環境變數 `{llm_cfg.get('api_key_env', 'BNA_API_KEY')}`(目前 {'✅ 已設定' if has_env_key else '❌ 未設定'})")
|
||||
|
||||
col_a, col_b = st.columns([1, 1])
|
||||
with col_a:
|
||||
if st.form_submit_button("💾 儲存設定"):
|
||||
try:
|
||||
import yaml
|
||||
settings_path = cm.config_dir / "settings.yaml"
|
||||
settings = cm.get_settings()
|
||||
settings["llm"] = {
|
||||
"enabled": st.session_state.llm_enabled_cb,
|
||||
"base_url": st.session_state.llm_base_url,
|
||||
"model": st.session_state.llm_model,
|
||||
"api_key": st.session_state.llm_api_key_input,
|
||||
"api_key_env": llm_cfg.get("api_key_env", "BNA_API_KEY"),
|
||||
"timeout_seconds": llm_cfg.get("timeout_seconds", 30),
|
||||
"temperature": llm_cfg.get("temperature", 0.1),
|
||||
"ssl_verify": st.session_state.llm_ssl_verify,
|
||||
"auto_apply_confidence": llm_cfg.get("auto_apply_confidence", 0.9),
|
||||
"fingerprint_auto_threshold": llm_cfg.get("fingerprint_auto_threshold", 80),
|
||||
"fingerprint_suggest_threshold": llm_cfg.get("fingerprint_suggest_threshold", 60),
|
||||
}
|
||||
with open(settings_path, "w", encoding="utf-8") as f:
|
||||
yaml.dump(settings, f, allow_unicode=True, default_flow_style=False)
|
||||
# Reload
|
||||
cm._settings = settings
|
||||
st.success("✅ 已儲存")
|
||||
except Exception as e:
|
||||
st.error(f"❌ 儲存失敗: {e}")
|
||||
with col_b:
|
||||
test_clicked = st.form_submit_button("🔌 測試連線")
|
||||
if test_clicked:
|
||||
import requests
|
||||
url = st.session_state.llm_base_url.rstrip("/") + "/chat/completions"
|
||||
key = st.session_state.llm_api_key_input or cm.get_llm_api_key()
|
||||
verify = st.session_state.get("llm_ssl_verify", True)
|
||||
try:
|
||||
resp = requests.post(url, headers={
|
||||
"Authorization": f"Bearer {key}",
|
||||
"Content-Type": "application/json",
|
||||
}, json={"model": st.session_state.llm_model, "messages": [{"role": "user", "content": "say OK"}], "max_tokens": 5},
|
||||
timeout=10, verify=verify)
|
||||
if resp.ok:
|
||||
st.success(f"✅ 連線成功 ({resp.status_code})")
|
||||
else:
|
||||
st.error(f"❌ {resp.status_code}: {resp.text[:100]}")
|
||||
except Exception as e:
|
||||
st.error(f"❌ 無法連線: {e}")
|
||||
|
||||
st.divider()
|
||||
if st.button("🔄 Start New Upload"):
|
||||
if st.button(t("sidebar.new_upload", lang), width="stretch", disabled=workflow_busy, icon=":material/add_notes:"):
|
||||
reset_session()
|
||||
st.rerun()
|
||||
|
||||
|
||||
# ── Page Router ──
|
||||
step = st.session_state.current_step
|
||||
# ── 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
|
||||
)
|
||||
|
||||
|
||||
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"
|
||||
render_confirm_page()
|
||||
else:
|
||||
st.session_state.current_step = "upload"
|
||||
render_upload_page()
|
||||
|
||||
|
||||
step = st.session_state.current_step
|
||||
if not step.startswith("admin_"):
|
||||
render_stepper(active_step, lang=lang)
|
||||
st.space("small")
|
||||
if step == "upload":
|
||||
render_upload_page()
|
||||
elif step == "confirm":
|
||||
render_confirm_page()
|
||||
elif step == "ai_analysis":
|
||||
if _optional_ai_route_available():
|
||||
render_ai_analysis_page()
|
||||
else:
|
||||
_render_safe_review_or_upload()
|
||||
elif step == "ai_summary":
|
||||
if _optional_ai_route_available():
|
||||
render_ai_summary_page()
|
||||
else:
|
||||
_render_safe_review_or_upload()
|
||||
elif step == "preview":
|
||||
render_preview_page_v2()
|
||||
render_preview_page()
|
||||
elif step == "export":
|
||||
render_export_page_v2()
|
||||
render_export_page()
|
||||
elif step == "admin_types":
|
||||
render_admin_page(tab="types")
|
||||
elif step == "admin_synonyms":
|
||||
render_admin_page(tab="synonyms")
|
||||
elif step == "admin_llm":
|
||||
render_admin_page(tab="llm")
|
||||
elif step == "admin_blueprints":
|
||||
render_admin_page(tab="blueprints")
|
||||
@@ -0,0 +1,68 @@
|
||||
app:
|
||||
name: NBD Offer Pre-Item Master
|
||||
version: 1.0.0
|
||||
default_export_format: xlsx
|
||||
fuzzy:
|
||||
default_threshold: 75
|
||||
algorithm: token_sort_ratio
|
||||
fallback_algorithm: partial_ratio
|
||||
keyword_match_min: 2
|
||||
analysis:
|
||||
low_confidence_warning_threshold: 40
|
||||
require_confirmation_below_threshold: true
|
||||
# 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
|
||||
# Writes one JSONL file per AI run so failed runs can be diagnosed after the fact.
|
||||
# Files are stored under gitignored data/debug/ and secrets are redacted.
|
||||
ai_debug_log:
|
||||
enabled: true
|
||||
dir: data/debug
|
||||
max_string_chars: 12000
|
||||
llm:
|
||||
enabled: false
|
||||
active_profile: local
|
||||
profiles:
|
||||
local:
|
||||
label: Local AI
|
||||
base_url: http://localhost:8000/v1
|
||||
model: local-model-name
|
||||
api_key: ''
|
||||
timeout_seconds: 60
|
||||
temperature: 0.1
|
||||
ssl_verify: false
|
||||
stream_response: true
|
||||
mode: small
|
||||
max_sheet_rows: 80
|
||||
max_sheet_cols: 30
|
||||
max_candidates_per_sheet: 4
|
||||
sample_rows_per_candidate: 4
|
||||
max_mapping_columns: 40
|
||||
cloud:
|
||||
label: Cloud AI
|
||||
base_url: https://api.deepseek.com/v1
|
||||
model: deepseek-chat
|
||||
api_key: ''
|
||||
timeout_seconds: 90
|
||||
temperature: 0.1
|
||||
ssl_verify: false
|
||||
stream_response: true
|
||||
mode: large
|
||||
max_sheet_rows: 200
|
||||
max_sheet_cols: 60
|
||||
max_candidates_per_sheet: 10
|
||||
sample_rows_per_candidate: 8
|
||||
max_mapping_columns: 100
|
||||
auto_apply_confidence: 0.9
|
||||
fingerprint_auto_threshold: 80
|
||||
fingerprint_suggest_threshold: 60
|
||||
security:
|
||||
admin_password_hash: ''
|
||||
admin_reauth_required_for_mutations: true
|
||||
paths:
|
||||
tmp_blueprints_dir: data/tmp_blueprints
|
||||
file:
|
||||
max_upload_size_mb: 200
|
||||
supported_formats:
|
||||
- .xlsx
|
||||
- .xls
|
||||
@@ -1,34 +0,0 @@
|
||||
app:
|
||||
name: "NBD Offer Pre-Item Master"
|
||||
version: "1.0.0"
|
||||
default_export_format: xlsx
|
||||
|
||||
fuzzy:
|
||||
default_threshold: 75
|
||||
algorithm: token_sort_ratio
|
||||
fallback_algorithm: partial_ratio
|
||||
keyword_match_min: 2
|
||||
|
||||
llm:
|
||||
enabled: true
|
||||
base_url: "https://bnaai02.bhk.local/v1"
|
||||
model: "gemma4:latest"
|
||||
api_key: "sk-Gwn3jPbBbi0vCOhPJy2VnA"
|
||||
api_key_env: "BNA_API_KEY" # read API key from this env var; never hardcode
|
||||
timeout_seconds: 30
|
||||
temperature: 0.1 # low temperature for stable matching
|
||||
ssl_verify: false # false for self-signed internal certs
|
||||
auto_apply_confidence: 0.9 # LLM confidence >= this auto-applies (0-1)
|
||||
fingerprint_auto_threshold: 80 # fingerprint score >= this auto-recognizes format
|
||||
fingerprint_suggest_threshold: 60 # 60-79: list top-3 for user to pick
|
||||
|
||||
# Key fields: at least ONE must be present for a row to be kept.
|
||||
# If ALL of these fields are empty/missing, the row is flagged for drop.
|
||||
key_fields:
|
||||
- generated_barcode
|
||||
- item_name_eng
|
||||
- item_name_jap
|
||||
|
||||
file:
|
||||
max_upload_size_mb: 200
|
||||
supported_formats: [.xlsx, .xls]
|
||||
+42
-23
@@ -4,23 +4,22 @@ category: kuji
|
||||
structure:
|
||||
header_pattern:
|
||||
keywords:
|
||||
- Age
|
||||
- CODE
|
||||
- Date
|
||||
- ITEM
|
||||
- JAN
|
||||
- Japan
|
||||
- Launch
|
||||
- Material_No
|
||||
- Ratings
|
||||
- SALES
|
||||
- SIZE
|
||||
- ※仕様の注意事項
|
||||
- SALES JAN CODE
|
||||
- GL品番
|
||||
- 商品名/日本語
|
||||
- 商品名/英語
|
||||
- 種類
|
||||
- 入数
|
||||
- 納品 倉庫
|
||||
- 原産国
|
||||
- 商品名
|
||||
- 日本語
|
||||
- 納品倉庫
|
||||
- 英語
|
||||
- 対象 年齢
|
||||
- Material
|
||||
- STYLE
|
||||
- Product contents
|
||||
- ITEM SIZE
|
||||
- QTY(pcs)
|
||||
- Age Ratings
|
||||
- Country of Origin
|
||||
strategy: max_keyword_match
|
||||
data_start_offset: 1
|
||||
mapping:
|
||||
@@ -31,7 +30,7 @@ mapping:
|
||||
required: true
|
||||
description: Generated Barcode
|
||||
- source_patterns:
|
||||
- Material_No
|
||||
- GL品番
|
||||
target: sap
|
||||
fuzzy_weight: 1.0
|
||||
required: true
|
||||
@@ -79,11 +78,18 @@ mapping:
|
||||
required: true
|
||||
description: Country of Origin
|
||||
- source_patterns:
|
||||
- 納品 倉庫
|
||||
- 納品倉庫
|
||||
target: factory
|
||||
fuzzy_weight: 1.0
|
||||
required: true
|
||||
description: Factory
|
||||
- source_patterns:
|
||||
- Material
|
||||
target: remark_item2
|
||||
fuzzy_weight: 1.0
|
||||
required: false
|
||||
description: Material / additional remark
|
||||
form_fields:
|
||||
- source_patterns:
|
||||
- SALES JAN CODE
|
||||
@@ -97,15 +103,16 @@ sheet_combine:
|
||||
strategy: join_on_form_fields
|
||||
sheet_relations:
|
||||
- name: Item Detail → DISNEY PRINCESS Enrichment
|
||||
description: >
|
||||
Extract grade code embedded in item name (商品名/英語 or 商品名/日本語)
|
||||
to match against DISNEY PRINCESS STYLE column.
|
||||
Example: "GRADE A:Figure" → token "A" → STYLE row "A" → copy ITEM SIZE, QTY, Age Ratings, Country of Origin.
|
||||
description: 'Extract grade code embedded in item name (商品名/英語 or 商品名/日本語) to match
|
||||
against DISNEY PRINCESS STYLE column. Example: "GRADE A:Figure" → token "A" →
|
||||
STYLE row "A" → copy ITEM SIZE, QTY, Age Ratings, Country of Origin.
|
||||
|
||||
'
|
||||
source:
|
||||
sheet_pattern: 'Item detail'
|
||||
sheet_pattern: Item detail
|
||||
key_column: 商品名/英語
|
||||
target:
|
||||
sheet_pattern: 'DISNEY*'
|
||||
sheet_pattern: DISNEY*
|
||||
match_rules:
|
||||
- column: STYLE
|
||||
strategy: reverse_token_match
|
||||
@@ -117,3 +124,15 @@ sheet_relations:
|
||||
- QTY(pcs)
|
||||
- Age Ratings
|
||||
- Country of Origin
|
||||
fingerprint_headers:
|
||||
- SALES JAN CODE
|
||||
- GL品番
|
||||
- ※仕様の注意事項
|
||||
- 商品名/日本語
|
||||
- 商品名/英語
|
||||
- 種類
|
||||
- 入数
|
||||
- 納品 倉庫
|
||||
- 原産国
|
||||
- 対象 年齢
|
||||
- Material
|
||||
@@ -0,0 +1,17 @@
|
||||
services:
|
||||
nbd-preitemmaster:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: nbd-offer-preitemmaster:latest
|
||||
container_name: nbd-offer-preitemmaster
|
||||
ports:
|
||||
- "8501:8501"
|
||||
volumes:
|
||||
- ./config:/app/config
|
||||
- ./data:/app/data
|
||||
environment:
|
||||
- ADMIN_PASSWORD_HASH=${ADMIN_PASSWORD_HASH:-}
|
||||
- STREAMLIT_SERVER_HEADLESS=true
|
||||
- STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
|
||||
restart: unless-stopped
|
||||
@@ -0,0 +1,103 @@
|
||||
# AI Analysis Tuning / AI 分析調校
|
||||
|
||||
## Summary / 摘要
|
||||
|
||||
The optional AI flow should help with uncertain mappings, not replace known-good deterministic workbook logic. For small models, the most reliable pattern is:
|
||||
|
||||
> deterministic recognition/type config first → bounded AI gap-fill → semantic validation → deterministic hybrid merge.
|
||||
|
||||
可選 AI 應該用嚟處理不確定 mapping,而唔係重新發明已經可靠嘅 type config / fuzzy matching。細 model 最穩陣嘅做法係:
|
||||
|
||||
> 先用 deterministic type recognition → 再俾 AI 做受限制嘅補位 → semantic validation → deterministic hybrid merge。
|
||||
|
||||
Historical measurements and the original failure analysis are archived in [archive/AI_ANALYSIS_BENCHMARKS.md](archive/AI_ANALYSIS_BENCHMARKS.md). They are evidence for the policy below, not a current performance SLA.
|
||||
|
||||
## Accuracy policy / 準確度政策
|
||||
|
||||
Speed is not the main quality metric. The production rule is precision first:
|
||||
|
||||
- 100% of deterministic known-type mappings must be preserved.
|
||||
- AI-only additions are accepted automatically only when confidence is at or above `analysis.ai_auto_accept_mapping_threshold` (default `85`).
|
||||
- Lower-confidence AI suggestions are skipped from export mappings; no approval flow is required.
|
||||
- Every accepted mapping must reference a real workbook header/form label and a real SQL target.
|
||||
|
||||
速度唔係主要質量指標。正式流程以 precision first 為原則:
|
||||
|
||||
- deterministic known-type mapping 必須 100% 保留。
|
||||
- AI-only 新增 mapping 只有信心達到 `analysis.ai_auto_accept_mapping_threshold`(預設 `85`)先會自動加入 export mapping。
|
||||
- 低信心 AI suggestion 會排除;唔需要 approval flow。
|
||||
- 每條 accepted mapping 都必須引用真實 workbook header/form label 同真實 SQL target。
|
||||
|
||||
Latest KUJI reference check / 最新 KUJI reference check:
|
||||
|
||||
| Sample | Baseline preserved | Final invalid pairs | Accepted AI additions | Skipped low-confidence suggestions |
|
||||
|---|---:|---:|---|---:|
|
||||
| `kuji_bntw.xlsx` | 12/12 | 0 | `Number of style -> no_of_asst`, `入数 -> pcs_ctn` | 1 |
|
||||
| `kuji_bntw_2.xlsx` | 12/12 | 0 | `Number of style -> no_of_asst`, `入数 -> pcs_ctn` | 3 |
|
||||
|
||||
|
||||
## Current flow / 現時流程
|
||||
|
||||
1. Parse workbook and detect headers/form fields locally.
|
||||
2. Fingerprint/type recognition selects known type when confidence is high.
|
||||
3. Build deterministic fallback summaries, sheet relations, and exact/fuzzy mappings.
|
||||
4. If a known type has usable mappings, skip open-ended AI Stage 1 and Stage 2.
|
||||
5. Run AI Stage 3 only as a bounded mapping review/gap-fill step.
|
||||
6. Validate model output against actual workbook headers and SQL targets.
|
||||
7. Drop invalid extra rows if valid rows remain; never accept invented fields.
|
||||
8. Merge as hybrid: deterministic mappings win, AI fills only uncovered targets/sources.
|
||||
|
||||
1. 本地 parse workbook,先搵 header / form fields。
|
||||
2. 用 fingerprint/type recognition;高信心就揀 known type。
|
||||
3. 先建立 deterministic fallback:summary、sheet relation、exact/fuzzy mapping。
|
||||
4. 如果 known type 已有可用 mapping,就跳過 open-ended AI Stage 1 / Stage 2。
|
||||
5. AI 只跑 Stage 3,做 bounded mapping review / gap-fill。
|
||||
6. AI output 必須 validate:只可引用真實 Excel header 同 SQL target。
|
||||
7. 如果 AI 多出少量錯 row,但有有效 row,就 drop 錯 row;唔接受 invented fields。
|
||||
8. Hybrid merge:deterministic mapping 優先,AI 只補未覆蓋嘅 target/source。
|
||||
|
||||
## Persistent debug logs / 持久化 debug log
|
||||
|
||||
Every AI run writes a redacted JSON Lines diagnostic file by default:
|
||||
|
||||
```text
|
||||
data/debug/ai_analysis_YYYYMMDD_HHMMSS_<run_id>.jsonl
|
||||
```
|
||||
|
||||
The AI details panel also shows the exact path after a run starts. Send this file back when AI analysis fails or the result is weaker than expected on another machine. The log includes workbook/sheet metadata, detected headers/form fields, selected type, redacted LLM profile/config, prompt/request metadata, HTTP status and response preview, streaming fallback, model response, parsed JSON, validation errors/warnings, final engine/mapping counts, and exception traceback if the run crashes. API keys, Authorization headers, bearer tokens, passwords, and token-shaped strings are redacted before writing.
|
||||
|
||||
To disable or redirect it, edit project-owned `config/settings.yaml`:
|
||||
|
||||
```yaml
|
||||
analysis:
|
||||
ai_debug_log:
|
||||
enabled: true
|
||||
dir: data/debug
|
||||
max_string_chars: 12000
|
||||
```
|
||||
|
||||
每次 AI run 預設會寫一份已遮蔽秘密嘅 JSONL debug log:
|
||||
|
||||
```text
|
||||
data/debug/ai_analysis_YYYYMMDD_HHMMSS_<run_id>.jsonl
|
||||
```
|
||||
|
||||
AI details panel 會顯示實際路徑。另一部機 AI analysis 失敗或者結果變差時,將呢個檔案交返嚟就可以分析。log 會包括 workbook/sheet metadata、detected headers/form fields、selected type、已 redacted LLM profile/config、prompt/request metadata、HTTP status/response preview、streaming fallback、model response、parsed JSON、validation errors/warnings、final engine/mapping count,同 crash traceback。API key、Authorization header、bearer token、password、token-like string 都會先 redact。
|
||||
|
||||
## Small model guidelines / 細 model 使用準則
|
||||
|
||||
- Prefer candidate selection over open-ended interpretation.
|
||||
- Give exact allowed headers and known mappings in the prompt.
|
||||
- Do not ask the model to rediscover row model or joins when type config already knows them.
|
||||
- Keep deterministic output authoritative.
|
||||
- Treat model output as proposals; validate every sheet/header/SQL target/confidence.
|
||||
- Accept valid subsets when safe, instead of retrying the whole response for one invented row.
|
||||
- Keep fallback non-regressing: AI unavailable/invalid still returns deterministic mapping.
|
||||
|
||||
- 優先用 candidate selection,避免 open-ended「理解成份 Excel」。
|
||||
- Prompt 入面列明 exact allowed headers 同 known mappings。
|
||||
- 如果 type config 已知 row model / sheet joins,就唔好叫 model 重新估。
|
||||
- deterministic output 係 authoritative。
|
||||
- model output 只係 proposal;每個 sheet/header/SQL target/confidence 都要 validate。
|
||||
- 有效部分安全時可以保留,錯嘅 invented row drop 掉,避免成份 response retry。
|
||||
- fallback 一定不可退化:AI unavailable/invalid 都要有 deterministic mapping。
|
||||
@@ -0,0 +1,63 @@
|
||||
# Business Flow / 業務流程
|
||||
|
||||
## English
|
||||
|
||||
### Purpose
|
||||
|
||||
This application converts supplier / offer Excel workbooks into a formal `pre_item_master` Excel file. The export file is shaped by `config/db_schema.yaml` and is intended for downstream item-master preparation.
|
||||
|
||||
### 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.
|
||||
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.
|
||||
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.
|
||||
- **Programmer / data team**: maintain parsing, schema, tests, and Docker deployment.
|
||||
|
||||
### Important business rules
|
||||
|
||||
- `config/db_schema.yaml` is the output contract.
|
||||
- Basic users do not directly change system type config.
|
||||
- AI is optional and must fail closed; the deterministic workflow remains available.
|
||||
- Admin write actions require password confirmation.
|
||||
|
||||
## 繁體中文
|
||||
|
||||
### 目的
|
||||
|
||||
此應用程式將 supplier / offer Excel workbook 轉成正式 `pre_item_master` Excel 檔案。匯出欄位以 `config/db_schema.yaml` 為準,供後續 item master 準備使用。
|
||||
|
||||
### 使用流程
|
||||
|
||||
1. **上傳 workbook** — Basic user 上傳 `.xlsx` / `.xls`。
|
||||
2. **預覽 worksheet** — 系統先顯示已抽取嘅 sheet rows,方便檢查來源資料。
|
||||
3. **偵測 workbook type** — 透過 fingerprint 同 deterministic rules 建議最接近嘅格式。
|
||||
4. **信心分數閘口** — 如果信心分數低於設定 threshold,user 必須勾選確認先可以繼續。
|
||||
5. **Basic analysis review** — 檢查 sheet、join rules、欄位 mapping。
|
||||
6. **Optional AI analysis** — AI 只會喺 user 主動按掣時執行;正常 export 唔需要 AI。
|
||||
7. **預覽合併 rows** — 以 `pre_item_master` 欄位顯示每個產品一行。
|
||||
8. **匯出** — 下載 `pre_item_master_<timestamp>.xlsx`。
|
||||
9. **Blueprint proposal** — Basic user 只可提交 temporary proposal,由 Admin review / merge。
|
||||
|
||||
### 角色
|
||||
|
||||
- **Basic user**:上傳、檢查、匯出、提交 temporary blueprint proposal。
|
||||
- **Admin / 管理員**:unlock Admin area,維護 type configs、synonyms、AI settings、merge proposals。
|
||||
- **Programmer / data team**:維護 parser、schema、tests、Docker deployment。
|
||||
|
||||
### 重要規則
|
||||
|
||||
- `config/db_schema.yaml` 係匯出 contract。
|
||||
- Basic user 不可直接修改 system type config。
|
||||
- AI 係 optional,失效時 deterministic workflow 必須照常可用。
|
||||
- Admin 寫入動作需要 password re-auth。
|
||||
@@ -0,0 +1,83 @@
|
||||
# Configuration / 設定
|
||||
|
||||
## English
|
||||
|
||||
### Files
|
||||
|
||||
| File | Purpose | Tracked |
|
||||
|---|---|---|
|
||||
| `config/settings.example.yaml` | Safe default template | Yes |
|
||||
| `config/settings.yaml` | Runtime settings and local secrets | No |
|
||||
| `config/db_schema.yaml` | Export table/column contract | Yes |
|
||||
| `config/schema.yaml` | AI target field descriptions | Yes |
|
||||
| `config/types/*.yaml` | Known workbook format definitions | Yes |
|
||||
| `config/synonyms.yaml` | Fuzzy matching synonyms | Yes |
|
||||
|
||||
### Runtime settings
|
||||
|
||||
Create `config/settings.yaml` from `config/settings.example.yaml` before deployment when local overrides are needed. The app loads the example defaults first and overlays `settings.yaml` when present.
|
||||
|
||||
Key sections:
|
||||
|
||||
- `analysis.low_confidence_warning_threshold`: default `40`; below this score Basic users must confirm before continuing.
|
||||
- `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.
|
||||
|
||||
### Admin password setup
|
||||
|
||||
Generate a hash:
|
||||
|
||||
```bash
|
||||
python scripts/hash_admin_password.py
|
||||
```
|
||||
|
||||
Then either:
|
||||
|
||||
- put it in `config/settings.yaml` under `security.admin_password_hash`, or
|
||||
- pass it as Docker environment variable `ADMIN_PASSWORD_HASH`.
|
||||
|
||||
Never commit real API keys, password hashes, or local runtime settings.
|
||||
|
||||
## 繁體中文
|
||||
|
||||
### 主要檔案
|
||||
|
||||
| 檔案 | 用途 | 是否 commit |
|
||||
|---|---|---|
|
||||
| `config/settings.example.yaml` | 安全預設 template | 是 |
|
||||
| `config/settings.yaml` | runtime setting / local secret | 否 |
|
||||
| `config/db_schema.yaml` | 匯出 table / column contract | 是 |
|
||||
| `config/schema.yaml` | AI target field 描述 | 是 |
|
||||
| `config/types/*.yaml` | 已知 workbook format definitions | 是 |
|
||||
| `config/synonyms.yaml` | fuzzy matching synonyms | 是 |
|
||||
|
||||
### Runtime 設定
|
||||
|
||||
如需要 local override,先由 `config/settings.example.yaml` 複製成 `config/settings.yaml`。系統會先讀 example defaults,再 overlay runtime `settings.yaml`。
|
||||
|
||||
重要 sections:
|
||||
|
||||
- `analysis.low_confidence_warning_threshold`:預設 `40`;低於此分數要 Basic user 勾選確認。
|
||||
- `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。
|
||||
|
||||
### Admin password 設定
|
||||
|
||||
產生 hash:
|
||||
|
||||
```bash
|
||||
python scripts/hash_admin_password.py
|
||||
```
|
||||
|
||||
然後二選一:
|
||||
|
||||
- 放入 `config/settings.yaml` 嘅 `security.admin_password_hash`;或
|
||||
- 用 Docker environment variable `ADMIN_PASSWORD_HASH` 傳入。
|
||||
|
||||
不可 commit 真實 API key、password hash 或 runtime config。
|
||||
@@ -0,0 +1,135 @@
|
||||
# Data Dictionary / 數據字典
|
||||
|
||||
## English
|
||||
|
||||
Target table: `pre_item_master`
|
||||
|
||||
This dictionary is generated from `config/db_schema.yaml`. Blank business descriptions are currently marked as `TBD / 待補` so the data/BI team can fill them in later without changing the export contract.
|
||||
|
||||
| Column | Type | Nullable | Key | Description |
|
||||
|---|---|---|---|---|
|
||||
| `generated_barcode` | `varchar(50)` | Yes / 是 | Yes / 是 | TBD / 待補 |
|
||||
| `sap` | `varchar(50)` | Yes / 是 | Yes / 是 | TBD / 待補 |
|
||||
| `item_name_eng` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `item_name_jap` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `license_apply` | `varchar(1)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `license_sticker` | `varchar(1)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `package_version` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `op_bl` | `varchar(2)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `package_style` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `package_size` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `pcs_ctn` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `dp_ctn` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `pcs_dp` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `no_of_asst` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `age_grade` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `instruction_sheet` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `battery` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark_item` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark_item2` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark_item3` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark_item4` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `information_release_date` | `date` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `images_release_date` | `date` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `period_launch` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `jp_bai_launch` | `date` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `period_asia` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `asia_obs` | `date` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `with_tax` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `without_tax` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `country_of_origin` | `varchar(2)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `currency` | `varchar(3)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `tba_stock` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `inventory_stock_offer` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `tag_qty` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `own_pro` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `ip_holder` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `vendor` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `factory` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `3c_avb` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `rate_rnd2_payto` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `ext_mat_grp` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `ip_group` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `product_line_code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `sales_channel` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `product_series` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `product_type` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `additional_grp` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `character code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `character` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `series code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `series text` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `pz_code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `gl_code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `operation_price` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `created_date` | `datetime` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `updated_date` | `datetime` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
|
||||
## 繁體中文
|
||||
|
||||
目標 table:`pre_item_master`
|
||||
|
||||
此數據字典由 `config/db_schema.yaml` 產生。未有 business description 嘅欄位暫時標記為 `TBD / 待補`,方便 data/BI team 之後補充而唔影響 export contract。
|
||||
|
||||
| 欄位 | 類型 | 可空白 | Key | 說明 |
|
||||
|---|---|---|---|---|
|
||||
| `generated_barcode` | `varchar(50)` | Yes / 是 | Yes / 是 | TBD / 待補 |
|
||||
| `sap` | `varchar(50)` | Yes / 是 | Yes / 是 | TBD / 待補 |
|
||||
| `item_name_eng` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `item_name_jap` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `license_apply` | `varchar(1)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `license_sticker` | `varchar(1)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `package_version` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `op_bl` | `varchar(2)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `package_style` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `package_size` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `pcs_ctn` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `dp_ctn` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `pcs_dp` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `no_of_asst` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `age_grade` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `instruction_sheet` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `battery` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark_item` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark_item2` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark_item3` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark_item4` | `text` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `information_release_date` | `date` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `images_release_date` | `date` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `period_launch` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `jp_bai_launch` | `date` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `period_asia` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `asia_obs` | `date` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `with_tax` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `without_tax` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `country_of_origin` | `varchar(2)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `currency` | `varchar(3)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `tba_stock` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `inventory_stock_offer` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `tag_qty` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `own_pro` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `ip_holder` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `vendor` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `factory` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `3c_avb` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `rate_rnd2_payto` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `remark` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `ext_mat_grp` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `ip_group` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `product_line_code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `sales_channel` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `product_series` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `product_type` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `additional_grp` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `character code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `character` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `series code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `series text` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `pz_code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `gl_code` | `varchar(50)` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `operation_price` | `int` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `created_date` | `datetime` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
| `updated_date` | `datetime` | Yes / 是 | No / 否 | TBD / 待補 |
|
||||
|
||||
Admin / 管理員注意:如要改欄位名稱、類型或順序,必須同步更新 `config/db_schema.yaml`、測試同下游交接文件。
|
||||
@@ -0,0 +1,97 @@
|
||||
# Deployment / 部署
|
||||
|
||||
## English
|
||||
|
||||
### Docker Compose
|
||||
|
||||
Build and start:
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
http://localhost:8501
|
||||
```
|
||||
|
||||
Useful commands:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f nbd-preitemmaster
|
||||
docker compose down
|
||||
```
|
||||
|
||||
### Volumes and persistence
|
||||
|
||||
`docker-compose.yml` mounts:
|
||||
|
||||
- `./config:/app/config` — type definitions, schema, runtime settings.
|
||||
- `./data:/app/data` — temporary blueprint proposals and runtime data.
|
||||
|
||||
Keep `config/settings.yaml` on the host only. It is gitignored and excluded from the Docker image.
|
||||
|
||||
### Admin password in Docker
|
||||
|
||||
Set the password hash before starting:
|
||||
|
||||
```bash
|
||||
export ADMIN_PASSWORD_HASH='pbkdf2_sha256$...'
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
On Windows PowerShell, set the same variable in the shell or use a local `.env` file that is not committed.
|
||||
|
||||
### Port
|
||||
|
||||
The app listens on container port `8501` and exposes host port `8501`.
|
||||
|
||||
## 繁體中文
|
||||
|
||||
### Docker Compose
|
||||
|
||||
Build 同啟動:
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
開啟:
|
||||
|
||||
```text
|
||||
http://localhost:8501
|
||||
```
|
||||
|
||||
常用指令:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f nbd-preitemmaster
|
||||
docker compose down
|
||||
```
|
||||
|
||||
### Volumes / persistent data
|
||||
|
||||
`docker-compose.yml` mount:
|
||||
|
||||
- `./config:/app/config` — type definitions、schema、runtime settings。
|
||||
- `./data:/app/data` — temporary blueprint proposals 同 runtime data。
|
||||
|
||||
`config/settings.yaml` 只留喺 host;此檔已 gitignore,亦不會 build 入 Docker image。
|
||||
|
||||
### Docker Admin password
|
||||
|
||||
啟動前設定 password hash:
|
||||
|
||||
```bash
|
||||
export ADMIN_PASSWORD_HASH='pbkdf2_sha256$...'
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Windows PowerShell 可喺 shell 設定同一個 variable,或使用不提交嘅 local `.env` file。
|
||||
|
||||
### Port
|
||||
|
||||
Container 監聽 `8501`,host expose `8501`。
|
||||
@@ -0,0 +1,165 @@
|
||||
# LLM Specification — NBD Offer Pre-Item Master
|
||||
|
||||
## Design principle
|
||||
|
||||
LLM support is optional. The core upload, mapping preview, merge, and export path must remain usable without any model.
|
||||
|
||||
Runtime app code reads only project-owned config.
|
||||
|
||||
## Configuration
|
||||
|
||||
All app settings live in the single [config/settings.yaml](../config/settings.yaml) file.
|
||||
|
||||
The LLM config is profile-based so local small models and cloud large models use the same code path. Example:
|
||||
|
||||
```yaml
|
||||
llm:
|
||||
enabled: true
|
||||
active_profile: local
|
||||
profiles:
|
||||
local:
|
||||
label: "DGX Spark Local"
|
||||
base_url: "http://localhost:8000/v1"
|
||||
model: "local-model-name"
|
||||
api_key: "YOUR_LOCAL_API_KEY_OR_BLANK"
|
||||
timeout_seconds: 60
|
||||
temperature: 0.1
|
||||
ssl_verify: false
|
||||
stream_response: true
|
||||
mode: small
|
||||
max_sheet_rows: 80
|
||||
max_sheet_cols: 30
|
||||
max_candidates_per_sheet: 4
|
||||
sample_rows_per_candidate: 4
|
||||
max_mapping_columns: 40
|
||||
cloud:
|
||||
label: "Cloud AI"
|
||||
base_url: "https://api.deepseek.com/v1"
|
||||
model: "deepseek-chat"
|
||||
api_key: "YOUR_CLOUD_API_KEY_OR_BLANK"
|
||||
timeout_seconds: 90
|
||||
temperature: 0.1
|
||||
ssl_verify: false
|
||||
stream_response: true
|
||||
mode: large
|
||||
max_sheet_rows: 200
|
||||
max_sheet_cols: 60
|
||||
max_candidates_per_sheet: 10
|
||||
sample_rows_per_candidate: 8
|
||||
max_mapping_columns: 100
|
||||
```
|
||||
|
||||
Switch `active_profile` to use a different provider without changing application code.
|
||||
|
||||
## Resolver contract
|
||||
|
||||
`ConfigManager.resolve_llm_connection_config()` returns either an OpenAI-compatible request config or `None`.
|
||||
|
||||
Example success shape:
|
||||
|
||||
```python
|
||||
{
|
||||
"profile": "local",
|
||||
"label": "DGX Spark Local",
|
||||
"mode": "small",
|
||||
"api_key": "...",
|
||||
"base_url": "http://localhost:8000/v1",
|
||||
"model": "local-model-name",
|
||||
"timeout_seconds": 60,
|
||||
"temperature": 0.1,
|
||||
"ssl_verify": False,
|
||||
"stream_response": True,
|
||||
"budgets": {
|
||||
"max_sheet_rows": 80,
|
||||
"max_sheet_cols": 30,
|
||||
"max_candidates_per_sheet": 4,
|
||||
"sample_rows_per_candidate": 4,
|
||||
"max_mapping_columns": 40,
|
||||
},
|
||||
"source": "project",
|
||||
}
|
||||
```
|
||||
|
||||
Return `None` when `llm.enabled` is false, the active profile is missing, the active profile API key is missing, or base URL is missing.
|
||||
|
||||
## LLM stages
|
||||
|
||||
The app uses OpenAI-compatible chat completion requests through `services/llm_stages.py`. Prompts are built by `services/llm_prompts.py` so local/cloud profiles keep one JSON contract while using different context budgets. When `stream_response` is true, requests first include OpenAI-compatible `stream: true` and the UI receives live response/progress chunks for the trace panel. If the provider rejects streaming or returns no usable stream, the same request automatically falls back to a normal non-streaming completion before deterministic fallback is considered.
|
||||
|
||||
### Stage 1 — Read sheet structure
|
||||
|
||||
Input: sheet name and budgeted raw rows/columns from the active profile.
|
||||
|
||||
Output: header row, sheet type, columns/samples, and shared/form values.
|
||||
|
||||
### Stage 2 — Find cross-sheet links
|
||||
|
||||
Input: sheet summaries.
|
||||
|
||||
Output: merge groups, master sheet, links, match strategy, and confidence.
|
||||
|
||||
### Stage 3 — Map columns
|
||||
|
||||
Input: budgeted sheet columns, optional known mappings, and target schema fields from [config/db_schema.yaml](../config/db_schema.yaml).
|
||||
|
||||
Output: Excel column, SQL target column, confidence, reason, and optional conflicts.
|
||||
|
||||
## Prompt / response expectations
|
||||
|
||||
Prompts require valid JSON only, forbid invented sheet names/rows/columns/SQL targets, and tell the model to lower confidence instead of guessing.
|
||||
|
||||
Every main `LLMStages` response is semantically validated before it can affect the mapping blueprint:
|
||||
|
||||
- Stage 1 `header_row` must be within the real sheet row range.
|
||||
- Stage 1 `sheet_type` must be `detail`, `definition`, or `other`.
|
||||
- Stage 1 column headers must exist in the worksheet cells provided to the model.
|
||||
- Stage 2 sheet names and link columns must exist in Stage 1 summaries.
|
||||
- Stage 2 `match_strategy` must be one of the supported enum values.
|
||||
- Stage 3 Excel columns must exist in discovered columns.
|
||||
- Stage 3 SQL targets must exist in [config/db_schema.yaml](../config/db_schema.yaml).
|
||||
- Every confidence value must be between `0` and `1`.
|
||||
|
||||
If validation fails, the app sends one correction prompt containing the validation errors and the previous JSON. If the retry also fails, the stage returns `None`/`[]` and the analyzer falls back to deterministic known-format/fuzzy matching. The trace panel shows progress chunks and validation status, not private chain-of-thought.
|
||||
|
||||
Small local profiles should use smaller budgets; cloud profiles can use larger budgets, but both follow the same response contracts and validation rules.
|
||||
|
||||
## Deterministic fallback rule
|
||||
|
||||
The analyzer always builds a deterministic fallback result first.
|
||||
|
||||
If the workbook is a known format, the deterministic result is authoritative for summaries, groups, row model, and cross-sheet merge shape.
|
||||
|
||||
LLM output may add extra mappings, but must not rewrite the validated row model.
|
||||
|
||||
## Failure behavior
|
||||
|
||||
| Failure | Behavior |
|
||||
|---|---|
|
||||
| LLM disabled | deterministic/fuzzy path only |
|
||||
| Active profile missing | LLM unavailable status, deterministic/fuzzy path only |
|
||||
| API key missing | LLM unavailable status, deterministic/fuzzy path only |
|
||||
| HTTP error | stage returns `None`, analyzer falls back |
|
||||
| streaming unsupported | request automatically retries once as normal non-streaming completion; set `stream_response: false` to skip the streaming attempt entirely |
|
||||
| invalid JSON | stage returns `None`, analyzer falls back |
|
||||
| weak/no mapping | analyzer falls back |
|
||||
|
||||
## Security
|
||||
|
||||
- Leave the active profile `api_key` empty to keep optional LLM analysis unavailable.
|
||||
- Do not log raw API keys.
|
||||
- Do not put API keys in docs, tests, or screenshots.
|
||||
- Use fake keys that do not match real secret patterns in tests.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
python -m pytest -q
|
||||
```
|
||||
|
||||
Key LLM/config tests:
|
||||
|
||||
- `tests/test_config_manager.py::TestLLMConfig`
|
||||
- `tests/test_llm_prompts.py`
|
||||
- `tests/test_llm_stages.py`
|
||||
- `tests/test_llm_validation.py`
|
||||
- `tests/test_e2e.py`
|
||||
@@ -0,0 +1,165 @@
|
||||
# LLM 規格 — NBD Offer Pre-Item Master
|
||||
|
||||
## 設計原則
|
||||
|
||||
LLM support 係 optional。核心 upload、mapping preview、merge 同 export path 必須喺冇任何 model 情況下仍然可用。
|
||||
|
||||
Runtime app code 只可以讀 project-owned config。
|
||||
|
||||
## Configuration
|
||||
|
||||
所有 app settings 都放喺單一 [config/settings.yaml](../config/settings.yaml)。
|
||||
|
||||
LLM config 用 profile-based 設計,令 local 細 model 同 cloud 大 model 共用同一條 code path。Example:
|
||||
|
||||
```yaml
|
||||
llm:
|
||||
enabled: true
|
||||
active_profile: local
|
||||
profiles:
|
||||
local:
|
||||
label: "DGX Spark Local"
|
||||
base_url: "http://localhost:8000/v1"
|
||||
model: "local-model-name"
|
||||
api_key: "YOUR_LOCAL_API_KEY_OR_BLANK"
|
||||
timeout_seconds: 60
|
||||
temperature: 0.1
|
||||
ssl_verify: false
|
||||
stream_response: true
|
||||
mode: small
|
||||
max_sheet_rows: 80
|
||||
max_sheet_cols: 30
|
||||
max_candidates_per_sheet: 4
|
||||
sample_rows_per_candidate: 4
|
||||
max_mapping_columns: 40
|
||||
cloud:
|
||||
label: "Cloud AI"
|
||||
base_url: "https://api.deepseek.com/v1"
|
||||
model: "deepseek-chat"
|
||||
api_key: "YOUR_CLOUD_API_KEY_OR_BLANK"
|
||||
timeout_seconds: 90
|
||||
temperature: 0.1
|
||||
ssl_verify: false
|
||||
stream_response: true
|
||||
mode: large
|
||||
max_sheet_rows: 200
|
||||
max_sheet_cols: 60
|
||||
max_candidates_per_sheet: 10
|
||||
sample_rows_per_candidate: 8
|
||||
max_mapping_columns: 100
|
||||
```
|
||||
|
||||
切換 `active_profile` 就可以換 provider,唔需要改 application code。
|
||||
|
||||
## Resolver contract
|
||||
|
||||
`ConfigManager.resolve_llm_connection_config()` 會回傳 OpenAI-compatible request config 或 `None`。
|
||||
|
||||
成功 shape 例子:
|
||||
|
||||
```python
|
||||
{
|
||||
"profile": "local",
|
||||
"label": "DGX Spark Local",
|
||||
"mode": "small",
|
||||
"api_key": "...",
|
||||
"base_url": "http://localhost:8000/v1",
|
||||
"model": "local-model-name",
|
||||
"timeout_seconds": 60,
|
||||
"temperature": 0.1,
|
||||
"ssl_verify": False,
|
||||
"stream_response": True,
|
||||
"budgets": {
|
||||
"max_sheet_rows": 80,
|
||||
"max_sheet_cols": 30,
|
||||
"max_candidates_per_sheet": 4,
|
||||
"sample_rows_per_candidate": 4,
|
||||
"max_mapping_columns": 40,
|
||||
},
|
||||
"source": "project",
|
||||
}
|
||||
```
|
||||
|
||||
如果 `llm.enabled` 係 false、active profile 不存在、active profile API key 缺失或 base URL 缺失,就回傳 `None`。
|
||||
|
||||
## LLM stages
|
||||
|
||||
App 透過 `services/llm_stages.py` 使用 OpenAI-compatible chat completion requests。Prompt 由 `services/llm_prompts.py` 建立,令 local/cloud profiles 保持同一 JSON contract,但使用唔同 context budget。當 `stream_response` 係 true,request 會先用 OpenAI-compatible `stream: true`,UI 會即時收到 response/progress chunks 並顯示喺 trace panel。如果 provider 拒絕 streaming 或回傳唔到 usable stream,同一次 request 會自動改用普通 non-streaming completion,之後先考慮 deterministic fallback。
|
||||
|
||||
### Stage 1 — Read sheet structure
|
||||
|
||||
Input:sheet name 同 active profile budget 後嘅 raw rows/columns。
|
||||
|
||||
Output:header row、sheet type、columns/samples、shared/form values。
|
||||
|
||||
### Stage 2 — Find cross-sheet links
|
||||
|
||||
Input:sheet summaries。
|
||||
|
||||
Output:merge groups、master sheet、links、match strategy 同 confidence。
|
||||
|
||||
### Stage 3 — Map columns
|
||||
|
||||
Input:budget 後嘅 sheet columns、optional known mappings,同 [config/db_schema.yaml](../config/db_schema.yaml) 嘅 target schema fields。
|
||||
|
||||
Output:Excel column、SQL target column、confidence、reason 同 optional conflicts。
|
||||
|
||||
## Prompt / response expectations
|
||||
|
||||
Prompt 要求 valid JSON only,禁止模型 invent sheet names / rows / columns / SQL targets,並要求唔肯定時降低 confidence,而唔係亂估。
|
||||
|
||||
主流程每個 `LLMStages` response 都會先做 semantic validation,通過後先可以影響 mapping blueprint:
|
||||
|
||||
- Stage 1 `header_row` 必須喺真實 sheet row range 入面。
|
||||
- Stage 1 `sheet_type` 只可以係 `detail`、`definition` 或 `other`。
|
||||
- Stage 1 column headers 必須存在於傳俾模型嘅 worksheet cells。
|
||||
- Stage 2 sheet names 同 link columns 必須存在於 Stage 1 summaries。
|
||||
- Stage 2 `match_strategy` 必須係支援嘅 enum value。
|
||||
- Stage 3 Excel columns 必須存在於 discovered columns。
|
||||
- Stage 3 SQL targets 必須存在於 [config/db_schema.yaml](../config/db_schema.yaml)。
|
||||
- 所有 confidence value 必須介乎 `0` 至 `1`。
|
||||
|
||||
如果 validation 失敗,app 會發一次 correction prompt,附上 validation errors 同 previous JSON。Retry 都失敗嘅話,stage 會 return `None` / `[]`,analyzer 會 fallback 去 deterministic known-format / fuzzy matching。Trace panel 只顯示 progress chunks 同 validation status,不顯示 private chain-of-thought。
|
||||
|
||||
Local small profile 應用較細 budget;cloud profile 可用較大 budget,但兩者仍然跟同一 response contract 同 validation rules。
|
||||
|
||||
## Deterministic fallback rule
|
||||
|
||||
Analyzer 一定會先建立 deterministic fallback result。
|
||||
|
||||
如果 workbook 係已知格式,deterministic result 對 summaries、groups、row model 同 cross-sheet merge shape 係 authority。
|
||||
|
||||
LLM output 只可以補 extra mappings,不可以改寫已驗證 row model。
|
||||
|
||||
## Failure behavior
|
||||
|
||||
| Failure | 行為 |
|
||||
|---|---|
|
||||
| LLM disabled | 只用 deterministic/fuzzy path |
|
||||
| Active profile missing | 顯示 LLM unavailable,繼續 deterministic/fuzzy path |
|
||||
| API key missing | 顯示 LLM unavailable,繼續 deterministic/fuzzy path |
|
||||
| HTTP error | stage returns `None`,analyzer fallback |
|
||||
| streaming unsupported | request 自動 retry 一次普通 non-streaming completion;設 `stream_response: false` 可以完全略過 streaming attempt |
|
||||
| invalid JSON | stage returns `None`,analyzer fallback |
|
||||
| weak/no mapping | analyzer fallback |
|
||||
|
||||
## Security
|
||||
|
||||
- 保持 active profile `api_key` 留空時,optional LLM analysis 會 unavailable。
|
||||
- 不可 log raw API keys。
|
||||
- 不可將 API keys 寫入 docs、tests 或 screenshots。
|
||||
- Tests 入面 fake key 不應符合真 secret pattern。
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
python -m pytest -q
|
||||
```
|
||||
|
||||
主要 LLM/config tests:
|
||||
|
||||
- `tests/test_config_manager.py::TestLLMConfig`
|
||||
- `tests/test_llm_prompts.py`
|
||||
- `tests/test_llm_stages.py`
|
||||
- `tests/test_llm_validation.py`
|
||||
- `tests/test_e2e.py`
|
||||
@@ -0,0 +1,77 @@
|
||||
# Operations Runbook / 維運手冊
|
||||
|
||||
## English
|
||||
|
||||
### Local run
|
||||
|
||||
```bash
|
||||
python -m pip install -r requirements.txt
|
||||
python -m streamlit run app.py --server.port=8501
|
||||
```
|
||||
|
||||
### Daily operator checks
|
||||
|
||||
1. Open the app at `http://localhost:8501` or the LAN server URL.
|
||||
2. Upload a known workbook fixture or recent supplier workbook.
|
||||
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.
|
||||
|
||||
### Admin tasks
|
||||
|
||||
1. Unlock Admin from the sidebar.
|
||||
2. Review type configs, synonyms, AI settings, or Blueprint proposals.
|
||||
3. Re-enter Admin password before save/delete/merge actions.
|
||||
4. Keep `config/settings.yaml` local and untracked.
|
||||
5. Run tests after config/code changes:
|
||||
|
||||
```bash
|
||||
PYTHONPATH=. python -m pytest -q
|
||||
```
|
||||
|
||||
### Backups
|
||||
|
||||
Back up these paths before changes:
|
||||
|
||||
- `config/settings.yaml`
|
||||
- `config/types/`
|
||||
- `config/synonyms.yaml`
|
||||
- `data/tmp_blueprints/`
|
||||
|
||||
## 繁體中文
|
||||
|
||||
### Local 啟動
|
||||
|
||||
```bash
|
||||
python -m pip install -r requirements.txt
|
||||
python -m streamlit run app.py --server.port=8501
|
||||
```
|
||||
|
||||
### 日常檢查
|
||||
|
||||
1. 開 `http://localhost:8501` 或 LAN server URL。
|
||||
2. 上傳已知 fixture 或最新 supplier workbook。
|
||||
3. 檢查 Basic analysis confidence 同 preview rows。
|
||||
4. 匯出 `.xlsx`,確認 sheet name 係 `pre_item_master`。
|
||||
5. 如遇到有用新格式,提交 blueprint proposal,唔好由 Basic user 直接改 system config。
|
||||
|
||||
### Admin / 管理員工作
|
||||
|
||||
1. 由 sidebar unlock Admin。
|
||||
2. Review type configs、synonyms、AI settings 或 Blueprint proposals。
|
||||
3. save / delete / merge 前要重新輸入 Admin password。
|
||||
4. `config/settings.yaml` 只保留本機,不可 commit。
|
||||
5. 改 config / code 後跑 tests:
|
||||
|
||||
```bash
|
||||
PYTHONPATH=. python -m pytest -q
|
||||
```
|
||||
|
||||
### Backup
|
||||
|
||||
改動前建議 backup:
|
||||
|
||||
- `config/settings.yaml`
|
||||
- `config/types/`
|
||||
- `config/synonyms.yaml`
|
||||
- `data/tmp_blueprints/`
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
# Specification — NBD Offer Pre-Item Master
|
||||
|
||||
## English
|
||||
|
||||
## Purpose
|
||||
|
||||
Convert inconsistent supplier / offer Excel workbooks into a formal SQL-table-shaped Excel workbook for the `pre_item_master` table.
|
||||
|
||||
The application reduces manual column mapping, handles multi-sheet workbooks, preserves deterministic behavior for known formats, and provides optional LLM assistance for unfamiliar formats.
|
||||
|
||||
## Scope
|
||||
|
||||
### In scope
|
||||
|
||||
- `.xlsx` / `.xls` upload through Streamlit.
|
||||
- Workbook sheet preview.
|
||||
- Known-format recognition by fingerprint.
|
||||
- Workbook structure analysis.
|
||||
- Cross-sheet relation detection and row merging.
|
||||
- Column mapping to `pre_item_master` SQL columns.
|
||||
- Merged-row preview.
|
||||
- Formal one-sheet Excel export.
|
||||
- Optional blueprint proposal submission for Admin review.
|
||||
- English-only runtime UI, with bilingual project documentation (English + Traditional Chinese).
|
||||
- LLM configuration through the single `config/settings.yaml` file.
|
||||
|
||||
### Out of scope
|
||||
|
||||
- Direct database writes.
|
||||
- Multi-user authentication.
|
||||
- Background job scheduling.
|
||||
- OCR / PDF / image extraction.
|
||||
- Runtime dependency on non-project configuration.
|
||||
|
||||
## Functional requirements
|
||||
|
||||
### FR-1 Upload
|
||||
The user can upload one Excel workbook. Supported extensions are configured in [config/settings.yaml](../config/settings.yaml).
|
||||
|
||||
### FR-2 Sheet preview
|
||||
The upload page displays workbook sheets and allows the user to preview the first N rows per sheet.
|
||||
|
||||
### FR-3 Format recognition
|
||||
The system computes a workbook signature and matches it against stored fingerprints. Recognition thresholds are configured by `llm.fingerprint_auto_threshold` and `llm.fingerprint_suggest_threshold`.
|
||||
|
||||
### FR-4 Analysis blueprint
|
||||
The system produces an `AnalysisResult` containing `summaries`, `groups`, `mappings`, `engine`, and `warnings`.
|
||||
|
||||
### FR-5 Deterministic fallback
|
||||
If LLM is disabled, unavailable, or weak, the app falls back to known type config and fuzzy matching. For known formats, deterministic summaries/groups are authoritative even when LLM is online.
|
||||
|
||||
### FR-6 Merge preview
|
||||
The preview page shows merged rows after applying the confirmed blueprint. The product model is one output row per product/prize/item.
|
||||
|
||||
### FR-7 Export
|
||||
The export page generates an Excel workbook with exactly one sheet named `pre_item_master`, header names/order from [config/db_schema.yaml](../config/db_schema.yaml), and filename `pre_item_master_<timestamp>.xlsx`.
|
||||
|
||||
### FR-8 Submit mapping proposal
|
||||
Basic users can submit a confirmed mapping as a temporary blueprint proposal. Only an authenticated Admin can review and merge a proposal into the reusable type configuration.
|
||||
|
||||
### FR-9 Language support
|
||||
The runtime UI is English-only. Documentation is maintained in both English and Traditional Chinese.
|
||||
|
||||
### FR-10 LLM config portability
|
||||
Runtime app code reads only project-owned config/env. LLM settings must come from project config/env only.
|
||||
|
||||
## Non-functional requirements
|
||||
|
||||
- No secrets in tracked files.
|
||||
- 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.
|
||||
- Generated artifacts and temporary files must not be committed.
|
||||
|
||||
## Data contract
|
||||
|
||||
Target table: `pre_item_master`.
|
||||
|
||||
Authoritative export schema: [config/db_schema.yaml](../config/db_schema.yaml).
|
||||
|
||||
LLM target field list: [config/schema.yaml](../config/schema.yaml).
|
||||
|
||||
Key fields used to keep/drop rows:
|
||||
|
||||
- `generated_barcode`
|
||||
- `item_name_eng`
|
||||
- `item_name_jap`
|
||||
|
||||
## Main modules
|
||||
|
||||
| Module | Responsibility |
|
||||
|---|---|
|
||||
| `app.py` | Streamlit app shell, sidebar, routing, LLM 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 |
|
||||
| `ui/preview_page.py` | Row merge preview |
|
||||
| `ui/export_page.py` | Formal Excel export and blueprint proposal submission |
|
||||
| `services/config_manager.py` | Load the single settings.yaml config |
|
||||
| `services/workbook_analyzer.py` | Orchestrate LLM + deterministic fallback |
|
||||
| `services/llm_stages.py` | OpenAI-compatible chat-completion calls |
|
||||
| `services/merge_engine.py` | Cross-sheet row merge |
|
||||
| `services/export_service.py` | XLSX generation |
|
||||
|
||||
## Verification requirements
|
||||
|
||||
```bash
|
||||
python -m pytest -q
|
||||
```
|
||||
|
||||
Regression fixtures must export non-blank `pre_item_master` workbooks.
|
||||
|
||||
## 繁體中文
|
||||
|
||||
### 目的與範圍
|
||||
|
||||
本系統將供應商/offer Excel workbook 轉換成符合 `pre_item_master` SQL schema 的單一 Excel worksheet。支援 sheet 預覽、format fingerprint、deterministic mapping、跨 sheet merge、可選 AI 補充分析、輸出預覽與正式匯出;不包含直接寫入 database、多用戶 authentication、background jobs 或 OCR。
|
||||
|
||||
### 核心需求
|
||||
|
||||
1. 使用者上傳 `.xlsx`/`.xls`,選擇要分析的 sheets。
|
||||
2. 系統先以 fingerprint、type config 和 fuzzy matching 建立 deterministic `AnalysisResult`。
|
||||
3. AI 只在使用者主動要求時執行;AI 不可覆蓋已驗證的 known-format row model。
|
||||
4. 低於 configurable confidence threshold(預設 40%)時必須明確確認,但確認後可以繼續。
|
||||
5. Preview 必須以 `config/db_schema.yaml` 的 column order 顯示每個 product/prize/item 一行。
|
||||
6. Export 必須只包含 `pre_item_master` sheet,filename 為 `pre_item_master_<timestamp>.xlsx`。
|
||||
7. Basic user 只可提交 temporary blueprint proposal;只有已驗證 Admin 可以 review 並 merge 至 reusable type config。
|
||||
|
||||
### 非功能與資料契約
|
||||
|
||||
- tracked files 不可包含 secrets;LLM unavailable 時仍必須可以 export。
|
||||
- known formats 必須維持 deterministic export。
|
||||
- `config/db_schema.yaml` 是正式 export schema;`config/schema.yaml` 是 LLM target field list。
|
||||
- 每次提交前必須執行完整 `python -m pytest -q`,並確保 regression fixtures 匯出非空 workbook。
|
||||
@@ -0,0 +1,65 @@
|
||||
# Troubleshooting / 疑難排解
|
||||
|
||||
## English
|
||||
|
||||
### Upload cannot be read
|
||||
|
||||
- Confirm the file is `.xlsx` or `.xls`.
|
||||
- Open the workbook in Excel and save a clean copy.
|
||||
- Check Docker/container logs or Streamlit terminal output.
|
||||
|
||||
### Low confidence warning appears
|
||||
|
||||
- The detected type score is below `analysis.low_confidence_warning_threshold`.
|
||||
- Pick another workbook type and rerun Basic analysis, or confirm deliberately to continue review.
|
||||
- If this is a repeated real format, submit a blueprint proposal for Admin review.
|
||||
|
||||
### Admin cannot unlock
|
||||
|
||||
- Confirm `ADMIN_PASSWORD_HASH` or `security.admin_password_hash` is configured.
|
||||
- Regenerate hash with `python scripts/hash_admin_password.py`.
|
||||
- Restart the Streamlit process/container after changing env vars.
|
||||
|
||||
### Optional AI unavailable
|
||||
|
||||
- This is not a blocker for Basic export.
|
||||
- Check `llm.enabled`, `llm.active_profile`, `base_url`, `model`, `api_key`, and `ssl_verify` in `config/settings.yaml`.
|
||||
- `ssl_verify` defaults to `false` for internal endpoint compatibility. Turn it on only when the endpoint certificate is trusted on this machine.
|
||||
|
||||
### Docker app not reachable
|
||||
|
||||
- Confirm Docker is installed and running.
|
||||
- Confirm port mapping `8501:8501` in `docker-compose.yml`.
|
||||
- Run `docker compose logs -f nbd-preitemmaster`.
|
||||
|
||||
## 繁體中文
|
||||
|
||||
### Upload 讀唔到
|
||||
|
||||
- 確認檔案係 `.xlsx` 或 `.xls`。
|
||||
- 用 Excel 開啟並另存乾淨 copy。
|
||||
- 查看 Docker/container logs 或 Streamlit terminal output。
|
||||
|
||||
### 出現 low confidence warning
|
||||
|
||||
- 偵測分數低於 `analysis.low_confidence_warning_threshold`。
|
||||
- 可以揀另一個 workbook type 再 run Basic analysis,或者確認後繼續 review。
|
||||
- 如果係常見新格式,提交 blueprint proposal 俾 Admin review。
|
||||
|
||||
### Admin unlock 失敗
|
||||
|
||||
- 確認有設定 `ADMIN_PASSWORD_HASH` 或 `security.admin_password_hash`。
|
||||
- 用 `python scripts/hash_admin_password.py` 重新產生 hash。
|
||||
- 改 env var 後要 restart Streamlit process/container。
|
||||
|
||||
### Optional AI unavailable
|
||||
|
||||
- 呢個唔會阻止 Basic export。
|
||||
- 檢查 `config/settings.yaml` 入面 `llm.enabled`、`llm.active_profile`、`base_url`、`model`、`api_key`、`ssl_verify`。
|
||||
- `ssl_verify` 預設係 `false`,方便內部 endpoint / self-signed certificate。只有 endpoint certificate 喺呢部機可信時先開返。
|
||||
|
||||
### Docker app 開唔到
|
||||
|
||||
- 確認 Docker 已安裝並運行。
|
||||
- 確認 `docker-compose.yml` 有 `8501:8501` port mapping。
|
||||
- 執行 `docker compose logs -f nbd-preitemmaster` 睇 logs。
|
||||
@@ -0,0 +1,177 @@
|
||||
# Workflow — NBD Offer Pre-Item Master
|
||||
|
||||
## English
|
||||
|
||||
## Operator workflow
|
||||
|
||||
### 1. Start the app
|
||||
|
||||
On Windows, use the project launcher so Streamlit runs inside the local `.venv` instead of a global Python install:
|
||||
|
||||
```bat
|
||||
run_app.bat
|
||||
```
|
||||
|
||||
Manual equivalent:
|
||||
|
||||
```bash
|
||||
PYTHONPATH= .venv/Scripts/python.exe -m streamlit run app.py
|
||||
```
|
||||
|
||||
Open the Streamlit URL.
|
||||
|
||||
### 2. Upload workbook and preview extracted data
|
||||
|
||||
1. Click **Choose an Excel file**.
|
||||
2. Select an `.xlsx` or `.xls` workbook.
|
||||
3. Review the extracted sheet preview.
|
||||
|
||||
The sidebar and page header show the five operator-facing steps:
|
||||
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
- structure summary;
|
||||
- deterministic cross-sheet join rules;
|
||||
- Excel source column/field → SQL target mapping.
|
||||
|
||||
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
|
||||
|
||||
The AI analysis run page is intentionally minimal.
|
||||
|
||||
- Click **Run AI analysis** only when a model-assisted review is needed.
|
||||
- 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.
|
||||
- When the run completes, the app automatically moves to **AI summary**.
|
||||
- Click **Use current analysis → Preview** to skip AI and continue with the basic result.
|
||||
|
||||
LLM/AI analysis is never triggered automatically by entering the page. Hidden/private chain-of-thought is not requested or exposed; the textarea shows the prompt plus visible streamed model output.
|
||||
|
||||
### 5. AI analysis summary page
|
||||
|
||||
The AI summary page contains the review details that should not clutter the run page:
|
||||
|
||||
- **Model response** — model-visible JSON response converted into review tables, with raw JSON available in an expander.
|
||||
- **Parsed validation** — validation status, errors, and normalized parsed JSON paths as tables.
|
||||
- **Final blueprint** — engine/sheet/link/mapping metrics plus a detailed AI Mapping Report explaining chosen sources, evidence, confidence, and reasons.
|
||||
- **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
|
||||
|
||||
The Preview page displays rows in the final `pre_item_master` output column order. This lets the user inspect the export result before downloading.
|
||||
|
||||
### 7. Export
|
||||
|
||||
The Export page creates:
|
||||
|
||||
```text
|
||||
pre_item_master_<timestamp>.xlsx
|
||||
```
|
||||
|
||||
The workbook contains one sheet:
|
||||
|
||||
```text
|
||||
pre_item_master
|
||||
```
|
||||
|
||||
### 8. Optional save mapping
|
||||
|
||||
If the workbook format should be reused, open **Optional: submit Match Blueprint proposal**, enter a format name, preview the YAML, and submit it. A verified Admin must review and merge the proposal before it changes reusable type configuration.
|
||||
|
||||
## Developer workflow
|
||||
|
||||
### Install dependencies
|
||||
|
||||
Prefer `run_app.bat` for normal Windows operation. It creates/uses `.venv`, clears `PYTHONPATH`, installs requirements, and starts Streamlit.
|
||||
|
||||
For manual setup, use a project-local virtualenv so the app can track the latest stable package set without conflicting with global tools. If your parent shell exports `PYTHONPATH`, clear it while running the project venv commands so imports come from `.venv` first.
|
||||
|
||||
```bash
|
||||
python -m venv .venv
|
||||
PYTHONPATH= .venv/Scripts/python.exe -m pip install --upgrade pip
|
||||
PYTHONPATH= .venv/Scripts/python.exe -m pip install --upgrade -r requirements.txt
|
||||
```
|
||||
|
||||
The requirements file uses the latest verified stable release as each minimum version plus a next-major upper bound, for example `streamlit>=1.59.0,<2`. This accepts future patch/minor fixes while avoiding surprise breaking major upgrades.
|
||||
|
||||
### Configure optional LLM
|
||||
|
||||
Edit `config/settings.yaml` directly. Paste the API key into the active profile `api_key`, or leave it blank to keep optional LLM analysis disabled / unavailable.
|
||||
|
||||
### Run tests
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
## Failure and fallback behavior
|
||||
|
||||
| Situation | Expected behavior |
|
||||
|---|---|
|
||||
| LLM disabled | Use known type config / fuzzy matching |
|
||||
| LLM unavailable | Show fallback status, 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 |
|
||||
| Export error | Show the error and do not produce a misleading file |
|
||||
|
||||
## Related files
|
||||
|
||||
- App shell: [app.py](../app.py)
|
||||
- Upload page: [ui/upload_page.py](../ui/upload_page.py)
|
||||
- Basic analysis page: [ui/confirm_page.py](../ui/confirm_page.py)
|
||||
- AI analysis page: [ui/ai_analysis_page.py](../ui/ai_analysis_page.py)
|
||||
- Preview page: [ui/preview_page.py](../ui/preview_page.py)
|
||||
- Export page: [ui/export_page.py](../ui/export_page.py)
|
||||
- Analyzer: [services/workbook_analyzer.py](../services/workbook_analyzer.py)
|
||||
- Export service: [services/export_service.py](../services/export_service.py)
|
||||
|
||||
## 繁體中文
|
||||
|
||||
### 操作流程
|
||||
|
||||
1. 用 `run_app.bat` 啟動,或在 project `.venv` 執行 `python -m streamlit run app.py`。
|
||||
2. 在 **Upload** 上傳 workbook、選擇要分析的 sheets,並確認偵測到的 Type。
|
||||
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。
|
||||
7. 在 **Export** 下載 `pre_item_master_<timestamp>.xlsx`。Workbook 只包含 `pre_item_master` sheet。
|
||||
8. 如格式需要重用,Basic user 可提交 temporary Match Blueprint proposal;只有已驗證 Admin 可 review、merge 和 archive proposal。
|
||||
|
||||
### 開發與 fallback 規則
|
||||
|
||||
- `ExcelParser → Fingerprint → WorkbookAnalyzer → MergeEngine → ExportService` 是唯一正式 pipeline。
|
||||
- known format 的 deterministic summaries、groups 和 mappings 優先;AI 只補足有效 gaps。
|
||||
- streaming 不支援時自動改用 non-streaming request;export error 時不可產生誤導檔案。
|
||||
- 修改後執行 `python -m pytest -q`,並驗證兩個 Kuji fixtures 的 row count、57 columns 和正式 sheet contract。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Historical AI analysis benchmarks
|
||||
|
||||
These measurements record the July 2026 tuning work against the Kuji reference workbooks. They are historical evidence, not a current performance SLA.
|
||||
|
||||
| Run | AI calls | Validation failures | Elapsed | Result |
|
||||
|---|---:|---:|---:|---|
|
||||
| Before tuning | 6 prompts | 2 Stage 1 failures | 308.78s | hybrid, 19 mappings |
|
||||
| Candidate hints and salvage validation | 4 prompts | 0 fatal failures | 190.12s | hybrid, 17 mappings |
|
||||
| Known-type fast path | 1 prompt | 0 fatal failures | 57.16s | hybrid, 17 mappings |
|
||||
| 85% AI-addition guard | 1 prompt per sample | 0 fatal failures | 67.81–92.70s | hybrid, 14 mappings; all deterministic mappings preserved |
|
||||
|
||||
The original failure mode was open-ended Stage 1 output containing blank or invented headers. The resulting production policy is documented in [AI_ANALYSIS_TUNING.md](../AI_ANALYSIS_TUNING.md): deterministic known-type structure remains authoritative and AI is a bounded, validated gap-fill step.
|
||||
|
||||
## 歷史說明
|
||||
|
||||
以上數據記錄 2026 年 7 月以 Kuji sample 進行的調校結果,只作歷史證據,不代表現時 performance SLA。主要改善是避免 AI 重新推斷 deterministic parser 已知的 structure,並以 confidence guard 和 semantic validation 限制 AI additions。
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,537 +0,0 @@
|
||||
# Dev Spec: Excel Upload WebApp with Intelligent Fuzzy Matching
|
||||
|
||||
**Date:** 2026-06-30
|
||||
**Status:** Approved
|
||||
**Project:** NBD Offer Pre-Item Master
|
||||
|
||||
---
|
||||
|
||||
## 1. Overview
|
||||
|
||||
A Streamlit WebApp that allows users to upload Excel files with unpredictable formats. The system uses fuzzy matching (backed by a configurable synonym dictionary) to map source columns to a target `pre_item_master` database schema. Each row is validated against required key fields; rows missing key data are flagged for review. Users can review, adjust mappings, and override drop decisions before exporting to Excel.
|
||||
|
||||
### 1.1 Problem Statement
|
||||
|
||||
Source Excel files come from 7+ different categories (KUJI BNA, KUJI TW, BCL SAP, CANDY, PRIZE, TOY, etc.) with:
|
||||
- Different column header names across sources (e.g., "SALES JAN CODE" vs "JAN_Code" vs "Material_No" all map to `generated_barcode`)
|
||||
- Mixed languages (Japanese, English, Chinese)
|
||||
- Non-tabular layouts: some data is sheet-level (form data), some is row-level (table data)
|
||||
- Data spread across multiple sheets that need combining
|
||||
|
||||
### 1.2 Key Design Decisions (from user interview)
|
||||
|
||||
| Decision | Choice |
|
||||
|---|---|
|
||||
| User model | Internal tool, no auth, no team separation |
|
||||
| Tech stack | Python Streamlit |
|
||||
| Row validation | Flag if barcode unidentifiable; user can override |
|
||||
| Fuzzy matching | Auto-match highest score + manual override |
|
||||
| Type system | Hybrid — type provides bias, fuzzy fallback when unsure |
|
||||
| Config management | File-based (YAML) + UI admin panel |
|
||||
| Multi-sheet | Support data scattered across sheets, combine on form fields |
|
||||
| Export | Default .xlsx with UTF-8 handling |
|
||||
| Deployment | Local (`streamlit run`) initially |
|
||||
|
||||
---
|
||||
|
||||
## 2. Architecture
|
||||
|
||||
### 2.1 Layer Structure
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ UI Layer (Streamlit) │
|
||||
│ upload_page │ structure_review │ ... │
|
||||
└──────────────────┬──────────────────────┘
|
||||
│
|
||||
┌──────────────────▼──────────────────────┐
|
||||
│ Service Layer (Python) │
|
||||
│ config_manager │ excel_parser │
|
||||
│ fuzzy_matcher │ data_processor │
|
||||
│ export_service │
|
||||
└──────────────────┬──────────────────────┘
|
||||
│
|
||||
┌──────────────────▼──────────────────────┐
|
||||
│ Config Layer (YAML Files) │
|
||||
│ db_schema.yaml │ types/*.yaml │
|
||||
│ synonyms.yaml │ settings.yaml │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 2.2 Directory Structure
|
||||
|
||||
```
|
||||
project_root/
|
||||
├── app.py # Entry point, Streamlit page routing
|
||||
├── config/
|
||||
│ ├── db_schema.yaml # Auto-generated from pre_item_master.sql
|
||||
│ ├── synonyms.yaml # Synonym dictionary for fuzzy matching
|
||||
│ ├── settings.yaml # App-level settings (thresholds, etc.)
|
||||
│ └── types/ # One YAML per source type
|
||||
│ ├── kuji_bna.yaml
|
||||
│ ├── kuji_tw.yaml
|
||||
│ ├── bcl_sap.yaml
|
||||
│ ├── candy.yaml
|
||||
│ ├── prize.yaml
|
||||
│ ├── kuji.yaml
|
||||
│ └── toy.yaml
|
||||
├── services/
|
||||
│ ├── __init__.py
|
||||
│ ├── config_manager.py # Load/save/import config
|
||||
│ ├── excel_parser.py # Read Excel, detect structure
|
||||
│ ├── fuzzy_matcher.py # Column/synonym matching engine
|
||||
│ ├── data_processor.py # Transform, validate, combine
|
||||
│ └── export_service.py # Generate output .xlsx
|
||||
├── ui/
|
||||
│ ├── __init__.py
|
||||
│ ├── upload_page.py # File upload + type selection
|
||||
│ ├── structure_review.py # Step 1: review detected structure
|
||||
│ ├── mapping_review.py # Step 2: review column mapping
|
||||
│ ├── data_preview.py # Step 3: preview + drop/recover
|
||||
│ ├── export_page.py # Step 4: download
|
||||
│ └── admin_page.py # Type config + synonym management
|
||||
├── utils/
|
||||
│ ├── __init__.py
|
||||
│ └── helpers.py # Shared utilities
|
||||
├── ref_files/ # Reference materials (existing)
|
||||
│ ├── kuji_bntw.xlsx
|
||||
│ ├── nbd_column_mapping.xlsx
|
||||
│ └── pre_item_master.sql
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Config Schema
|
||||
|
||||
### 3.1 `config/db_schema.yaml`
|
||||
|
||||
Generated from `pre_item_master.sql`. Lists all target database columns.
|
||||
|
||||
```yaml
|
||||
table: pre_item_master
|
||||
columns:
|
||||
- name: generated_barcode
|
||||
type: varchar(50)
|
||||
nullable: true
|
||||
description: "GL JAN / SALES JAN CODE"
|
||||
is_key: true
|
||||
- name: sap
|
||||
type: varchar(50)
|
||||
nullable: true
|
||||
description: "SAP #"
|
||||
is_key: true
|
||||
- name: item_name_eng
|
||||
type: text
|
||||
nullable: true
|
||||
description: "Item Name ENG"
|
||||
is_key: false
|
||||
# ... all 55 columns
|
||||
```
|
||||
|
||||
### 3.2 `config/types/<type_id>.yaml`
|
||||
|
||||
One file per source type. Contains structure hints, column mapping, required field definitions, form field patterns, and multi-sheet combine rules.
|
||||
|
||||
```yaml
|
||||
type_id: kuji_bna
|
||||
label: "KUJI BNA"
|
||||
category: kuji
|
||||
|
||||
structure:
|
||||
header_pattern:
|
||||
keywords: ["GL品番", "商品名", "SALES JAN", "入数", "納品", "原産国"]
|
||||
strategy: max_keyword_match
|
||||
data_start_offset: 1 # rows after header
|
||||
|
||||
mapping:
|
||||
- source_patterns: ["SALES JAN CODE", "JAN CODE", "JAN_Code"]
|
||||
target: generated_barcode
|
||||
fuzzy_weight: 1.0
|
||||
required: true
|
||||
description: "PK — row dropped if missing"
|
||||
|
||||
- source_patterns: ["商品名/英語", "Material_Offical_Desc_EN", "ITEM NAME"]
|
||||
target: item_name_eng
|
||||
fuzzy_weight: 0.9
|
||||
required: false
|
||||
|
||||
- source_patterns: ["商品名/日本語", "Material_Offical_Desc_JP"]
|
||||
target: item_name_jap
|
||||
fuzzy_weight: 0.9
|
||||
required: false
|
||||
|
||||
- source_patterns: ["Japan Launch Date", "発売月", "Release_Date"]
|
||||
target: jp_bai_launch
|
||||
fuzzy_weight: 0.8
|
||||
required: false
|
||||
# ... all mappings
|
||||
|
||||
form_fields:
|
||||
- source_patterns: ["SALES JAN CODE", "JAN CODE"]
|
||||
target: generated_barcode
|
||||
propagate: true
|
||||
- source_patterns: ["Japan Launch Date", "発売月"]
|
||||
target: jp_bai_launch
|
||||
propagate: true
|
||||
|
||||
sheet_combine:
|
||||
strategy: join_on_form_fields
|
||||
```
|
||||
|
||||
### 3.3 `config/synonyms.yaml`
|
||||
|
||||
Auto-generated from existing mapping + accumulates new synonyms from user corrections.
|
||||
|
||||
```yaml
|
||||
synonyms:
|
||||
generated_barcode:
|
||||
- "SALES JAN CODE"
|
||||
- "JAN CODE"
|
||||
- "JAN_Code"
|
||||
- "GL JAN"
|
||||
- "Material_No"
|
||||
- "barcode"
|
||||
- "bar code"
|
||||
- "ean"
|
||||
item_name_eng:
|
||||
- "ITEM NAME"
|
||||
- "Product contents"
|
||||
- "Material_Offical_Desc_EN"
|
||||
- "Item Name"
|
||||
- "product name"
|
||||
- "description"
|
||||
- "goods name"
|
||||
item_name_jap:
|
||||
- "ITEM NAME(JPN)"
|
||||
- "商品名/日本語"
|
||||
- "Material_Offical_Desc_JP"
|
||||
- "商品名"
|
||||
- "和名"
|
||||
- "日本語名"
|
||||
jp_bai_launch:
|
||||
- "Japan Launch Date"
|
||||
- "発売月"
|
||||
- "Release_Date"
|
||||
- "Launch"
|
||||
- "launch date"
|
||||
- "release date"
|
||||
- "発売日"
|
||||
- "上市日期"
|
||||
# ... all target fields
|
||||
```
|
||||
|
||||
### 3.4 `config/settings.yaml`
|
||||
|
||||
```yaml
|
||||
app:
|
||||
name: "NBD Offer Pre-Item Master"
|
||||
version: "1.0.0"
|
||||
default_export_format: xlsx
|
||||
|
||||
fuzzy:
|
||||
default_threshold: 75 # minimum similarity score (0-100) for auto-match
|
||||
algorithm: token_sort_ratio # primary algorithm
|
||||
fallback_algorithm: partial_ratio
|
||||
keyword_match_min: 2 # min keyword hits for Pass 1 lock-in
|
||||
|
||||
file:
|
||||
max_upload_size_mb: 200
|
||||
supported_formats: [.xlsx, .xls]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Data Flow & Processing Pipeline
|
||||
|
||||
### 4.1 Pipeline Overview
|
||||
|
||||
```
|
||||
Upload Excel + Select Type
|
||||
│
|
||||
▼
|
||||
┌─ Stage 1: Structure Detection ─┐
|
||||
│ • Detect header row per sheet │
|
||||
│ • Detect data region │
|
||||
│ • Detect form fields │
|
||||
│ • User reviews/adjusts │
|
||||
└───────────────┬────────────────┘
|
||||
▼
|
||||
┌─ Stage 2: Column Mapping ──────┐
|
||||
│ • Pass 1: Keyword pre-match │
|
||||
│ • Pass 2: Synonym fuzzy match │
|
||||
│ • Pass 3: Target field fuzzy │
|
||||
│ • User reviews/adjusts │
|
||||
└───────────────┬────────────────┘
|
||||
▼
|
||||
┌─ Stage 3: Data Preview ────────┐
|
||||
│ • Combine multi-sheet data │
|
||||
│ • Transform to target schema │
|
||||
│ • Validate required fields │
|
||||
│ • Flag dropped rows │
|
||||
│ • User previews/overrides │
|
||||
└───────────────┬────────────────┘
|
||||
▼
|
||||
┌─ Stage 4: Export ──────────────┐
|
||||
│ • Generate .xlsx output │
|
||||
│ • Include dropped row report │
|
||||
│ • Download │
|
||||
└────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 4.2 Stage 1: Structure Detection
|
||||
|
||||
**Detection algorithm:**
|
||||
1. For each sheet, iterate through first N rows (configurable, default 30)
|
||||
2. For each row, count how many cells contain non-empty text AND how many of those match any keyword from the selected type's `structure.header_pattern.keywords` list
|
||||
3. Row with highest keyword match count = header row
|
||||
4. Data starts at `header_row + structure.data_start_offset`
|
||||
5. Scan remaining cells outside data region for single-value cells matching `form_fields.source_patterns` → these are form fields
|
||||
|
||||
**User controls:**
|
||||
- Select which sheets to include in processing
|
||||
- Override header row (manual row number input)
|
||||
- Mark/unmark cells as form fields via checkbox
|
||||
- Define data region boundaries (start row, end row, start col, end col)
|
||||
- Preview of header + first 5 data rows shown
|
||||
|
||||
### 4.3 Stage 2: Column Mapping
|
||||
|
||||
**Three-pass matching:**
|
||||
|
||||
| Pass | Method | Match Condition | Fallback |
|
||||
|------|--------|-----------------|----------|
|
||||
| 1: Keyword | Intersection of source header tokens with each target's `source_patterns` tokenized set | ≥ `keyword_match_min` (default 2) tokens intersect | → Pass 2 |
|
||||
| 2: Synonym | `rapidfuzz.token_sort_ratio(source_header, each_synonym)` across all synonyms | Best score ≥ threshold (default 75) | → Pass 3 |
|
||||
| 3: Target | `rapidfuzz.token_sort_ratio(source_header, target_column_name)` against DB column names | Best score ≥ threshold | → Unmatched |
|
||||
|
||||
**Tie-breaking:**
|
||||
- Two source columns → same target: higher score wins
|
||||
- One source column → two targets: show both in UI dropdown, let user pick
|
||||
|
||||
**User controls:**
|
||||
- Dropdown per source column to change target mapping
|
||||
- Confidence score color: green ≥85%, yellow 75–84%, red <75%
|
||||
- "Unmatched targets" section showing DB columns with no source mapped
|
||||
- "Save as Type Default" checkbox to persist mapping back to config YAML
|
||||
|
||||
### 4.4 Stage 3: Data Preview & Validation
|
||||
|
||||
**Multi-sheet combining:**
|
||||
- Form field values from all selected sheets are collected
|
||||
- If multiple sheets provide the same form field (e.g., two sheets both have `SALES JAN CODE`), values must match; conflict → user prompt
|
||||
- Each sheet's data rows are augmented with all collected form field values before combination
|
||||
|
||||
**Row validation:**
|
||||
- For each row, check all mappings where `required: true`
|
||||
- If any required target field has an empty/null value after transformation → flag row
|
||||
- Primary required field: `generated_barcode`
|
||||
- Dropped rows are stored separately with a `drop_reason` field
|
||||
|
||||
**User controls:**
|
||||
- Two tabs: "Preview" (good data) and "Dropped Rows"
|
||||
- Dropped rows table: columns = [Row#, Sheet, Drop Reason, Source Data preview]
|
||||
- "Restore" button per dropped row
|
||||
- Editable cells in preview (correct values inline)
|
||||
- Summary stats: "X rows processed | Y flagged | Z will be exported"
|
||||
- Search/filter bar on preview
|
||||
|
||||
### 4.5 Stage 4: Export
|
||||
|
||||
**Output Excel structure:**
|
||||
- Sheet 1: "Exported Data" — all kept rows in target schema column order
|
||||
- Sheet 2: "Dropped Rows" — flagged rows with drop reason column
|
||||
- Auto-formatted: date columns as dates, numeric columns as numbers, column widths auto-fit
|
||||
|
||||
---
|
||||
|
||||
## 5. UI Pages
|
||||
|
||||
### 5.1 Navigation
|
||||
|
||||
Streamlit multi-page with sidebar:
|
||||
```
|
||||
🏠 Home / Upload
|
||||
🔍 Step 1: Structure Review
|
||||
🔗 Step 2: Column Mapping
|
||||
👁️ Step 3: Data Preview & Validate
|
||||
📥 Step 4: Export
|
||||
───────
|
||||
⚙️ Admin: Type Config
|
||||
📖 Admin: Synonym Dictionary
|
||||
```
|
||||
|
||||
Navigation is **sequential** — user can go back to previous steps but cannot skip ahead. Step completion gates are enforced (e.g., cannot go to Step 2 until Structure is confirmed). Session state tracks progress.
|
||||
|
||||
### 5.2 Page Details
|
||||
|
||||
**🏠 Upload Page:**
|
||||
- File uploader (drag-and-drop or browse)
|
||||
- Type selector dropdown: "KUJI BNA", "KUJI TW", "BCL SAP", "CANDY", "PRIZE", "KUJI", "TOY", "Auto-Detect"
|
||||
- "Auto-Detect" runs fuzzy matching against ALL type configs in parallel; the type with the highest aggregate keyword match score across all sheets wins. This is ideal when the user doesn't know the exact type or when a new variant is close to an existing type.
|
||||
- After upload: sheet preview cards (sheet name, row x col dimensions, first 5 rows preview)
|
||||
- "Start Processing" button → triggers Stage 1, navigates to Step 1
|
||||
|
||||
**🔍 Step 1: Structure Review:**
|
||||
- Per-sheet expandable cards
|
||||
- Preview table with detected header row highlighted
|
||||
- Detected form fields listed with extracted values
|
||||
- Actions: change header row (number input), toggle form field, define data region
|
||||
- Sheet include/exclude toggles
|
||||
- "Confirm Structure → Next"
|
||||
|
||||
**🔗 Step 2: Column Mapping:**
|
||||
- Main mapping table: Source Column | → Target DB Column (dropdown) | Confidence (badge)
|
||||
- Unmatched targets highlight section
|
||||
- Form field mapping sub-table
|
||||
- "Save as Type Default" checkbox
|
||||
- Button: "Confirm Mapping → Next"
|
||||
|
||||
**👁️ Step 3: Data Preview:**
|
||||
- Tab 1 "Preview": scrollable/filterable data table, missing cells in yellow
|
||||
- Tab 2 "Dropped Rows": table with restore buttons
|
||||
- Summary bar at top
|
||||
- "Proceed to Export" button
|
||||
|
||||
**📥 Step 4: Export:**
|
||||
- Download button for .xlsx (styled)
|
||||
- Optional: "Also export Dropped Row Report separately"
|
||||
- Summary card (rows processed, exported, dropped)
|
||||
- "Start New Upload" button (resets session)
|
||||
|
||||
**⚙️ Admin: Type Config:**
|
||||
- List existing types with edit/delete
|
||||
- Create new type (form: type_id, label, category)
|
||||
- Import mapping from Excel (upload existing mapping file → populate YAML)
|
||||
- Edit mapping rules (add/remove/reorder source_patterns per target field)
|
||||
- Edit structure detection keywords
|
||||
- Changes write back to `config/types/*.yaml`
|
||||
|
||||
**📖 Admin: Synonym Dictionary:**
|
||||
- Grouped by target field
|
||||
- View all synonyms per field
|
||||
- Add/remove synonyms
|
||||
- Merge duplicate entries
|
||||
- Search across all synonyms
|
||||
- Changes write back to `config/synonyms.yaml`
|
||||
|
||||
---
|
||||
|
||||
## 6. Fuzzy Matching Engine Detail
|
||||
|
||||
### 6.1 Core Library
|
||||
|
||||
`rapidfuzz` (MIT license, ~10x faster than `fuzzywuzzy`)
|
||||
|
||||
### 6.2 Algorithms Used
|
||||
|
||||
| Algorithm | Use Case | Description |
|
||||
|-----------|----------|-------------|
|
||||
| `token_sort_ratio` | Primary | Tokenizes, sorts alphabetically, compares — good for word-order differences like "JAN CODE SALES" vs "SALES JAN CODE" |
|
||||
| `partial_ratio` | Fallback | Best partial substring match — good when one string is embedded in another, e.g., "商品名/日本語" contains cues |
|
||||
| `token_set_ratio` | Synonym comparison | Ignores duplicate words, good for comparing against longer synonym lists |
|
||||
|
||||
### 6.3 Scoring Formula
|
||||
|
||||
```
|
||||
For each unmatched source column header H:
|
||||
candidates = []
|
||||
for each target_field T in db_schema:
|
||||
for each pattern P in T.source_patterns + synonyms[T]:
|
||||
raw_score = max(token_sort_ratio(H, P), partial_ratio(H, P))
|
||||
weighted_score = raw_score * T.fuzzy_weight (default 1.0 if not set)
|
||||
candidates.append({
|
||||
target: T.name,
|
||||
score: weighted_score,
|
||||
matched_pattern: P
|
||||
})
|
||||
best = argmax(candidates, key=score)
|
||||
if best.score >= threshold → auto-match
|
||||
else → present top-3 candidates to user
|
||||
```
|
||||
|
||||
`fuzzy_weight` biases matching toward important fields (e.g., `generated_barcode` at 1.0) and away from low-priority ones (e.g., `remark_item4` at 0.5). It acts as a multiplier on the raw fuzzy score before comparison.
|
||||
|
||||
### 6.4 Synonym Auto-Learning
|
||||
|
||||
When a user manually maps a source column to a target field that has no existing synonym match:
|
||||
1. System stores the mapping in session state
|
||||
2. On export, prompts: "Save new synonyms from this session to config?" [Yes] [No]
|
||||
3. If Yes: appends new source column names to `config/synonyms.yaml` under the correct target field
|
||||
4. Existing synonyms are preserved (append-only, no auto-delete)
|
||||
|
||||
---
|
||||
|
||||
## 7. Error Handling
|
||||
|
||||
### 7.1 File-Level Errors
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| Empty Excel (no sheets) | Error message: "File contains no sheets" |
|
||||
| Password-protected | Catch `openpyxl` exception → "File is password-protected. Please remove protection and re-upload." |
|
||||
| Corrupted file | Catch `BadZipFile` → "File appears to be corrupted or not a valid Excel file." |
|
||||
| Unsupported format | Catch on upload → "Only .xlsx and .xls files are supported." |
|
||||
| File too large | Check file size before reading → "File exceeds maximum size of X MB." |
|
||||
|
||||
### 7.2 Processing-Level Errors
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| No header detected | Show warning + fallback to manual mode (user selects header row) |
|
||||
| No columns matched | Show all as unmatched, pre-fill nothing, prompt user to manually map |
|
||||
| All rows dropped (all missing barcode) | Warning: "All rows flagged — no data will be exported. Please review required field mappings." |
|
||||
| Multi-sheet form field conflict | Show conflict details + radio buttons to pick which sheet's value to use |
|
||||
| Duplicate barcodes detected | Flag in preview, user decides: keep first / keep all as separate rows / merge |
|
||||
|
||||
### 7.3 Export Errors
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| Write permission denied | Show error path + suggest checking file permissions |
|
||||
| Memory error (large dataset) | Suggest splitting file or increasing system memory |
|
||||
|
||||
### 7.4 Session State
|
||||
|
||||
- All processing state stored in `st.session_state`
|
||||
- "Start New Upload" clears all state
|
||||
- Unsaved mapping changes trigger prompt: "You have unsaved mapping changes. Discard?" [Discard] [Go Back]
|
||||
|
||||
---
|
||||
|
||||
## 8. Dependencies
|
||||
|
||||
```
|
||||
streamlit>=1.28
|
||||
pandas>=2.0
|
||||
openpyxl>=3.1
|
||||
rapidfuzz>=3.0
|
||||
pyyaml>=6.0
|
||||
python-dateutil>=2.8
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Out of Scope (for v1)
|
||||
|
||||
- Authentication / authorization
|
||||
- Database persistence (reading/writing directly to MySQL)
|
||||
- Multi-user concurrent access
|
||||
- Email notifications
|
||||
- Scheduled/batch processing
|
||||
- API endpoints
|
||||
- Docker/container deployment (keep as local `streamlit run` initially)
|
||||
- Automatic barcode generation for missing rows
|
||||
|
||||
---
|
||||
|
||||
## 10. Initial Setup Tasks
|
||||
|
||||
These will be detailed in the implementation plan, but high-level:
|
||||
|
||||
1. Convert `nbd_column_mapping.xlsx` → `config/types/*.yaml` (one per type)
|
||||
2. Convert `pre_item_master.sql` → `config/db_schema.yaml`
|
||||
3. Bootstrap `config/synonyms.yaml` from existing mapping column names
|
||||
4. Build service layer (config_manager → excel_parser → fuzzy_matcher → data_processor → export_service)
|
||||
5. Build UI pages
|
||||
6. End-to-end test with `kuji_bntw.xlsx` sample
|
||||
@@ -1,313 +0,0 @@
|
||||
# Spec + Flow:互動式配對 + LLM 智能辨識(Config 體驗重設)
|
||||
|
||||
**日期:** 2026-07-03
|
||||
**狀態:** Approved
|
||||
**項目:** NBD Offer Pre-Item Master
|
||||
|
||||
---
|
||||
|
||||
## 1. 概覽
|
||||
|
||||
### 1.1 問題
|
||||
|
||||
現有設計是 **config-first**:使用者要先理解 `source_patterns`、`fuzzy_weight`、`match_rules`、`strategy: token_match`、`reverse_token_match`、`join_type` 等技術概念,透過 Admin UI(本質是包了層皮的 YAML 編輯器)設定 Type,才能正常使用。對非技術使用者而言:
|
||||
|
||||
- **概念太抽象** — 同時要理解 Type → Mapping → Form Fields → Sheet Relations → Match Strategies 五層
|
||||
- **Admin UI 難明** — 只是把 YAML 換成表格,底層技術概念沒變
|
||||
- **不知道從何著手** — 沒有明確的「先做這個、再做那個」流程
|
||||
|
||||
### 1.2 解法
|
||||
|
||||
轉為 **interaction-first** + **learn-by-example**:
|
||||
|
||||
- 使用者 **Upload → 用 dropdown 點選配對 → 匯出**,全程不碰 config
|
||||
- 系統用 **LLM(gemma4)做智能欄位配對 + 跨表偵測**,並附理由供確認
|
||||
- 系統 **記住格式的「指紋」**,下次同款 Excel 自動套用
|
||||
- **YAML config 保留**,作底層儲存 + power user 直接編輯 + 版本控制,但一般使用者永遠看不到
|
||||
|
||||
### 1.3 核心決策(來自訪談)
|
||||
|
||||
| 決策點 | 選擇 |
|
||||
|---|---|
|
||||
| 主要操作方式 | Upload 後在 UI 用 dropdown 點選配對(不寫 config) |
|
||||
| 是否記住 | 認「Excel 的樣」(指紋),同款格式自動套用 |
|
||||
| 跨表處理 | 自動偵測 + 提議,使用者 confirm 或手動指(不出現 strategy 等字眼) |
|
||||
| 欄位配對 UI | Dropdown 下拉選單 |
|
||||
| Config 去留 | **保留 YAML**(儲存 + 版本控制 + power user 編輯) |
|
||||
| 智能引擎 | **LLM Judge(gemma4)**,OpenAI 兼容 API |
|
||||
| 認格式方式 | 模糊指紋 + 評分(robust,容忍欄位小改動) |
|
||||
|
||||
---
|
||||
|
||||
## 2. 心智模型:3 個概念(解決「太抽象」)
|
||||
|
||||
所有使用者面向的字眼收窄到 **3 個日常概念**,技術字眼全部收進 YAML。
|
||||
|
||||
| 使用者見到 | 收在 YAML(power user 才碰) |
|
||||
|---|---|
|
||||
| **格式(Format)** —「這種 Excel 的處理方式」,如「KUJI BNA 標準格式」 | `type_id`, `label`, `category`, type YAML 檔 |
|
||||
| **欄位配對** —「Excel 這欄 = DB 那欄」,dropdown 揀 | `mapping`, `source_patterns`, `fuzzy_weight`, `required` |
|
||||
| **跨表連結** —「這張表的 A = 那張表的 A賞」,系統偵測 + confirm | `sheet_relations`, `match_rules`, `strategy`, `join.type` |
|
||||
|
||||
**使用者永遠不會看到**:`source_patterns`、`fuzzy_weight`、`strategy`、`token_match`、`reverse_lookup`、`join_type`、`header_pattern`。
|
||||
|
||||
---
|
||||
|
||||
## 3. 使用者流程(解決「不知道點做」)
|
||||
|
||||
使用者面向只有 **3 個主動作**(Upload、Review、Export);指紋辨識與 LLM 配對是系統在背後自動做的子步驟。下圖標出完整 6 個階段(含系統內部步驟):
|
||||
|
||||
```
|
||||
① Upload Excel ← 使用者動作
|
||||
↓
|
||||
② 系統計「指紋」→ 模糊比對已知格式 ← 系統自動
|
||||
├─ 認到(≥80% 似)→ 自動套用,跳到 ④ 預覽
|
||||
│ 顯示:「我認得這是『KUJI BNA 標準』✓(87% 似),已套用上次配對」
|
||||
└─ 認不到 → 落 ③
|
||||
↓
|
||||
③ LLM 智能配對(gemma4,一次 call) ← 系統自動
|
||||
├─ 偵測 header row(如有需要)
|
||||
├─ 配對所有欄位 → source → target + 信心 + 理由
|
||||
└─ 偵測跨表關係 →「STYLE A ↔ A賞,要連嗎?」
|
||||
↓
|
||||
④ 用戶 Review ← 使用者動作
|
||||
├─ 欄位配對:dropdown 改(預填 LLM 估計)
|
||||
└─ 跨表連結:confirm / 自己指
|
||||
↓
|
||||
⑤ 預覽 + 匯出 ← 使用者動作
|
||||
├─ 轉換後的表,缺 key 的 row 標記
|
||||
└─ 匯出 Excel
|
||||
↓
|
||||
⑥ 「記住這個配對,下次自動用?」 ← optional
|
||||
└─ [儲存] → 寫入 YAML + 記指紋
|
||||
```
|
||||
|
||||
### 每步的「白話提示」(取代技術標題)
|
||||
|
||||
| 舊標題(技術) | 新提示(白話) |
|
||||
|---|---|
|
||||
| Structure Detection | 「我找到一個表,從第 X 行開始,對嗎?」 |
|
||||
| Fuzzy Matching / Mapping | 「我幫你逐欄配好,看看對不對」 |
|
||||
| Sheet Relations | 「我發現兩張表有關連,要連嗎?」 |
|
||||
| Validation | 「有 N 行缺重要資料,要丟掉還是保留?」 |
|
||||
|
||||
### 流程關鍵改變
|
||||
|
||||
- **沒有「揀 Type」這一步** — 系統自動認,認到就靜靜套用,認不到就告知「我會幫你估」
|
||||
- **儲存是 optional 的尾步** — 不是開頭要你 setup,是做完自然問「要不要記住」
|
||||
|
||||
---
|
||||
|
||||
## 4. 技術架構
|
||||
|
||||
### 4.1 配對的三層兜底(robustness)
|
||||
|
||||
```
|
||||
① LLM Judge(gemma4) ← 主要引擎(最準、跨語、會推理)
|
||||
↓ 失敗 / timeout / API 冇 response
|
||||
② Fuzzy + Synonym(rapidfuzz) ← 自動兜底(現有引擎,零依賴)
|
||||
↓ 都不夠分
|
||||
③ 用戶手動 dropdown ← 最後防線
|
||||
```
|
||||
|
||||
使用者只見到「系統配好了,你 confirm」,背後是 LLM 還是 fuzzy 不需知道。**LLM 沒 response 不會死,靜靜退返 fuzzy。**
|
||||
|
||||
### 4.2 LLM Judge 詳情
|
||||
|
||||
**呼叫方式**:OpenAI 兼容 API,一次 call 配齊所有欄位(不逐欄 call)。
|
||||
|
||||
```
|
||||
POST https://bnaai02.bhk.local/v1/chat/completions
|
||||
Authorization: Bearer <API_KEY>
|
||||
Model: gemma4:latest
|
||||
|
||||
系統 prompt 傳入:
|
||||
- 所有 source 欄位 header(+ 每欄 2-3 個 sample 值作 context)
|
||||
- 所有 target DB 欄位名(+ 描述)
|
||||
- 要求回傳 JSON:{ source_col: {target, confidence, reason} }
|
||||
|
||||
gemma4 回傳範例:
|
||||
{
|
||||
"商品名/英語": {"target": "item_name_eng", "confidence": 0.95,
|
||||
"reason": "英文商品名"},
|
||||
"STYLE": {"target": "package_style", "confidence": 0.80,
|
||||
"reason": "款式代碼 A/B/C"},
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**LLM Judge 也能偵測跨表關係**(embeddings 做不到的):
|
||||
|
||||
```
|
||||
prompt 附上兩張表的欄位 + sample,問:
|
||||
「這兩張表有沒有可連結的欄位?例如一邊的 A/B/C 對應另一邊的 A賞/B賞?」
|
||||
gemma4 回傳:
|
||||
{ "relation": "STYLE ↔ 商品名/日本語", "confidence": 0.85,
|
||||
"reason": "STYLE 的 A/B/C 對應商品名/日本語的 A賞/B賞" }
|
||||
```
|
||||
|
||||
**Token / 速度優化**:
|
||||
|
||||
| 做法 | 原因 |
|
||||
|---|---|
|
||||
| 一次 call 配齊所有欄位 | 不逐欄 call,省往返 |
|
||||
| 每欄附 2-3 個 sample 值 | 給模型 context(只看 header 名有時不夠) |
|
||||
| 結果 cache 落 YAML | 配完 → confirm → 寫入 `config/types/*.yaml`,下次同款格式不再 call |
|
||||
| 回傳 JSON + 信心分 | 系統依信心決定 auto-apply(≥0.9)或要 user confirm |
|
||||
|
||||
### 4.3 指紋辨識(認格式)
|
||||
|
||||
不是硬 hash(太脆),而是**模糊評分**:
|
||||
|
||||
1. 取 Excel 每張 sheet 偵測到的欄位 header 集合
|
||||
2. 與每個已知格式的 header 集合做模糊比對(用現有 FuzzyMatcher)
|
||||
3. 評分規則:
|
||||
- **≥ 80 分** → 自動套用 + 顯示「我認得是 XXX(87% 似)」
|
||||
- **60–80 分** → 列出 top 3 供使用者揀
|
||||
- **< 60 分** → 當新格式,落 LLM 配對流程
|
||||
|
||||
### 4.4 YAML 的角色(保留 config 的要求)
|
||||
|
||||
- **YAML 仍是唯一儲存格式** — 互動 UI 做的所有事,最終都讀寫 `config/types/*.yaml`
|
||||
- **Power user 可直接改 YAML** — 大量改、copy-paste、version control diff
|
||||
- **現有 6 個 type YAML 變「預設種子」** — 出廠預設,兜底用
|
||||
- **Admin 頁面降級為「進階」** — 收在 sidebar 底,預設收起,主流程完全不經過
|
||||
|
||||
### 4.5 儲存層次(3 個來源,優先序高至低)
|
||||
|
||||
| 層次 | 來源 | 誰管理 |
|
||||
|---|---|---|
|
||||
| 1 | **互動配對(本次 session)** | 使用者即場點的,最優先 |
|
||||
| 2 | **已學格式(YAML template)** | 系統自動認 / 之前儲存 |
|
||||
| 3 | **預設種子(現有 6 個 type YAML)** | 出廠預設,兜底 |
|
||||
|
||||
---
|
||||
|
||||
## 5. Config 設計
|
||||
|
||||
### 5.1 新增 `config/settings.yaml` 區段
|
||||
|
||||
```yaml
|
||||
llm:
|
||||
enabled: true
|
||||
base_url: "https://bnaai02.bhk.local/v1"
|
||||
model: "gemma4:latest"
|
||||
api_key_env: "BNA_API_KEY" # 從環境變數讀,不寫死
|
||||
timeout_seconds: 30
|
||||
temperature: 0.1 # 低溫度,求穩定
|
||||
# 自動套用門檻
|
||||
auto_apply_confidence: 0.9 # LLM 信心 ≥ 此值才 auto-apply
|
||||
fingerprint_auto_threshold: 80 # 指紋 ≥ 此分才自動認格式
|
||||
fingerprint_suggest_threshold: 60 # 此區間列出 top 3 供揀
|
||||
|
||||
fuzzy:
|
||||
default_threshold: 75 # fallback fuzzy 用
|
||||
keyword_match_min: 2
|
||||
```
|
||||
|
||||
### 5.2 API Key 安全處理
|
||||
|
||||
- **不寫入 git** — 用環境變數 `BNA_API_KEY` 或 `config/settings.local.yaml`(已加 `.gitignore`)
|
||||
- 範例 config 只放 placeholder:`api_key_env: "BNA_API_KEY"`
|
||||
- **建議 rotate** 目前貼出的 key
|
||||
|
||||
### 5.3 Type YAML 不變
|
||||
|
||||
`config/types/*.yaml` 格式完全保留(向後相容)。互動 UI 產生 / 編輯的就是這個格式。新增「指紋」資訊可選擇性地附在 YAML(作註解或獨立 cache 檔)。
|
||||
|
||||
---
|
||||
|
||||
## 6. UI 頁面變更
|
||||
|
||||
### 6.1 主流程頁面(簡化)
|
||||
|
||||
| 頁面 | 變更 |
|
||||
|---|---|
|
||||
| **Upload** | 移除「揀 Type」下拉;改顯示指紋辨識結果(認到 / 認不到) |
|
||||
| **Step 1 結構**(改名) | 「我找到一個表,從第 X 行開始,對嗎?」+ 確認按鈕 |
|
||||
| **Step 2 配對**(改名) | 每欄 dropdown(預填 LLM 估計)+ 信心 + 理由tooltip |
|
||||
| **Step 3 跨表**(新增) | 系統提議連結:「STYLE A ↔ A賞,要連嗎?」[連][不連][自己指] |
|
||||
| **Step 4 預覽** | 不變 |
|
||||
| **Step 5 匯出** | 加「記住這個配對?」[儲存為「XXX 格式」] |
|
||||
|
||||
### 6.2 Admin 頁面(降級)
|
||||
|
||||
- 移到 sidebar 底部「⚙️ 進階」摺疊區
|
||||
- 預設收起
|
||||
- 保留現有 Form + YAML preview(power user 用)
|
||||
|
||||
---
|
||||
|
||||
## 7. 元件變更摘要
|
||||
|
||||
| 元件 | 動作 |
|
||||
|---|---|
|
||||
| `services/llm_matcher.py` | **新增** — 呼叫 gemma4 做欄位配對 + 跨表偵測,回傳結構化結果 |
|
||||
| `services/fingerprint.py` | **新增** — 計 Excel 指紋 + 模糊比對已知格式 |
|
||||
| `services/fuzzy_matcher.py` | **保留** — 作 LLM fallback |
|
||||
| `services/config_manager.py` | **擴充** — 讀 LLM 設定、管理指紋 cache、讀 API key from env |
|
||||
| `ui/upload_page.py` | **改** — 移除 Type 下拉,加指紋辨識顯示 |
|
||||
| `ui/mapping_review.py` | **改** — 改用 LLM 配對結果預填 dropdown,顯示信心 + 理由 |
|
||||
| `ui/cross_sheet_page.py` | **新增** — Step 3 跨表連結 confirm UI |
|
||||
| `ui/export_page.py` | **改** — 加「儲存配對」尾步 |
|
||||
| `ui/admin_page.py` | **改** — 降級到「進階」區 |
|
||||
| `config/settings.yaml` | **擴充** — 加 `llm` 區段 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 錯誤處理
|
||||
|
||||
| 情境 | 處理 |
|
||||
|---|---|
|
||||
| Ollama / API server 沒 response | 靜靜退返 fuzzy,顯示「智能配對暫時不可用,改用基本配對」 |
|
||||
| API timeout(>30s) | 同上,退 fuzzy |
|
||||
| LLM 回傳非 JSON / 解析失敗 | 退 fuzzy,不 crash |
|
||||
| LLM 配對信心全部偏低 | 顯示「智能配對不確定,請手動確認」,全交 dropdown |
|
||||
| API key 未設 | 啟動時檢查,提示「未設 `BNA_API_KEY`,將只用基本配對」 |
|
||||
| 指紋比對有多個同分 | 列出供使用者揀,不自動套用 |
|
||||
|
||||
---
|
||||
|
||||
## 9. 不在範圍(v1)
|
||||
|
||||
- 線上 / 多人協作
|
||||
- 用 embeddings 模型(改用 LLM Judge,已有 gemma4)
|
||||
- 自動學習優化(如持續 fine-tune)— v1 只做「記住 + 套用」
|
||||
- 直接讀寫 MySQL DB
|
||||
- 行事曆 / 排程 / 批次
|
||||
|
||||
---
|
||||
|
||||
## 10. 實作順序(供後續 plan 參考)
|
||||
|
||||
1. **LLM Matcher 服務** — `llm_matcher.py` + settings + API key from env
|
||||
2. **指紋服務** — `fingerprint.py` + 比對邏輯
|
||||
3. **整合到 DataProcessor / 配對流程** — LLM 主、fuzzy 兜底
|
||||
4. **UI:Upload 頁指紋顯示**
|
||||
5. **UI:Mapping 頁改 dropdown 預填 + 信心 + 理由**
|
||||
6. **UI:新增跨表 confirm 頁**
|
||||
7. **UI:匯出頁加「儲存配對」**
|
||||
8. **Admin 頁降級**
|
||||
9. **端對端測試**(kuji_bntw.xlsx)
|
||||
|
||||
---
|
||||
|
||||
## 附錄 A:使用者見到 vs 收起來(總覽)
|
||||
|
||||
| 使用者見到 | 收在 YAML / 內部 |
|
||||
|---|---|
|
||||
| 格式、欄位、配對、連結 | `source_patterns`, `fuzzy_weight`, `match_rules`, `strategy` |
|
||||
| 「gemma4 說這欄是英文名(95%),對嗎?」 | API call, JSON parsing, confidence logic |
|
||||
| Dropdown 揀 / confirm 按鈕 | fallback 到 rapidfuzz |
|
||||
| 「記住這個配對?」 | 指紋計算 + cache |
|
||||
|
||||
## 附錄 B:與現有設計的差異
|
||||
|
||||
| 面向 | 現有 | 新設計 |
|
||||
|---|---|---|
|
||||
| 主介面 | Admin Form + YAML preview | Upload → dropdown 互動 |
|
||||
| 配對引擎 | Fuzzy + Synonym | LLM Judge 主,Fuzzy 兜底 |
|
||||
| 認格式 | 使用者揀 Type | 系統指紋自動認 |
|
||||
| 跨表 | 手動設 match_rules | LLM 偵測 + confirm |
|
||||
| YAML | 主要編輯介面 | 底層儲存(power user 才碰) |
|
||||
| 概念數 | 5+ 層 | 3 個(格式 / 配對 / 連結) |
|
||||
@@ -1,331 +0,0 @@
|
||||
# Spec:LLM 多階段通讀 + 跨表合併(重寫設計)
|
||||
|
||||
**日期:** 2026-07-03
|
||||
**狀態:** Approved
|
||||
**項目:** NBD Offer Pre-Item Master
|
||||
**性質:** **由零重寫**(唔 patch 現有 code)
|
||||
|
||||
---
|
||||
|
||||
## 1. 點解要重寫
|
||||
|
||||
### 1.1 現有設計嘅根本問題
|
||||
|
||||
現有 LLM 整合係**碎片化**嘅 — 欄位配對、跨表連結、共用值偵測**分開做、各自為政**。後果:
|
||||
|
||||
- **同一隻產品散落多張 sheet,最後出多行**。例如 Grade A Figure:DISNEY PRINCESS 有 STYLE A + size、Item detail 有 GL品番 + 商品名「A賞」。呢啲明明係同一隻嘢,但因為 LLM 逐張 sheet 睇、唔識當一個整體,結果 join 唔到,出 2-3 行缺料。
|
||||
- **LLM 冇「通讀」**。而家 LLM 淨係配欄位,冇先理解成個 workbook 嘅結構同 sheet 之間嘅關係。
|
||||
- **Config 太抽象**。技術字眼(`source_patterns`、`strategy`、`fuzzy_weight`)暴露俾用戶。
|
||||
|
||||
### 1.2 重寫嘅核心轉變
|
||||
|
||||
| 面向 | 舊(碎片化) | 新(通讀整合) |
|
||||
|---|---|---|
|
||||
| LLM 做咩 | 淨配欄位 | 先通讀理解結構,再合併,再配欄位 |
|
||||
| Sheet 處理 | 各自獨立 | 先分析關連,再合併成一體 |
|
||||
| 一行代表 | 一個 sheet row | **一隻產品(多 sheet 合併)** |
|
||||
| 決策點 | 多步分散 | **一個 confirm 位(合併藍圖)** |
|
||||
| Config 角色 | 主要編輯介面 | **保底 cache**(LLM 學識後 save) |
|
||||
|
||||
---
|
||||
|
||||
## 2. 工具定位(重要澄清)
|
||||
|
||||
> **呢個工具淨係負責「搵到就配,搵唔到就留空」。唔係所有 SQL column 都要喺 Excel 搵到。**
|
||||
|
||||
SQL schema 只係「**可能嘅目標欄位清單**」。Excel 搵到對應就填,搵唔到就留空。**冇「required must match」**。唔使區分 dropdown / calculated / lookup 嗰啲 input_type — 呢啲係匯出之後嘅事。
|
||||
|
||||
---
|
||||
|
||||
## 3. 數據結構理解(設計基礎)
|
||||
|
||||
| 層 | 來源 | 欄數 | 性質 |
|
||||
|---|---|---|---|
|
||||
| ① pre_item_master (SQL) | DB 結構 | 57 | 產品主檔 |
|
||||
| ② Source Excel | 7 種格式 | 不定 | column 名差異大 |
|
||||
| ③ 1.1 Data Upload | 最終匯出目標 | 85 | Offer 系統格式 |
|
||||
|
||||
**本工具處理範圍**:② → ①(搵到就配)。③ 嘅 offer-level / calculated / lookup 欄位**唔在本工具範圍**,留空俾後續系統處理。
|
||||
|
||||
### 3.1 SQL 57 欄嘅語義分類(俾 LLM 配對參考)
|
||||
|
||||
```
|
||||
🔑 Identity: generated_barcode, sap
|
||||
📝 Names: item_name_eng, item_name_jap
|
||||
📦 Package: version/style/size/pcs_ctn/dp_ctn/pcs_dp/no_of_asst
|
||||
⚖️ Compliance: license_apply/sticker, age_grade, 3c_avb, battery, instruction_sheet
|
||||
📅 Dates: release/launch/period/obs
|
||||
💰 Pricing: with/without_tax, operation_price
|
||||
🏭 Origin: country/currency/factory/vendor
|
||||
🎭 IP/Char: ip_holder/group, character, series, product_line/type
|
||||
```
|
||||
|
||||
### 3.2 Source column 名差異極大
|
||||
|
||||
同一 target,7 種叫法:
|
||||
```
|
||||
generated_barcode: GL JAN | SALES JAN CODE | JAN_Code | JAN | Material_No
|
||||
item_name_eng: ITEM NAME | Product contents | 商品名/英語 | Material_Offical_Desc_EN
|
||||
factory: 生産メーカー | 納品倉庫 | Manufacturer
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 完整 Pipeline
|
||||
|
||||
```
|
||||
① Upload Excel
|
||||
↓
|
||||
② LLM Stage 1: 逐張 sheet 通讀(每張 1 call)
|
||||
→ 各 sheet 嘅「摘要」(header_row + 欄位性質 + sheet_type + shared_values)
|
||||
↓
|
||||
③ LLM Stage 2: 跨表連結分析(1 call,淨睇摘要)
|
||||
→ 「合併藍圖」(主表建議 + 連結 key + match_strategy + 理由)
|
||||
↓
|
||||
④ ──── CONFIRM 位(唯一停頓)────
|
||||
你見到合併藍圖 + 配對建議 + 信心
|
||||
可改: 主表 / 連結 / 配對
|
||||
↓
|
||||
⑤ 合併執行 + 欄位配對(按藍圖,自動)
|
||||
同一隻產品多 sheet 資料 → 合成 1 行
|
||||
Excel 欄 → SQL target(搵到就配,搵唔到留空)
|
||||
↓
|
||||
⑥ 預覽 + 匯出
|
||||
一行一產品,缺料標記,可改可 drop
|
||||
↓
|
||||
⑦ Save?(optional)→ YAML cache(下次同款格式自動套用)
|
||||
```
|
||||
|
||||
### 每步嘅白話提示
|
||||
|
||||
| 階段 | 提示 |
|
||||
|---|---|
|
||||
| Stage 1+2 | 「緊係通讀緊成個 workbook,理解緊結構…」 |
|
||||
| Confirm | 「我理解到 N 張表,呢兩張講緊同一批貨,咁連啱唔啱?」 |
|
||||
| Stage 3 | 「幫你配緊欄位…」 |
|
||||
| 預覽 | 「合併咗 M 隻產品,N 行缺料」 |
|
||||
|
||||
---
|
||||
|
||||
## 5. LLM 多階段詳情(9B 友善)
|
||||
|
||||
9B model 每次只能做**一件簡單嘢**。每個 prompt 淨問一樣,output 係細 JSON。
|
||||
|
||||
### 5.1 Stage 1:逐張 sheet 通讀
|
||||
|
||||
- **Input**: 一張 sheet 嘅 raw data(前 30 行)
|
||||
- **Task**: 淨理解,唔配欄位
|
||||
- **Output per sheet**:
|
||||
```json
|
||||
{
|
||||
"header_row": 20,
|
||||
"sheet_type": "definition" | "detail",
|
||||
"columns": [{"header": "STYLE", "samples": ["A","B"], "meaning": "款式代碼"}],
|
||||
"shared_values": [{"label": "SALES JAN CODE", "value": "457310268..."}]
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 Stage 2:跨表連結分析
|
||||
|
||||
- **Input**: 所有 sheet 嘅 Stage 1 摘要(文字,幾百字)
|
||||
- **Task**: 淨搵關連,唔碰 raw data
|
||||
- **Output**:
|
||||
```json
|
||||
{
|
||||
"groups": [{
|
||||
"sheets": ["DISNEY PRINCESS", "Item detail"],
|
||||
"master_sheet": "Item detail",
|
||||
"master_reason": "有 GL品番 unique key",
|
||||
"links": [{
|
||||
"from_sheet": "DISNEY PRINCESS", "from_column": "STYLE",
|
||||
"to_sheet": "Item detail", "to_column": "商品名",
|
||||
"key_pattern": "A/B/C 級別代碼",
|
||||
"match_strategy": "value_token"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
### 5.3 Stage 3:欄位配對
|
||||
|
||||
- **Input**: 合併藍圖 + 各 sheet columns + SQL schema(目標清單)
|
||||
- **Task**: Excel 欄 → SQL target
|
||||
- **Output**:
|
||||
```json
|
||||
{"mapping": [{"excel": "商品名/英語", "sql": "item_name_eng", "confidence": 0.95}]}
|
||||
```
|
||||
|
||||
### 9B 友善設計原則
|
||||
|
||||
| 設計 | 點解 |
|
||||
|---|---|
|
||||
| 每個 stage 淨做一件事 | 9B 多 task 會亂 |
|
||||
| Stage 2 淨睇摘要 | 幾百字 vs 幾萬 cell,9B 先睇得明 |
|
||||
| 每個 output 係細 JSON | 9B 大 JSON 易出錯 |
|
||||
| 可重試單個 stage | 邊個錯重做嗰個,唔使全部重來 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 合併引擎
|
||||
|
||||
藍圖話「DISNEY.STYLE ↔ Item detail.商品名,strategy=value_token」,引擎執行:
|
||||
|
||||
```
|
||||
Step A: 攞主表每行做 base
|
||||
Step B: 拎 key(商品名="A賞...")→ normalize → extract key token "a"
|
||||
Step C: 從表搵 matching row(DISNEY.STYLE 嘅 token set 包含 "a")
|
||||
Step D: merge 從表嗰行其他欄位落 base(size/qty/age/country)
|
||||
結果: Item detail 行 + DISNEY 規格 = 1 行齊料
|
||||
```
|
||||
|
||||
### Match Strategy(LLM 喺 Stage 2 揀,引擎執行)
|
||||
|
||||
| Strategy | 例子 | 判法 |
|
||||
|---|---|---|
|
||||
| `value_token` | A ↔ A賞 / GRADE A | key 係從表 value 嘅一個 token |
|
||||
| `value_prefix` | A ↔ A賞 | 從表 value 以 key 開頭 |
|
||||
| `value_exact` | 2884768 ↔ 2884768 | 完全一樣 |
|
||||
| `value_contains` | A ↔ GRADE A:Figure | key 出現喺從表 value 任何位 |
|
||||
|
||||
**Normalize**:NFKC + 全形→半形 + lowercase + strip,等 `F` ↔ `F` 認到。
|
||||
|
||||
### 主表決定(漸進式)
|
||||
|
||||
1. LLM Stage 2 建議主表(通常 unique key 嗰張 / 行數最多嗰張)
|
||||
2. Confirm 位你可以改(dropdown)
|
||||
3. Save 時記低你嘅揀法 → 下次同款格式自動用
|
||||
|
||||
---
|
||||
|
||||
## 7. Confirm UI(唯一停頓位)
|
||||
|
||||
```
|
||||
┌─────────────── 合併藍圖 ───────────────┐
|
||||
│ 📊 結構理解 │
|
||||
│ ├ DISNEY PRINCESS → 定義表 │
|
||||
│ └ Item detail → 明細表 ⭐ 主表 │
|
||||
│ │
|
||||
│ 🔗 跨表連結 │
|
||||
│ DISNEY.STYLE ↔ Item detail.商品名 │
|
||||
│ 策略: value_token | 信心 85% │
|
||||
│ │
|
||||
│ 主表: [Item detail ▼] ← 可改 │
|
||||
│ 預覽: 14 行 │
|
||||
│ │
|
||||
│ 📝 欄位配對 (14 項) │
|
||||
│ 商品名/英語 → item_name_eng (95%) │
|
||||
│ ... [展開全部] │
|
||||
│ │
|
||||
│ [✅ 全部 OK] [✏️ 改] │
|
||||
└────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Config 結構(保底)
|
||||
|
||||
### 三層兜底
|
||||
|
||||
```
|
||||
① LLM 在線 → 實時 Stage 1+2+3 分析(最準)
|
||||
↓ offline / 出錯
|
||||
② YAML cache → 上次同款格式 save 咗嘅藍圖(保底)
|
||||
↓ YAML 都冇
|
||||
③ Fuzzy + 猜測(最後防線)
|
||||
```
|
||||
|
||||
### `config/schema.yaml`(目標欄位清單,純清單)
|
||||
|
||||
```yaml
|
||||
table: pre_item_master
|
||||
fields:
|
||||
- name: generated_barcode
|
||||
description: "GL JAN / SALES JAN CODE" # 俾 LLM 配對用嘅人話描述
|
||||
- name: item_name_eng
|
||||
description: "Item Name English"
|
||||
- name: license_apply
|
||||
description: "License apply (Y/N)"
|
||||
# ... 全部 57 欄,淨係 name + description
|
||||
```
|
||||
|
||||
**冇** input_type、冇 required flag、冇 default — 搵到就配,搵唔到就空。
|
||||
|
||||
### `config/types/<learned>.yaml`(LLM 學識後 save 嘅藍圖)
|
||||
|
||||
```yaml
|
||||
type_id: kuji_bna_learned
|
||||
label: "KUJI BNA (learned)"
|
||||
fingerprint:
|
||||
sheets: ["DISNEY*", "Item detail"] # 認格式用
|
||||
structure:
|
||||
sheets:
|
||||
- {name: "DISNEY*", role: definition, header_row: 20}
|
||||
- {name: "Item detail", role: detail, header_row: 1}
|
||||
merge:
|
||||
master_sheet: "Item detail"
|
||||
links:
|
||||
- {from: "DISNEY*.STYLE", to: "Item detail.商品名", strategy: value_token}
|
||||
mapping:
|
||||
商品名/英語: item_name_eng
|
||||
STYLE: package_style
|
||||
ITEM SIZE: package_size
|
||||
...
|
||||
shared_values:
|
||||
- {label: "SALES JAN CODE", target: generated_barcode}
|
||||
```
|
||||
|
||||
下次同款格式 → fingerprint 認到 → 直接用呢份藍圖,**唔使 call LLM**。
|
||||
|
||||
---
|
||||
|
||||
## 9. 錯誤處理
|
||||
|
||||
| 情境 | 處理 |
|
||||
|---|---|
|
||||
| Stage 1 某 sheet JSON 亂 | 重試嗰張 2 次,再失敗 mark「未理解」跳過 |
|
||||
| Stage 2 認唔到連結 | 當冇連結,各 sheet 獨立輸出 + 提示 |
|
||||
| Stage 3 配對信心全低 | 全 highlight 紅,confirm 位逐個睇 |
|
||||
| LLM 完全 offline | 用 YAML / fuzzy 保底 |
|
||||
| 主表揀錯(合併行數唔合理) | 警告「主表 N 行但從表 M 行,可能主表揀錯」 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 重寫範圍
|
||||
|
||||
**由零重寫以下**(唔 patch 現有):
|
||||
|
||||
| 元件 | 動作 |
|
||||
|---|---|
|
||||
| `services/llm_stages.py` | **新建** — Stage 1/2/3 三個 LLM call |
|
||||
| `services/merge_engine.py` | **新建** — 執行合併藍圖(match strategy + normalize) |
|
||||
| `services/workbook_analyzer.py` | **新建** — 協調三個 stage + 合併 + fallback |
|
||||
| `services/fingerprint.py` | **保留改良** — 認格式用 |
|
||||
| `config/schema.yaml` | **重建** — 純目標清單(name + description) |
|
||||
| `config/types/*.yaml` | **重建** — 改做藍圖格式(structure + merge + mapping) |
|
||||
| `ui/` | **重寫** — Upload → Confirm(藍圖)→ Preview → Export |
|
||||
| 舊 `fuzzy_matcher` / `value_matcher` / `data_processor` | **降級做 fallback**,唔再係主路徑 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 不在範圍(v1)
|
||||
|
||||
- Offer-level 欄位(Offer Number/Title/Date)— 留空
|
||||
- Calculated 欄位(Chk #/Item #)— 留空
|
||||
- Lookup 欄位(Main Category/Team)— 留空
|
||||
- 1.1 格式 85 欄完整匯出 — 淨做 57 SQL 欄
|
||||
- 多人 / 線上
|
||||
- 直接寫 MySQL DB
|
||||
|
||||
---
|
||||
|
||||
## 附錄:核心決策(來自訪談)
|
||||
|
||||
| 決策點 | 選擇 | 理由 |
|
||||
|---|---|---|
|
||||
| LLM 通讀方式 | 多階段(每階段一細 task) | 9B 能力有限,分而治之更準 |
|
||||
| Token 限制 | 無限(本地 model) | 但 9B 長 context 易亂,仍要拆細 |
|
||||
| 一行代表 | 一隻產品(多 sheet 合併) | 輸出精簡,要準確 join |
|
||||
| LLM 介入程度 | 自動 + 一個 confirm 位 | 準 + 唔煩 |
|
||||
| 主表決定 | LLM 建議 + 你 confirm + 學識 | 漸進式,情況每次唔同 |
|
||||
| Config 角色 | 保底 cache(唔係主介面) | LLM 學識後 save,下次自動 |
|
||||
| 工具定位 | 搵到就配,搵唔到留空 | 唔強制所有欄配到 |
|
||||
+17
-9
@@ -1,10 +1,18 @@
|
||||
streamlit>=1.28
|
||||
# streamlit 1.58 imports gzip middleware symbols only present in starlette 1.x.
|
||||
# Runtime dependencies use the latest verified stable release as the minimum,
|
||||
# with a next-major upper bound to accept future patch/minor fixes without
|
||||
# silently taking breaking major releases.
|
||||
streamlit>=1.59.0,<2
|
||||
requests>=2.34.2,<3
|
||||
python-multipart>=0.0.32,<1
|
||||
# streamlit 1.58+ imports gzip middleware symbols only present in starlette 1.x.
|
||||
# Pin explicitly so a globally-installed fastapi (which caps starlette <0.42) doesn't break the install.
|
||||
starlette>=1.3.1
|
||||
pandas>=2.0
|
||||
openpyxl>=3.1
|
||||
rapidfuzz>=3.0
|
||||
pyyaml>=6.0
|
||||
python-dateutil>=2.8
|
||||
pytest>=7.0
|
||||
starlette>=1.3.1,<2
|
||||
pandas>=3.0.3,<4
|
||||
openpyxl>=3.1.5,<4
|
||||
rapidfuzz>=3.14.5,<4
|
||||
pyyaml>=6.0.3,<7
|
||||
python-dateutil>=2.9.0.post0,<3
|
||||
|
||||
# Test / maintenance helpers used directly by the suite.
|
||||
pytest>=9.1.1,<10
|
||||
packaging>=26.2,<27
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
|
||||
if not exist ".venv\Scripts\python.exe" (
|
||||
echo Creating project virtual environment...
|
||||
python -m venv .venv
|
||||
if errorlevel 1 exit /b %errorlevel%
|
||||
)
|
||||
|
||||
set PYTHONPATH=
|
||||
".venv\Scripts\python.exe" -m pip install --upgrade -r requirements.txt
|
||||
if errorlevel 1 exit /b %errorlevel%
|
||||
|
||||
".venv\Scripts\python.exe" -m streamlit run app.py
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Generate an admin password hash for config/settings.yaml."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from services.security import hash_password
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Generate PBKDF2 admin password hash")
|
||||
parser.add_argument("password", nargs="?", help="Password to hash. Omit to prompt securely.")
|
||||
args = parser.parse_args()
|
||||
password = args.password or getpass.getpass("Admin password: ")
|
||||
if not password:
|
||||
print("Password must not be empty", file=sys.stderr)
|
||||
return 2
|
||||
print(hash_password(password))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1 @@
|
||||
"""Business-logic services for parsing, matching, merging, and exporting workbooks."""
|
||||
@@ -0,0 +1,268 @@
|
||||
"""Persistent debug logging for optional AI analysis runs.
|
||||
|
||||
The Streamlit UI already shows a visible run trace, but operators sometimes need
|
||||
a file they can copy from another environment for root-cause analysis. This
|
||||
module writes JSON Lines with redacted secrets, request/response metadata,
|
||||
validation events, deterministic fallback summaries, and final blueprint stats.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, is_dataclass
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import traceback
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
|
||||
_SECRET_KEY_PARTS = (
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
"bearer",
|
||||
"token",
|
||||
"password",
|
||||
"secret",
|
||||
)
|
||||
_BEARER_RE = re.compile(r"Bearer\s+[^\s,;]+", re.IGNORECASE)
|
||||
_API_KEY_RE = re.compile(r"\bsk-[A-Za-z0-9_-]{8,}\b")
|
||||
_LONG_TOKEN_RE = re.compile(r"\b[A-Za-z0-9_-]{32,}\.[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}\b")
|
||||
|
||||
|
||||
def create_ai_analysis_debug_log(
|
||||
config_manager: ConfigManager,
|
||||
parsed: Any,
|
||||
selected_type: str | None,
|
||||
run_id: str | None = None,
|
||||
) -> "AIDebugLog | None":
|
||||
"""Create and prime a debug log for one AI run, or return None when disabled."""
|
||||
debug_cfg = config_manager.get_ai_debug_log_config()
|
||||
if not debug_cfg.get("enabled", True):
|
||||
return None
|
||||
|
||||
log_dir = config_manager.get_ai_debug_log_dir()
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
safe_run = _safe_filename(run_id or uuid.uuid4().hex[:8])
|
||||
path = log_dir / f"ai_analysis_{timestamp}_{safe_run}.jsonl"
|
||||
logger = AIDebugLog(path, run_id=safe_run, max_string_chars=int(debug_cfg.get("max_string_chars", 12000)))
|
||||
workbook = summarize_parsed_workbook(parsed)
|
||||
logger.write(
|
||||
"run_start",
|
||||
workbook={"file_name": workbook.get("file_name", ""), "sheet_count": workbook.get("sheet_count", 0)},
|
||||
selected_type=selected_type or "",
|
||||
llm=summarize_llm_config(config_manager),
|
||||
analysis={
|
||||
"ai_auto_accept_mapping_threshold": config_manager.get_ai_auto_accept_mapping_threshold(),
|
||||
"debug_log": debug_cfg,
|
||||
},
|
||||
)
|
||||
logger.write("workbook_snapshot", workbook=workbook)
|
||||
return logger
|
||||
|
||||
|
||||
class AIDebugLog:
|
||||
"""Line-buffered JSONL writer with recursive secret redaction."""
|
||||
|
||||
def __init__(self, path: Path, run_id: str, max_string_chars: int = 12000):
|
||||
self.path = Path(path)
|
||||
self.run_id = str(run_id or "current")
|
||||
self.max_string_chars = max(1000, int(max_string_chars or 12000))
|
||||
self._seq = 0
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._fh = self.path.open("a", encoding="utf-8", buffering=1)
|
||||
|
||||
def write(self, event_type: str, **payload: Any) -> None:
|
||||
"""Append one sanitized JSON object to the log."""
|
||||
self._seq += 1
|
||||
record = {
|
||||
"ts": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||
"seq": self._seq,
|
||||
"run_id": self.run_id,
|
||||
"event_type": event_type,
|
||||
}
|
||||
record.update(_sanitize(payload, max_string_chars=self.max_string_chars))
|
||||
self._fh.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n")
|
||||
self._fh.flush()
|
||||
|
||||
def log_exception(self, event_type: str, exc: BaseException, **context: Any) -> None:
|
||||
"""Append an exception record with traceback for post-run diagnosis."""
|
||||
self.write(
|
||||
event_type,
|
||||
error_type=exc.__class__.__name__,
|
||||
error=str(exc),
|
||||
traceback=traceback.format_exc(),
|
||||
**context,
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the log file; safe to call multiple times."""
|
||||
if getattr(self, "_fh", None) and not self._fh.closed:
|
||||
self._fh.close()
|
||||
|
||||
def __enter__(self) -> "AIDebugLog":
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
if exc is not None:
|
||||
self.log_exception("run_exception", exc)
|
||||
self.close()
|
||||
|
||||
|
||||
def summarize_llm_config(config_manager: ConfigManager) -> dict[str, Any]:
|
||||
"""Return a redacted snapshot of effective LLM settings."""
|
||||
cfg = config_manager.get_llm_config()
|
||||
conn = config_manager.resolve_llm_connection_config()
|
||||
active_profile = cfg.get("active_profile")
|
||||
return _sanitize({
|
||||
"enabled": cfg.get("enabled"),
|
||||
"active_profile": active_profile,
|
||||
"active_profile_available": active_profile in (cfg.get("profiles") or {}),
|
||||
"resolved_connection": conn or None,
|
||||
})
|
||||
|
||||
|
||||
def summarize_parsed_workbook(parsed: Any) -> dict[str, Any]:
|
||||
"""Return compact workbook metadata and a small cell preview per sheet."""
|
||||
sheets = []
|
||||
for sheet in getattr(parsed, "sheets", []) or []:
|
||||
raw_data = getattr(sheet, "raw_data", []) or []
|
||||
preview_rows = []
|
||||
for row in raw_data[:5]:
|
||||
preview_rows.append([_stringify_cell(cell) for cell in list(row)[:20]])
|
||||
form_fields = []
|
||||
for field in getattr(sheet, "form_fields", []) or []:
|
||||
form_fields.append({
|
||||
"label": getattr(field, "label", ""),
|
||||
"value": getattr(field, "value", ""),
|
||||
})
|
||||
sheets.append({
|
||||
"name": getattr(sheet, "name", ""),
|
||||
"rows": getattr(sheet, "rows", None),
|
||||
"cols": getattr(sheet, "cols", None),
|
||||
"header_row": getattr(sheet, "header_row", None),
|
||||
"data_start_row": getattr(sheet, "data_start_row", None),
|
||||
"data_end_row": getattr(sheet, "data_end_row", None),
|
||||
"detected_headers": list(getattr(sheet, "detected_headers", []) or []),
|
||||
"form_fields": form_fields[:30],
|
||||
"raw_preview_first_5_rows": preview_rows,
|
||||
})
|
||||
return {
|
||||
"file_name": getattr(parsed, "file_name", ""),
|
||||
"sheet_count": len(sheets),
|
||||
"sheets": sheets,
|
||||
}
|
||||
|
||||
|
||||
def summarize_analysis_result(result: Any) -> dict[str, Any]:
|
||||
"""Return JSON-safe final blueprint summary with mappings and warnings."""
|
||||
summaries = []
|
||||
for summary in getattr(result, "summaries", []) or []:
|
||||
summaries.append({
|
||||
"sheet_name": getattr(summary, "sheet_name", ""),
|
||||
"header_row": getattr(summary, "header_row", None),
|
||||
"sheet_type": getattr(summary, "sheet_type", ""),
|
||||
"columns": getattr(summary, "columns", []) or [],
|
||||
"shared_values": getattr(summary, "shared_values", []) or [],
|
||||
})
|
||||
groups = []
|
||||
for group in getattr(result, "groups", []) or []:
|
||||
links = []
|
||||
for link in getattr(group, "links", []) or []:
|
||||
links.append({
|
||||
"from_sheet": getattr(link, "from_sheet", ""),
|
||||
"from_column": getattr(link, "from_column", ""),
|
||||
"to_sheet": getattr(link, "to_sheet", ""),
|
||||
"to_column": getattr(link, "to_column", ""),
|
||||
"key_pattern": getattr(link, "key_pattern", ""),
|
||||
"match_strategy": getattr(link, "match_strategy", ""),
|
||||
"confidence": getattr(link, "confidence", None),
|
||||
"reason": getattr(link, "reason", ""),
|
||||
})
|
||||
groups.append({
|
||||
"sheets": getattr(group, "sheets", []) or [],
|
||||
"master_sheet": getattr(group, "master_sheet", ""),
|
||||
"master_reason": getattr(group, "master_reason", ""),
|
||||
"links": links,
|
||||
})
|
||||
mappings = []
|
||||
for mapping in getattr(result, "mappings", []) or []:
|
||||
mappings.append({
|
||||
"excel_column": getattr(mapping, "excel_column", ""),
|
||||
"sql_target": getattr(mapping, "sql_target", ""),
|
||||
"confidence": getattr(mapping, "confidence", None),
|
||||
"reason": getattr(mapping, "reason", ""),
|
||||
})
|
||||
return {
|
||||
"engine": getattr(result, "engine", ""),
|
||||
"summary_count": len(summaries),
|
||||
"group_count": len(groups),
|
||||
"mapping_count": len(mappings),
|
||||
"warnings": list(getattr(result, "warnings", []) or []),
|
||||
"summaries": summaries,
|
||||
"groups": groups,
|
||||
"mappings": mappings,
|
||||
}
|
||||
|
||||
|
||||
def _sanitize(value: Any, *, max_string_chars: int = 12000, depth: int = 0) -> Any:
|
||||
"""Recursively convert values to JSON-safe forms while redacting secrets."""
|
||||
if depth > 8:
|
||||
return "«max-depth»"
|
||||
if is_dataclass(value):
|
||||
value = asdict(value)
|
||||
if isinstance(value, dict):
|
||||
sanitized = {}
|
||||
for key, item in value.items():
|
||||
key_text = str(key)
|
||||
if _is_secret_key(key_text):
|
||||
sanitized[key_text] = "«redacted»" if item else item
|
||||
else:
|
||||
sanitized[key_text] = _sanitize(item, max_string_chars=max_string_chars, depth=depth + 1)
|
||||
return sanitized
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
seq = list(value)
|
||||
kept = [_sanitize(item, max_string_chars=max_string_chars, depth=depth + 1) for item in seq[:200]]
|
||||
if len(seq) > 200:
|
||||
kept.append(f"«truncated {len(seq) - 200} item(s)»")
|
||||
return kept
|
||||
if isinstance(value, Path):
|
||||
return str(value)
|
||||
if isinstance(value, (str, bytes)):
|
||||
text = value.decode("utf-8", errors="replace") if isinstance(value, bytes) else value
|
||||
text = _redact_secret_text(text)
|
||||
return _clip(text, max_string_chars)
|
||||
if isinstance(value, (int, float, bool)) or value is None:
|
||||
return value
|
||||
return _clip(_redact_secret_text(str(value)), max_string_chars)
|
||||
|
||||
|
||||
def _is_secret_key(key: str) -> bool:
|
||||
normalized = key.lower().replace("-", "_")
|
||||
return any(part in normalized for part in _SECRET_KEY_PARTS)
|
||||
|
||||
|
||||
def _redact_secret_text(text: str) -> str:
|
||||
text = _BEARER_RE.sub("Bearer «redacted»", text)
|
||||
text = _API_KEY_RE.sub("sk-«redacted»", text)
|
||||
text = _LONG_TOKEN_RE.sub("«redacted-token»", text)
|
||||
return text
|
||||
|
||||
|
||||
def _clip(text: str, limit: int) -> str:
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
return text[:limit] + f"\n«truncated {len(text) - limit} chars»"
|
||||
|
||||
|
||||
def _stringify_cell(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return _clip(str(value), 500)
|
||||
|
||||
|
||||
def _safe_filename(value: str) -> str:
|
||||
safe = re.sub(r"[^A-Za-z0-9_.-]", "-", str(value or "run"))
|
||||
return safe.strip(".-") or "run"
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Save and review temporary blueprint proposals.
|
||||
|
||||
Basic users may write proposal files for IT/Admin review. Only admin-confirmed
|
||||
flows should merge these proposals into config/types/*.yaml.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
import re
|
||||
|
||||
import yaml
|
||||
|
||||
from services.learned_blueprint import build_learned_type_config
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BlueprintProposalRef:
|
||||
"""Small listing item for a saved blueprint proposal."""
|
||||
|
||||
path: Path
|
||||
created_at: str
|
||||
source_workbook_name: str
|
||||
selected_type: str
|
||||
analysis_engine: str
|
||||
mappings: int
|
||||
|
||||
|
||||
def _safe_slug(value: str) -> str:
|
||||
slug = re.sub(r"[^a-zA-Z0-9]+", "_", (value or "blueprint").strip().lower()).strip("_")
|
||||
return slug or "blueprint"
|
||||
|
||||
|
||||
def _as_plain(value: Any) -> Any:
|
||||
"""Convert dataclasses/simple objects used in blueprints into YAML-safe values."""
|
||||
if isinstance(value, dict):
|
||||
return {str(k): _as_plain(v) for k, v in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [_as_plain(v) for v in value]
|
||||
if hasattr(value, "__dataclass_fields__"):
|
||||
return {name: _as_plain(getattr(value, name)) for name in value.__dataclass_fields__}
|
||||
if hasattr(value, "__dict__") and value.__class__.__module__.startswith("services."):
|
||||
return {k: _as_plain(v) for k, v in vars(value).items() if not k.startswith("_")}
|
||||
return value
|
||||
|
||||
|
||||
def save_blueprint_proposal(
|
||||
base_dir: Path | str,
|
||||
*,
|
||||
blueprint: dict[str, Any],
|
||||
proposal_name: str,
|
||||
source_workbook_name: str,
|
||||
selected_type: str | None,
|
||||
analysis_engine: str | 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"
|
||||
payload = {
|
||||
"proposal_version": 1,
|
||||
"created_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 {}),
|
||||
}
|
||||
path.write_text(yaml.safe_dump(payload, allow_unicode=True, sort_keys=False), encoding="utf-8")
|
||||
return _ref_from_payload(path, payload)
|
||||
|
||||
|
||||
def list_blueprint_proposals(base_dir: Path | str) -> list[BlueprintProposalRef]:
|
||||
"""Return saved proposal files sorted oldest-to-newest by filename."""
|
||||
base = Path(base_dir)
|
||||
if not base.exists():
|
||||
return []
|
||||
refs: list[BlueprintProposalRef] = []
|
||||
for path in sorted(base.glob("*.yaml")):
|
||||
try:
|
||||
refs.append(_ref_from_payload(path, load_blueprint_proposal(path)))
|
||||
except Exception:
|
||||
continue
|
||||
return refs
|
||||
|
||||
|
||||
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:
|
||||
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 archive_blueprint_proposal(path: Path | str) -> Path:
|
||||
"""Move a processed proposal next to the pending folder under archive/."""
|
||||
p = Path(path)
|
||||
archive_dir = p.parent / "archive"
|
||||
archive_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = archive_dir / p.name
|
||||
p.replace(target)
|
||||
return target
|
||||
|
||||
|
||||
def _ref_from_payload(path: Path, payload: dict[str, Any]) -> BlueprintProposalRef:
|
||||
blueprint = payload.get("blueprint") or {}
|
||||
return BlueprintProposalRef(
|
||||
path=path,
|
||||
created_at=str(payload.get("created_at", "")),
|
||||
source_workbook_name=str(payload.get("source_workbook_name", "")),
|
||||
selected_type=str(payload.get("selected_type", "")),
|
||||
analysis_engine=str(payload.get("analysis_engine", "")),
|
||||
mappings=len(blueprint.get("mappings") or []),
|
||||
)
|
||||
+222
-30
@@ -1,6 +1,6 @@
|
||||
"""Load, cache, and save configuration from YAML files."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
@@ -9,6 +9,7 @@ class ConfigManager:
|
||||
"""Manages all config loading and saving for the NBD Pre-Item Master app."""
|
||||
|
||||
def __init__(self, config_dir: Path | str | None = None):
|
||||
"""Create a config manager rooted at the project config directory."""
|
||||
if config_dir is None:
|
||||
config_dir = Path(__file__).resolve().parent.parent / "config"
|
||||
self.config_dir = Path(config_dir)
|
||||
@@ -27,6 +28,7 @@ class ConfigManager:
|
||||
self._load_type_configs()
|
||||
|
||||
def _load_db_schema(self):
|
||||
"""Load the formal SQL target table and column order."""
|
||||
path = self.config_dir / "db_schema.yaml"
|
||||
if path.exists():
|
||||
with open(path, encoding="utf-8") as f:
|
||||
@@ -35,12 +37,45 @@ class ConfigManager:
|
||||
self._db_schema = data.get("columns", [])
|
||||
|
||||
def _load_settings(self):
|
||||
path = self.config_dir / "settings.yaml"
|
||||
if path.exists():
|
||||
with open(path, encoding="utf-8") as f:
|
||||
self._settings = yaml.safe_load(f)
|
||||
"""Load settings.example.yaml defaults overlaid by runtime settings.yaml."""
|
||||
settings: dict = {}
|
||||
example_path = self.config_dir / "settings.example.yaml"
|
||||
if example_path.exists():
|
||||
with open(example_path, encoding="utf-8") as f:
|
||||
settings = yaml.safe_load(f) or {}
|
||||
|
||||
runtime_path = self.config_dir / "settings.yaml"
|
||||
if runtime_path.exists():
|
||||
with open(runtime_path, encoding="utf-8") as f:
|
||||
runtime = yaml.safe_load(f) or {}
|
||||
settings = self._deep_merge(settings, runtime)
|
||||
if self._should_force_offline_ai_for_tests():
|
||||
settings.setdefault("llm", {})["enabled"] = False
|
||||
self._settings = settings
|
||||
|
||||
def _should_force_offline_ai_for_tests(self) -> bool:
|
||||
"""Disable real AI for default project config during normal pytest runs."""
|
||||
if os.getenv("RUN_REAL_AI_TESTS") == "1" or not os.getenv("PYTEST_CURRENT_TEST"):
|
||||
return False
|
||||
default_config_dir = Path(__file__).resolve().parent.parent / "config"
|
||||
try:
|
||||
return self.config_dir.resolve() == default_config_dir.resolve()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _deep_merge(base: dict, override: dict) -> dict:
|
||||
"""Return base recursively overlaid by override without mutating inputs."""
|
||||
merged = dict(base or {})
|
||||
for key, value in (override or {}).items():
|
||||
if isinstance(value, dict) and isinstance(merged.get(key), dict):
|
||||
merged[key] = ConfigManager._deep_merge(merged[key], value)
|
||||
else:
|
||||
merged[key] = value
|
||||
return merged
|
||||
|
||||
def _load_synonyms(self):
|
||||
"""Load fuzzy-matching synonym lists from YAML."""
|
||||
path = self.config_dir / "synonyms.yaml"
|
||||
if path.exists():
|
||||
with open(path, encoding="utf-8") as f:
|
||||
@@ -48,6 +83,7 @@ class ConfigManager:
|
||||
self._synonyms = data.get("synonyms", {})
|
||||
|
||||
def _load_type_configs(self):
|
||||
"""Load every known workbook-type YAML definition."""
|
||||
types_dir = self.config_dir / "types"
|
||||
if types_dir.exists():
|
||||
for type_file in types_dir.glob("*.yaml"):
|
||||
@@ -67,6 +103,7 @@ class ConfigManager:
|
||||
return self._db_table
|
||||
|
||||
def get_target_column_names(self) -> list[str]:
|
||||
"""Return target SQL column names in export order."""
|
||||
|
||||
return [c["name"] for c in self.get_db_schema()]
|
||||
|
||||
@@ -106,8 +143,71 @@ class ConfigManager:
|
||||
"""Return app settings dictionary."""
|
||||
return self._settings or {}
|
||||
|
||||
def get_analysis_config(self) -> dict:
|
||||
"""Return operator analysis policy settings."""
|
||||
return self.get_settings().get("analysis", {}) or {}
|
||||
|
||||
def get_ai_debug_log_config(self) -> dict:
|
||||
"""Return persistent AI debug-log settings with safe defaults."""
|
||||
raw = self.get_analysis_config().get("ai_debug_log", {}) or {}
|
||||
if not isinstance(raw, dict):
|
||||
raw = {}
|
||||
enabled = raw.get("enabled", True)
|
||||
if isinstance(enabled, str):
|
||||
enabled = enabled.strip().lower() not in {"0", "false", "no", "off"}
|
||||
return {
|
||||
"enabled": bool(enabled),
|
||||
"dir": str(raw.get("dir", "data/debug") or "data/debug"),
|
||||
"max_string_chars": int(raw.get("max_string_chars", 12000) or 12000),
|
||||
}
|
||||
|
||||
def get_ai_debug_log_dir(self) -> Path:
|
||||
"""Return the persistent AI debug-log directory."""
|
||||
raw = self.get_ai_debug_log_config().get("dir", "data/debug")
|
||||
path = Path(str(raw))
|
||||
return path if path.is_absolute() else self.config_dir.parent / path
|
||||
|
||||
def get_low_confidence_warning_threshold(self) -> float:
|
||||
"""Return confidence percentage below which user confirmation is required."""
|
||||
return float(self.get_analysis_config().get("low_confidence_warning_threshold", 40) or 40)
|
||||
|
||||
def should_require_low_confidence_confirmation(self) -> bool:
|
||||
"""Return whether low-confidence uploads need explicit user confirmation."""
|
||||
return bool(self.get_analysis_config().get("require_confirmation_below_threshold", True))
|
||||
|
||||
def get_ai_auto_accept_mapping_threshold(self) -> float:
|
||||
"""Return minimum model confidence for auto-accepting AI-only mapping additions.
|
||||
|
||||
Stored as a percentage in settings for operator readability, but accepts
|
||||
either 85 or 0.85. The returned value is always a 0-1 fraction.
|
||||
"""
|
||||
raw = float(self.get_analysis_config().get("ai_auto_accept_mapping_threshold", 85) or 85)
|
||||
value = raw / 100.0 if raw > 1 else raw
|
||||
return max(0.0, min(1.0, value))
|
||||
|
||||
def get_security_config(self) -> dict:
|
||||
"""Return admin/password security settings."""
|
||||
return self.get_settings().get("security", {}) or {}
|
||||
|
||||
def get_admin_password_hash(self) -> str:
|
||||
"""Return stored admin password hash, preferring Docker/runtime env override."""
|
||||
env_hash = os.getenv("ADMIN_PASSWORD_HASH", "").strip()
|
||||
if env_hash:
|
||||
return env_hash
|
||||
return str(self.get_security_config().get("admin_password_hash", "") or "")
|
||||
|
||||
def admin_reauth_required_for_mutations(self) -> bool:
|
||||
"""Return whether admin writes should ask for password again."""
|
||||
return bool(self.get_security_config().get("admin_reauth_required_for_mutations", True))
|
||||
|
||||
def get_tmp_blueprints_dir(self) -> Path:
|
||||
"""Return temporary blueprint proposal directory."""
|
||||
raw = str((self.get_settings().get("paths", {}) or {}).get("tmp_blueprints_dir", "data/tmp_blueprints") or "data/tmp_blueprints")
|
||||
path = Path(raw)
|
||||
return path if path.is_absolute() else self.config_dir.parent / path
|
||||
|
||||
def get_fuzzy_threshold(self) -> int:
|
||||
"""Return the fuzzy match threshold (0-100)."""
|
||||
|
||||
settings = self.get_settings()
|
||||
return settings.get("fuzzy", {}).get("default_threshold", 75)
|
||||
|
||||
@@ -116,47 +216,114 @@ class ConfigManager:
|
||||
settings = self.get_settings()
|
||||
return settings.get("fuzzy", {}).get("keyword_match_min", 2)
|
||||
|
||||
def get_key_fields(self) -> list[str]:
|
||||
"""Return key field names. At least one must be present to keep a row."""
|
||||
settings = self.get_settings()
|
||||
return settings.get("key_fields", ["generated_barcode", "item_name_eng", "item_name_jap"])
|
||||
|
||||
def get_llm_config(self) -> dict:
|
||||
"""Return the llm settings block with defaults for missing keys."""
|
||||
"""Return profile-based LLM settings with defaults for missing keys."""
|
||||
settings = self.get_settings()
|
||||
llm = settings.get("llm", {})
|
||||
llm = settings.get("llm", {}) or {}
|
||||
defaults = {
|
||||
"enabled": False,
|
||||
"base_url": "",
|
||||
"model": "gemma4:latest",
|
||||
"api_key": "",
|
||||
"api_key_env": "BNA_API_KEY",
|
||||
"timeout_seconds": 30,
|
||||
"temperature": 0.1,
|
||||
"active_profile": "local",
|
||||
"profiles": {},
|
||||
"auto_apply_confidence": 0.9,
|
||||
"fingerprint_auto_threshold": 80,
|
||||
"fingerprint_suggest_threshold": 60,
|
||||
"ssl_verify": True, # set to False for self-signed internal certs
|
||||
}
|
||||
defaults.update(llm)
|
||||
defaults["profiles"] = defaults.get("profiles") or {}
|
||||
return defaults
|
||||
|
||||
def get_active_llm_profile_config(self) -> dict | None:
|
||||
"""Return the active LLM profile merged with per-profile defaults."""
|
||||
cfg = self.get_llm_config()
|
||||
profile_id = str(cfg.get("active_profile", "local") or "local").strip()
|
||||
profiles = cfg.get("profiles") or {}
|
||||
if profile_id not in profiles:
|
||||
return None
|
||||
raw = profiles.get(profile_id) or {}
|
||||
profile_defaults = {
|
||||
"label": profile_id,
|
||||
"base_url": "",
|
||||
"model": "deepseek-chat",
|
||||
"api_key": "",
|
||||
"timeout_seconds": 30,
|
||||
"temperature": 0.1,
|
||||
"ssl_verify": False,
|
||||
"stream_response": True,
|
||||
"mode": "small",
|
||||
"max_sheet_rows": 80,
|
||||
"max_sheet_cols": 30,
|
||||
"max_candidates_per_sheet": 4,
|
||||
"sample_rows_per_candidate": 4,
|
||||
"max_mapping_columns": 40,
|
||||
}
|
||||
profile_defaults.update(raw)
|
||||
profile_defaults["profile"] = profile_id
|
||||
return profile_defaults
|
||||
|
||||
def is_llm_enabled(self) -> bool:
|
||||
"""True only if LLM enabled AND an API key is available."""
|
||||
"""True only if LLM is enabled and the active profile has an API key."""
|
||||
cfg = self.get_llm_config()
|
||||
return bool(cfg.get("enabled")) and self.get_llm_api_key() is not None
|
||||
|
||||
def get_llm_api_key(self) -> str | None:
|
||||
"""Read the API key: direct value first, then env var fallback."""
|
||||
import os
|
||||
cfg = self.get_llm_config()
|
||||
# Direct key stored in config (set via UI)
|
||||
direct = cfg.get("api_key", "")
|
||||
if direct:
|
||||
"""Read the API key from the active project LLM profile only."""
|
||||
profile = self.get_active_llm_profile_config()
|
||||
if not profile:
|
||||
return None
|
||||
direct = str(profile.get("api_key", "") or "").strip()
|
||||
if direct and not self._looks_like_redacted_secret(direct):
|
||||
return direct
|
||||
# Env var fallback
|
||||
env_var = cfg.get("api_key_env", "BNA_API_KEY")
|
||||
return os.environ.get(env_var)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _looks_like_redacted_secret(value: str) -> bool:
|
||||
"""True for placeholder strings produced by secret redaction, not real keys."""
|
||||
v = (value or "").strip().lower()
|
||||
return (
|
||||
not v
|
||||
or v.startswith("«redacted:")
|
||||
or v.startswith("<redacted")
|
||||
or v.startswith("[redacted")
|
||||
or v in {"redacted", "***", "********"}
|
||||
)
|
||||
|
||||
def resolve_llm_connection_config(self) -> dict | None:
|
||||
"""Resolve the effective OpenAI-compatible LLM config from active profile."""
|
||||
cfg = self.get_llm_config()
|
||||
if not cfg.get("enabled"):
|
||||
return None
|
||||
|
||||
profile = self.get_active_llm_profile_config()
|
||||
if not profile:
|
||||
return None
|
||||
|
||||
api_key = self.get_llm_api_key()
|
||||
base_url = str(profile.get("base_url", "") or "").strip()
|
||||
model = str(profile.get("model", "") or "").strip() or "deepseek-chat"
|
||||
if not api_key or not base_url:
|
||||
return None
|
||||
|
||||
budgets = {
|
||||
"max_sheet_rows": int(profile.get("max_sheet_rows", 80) or 80),
|
||||
"max_sheet_cols": int(profile.get("max_sheet_cols", 30) or 30),
|
||||
"max_candidates_per_sheet": int(profile.get("max_candidates_per_sheet", 4) or 4),
|
||||
"sample_rows_per_candidate": int(profile.get("sample_rows_per_candidate", 4) or 4),
|
||||
"max_mapping_columns": int(profile.get("max_mapping_columns", 40) or 40),
|
||||
}
|
||||
return {
|
||||
"profile": profile.get("profile"),
|
||||
"label": profile.get("label") or profile.get("profile"),
|
||||
"mode": profile.get("mode", "small"),
|
||||
"api_key": api_key,
|
||||
"base_url": base_url,
|
||||
"model": model,
|
||||
"timeout_seconds": profile.get("timeout_seconds", 30),
|
||||
"temperature": profile.get("temperature", 0.1),
|
||||
"ssl_verify": profile.get("ssl_verify", False),
|
||||
"stream_response": bool(profile.get("stream_response", True)),
|
||||
"budgets": budgets,
|
||||
"source": "project",
|
||||
}
|
||||
|
||||
def get_fingerprint_thresholds(self) -> tuple[int, int]:
|
||||
"""Return (auto_threshold, suggest_threshold)."""
|
||||
@@ -192,3 +359,28 @@ class ConfigManager:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
yaml.dump({"synonyms": synonyms}, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
|
||||
self._synonyms = synonyms
|
||||
|
||||
def load_type_support_notes(self, type_id: str) -> dict | None:
|
||||
"""Load optional AI support notes for a workbook Type."""
|
||||
path = self.config_dir / "type_notes" / f"{self._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 {}
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
def save_type_support_notes(self, type_id: str, notes: dict) -> Path:
|
||||
"""Save AI support notes for a workbook Type and return the path."""
|
||||
notes_dir = self.config_dir / "type_notes"
|
||||
notes_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_type = self._safe_type_id(type_id)
|
||||
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")
|
||||
return path
|
||||
|
||||
@staticmethod
|
||||
def _safe_type_id(type_id: str) -> str:
|
||||
"""Return a filesystem-safe type id."""
|
||||
safe = "".join(ch if ch.isalnum() or ch in {"_", "-"} else "_" for ch in str(type_id or "").strip())
|
||||
return safe or "unknown"
|
||||
@@ -20,6 +20,7 @@ class ConfigValidator:
|
||||
"""Validates a type config dictionary before saving."""
|
||||
|
||||
def __init__(self, valid_target_columns: list[str]):
|
||||
"""Create a validator constrained to the known target SQL columns."""
|
||||
self.valid_targets = set(valid_target_columns)
|
||||
|
||||
def validate(self, config: dict) -> ValidationResult:
|
||||
@@ -32,6 +33,7 @@ class ConfigValidator:
|
||||
return result
|
||||
|
||||
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", [])):
|
||||
target = m.get("target", "")
|
||||
if not target:
|
||||
@@ -42,6 +44,7 @@ class ConfigValidator:
|
||||
)
|
||||
|
||||
def _check_mapping_required(self, config: dict, result: ValidationResult):
|
||||
"""Warn when important key fields are not mapped."""
|
||||
for i, m in enumerate(config.get("mapping", [])):
|
||||
if m.get("required") and not m.get("source_patterns"):
|
||||
result.warnings.append(
|
||||
@@ -50,6 +53,7 @@ class ConfigValidator:
|
||||
)
|
||||
|
||||
def _check_sheet_relations(self, config: dict, result: ValidationResult):
|
||||
"""Validate cross-sheet relation shape and required fields."""
|
||||
rels = config.get("sheet_relations", [])
|
||||
seen_names: set[str] = set()
|
||||
|
||||
@@ -115,6 +119,7 @@ class ConfigValidator:
|
||||
)
|
||||
|
||||
def _check_structure(self, config: dict, result: ValidationResult):
|
||||
"""Validate basic header-detection settings."""
|
||||
struct = config.get("structure", {})
|
||||
hp = struct.get("header_pattern", {})
|
||||
if not hp.get("keywords"):
|
||||
|
||||
@@ -1,364 +0,0 @@
|
||||
"""Transform parsed Excel data into target schema, validate rows, handle multi-sheet combining."""
|
||||
import fnmatch
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.excel_parser import ParsedWorkbook, ParsedSheet, FormField
|
||||
from services.fuzzy_matcher import MatchResult, FormFieldMatch
|
||||
from services.value_matcher import ValueMatcher
|
||||
|
||||
|
||||
@dataclass
|
||||
class DroppedRow:
|
||||
"""A row flagged for dropping."""
|
||||
source_sheet: str
|
||||
source_row: int # 1-indexed row in source
|
||||
drop_reason: str
|
||||
data: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProcessedData:
|
||||
"""Result of data processing and validation."""
|
||||
rows: list[dict[str, Any]] = field(default_factory=list) # kept rows
|
||||
dropped_rows: list[DroppedRow] = field(default_factory=list)
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
target_columns: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
class DataProcessor:
|
||||
"""Transforms and validates parsed Excel data against target schema."""
|
||||
|
||||
def __init__(self, config_manager: ConfigManager):
|
||||
self.cm = config_manager
|
||||
|
||||
def process(
|
||||
self,
|
||||
workbook: ParsedWorkbook,
|
||||
match_results: list[MatchResult],
|
||||
form_matches: list[FormFieldMatch],
|
||||
type_id: str | None = None,
|
||||
) -> ProcessedData:
|
||||
"""
|
||||
Transform parsed sheets into target schema rows.
|
||||
|
||||
1. Get column index mapping from match results
|
||||
2. For each included sheet, extract rows
|
||||
3. Apply form field propagation
|
||||
4. Combine multi-sheet data
|
||||
5. Validate required fields → flag dropped rows
|
||||
"""
|
||||
target_columns = self.cm.get_target_column_names()
|
||||
type_config = self.cm.get_type_config(type_id) if type_id else None
|
||||
|
||||
# Build source header text → target column mapping.
|
||||
# match_results come from the global deduplicated header list across all
|
||||
# sheets, so we CANNOT use their list index as a column index. Instead we
|
||||
# map by header text, then resolve to the correct column index per sheet.
|
||||
header_to_target: dict[str, str] = {}
|
||||
for mr in match_results:
|
||||
if mr.matched_target and mr.source_header:
|
||||
header_to_target[mr.source_header] = mr.matched_target
|
||||
|
||||
# Build form field propagation map
|
||||
form_data: dict[str, Any] = {}
|
||||
for fm in form_matches:
|
||||
if fm.matched_target:
|
||||
# If conflict, first value wins
|
||||
if fm.matched_target not in form_data:
|
||||
form_data[fm.matched_target] = fm.value
|
||||
|
||||
# Key fields: at least ONE must be present to keep the row.
|
||||
# Configurable via settings.yaml — defaults to generated_barcode + item names.
|
||||
key_fields: list[str] = self.cm.get_key_fields()
|
||||
|
||||
result = ProcessedData(target_columns=target_columns)
|
||||
|
||||
for sheet in workbook.sheets:
|
||||
if sheet.header_row == 0 or sheet.data_end_row < sheet.data_start_row:
|
||||
continue # Skip sheets with no detected data
|
||||
|
||||
# Resolve header_text → target to column_idx → target FOR THIS SHEET.
|
||||
# Different sheets have different column layouts, so this must be
|
||||
# rebuilt per sheet using the sheet's own detected_headers.
|
||||
sheet_col_to_target: dict[int, str] = {}
|
||||
for col_idx, hdr in enumerate(sheet.detected_headers):
|
||||
if hdr:
|
||||
target = header_to_target.get(hdr)
|
||||
if target:
|
||||
sheet_col_to_target[col_idx] = target
|
||||
|
||||
for row_idx in range(sheet.data_start_row - 1, min(sheet.data_end_row, len(sheet.raw_data))):
|
||||
source_data = sheet.raw_data[row_idx]
|
||||
|
||||
# Build target row
|
||||
row_dict: dict[str, Any] = {}
|
||||
for col_idx, target in sheet_col_to_target.items():
|
||||
if col_idx < len(source_data):
|
||||
row_dict[target] = source_data[col_idx]
|
||||
|
||||
# Apply form field propagation
|
||||
for target, value in form_data.items():
|
||||
if target not in row_dict or row_dict[target] is None or str(row_dict[target]).strip() == "":
|
||||
row_dict[target] = value
|
||||
|
||||
# Fill missing target columns with None
|
||||
for tc in target_columns:
|
||||
if tc not in row_dict:
|
||||
row_dict[tc] = None
|
||||
|
||||
# Validate key fields: at least ONE must be present to keep the row
|
||||
missing_keys = []
|
||||
all_missing = True
|
||||
for kf in key_fields:
|
||||
val = row_dict.get(kf)
|
||||
if val is not None and not (isinstance(val, str) and val.strip() == ""):
|
||||
all_missing = False
|
||||
break
|
||||
else:
|
||||
missing_keys.append(kf)
|
||||
|
||||
if all_missing:
|
||||
result.dropped_rows.append(DroppedRow(
|
||||
source_sheet=sheet.name,
|
||||
source_row=row_idx + 1,
|
||||
drop_reason=f"No key field present (checked: {', '.join(key_fields)})",
|
||||
data=row_dict,
|
||||
))
|
||||
else:
|
||||
result.rows.append(row_dict)
|
||||
|
||||
# ── Apply cross-sheet relations ──
|
||||
if type_config:
|
||||
self._apply_sheet_relations(workbook, result, type_config, match_results)
|
||||
|
||||
# Check for duplicate barcodes
|
||||
barcodes_seen: dict[str, int] = {}
|
||||
for i, row in enumerate(result.rows):
|
||||
bc = str(row.get("generated_barcode", "")).strip()
|
||||
if bc and bc in barcodes_seen:
|
||||
result.warnings.append(f"Duplicate barcode '{bc}' at rows {barcodes_seen[bc]+1} and {i+1}")
|
||||
elif bc:
|
||||
barcodes_seen[bc] = i
|
||||
|
||||
# Warn if all rows dropped
|
||||
if len(result.dropped_rows) > 0 and len(result.rows) == 0:
|
||||
result.warnings.append("All rows flagged for drop — no data will be exported. Please review required field mappings.")
|
||||
|
||||
return result
|
||||
|
||||
def _apply_sheet_relations(
|
||||
self, workbook: ParsedWorkbook, result: ProcessedData, type_config: dict,
|
||||
match_results: list[MatchResult],
|
||||
):
|
||||
"""Apply cross-sheet value matching and join as defined in sheet_relations.
|
||||
|
||||
Works at the raw-sheet level: finds keys in source sheet rows, matches
|
||||
against target sheet rows via ValueMatcher, merges matched column values
|
||||
into result rows.
|
||||
"""
|
||||
vm = ValueMatcher()
|
||||
relations = type_config.get("sheet_relations", [])
|
||||
|
||||
if not relations:
|
||||
return
|
||||
|
||||
# Build resolvers to map a source header text to a target DB column.
|
||||
# A brought-over target column (e.g. 商品名/英語) may not be in THIS
|
||||
# type's mapping, so we resolve via three layers:
|
||||
# 1. match_results header→target (confirmed by the matcher)
|
||||
# 2. this type's mapping source_patterns
|
||||
# 3. synonyms (reverse lookup: which target lists this as a synonym)
|
||||
mapping_entries = type_config.get("mapping", [])
|
||||
match_map: dict[str, str] = {
|
||||
mr.source_header: mr.matched_target
|
||||
for mr in match_results if mr.matched_target
|
||||
}
|
||||
synonyms = self.cm.get_synonyms()
|
||||
syn_reverse: dict[str, str] = {}
|
||||
for target, syn_list in synonyms.items():
|
||||
for s in syn_list:
|
||||
syn_reverse[s] = target
|
||||
|
||||
def _source_to_target(src_col: str) -> str | None:
|
||||
"""Find the target column that a source column header maps to."""
|
||||
if not src_col:
|
||||
return None
|
||||
# Layer 1: matcher-confirmed map
|
||||
if src_col in match_map:
|
||||
return match_map[src_col]
|
||||
# Layer 2: this type's mapping
|
||||
for me in mapping_entries:
|
||||
if src_col in me.get("source_patterns", []):
|
||||
return me["target"]
|
||||
# Layer 3: synonyms reverse lookup
|
||||
if src_col in syn_reverse:
|
||||
return syn_reverse[src_col]
|
||||
return None
|
||||
|
||||
# Index sheets by name for pattern lookup
|
||||
sheet_index: dict[str, ParsedSheet] = {}
|
||||
for sheet in workbook.sheets:
|
||||
sheet_index[sheet.name] = sheet
|
||||
|
||||
for rel in relations:
|
||||
src_cfg = rel.get("source", {})
|
||||
tgt_cfg = rel.get("target", {})
|
||||
join_cfg = rel.get("join", {})
|
||||
join_type = join_cfg.get("type", "lookup")
|
||||
join_columns_spec = join_cfg.get("columns", "all")
|
||||
src_key_col = src_cfg.get("key_column", "")
|
||||
|
||||
# Find source and target sheets by fnmatch pattern
|
||||
src_pattern = src_cfg.get("sheet_pattern", "*")
|
||||
tgt_pattern = tgt_cfg.get("sheet_pattern", "*")
|
||||
|
||||
src_sheets = [s for name, s in sheet_index.items()
|
||||
if fnmatch.fnmatch(name, src_pattern)]
|
||||
tgt_sheets = [s for name, s in sheet_index.items()
|
||||
if fnmatch.fnmatch(name, tgt_pattern)]
|
||||
|
||||
if not src_sheets or not tgt_sheets:
|
||||
result.warnings.append(
|
||||
f"Sheet relation '{rel.get('name', 'unnamed')}': "
|
||||
f"no sheet matched source='{src_pattern}' or target='{tgt_pattern}'"
|
||||
)
|
||||
continue
|
||||
|
||||
match_rules = tgt_cfg.get("match_rules", [])
|
||||
|
||||
# Determine which target column holds the source key value
|
||||
src_key_target = _source_to_target(src_key_col)
|
||||
|
||||
joined_rows: list[dict] = []
|
||||
inner_dropped: list[dict] = []
|
||||
|
||||
for row_dict in result.rows:
|
||||
# Look up the key — try target-column name first, then raw source name
|
||||
key_val = row_dict.get(src_key_target or src_key_col)
|
||||
if key_val is None:
|
||||
key_val = row_dict.get(src_key_col)
|
||||
key_str = str(key_val).strip() if key_val is not None else ""
|
||||
|
||||
if not key_str:
|
||||
if join_type == "inner":
|
||||
inner_dropped.append(row_dict)
|
||||
else:
|
||||
joined_rows.append(row_dict)
|
||||
continue
|
||||
|
||||
# Search target sheets
|
||||
found_match = False
|
||||
|
||||
# Detect if any rule uses reverse_lookup strategy
|
||||
uses_reverse = any(
|
||||
r.get("strategy", "").startswith("reverse_")
|
||||
for r in match_rules
|
||||
)
|
||||
|
||||
for tgt_sheet in tgt_sheets:
|
||||
tgt_headers = tgt_sheet.detected_headers
|
||||
tgt_raw = tgt_sheet.raw_data
|
||||
|
||||
if uses_reverse:
|
||||
# reverse_lookup: scan target column values,
|
||||
# check each against the source cell
|
||||
# Normalize strategy names: strip "reverse_" prefix
|
||||
reverse_rules = []
|
||||
for r in match_rules:
|
||||
s = r.get("strategy", "contains")
|
||||
if s.startswith("reverse_"):
|
||||
reverse_rules.append({
|
||||
**r,
|
||||
"strategy": s[len("reverse_"):], # e.g. "token_match"
|
||||
})
|
||||
result_match = vm.reverse_lookup(
|
||||
key_str, tgt_raw, tgt_headers, reverse_rules
|
||||
)
|
||||
if result_match is None:
|
||||
continue
|
||||
else:
|
||||
matches = vm.match(key_str, tgt_raw, tgt_headers, match_rules)
|
||||
if not matches:
|
||||
continue
|
||||
result_match = matches[0]
|
||||
|
||||
# First matching row wins
|
||||
matched_raw_row = tgt_raw[result_match.target_row_idx]
|
||||
|
||||
# Determine which columns to copy from target
|
||||
if join_columns_spec == "all":
|
||||
col_indices = list(range(len(tgt_headers)))
|
||||
elif isinstance(join_columns_spec, list):
|
||||
col_indices = [
|
||||
i for i, h in enumerate(tgt_headers)
|
||||
if h in join_columns_spec
|
||||
]
|
||||
else:
|
||||
col_indices = []
|
||||
|
||||
for ci in col_indices:
|
||||
if ci >= len(matched_raw_row) or ci >= len(tgt_headers):
|
||||
continue
|
||||
hdr = tgt_headers[ci]
|
||||
if not hdr:
|
||||
continue
|
||||
val = matched_raw_row[ci]
|
||||
# Map the source header to a target column
|
||||
hdr_target = _source_to_target(hdr) or hdr
|
||||
# Fill target: prefer the more complete value.
|
||||
# If existing is empty, take the new value. If both are
|
||||
# non-empty, keep whichever is longer (the looked-up
|
||||
# name like 'GRADE A:Figure' beats a partial 'GRADE A:').
|
||||
existing = row_dict.get(hdr_target)
|
||||
existing_str = str(existing).strip() if existing is not None else ""
|
||||
new_str = str(val).strip() if val is not None else ""
|
||||
if not existing_str:
|
||||
row_dict[hdr_target] = val
|
||||
elif new_str and len(new_str) > len(existing_str):
|
||||
row_dict[hdr_target] = val
|
||||
|
||||
found_match = True
|
||||
break # one match per row
|
||||
|
||||
if join_type == "inner" and not found_match:
|
||||
inner_dropped.append(row_dict)
|
||||
else:
|
||||
joined_rows.append(row_dict)
|
||||
|
||||
if join_type == "inner":
|
||||
old_count = len(result.rows)
|
||||
result.rows = joined_rows
|
||||
for dr in inner_dropped:
|
||||
result.dropped_rows.append(DroppedRow(
|
||||
source_sheet="(inner join)",
|
||||
source_row=0,
|
||||
drop_reason=f"Sheet relation '{rel.get('name', '')}': no match for key '{src_key_col}'",
|
||||
data=dr,
|
||||
))
|
||||
if len(inner_dropped) > 0:
|
||||
result.warnings.append(
|
||||
f"Sheet relation '{rel.get('name', 'unnamed')}': "
|
||||
f"inner join dropped {len(inner_dropped)}/{old_count} rows "
|
||||
f"(no match for key '{src_key_col}')"
|
||||
)
|
||||
|
||||
def restore_row(self, processed: ProcessedData, dropped_index: int) -> ProcessedData:
|
||||
"""Move a dropped row back to the kept rows list."""
|
||||
if 0 <= dropped_index < len(processed.dropped_rows):
|
||||
row = processed.dropped_rows.pop(dropped_index)
|
||||
processed.rows.append(row.data)
|
||||
return processed
|
||||
|
||||
def drop_row(self, processed: ProcessedData, kept_index: int, reason: str = "User flagged") -> ProcessedData:
|
||||
"""Move a kept row to dropped rows."""
|
||||
if 0 <= kept_index < len(processed.rows):
|
||||
row_data = processed.rows.pop(kept_index)
|
||||
processed.dropped_rows.append(DroppedRow(
|
||||
source_sheet="(user action)",
|
||||
source_row=kept_index + 1,
|
||||
drop_reason=reason,
|
||||
data=row_data,
|
||||
))
|
||||
return processed
|
||||
@@ -4,10 +4,9 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from utils.helpers import tokenize, normalize_header
|
||||
from utils.helpers import normalize_header
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -48,6 +47,7 @@ class ExcelParser:
|
||||
"""Parses Excel files and detects structure."""
|
||||
|
||||
def __init__(self, config_manager: ConfigManager):
|
||||
"""Store configuration and known workbook-type hints for parsing."""
|
||||
self.cm = config_manager
|
||||
|
||||
def parse(self, file_path: str | Path, type_id: str | None = None) -> ParsedWorkbook:
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Data transfer objects consumed by the formal Excel export service."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class DroppedRow:
|
||||
"""A source row excluded from the formal export."""
|
||||
|
||||
source_sheet: str
|
||||
source_row: int
|
||||
drop_reason: str
|
||||
data: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProcessedData:
|
||||
"""SQL-shaped rows and optional export diagnostics."""
|
||||
|
||||
rows: list[dict[str, Any]] = field(default_factory=list)
|
||||
dropped_rows: list[DroppedRow] = field(default_factory=list)
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
target_columns: list[str] = field(default_factory=list)
|
||||
@@ -7,7 +7,7 @@ import openpyxl
|
||||
from openpyxl.styles import Font, PatternFill, Alignment
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from services.data_processor import ProcessedData
|
||||
from services.export_models import ProcessedData
|
||||
|
||||
HEADER_FILL = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
|
||||
HEADER_FONT = Font(color="FFFFFF", bold=True, size=11)
|
||||
@@ -65,6 +65,7 @@ class ExportService:
|
||||
sheet_name: str,
|
||||
include_diagnostics: bool,
|
||||
) -> openpyxl.Workbook:
|
||||
"""Build the workbook object before it is saved or returned as bytes."""
|
||||
wb = openpyxl.Workbook()
|
||||
|
||||
table_ws = wb.active
|
||||
@@ -98,6 +99,7 @@ class ExportService:
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
def _write_dropped_rows_sheet(self, wb, processed: ProcessedData, columns: list[str]) -> None:
|
||||
"""Write optional diagnostics for rows excluded from export."""
|
||||
ws = wb.create_sheet("Dropped Rows")
|
||||
drop_headers = ["Source Sheet", "Source Row", "Drop Reason"] + columns
|
||||
for col_idx, header in enumerate(drop_headers, 1):
|
||||
@@ -117,6 +119,7 @@ class ExportService:
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
def _write_summary_sheet(self, wb, processed: ProcessedData) -> None:
|
||||
"""Write optional warning/statistics diagnostics."""
|
||||
if not processed.warnings:
|
||||
return
|
||||
ws = wb.create_sheet("Summary")
|
||||
@@ -129,6 +132,7 @@ class ExportService:
|
||||
|
||||
@staticmethod
|
||||
def _safe_sheet_name(name: str) -> str:
|
||||
"""Return an Excel-safe worksheet name no longer than 31 characters."""
|
||||
clean = "".join("_" if ch in r"[]:*?/\\" else ch for ch in (name or "pre_item_master"))
|
||||
return clean[:31] or "pre_item_master"
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Schema-aware output value normalization."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
|
||||
|
||||
def transform_field_value(cm: ConfigManager, field_name: str, value: Any) -> Any:
|
||||
"""Normalize a single output value according to the DB schema.
|
||||
|
||||
Rules are intentionally conservative:
|
||||
- string-like DB fields (varchar/text/char) are trim-stripped;
|
||||
- generated_barcode additionally removes all whitespace, because barcode
|
||||
values must not contain spaces.
|
||||
"""
|
||||
if value is None or isinstance(value, (datetime, date, int, float)):
|
||||
return value
|
||||
|
||||
schema_by_name = {col.get("name"): str(col.get("type", "")).lower() for col in cm.get_db_schema()}
|
||||
db_type = schema_by_name.get(field_name, "")
|
||||
if not _is_string_type(db_type) and field_name != "generated_barcode":
|
||||
return value
|
||||
|
||||
text = str(value).strip()
|
||||
if field_name == "generated_barcode":
|
||||
text = re.sub(r"\s+", "", text)
|
||||
return text
|
||||
|
||||
|
||||
def _is_string_type(db_type: str) -> bool:
|
||||
return any(token in db_type for token in ("char", "text", "varchar"))
|
||||
+17
-41
@@ -1,8 +1,5 @@
|
||||
"""Fingerprint recognition: identify an uploaded Excel's format by comparing
|
||||
its detected headers against known type signatures (fuzzy)."""
|
||||
import json
|
||||
"""Fingerprint recognition: identify an uploaded Excel format from type config."""
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from rapidfuzz import fuzz
|
||||
|
||||
@@ -19,15 +16,10 @@ class FingerprintMatch:
|
||||
|
||||
|
||||
class Fingerprint:
|
||||
"""Recognizes an uploaded workbook's format."""
|
||||
"""Recognizes an uploaded workbook's format using tracked YAML config only."""
|
||||
|
||||
def __init__(self, config_manager: ConfigManager):
|
||||
self.cm = config_manager
|
||||
self.cache_path = (
|
||||
config_manager.config_dir / "fingerprints.json"
|
||||
if hasattr(config_manager, "config_dir")
|
||||
else Path("config/fingerprints.json")
|
||||
)
|
||||
|
||||
def compute_signature(self, parsed_workbook: ParsedWorkbook) -> dict[str, list[str]]:
|
||||
"""Return {sheet_name: [detected_headers]} for a parsed workbook."""
|
||||
@@ -39,9 +31,12 @@ class Fingerprint:
|
||||
return sig
|
||||
|
||||
def recognize(self, signature: dict[str, list[str]]) -> list[FingerprintMatch]:
|
||||
"""Score signature against every known type. Returns matches sorted
|
||||
by score descending. Uses saved fingerprints if present, else the
|
||||
type's mapping source_patterns."""
|
||||
"""Score uploaded headers against each type's configured signature.
|
||||
|
||||
The score is generic: average best fuzzy match of every expected header
|
||||
from the type config against the uploaded workbook headers. There are no
|
||||
workbook-specific code branches or forced scores.
|
||||
"""
|
||||
all_headers: list[str] = []
|
||||
for hdrs in signature.values():
|
||||
all_headers.extend(hdrs)
|
||||
@@ -62,16 +57,18 @@ class Fingerprint:
|
||||
return results
|
||||
|
||||
def _expected_headers(self, type_id: str) -> list[str]:
|
||||
"""Headers we expect for a type: saved fingerprint, else source_patterns."""
|
||||
saved = self.get_saved(type_id)
|
||||
if saved:
|
||||
hdrs = []
|
||||
for v in saved.values():
|
||||
hdrs.extend(v)
|
||||
return hdrs
|
||||
"""Headers expected for a type, read from tracked YAML config.
|
||||
|
||||
`fingerprint_headers` is the preferred recognition signature. If it is
|
||||
absent, mapping source patterns are used as a generic fallback for simple
|
||||
or newly authored type configs. Nothing is read from local runtime cache.
|
||||
"""
|
||||
cfg = self.cm.get_type_config(type_id)
|
||||
if not cfg:
|
||||
return []
|
||||
explicit = [str(h).strip() for h in cfg.get("fingerprint_headers", []) if str(h).strip()]
|
||||
if explicit:
|
||||
return explicit
|
||||
hdrs: list[str] = []
|
||||
for m in cfg.get("mapping", []):
|
||||
hdrs.extend(m.get("source_patterns", []))
|
||||
@@ -92,24 +89,3 @@ class Fingerprint:
|
||||
)
|
||||
total += best
|
||||
return round(total / len(expected), 1)
|
||||
|
||||
def save(self, type_id: str, signature: dict[str, list[str]]) -> None:
|
||||
"""Persist a type's signature to the cache file."""
|
||||
data = self._load_cache()
|
||||
data[type_id] = signature
|
||||
self.cache_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.cache_path.write_text(
|
||||
json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
|
||||
def get_saved(self, type_id: str) -> dict[str, list[str]] | None:
|
||||
"""Return a saved signature for a type, or None."""
|
||||
return self._load_cache().get(type_id)
|
||||
|
||||
def _load_cache(self) -> dict:
|
||||
if not self.cache_path.exists():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(self.cache_path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return {}
|
||||
@@ -2,7 +2,7 @@
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from rapidfuzz import fuzz, process
|
||||
from rapidfuzz import fuzz
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from utils.helpers import tokenize, normalize_header
|
||||
@@ -32,6 +32,7 @@ class FuzzyMatcher:
|
||||
"""Matches source column headers to target DB columns via 3-pass algorithm."""
|
||||
|
||||
def __init__(self, config_manager: ConfigManager):
|
||||
"""Create a fuzzy matcher with project thresholds, synonyms, and type configs."""
|
||||
self.cm = config_manager
|
||||
|
||||
def match(
|
||||
@@ -151,7 +152,6 @@ class FuzzyMatcher:
|
||||
))
|
||||
|
||||
return results
|
||||
|
||||
def match_form_fields(
|
||||
self,
|
||||
form_fields: list, # list of FormField from excel_parser
|
||||
@@ -191,61 +191,3 @@ class FuzzyMatcher:
|
||||
|
||||
return results
|
||||
|
||||
def get_unmatched_targets(
|
||||
self,
|
||||
match_results: list[MatchResult],
|
||||
type_id: str | None = None,
|
||||
) -> list[str]:
|
||||
"""Return target column names that have no source mapped."""
|
||||
all_targets = set(self.cm.get_target_column_names())
|
||||
matched = {mr.matched_target for mr in match_results if mr.matched_target}
|
||||
return sorted(all_targets - matched)
|
||||
|
||||
def auto_detect_type(self, parsed_workbook) -> str | None:
|
||||
"""
|
||||
Auto-detect the best matching type by scoring all type configs
|
||||
against the detected headers and form field labels.
|
||||
|
||||
Returns the type_id with the highest aggregate keyword match score,
|
||||
or None if no type scores above threshold.
|
||||
"""
|
||||
from services.excel_parser import ParsedWorkbook
|
||||
|
||||
all_type_ids = self.cm.get_all_type_ids()
|
||||
if not all_type_ids:
|
||||
return None
|
||||
|
||||
# Collect all text from headers and form field labels
|
||||
all_text = []
|
||||
for sheet in parsed_workbook.sheets:
|
||||
all_text.extend(sheet.detected_headers)
|
||||
for ff in sheet.form_fields:
|
||||
all_text.append(ff.label)
|
||||
|
||||
combined = " ".join(t for t in all_text if t).lower()
|
||||
if not combined:
|
||||
return None
|
||||
|
||||
scores = {}
|
||||
for type_id in all_type_ids:
|
||||
cfg = self.cm.get_type_config(type_id)
|
||||
if not cfg:
|
||||
continue
|
||||
keywords = cfg.get("structure", {}).get("header_pattern", {}).get("keywords", [])
|
||||
if not keywords:
|
||||
continue
|
||||
# Score = how many keywords appear in the combined text
|
||||
hit_count = sum(1 for kw in keywords if kw.lower() in combined)
|
||||
scores[type_id] = hit_count
|
||||
|
||||
if not scores:
|
||||
return None
|
||||
|
||||
best_type = max(scores, key=scores.get)
|
||||
best_score = scores[best_type]
|
||||
|
||||
# Require at least 2 keyword hits to auto-detect
|
||||
if best_score >= 2:
|
||||
return best_type
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
"""Build reusable non-LLM type configs from a confirmed analysis blueprint."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def slugify_type_id(name: str) -> str:
|
||||
"""Return a safe config/type id from a user-visible format name."""
|
||||
slug = re.sub(r"[^a-zA-Z0-9]+", "_", (name or "").strip().lower()).strip("_")
|
||||
return slug or "learned_format"
|
||||
|
||||
|
||||
def build_blueprint_summary(blueprint: dict[str, Any] | None) -> dict[str, int]:
|
||||
"""Return small counts for UI preview cards."""
|
||||
if not blueprint:
|
||||
return {"sheets": 0, "links": 0, "mappings": 0}
|
||||
groups = blueprint.get("groups", []) or []
|
||||
return {
|
||||
"sheets": len(blueprint.get("summaries", []) or []),
|
||||
"links": sum(len(_get(g, "links", [])) for g in groups),
|
||||
"mappings": len(blueprint.get("mappings", []) or []),
|
||||
}
|
||||
|
||||
|
||||
def build_learned_type_config(name: str, blueprint: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Convert a confirmed analysis blueprint into the app's reusable type YAML.
|
||||
|
||||
The saved config is intentionally compatible with the deterministic parser,
|
||||
fingerprint recognition, fuzzy matcher, and workbook analyzer fallback path.
|
||||
It does not require an LLM when the same format appears again.
|
||||
"""
|
||||
type_id = slugify_type_id(name)
|
||||
summaries = blueprint.get("summaries", []) or []
|
||||
groups = blueprint.get("groups", []) or []
|
||||
mappings = blueprint.get("mappings", []) or []
|
||||
|
||||
keywords = _collect_keywords(summaries, mappings)
|
||||
fingerprint_headers = _collect_fingerprint_headers(summaries, mappings)
|
||||
mapping_entries = _build_mapping_entries(mappings)
|
||||
shared_labels = _collect_shared_labels(summaries)
|
||||
form_entries = [
|
||||
{
|
||||
"source_patterns": [entry["source_patterns"][0]],
|
||||
"target": entry["target"],
|
||||
"propagate": True,
|
||||
}
|
||||
for entry in mapping_entries
|
||||
if entry["source_patterns"][0] in shared_labels
|
||||
]
|
||||
|
||||
cfg: dict[str, Any] = {
|
||||
"type_id": type_id,
|
||||
"label": name.strip() or type_id,
|
||||
"category": "learned",
|
||||
"structure": {
|
||||
"header_pattern": {
|
||||
"keywords": keywords,
|
||||
"strategy": "max_keyword_match",
|
||||
},
|
||||
"data_start_offset": 1,
|
||||
"sheets": [
|
||||
{
|
||||
"name": _get(s, "sheet_name", ""),
|
||||
"role": _get(s, "sheet_type", "other"),
|
||||
"header_row": int(_get(s, "header_row", 1) or 1),
|
||||
}
|
||||
for s in summaries
|
||||
if _get(s, "sheet_name", "")
|
||||
],
|
||||
},
|
||||
"mapping": mapping_entries,
|
||||
"form_fields": form_entries,
|
||||
"sheet_combine": {"strategy": "merge_blueprint" if groups else "single_or_append"},
|
||||
"fingerprint_headers": fingerprint_headers,
|
||||
}
|
||||
|
||||
relations = _build_sheet_relations(groups)
|
||||
if relations:
|
||||
cfg["sheet_relations"] = relations
|
||||
return cfg
|
||||
|
||||
|
||||
def dump_learned_type_yaml(config: dict[str, Any]) -> str:
|
||||
"""Render a learned type config as readable YAML for preview/download."""
|
||||
return yaml.dump(config, allow_unicode=True, default_flow_style=False, sort_keys=False)
|
||||
|
||||
|
||||
def _get(obj: Any, name: str, default: Any = None) -> Any:
|
||||
if isinstance(obj, dict):
|
||||
return obj.get(name, default)
|
||||
return getattr(obj, name, default)
|
||||
|
||||
|
||||
def _collect_keywords(summaries: list[Any], mappings: list[Any]) -> list[str]:
|
||||
values: list[str] = []
|
||||
for mapping in mappings:
|
||||
col = str(_get(mapping, "excel_column", "") or "").strip()
|
||||
if col:
|
||||
values.append(col)
|
||||
for summary in summaries:
|
||||
for col in _get(summary, "columns", []) or []:
|
||||
header = str(_get(col, "header", "") or "").strip()
|
||||
if header:
|
||||
values.append(header)
|
||||
return _unique(values)[:60]
|
||||
|
||||
|
||||
def _collect_fingerprint_headers(summaries: list[Any], mappings: list[Any]) -> list[str]:
|
||||
"""Return a compact recognition signature for the learned type config."""
|
||||
values: list[str] = []
|
||||
for mapping in mappings:
|
||||
col = str(_get(mapping, "excel_column", "") or "").strip()
|
||||
if col:
|
||||
values.append(col)
|
||||
for summary in summaries:
|
||||
for shared in _get(summary, "shared_values", []) or []:
|
||||
label = str(_get(shared, "label", "") or "").strip()
|
||||
if label:
|
||||
values.append(label)
|
||||
for summary in summaries:
|
||||
for col in _get(summary, "columns", []) or []:
|
||||
header = str(_get(col, "header", "") or "").strip()
|
||||
if header:
|
||||
values.append(header)
|
||||
return _unique(values)[:40]
|
||||
|
||||
|
||||
def _build_mapping_entries(mappings: list[Any]) -> list[dict[str, Any]]:
|
||||
entries: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for mapping in mappings:
|
||||
excel = str(_get(mapping, "excel_column", "") or "").strip()
|
||||
target = str(_get(mapping, "sql_target", "") or "").strip()
|
||||
if not excel or not target:
|
||||
continue
|
||||
key = (excel, target)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
confidence = float(_get(mapping, "confidence", 0.0) or 0.0)
|
||||
entries.append({
|
||||
"source_patterns": [excel],
|
||||
"target": target,
|
||||
"fuzzy_weight": round(max(0.0, min(1.0, confidence)), 2),
|
||||
"required": confidence >= 0.9,
|
||||
"description": str(_get(mapping, "reason", "") or target),
|
||||
})
|
||||
return entries
|
||||
|
||||
|
||||
def _collect_shared_labels(summaries: list[Any]) -> set[str]:
|
||||
labels: set[str] = set()
|
||||
for summary in summaries:
|
||||
for shared in _get(summary, "shared_values", []) or []:
|
||||
label = str(_get(shared, "label", "") or "").strip()
|
||||
if label:
|
||||
labels.add(label)
|
||||
return labels
|
||||
|
||||
|
||||
def _build_sheet_relations(groups: list[Any]) -> list[dict[str, Any]]:
|
||||
relations: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, str, str]] = set()
|
||||
for idx, group in enumerate(groups, start=1):
|
||||
master = str(_get(group, "master_sheet", "") or "").strip()
|
||||
if not master:
|
||||
continue
|
||||
for link in _get(group, "links", []) or []:
|
||||
src_key, target_sheet, target_col = _orient_link(master, link)
|
||||
if not src_key or not target_sheet or not target_col:
|
||||
continue
|
||||
key = (master, target_sheet, src_key)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
related_links = [
|
||||
l for l in (_get(group, "links", []) or [])
|
||||
if _orient_link(master, l)[:2] == (src_key, target_sheet)
|
||||
]
|
||||
relations.append({
|
||||
"name": f"Learned relation {idx}: {master} ↔ {target_sheet}",
|
||||
"description": str(_get(group, "master_reason", "") or "Learned from confirmed LLM blueprint"),
|
||||
"source": {
|
||||
"sheet_pattern": master,
|
||||
"key_column": src_key,
|
||||
},
|
||||
"target": {
|
||||
"sheet_pattern": target_sheet,
|
||||
"match_rules": [
|
||||
{
|
||||
"column": _orient_link(master, l)[2],
|
||||
"strategy": _to_config_strategy(str(_get(l, "match_strategy", "value_contains") or "")),
|
||||
}
|
||||
for l in related_links
|
||||
if _orient_link(master, l)[2]
|
||||
],
|
||||
"multiple": "one_to_one",
|
||||
},
|
||||
"join": {
|
||||
"type": "lookup",
|
||||
"columns": "all",
|
||||
},
|
||||
})
|
||||
return relations
|
||||
|
||||
|
||||
def _orient_link(master_sheet: str, link: Any) -> tuple[str, str, str]:
|
||||
"""Return (master_key_column, other_sheet, other_column) for a MergeLink."""
|
||||
from_sheet = str(_get(link, "from_sheet", "") or "").strip()
|
||||
from_col = str(_get(link, "from_column", "") or "").strip()
|
||||
to_sheet = str(_get(link, "to_sheet", "") or "").strip()
|
||||
to_col = str(_get(link, "to_column", "") or "").strip()
|
||||
if to_sheet == master_sheet:
|
||||
return to_col, from_sheet, from_col
|
||||
if from_sheet == master_sheet:
|
||||
return from_col, to_sheet, to_col
|
||||
return "", "", ""
|
||||
|
||||
|
||||
def _to_config_strategy(strategy: str) -> str:
|
||||
base = (strategy or "value_contains").strip().lower()
|
||||
return {
|
||||
"value_token": "token_match",
|
||||
"value_prefix": "prefix",
|
||||
"value_exact": "exact",
|
||||
"value_contains": "contains",
|
||||
"token_match": "token_match",
|
||||
"prefix": "prefix",
|
||||
"exact": "exact",
|
||||
"contains": "contains",
|
||||
}.get(base, "contains")
|
||||
|
||||
|
||||
def _unique(values: list[str]) -> list[str]:
|
||||
out: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for value in values:
|
||||
normalized = value.strip()
|
||||
if not normalized or normalized in seen:
|
||||
continue
|
||||
seen.add(normalized)
|
||||
out.append(normalized)
|
||||
return out
|
||||
@@ -1,270 +0,0 @@
|
||||
"""LLM-as-judge matcher: calls an OpenAI-compatible chat API (gemma4) to map
|
||||
columns and detect cross-sheet relations. Returns [] on ANY failure so callers
|
||||
fall back to the fuzzy matcher without crashing.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
|
||||
|
||||
@dataclass
|
||||
class LLMColumnMatch:
|
||||
"""One LLM-suggested column mapping."""
|
||||
source_header: str
|
||||
target: str
|
||||
confidence: float # 0-1
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class LLMRelation:
|
||||
"""One LLM-detected cross-sheet relation."""
|
||||
source_sheet: str
|
||||
source_column: str
|
||||
target_sheet: str
|
||||
target_column: str
|
||||
confidence: float # 0-1
|
||||
reason: str
|
||||
|
||||
|
||||
class LLMMatcher:
|
||||
"""Calls a chat model to judge column mappings and cross-sheet relations."""
|
||||
|
||||
def __init__(self, config_manager: ConfigManager):
|
||||
self.cm = config_manager
|
||||
|
||||
# ── Column matching ─────────────────────────────────────
|
||||
|
||||
def match_columns(
|
||||
self,
|
||||
source_columns: list[dict],
|
||||
target_columns: list[dict],
|
||||
) -> list[LLMColumnMatch]:
|
||||
"""Ask the LLM to map each source column to a target column.
|
||||
|
||||
source_columns: [{"header": str, "samples": [str, ...]}]
|
||||
target_columns: [{"name": str, "description": str}]
|
||||
Returns [] on any failure (caller falls back to fuzzy).
|
||||
"""
|
||||
if not self.cm.is_llm_enabled():
|
||||
return []
|
||||
|
||||
valid_targets = {t["name"] for t in target_columns}
|
||||
prompt = self._build_column_prompt(source_columns, target_columns)
|
||||
data = self._call_chat(prompt)
|
||||
if data is None:
|
||||
return []
|
||||
|
||||
matches_raw = data.get("matches", [])
|
||||
results: list[LLMColumnMatch] = []
|
||||
for m in matches_raw:
|
||||
target = m.get("target", "")
|
||||
if target not in valid_targets:
|
||||
continue # drop hallucinated targets
|
||||
results.append(LLMColumnMatch(
|
||||
source_header=m.get("source", ""),
|
||||
target=target,
|
||||
confidence=float(m.get("confidence", 0.0)),
|
||||
reason=m.get("reason", ""),
|
||||
))
|
||||
return results
|
||||
|
||||
def _build_column_prompt(self, source_columns: list[dict], target_columns: list[dict]) -> str:
|
||||
src_lines = []
|
||||
for sc in source_columns:
|
||||
samples = ", ".join(str(s) for s in sc.get("samples", [])[:3])
|
||||
src_lines.append(f'- "{sc["header"]}" (samples: {samples})')
|
||||
tgt_lines = [
|
||||
f'- {t["name"]}: {t.get("description", "")}' for t in target_columns
|
||||
]
|
||||
return (
|
||||
"You are a data mapping assistant. Map each source Excel column to the "
|
||||
"BEST matching target database column.\n\n"
|
||||
f"Source columns:\n{chr(10).join(src_lines)}\n\n"
|
||||
f"Target columns:\n{chr(10).join(tgt_lines)}\n\n"
|
||||
"Return ONLY valid JSON, no prose, in this exact shape:\n"
|
||||
'{"matches": [{"source": "<source header>", "target": "<target name>", '
|
||||
'"confidence": <0-1>, "reason": "<short reason>"}]}\n'
|
||||
"Omit any source you cannot map. confidence is your certainty 0-1."
|
||||
)
|
||||
|
||||
# ── Cross-sheet relation detection ──────────────────────
|
||||
|
||||
def detect_relations(self, sheets_info: list[dict]) -> list[LLMRelation]:
|
||||
"""Ask the LLM to detect joinable relations between sheets.
|
||||
|
||||
sheets_info: [{"name": str, "columns": [{"header", "samples"}]}]
|
||||
Returns [] on failure or when fewer than 2 sheets.
|
||||
"""
|
||||
if not self.cm.is_llm_enabled() or len(sheets_info) < 2:
|
||||
return []
|
||||
|
||||
prompt = self._build_relation_prompt(sheets_info)
|
||||
data = self._call_chat(prompt)
|
||||
if data is None:
|
||||
return []
|
||||
|
||||
relations_raw = data.get("relations", [])
|
||||
results: list[LLMRelation] = []
|
||||
for r in relations_raw:
|
||||
results.append(LLMRelation(
|
||||
source_sheet=r.get("source_sheet", ""),
|
||||
source_column=r.get("source_column", ""),
|
||||
target_sheet=r.get("target_sheet", ""),
|
||||
target_column=r.get("target_column", ""),
|
||||
confidence=float(r.get("confidence", 0.0)),
|
||||
reason=r.get("reason", ""),
|
||||
))
|
||||
return results
|
||||
|
||||
def _build_relation_prompt(self, sheets_info: list[dict]) -> str:
|
||||
parts = []
|
||||
for sh in sheets_info:
|
||||
cols = ", ".join(f'"{c["header"]}" (e.g. {", ".join(str(s) for s in c.get("samples", [])[:3])})'
|
||||
for c in sh.get("columns", []))
|
||||
parts.append(f'Sheet "{sh["name"]}": {cols}')
|
||||
return (
|
||||
"You are a data analyst. Examine these Excel sheets and detect any "
|
||||
"joinable relations between them (e.g. one sheet's A/B/C codes "
|
||||
"corresponding to another sheet's A賞/B賞 names).\n\n"
|
||||
f"{chr(10).join(parts)}\n\n"
|
||||
"Return ONLY valid JSON, no prose:\n"
|
||||
'{"relations": [{"source_sheet": "...", "source_column": "...", '
|
||||
'"target_sheet": "...", "target_column": "...", "confidence": <0-1>, '
|
||||
'"reason": "..."}]}\n'
|
||||
"Return empty list if none."
|
||||
)
|
||||
|
||||
# ── Full config generation ─────────────────────────────
|
||||
|
||||
def generate_config(
|
||||
self,
|
||||
source_columns: list[dict],
|
||||
target_columns: list[dict],
|
||||
sheets_info: list[dict],
|
||||
) -> dict | None:
|
||||
"""Let LLM analyze the full workbook and produce a complete type config.
|
||||
|
||||
Returns a dict with: mapping, sheet_relations, form_fields, structure_keywords.
|
||||
Returns None on failure (caller falls back to per-column matching).
|
||||
"""
|
||||
if not self.cm.is_llm_enabled():
|
||||
return None
|
||||
|
||||
prompt = (
|
||||
"You are an Excel data mapping expert. Analyze this workbook and "
|
||||
"generate a complete configuration for mapping it into a target schema.\n\n"
|
||||
"=== SOURCE COLUMNS (with sample values) ===\n"
|
||||
)
|
||||
for sh in sheets_info:
|
||||
prompt += f"\nSheet \"{sh['name']}\":\n"
|
||||
for c in sh.get("columns", []):
|
||||
samples = ", ".join(str(s) for s in c.get("samples", [])[:3])
|
||||
prompt += f' - "{c["header"]}" samples: [{samples}]\n'
|
||||
|
||||
prompt += (
|
||||
"\n=== TARGET DATABASE COLUMNS ===\n"
|
||||
)
|
||||
for t in target_columns:
|
||||
prompt += f' - {t["name"]}: {t.get("description", "")}\n'
|
||||
|
||||
prompt += (
|
||||
"\n=== YOUR TASK ===\n"
|
||||
"Return ONLY valid JSON, no prose:\n"
|
||||
"{\n"
|
||||
' "mapping": [\n'
|
||||
' {"source_patterns": ["<column header>"], "target": "<target name>",'
|
||||
' "required": true/false}\n'
|
||||
' ...\n'
|
||||
' ],\n'
|
||||
' "sheet_relations": [\n'
|
||||
' {"source_sheet": "<sheet name or pattern>", "source_key": "<column>",\n'
|
||||
' "target_sheet": "<sheet name or pattern>", "target_column": "<column>",\n'
|
||||
' "match_strategy": "prefix|token_match|exact|contains",\n'
|
||||
' "join_type": "lookup|inner",\n'
|
||||
' "reason": "<why this relation exists>"}\n'
|
||||
' ... (empty list if only one sheet or no relations)\n'
|
||||
' ],\n'
|
||||
' "form_fields": [\n'
|
||||
' {"source_patterns": ["<label>"], "target": "<target name>"}\n'
|
||||
' ... (empty if none)\n'
|
||||
' ],\n'
|
||||
' "structure_keywords": ["<keyword1>", "<keyword2>", ...],\n'
|
||||
' "analysis": "<brief analysis of this workbook type>"\n'
|
||||
"}\n\n"
|
||||
"Rules:\n"
|
||||
"- source_patterns: the EXACT header text(s) in the Excel\n"
|
||||
"- required=true only for truly essential key fields (barcode, primary name)\n"
|
||||
"- sheet_relations: detect cross-sheet joins (e.g. code column A/B/C matches name column A賞/B賞)\n"
|
||||
"- form_fields: single-value cells that should propagate to all rows (e.g. shared JAN code, launch date)\n"
|
||||
"- structure_keywords: 5-15 words from column headers that help identify this format\n"
|
||||
"- match_strategy: 'prefix' if key is start of target, 'token_match' for word-bounded match, 'exact' for identical values\n"
|
||||
)
|
||||
|
||||
data = self._call_chat(prompt)
|
||||
if data is None:
|
||||
return None
|
||||
return data # caller validates fields
|
||||
|
||||
# ── HTTP call + JSON extraction ─────────────────────────
|
||||
|
||||
def _call_chat(self, prompt: str) -> dict | None:
|
||||
"""POST to chat completions, return parsed JSON dict or None."""
|
||||
cfg = self.cm.get_llm_config()
|
||||
url = cfg["base_url"].rstrip("/") + "/chat/completions"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.cm.get_llm_api_key()}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
body = {
|
||||
"model": cfg["model"],
|
||||
"temperature": cfg["temperature"],
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
}
|
||||
verify = cfg.get("ssl_verify", True)
|
||||
try:
|
||||
if not verify:
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
warnings.filterwarnings("ignore", message="Unverified HTTPS request")
|
||||
resp = requests.post(
|
||||
url, headers=headers, json=body,
|
||||
timeout=cfg["timeout_seconds"], verify=verify,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
content = ""
|
||||
try:
|
||||
data = resp.json()
|
||||
content = data["choices"][0]["message"]["content"]
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
return self._extract_json(content)
|
||||
|
||||
@staticmethod
|
||||
def _extract_json(content: str) -> dict | None:
|
||||
"""Extract the first {...} JSON object from a model response."""
|
||||
if not content:
|
||||
return None
|
||||
# Try direct parse first
|
||||
try:
|
||||
return json.loads(content)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
# Fallback: grab the first balanced {...} block
|
||||
match = re.search(r"\{.*\}", content, re.DOTALL)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
return json.loads(match.group(0))
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Prompt builders for staged Excel AI analysis.
|
||||
|
||||
The builders keep local/cloud model behavior on the same JSON contracts while
|
||||
letting the active LLM profile control how much context is included.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
STRICT_JSON_RULES = (
|
||||
"Return ONLY raw valid JSON. Do not wrap JSON in Markdown fences.\n"
|
||||
"Do not invent sheet names, row numbers, column headers, or SQL targets.\n"
|
||||
"If unsure, lower confidence instead of guessing."
|
||||
)
|
||||
|
||||
|
||||
def build_sheet_structure_prompt(
|
||||
sheet_name: str,
|
||||
raw_rows: list[list[Any]],
|
||||
budget: dict | None = None,
|
||||
known_header_row: int | None = None,
|
||||
known_headers: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Build Stage 1 prompt for sheet structure with budgeted row/column preview."""
|
||||
budget = budget or {}
|
||||
max_rows = int(budget.get("max_sheet_rows", 30) or 30)
|
||||
max_cols = int(budget.get("max_sheet_cols", 30) or 30)
|
||||
preview = [
|
||||
[str(c)[:60] if c is not None else "" for c in row[:max_cols]]
|
||||
for row in raw_rows[:max_rows]
|
||||
]
|
||||
header_hints = _render_header_hints(known_header_row, known_headers)
|
||||
return (
|
||||
"You are an Excel structure analyst. Examine this sheet and return its structure.\n"
|
||||
f"{STRICT_JSON_RULES}\n"
|
||||
"For small-model reliability: choose from explicit candidates; do not rename headers.\n"
|
||||
"Omit blank headers and merged-value cells that do not have their own header.\n\n"
|
||||
f"Sheet name: \"{sheet_name}\"\n"
|
||||
f"{header_hints}"
|
||||
f"Rows (first {max_rows}, first {max_cols} columns, cells truncated):\n"
|
||||
f"{json.dumps(preview, ensure_ascii=False)}\n\n"
|
||||
"Return this exact JSON shape:\n"
|
||||
'{"header_row": <int>, "sheet_type": "detail|definition|other", '
|
||||
'"columns": [{"header":"<text>","samples":["<v>"],"meaning":"<short>"}], '
|
||||
'"shared_values": [{"label":"<text>","value":"<text>"}]}\n'
|
||||
"sheet_type: 'detail' = one product per row; 'definition' = defines styles/codes; "
|
||||
"'other' = cover/info. shared_values = single cells that apply to all rows."
|
||||
)
|
||||
|
||||
|
||||
def build_sheet_links_prompt(summaries: list[Any]) -> str:
|
||||
"""Build Stage 2 prompt for cross-sheet merge/link detection."""
|
||||
parts = []
|
||||
for s in summaries:
|
||||
cols = ", ".join(f'"{c.get("header", "")}"' for c in getattr(s, "columns", []))
|
||||
parts.append(
|
||||
f'Sheet "{getattr(s, "sheet_name", "")}" '
|
||||
f'({getattr(s, "sheet_type", "")}, header_row={getattr(s, "header_row", "")}): {cols}'
|
||||
)
|
||||
return (
|
||||
"You are a data analyst. These sheets may describe the same products in different ways.\n"
|
||||
f"{STRICT_JSON_RULES}\n\n"
|
||||
f"{chr(10).join(parts)}\n\n"
|
||||
"Detect which sheets should be MERGED into single output rows, and the join key.\n\n"
|
||||
"Return this exact JSON shape:\n"
|
||||
'{"groups": [{"sheets": ["<name>", "<name>"], "master_sheet": "<name>", '
|
||||
'"master_reason": "<why>", "links": [{"from_sheet":"<name>","from_column":"<col>",'
|
||||
'"to_sheet":"<name>","to_column":"<col>","key_pattern":"<desc>",'
|
||||
'"match_strategy":"value_token|value_prefix|value_exact|value_contains",'
|
||||
'"confidence":<0-1>,"reason":"<short>"}]}]}\n'
|
||||
"master_sheet = the sheet with the most rows / a unique key. Empty groups list if no links."
|
||||
)
|
||||
|
||||
|
||||
def build_schema_mapping_prompt(
|
||||
excel_cols: list[dict],
|
||||
target_list: list[dict],
|
||||
budget: dict | None = None,
|
||||
known_mappings: list[dict] | None = None,
|
||||
type_support_notes: dict | None = None,
|
||||
) -> str:
|
||||
"""Build Stage 3 prompt for evidence-backed SQL schema mapping."""
|
||||
budget = budget or {}
|
||||
max_cols = int(budget.get("max_mapping_columns", 40) or 40)
|
||||
known_mappings = known_mappings or []
|
||||
known_excel = {
|
||||
str(item.get("excel", "") or "").strip()
|
||||
for item in known_mappings
|
||||
if str(item.get("excel", "") or "").strip()
|
||||
}
|
||||
known_sql = {
|
||||
str(item.get("sql", "") or "").strip()
|
||||
for item in known_mappings
|
||||
if str(item.get("sql", "") or "").strip()
|
||||
}
|
||||
budgeted_cols = [
|
||||
col for col in excel_cols
|
||||
if str(col.get("header", "") or "").strip() not in known_excel
|
||||
][:max_cols]
|
||||
target_names = [
|
||||
str(item.get("name", "") or "").strip()
|
||||
for item in target_list
|
||||
if str(item.get("name", "") or "").strip()
|
||||
and str(item.get("name", "") or "").strip() not in known_sql
|
||||
]
|
||||
if not target_names:
|
||||
target_names = [
|
||||
str(item.get("name", "") or "").strip()
|
||||
for item in target_list
|
||||
if str(item.get("name", "") or "").strip()
|
||||
]
|
||||
support_notes_text = _render_type_support_notes_for_prompt(type_support_notes)
|
||||
support_section = f"\n\n{support_notes_text}\n" if support_notes_text else ""
|
||||
return (
|
||||
"You are a data mapping assistant. Map each Excel column that still needs review to the BEST matching target.\n"
|
||||
f"{STRICT_JSON_RULES}\n"
|
||||
"Known exact mappings are authoritative and already applied by the system. "
|
||||
"Do NOT repeat already-applied known mappings in mapping. "
|
||||
"If you disagree, output a conflict instead of replacing them.\n"
|
||||
"For small-model reliability: map only listed review Excel columns to listed available SQL targets; do not infer hidden fields.\n\n"
|
||||
f"Excel columns still needing AI review:\n{json.dumps(budgeted_cols, ensure_ascii=False)}\n\n"
|
||||
f"Available SQL target names not already filled:\n{json.dumps(target_names, ensure_ascii=False)}\n\n"
|
||||
f"Already-applied known exact mappings:\n{json.dumps(known_mappings, ensure_ascii=False)}"
|
||||
f"{support_section}\n"
|
||||
"Return this exact JSON shape:\n"
|
||||
'{"mapping": [{"excel":"<col>","sql":"<target>","confidence":<0-1>,"reason":"<short>"}], '
|
||||
'"conflicts": [{"excel":"<col>","suggested_sql":"<target>","known_sql":"<target>",'
|
||||
'"confidence":<0-1>,"reason":"<short>"}]}\n'
|
||||
"The top-level JSON value must be this object, not an array. "
|
||||
"Omit columns you cannot map. 'sql' and 'suggested_sql' must be exact available target names; "
|
||||
"'known_sql' must be an exact known target name."
|
||||
)
|
||||
|
||||
|
||||
def _render_header_hints(known_header_row: int | None, known_headers: list[str] | None) -> str:
|
||||
"""Render parser-detected candidates that bound Stage 1 model choices."""
|
||||
hints: list[str] = []
|
||||
if known_header_row:
|
||||
hints.append(f"Parser-detected header row: {int(known_header_row)}")
|
||||
clean_headers = [str(h).strip() for h in (known_headers or []) if str(h).strip()]
|
||||
if clean_headers:
|
||||
hints.append("Allowed column headers (exact strings; Choose from the allowed headers only):")
|
||||
hints.append(json.dumps(clean_headers, ensure_ascii=False))
|
||||
if not hints:
|
||||
return ""
|
||||
return "\n".join(hints) + "\n"
|
||||
|
||||
|
||||
def _render_type_support_notes_for_prompt(notes: dict | None, limit: int = 2200) -> str:
|
||||
"""Render compact type support notes without importing UI/service helpers."""
|
||||
if not notes:
|
||||
return ""
|
||||
payload = notes.get("notes") or {}
|
||||
lines = ["TYPE SUPPORT NOTES (hints for this selected workbook Type; do not override workbook evidence):"]
|
||||
for item in payload.get("header_aliases") or []:
|
||||
headers = ", ".join(str(h) for h in item.get("preferred_headers", []) if str(h).strip())
|
||||
if headers:
|
||||
lines.append(f"- Prefer header(s) {headers} for SQL target {item.get('sql_target', '')}. Reason: {item.get('reason', '')}")
|
||||
for item in payload.get("join_hints") or []:
|
||||
lines.append(f"- Join hint: {item.get('pattern', '')} using {item.get('strategy', '')}. Reason: {item.get('reason', '')}")
|
||||
for item in payload.get("mapping_guidance") or []:
|
||||
lines.append(f"- Mapping guidance: {item.get('source_header', '')} -> {item.get('sql_target', '')}. {item.get('condition', '')} Reason: {item.get('reason', '')}")
|
||||
return "\n".join(lines)[:limit]
|
||||
|
||||
|
||||
def build_validation_retry_prompt(original_prompt: str, invalid_json: str, errors: list[str]) -> str:
|
||||
"""Build a compact retry prompt that asks the model to correct invalid JSON."""
|
||||
original_context = _clip_preserving_tail(str(original_prompt), head=2800, tail=2200)
|
||||
return (
|
||||
"Your previous JSON was invalid for these reasons:\n"
|
||||
+ "\n".join(f"- {error}" for error in errors)
|
||||
+ "\n\nPrevious response:\n"
|
||||
+ str(invalid_json)[:2000]
|
||||
+ "\n\nOriginal instructions:\n"
|
||||
+ original_context
|
||||
+ "\n\nReturn corrected JSON only. Do not add prose."
|
||||
)
|
||||
|
||||
|
||||
def _clip_preserving_tail(text: str, head: int, tail: int) -> str:
|
||||
"""Clip long prompts while preserving the final output contract."""
|
||||
if len(text) <= head + tail:
|
||||
return text
|
||||
return text[:head] + "\n...[middle omitted for retry prompt]...\n" + text[-tail:]
|
||||
+430
-67
@@ -7,12 +7,33 @@ import json
|
||||
import re
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
from typing import Any, Callable
|
||||
|
||||
# Some operator machines still have an old global requests install paired with
|
||||
# newer urllib3/chardet. The project .venv pins a clean set; this filter keeps a
|
||||
# stale global env from spamming Streamlit logs before the UI can show guidance.
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message=r"urllib3 .*doesn't match a supported version!",
|
||||
category=Warning,
|
||||
module=r"requests\.__init__",
|
||||
)
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.llm_prompts import (
|
||||
build_sheet_structure_prompt,
|
||||
build_sheet_links_prompt,
|
||||
build_schema_mapping_prompt,
|
||||
build_validation_retry_prompt,
|
||||
)
|
||||
from services.llm_validation import (
|
||||
ValidationResult,
|
||||
validate_sheet_structure,
|
||||
validate_sheet_links,
|
||||
validate_schema_mapping,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -57,29 +78,42 @@ class ColumnMapping:
|
||||
|
||||
|
||||
class LLMStages:
|
||||
def __init__(self, config_manager: ConfigManager, max_retries: int = 2):
|
||||
"""Small staged LLM client used by WorkbookAnalyzer; every failure returns fallback-friendly None or empty lists."""
|
||||
def __init__(
|
||||
self,
|
||||
config_manager: ConfigManager,
|
||||
max_retries: int = 2,
|
||||
event_callback: Callable[[dict], None] | None = None,
|
||||
):
|
||||
"""Store config, retry count, and optional live UI event callback."""
|
||||
self.cm = config_manager
|
||||
self.max_retries = max_retries
|
||||
self.event_callback = event_callback
|
||||
|
||||
# ── Stage 1: read one sheet ────────────────────────────
|
||||
|
||||
def stage1_read_sheet(self, sheet_name: str, raw_rows: list[list]) -> SheetSummary | None:
|
||||
def stage1_read_sheet(
|
||||
self,
|
||||
sheet_name: str,
|
||||
raw_rows: list[list],
|
||||
known_header_row: int | None = None,
|
||||
known_headers: list[str] | None = None,
|
||||
) -> SheetSummary | None:
|
||||
"""Ask the model to summarize one worksheet structure using parser-bounded candidates."""
|
||||
if not self.cm.is_llm_enabled():
|
||||
return None
|
||||
preview = [[str(c)[:60] if c is not None else "" for c in row[:30]]
|
||||
for row in raw_rows[:30]]
|
||||
prompt = (
|
||||
"You are an Excel structure analyst. Examine this sheet and return its structure.\n\n"
|
||||
f"Sheet name: \"{sheet_name}\"\n"
|
||||
f"Rows (first 30, truncated):\n{json.dumps(preview, ensure_ascii=False)}\n\n"
|
||||
"Return ONLY JSON:\n"
|
||||
'{"header_row": <int>, "sheet_type": "detail|definition|other", '
|
||||
'"columns": [{"header":"<text>","samples":["<v>"],"meaning":"<short>"}], '
|
||||
'"shared_values": [{"label":"<text>","value":"<text>"}]}\n'
|
||||
"sheet_type: 'detail' = one product per row; 'definition' = defines styles/codes; "
|
||||
"'other' = cover/info. shared_values = single cells that apply to all rows."
|
||||
prompt = build_sheet_structure_prompt(
|
||||
sheet_name,
|
||||
raw_rows,
|
||||
self._budgets(),
|
||||
known_header_row=known_header_row,
|
||||
known_headers=known_headers,
|
||||
)
|
||||
data = self._call_with_validation(
|
||||
prompt,
|
||||
lambda payload: validate_sheet_structure(sheet_name, raw_rows, payload),
|
||||
label=f"Stage 1 sheet '{sheet_name}'",
|
||||
)
|
||||
data = self._call_with_retry(prompt)
|
||||
if data is None:
|
||||
return None
|
||||
return SheetSummary(
|
||||
@@ -93,25 +127,15 @@ class LLMStages:
|
||||
# ── Stage 2: find cross-sheet links ────────────────────
|
||||
|
||||
def stage2_find_links(self, summaries: list[SheetSummary]) -> list[MergeGroup]:
|
||||
"""Ask the model to detect cross-sheet merge groups."""
|
||||
if not self.cm.is_llm_enabled() or len(summaries) < 2:
|
||||
return []
|
||||
parts = []
|
||||
for s in summaries:
|
||||
cols = ", ".join(f'"{c.get("header","")}"' for c in s.columns)
|
||||
parts.append(f'Sheet "{s.sheet_name}" ({s.sheet_type}, header_row={s.header_row}): {cols}')
|
||||
prompt = (
|
||||
"You are a data analyst. These sheets may describe the same products in different ways.\n\n"
|
||||
f"{chr(10).join(parts)}\n\n"
|
||||
"Detect which sheets should be MERGED into single output rows, and the join key.\n\n"
|
||||
"Return ONLY JSON:\n"
|
||||
'{"groups": [{"sheets": ["<name>", "<name>"], "master_sheet": "<name>", '
|
||||
'"master_reason": "<why>", "links": [{"from_sheet":"<name>","from_column":"<col>",'
|
||||
'"to_sheet":"<name>","to_column":"<col>","key_pattern":"<desc>",'
|
||||
'"match_strategy":"value_token|value_prefix|value_exact|value_contains",'
|
||||
'"confidence":<0-1>,"reason":"<short>"}]}]}\n'
|
||||
"master_sheet = the sheet with the most rows / a unique key. Empty groups list if no links."
|
||||
prompt = build_sheet_links_prompt(summaries)
|
||||
data = self._call_with_validation(
|
||||
prompt,
|
||||
lambda payload: validate_sheet_links(summaries, payload),
|
||||
label="Stage 2 sheet links",
|
||||
)
|
||||
data = self._call_with_retry(prompt)
|
||||
if data is None:
|
||||
return []
|
||||
groups = []
|
||||
@@ -141,7 +165,10 @@ class LLMStages:
|
||||
summaries: list[SheetSummary],
|
||||
groups: list[MergeGroup],
|
||||
schema_fields: list[dict],
|
||||
type_id: str | None = None,
|
||||
known_mappings: list[dict] | None = None,
|
||||
) -> list[ColumnMapping]:
|
||||
"""Ask the model to map discovered columns to the target schema."""
|
||||
if not self.cm.is_llm_enabled():
|
||||
return []
|
||||
valid_targets = {f["name"] for f in schema_fields}
|
||||
@@ -155,15 +182,19 @@ class LLMStages:
|
||||
excel_cols.append({"header": h, "samples": c.get("samples", [])})
|
||||
target_list = [{"name": f["name"], "description": f.get("description", "")} for f in schema_fields]
|
||||
|
||||
prompt = (
|
||||
"You are a data mapping assistant. Map each Excel column to the BEST matching target.\n\n"
|
||||
f"Excel columns:\n{json.dumps(excel_cols[:40], ensure_ascii=False)}\n\n"
|
||||
f"Target columns:\n{json.dumps(target_list, ensure_ascii=False)}\n\n"
|
||||
"Return ONLY JSON:\n"
|
||||
'{"mapping": [{"excel":"<col>","sql":"<target>","confidence":<0-1>,"reason":"<short>"}]}\n'
|
||||
"Omit columns you cannot map. 'sql' must be an exact target name."
|
||||
type_support_notes = self.cm.load_type_support_notes(type_id) if type_id else None
|
||||
prompt = build_schema_mapping_prompt(
|
||||
excel_cols,
|
||||
target_list,
|
||||
self._budgets(),
|
||||
known_mappings=known_mappings,
|
||||
type_support_notes=type_support_notes,
|
||||
)
|
||||
data = self._call_with_validation(
|
||||
prompt,
|
||||
lambda payload: validate_schema_mapping(summaries, schema_fields, payload),
|
||||
label="Stage 3 schema mapping",
|
||||
)
|
||||
data = self._call_with_retry(prompt)
|
||||
if data is None:
|
||||
return []
|
||||
mappings = []
|
||||
@@ -179,53 +210,385 @@ class LLMStages:
|
||||
))
|
||||
return mappings
|
||||
|
||||
def _budgets(self) -> dict:
|
||||
"""Return active profile prompt budgets, or safe small-model defaults."""
|
||||
conn = self.cm.resolve_llm_connection_config()
|
||||
if conn and isinstance(conn.get("budgets"), dict):
|
||||
return conn["budgets"]
|
||||
return {
|
||||
"max_sheet_rows": 80,
|
||||
"max_sheet_cols": 30,
|
||||
"max_candidates_per_sheet": 4,
|
||||
"sample_rows_per_candidate": 4,
|
||||
"max_mapping_columns": 40,
|
||||
}
|
||||
|
||||
# ── HTTP ───────────────────────────────────────────────
|
||||
|
||||
def _call_with_retry(self, prompt: str) -> dict | None:
|
||||
for _ in range(self.max_retries + 1):
|
||||
data = self._call_chat(prompt)
|
||||
if data is not None:
|
||||
return data
|
||||
def _call_with_validation(self, prompt: str, validator, label: str) -> dict | None:
|
||||
"""Call the model, semantically validate JSON, and retry once with feedback."""
|
||||
current_prompt = prompt
|
||||
last_errors: list[str] = []
|
||||
for attempt in range(self.max_retries + 1):
|
||||
attempt_label = label if attempt == 0 else f"{label} correction retry {attempt}"
|
||||
data = self._call_chat(current_prompt, label=attempt_label)
|
||||
if data is None:
|
||||
last_errors = ["response was not valid JSON"]
|
||||
self._emit_event("Validation retry requested", f"{label}: model response was not valid JSON")
|
||||
current_prompt = build_validation_retry_prompt(prompt, "<not valid JSON>", last_errors)
|
||||
continue
|
||||
result: ValidationResult = validator(data)
|
||||
if result.valid:
|
||||
self._emit_event(
|
||||
"Validated model JSON",
|
||||
f"{label}: output passed semantic checks",
|
||||
kind="validation_result",
|
||||
label=label,
|
||||
validation_status="passed",
|
||||
normalized_preview=self._clip(json.dumps(result.data, ensure_ascii=False, indent=2), limit=6000),
|
||||
validation_errors=[],
|
||||
validation_warnings=result.warnings,
|
||||
)
|
||||
return result.data
|
||||
last_errors = result.errors
|
||||
self._emit_event(
|
||||
"Validation retry requested",
|
||||
f"{label}: {len(last_errors)} semantic issue(s) found; asking model to correct JSON",
|
||||
kind="validation_result",
|
||||
label=label,
|
||||
validation_status="failed",
|
||||
normalized_preview=self._clip(json.dumps(data, ensure_ascii=False, indent=2), limit=3000),
|
||||
validation_errors=last_errors,
|
||||
)
|
||||
current_prompt = build_validation_retry_prompt(
|
||||
prompt,
|
||||
json.dumps(data, ensure_ascii=False),
|
||||
last_errors,
|
||||
)
|
||||
self._emit_event("Validation fallback", f"{label}: no valid JSON after retry; deterministic fallback can continue")
|
||||
return None
|
||||
|
||||
def _call_chat(self, prompt: str) -> dict | None:
|
||||
cfg = self.cm.get_llm_config()
|
||||
url = cfg["base_url"].rstrip("/") + "/chat/completions"
|
||||
def _call_chat(self, prompt: str, label: str = "LLM request") -> dict | None:
|
||||
"""Call the configured chat completions endpoint and parse the JSON response."""
|
||||
conn = self.cm.resolve_llm_connection_config()
|
||||
if not conn:
|
||||
self._emit_event(
|
||||
"LLM config unavailable",
|
||||
f"{label}: active profile is missing a usable API key or base URL",
|
||||
kind="llm_error",
|
||||
label=label,
|
||||
)
|
||||
return None
|
||||
|
||||
url = conn["base_url"].rstrip("/") + "/chat/completions"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.cm.get_llm_api_key()}",
|
||||
"Authorization": f"Bearer {conn['api_key']}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
body = {
|
||||
"model": cfg["model"],
|
||||
"temperature": cfg.get("temperature", 0.1),
|
||||
"model": conn.get("model") or "deepseek-chat",
|
||||
"temperature": conn.get("temperature", 0.1),
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
}
|
||||
verify = cfg.get("ssl_verify", True)
|
||||
self._emit_event(
|
||||
"Prompt sent",
|
||||
f"{label}: prompt prepared for model",
|
||||
kind="prompt",
|
||||
label=label,
|
||||
prompt=self._clip(prompt, limit=10000),
|
||||
request={
|
||||
"url": url,
|
||||
"model": body["model"],
|
||||
"temperature": body["temperature"],
|
||||
"timeout_seconds": conn.get("timeout_seconds", 30),
|
||||
"ssl_verify": conn.get("ssl_verify", False),
|
||||
"stream_response": bool(conn.get("stream_response", False)),
|
||||
"profile": conn.get("profile"),
|
||||
"mode": conn.get("mode"),
|
||||
"budgets": conn.get("budgets"),
|
||||
},
|
||||
)
|
||||
verify = conn.get("ssl_verify", False)
|
||||
resp = None
|
||||
try:
|
||||
if not verify:
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
warnings.filterwarnings("ignore", message="Unverified HTTPS request")
|
||||
if bool(conn.get("stream_response", False)) and self.event_callback is not None:
|
||||
streamed = self._call_chat_streaming(url, headers, body, conn, verify, label)
|
||||
if streamed is not None:
|
||||
return streamed
|
||||
self._emit_event(
|
||||
"Streaming unavailable",
|
||||
f"{label}: provider did not return a usable stream; switching to standard response",
|
||||
kind="llm_error",
|
||||
label=label,
|
||||
)
|
||||
resp = requests.post(url, headers=headers, json=body,
|
||||
timeout=cfg.get("timeout_seconds", 30), verify=verify)
|
||||
timeout=conn.get("timeout_seconds", 30), verify=verify)
|
||||
self._emit_event(
|
||||
"HTTP response received",
|
||||
f"{label}: non-streaming response status {getattr(resp, 'status_code', 'unknown')}",
|
||||
kind="llm_http",
|
||||
label=label,
|
||||
status_code=getattr(resp, "status_code", None),
|
||||
response_preview=self._clip(str(getattr(resp, "text", "") or ""), limit=2000),
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
content = data["choices"][0]["message"]["content"]
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
self._emit_event(
|
||||
"LLM request failed",
|
||||
f"{label}: {exc.__class__.__name__}: {exc}",
|
||||
kind="llm_error",
|
||||
label=label,
|
||||
error_type=exc.__class__.__name__,
|
||||
error=str(exc),
|
||||
status_code=getattr(resp, "status_code", None) if resp is not None else None,
|
||||
response_preview=self._clip(str(getattr(resp, "text", "") or ""), limit=4000) if resp is not None else "",
|
||||
)
|
||||
return None
|
||||
return self._extract_json(content)
|
||||
return self._extract_and_emit_json(content, label)
|
||||
|
||||
def _call_chat_streaming(
|
||||
self,
|
||||
url: str,
|
||||
headers: dict,
|
||||
body: dict,
|
||||
conn: dict,
|
||||
verify: bool,
|
||||
label: str,
|
||||
) -> dict | None:
|
||||
"""Read OpenAI-compatible SSE chunks and emit visible progress events while buffering JSON."""
|
||||
stream_body = dict(body)
|
||||
stream_body["stream"] = True
|
||||
content = ""
|
||||
next_emit_at = 1
|
||||
resp = None
|
||||
streaming_body_started = False
|
||||
try:
|
||||
self._emit_event("Streaming AI response", f"{label}: request sent; waiting for JSON chunks")
|
||||
resp = requests.post(
|
||||
url,
|
||||
headers=headers,
|
||||
json=stream_body,
|
||||
timeout=conn.get("timeout_seconds", 30),
|
||||
verify=verify,
|
||||
stream=True,
|
||||
)
|
||||
self._emit_event(
|
||||
"HTTP response received",
|
||||
f"{label}: streaming response status {getattr(resp, 'status_code', 'unknown')}",
|
||||
kind="llm_http",
|
||||
label=label,
|
||||
status_code=getattr(resp, "status_code", None),
|
||||
stream=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
streaming_body_started = True
|
||||
for raw_line in resp.iter_lines(decode_unicode=True):
|
||||
if not raw_line:
|
||||
continue
|
||||
line = raw_line.decode("utf-8", errors="ignore") if isinstance(raw_line, bytes) else str(raw_line)
|
||||
piece = self._parse_stream_line(line)
|
||||
if piece is None:
|
||||
continue
|
||||
if piece == "[DONE]":
|
||||
break
|
||||
content += piece
|
||||
if len(content) >= next_emit_at:
|
||||
self._emit_event(
|
||||
"Streaming AI response",
|
||||
f"{label}: {len(content)} chars received; latest: {self._snippet(content)}",
|
||||
stream_text=content,
|
||||
label=label,
|
||||
)
|
||||
next_emit_at = len(content) + 120
|
||||
self._emit_event("Streaming completed", f"{label}: {len(content)} chars received; validating JSON")
|
||||
except Exception as exc:
|
||||
response_preview = ""
|
||||
if resp is not None and not streaming_body_started:
|
||||
response_preview = self._clip(str(getattr(resp, "text", "") or ""), limit=4000)
|
||||
self._emit_event(
|
||||
"Streaming failed",
|
||||
f"{label}: {exc.__class__.__name__}: {exc}; trying standard response",
|
||||
kind="llm_error",
|
||||
label=label,
|
||||
error_type=exc.__class__.__name__,
|
||||
error=str(exc),
|
||||
status_code=getattr(resp, "status_code", None) if resp is not None else None,
|
||||
response_preview=response_preview,
|
||||
)
|
||||
return None
|
||||
return self._extract_and_emit_json(content, label)
|
||||
|
||||
@staticmethod
|
||||
def _extract_json(content: str) -> dict | None:
|
||||
def _parse_stream_line(line: str) -> str | None:
|
||||
"""Return visible content from one OpenAI-compatible SSE line."""
|
||||
data = line.strip()
|
||||
if not data:
|
||||
return None
|
||||
if data.startswith("data:"):
|
||||
data = data[5:].strip()
|
||||
if data == "[DONE]":
|
||||
return "[DONE]"
|
||||
try:
|
||||
payload = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
choices = payload.get("choices") or []
|
||||
if not choices:
|
||||
return None
|
||||
choice = choices[0] or {}
|
||||
delta = choice.get("delta") or {}
|
||||
if isinstance(delta, dict) and delta.get("content"):
|
||||
return str(delta.get("content"))
|
||||
message = choice.get("message") or {}
|
||||
if isinstance(message, dict) and message.get("content"):
|
||||
return str(message.get("content"))
|
||||
return None
|
||||
|
||||
def _emit_event(self, title: str, detail: str, kind: str = "llm_stream", **extra: Any) -> None:
|
||||
"""Emit an LLM progress event without exposing credentials or hidden reasoning."""
|
||||
if self.event_callback is None:
|
||||
return
|
||||
event = {"kind": kind, "title": title, "detail": detail}
|
||||
event.update(extra)
|
||||
label = str(event.get("label") or "")
|
||||
if label:
|
||||
for key, value in self._stage_meta(label, title=title, kind=kind, event=event).items():
|
||||
event.setdefault(key, value)
|
||||
self.event_callback(event)
|
||||
|
||||
@staticmethod
|
||||
def _stage_meta(label: str, title: str, kind: str, event: dict) -> dict[str, Any]:
|
||||
"""Return coarse progress metadata for stage-aware UI rendering."""
|
||||
normalized = label.lower()
|
||||
if normalized.startswith("stage 1"):
|
||||
stage, index, ranges = "sheet_structure", 1, {
|
||||
"prompt": 12, "stream": 28, "stream_done": 40, "response": 42, "parsed": 43, "validation": 45,
|
||||
}
|
||||
elif normalized.startswith("stage 2"):
|
||||
stage, index, ranges = "sheet_links", 2, {
|
||||
"prompt": 50, "stream": 57, "stream_done": 62, "response": 63, "parsed": 64, "validation": 65,
|
||||
}
|
||||
elif normalized.startswith("stage 3"):
|
||||
stage, index, ranges = "schema_mapping", 3, {
|
||||
"prompt": 72, "stream": 80, "stream_done": 86, "response": 88, "parsed": 89, "validation": 90,
|
||||
}
|
||||
else:
|
||||
stage, index, ranges = "model_request", 0, {
|
||||
"prompt": 10, "stream": 35, "stream_done": 60, "response": 70, "parsed": 75, "validation": 80,
|
||||
}
|
||||
title_lower = title.lower()
|
||||
if kind == "prompt":
|
||||
phase = "prompt"
|
||||
elif kind == "model_response":
|
||||
phase = "response"
|
||||
elif kind == "model_parsed":
|
||||
phase = "parsed"
|
||||
elif kind == "validation_result":
|
||||
phase = "validation"
|
||||
elif "completed" in title_lower:
|
||||
phase = "stream_done"
|
||||
elif event.get("stream_text"):
|
||||
phase = "stream"
|
||||
else:
|
||||
phase = "stream"
|
||||
return {
|
||||
"stage": stage,
|
||||
"stage_index": index,
|
||||
"stage_total": 3,
|
||||
"percent": ranges.get(phase, ranges["stream"]),
|
||||
}
|
||||
|
||||
def _extract_and_emit_json(self, content: str, label: str) -> Any | None:
|
||||
"""Emit visible model response metadata, then parse JSON for validation."""
|
||||
self._emit_event(
|
||||
"Model response received",
|
||||
f"{label}: {len(content or '')} chars received from model",
|
||||
kind="model_response",
|
||||
label=label,
|
||||
content_preview=self._visible_content_preview(content, limit=1200),
|
||||
raw_content=self._clip(content, limit=6000),
|
||||
)
|
||||
parsed = self._extract_json(content)
|
||||
if parsed is None:
|
||||
self._emit_event(
|
||||
"Model response parse failed",
|
||||
f"{label}: response was not valid JSON",
|
||||
kind="validation_result",
|
||||
label=label,
|
||||
validation_status="invalid_json",
|
||||
normalized_preview="",
|
||||
validation_errors=["response was not valid JSON"],
|
||||
)
|
||||
return None
|
||||
if isinstance(parsed, dict):
|
||||
detail = f"{label}: JSON keys {', '.join(sorted(str(k) for k in parsed.keys()))}"
|
||||
else:
|
||||
detail = f"{label}: JSON top-level type {type(parsed).__name__}"
|
||||
self._emit_event(
|
||||
"Model JSON parsed",
|
||||
detail,
|
||||
kind="model_parsed",
|
||||
label=label,
|
||||
normalized_preview=self._clip(json.dumps(parsed, ensure_ascii=False, indent=2), limit=6000),
|
||||
)
|
||||
return parsed
|
||||
|
||||
@staticmethod
|
||||
def _snippet(content: str, limit: int = 120) -> str:
|
||||
"""Compact streamed JSON text for display in the trace panel."""
|
||||
compact = " ".join((content or "").split())
|
||||
if len(compact) <= limit:
|
||||
return compact
|
||||
return "…" + compact[-limit:]
|
||||
|
||||
@staticmethod
|
||||
def _visible_content_preview(content: str, limit: int = 1200) -> str:
|
||||
"""Return a readable preview of model JSON, preserving non-ASCII text."""
|
||||
parsed = LLMStages._extract_json(content)
|
||||
if parsed is not None:
|
||||
return LLMStages._clip(json.dumps(parsed, ensure_ascii=False, indent=2), limit=limit)
|
||||
return LLMStages._snippet(content, limit=limit)
|
||||
|
||||
@staticmethod
|
||||
def _clip(content: str, limit: int = 6000) -> str:
|
||||
"""Clip visible model text for UI display without changing parser behavior."""
|
||||
text = str(content or "")
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
return text[:limit] + "\n…[truncated]"
|
||||
|
||||
@staticmethod
|
||||
def _extract_json(content: str) -> Any | None:
|
||||
"""Extract direct, fenced, or prose-wrapped JSON from model output."""
|
||||
if not content:
|
||||
return None
|
||||
try:
|
||||
return json.loads(content)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
match = re.search(r"\{.*\}", content, re.DOTALL)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
return json.loads(match.group(0))
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
text = str(content).strip()
|
||||
for candidate in LLMStages._json_candidates(text):
|
||||
try:
|
||||
return json.loads(candidate)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
continue
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _json_candidates(text: str) -> list[str]:
|
||||
"""Return likely JSON substrings, preserving arrays for semantic validation."""
|
||||
candidates = [text]
|
||||
fence = re.search(r"```(?:json)?\s*(.*?)\s*```", text, re.DOTALL | re.IGNORECASE)
|
||||
if fence:
|
||||
candidates.append(fence.group(1).strip())
|
||||
for opener, closer in (("{", "}"), ("[", "]")):
|
||||
start = text.find(opener)
|
||||
end = text.rfind(closer)
|
||||
if start != -1 and end > start:
|
||||
candidates.append(text[start:end + 1])
|
||||
unique: list[str] = []
|
||||
for candidate in candidates:
|
||||
if candidate and candidate not in unique:
|
||||
unique.append(candidate)
|
||||
return unique
|
||||
@@ -0,0 +1,350 @@
|
||||
"""Semantic validators for LLM stage outputs.
|
||||
|
||||
These checks keep local/cloud model responses grounded in workbook evidence:
|
||||
models may only refer to sheets, headers, SQL targets, and confidence values that
|
||||
exist in the current request context.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
import unicodedata
|
||||
|
||||
|
||||
ALLOWED_SHEET_TYPES = {"detail", "definition", "other"}
|
||||
ALLOWED_MATCH_STRATEGIES = {"value_token", "value_prefix", "value_exact", "value_contains"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ValidationResult:
|
||||
"""Validation result with normalized data, fatal errors, and salvage warnings."""
|
||||
valid: bool
|
||||
data: dict = field(default_factory=dict)
|
||||
errors: list[str] = field(default_factory=list)
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def validate_sheet_structure(sheet_name: str, raw_rows: list[list[Any]], data: Any) -> ValidationResult:
|
||||
"""Validate Stage 1 sheet-structure JSON against raw worksheet cells.
|
||||
|
||||
Small models often add one blank/invented column to an otherwise useful
|
||||
response. Treat those rows as salvageable warnings and drop them; keep
|
||||
header_row/sheet_type problems fatal.
|
||||
"""
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
if not isinstance(data, dict):
|
||||
return ValidationResult(False, {}, ["response must be a JSON object"])
|
||||
|
||||
max_row = len(raw_rows)
|
||||
header_row = _as_int(data.get("header_row"), default=None)
|
||||
if header_row is None:
|
||||
errors.append("header_row must be an integer")
|
||||
header_row = 1
|
||||
elif header_row < 1 or header_row > max(max_row, 1):
|
||||
errors.append(f"header_row {header_row} is outside sheet '{sheet_name}' row range 1-{max_row}")
|
||||
|
||||
sheet_type = str(data.get("sheet_type", "other") or "other").strip()
|
||||
if sheet_type not in ALLOWED_SHEET_TYPES:
|
||||
errors.append(f"sheet_type '{sheet_type}' is not one of {sorted(ALLOWED_SHEET_TYPES)}")
|
||||
sheet_type = "other"
|
||||
|
||||
cell_values = _cell_value_set(raw_rows)
|
||||
columns = []
|
||||
raw_columns = data.get("columns", [])
|
||||
raw_columns_was_list = isinstance(raw_columns, list)
|
||||
if not raw_columns_was_list:
|
||||
errors.append("columns must be a list")
|
||||
raw_columns = []
|
||||
for idx, col in enumerate(raw_columns):
|
||||
if not isinstance(col, dict):
|
||||
warnings.append(f"columns[{idx}] must be an object; dropped")
|
||||
continue
|
||||
header = str(col.get("header", "") or "").strip()
|
||||
if not header:
|
||||
warnings.append(f"columns[{idx}] has a blank header; dropped")
|
||||
continue
|
||||
if header not in cell_values:
|
||||
warnings.append(f"column header '{header}' was not found in sheet '{sheet_name}'; dropped")
|
||||
continue
|
||||
samples = col.get("samples", [])
|
||||
if not isinstance(samples, list):
|
||||
warnings.append(f"columns[{idx}].samples must be a list; coerced to empty list")
|
||||
samples = []
|
||||
columns.append({
|
||||
"header": header,
|
||||
"samples": [str(s) for s in samples[:5]],
|
||||
"meaning": str(col.get("meaning", "") or ""),
|
||||
})
|
||||
|
||||
if raw_columns_was_list and raw_columns and not columns:
|
||||
errors.append("columns did not contain any valid workbook headers")
|
||||
|
||||
shared_values = []
|
||||
raw_shared = data.get("shared_values", [])
|
||||
if not isinstance(raw_shared, list):
|
||||
errors.append("shared_values must be a list")
|
||||
raw_shared = []
|
||||
for idx, item in enumerate(raw_shared):
|
||||
if not isinstance(item, dict):
|
||||
warnings.append(f"shared_values[{idx}] must be an object; dropped")
|
||||
continue
|
||||
label = str(item.get("label", "") or "").strip()
|
||||
value = str(item.get("value", "") or "").strip()
|
||||
if label or value:
|
||||
shared_values.append({"label": label, "value": value})
|
||||
|
||||
normalized = {
|
||||
"header_row": header_row,
|
||||
"sheet_type": sheet_type,
|
||||
"columns": columns,
|
||||
"shared_values": shared_values,
|
||||
}
|
||||
fatal_errors = list(errors)
|
||||
if fatal_errors:
|
||||
fatal_errors.extend(warnings)
|
||||
return ValidationResult(not fatal_errors, normalized, fatal_errors, warnings if not fatal_errors else [])
|
||||
|
||||
|
||||
def validate_sheet_links(summaries: list[Any], data: Any) -> ValidationResult:
|
||||
"""Validate Stage 2 cross-sheet link JSON against Stage 1 summaries."""
|
||||
errors: list[str] = []
|
||||
if not isinstance(data, dict):
|
||||
return ValidationResult(False, {}, ["response must be a JSON object"])
|
||||
|
||||
sheet_names = {s.sheet_name for s in summaries}
|
||||
columns_by_sheet = {
|
||||
s.sheet_name: {str(c.get("header", "") or "").strip() for c in s.columns if c.get("header")}
|
||||
for s in summaries
|
||||
}
|
||||
|
||||
groups = []
|
||||
raw_groups = data.get("groups", [])
|
||||
if not isinstance(raw_groups, list):
|
||||
errors.append("groups must be a list")
|
||||
raw_groups = []
|
||||
|
||||
for gi, group in enumerate(raw_groups):
|
||||
if not isinstance(group, dict):
|
||||
errors.append(f"groups[{gi}] must be an object")
|
||||
continue
|
||||
sheets = [str(s).strip() for s in group.get("sheets", []) if str(s).strip()]
|
||||
if not sheets:
|
||||
errors.append(f"groups[{gi}].sheets must include at least one sheet")
|
||||
for sheet in sheets:
|
||||
if sheet not in sheet_names:
|
||||
errors.append(f"groups[{gi}] references unknown sheet '{sheet}'")
|
||||
master_sheet = str(group.get("master_sheet", "") or "").strip()
|
||||
if master_sheet not in sheet_names:
|
||||
errors.append(f"groups[{gi}].master_sheet references unknown sheet '{master_sheet}'")
|
||||
|
||||
links = []
|
||||
raw_links = group.get("links", [])
|
||||
if not isinstance(raw_links, list):
|
||||
errors.append(f"groups[{gi}].links must be a list")
|
||||
raw_links = []
|
||||
for li, link in enumerate(raw_links):
|
||||
if not isinstance(link, dict):
|
||||
errors.append(f"groups[{gi}].links[{li}] must be an object")
|
||||
continue
|
||||
from_sheet = str(link.get("from_sheet", "") or "").strip()
|
||||
to_sheet = str(link.get("to_sheet", "") or "").strip()
|
||||
from_column = str(link.get("from_column", "") or "").strip()
|
||||
to_column = str(link.get("to_column", "") or "").strip()
|
||||
if from_sheet not in sheet_names:
|
||||
errors.append(f"link {gi}.{li} references unknown from_sheet '{from_sheet}'")
|
||||
if to_sheet not in sheet_names:
|
||||
errors.append(f"link {gi}.{li} references unknown to_sheet '{to_sheet}'")
|
||||
if from_sheet in columns_by_sheet and from_column not in columns_by_sheet[from_sheet]:
|
||||
errors.append(f"link {gi}.{li} references unknown column '{from_column}' in sheet '{from_sheet}'")
|
||||
if to_sheet in columns_by_sheet and to_column not in columns_by_sheet[to_sheet]:
|
||||
errors.append(f"link {gi}.{li} references unknown column '{to_column}' in sheet '{to_sheet}'")
|
||||
strategy = str(link.get("match_strategy", "") or "").strip()
|
||||
if strategy not in ALLOWED_MATCH_STRATEGIES:
|
||||
errors.append(f"link {gi}.{li}.match_strategy '{strategy}' is invalid")
|
||||
strategy = "value_token"
|
||||
confidence = _as_float(link.get("confidence"), default=None)
|
||||
if confidence is None or confidence < 0 or confidence > 1:
|
||||
errors.append(f"link {gi}.{li}.confidence must be between 0 and 1")
|
||||
confidence = 0.0
|
||||
links.append({
|
||||
"from_sheet": from_sheet,
|
||||
"from_column": from_column,
|
||||
"to_sheet": to_sheet,
|
||||
"to_column": to_column,
|
||||
"key_pattern": str(link.get("key_pattern", "") or ""),
|
||||
"match_strategy": strategy,
|
||||
"confidence": confidence,
|
||||
"reason": str(link.get("reason", "") or ""),
|
||||
})
|
||||
groups.append({
|
||||
"sheets": sheets,
|
||||
"master_sheet": master_sheet,
|
||||
"master_reason": str(group.get("master_reason", "") or ""),
|
||||
"links": links,
|
||||
})
|
||||
|
||||
return ValidationResult(not errors, {"groups": groups}, errors)
|
||||
|
||||
|
||||
def validate_schema_mapping(summaries: list[Any], schema_fields: list[dict], data: Any) -> ValidationResult:
|
||||
"""Validate Stage 3 mapping JSON against discovered headers and SQL schema.
|
||||
|
||||
Invalid mapping rows are dropped if at least one valid mapping remains. This
|
||||
keeps a small-model typo from forcing a full retry/fallback.
|
||||
"""
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
if not isinstance(data, dict):
|
||||
return ValidationResult(False, {}, ["response must be a JSON object"])
|
||||
|
||||
known_excel = {
|
||||
str(c.get("header", "") or "").strip()
|
||||
for s in summaries
|
||||
for c in s.columns
|
||||
if c.get("header")
|
||||
}
|
||||
known_excel_lookup, ambiguous_excel_keys = _build_excel_header_lookup(known_excel)
|
||||
valid_sql = {str(f.get("name", "") or "").strip() for f in schema_fields if f.get("name")}
|
||||
|
||||
mappings = []
|
||||
raw_mapping = data.get("mapping", [])
|
||||
raw_mapping_was_list = isinstance(raw_mapping, list)
|
||||
if not raw_mapping_was_list:
|
||||
errors.append("mapping must be a list")
|
||||
raw_mapping = []
|
||||
for idx, item in enumerate(raw_mapping):
|
||||
row_errors: list[str] = []
|
||||
if not isinstance(item, dict):
|
||||
warnings.append(f"mapping[{idx}] must be an object; dropped")
|
||||
continue
|
||||
excel = str(item.get("excel", "") or "").strip()
|
||||
sql = str(item.get("sql", "") or "").strip()
|
||||
matched_excel = _resolve_excel_header(excel, known_excel, known_excel_lookup, ambiguous_excel_keys)
|
||||
if matched_excel is None:
|
||||
row_errors.append(f"mapping[{idx}] references unknown Excel column '{excel}'")
|
||||
else:
|
||||
excel = matched_excel
|
||||
if sql not in valid_sql:
|
||||
row_errors.append(f"mapping[{idx}] references unknown SQL target '{sql}'")
|
||||
confidence = _as_float(item.get("confidence"), default=None)
|
||||
if confidence is None or confidence < 0 or confidence > 1:
|
||||
row_errors.append(f"mapping[{idx}].confidence must be between 0 and 1")
|
||||
confidence = 0.0
|
||||
if row_errors:
|
||||
warnings.extend(f"{msg}; dropped" for msg in row_errors)
|
||||
continue
|
||||
mappings.append({
|
||||
"excel": excel,
|
||||
"sql": sql,
|
||||
"confidence": confidence,
|
||||
"reason": str(item.get("reason", "") or ""),
|
||||
})
|
||||
|
||||
if raw_mapping_was_list and raw_mapping and not mappings:
|
||||
errors.append("mapping did not contain any valid Excel-to-SQL rows")
|
||||
|
||||
conflicts = []
|
||||
raw_conflicts = data.get("conflicts", [])
|
||||
if raw_conflicts is not None and not isinstance(raw_conflicts, list):
|
||||
errors.append("conflicts must be a list")
|
||||
raw_conflicts = []
|
||||
for idx, item in enumerate(raw_conflicts or []):
|
||||
if not isinstance(item, dict):
|
||||
errors.append(f"conflicts[{idx}] must be an object")
|
||||
continue
|
||||
excel = str(item.get("excel", "") or "").strip()
|
||||
suggested_sql = str(item.get("suggested_sql", "") or "").strip()
|
||||
known_sql = str(item.get("known_sql", "") or "").strip()
|
||||
matched_excel = _resolve_excel_header(excel, known_excel, known_excel_lookup, ambiguous_excel_keys) if excel else ""
|
||||
if excel and matched_excel is None:
|
||||
errors.append(f"conflicts[{idx}] references unknown Excel column '{excel}'")
|
||||
elif matched_excel:
|
||||
excel = matched_excel
|
||||
if suggested_sql and suggested_sql not in valid_sql:
|
||||
errors.append(f"conflicts[{idx}] references unknown suggested_sql '{suggested_sql}'")
|
||||
if known_sql and known_sql not in valid_sql:
|
||||
errors.append(f"conflicts[{idx}] references unknown known_sql '{known_sql}'")
|
||||
confidence = _as_float(item.get("confidence"), default=0.0)
|
||||
if confidence < 0 or confidence > 1:
|
||||
errors.append(f"conflicts[{idx}].confidence must be between 0 and 1")
|
||||
confidence = 0.0
|
||||
conflicts.append({
|
||||
"excel": excel,
|
||||
"suggested_sql": suggested_sql,
|
||||
"known_sql": known_sql,
|
||||
"confidence": confidence,
|
||||
"reason": str(item.get("reason", "") or ""),
|
||||
})
|
||||
|
||||
fatal_errors = list(errors)
|
||||
if fatal_errors:
|
||||
fatal_errors.extend(warnings)
|
||||
return ValidationResult(not fatal_errors, {"mapping": mappings, "conflicts": conflicts}, fatal_errors, warnings if not fatal_errors else [])
|
||||
|
||||
|
||||
def _build_excel_header_lookup(headers: set[str]) -> tuple[dict[str, str], set[str]]:
|
||||
"""Return a Unicode-width-insensitive lookup for known Excel headers.
|
||||
|
||||
This accepts small-model punctuation/width drift such as QTY(pcs) vs
|
||||
QTY(pcs), but only when the normalized key uniquely identifies one real
|
||||
parser-detected header.
|
||||
"""
|
||||
lookup: dict[str, str] = {}
|
||||
ambiguous: set[str] = set()
|
||||
for header in headers:
|
||||
key = _canonical_excel_header(header)
|
||||
if not key:
|
||||
continue
|
||||
if key in lookup and lookup[key] != header:
|
||||
ambiguous.add(key)
|
||||
continue
|
||||
lookup[key] = header
|
||||
for key in ambiguous:
|
||||
lookup.pop(key, None)
|
||||
return lookup, ambiguous
|
||||
|
||||
|
||||
def _resolve_excel_header(
|
||||
value: str,
|
||||
known_excel: set[str],
|
||||
lookup: dict[str, str],
|
||||
ambiguous: set[str],
|
||||
) -> str | None:
|
||||
"""Resolve a model-supplied Excel header to the exact parser header."""
|
||||
if value in known_excel:
|
||||
return value
|
||||
key = _canonical_excel_header(value)
|
||||
if not key or key in ambiguous:
|
||||
return None
|
||||
return lookup.get(key)
|
||||
|
||||
|
||||
def _canonical_excel_header(value: str) -> str:
|
||||
"""Normalize width, punctuation, and whitespace for header matching only."""
|
||||
normalized = unicodedata.normalize("NFKC", str(value or "")).strip().casefold()
|
||||
return " ".join(normalized.split())
|
||||
|
||||
|
||||
def _cell_value_set(raw_rows: list[list[Any]]) -> set[str]:
|
||||
values: set[str] = set()
|
||||
for row in raw_rows:
|
||||
for cell in row:
|
||||
text = str(cell).strip() if cell is not None else ""
|
||||
if text:
|
||||
values.add(text)
|
||||
return values
|
||||
|
||||
|
||||
def _as_int(value: Any, default: int | None = None) -> int | None:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _as_float(value: Any, default: float | None = None) -> float | None:
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
@@ -1,133 +0,0 @@
|
||||
"""Matching orchestrator: LLM judge first (full config generation), fuzzy fallback.
|
||||
Returns unified MatchResult list tagged with the engine that produced each match."""
|
||||
from services.config_manager import ConfigManager
|
||||
from services.excel_parser import ParsedWorkbook
|
||||
from services.fuzzy_matcher import FuzzyMatcher, MatchResult
|
||||
from services.llm_matcher import LLMMatcher, LLMRelation
|
||||
|
||||
|
||||
class MatchingService:
|
||||
"""Coordinates LLM and fuzzy matchers with automatic fallback."""
|
||||
|
||||
def __init__(self, config_manager: ConfigManager):
|
||||
self.cm = config_manager
|
||||
self.llm = LLMMatcher(config_manager)
|
||||
self.fuzzy = FuzzyMatcher(config_manager)
|
||||
self._last_generated_config: dict | None = None
|
||||
|
||||
def get_generated_config(self) -> dict | None:
|
||||
"""Return the full LLM-generated config, or None if not available."""
|
||||
return self._last_generated_config
|
||||
|
||||
def match(
|
||||
self,
|
||||
parsed_workbook: ParsedWorkbook,
|
||||
type_id: str | None = None,
|
||||
) -> list[MatchResult]:
|
||||
"""Match all detected headers. Tries LLM first; falls back to fuzzy."""
|
||||
ordered_headers: list[str] = []
|
||||
header_samples: dict[str, list[str]] = {}
|
||||
for sheet in parsed_workbook.sheets:
|
||||
for col_idx, header in enumerate(sheet.detected_headers):
|
||||
if not header or header in header_samples:
|
||||
continue
|
||||
ordered_headers.append(header)
|
||||
samples = []
|
||||
for row in sheet.raw_data[sheet.data_start_row - 1:sheet.data_end_row]:
|
||||
if col_idx < len(row) and row[col_idx] is not None:
|
||||
samples.append(str(row[col_idx]))
|
||||
if len(samples) >= 3:
|
||||
break
|
||||
header_samples[header] = samples
|
||||
|
||||
self._last_generated_config = None
|
||||
|
||||
# ── LLM: full config generation (primary) ──
|
||||
if self.cm.is_llm_enabled():
|
||||
source_columns = [
|
||||
{"header": h, "samples": header_samples[h]} for h in ordered_headers
|
||||
]
|
||||
target_columns = [
|
||||
{"name": c["name"], "description": c.get("description", "")}
|
||||
for c in self.cm.get_db_schema()
|
||||
]
|
||||
sheets_info = [
|
||||
{"name": s.name, "columns": [
|
||||
{"header": h, "samples": header_samples.get(h, [])}
|
||||
for h in s.detected_headers if h
|
||||
]}
|
||||
for s in parsed_workbook.sheets
|
||||
]
|
||||
gen_config = self.llm.generate_config(source_columns, target_columns, sheets_info)
|
||||
if gen_config and gen_config.get("mapping"):
|
||||
self._last_generated_config = gen_config
|
||||
results: list[MatchResult] = []
|
||||
llm_map = {p: m["target"] for m in gen_config.get("mapping", [])
|
||||
for p in m.get("source_patterns", [])}
|
||||
for h in ordered_headers:
|
||||
target = llm_map.get(h, "")
|
||||
results.append(MatchResult(
|
||||
source_header=h, matched_target=target,
|
||||
confidence=90.0, engine="llm",
|
||||
reason=gen_config.get("analysis", "LLM 分析生成"),
|
||||
))
|
||||
return results
|
||||
|
||||
# ── LLM: per-column fallback ──
|
||||
llm_matches = self.llm.match_columns(source_columns, target_columns)
|
||||
if llm_matches:
|
||||
llm_by_source = {m.source_header: m for m in llm_matches}
|
||||
results: list[MatchResult] = []
|
||||
for h in ordered_headers:
|
||||
m = llm_by_source.get(h)
|
||||
if m:
|
||||
results.append(MatchResult(
|
||||
source_header=h, matched_target=m.target,
|
||||
confidence=round(m.confidence * 100, 1),
|
||||
reason=m.reason, engine="llm",
|
||||
))
|
||||
else:
|
||||
results.append(MatchResult(source_header=h, matched_target="",
|
||||
engine="llm"))
|
||||
return results
|
||||
|
||||
# Fallback: fuzzy
|
||||
fuzzy_results = self.fuzzy.match(ordered_headers, type_id=type_id)
|
||||
for r in fuzzy_results:
|
||||
r.engine = "fuzzy"
|
||||
return fuzzy_results
|
||||
|
||||
def detect_relations(self, parsed_workbook: ParsedWorkbook) -> list[LLMRelation]:
|
||||
"""Detect cross-sheet relations via LLM. Returns [] if LLM off.
|
||||
If a full config was already generated, returns its sheet_relations."""
|
||||
# Already have relations from generate_config
|
||||
if self._last_generated_config:
|
||||
sr_list = self._last_generated_config.get("sheet_relations", [])
|
||||
return [
|
||||
LLMRelation(
|
||||
source_sheet=sr.get("source_sheet", ""),
|
||||
source_column=sr.get("source_key", ""),
|
||||
target_sheet=sr.get("target_sheet", ""),
|
||||
target_column=sr.get("target_column", ""),
|
||||
confidence=0.90,
|
||||
reason=sr.get("reason", "LLM 分析生成"),
|
||||
) for sr in sr_list
|
||||
]
|
||||
if not self.cm.is_llm_enabled():
|
||||
return []
|
||||
sheets_info = []
|
||||
for sheet in parsed_workbook.sheets:
|
||||
cols = []
|
||||
for col_idx, header in enumerate(sheet.detected_headers):
|
||||
if not header:
|
||||
continue
|
||||
samples = []
|
||||
for row in sheet.raw_data[sheet.data_start_row - 1:sheet.data_end_row]:
|
||||
if col_idx < len(row) and row[col_idx] is not None:
|
||||
samples.append(str(row[col_idx]))
|
||||
if len(samples) >= 3:
|
||||
break
|
||||
cols.append({"header": header, "samples": samples})
|
||||
if cols:
|
||||
sheets_info.append({"name": sheet.name, "columns": cols})
|
||||
return self.llm.detect_relations(sheets_info)
|
||||
@@ -59,6 +59,7 @@ class MergeEngine:
|
||||
|
||||
@staticmethod
|
||||
def _col_index(headers: list[str], name: str) -> int | None:
|
||||
"""Return a column index from a case-insensitive header lookup."""
|
||||
for i, h in enumerate(headers):
|
||||
if h is not None and str(h).strip() == str(name).strip():
|
||||
return i
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Review-stage helper functions for human-in-the-loop workbook cleanup."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
from services.excel_parser import ParsedSheet
|
||||
from services.llm_stages import ColumnMapping
|
||||
from services.workbook_analyzer import AnalysisResult
|
||||
from utils.helpers import normalize_header
|
||||
|
||||
|
||||
def apply_header_row_override(sheet: ParsedSheet, header_row: int) -> ParsedSheet:
|
||||
"""Apply a 1-indexed header-row override to a parsed sheet in place.
|
||||
|
||||
The parser already keeps the raw worksheet rows. Rebuilding the header list
|
||||
from ``raw_data`` is enough for the Review UI to update downstream mapping
|
||||
choices without reparsing the original workbook file.
|
||||
"""
|
||||
safe_header_row = max(1, min(int(header_row), max(len(sheet.raw_data), 1)))
|
||||
sheet.header_row = safe_header_row
|
||||
sheet.data_start_row = safe_header_row + 1
|
||||
if sheet.data_end_row < sheet.data_start_row:
|
||||
sheet.data_end_row = sheet.rows or len(sheet.raw_data)
|
||||
|
||||
header_idx = safe_header_row - 1
|
||||
source_row = sheet.raw_data[header_idx] if header_idx < len(sheet.raw_data) else []
|
||||
detected_headers: list[str] = []
|
||||
col_headers: dict[int, str] = {}
|
||||
col_count = max(sheet.cols, len(source_row))
|
||||
for col_idx in range(col_count):
|
||||
raw_value = source_row[col_idx] if col_idx < len(source_row) else None
|
||||
header = normalize_header(str(raw_value)) if raw_value not in (None, "") else ""
|
||||
detected_headers.append(header)
|
||||
if header:
|
||||
col_headers[col_idx] = header
|
||||
sheet.detected_headers = detected_headers
|
||||
sheet.col_headers = col_headers
|
||||
return sheet
|
||||
|
||||
|
||||
def build_column_mapping_result(result: AnalysisResult, manual_mappings: dict[str, str]) -> AnalysisResult:
|
||||
"""Return a copy of ``result`` with operator-reviewed mappings applied.
|
||||
|
||||
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()
|
||||
]
|
||||
return replace(result, mappings=mappings, engine="manual")
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Deterministic row-quality checks for export preview."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RowQualityRecord:
|
||||
"""One row plus quality metadata, preserving its original position."""
|
||||
index: int
|
||||
row: dict
|
||||
populated_fields: int
|
||||
reason: str = ""
|
||||
restored: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RowQualityResult:
|
||||
"""Accepted/dropped row split plus the final export-order row list."""
|
||||
accepted: list[RowQualityRecord]
|
||||
dropped: list[RowQualityRecord]
|
||||
export_rows: list[RowQualityRecord]
|
||||
|
||||
|
||||
def _is_populated(value) -> bool:
|
||||
if value is None:
|
||||
return False
|
||||
text = str(value).strip()
|
||||
return bool(text) and text.lower() not in {"nan", "none", "null"}
|
||||
|
||||
|
||||
def split_rows_by_quality(
|
||||
rows: list[dict],
|
||||
*,
|
||||
key_columns: Iterable[str] | None = None,
|
||||
restore_indexes: Iterable[int] | None = None,
|
||||
sparse_threshold: int = 2,
|
||||
) -> RowQualityResult:
|
||||
"""Split rows into accepted and suggested-dropped lists.
|
||||
|
||||
Rows with very few populated fields are usually subtotal/title/noise rows in
|
||||
this import flow. They are not deleted: they go to a dropped list and can be
|
||||
restored by original row index before export.
|
||||
"""
|
||||
key_columns = set(key_columns or [])
|
||||
restore_indexes = set(restore_indexes or set())
|
||||
accepted: list[RowQualityRecord] = []
|
||||
dropped: list[RowQualityRecord] = []
|
||||
export_records: list[RowQualityRecord] = []
|
||||
|
||||
for idx, row in enumerate(rows):
|
||||
populated = sum(1 for value in row.values() if _is_populated(value))
|
||||
has_key = any(_is_populated(row.get(col)) for col in key_columns)
|
||||
reason = ""
|
||||
if populated == 0:
|
||||
reason = "Empty row"
|
||||
elif populated <= sparse_threshold:
|
||||
reason = f"Only {populated} populated field{'s' if populated != 1 else ''}"
|
||||
if has_key:
|
||||
reason += " — review before export"
|
||||
record = RowQualityRecord(idx, row, populated, reason=reason, restored=idx in restore_indexes)
|
||||
if reason:
|
||||
dropped.append(record)
|
||||
if record.restored:
|
||||
export_records.append(record)
|
||||
else:
|
||||
accepted.append(record)
|
||||
export_records.append(record)
|
||||
|
||||
export_records.sort(key=lambda item: item.index)
|
||||
return RowQualityResult(accepted=accepted, dropped=dropped, export_rows=export_records)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Admin password hashing and verification helpers.
|
||||
|
||||
The app intentionally uses a lightweight single-password gate for LAN-only
|
||||
system settings. Passwords are stored only as salted PBKDF2 hashes in the
|
||||
project-owned runtime config file.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
|
||||
ALGORITHM = "pbkdf2_sha256"
|
||||
DEFAULT_ITERATIONS = 260_000
|
||||
|
||||
|
||||
def _b64(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _unb64(text: str) -> bytes:
|
||||
padded = text + "=" * (-len(text) % 4)
|
||||
return base64.urlsafe_b64decode(padded.encode("ascii"))
|
||||
|
||||
|
||||
def hash_password(password: str, *, salt: bytes | None = None, iterations: int = DEFAULT_ITERATIONS) -> str:
|
||||
"""Return a salted PBKDF2-SHA256 hash string for an admin password."""
|
||||
if not password:
|
||||
raise ValueError("password must not be empty")
|
||||
salt = salt or os.urandom(16)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, int(iterations))
|
||||
return f"{ALGORITHM}${int(iterations)}${_b64(salt)}${_b64(digest)}"
|
||||
|
||||
|
||||
def is_configured_hash(encoded: str | None) -> bool:
|
||||
"""True when a value looks like a supported admin password hash."""
|
||||
if not encoded:
|
||||
return False
|
||||
parts = str(encoded).split("$")
|
||||
if len(parts) != 4:
|
||||
return False
|
||||
algorithm, iterations, salt, digest = parts
|
||||
if algorithm != ALGORITHM:
|
||||
return False
|
||||
try:
|
||||
int(iterations)
|
||||
return bool(salt and digest)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def verify_password(password: str, encoded: str | None) -> bool:
|
||||
"""Return True only if password matches the stored hash."""
|
||||
if not password or not is_configured_hash(encoded):
|
||||
return False
|
||||
try:
|
||||
algorithm, iterations_text, salt_text, digest_text = str(encoded).split("$", 3)
|
||||
if algorithm != ALGORITHM:
|
||||
return False
|
||||
iterations = int(iterations_text)
|
||||
salt = _unb64(salt_text)
|
||||
expected = _unb64(digest_text)
|
||||
actual = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
||||
return hmac.compare_digest(actual, expected)
|
||||
except Exception:
|
||||
return False
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Text normalization + token utilities for value matching across sheets.
|
||||
|
||||
Shared by the merge engine. Separated from value_matcher (which has its own
|
||||
copy) so the new rewrite does not modify existing code.
|
||||
Shared by the merge engine so cross-sheet keys use one deterministic policy.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Reusable support notes learned from approved AI mapping reports."""
|
||||
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")
|
||||
|
||||
|
||||
def build_type_support_notes(
|
||||
type_id: str,
|
||||
workbook_name: str,
|
||||
result: AnalysisResult,
|
||||
report: dict[str, list[dict]],
|
||||
) -> dict[str, Any]:
|
||||
"""Build stable, reusable type-scoped notes from an approved AI report.
|
||||
|
||||
The output intentionally keeps guidance-level facts only: preferred headers,
|
||||
join hints, and mapping guidance. It does not store raw prompts, API keys,
|
||||
row dumps, or transient run timings.
|
||||
"""
|
||||
source_type = _safe_type_id(type_id)
|
||||
mapping_rows = report.get("mapping_decisions") or []
|
||||
join_rows = report.get("join_decisions") or []
|
||||
|
||||
header_aliases: list[dict[str, Any]] = []
|
||||
mapping_guidance: list[dict[str, str]] = []
|
||||
seen_aliases: set[tuple[str, str]] = set()
|
||||
for row in mapping_rows:
|
||||
sql_target = _clean(row.get("sql_target"))
|
||||
source = _clean(row.get("chosen_source"))
|
||||
if not sql_target or not source:
|
||||
continue
|
||||
key = (sql_target, source)
|
||||
if key in seen_aliases:
|
||||
continue
|
||||
seen_aliases.add(key)
|
||||
reason = _clean(row.get("reason") or row.get("evidence") or "Accepted mapping decision")
|
||||
header_aliases.append({
|
||||
"sql_target": sql_target,
|
||||
"preferred_headers": [source],
|
||||
"avoid_headers": [],
|
||||
"reason": reason,
|
||||
})
|
||||
mapping_guidance.append({
|
||||
"sql_target": sql_target,
|
||||
"source_header": source,
|
||||
"condition": "Use for matching workbooks of this Type when the header is present.",
|
||||
"reason": reason,
|
||||
})
|
||||
|
||||
join_hints: list[dict[str, str]] = []
|
||||
seen_joins: set[str] = set()
|
||||
for row in join_rows:
|
||||
join_key = _clean(row.get("join_key"))
|
||||
if not join_key or join_key in seen_joins:
|
||||
continue
|
||||
seen_joins.add(join_key)
|
||||
join_hints.append({
|
||||
"master_sheet": _clean(row.get("master_sheet")),
|
||||
"lookup_sheet": _clean(row.get("linked_sheet")),
|
||||
"pattern": join_key,
|
||||
"strategy": _clean(row.get("strategy")),
|
||||
"reason": _clean(row.get("reason")),
|
||||
})
|
||||
|
||||
notes = {
|
||||
"version": 1,
|
||||
"source_type": source_type,
|
||||
"updated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"learned_from": {
|
||||
"workbook_name": _clean(workbook_name),
|
||||
"engine": _clean(result.engine),
|
||||
},
|
||||
"notes": {
|
||||
"header_aliases": header_aliases,
|
||||
"join_hints": join_hints,
|
||||
"mapping_guidance": mapping_guidance,
|
||||
},
|
||||
}
|
||||
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:
|
||||
return ""
|
||||
payload = notes.get("notes") or {}
|
||||
lines = ["TYPE SUPPORT NOTES (hints for this selected workbook Type; do not override workbook evidence):"]
|
||||
for item in payload.get("header_aliases") or []:
|
||||
headers = ", ".join(str(h) for h in item.get("preferred_headers", []) if str(h).strip())
|
||||
if headers:
|
||||
lines.append(f"- Prefer header(s) {headers} for SQL target {item.get('sql_target', '')}. Reason: {item.get('reason', '')}")
|
||||
for item in payload.get("join_hints") or []:
|
||||
lines.append(
|
||||
f"- Join hint: {item.get('pattern', '')} using {item.get('strategy', '')}. "
|
||||
f"Reason: {item.get('reason', '')}"
|
||||
)
|
||||
for item in payload.get("mapping_guidance") or []:
|
||||
lines.append(
|
||||
f"- Mapping guidance: {item.get('source_header', '')} -> {item.get('sql_target', '')}. "
|
||||
f"{item.get('condition', '')} Reason: {item.get('reason', '')}"
|
||||
)
|
||||
text = "\n".join(_clean(line) for line in lines if _clean(line))
|
||||
return text[:limit]
|
||||
|
||||
|
||||
def _safe_type_id(type_id: str) -> str:
|
||||
safe = "".join(ch if ch.isalnum() or ch in {"_", "-"} else "_" for ch in str(type_id).strip())
|
||||
return safe or "unknown"
|
||||
|
||||
|
||||
def _clean(value: Any) -> str:
|
||||
text = " ".join(str(value or "").split())
|
||||
lower = text.lower()
|
||||
if any(word in lower for word in _SECRET_WORDS):
|
||||
return "[REDACTED]"
|
||||
return text[:500]
|
||||
|
||||
|
||||
def _drop_secret_like_values(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
cleaned = {}
|
||||
for key, child in value.items():
|
||||
key_text = str(key)
|
||||
if any(word in key_text.lower() for word in _SECRET_WORDS):
|
||||
cleaned[key_text] = "[REDACTED]"
|
||||
else:
|
||||
cleaned[key_text] = _drop_secret_like_values(child)
|
||||
return cleaned
|
||||
if isinstance(value, list):
|
||||
return [_drop_secret_like_values(item) for item in value]
|
||||
if isinstance(value, str):
|
||||
return _clean(value)
|
||||
return value
|
||||
@@ -1,215 +0,0 @@
|
||||
"""Cross-sheet value-level matching engine.
|
||||
|
||||
Matches cell values between sheets using configurable strategies:
|
||||
prefix, suffix, contains, token_match, exact, pattern.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
# Common full-width → half-width mapping for alphanumerics
|
||||
_FW_TO_HW = str.maketrans(
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ValueMatch:
|
||||
"""A single cross-sheet value match result."""
|
||||
key: str
|
||||
target_row_idx: int # 0-indexed row in the target sheet
|
||||
matched_column: str
|
||||
matched_value: str
|
||||
strategy: str
|
||||
confidence: float = 1.0
|
||||
|
||||
|
||||
class ValueMatcher:
|
||||
"""Matches a key value against rows in a target sheet using multiple strategies."""
|
||||
|
||||
def __init__(self, strategies: list[str] | None = None):
|
||||
self.strategies = strategies or ["prefix", "suffix", "contains", "token_match", "exact", "pattern"]
|
||||
|
||||
def match(
|
||||
self,
|
||||
key: str,
|
||||
target_rows: list[list], # raw data rows from target sheet
|
||||
target_headers: list[str], # column headers for target sheet
|
||||
match_rules: list[dict], # [{column, strategy, pattern?}]
|
||||
) -> list[ValueMatch]:
|
||||
"""
|
||||
For each match rule, scan target rows for a value matching the key.
|
||||
Returns a list of ValueMatch results (one per successful rule).
|
||||
"""
|
||||
if not key or not key.strip():
|
||||
return []
|
||||
|
||||
key_norm = self._normalize(key.strip())
|
||||
results: list[ValueMatch] = []
|
||||
|
||||
for rule in match_rules:
|
||||
strategy = rule.get("strategy", "contains")
|
||||
col_name = rule.get("column", "")
|
||||
pattern_template = rule.get("pattern", "")
|
||||
|
||||
# Find column index
|
||||
col_idx = None
|
||||
for i, h in enumerate(target_headers):
|
||||
if h and h.strip() == col_name.strip():
|
||||
col_idx = i
|
||||
break
|
||||
if col_idx is None:
|
||||
continue
|
||||
|
||||
# Scan target rows
|
||||
for row_idx, row in enumerate(target_rows):
|
||||
if col_idx >= len(row):
|
||||
continue
|
||||
cell_val = str(row[col_idx]) if row[col_idx] is not None else ""
|
||||
cell_norm = self._normalize(cell_val)
|
||||
|
||||
matched = False
|
||||
if strategy == "exact":
|
||||
matched = (cell_norm == key_norm)
|
||||
elif strategy == "prefix":
|
||||
matched = cell_norm.startswith(key_norm)
|
||||
elif strategy == "suffix":
|
||||
matched = cell_norm.endswith(key_norm)
|
||||
elif strategy == "contains":
|
||||
matched = key_norm in cell_norm
|
||||
elif strategy == "token_match":
|
||||
# Key appears as a contiguous token sequence (bounded by
|
||||
# spaces, colons, parens, etc.). Supports multi-word keys
|
||||
# like 'last one' matching 'last one:room light'.
|
||||
matched = self._token_sequence_in(key_norm, cell_norm)
|
||||
elif strategy == "pattern":
|
||||
if pattern_template and "{key}" in pattern_template:
|
||||
# User template, e.g. "GRADE {key}:*"
|
||||
escaped = re.escape(pattern_template.replace("{key}", "___KEY___"))
|
||||
pattern = escaped.replace("___KEY___", r"(.+?)")
|
||||
m = re.search(pattern, cell_norm)
|
||||
matched = (m is not None)
|
||||
else:
|
||||
matched = key_norm in cell_norm
|
||||
else:
|
||||
matched = key_norm in cell_norm
|
||||
|
||||
if matched:
|
||||
results.append(ValueMatch(
|
||||
key=key,
|
||||
target_row_idx=row_idx,
|
||||
matched_column=col_name,
|
||||
matched_value=cell_val.strip(),
|
||||
strategy=strategy,
|
||||
))
|
||||
break # first match per rule wins
|
||||
|
||||
return results
|
||||
|
||||
def reverse_lookup(
|
||||
self,
|
||||
source_value: str,
|
||||
target_rows: list[list],
|
||||
target_headers: list[str],
|
||||
match_rules: list[dict],
|
||||
) -> ValueMatch | None:
|
||||
"""
|
||||
Scan all values in the target column; return the first row where a
|
||||
target value appears in the source_value (using the rule's strategy).
|
||||
|
||||
Use when the key is embedded in the source cell and you need to
|
||||
discover which target key matches. Example:
|
||||
|
||||
source_value = "GRADE A:Figure" (from Item detail)
|
||||
target column STYLE values: ["A", "B", "C", ..., "Last One"]
|
||||
strategy: token_match → "A" appears as token in "GRADE A:Figure" → match
|
||||
"""
|
||||
if not source_value or not source_value.strip():
|
||||
return None
|
||||
|
||||
src_norm = self._normalize(source_value.strip())
|
||||
|
||||
for rule in match_rules:
|
||||
strategy = rule.get("strategy", "contains")
|
||||
col_name = rule.get("column", "")
|
||||
|
||||
col_idx = None
|
||||
for i, h in enumerate(target_headers):
|
||||
if h and h.strip() == col_name.strip():
|
||||
col_idx = i
|
||||
break
|
||||
if col_idx is None:
|
||||
continue
|
||||
|
||||
# Collect (row_idx, value) pairs, deduplicated
|
||||
seen: set[str] = set()
|
||||
for row_idx, row in enumerate(target_rows):
|
||||
if col_idx >= len(row):
|
||||
continue
|
||||
tgt_val = str(row[col_idx]) if row[col_idx] is not None else ""
|
||||
tgt_norm = self._normalize(tgt_val)
|
||||
if not tgt_norm or tgt_norm in seen:
|
||||
continue
|
||||
seen.add(tgt_norm)
|
||||
|
||||
# Check: does tgt_norm appear in src_norm according to strategy?
|
||||
matched = self._test_match(key=tgt_norm, cell=src_norm, strategy=strategy)
|
||||
if matched:
|
||||
return ValueMatch(
|
||||
key=tgt_val.strip(),
|
||||
target_row_idx=row_idx,
|
||||
matched_column=col_name,
|
||||
matched_value=tgt_val.strip(),
|
||||
strategy=f"reverse_{strategy}",
|
||||
confidence=1.0,
|
||||
)
|
||||
|
||||
# Only first rule with matches wins
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _test_match(*, key: str, cell: str, strategy: str) -> bool:
|
||||
"""Check if `key` matches `cell` using the given strategy."""
|
||||
if strategy == "exact":
|
||||
return cell == key
|
||||
elif strategy == "prefix":
|
||||
return cell.startswith(key)
|
||||
elif strategy == "suffix":
|
||||
return cell.endswith(key)
|
||||
elif strategy == "contains":
|
||||
return key in cell
|
||||
elif strategy == "token_match":
|
||||
return ValueMatcher._token_sequence_in(key, cell)
|
||||
else:
|
||||
return key in cell
|
||||
|
||||
@staticmethod
|
||||
def _normalize(text: str) -> str:
|
||||
"""Normalize text: NFKC, full-width→half-width, strip, lowercase."""
|
||||
if not text:
|
||||
return ""
|
||||
text = unicodedata.normalize("NFKC", text)
|
||||
text = text.translate(_FW_TO_HW)
|
||||
return text.strip().lower()
|
||||
|
||||
@staticmethod
|
||||
def _token_sequence_in(key: str, cell: str) -> bool:
|
||||
"""True if the key's tokens form a contiguous subsequence of the
|
||||
cell's tokens (both split on the same delimiters).
|
||||
|
||||
Supports multi-word keys: 'last one' matches 'last one:room light'.
|
||||
"""
|
||||
if not key:
|
||||
return False
|
||||
delim = r'[\s::;;、,,/()()\-/]+'
|
||||
key_tokens = [t for t in re.split(delim, key) if t.strip()]
|
||||
cell_tokens = [t for t in re.split(delim, cell) if t.strip()]
|
||||
if not key_tokens:
|
||||
return False
|
||||
# Contiguous subsequence search
|
||||
nk, nc = len(key_tokens), len(cell_tokens)
|
||||
for start in range(nc - nk + 1):
|
||||
if cell_tokens[start:start + nk] == key_tokens:
|
||||
return True
|
||||
return False
|
||||
+196
-45
@@ -13,6 +13,7 @@ Key behavior:
|
||||
the analyzer can still find it by the required relation columns.
|
||||
"""
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
import fnmatch
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
@@ -33,7 +34,9 @@ class AnalysisResult:
|
||||
|
||||
|
||||
class WorkbookAnalyzer:
|
||||
"""Builds the confirm-page blueprint by combining deterministic fallback with optional LLM output."""
|
||||
def __init__(self, config_manager: ConfigManager):
|
||||
"""Create the analyzer and staged LLM helper for a ConfigManager."""
|
||||
self.cm = config_manager
|
||||
self.stages = LLMStages(config_manager)
|
||||
|
||||
@@ -41,54 +44,163 @@ class WorkbookAnalyzer:
|
||||
self,
|
||||
parsed: ParsedWorkbook,
|
||||
preferred_type_id: str | None = None,
|
||||
progress_callback: Callable[[dict], None] | None = None,
|
||||
use_llm: bool = True,
|
||||
) -> AnalysisResult:
|
||||
"""Run stage 1 → 2 → 3. Fall back to known type / fuzzy when needed."""
|
||||
"""Run deterministic basic analysis, optionally enhanced by LLM stages."""
|
||||
self._emit(progress_callback, 5, "Preparing deterministic fallback", "Known formats and fuzzy matching are ready without a model call.")
|
||||
fallback = self._build_fallback_result(parsed, preferred_type_id)
|
||||
|
||||
if not use_llm:
|
||||
self._emit(progress_callback, 100, "Basic analysis ready", "Deterministic type matching, sheet relations, and mappings are ready to review.")
|
||||
return fallback
|
||||
|
||||
if not self.cm.is_llm_enabled():
|
||||
fallback.warnings.insert(0, "LLM 不可用,改用已知格式 / 基本配對")
|
||||
self._emit(progress_callback, 100, "Using deterministic fallback", "LLM is disabled or not configured; continuing without a model call.")
|
||||
fallback.warnings.insert(0, "LLM unavailable; using known-format/basic matching fallback")
|
||||
return fallback
|
||||
|
||||
llm_result = AnalysisResult(engine="llm")
|
||||
stages = self.stages
|
||||
stages.event_callback = progress_callback
|
||||
|
||||
# Stage 1: read each sheet
|
||||
for sheet in parsed.sheets:
|
||||
summary = self.stages.stage1_read_sheet(sheet.name, sheet.raw_data)
|
||||
if summary is None:
|
||||
llm_result.warnings.append(f"Stage 1 失敗:無法理解 sheet「{sheet.name}」")
|
||||
if self._can_use_known_type_fast_path(preferred_type_id, fallback):
|
||||
# For known formats, the parser/type config already gives the reliable
|
||||
# row model. Small models are more accurate when they only fill gaps
|
||||
# instead of re-inventing header rows and sheet joins.
|
||||
llm_result.summaries = fallback.summaries
|
||||
llm_result.groups = fallback.groups
|
||||
self._emit(
|
||||
progress_callback,
|
||||
55,
|
||||
"Known-type context selected",
|
||||
"Using deterministic sheet structure and joins; AI will only review/fill field mappings.",
|
||||
)
|
||||
else:
|
||||
# Stage 1: read each sheet
|
||||
sheet_count = max(len(parsed.sheets), 1)
|
||||
for idx, sheet in enumerate(parsed.sheets, start=1):
|
||||
pct = 10 + int((idx - 1) / sheet_count * 35)
|
||||
self._emit(
|
||||
progress_callback,
|
||||
pct,
|
||||
f"Stage 1 — reading sheet {idx}/{sheet_count}",
|
||||
f"Understanding structure, header row, and shared values in '{sheet.name}'.",
|
||||
)
|
||||
try:
|
||||
summary = stages.stage1_read_sheet(
|
||||
sheet.name,
|
||||
sheet.raw_data,
|
||||
known_header_row=sheet.header_row,
|
||||
known_headers=[h for h in sheet.detected_headers if h],
|
||||
)
|
||||
except TypeError as exc:
|
||||
if "known_header" not in str(exc) and "unexpected keyword" not in str(exc):
|
||||
raise
|
||||
summary = stages.stage1_read_sheet(sheet.name, sheet.raw_data)
|
||||
if summary is None:
|
||||
llm_result.warnings.append(f"Stage 1 failed: could not understand sheet '{sheet.name}'")
|
||||
self._emit(progress_callback, pct + 3, "Stage 1 fallback note", f"Could not read '{sheet.name}' with LLM; fallback summary remains available.")
|
||||
else:
|
||||
sheet.header_row = summary.header_row
|
||||
sheet.data_start_row = summary.header_row + 1
|
||||
llm_result.summaries.append(summary)
|
||||
self._emit(progress_callback, pct + 5, "Stage 1 result", f"'{sheet.name}' looks like {summary.sheet_type}; {len(summary.columns)} columns detected.")
|
||||
|
||||
if not llm_result.summaries:
|
||||
self._emit(progress_callback, 100, "Fallback selected", "No sheet returned a usable LLM summary; using deterministic matching.")
|
||||
llm_result.warnings.append("Stage 1 failed for every sheet; using known-format/basic matching fallback")
|
||||
return self._prefer_fallback(llm_result, fallback)
|
||||
|
||||
# Stage 2: find links
|
||||
self._emit(progress_callback, 55, "Stage 2 — finding sheet links", "Checking whether sheets should be joined into one product row.")
|
||||
llm_result.groups = stages.stage2_find_links(llm_result.summaries)
|
||||
if not llm_result.groups and len(llm_result.summaries) >= 2:
|
||||
llm_result.warnings.append("No cross-sheet relations detected; sheets will be processed independently")
|
||||
self._emit(progress_callback, 68, "Stage 2 result", "No confident cross-sheet links found; independent sheet processing remains possible.")
|
||||
else:
|
||||
sheet.header_row = summary.header_row
|
||||
sheet.data_start_row = summary.header_row + 1
|
||||
llm_result.summaries.append(summary)
|
||||
|
||||
if not llm_result.summaries:
|
||||
llm_result.warnings.append("Stage 1 全部失敗,改用已知格式 / 基本配對")
|
||||
return self._prefer_fallback(llm_result, fallback)
|
||||
|
||||
# Stage 2: find links
|
||||
llm_result.groups = self.stages.stage2_find_links(llm_result.summaries)
|
||||
if not llm_result.groups and len(llm_result.summaries) >= 2:
|
||||
llm_result.warnings.append("偵測唔到跨表關係,各 sheet 將獨立處理")
|
||||
link_count = sum(len(g.links) for g in llm_result.groups)
|
||||
self._emit(progress_callback, 68, "Stage 2 result", f"Detected {link_count} possible link(s) across {len(llm_result.groups)} group(s).")
|
||||
|
||||
# Stage 3: map columns
|
||||
self._emit(progress_callback, 78, "Stage 3 — mapping to SQL columns", "Matching Excel headers and shared fields to pre_item_master columns.")
|
||||
schema_fields = self.cm.get_schema_fields()
|
||||
llm_result.mappings = self.stages.stage3_map_columns(
|
||||
llm_result.summaries, llm_result.groups, schema_fields
|
||||
)
|
||||
try:
|
||||
llm_result.mappings = stages.stage3_map_columns(
|
||||
llm_result.summaries,
|
||||
llm_result.groups,
|
||||
schema_fields,
|
||||
type_id=preferred_type_id,
|
||||
known_mappings=self._known_mapping_payload(fallback.mappings),
|
||||
)
|
||||
except TypeError as exc:
|
||||
if "type_id" not in str(exc):
|
||||
raise
|
||||
# Some tests and external callers monkeypatch the old 3-argument
|
||||
# stage3_map_columns signature. Keep that seam compatible while the
|
||||
# real implementation accepts type support notes.
|
||||
llm_result.mappings = stages.stage3_map_columns(
|
||||
llm_result.summaries, llm_result.groups, schema_fields
|
||||
)
|
||||
if not llm_result.mappings:
|
||||
llm_result.warnings.append("Stage 3 配對失敗,改用已知格式 / 基本配對")
|
||||
self._emit(progress_callback, 100, "Fallback selected", "LLM returned no usable SQL mappings; using deterministic matching.")
|
||||
llm_result.warnings.append("Stage 3 mapping failed; using known-format/basic matching fallback")
|
||||
return self._prefer_fallback(llm_result, fallback)
|
||||
self._emit(progress_callback, 90, "Stage 3 result", f"Mapped {len(llm_result.mappings)} column(s) to the target schema.")
|
||||
|
||||
# Hybrid mode: deterministic known-type mappings override/fill LLM mappings.
|
||||
if fallback.mappings:
|
||||
hybrid = self._merge_results(llm_result, fallback)
|
||||
if len(hybrid.mappings) >= len(llm_result.mappings):
|
||||
hybrid.warnings.append("已用已知格式補強 LLM 配對結果")
|
||||
return hybrid
|
||||
hybrid.warnings.append("Known-format mappings were used to strengthen the LLM result")
|
||||
self._emit(progress_callback, 100, "Hybrid blueprint ready", f"LLM result strengthened with {len(fallback.mappings)} deterministic mapping(s).")
|
||||
return hybrid
|
||||
|
||||
self._emit(progress_callback, 100, "LLM blueprint ready", "Review the proposed structure, links, and mappings before export.")
|
||||
return llm_result
|
||||
|
||||
@staticmethod
|
||||
def _can_use_known_type_fast_path(preferred_type_id: str | None, fallback: AnalysisResult) -> bool:
|
||||
"""Return True when deterministic type config is strong enough to bound AI to Stage 3."""
|
||||
return bool(
|
||||
preferred_type_id
|
||||
and fallback.engine == "yaml"
|
||||
and fallback.summaries
|
||||
and fallback.mappings
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _known_mapping_payload(mappings: list[ColumnMapping]) -> list[dict]:
|
||||
"""Return deterministic mappings in the compact shape expected by Stage 3 prompts."""
|
||||
payload = []
|
||||
for mapping in mappings:
|
||||
if not mapping.excel_column or not mapping.sql_target:
|
||||
continue
|
||||
payload.append({
|
||||
"excel": mapping.excel_column,
|
||||
"sql": mapping.sql_target,
|
||||
"confidence": mapping.confidence,
|
||||
"reason": mapping.reason,
|
||||
})
|
||||
return payload
|
||||
|
||||
@staticmethod
|
||||
def _emit(
|
||||
progress_callback: Callable[[dict], None] | None,
|
||||
percent: int,
|
||||
title: str,
|
||||
detail: str,
|
||||
) -> None:
|
||||
"""Send a small progress event to the UI without coupling the service to Streamlit."""
|
||||
if progress_callback is None:
|
||||
return
|
||||
progress_callback({
|
||||
"percent": max(0, min(100, int(percent))),
|
||||
"title": title,
|
||||
"detail": detail,
|
||||
})
|
||||
|
||||
def _prefer_fallback(self, llm_result: AnalysisResult, fallback: AnalysisResult) -> AnalysisResult:
|
||||
"""Return deterministic fallback output when the LLM path is empty or weak."""
|
||||
if fallback.mappings:
|
||||
return AnalysisResult(
|
||||
summaries=fallback.summaries,
|
||||
@@ -103,37 +215,57 @@ class WorkbookAnalyzer:
|
||||
def _merge_results(self, llm_result: AnalysisResult, fallback: AnalysisResult) -> AnalysisResult:
|
||||
"""Combine deterministic and LLM mappings.
|
||||
|
||||
Do not de-duplicate by SQL target: the same SQL target may legitimately
|
||||
appear in multiple source sheets, and row-local merge order decides which
|
||||
non-empty value wins.
|
||||
Keep one authoritative Excel source per SQL target. Deterministic fallback
|
||||
mappings are considered stronger than LLM additions for known formats.
|
||||
"""
|
||||
combined: list[ColumnMapping] = []
|
||||
seen_pairs: set[tuple[str, str]] = set()
|
||||
seen_targets: set[str] = set()
|
||||
deterministic_sources: set[str] = set()
|
||||
|
||||
for mapping in fallback.mappings:
|
||||
if not mapping.excel_column or not mapping.sql_target:
|
||||
continue
|
||||
key = (mapping.excel_column, mapping.sql_target)
|
||||
if key in seen_pairs:
|
||||
if key in seen_pairs or mapping.sql_target in seen_targets:
|
||||
continue
|
||||
combined.append(mapping)
|
||||
seen_pairs.add(key)
|
||||
seen_targets.add(mapping.sql_target)
|
||||
deterministic_sources.add(mapping.excel_column)
|
||||
|
||||
ai_threshold = self.cm.get_ai_auto_accept_mapping_threshold()
|
||||
skipped_low_confidence = 0
|
||||
for mapping in llm_result.mappings:
|
||||
if not mapping.excel_column or not mapping.sql_target:
|
||||
continue
|
||||
key = (mapping.excel_column, mapping.sql_target)
|
||||
if key in seen_pairs:
|
||||
if mapping.excel_column in deterministic_sources:
|
||||
continue
|
||||
if key in seen_pairs or mapping.sql_target in seen_targets:
|
||||
continue
|
||||
if mapping.confidence < ai_threshold:
|
||||
skipped_low_confidence += 1
|
||||
continue
|
||||
combined.append(mapping)
|
||||
seen_pairs.add(key)
|
||||
seen_targets.add(mapping.sql_target)
|
||||
|
||||
warnings = [*llm_result.warnings, *fallback.warnings]
|
||||
if skipped_low_confidence:
|
||||
warnings.append(
|
||||
f"Skipped {skipped_low_confidence} low-confidence AI mapping suggestion(s) below "
|
||||
f"{ai_threshold * 100:.0f}% auto-use threshold"
|
||||
)
|
||||
|
||||
return AnalysisResult(
|
||||
summaries=llm_result.summaries or fallback.summaries,
|
||||
groups=llm_result.groups or fallback.groups,
|
||||
# For known formats, deterministic summaries/groups are the authority.
|
||||
# LLM may add mappings, but should not rewrite the validated row model.
|
||||
summaries=fallback.summaries or llm_result.summaries,
|
||||
groups=fallback.groups or llm_result.groups,
|
||||
mappings=combined,
|
||||
engine="hybrid",
|
||||
warnings=[*llm_result.warnings, *fallback.warnings],
|
||||
warnings=warnings,
|
||||
)
|
||||
|
||||
def _build_fallback_result(
|
||||
@@ -141,18 +273,25 @@ class WorkbookAnalyzer:
|
||||
parsed: ParsedWorkbook,
|
||||
preferred_type_id: str | None,
|
||||
) -> AnalysisResult:
|
||||
"""Build summaries, groups, and mappings from known type config plus fuzzy matching."""
|
||||
summaries = self._build_basic_summaries(parsed)
|
||||
type_id, type_label, type_score = self._choose_fallback_type(parsed, preferred_type_id)
|
||||
|
||||
matcher = FuzzyMatcher(self.cm)
|
||||
mappings = self._build_exact_type_column_mappings(parsed, type_id, type_label)
|
||||
existing = {(m.excel_column, m.sql_target) for m in mappings}
|
||||
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
|
||||
@@ -163,29 +302,32 @@ class WorkbookAnalyzer:
|
||||
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
|
||||
# be propagated to every exported row.
|
||||
# be propagated to every exported row. A single SQL target should be
|
||||
# backed by one chosen source column/field in the blueprint.
|
||||
form_mappings = self._build_form_field_mappings(parsed, type_id, type_label)
|
||||
for mapping in form_mappings:
|
||||
key = (mapping.excel_column, mapping.sql_target)
|
||||
if key not in existing:
|
||||
if key not in existing and mapping.sql_target not in existing_targets:
|
||||
mappings.append(mapping)
|
||||
existing.add(key)
|
||||
existing_targets.add(mapping.sql_target)
|
||||
|
||||
groups = self._build_groups_from_type_config(parsed, type_id) if type_id else []
|
||||
engine = "yaml" if type_id else "fuzzy"
|
||||
warnings: list[str] = []
|
||||
if type_id:
|
||||
if preferred_type_id:
|
||||
warnings.append(f"已使用格式「{type_label or type_id}」作為 fallback")
|
||||
warnings.append(f"Using known format '{type_label or type_id}' as fallback")
|
||||
elif type_score is not None:
|
||||
warnings.append(
|
||||
f"根據 fingerprint 建議格式「{type_label or type_id}」({type_score:.0f}%) 作為 fallback"
|
||||
f"Fingerprint suggested format '{type_label or type_id}' ({type_score:.0f}%) for fallback"
|
||||
)
|
||||
else:
|
||||
warnings.append("未識別到已知格式,只能使用基本字串配對")
|
||||
warnings.append("No known format recognized; using basic string matching only")
|
||||
|
||||
return AnalysisResult(
|
||||
summaries=summaries,
|
||||
@@ -203,9 +345,8 @@ class WorkbookAnalyzer:
|
||||
) -> list[ColumnMapping]:
|
||||
"""Return exact source_pattern mappings for every detected header.
|
||||
|
||||
Fuzzy matching de-duplicates by SQL target, but the same target can
|
||||
legitimately appear in multiple source sheets. Keeping exact type config
|
||||
mappings lets the merge layer choose the best row-local value.
|
||||
Keep the first exact source for each SQL target. This prevents review UI
|
||||
confusion where two Excel columns appear to feed the same SQL column.
|
||||
"""
|
||||
if not type_id:
|
||||
return []
|
||||
@@ -221,6 +362,7 @@ class WorkbookAnalyzer:
|
||||
}
|
||||
mappings: list[ColumnMapping] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
seen_targets: set[str] = set()
|
||||
for entry in cfg.get("mapping", []):
|
||||
target = entry.get("target", "")
|
||||
if not target:
|
||||
@@ -230,7 +372,7 @@ class WorkbookAnalyzer:
|
||||
if not header or header not in detected_headers:
|
||||
continue
|
||||
key = (header, target)
|
||||
if key in seen:
|
||||
if key in seen or target in seen_targets:
|
||||
continue
|
||||
mappings.append(ColumnMapping(
|
||||
excel_column=header,
|
||||
@@ -239,6 +381,7 @@ class WorkbookAnalyzer:
|
||||
reason=f"Exact type mapping: {type_label or type_id}",
|
||||
))
|
||||
seen.add(key)
|
||||
seen_targets.add(target)
|
||||
return mappings
|
||||
|
||||
def _build_form_field_mappings(
|
||||
@@ -259,6 +402,7 @@ class WorkbookAnalyzer:
|
||||
|
||||
mappings: list[ColumnMapping] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
seen_targets: set[str] = set()
|
||||
|
||||
cfg = self.cm.get_type_config(type_id) if type_id else None
|
||||
if cfg:
|
||||
@@ -267,7 +411,7 @@ class WorkbookAnalyzer:
|
||||
for pattern in entry.get("source_patterns", []):
|
||||
if pattern in detected_labels and target:
|
||||
key = (pattern, target)
|
||||
if key in seen:
|
||||
if key in seen or target in seen_targets:
|
||||
continue
|
||||
mappings.append(ColumnMapping(
|
||||
excel_column=pattern,
|
||||
@@ -276,13 +420,14 @@ class WorkbookAnalyzer:
|
||||
reason=f"Known form field: {type_label or type_id}",
|
||||
))
|
||||
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:
|
||||
if key in seen or fm.matched_target in seen_targets:
|
||||
continue
|
||||
mappings.append(ColumnMapping(
|
||||
excel_column=fm.label,
|
||||
@@ -291,6 +436,7 @@ class WorkbookAnalyzer:
|
||||
reason="Fuzzy form field",
|
||||
))
|
||||
seen.add(key)
|
||||
seen_targets.add(fm.matched_target)
|
||||
|
||||
return mappings
|
||||
|
||||
@@ -299,6 +445,7 @@ class WorkbookAnalyzer:
|
||||
parsed: ParsedWorkbook,
|
||||
preferred_type_id: str | None,
|
||||
) -> tuple[str | None, str | None, float | None]:
|
||||
"""Choose the preferred or fingerprint-suggested workbook type for fallback."""
|
||||
if preferred_type_id:
|
||||
cfg = self.cm.get_type_config(preferred_type_id)
|
||||
return preferred_type_id, (cfg or {}).get("label", preferred_type_id), None
|
||||
@@ -315,6 +462,7 @@ class WorkbookAnalyzer:
|
||||
return None, None, best.score
|
||||
|
||||
def _build_basic_summaries(self, parsed: ParsedWorkbook) -> list[SheetSummary]:
|
||||
"""Convert parsed sheet metadata into analyzer sheet summaries."""
|
||||
summaries: list[SheetSummary] = []
|
||||
for sheet in parsed.sheets:
|
||||
columns = []
|
||||
@@ -350,6 +498,7 @@ class WorkbookAnalyzer:
|
||||
parsed: ParsedWorkbook,
|
||||
type_id: str | None,
|
||||
) -> list[MergeGroup]:
|
||||
"""Translate type-config sheet relations into merge groups for preview."""
|
||||
if not type_id:
|
||||
return []
|
||||
|
||||
@@ -448,6 +597,7 @@ class WorkbookAnalyzer:
|
||||
|
||||
@staticmethod
|
||||
def _collect_ordered_headers(parsed: ParsedWorkbook) -> list[str]:
|
||||
"""Collect unique detected headers in workbook order."""
|
||||
headers: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for sheet in parsed.sheets:
|
||||
@@ -460,6 +610,7 @@ class WorkbookAnalyzer:
|
||||
|
||||
@staticmethod
|
||||
def _to_merge_strategy(strategy: str) -> str:
|
||||
"""Translate config relation strategies to MergeEngine strategy names."""
|
||||
base = (strategy or "contains").strip().lower()
|
||||
if base.startswith("reverse_"):
|
||||
base = base[len("reverse_"):]
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Helpers for operator-selected workbook sheet scope."""
|
||||
from __future__ import annotations
|
||||
|
||||
from services.excel_parser import ParsedWorkbook
|
||||
|
||||
|
||||
def filter_parsed_workbook_sheets(
|
||||
workbook: ParsedWorkbook,
|
||||
selected_sheet_names: list[str] | tuple[str, ...] | set[str] | None,
|
||||
) -> ParsedWorkbook:
|
||||
"""Return a workbook containing only selected sheets, preserving workbook order.
|
||||
|
||||
``None`` means no operator selection has been made yet, so all sheets remain
|
||||
in scope. An empty collection intentionally returns an empty workbook so the
|
||||
UI can block analysis until at least one sheet is selected.
|
||||
"""
|
||||
if selected_sheet_names is None:
|
||||
selected = {sheet.name for sheet in workbook.sheets}
|
||||
else:
|
||||
selected = {str(name) for name in selected_sheet_names}
|
||||
return ParsedWorkbook(
|
||||
file_name=workbook.file_name,
|
||||
sheets=[sheet for sheet in workbook.sheets if sheet.name in selected],
|
||||
)
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Regression tests for admin/config Streamlit controls."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.security import hash_password
|
||||
|
||||
PROJECT = Path(__file__).resolve().parent.parent
|
||||
ADMIN_PASSWORD = "admin-ui-test-password"
|
||||
ADMIN_PASSWORD_HASH = hash_password(ADMIN_PASSWORD, salt=b"admin-ui-test-salt", iterations=1200)
|
||||
|
||||
|
||||
def _admin_env() -> dict[str, str]:
|
||||
env = os.environ.copy()
|
||||
env["ADMIN_PASSWORD_HASH"] = ADMIN_PASSWORD_HASH
|
||||
return env
|
||||
|
||||
|
||||
def _unlock_admin(page) -> None:
|
||||
page.locator('[data-testid="stExpander"]').first.click()
|
||||
page.get_by_label("Admin password").fill(ADMIN_PASSWORD)
|
||||
page.locator("button").filter(has_text="Unlock admin").last.click()
|
||||
page.wait_for_selector("text=Type configuration", timeout=30000)
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return int(sock.getsockname()[1])
|
||||
|
||||
|
||||
def _wait_ready(url: str, timeout: float = 45.0) -> None:
|
||||
deadline = time.time() + timeout
|
||||
last_error: Exception | None = None
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=2) as resp:
|
||||
if resp.status == 200:
|
||||
return
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
time.sleep(0.5)
|
||||
raise AssertionError(f"Streamlit not ready: {last_error!r}")
|
||||
|
||||
|
||||
def _select_option(page, label: str, option: str) -> None:
|
||||
page.get_by_label(label).first.click()
|
||||
page.get_by_role("option", name=option).click()
|
||||
page.wait_for_timeout(900)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not (PROJECT / "config" / "types" / "kuji_tw.yaml").exists(), reason="type config fixtures missing")
|
||||
def test_admin_type_dropdown_refreshes_dependent_controls():
|
||||
"""Switching Type Config must refresh all dependent input/select controls."""
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
port = _free_port()
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
proc = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"streamlit",
|
||||
"run",
|
||||
"app.py",
|
||||
"--server.headless",
|
||||
"true",
|
||||
"--server.address",
|
||||
"127.0.0.1",
|
||||
"--server.port",
|
||||
str(port),
|
||||
"--server.fileWatcherType",
|
||||
"none",
|
||||
],
|
||||
cwd=PROJECT,
|
||||
env=_admin_env(),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
try:
|
||||
_wait_ready(url)
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 1000})
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
page.wait_for_selector("text=Upload a workbook", timeout=30000)
|
||||
_unlock_admin(page)
|
||||
page.locator("button").filter(has_text="Type configuration").first.click()
|
||||
page.wait_for_selector("text=Type Configuration", timeout=30000)
|
||||
|
||||
_select_option(page, "Select type", "kuji_tw")
|
||||
assert page.get_by_label("Type ID").first.input_value() == "kuji_tw"
|
||||
assert page.get_by_label("Label").first.input_value() == "KUJI TW"
|
||||
assert page.get_by_label("Category").first.input_value() == "kuji"
|
||||
assert page.get_by_label("Source Patterns (comma-separated)").first.input_value() == "SALES JAN CODE"
|
||||
|
||||
_select_option(page, "Select type", "bcl_sap")
|
||||
assert page.get_by_label("Type ID").first.input_value() == "bcl_sap"
|
||||
assert page.get_by_label("Label").first.input_value() == "BCL SAP"
|
||||
assert page.get_by_label("Category").first.input_value() == "bcl"
|
||||
assert page.get_by_label("Source Patterns (comma-separated)").first.input_value() == "JAN_Code"
|
||||
|
||||
_select_option(page, "Select type", "kuji_bna")
|
||||
assert page.get_by_label("Type ID").first.input_value() == "kuji_bna"
|
||||
assert page.get_by_label("Label").first.input_value() == "KUJI BNA"
|
||||
assert page.get_by_label("Category").first.input_value() == "kuji"
|
||||
assert page.get_by_label("Source Patterns (comma-separated)").first.input_value() == "SALES JAN CODE"
|
||||
|
||||
body = page.locator("body").inner_text()
|
||||
assert "Traceback" not in body
|
||||
assert "StreamlitAPIException" not in body
|
||||
metrics = page.evaluate("""() => ({
|
||||
innerWidth: window.innerWidth,
|
||||
bodyScrollWidth: document.body.scrollWidth,
|
||||
})""")
|
||||
assert metrics["bodyScrollWidth"] <= metrics["innerWidth"] + 1
|
||||
browser.close()
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=8)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait(timeout=8)
|
||||
|
||||
|
||||
|
||||
def test_admin_llm_profile_dropdown_refreshes_profile_fields():
|
||||
"""Switching LLM profile must refresh profile-specific fields without saving first."""
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
profiles = ConfigManager().get_llm_config().get("profiles") or {}
|
||||
if len(profiles) < 2:
|
||||
pytest.skip("Need at least two LLM profiles to verify profile switching")
|
||||
profile_ids = list(profiles.keys())[:2]
|
||||
|
||||
port = _free_port()
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
proc = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"streamlit",
|
||||
"run",
|
||||
"app.py",
|
||||
"--server.headless",
|
||||
"true",
|
||||
"--server.address",
|
||||
"127.0.0.1",
|
||||
"--server.port",
|
||||
str(port),
|
||||
"--server.fileWatcherType",
|
||||
"none",
|
||||
],
|
||||
cwd=PROJECT,
|
||||
env=_admin_env(),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
try:
|
||||
_wait_ready(url)
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 1000})
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
page.wait_for_selector("text=Upload a workbook", timeout=30000)
|
||||
_unlock_admin(page)
|
||||
page.locator("button").filter(has_text="AI configuration").first.click()
|
||||
page.wait_for_selector("text=one credential field only", timeout=30000)
|
||||
|
||||
for pid in profile_ids:
|
||||
profile = profiles[pid]
|
||||
option_label = f"{profile.get('label', pid)} ({pid})"
|
||||
page.locator('[data-testid="stSelectbox"]').first.click()
|
||||
page.get_by_role("option", name=option_label).click()
|
||||
page.wait_for_timeout(900)
|
||||
assert page.get_by_label("Label").first.input_value() == str(profile.get("label", pid) or pid)
|
||||
assert page.get_by_label("Base URL").first.input_value() == str(profile.get("base_url", "") or "")
|
||||
assert page.get_by_label("Model").first.input_value() == str(profile.get("model", "") or "deepseek-chat")
|
||||
|
||||
body = page.locator("body").inner_text()
|
||||
assert "Traceback" not in body
|
||||
assert "StreamlitAPIException" not in body
|
||||
browser.close()
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=8)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait(timeout=8)
|
||||
@@ -0,0 +1,299 @@
|
||||
"""Tests for compact AI-analysis UI helper output."""
|
||||
from __future__ import annotations
|
||||
|
||||
from services.workbook_analyzer import AnalysisResult
|
||||
from services.llm_stages import SheetSummary, MergeGroup, MergeLink, ColumnMapping
|
||||
from ui.ai_analysis_page import (
|
||||
build_ai_run_console_text,
|
||||
build_ai_run_status,
|
||||
build_ai_status_card_html,
|
||||
build_ai_visibility_snapshot,
|
||||
build_analysis_conclusion,
|
||||
build_compact_warning_rows,
|
||||
build_final_blueprint_report,
|
||||
build_model_response_tables,
|
||||
build_stream_console_html,
|
||||
build_validation_tables,
|
||||
_render_ai_run_status_card,
|
||||
_render_refresh_guard,
|
||||
_render_table_block,
|
||||
)
|
||||
|
||||
|
||||
def test_refresh_guard_uses_st_iframe_not_deprecated_components(monkeypatch):
|
||||
iframe_calls = []
|
||||
monkeypatch.setattr("ui.ai_analysis_page.st.iframe", lambda src, **kwargs: iframe_calls.append((src, kwargs)))
|
||||
|
||||
_render_refresh_guard(True)
|
||||
_render_refresh_guard(False)
|
||||
|
||||
assert "onbeforeunload" in iframe_calls[0][0]
|
||||
assert "AI analysis is running" in iframe_calls[0][0]
|
||||
assert "onbeforeunload = null" in iframe_calls[1][0]
|
||||
assert iframe_calls[0][1]["height"] == 1
|
||||
assert iframe_calls[0][1]["width"] == "stretch"
|
||||
|
||||
|
||||
|
||||
def test_stream_console_html_uses_stable_container_and_bottom_anchor():
|
||||
html1 = build_stream_console_html("PROMPT\nfirst", run_id="abc", running=True)
|
||||
html2 = build_stream_console_html("PROMPT\nfirst\nsecond", run_id="abc", running=True)
|
||||
|
||||
assert 'id="ai-run-console-abc"' in html1
|
||||
assert 'id="ai-run-console-abc"' in html2
|
||||
assert 'ai-run-console-bottom-abc' in html2
|
||||
assert 'data-testid="ai-run-console-scroll"' in html2
|
||||
assert 'scrollTop' in html2 or 'scrollIntoView' in html2
|
||||
assert '<textarea' not in html2
|
||||
assert 'PROMPT' in html2
|
||||
|
||||
|
||||
def test_build_ai_run_status_tracks_elapsed_without_eta_and_stage():
|
||||
events = [
|
||||
{"percent": 10, "title": "Prompt sent", "kind": "prompt"},
|
||||
{"percent": 45, "title": "Streaming AI response", "kind": "llm_stream", "detail": "Stage 1: 120 chars received"},
|
||||
]
|
||||
|
||||
status = build_ai_run_status(events, running=True, started_at=100.0, now=112.0)
|
||||
|
||||
assert status["state"] == "running"
|
||||
assert status["elapsed_label"] == "00:12"
|
||||
assert status["percent"] == 45
|
||||
assert status["stage"] == "Streaming AI response"
|
||||
assert status["detail"] == "Stage 1: 120 chars received"
|
||||
assert "eta_seconds" not in status
|
||||
assert "eta_label" not in status
|
||||
|
||||
|
||||
def test_render_ai_status_card_shows_standalone_elapsed_timer_without_eta():
|
||||
class FakeSlot:
|
||||
html = ""
|
||||
|
||||
def markdown(self, html, **kwargs):
|
||||
self.html = html
|
||||
self.kwargs = kwargs
|
||||
|
||||
slot = FakeSlot()
|
||||
status = build_ai_run_status(
|
||||
[{"percent": 45, "title": "Streaming AI response", "detail": "Stage 1: 120 chars received"}],
|
||||
running=True,
|
||||
started_at=100.0,
|
||||
now=112.0,
|
||||
)
|
||||
|
||||
_render_ai_run_status_card(slot, status)
|
||||
|
||||
assert "Elapsed Time" in slot.html
|
||||
assert "00:12" in slot.html
|
||||
assert "ETA" not in slot.html
|
||||
assert "estimating" not in slot.html
|
||||
assert "nbd-ai-elapsed-card" in slot.html
|
||||
assert "data-initial-seconds=\"12\"" in slot.html
|
||||
assert "setInterval" in slot.html
|
||||
|
||||
|
||||
def test_status_card_static_when_not_running():
|
||||
html = build_ai_status_card_html({
|
||||
"state": "complete",
|
||||
"elapsed_seconds": 65,
|
||||
"elapsed_label": "01:05",
|
||||
"percent": 100,
|
||||
"stage": "Done",
|
||||
"detail": "Finished",
|
||||
})
|
||||
|
||||
assert "01:05" in html
|
||||
assert "data-running=\"false\"" in html
|
||||
|
||||
|
||||
def test_build_ai_run_status_handles_ready_without_events():
|
||||
status = build_ai_run_status([], running=False, started_at=None, now=10.0)
|
||||
|
||||
assert status["state"] == "ready"
|
||||
assert status["percent"] == 0
|
||||
assert status["elapsed_label"] == "00:00"
|
||||
assert "eta_label" not in status
|
||||
|
||||
|
||||
def test_build_ai_run_console_text_includes_prompt_and_stream_without_empty_progress_noise():
|
||||
events = [
|
||||
{"kind": "prompt", "label": "Stage 1 sheet 'Item detail'", "prompt": "Prompt body with workbook headers"},
|
||||
{"kind": "llm_stream", "title": "Streaming AI response", "detail": "Stage 1: 12 chars received", "stream_text": "{\"header"},
|
||||
{"kind": "model_response", "label": "Stage 1 sheet 'Item detail'", "content_preview": '{"header_row":1}'},
|
||||
]
|
||||
|
||||
text = build_ai_run_console_text(events)
|
||||
|
||||
assert "PROMPT — Stage 1 sheet 'Item detail'" in text
|
||||
assert "Prompt body with workbook headers" in text
|
||||
assert "AI RESPONSE STREAM" in text
|
||||
assert "{\"header" in text
|
||||
assert "MODEL RESPONSE — Stage 1 sheet 'Item detail'" in text
|
||||
assert "0%" not in text
|
||||
assert "Waiting to start" not in text
|
||||
assert "No AI run yet" not in text
|
||||
|
||||
|
||||
def test_compact_warning_rows_are_plain_data_not_alert_banners():
|
||||
rows = build_compact_warning_rows([
|
||||
"Stage 1 failed: could not understand sheet 'DISNEY PRINCESS'",
|
||||
"Using known format 'KUJI TW' as fallback",
|
||||
])
|
||||
|
||||
assert rows == [
|
||||
{"type": "note", "message": "Stage 1 failed: could not understand sheet 'DISNEY PRINCESS'"},
|
||||
{"type": "note", "message": "Using known format 'KUJI TW' as fallback"},
|
||||
]
|
||||
|
||||
|
||||
|
||||
def test_build_ai_visibility_snapshot_exposes_response_validation_and_reasons():
|
||||
result = AnalysisResult(
|
||||
summaries=[SheetSummary(sheet_name="Item detail", header_row=1, sheet_type="detail", columns=[
|
||||
{"header": "商品名/英語", "meaning": "English item name", "samples": ["GRADE A"]}
|
||||
])],
|
||||
groups=[MergeGroup(
|
||||
sheets=["Item detail", "DISNEY PRINCESS"],
|
||||
master_sheet="Item detail",
|
||||
master_reason="Product rows live here",
|
||||
links=[MergeLink("DISNEY PRINCESS", "STYLE", "Item detail", "商品名/英語", "GRADE", "value_token", 1.0, "Grade code")],
|
||||
)],
|
||||
mappings=[ColumnMapping("商品名/英語", "item_name_eng", 1.0, "Exact English name mapping")],
|
||||
engine="hybrid",
|
||||
)
|
||||
events = [
|
||||
{"kind": "model_response", "title": "Model response received", "detail": "Stage 1", "content_preview": '{"header_row":1}'},
|
||||
{"kind": "validation_result", "title": "Validated model JSON", "detail": "passed", "validation_status": "passed", "normalized_preview": '{"header_row":1}'},
|
||||
]
|
||||
|
||||
snapshot = build_ai_visibility_snapshot(events, result)
|
||||
|
||||
assert snapshot["response_events"][0]["content_preview"] == '{"header_row":1}'
|
||||
assert snapshot["validation_events"][0]["validation_status"] == "passed"
|
||||
reason_text = " ".join(row["reason"] for row in snapshot["reasoning_rows"])
|
||||
assert "English item name" in reason_text
|
||||
assert "Grade code" in reason_text
|
||||
assert "Exact English name mapping" in reason_text
|
||||
assert snapshot["final"]["mappings"] == 1
|
||||
|
||||
|
||||
def test_build_analysis_conclusion_summarizes_final_ai_result():
|
||||
result = AnalysisResult(
|
||||
summaries=[SheetSummary(sheet_name="Item detail", header_row=1, sheet_type="detail")],
|
||||
groups=[MergeGroup(
|
||||
sheets=["Item detail", "DISNEY PRINCESS"],
|
||||
master_sheet="Item detail",
|
||||
master_reason="Product rows live here",
|
||||
links=[MergeLink("DISNEY PRINCESS", "STYLE", "Item detail", "商品名/英語", "GRADE", "value_token", 1.0, "Grade code")],
|
||||
)],
|
||||
mappings=[ColumnMapping("商品名/英語", "item_name_eng", 1.0, "Exact mapping")],
|
||||
engine="hybrid",
|
||||
warnings=[],
|
||||
)
|
||||
|
||||
conclusion = build_analysis_conclusion(result, used_ai=True)
|
||||
|
||||
assert conclusion["title"] == "AI analysis complete"
|
||||
assert "HYBRID" in conclusion["headline"]
|
||||
assert "1 sheet" in conclusion["headline"]
|
||||
assert "1 link" in conclusion["headline"]
|
||||
assert "1 mapping" in conclusion["headline"]
|
||||
assert conclusion["severity"] == "success"
|
||||
|
||||
|
||||
def test_build_analysis_conclusion_calls_out_fallback_when_ai_unavailable():
|
||||
result = AnalysisResult(
|
||||
summaries=[],
|
||||
groups=[],
|
||||
mappings=[],
|
||||
engine="yaml",
|
||||
warnings=["LLM unavailable; using known-format/basic matching fallback"],
|
||||
)
|
||||
|
||||
conclusion = build_analysis_conclusion(result, used_ai=False)
|
||||
|
||||
assert conclusion["title"] == "Basic fallback selected"
|
||||
assert conclusion["severity"] == "warning"
|
||||
assert "deterministic" in conclusion["headline"].lower()
|
||||
|
||||
|
||||
def test_model_response_tables_expand_stage_json_to_readable_rows():
|
||||
events = [
|
||||
{
|
||||
"kind": "model_response",
|
||||
"label": "Stage 1 sheet 'Item detail'",
|
||||
"raw_content": '{"header_row":1,"sheet_type":"detail","columns":[{"header":"商品名/英語","meaning":"English item name","samples":["GRADE A"]}],"shared_values":[]}',
|
||||
},
|
||||
{
|
||||
"kind": "model_response",
|
||||
"label": "Stage 2 sheet links",
|
||||
"raw_content": '{"groups":[{"sheets":["Item detail","DISNEY PRINCESS"],"master_sheet":"Item detail","master_reason":"Product rows","links":[{"from_sheet":"DISNEY PRINCESS","from_column":"STYLE","to_sheet":"Item detail","to_column":"商品名/英語","key_pattern":"GRADE","match_strategy":"value_token","confidence":0.96,"reason":"Grade token"}]}]}',
|
||||
},
|
||||
{
|
||||
"kind": "model_response",
|
||||
"label": "Stage 3 schema mapping",
|
||||
"raw_content": '{"mapping":[{"excel":"商品名/英語","sql":"item_name_eng","confidence":0.99,"reason":"Exact English header"}],"conflicts":[]}',
|
||||
},
|
||||
]
|
||||
|
||||
tables = build_model_response_tables(events)
|
||||
|
||||
assert tables["sheet_structure"][0]["header_row"] == 1
|
||||
assert tables["sheet_columns"][0]["header"] == "商品名/英語"
|
||||
assert tables["join_rules"][0]["strategy"] == "value_token"
|
||||
assert tables["mapping"][0]["sql"] == "item_name_eng"
|
||||
assert tables["mapping"][0]["reason"] == "Exact English header"
|
||||
|
||||
|
||||
def test_validation_tables_show_status_errors_and_normalized_paths():
|
||||
events = [
|
||||
{"kind": "model_parsed", "label": "Stage 1", "normalized_preview": '{"header_row": 1, "columns": [{"header":"A"}]}'},
|
||||
{"kind": "validation_result", "label": "Stage 1", "validation_status": "passed", "validation_errors": [], "detail": "Validation passed"},
|
||||
{"kind": "validation_result", "label": "Stage 3", "validation_status": "failed", "validation_errors": ["mapping[0] references unknown SQL target 'x'"], "detail": "Validation failed"},
|
||||
]
|
||||
|
||||
tables = build_validation_tables(events)
|
||||
|
||||
assert tables["status"][0]["status"] == "passed"
|
||||
assert tables["status"][1]["error_count"] == 1
|
||||
assert tables["errors"][0]["message"] == "mapping[0] references unknown SQL target 'x'"
|
||||
assert any(row["path"].endswith("header_row") and row["value"] == "1" for row in tables["normalized"])
|
||||
|
||||
|
||||
def test_final_blueprint_report_explains_mapping_join_and_decision_source():
|
||||
result = AnalysisResult(
|
||||
summaries=[SheetSummary(sheet_name="Item detail", header_row=1, sheet_type="detail", columns=[
|
||||
{"header": "商品名/英語", "meaning": "English item name", "samples": ["GRADE A"]}
|
||||
])],
|
||||
groups=[MergeGroup(
|
||||
sheets=["Item detail", "DISNEY PRINCESS"],
|
||||
master_sheet="Item detail",
|
||||
master_reason="Product rows live here",
|
||||
links=[MergeLink("DISNEY PRINCESS", "STYLE", "Item detail", "商品名/英語", "GRADE", "value_token", 0.96, "Grade code")],
|
||||
)],
|
||||
mappings=[ColumnMapping("商品名/英語", "item_name_eng", 0.99, "Exact English name mapping")],
|
||||
engine="hybrid",
|
||||
warnings=["Using known-format fallback for sheet metadata"],
|
||||
)
|
||||
|
||||
report = build_final_blueprint_report(result, events=[])
|
||||
|
||||
assert report["summary"][0]["engine"] == "HYBRID"
|
||||
assert report["mapping_decisions"][0]["sql_target"] == "item_name_eng"
|
||||
assert report["mapping_decisions"][0]["chosen_source"] == "商品名/英語"
|
||||
assert "Exact English name mapping" in report["mapping_decisions"][0]["reason"]
|
||||
assert report["mapping_decisions"][0]["decision_source"] in {"AI validated", "Known type config", "Fuzzy fallback", "Hybrid"}
|
||||
assert report["join_decisions"][0]["strategy"] == "value_token"
|
||||
assert report["fallback_notes"][0]["message"] == "Using known-format fallback for sheet metadata"
|
||||
|
||||
|
||||
def test_render_table_block_omits_invalid_none_height(monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr("ui.ai_analysis_page.st.markdown", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr("ui.ai_analysis_page.st.dataframe", lambda **kwargs: calls.append(kwargs))
|
||||
|
||||
_render_table_block("Rows", [{"a": "b"}], height=None)
|
||||
|
||||
assert calls
|
||||
assert "height" not in calls[0]
|
||||
assert calls[0]["width"] == "stretch"
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Tests for persistent AI analysis debug logs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from services.ai_debug_log import AIDebugLog
|
||||
from services.excel_parser import ParsedSheet, ParsedWorkbook
|
||||
from services.llm_stages import ColumnMapping
|
||||
from services.workbook_analyzer import AnalysisResult
|
||||
from ui.ai_analysis_page import _run_llm_analysis_console
|
||||
|
||||
SK_PREFIX = "sk" + "-"
|
||||
|
||||
|
||||
def _fake_secret(suffix: str) -> str:
|
||||
"""Build a token-shaped fake secret without storing a raw key-shaped literal."""
|
||||
return SK_PREFIX + suffix
|
||||
|
||||
|
||||
class FakeSessionState(dict):
|
||||
"""Tiny dict/object hybrid for Streamlit session_state in unit tests."""
|
||||
|
||||
def __getattr__(self, key):
|
||||
try:
|
||||
return self[key]
|
||||
except KeyError as exc:
|
||||
raise AttributeError(key) from exc
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
self[key] = value
|
||||
|
||||
|
||||
class FakeSlot:
|
||||
def markdown(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def html(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class FakeConfigManager:
|
||||
def __init__(self, debug_dir: Path, enabled: bool = True):
|
||||
self.debug_dir = debug_dir
|
||||
self.enabled = enabled
|
||||
|
||||
def get_ai_debug_log_config(self) -> dict:
|
||||
return {"enabled": self.enabled, "dir": str(self.debug_dir), "max_string_chars": 2000}
|
||||
|
||||
def get_ai_debug_log_dir(self) -> Path:
|
||||
return self.debug_dir
|
||||
|
||||
def get_ai_auto_accept_mapping_threshold(self) -> float:
|
||||
return 0.85
|
||||
|
||||
def get_llm_config(self) -> dict:
|
||||
return {"enabled": True, "active_profile": "local", "profiles": {"local": {}}}
|
||||
|
||||
def resolve_llm_connection_config(self) -> dict:
|
||||
return {
|
||||
"profile": "local",
|
||||
"mode": "small",
|
||||
"base_url": "https://llm.example/v1",
|
||||
"model": "local-model",
|
||||
"api_key": _fake_secret("config-secret-token-abcdefghi"),
|
||||
"timeout_seconds": 5,
|
||||
"stream_response": True,
|
||||
}
|
||||
|
||||
|
||||
def _parsed_workbook() -> ParsedWorkbook:
|
||||
wb = ParsedWorkbook(file_name="offer.xlsx")
|
||||
wb.sheets.append(ParsedSheet(
|
||||
name="Item detail",
|
||||
rows=2,
|
||||
cols=2,
|
||||
header_row=1,
|
||||
data_start_row=2,
|
||||
data_end_row=2,
|
||||
detected_headers=["GL品番", "商品名"],
|
||||
raw_data=[["GL品番", "商品名"], ["SAP001", "A prize"]],
|
||||
))
|
||||
return wb
|
||||
|
||||
|
||||
def _read_jsonl(path: Path) -> list[dict]:
|
||||
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
|
||||
|
||||
def test_ai_debug_log_redacts_secrets_and_clips_long_values(tmp_path):
|
||||
header_secret = _fake_secret("header-secret-token-abcdefghi")
|
||||
body_secret = _fake_secret("body-secret-token-abcdefghi")
|
||||
direct_secret = _fake_secret("direct-secret-token-abcdefghi")
|
||||
log = AIDebugLog(tmp_path / "ai_debug.jsonl", run_id="unit", max_string_chars=80)
|
||||
try:
|
||||
log.write(
|
||||
"llm_error",
|
||||
headers={"Authorization": f"Bearer {header_secret}"},
|
||||
body=f"prefix {body_secret} suffix " + ("x" * 1300),
|
||||
api_key=direct_secret,
|
||||
)
|
||||
finally:
|
||||
log.close()
|
||||
|
||||
text = (tmp_path / "ai_debug.jsonl").read_text(encoding="utf-8")
|
||||
record = json.loads(text)
|
||||
|
||||
assert record["event_type"] == "llm_error"
|
||||
assert record["headers"]["Authorization"] == "«redacted»"
|
||||
assert record["api_key"] == "«redacted»"
|
||||
assert header_secret not in text
|
||||
assert body_secret not in text
|
||||
assert direct_secret not in text
|
||||
assert "truncated" in text
|
||||
|
||||
|
||||
def test_run_llm_analysis_console_writes_persistent_debug_log(monkeypatch, tmp_path):
|
||||
session_state = FakeSessionState({
|
||||
"ai_analysis_started_at": 100.0,
|
||||
"ai_analysis_run_id": "unit-run",
|
||||
})
|
||||
monkeypatch.setattr("ui.ai_analysis_page.st.session_state", session_state, raising=False)
|
||||
monkeypatch.setattr("ui.ai_analysis_page._render_ai_run_status_card", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr("ui.ai_analysis_page._render_console_panel", lambda *args, **kwargs: None)
|
||||
prompt_secret = _fake_secret("prompt-secret-token-abcdefghi")
|
||||
request_secret = _fake_secret("request-secret-token-abcdefghi")
|
||||
error_secret = _fake_secret("error-secret-token-abcdefghi")
|
||||
config_secret = _fake_secret("config-secret-token-abcdefghi")
|
||||
|
||||
class FakeAnalyzer:
|
||||
def __init__(self, config_manager):
|
||||
self.config_manager = config_manager
|
||||
|
||||
def analyze(self, parsed, preferred_type_id, progress_callback, use_llm):
|
||||
progress_callback({
|
||||
"kind": "prompt",
|
||||
"percent": 78,
|
||||
"title": "Prompt sent",
|
||||
"label": "Stage 3 schema mapping",
|
||||
"prompt": f"Map GL品番 using Bearer {prompt_secret}",
|
||||
"request": {"api_key": request_secret},
|
||||
})
|
||||
progress_callback({
|
||||
"kind": "llm_error",
|
||||
"percent": 80,
|
||||
"title": "LLM request failed",
|
||||
"label": "Stage 3 schema mapping",
|
||||
"error": f"Connection failed for {error_secret}",
|
||||
"status_code": 500,
|
||||
})
|
||||
return AnalysisResult(
|
||||
summaries=[],
|
||||
groups=[],
|
||||
mappings=[ColumnMapping("GL品番", "sap", 0.9, "AI fill")],
|
||||
engine="hybrid",
|
||||
warnings=["Known-format mappings were used to strengthen the LLM result"],
|
||||
)
|
||||
|
||||
monkeypatch.setattr("ui.ai_analysis_page.WorkbookAnalyzer", FakeAnalyzer)
|
||||
|
||||
_run_llm_analysis_console(
|
||||
FakeConfigManager(tmp_path / "debug"),
|
||||
_parsed_workbook(),
|
||||
"kuji_tw",
|
||||
FakeSlot(),
|
||||
FakeSlot(),
|
||||
)
|
||||
|
||||
log_path = Path(session_state["ai_analysis_debug_log_path"])
|
||||
records = _read_jsonl(log_path)
|
||||
event_types = [record["event_type"] for record in records]
|
||||
log_text = log_path.read_text(encoding="utf-8")
|
||||
|
||||
assert log_path.exists()
|
||||
assert event_types[:2] == ["run_start", "workbook_snapshot"]
|
||||
assert "prompt" in event_types
|
||||
assert "llm_error" in event_types
|
||||
assert event_types[-1] == "run_complete"
|
||||
assert records[-1]["result"]["engine"] == "hybrid"
|
||||
assert records[-1]["result"]["mapping_count"] == 1
|
||||
assert "offer.xlsx" in log_text
|
||||
assert prompt_secret not in log_text
|
||||
assert request_secret not in log_text
|
||||
assert error_secret not in log_text
|
||||
assert config_secret not in log_text
|
||||
|
||||
|
||||
def test_run_llm_analysis_console_skips_debug_log_when_disabled(monkeypatch, tmp_path):
|
||||
session_state = FakeSessionState({"ai_analysis_run_id": "disabled-run"})
|
||||
monkeypatch.setattr("ui.ai_analysis_page.st.session_state", session_state, raising=False)
|
||||
monkeypatch.setattr("ui.ai_analysis_page._render_ai_run_status_card", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr("ui.ai_analysis_page._render_console_panel", lambda *args, **kwargs: None)
|
||||
|
||||
class FakeAnalyzer:
|
||||
def __init__(self, config_manager):
|
||||
pass
|
||||
|
||||
def analyze(self, parsed, preferred_type_id, progress_callback, use_llm):
|
||||
return AnalysisResult(engine="yaml")
|
||||
|
||||
monkeypatch.setattr("ui.ai_analysis_page.WorkbookAnalyzer", FakeAnalyzer)
|
||||
|
||||
_run_llm_analysis_console(
|
||||
FakeConfigManager(tmp_path / "debug", enabled=False),
|
||||
_parsed_workbook(),
|
||||
"kuji_tw",
|
||||
FakeSlot(),
|
||||
FakeSlot(),
|
||||
)
|
||||
|
||||
assert "ai_analysis_debug_log_path" not in session_state
|
||||
assert not (tmp_path / "debug").exists()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Default test runs must not call real AI providers."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.llm_stages import LLMStages
|
||||
|
||||
|
||||
def test_real_ai_tests_are_opt_in(monkeypatch):
|
||||
monkeypatch.delenv("RUN_REAL_AI_TESTS", raising=False)
|
||||
assert os.environ.get("RUN_REAL_AI_TESTS") != "1"
|
||||
|
||||
|
||||
def test_default_project_config_disables_ai_during_pytest_without_opt_in(monkeypatch):
|
||||
monkeypatch.delenv("RUN_REAL_AI_TESTS", raising=False)
|
||||
monkeypatch.setenv("PYTEST_CURRENT_TEST", "tests/test_ai_offline_policy.py::test_default_project_config_disables_ai_during_pytest_without_opt_in (call)")
|
||||
cm = ConfigManager()
|
||||
assert cm.is_llm_enabled() is False
|
||||
assert cm.resolve_llm_connection_config() is None
|
||||
|
||||
|
||||
def test_llm_stage_returns_none_when_config_incomplete(tmp_path):
|
||||
config_dir = tmp_path / "config"
|
||||
config_dir.mkdir()
|
||||
(config_dir / "settings.example.yaml").write_text(
|
||||
"llm:\n enabled: true\n active_profile: local\n profiles:\n local:\n base_url: http://example.invalid/v1\n model: test\n api_key: ''\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
cm = ConfigManager(config_dir=config_dir)
|
||||
assert cm.resolve_llm_connection_config() is None
|
||||
assert LLMStages(cm).stage1_read_sheet("Sheet1", [["A"], ["B"]]) is None
|
||||
@@ -0,0 +1,243 @@
|
||||
"""Regression tests for small-model AI prompt/flow quality."""
|
||||
from __future__ import annotations
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.excel_parser import ParsedSheet, ParsedWorkbook
|
||||
from services.llm_prompts import build_schema_mapping_prompt, build_sheet_structure_prompt
|
||||
from services.llm_stages import ColumnMapping, MergeGroup, SheetSummary
|
||||
from services.llm_validation import validate_schema_mapping, validate_sheet_structure
|
||||
from services.workbook_analyzer import AnalysisResult, WorkbookAnalyzer
|
||||
|
||||
|
||||
def test_sheet_structure_prompt_bounds_model_to_parser_detected_headers():
|
||||
prompt = build_sheet_structure_prompt(
|
||||
"DISNEY PRINCESS",
|
||||
[["STYLE", "Product contents", "", "ITEM SIZE"], ["A", "GRADE A", "Figure", "H:16cm"]],
|
||||
budget={"max_sheet_rows": 20, "max_sheet_cols": 10},
|
||||
known_header_row=1,
|
||||
known_headers=["STYLE", "Product contents", "ITEM SIZE"],
|
||||
)
|
||||
|
||||
assert "Parser-detected header row: 1" in prompt
|
||||
assert "Allowed column headers" in prompt
|
||||
assert '"STYLE"' in prompt
|
||||
assert '"Product contents"' in prompt
|
||||
assert "Omit blank headers" in prompt
|
||||
assert "Choose from the allowed headers" in prompt
|
||||
|
||||
|
||||
def test_validate_sheet_structure_accepts_valid_subset_and_drops_blank_or_invented_columns():
|
||||
raw_rows = [["STYLE", "Product contents", "", "ITEM SIZE"], ["A", "GRADE A", "Figure", "H:16cm"]]
|
||||
data = {
|
||||
"header_row": 1,
|
||||
"sheet_type": "definition",
|
||||
"columns": [
|
||||
{"header": "STYLE", "samples": ["A"], "meaning": "grade code"},
|
||||
{"header": "", "samples": ["Figure"], "meaning": "blank merged header"},
|
||||
{"header": "ITEM TYPE", "samples": ["Figure"], "meaning": "invented name"},
|
||||
{"header": "ITEM SIZE", "samples": ["H:16cm"], "meaning": "size"},
|
||||
],
|
||||
"shared_values": [],
|
||||
}
|
||||
|
||||
result = validate_sheet_structure("DISNEY PRINCESS", raw_rows, data)
|
||||
|
||||
assert result.valid is True
|
||||
assert [c["header"] for c in result.data["columns"]] == ["STYLE", "ITEM SIZE"]
|
||||
assert any("ITEM TYPE" in warning for warning in result.warnings)
|
||||
assert any("blank" in warning.lower() for warning in result.warnings)
|
||||
|
||||
|
||||
def test_schema_mapping_prompt_lists_authoritative_known_mappings():
|
||||
prompt = build_schema_mapping_prompt(
|
||||
[{"header": "STYLE", "samples": ["A"]}],
|
||||
[{"name": "package_style", "description": "Style code"}],
|
||||
known_mappings=[{"excel": "STYLE", "sql": "package_style", "confidence": 1.0, "reason": "Known type"}],
|
||||
)
|
||||
|
||||
assert "Known exact mappings are authoritative" in prompt
|
||||
assert '"excel": "STYLE"' in prompt
|
||||
assert '"sql": "package_style"' in prompt
|
||||
|
||||
|
||||
def test_validate_schema_mapping_accepts_valid_subset_and_drops_invalid_rows():
|
||||
summaries = [SheetSummary("S", 1, "detail", [{"header": "STYLE"}, {"header": "ITEM SIZE"}], [])]
|
||||
schema = [{"name": "package_style"}, {"name": "package_size"}]
|
||||
data = {
|
||||
"mapping": [
|
||||
{"excel": "STYLE", "sql": "package_style", "confidence": 0.9, "reason": "known"},
|
||||
{"excel": "Invented", "sql": "not_real", "confidence": 0.8, "reason": "guess"},
|
||||
]
|
||||
}
|
||||
|
||||
result = validate_schema_mapping(summaries, schema, data)
|
||||
|
||||
assert result.valid is True
|
||||
assert result.data["mapping"] == [
|
||||
{"excel": "STYLE", "sql": "package_style", "confidence": 0.9, "reason": "known"}
|
||||
]
|
||||
assert any("Invented" in warning for warning in result.warnings)
|
||||
assert any("not_real" in warning for warning in result.warnings)
|
||||
|
||||
|
||||
def test_workbook_analyzer_passes_parser_context_to_stage1_for_unknown_formats(monkeypatch):
|
||||
cm = ConfigManager()
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
analyzer = WorkbookAnalyzer(cm)
|
||||
wb = ParsedWorkbook(file_name="t.xlsx")
|
||||
wb.sheets.append(ParsedSheet(
|
||||
name="UNKNOWN", rows=2, cols=2, header_row=3, data_start_row=4, data_end_row=5,
|
||||
detected_headers=["STYLE", "ITEM SIZE"], raw_data=[["STYLE", "ITEM SIZE"], ["A", "H:16cm"]]
|
||||
))
|
||||
fallback = AnalysisResult(summaries=[], groups=[], mappings=[], engine="fuzzy")
|
||||
monkeypatch.setattr(analyzer, "_build_fallback_result", lambda parsed, preferred_type_id: fallback)
|
||||
seen = {}
|
||||
|
||||
def fake_stage1(name, rows, **kwargs):
|
||||
seen["stage1"] = kwargs
|
||||
return SheetSummary(name, 3, "definition", [{"header": "STYLE"}, {"header": "ITEM SIZE"}], [])
|
||||
|
||||
def fake_stage3(summaries, groups, schema_fields, **kwargs):
|
||||
seen["stage3"] = kwargs
|
||||
return [ColumnMapping("ITEM SIZE", "package_size", 0.85, "AI fill")]
|
||||
|
||||
monkeypatch.setattr(analyzer.stages, "stage1_read_sheet", fake_stage1)
|
||||
monkeypatch.setattr(analyzer.stages, "stage2_find_links", lambda summaries: [])
|
||||
monkeypatch.setattr(analyzer.stages, "stage3_map_columns", fake_stage3)
|
||||
|
||||
result = analyzer.analyze(wb, preferred_type_id=None, use_llm=True)
|
||||
|
||||
assert seen["stage1"]["known_header_row"] == 3
|
||||
assert seen["stage1"]["known_headers"] == ["STYLE", "ITEM SIZE"]
|
||||
assert seen["stage3"]["known_mappings"] == []
|
||||
assert result.engine == "llm"
|
||||
|
||||
|
||||
def test_workbook_analyzer_uses_known_type_fast_path_for_small_models(monkeypatch):
|
||||
cm = ConfigManager()
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
analyzer = WorkbookAnalyzer(cm)
|
||||
wb = ParsedWorkbook(file_name="t.xlsx")
|
||||
wb.sheets.append(ParsedSheet(
|
||||
name="DISNEY", rows=2, cols=2, header_row=3, data_start_row=4, data_end_row=5,
|
||||
detected_headers=["STYLE", "ITEM SIZE"], raw_data=[["STYLE", "ITEM SIZE"], ["A", "H:16cm"]]
|
||||
))
|
||||
fallback = AnalysisResult(
|
||||
summaries=[SheetSummary("DISNEY", 3, "definition", [{"header": "STYLE"}, {"header": "ITEM SIZE"}], [])],
|
||||
groups=[MergeGroup(["DISNEY"], "DISNEY", "known type", [])],
|
||||
mappings=[ColumnMapping("STYLE", "package_style", 1.0, "Known type")],
|
||||
engine="yaml",
|
||||
)
|
||||
monkeypatch.setattr(analyzer, "_build_fallback_result", lambda parsed, preferred_type_id: fallback)
|
||||
seen = {"stage1_called": False, "stage2_called": False}
|
||||
|
||||
def fail_stage1(*args, **kwargs):
|
||||
seen["stage1_called"] = True
|
||||
raise AssertionError("Known-type fast path should not rerun open-ended Stage 1")
|
||||
|
||||
def fail_stage2(*args, **kwargs):
|
||||
seen["stage2_called"] = True
|
||||
raise AssertionError("Known-type fast path should not rerun open-ended Stage 2")
|
||||
|
||||
def fake_stage3(summaries, groups, schema_fields, **kwargs):
|
||||
seen["stage3"] = kwargs
|
||||
assert summaries == fallback.summaries
|
||||
assert groups == fallback.groups
|
||||
return [ColumnMapping("ITEM SIZE", "package_size", 0.85, "AI fill")]
|
||||
|
||||
monkeypatch.setattr(analyzer.stages, "stage1_read_sheet", fail_stage1)
|
||||
monkeypatch.setattr(analyzer.stages, "stage2_find_links", fail_stage2)
|
||||
monkeypatch.setattr(analyzer.stages, "stage3_map_columns", fake_stage3)
|
||||
|
||||
result = analyzer.analyze(wb, preferred_type_id="kuji_tw", use_llm=True)
|
||||
|
||||
assert seen["stage1_called"] is False
|
||||
assert seen["stage2_called"] is False
|
||||
assert seen["stage3"]["known_mappings"] == [{
|
||||
"excel": "STYLE",
|
||||
"sql": "package_style",
|
||||
"confidence": 1.0,
|
||||
"reason": "Known type",
|
||||
}]
|
||||
assert result.engine == "hybrid"
|
||||
|
||||
|
||||
def test_workbook_analyzer_prefers_hybrid_even_when_llm_has_more_conflicting_rows(monkeypatch):
|
||||
cm = ConfigManager()
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
analyzer = WorkbookAnalyzer(cm)
|
||||
wb = ParsedWorkbook(file_name="t.xlsx")
|
||||
wb.sheets.append(ParsedSheet(
|
||||
name="DISNEY", rows=2, cols=3, header_row=1, data_start_row=2, data_end_row=2,
|
||||
detected_headers=["STYLE", "Product contents", "ITEM SIZE"],
|
||||
raw_data=[["STYLE", "Product contents", "ITEM SIZE"], ["A", "GRADE A", "H:16cm"]],
|
||||
))
|
||||
fallback = AnalysisResult(
|
||||
summaries=[SheetSummary("DISNEY", 1, "definition", [
|
||||
{"header": "STYLE"}, {"header": "Product contents"}, {"header": "ITEM SIZE"}
|
||||
], [])],
|
||||
groups=[],
|
||||
mappings=[ColumnMapping("STYLE", "package_style", 1.0, "Known type")],
|
||||
engine="yaml",
|
||||
)
|
||||
monkeypatch.setattr(analyzer, "_build_fallback_result", lambda parsed, preferred_type_id: fallback)
|
||||
monkeypatch.setattr(analyzer.stages, "stage3_map_columns", lambda *args, **kwargs: [
|
||||
ColumnMapping("STYLE", "package_size", 0.8, "wrong/conflicting guess"),
|
||||
ColumnMapping("ITEM SIZE", "package_size", 0.85, "AI fill"),
|
||||
])
|
||||
|
||||
result = analyzer.analyze(wb, preferred_type_id="kuji_tw", use_llm=True)
|
||||
|
||||
assert result.engine == "hybrid"
|
||||
mapped = {m.sql_target: m.excel_column for m in result.mappings}
|
||||
assert mapped["package_style"] == "STYLE"
|
||||
assert mapped["package_size"] == "ITEM SIZE"
|
||||
|
||||
|
||||
def test_hybrid_known_type_filters_low_confidence_ai_additions(monkeypatch):
|
||||
cm = ConfigManager()
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
analyzer = WorkbookAnalyzer(cm)
|
||||
wb = ParsedWorkbook(file_name="t.xlsx")
|
||||
wb.sheets.append(ParsedSheet(
|
||||
name="DISNEY", rows=2, cols=4, header_row=1, data_start_row=2, data_end_row=2,
|
||||
detected_headers=["STYLE", "ITEM SIZE", "QTY(pcs)", "入数"],
|
||||
raw_data=[["STYLE", "ITEM SIZE", "QTY(pcs)", "入数"], ["A", "H:16cm", "1", "64"]],
|
||||
))
|
||||
fallback = AnalysisResult(
|
||||
summaries=[SheetSummary("DISNEY", 1, "definition", [
|
||||
{"header": "STYLE"}, {"header": "ITEM SIZE"}, {"header": "QTY(pcs)"}, {"header": "入数"}
|
||||
], [])],
|
||||
groups=[],
|
||||
mappings=[ColumnMapping("STYLE", "package_style", 1.0, "Known type")],
|
||||
engine="yaml",
|
||||
)
|
||||
monkeypatch.setattr(analyzer, "_build_fallback_result", lambda parsed, preferred_type_id: fallback)
|
||||
monkeypatch.setattr(analyzer.stages, "stage3_map_columns", lambda *args, **kwargs: [
|
||||
ColumnMapping("ITEM SIZE", "package_size", 0.84, "below auto-use threshold"),
|
||||
ColumnMapping("入数", "pcs_ctn", 0.90, "high confidence AI fill"),
|
||||
])
|
||||
|
||||
result = analyzer.analyze(wb, preferred_type_id="kuji_tw", use_llm=True)
|
||||
|
||||
mapped = {m.sql_target: m.excel_column for m in result.mappings}
|
||||
assert mapped["package_style"] == "STYLE"
|
||||
assert "package_size" not in mapped
|
||||
assert mapped["pcs_ctn"] == "入数"
|
||||
warning_text = "\n".join(result.warnings).lower()
|
||||
assert "low-confidence ai mapping" in warning_text
|
||||
assert "auto-use threshold" in warning_text
|
||||
assert "approval" not in warning_text
|
||||
assert "review threshold" not in warning_text
|
||||
|
||||
|
||||
def test_ai_auto_accept_mapping_threshold_accepts_percent_or_fraction(tmp_path):
|
||||
import yaml
|
||||
|
||||
cfg = tmp_path / "config"
|
||||
cfg.mkdir()
|
||||
(cfg / "settings.example.yaml").write_text(yaml.safe_dump({"analysis": {"ai_auto_accept_mapping_threshold": 85}}), encoding="utf-8")
|
||||
assert ConfigManager(cfg).get_ai_auto_accept_mapping_threshold() == 0.85
|
||||
|
||||
(cfg / "settings.yaml").write_text(yaml.safe_dump({"analysis": {"ai_auto_accept_mapping_threshold": 0.9}}), encoding="utf-8")
|
||||
assert ConfigManager(cfg).get_ai_auto_accept_mapping_threshold() == 0.9
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Tests for Streamlit chrome/polish helpers."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from ui.app_chrome import build_step_items
|
||||
|
||||
|
||||
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",
|
||||
]
|
||||
assert [i["state"] for i in items] == [
|
||||
"done", "done", "done", "current", "pending",
|
||||
]
|
||||
assert items[3]["label"] == "Preview"
|
||||
assert items[3]["icon"] == "👁️"
|
||||
|
||||
|
||||
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",
|
||||
]
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_build_step_items_maps_internal_ai_summary_to_optional_ai_step():
|
||||
items = build_step_items("ai_summary")
|
||||
|
||||
assert [i["state"] for i in items] == ["done", "done", "current", "pending", "pending"]
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Temporary blueprint proposal persistence tests."""
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
def _sample_blueprint():
|
||||
return {
|
||||
"summaries": [
|
||||
{"sheet_name": "Item detail", "header_row": 1, "sheet_type": "detail", "columns": [{"header": "JAN", "samples": ["123"]}], "shared_values": []}
|
||||
],
|
||||
"groups": [],
|
||||
"mappings": [{"excel_column": "JAN", "sql_target": "generated_barcode", "confidence": 0.95, "reason": "test"}],
|
||||
}
|
||||
|
||||
|
||||
def test_save_list_load_blueprint_proposal(tmp_path: Path):
|
||||
saved = save_blueprint_proposal(
|
||||
tmp_path,
|
||||
blueprint=_sample_blueprint(),
|
||||
proposal_name="../Odd Name!",
|
||||
source_workbook_name="offer.xlsx",
|
||||
selected_type="kuji_tw",
|
||||
analysis_engine="hybrid",
|
||||
)
|
||||
assert saved.path.parent == tmp_path
|
||||
assert saved.path.name.endswith("odd_name.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["source_workbook_name"] == "offer.xlsx"
|
||||
assert payload["blueprint"]["mappings"][0]["sql_target"] == "generated_barcode"
|
||||
|
||||
|
||||
def test_build_type_config_from_proposal(tmp_path: Path):
|
||||
saved = save_blueprint_proposal(
|
||||
tmp_path,
|
||||
blueprint=_sample_blueprint(),
|
||||
proposal_name="My Learned Type",
|
||||
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)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Regression tests for BNTW KUJI workbook recognition and mapping."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.excel_parser import ExcelParser
|
||||
from services.fingerprint import Fingerprint
|
||||
from services.workbook_analyzer import WorkbookAnalyzer
|
||||
from services.field_transformer import transform_field_value
|
||||
from ui.preview_page import _build_merged_rows
|
||||
|
||||
|
||||
BNTW_FIXTURES = [
|
||||
Path("ref_files/kuji_bntw.xlsx"),
|
||||
Path("ref_files/kuji_bntw_2.xlsx"),
|
||||
]
|
||||
|
||||
|
||||
def _analysis_for(path: Path):
|
||||
cm = ConfigManager()
|
||||
parser = ExcelParser(cm)
|
||||
fp = Fingerprint(cm)
|
||||
parsed_initial = parser.parse(path)
|
||||
matches = fp.recognize(fp.compute_signature(parsed_initial))
|
||||
selected = matches[0].type_id
|
||||
parsed = parser.parse(path, type_id=selected)
|
||||
analysis = WorkbookAnalyzer(cm).analyze(parsed, preferred_type_id=selected, use_llm=False)
|
||||
return cm, parsed, matches, analysis
|
||||
|
||||
|
||||
def test_bntw_fixtures_recognize_kuji_tw_at_100_percent():
|
||||
for fixture in BNTW_FIXTURES:
|
||||
assert fixture.exists(), fixture
|
||||
_, _, matches, _ = _analysis_for(fixture)
|
||||
assert matches[0].type_id == "kuji_tw"
|
||||
assert matches[0].score == 100.0
|
||||
|
||||
|
||||
def test_bntw_sap_maps_from_gl_code_not_material():
|
||||
for fixture in BNTW_FIXTURES:
|
||||
_, _, _, analysis = _analysis_for(fixture)
|
||||
mapping = {(m.excel_column, m.sql_target) for m in analysis.mappings}
|
||||
assert ("GL品番", "sap") in mapping
|
||||
assert ("Material", "sap") not in mapping
|
||||
assert ("Material", "remark_item2") in mapping
|
||||
|
||||
|
||||
def test_bntw_generated_barcode_removes_spaces_in_output_preview():
|
||||
for fixture in BNTW_FIXTURES:
|
||||
cm, parsed, _, analysis = _analysis_for(fixture)
|
||||
rows = _build_merged_rows(parsed, {
|
||||
"summaries": analysis.summaries,
|
||||
"groups": analysis.groups,
|
||||
"mappings": analysis.mappings,
|
||||
})
|
||||
target_cols = cm.get_target_column_names()
|
||||
shaped = [{c: transform_field_value(cm, c, row.get(c)) for c in target_cols} for row in rows]
|
||||
assert shaped
|
||||
assert all(" " not in str(row.get("generated_barcode") or "") for row in shaped)
|
||||
|
||||
|
||||
def test_bntw_mapping_uses_one_excel_column_per_sql_target():
|
||||
for fixture in BNTW_FIXTURES:
|
||||
_, _, _, analysis = _analysis_for(fixture)
|
||||
by_target = {}
|
||||
for mapping in analysis.mappings:
|
||||
by_target.setdefault(mapping.sql_target, []).append(mapping.excel_column)
|
||||
|
||||
duplicates = {target: cols for target, cols in by_target.items() if len(cols) > 1}
|
||||
assert duplicates == {}
|
||||
assert by_target["item_name_eng"] == ["商品名/英語"]
|
||||
assert "Product contents" not in by_target["item_name_eng"]
|
||||
+247
-18
@@ -1,11 +1,11 @@
|
||||
"""Tests for ConfigManager."""
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
# We'll inject the config path for testing
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
@@ -16,7 +16,6 @@ def temp_config_dir():
|
||||
"""Create a temporary config directory with minimal valid configs."""
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
cfg = Path(tmpdir)
|
||||
# db_schema.yaml
|
||||
(cfg / "db_schema.yaml").write_text(yaml.dump({
|
||||
"table": "pre_item_master",
|
||||
"columns": [
|
||||
@@ -26,14 +25,12 @@ def temp_config_dir():
|
||||
]
|
||||
}, allow_unicode=True), encoding="utf-8")
|
||||
|
||||
# settings.yaml
|
||||
(cfg / "settings.yaml").write_text(yaml.dump({
|
||||
"app": {"name": "Test", "version": "0.1"},
|
||||
"fuzzy": {"default_threshold": 75, "keyword_match_min": 2},
|
||||
"file": {"max_upload_size_mb": 200}
|
||||
"file": {"max_upload_size_mb": 200},
|
||||
}, allow_unicode=True), encoding="utf-8")
|
||||
|
||||
# types directory
|
||||
types_dir = cfg / "types"
|
||||
types_dir.mkdir()
|
||||
(types_dir / "test_type.yaml").write_text(yaml.dump({
|
||||
@@ -49,7 +46,6 @@ def temp_config_dir():
|
||||
"sheet_combine": {"strategy": "join_on_form_fields"},
|
||||
}, allow_unicode=True), encoding="utf-8")
|
||||
|
||||
# synonyms.yaml
|
||||
(cfg / "synonyms.yaml").write_text(yaml.dump({
|
||||
"synonyms": {
|
||||
"generated_barcode": ["SALES JAN CODE", "JAN CODE", "GL JAN"],
|
||||
@@ -60,6 +56,60 @@ def temp_config_dir():
|
||||
yield cfg
|
||||
|
||||
|
||||
def write_llm_profile_settings(
|
||||
config_dir: Path,
|
||||
*,
|
||||
enabled: bool = True,
|
||||
active_profile: str = "local",
|
||||
profiles: dict | None = None,
|
||||
) -> None:
|
||||
"""Replace the llm block with profile-based test settings."""
|
||||
settings_path = config_dir / "settings.yaml"
|
||||
settings = yaml.safe_load(settings_path.read_text(encoding="utf-8")) or {}
|
||||
settings["llm"] = {
|
||||
"enabled": enabled,
|
||||
"active_profile": active_profile,
|
||||
"profiles": profiles or {
|
||||
"local": {
|
||||
"label": "DGX Spark Local",
|
||||
"base_url": "http://localhost:8000/v1",
|
||||
"model": "local-llm",
|
||||
"api_key": "local-key",
|
||||
"timeout_seconds": 60,
|
||||
"temperature": 0.1,
|
||||
"ssl_verify": True,
|
||||
"stream_response": True,
|
||||
"mode": "small",
|
||||
"max_sheet_rows": 80,
|
||||
"max_sheet_cols": 30,
|
||||
"max_candidates_per_sheet": 4,
|
||||
"sample_rows_per_candidate": 4,
|
||||
"max_mapping_columns": 40,
|
||||
},
|
||||
"cloud": {
|
||||
"label": "Cloud AI",
|
||||
"base_url": "https://api.deepseek.com/v1",
|
||||
"model": "deepseek-chat",
|
||||
"api_key": "cloud-key",
|
||||
"timeout_seconds": 90,
|
||||
"temperature": 0.1,
|
||||
"ssl_verify": True,
|
||||
"stream_response": True,
|
||||
"mode": "large",
|
||||
"max_sheet_rows": 200,
|
||||
"max_sheet_cols": 60,
|
||||
"max_candidates_per_sheet": 10,
|
||||
"sample_rows_per_candidate": 8,
|
||||
"max_mapping_columns": 100,
|
||||
},
|
||||
},
|
||||
"auto_apply_confidence": 0.9,
|
||||
"fingerprint_auto_threshold": 80,
|
||||
"fingerprint_suggest_threshold": 60,
|
||||
}
|
||||
settings_path.write_text(yaml.dump(settings, allow_unicode=True), encoding="utf-8")
|
||||
|
||||
|
||||
class TestConfigManager:
|
||||
def test_loads_db_schema(self, temp_config_dir):
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
@@ -109,6 +159,25 @@ class TestConfigManager:
|
||||
settings = cm.get_settings()
|
||||
assert settings["fuzzy"]["default_threshold"] == 75
|
||||
|
||||
def test_ai_debug_log_config_defaults_to_project_data_debug(self, temp_config_dir):
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
|
||||
cfg = cm.get_ai_debug_log_config()
|
||||
|
||||
assert cfg == {"enabled": True, "dir": "data/debug", "max_string_chars": 12000}
|
||||
assert cm.get_ai_debug_log_dir() == temp_config_dir.parent / "data" / "debug"
|
||||
|
||||
def test_ai_debug_log_config_can_be_disabled_and_redirected(self, temp_config_dir):
|
||||
settings_path = temp_config_dir / "settings.yaml"
|
||||
settings = yaml.safe_load(settings_path.read_text(encoding="utf-8")) or {}
|
||||
settings["analysis"] = {"ai_debug_log": {"enabled": "off", "dir": "logs/ai", "max_string_chars": 3333}}
|
||||
settings_path.write_text(yaml.dump(settings, allow_unicode=True), encoding="utf-8")
|
||||
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
|
||||
assert cm.get_ai_debug_log_config() == {"enabled": False, "dir": "logs/ai", "max_string_chars": 3333}
|
||||
assert cm.get_ai_debug_log_dir() == temp_config_dir.parent / "logs" / "ai"
|
||||
|
||||
def test_save_type_config(self, temp_config_dir):
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
new_cfg = {
|
||||
@@ -121,7 +190,6 @@ class TestConfigManager:
|
||||
"sheet_combine": {"strategy": "join_on_form_fields"},
|
||||
}
|
||||
cm.save_type_config("new_type", new_cfg)
|
||||
# Verify written to disk
|
||||
saved = yaml.safe_load((temp_config_dir / "types" / "new_type.yaml").read_text(encoding="utf-8"))
|
||||
assert saved["type_id"] == "new_type"
|
||||
|
||||
@@ -132,31 +200,192 @@ class TestConfigManager:
|
||||
saved = yaml.safe_load((temp_config_dir / "synonyms.yaml").read_text(encoding="utf-8"))
|
||||
assert "NEW SYNONYM" in saved["synonyms"]["generated_barcode"]
|
||||
|
||||
def test_type_support_notes_roundtrip(self, temp_config_dir):
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
notes = {
|
||||
"version": 1,
|
||||
"source_type": "test_type",
|
||||
"notes": {"header_aliases": [{"sql_target": "item_name_eng", "preferred_headers": ["ITEM NAME"]}]},
|
||||
}
|
||||
|
||||
saved_path = cm.save_type_support_notes("test_type", notes)
|
||||
loaded = cm.load_type_support_notes("test_type")
|
||||
|
||||
assert saved_path == temp_config_dir / "type_notes" / "test_type.ai_notes.yaml"
|
||||
assert loaded["source_type"] == "test_type"
|
||||
assert loaded["notes"]["header_aliases"][0]["preferred_headers"] == ["ITEM NAME"]
|
||||
assert cm.load_type_support_notes("missing") is None
|
||||
|
||||
|
||||
class TestLLMConfig:
|
||||
def test_get_llm_config_with_defaults(self, temp_config_dir, monkeypatch):
|
||||
# temp_config_dir's settings.yaml has no llm block -> defaults apply
|
||||
def test_get_llm_config_with_defaults(self, temp_config_dir):
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
cfg = cm.get_llm_config()
|
||||
assert cfg["enabled"] is False # default when absent
|
||||
assert cfg["timeout_seconds"] == 30
|
||||
assert cfg["enabled"] is False
|
||||
assert cfg["active_profile"] == "local"
|
||||
assert cfg["profiles"] == {}
|
||||
assert cfg["auto_apply_confidence"] == 0.9
|
||||
|
||||
def test_is_llm_enabled_false_when_absent(self, temp_config_dir):
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
assert cm.is_llm_enabled() is False
|
||||
|
||||
def test_get_llm_api_key_from_env(self, temp_config_dir, monkeypatch):
|
||||
def test_get_llm_api_key_from_active_profile(self, temp_config_dir):
|
||||
write_llm_profile_settings(temp_config_dir, active_profile="local")
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
monkeypatch.setenv("BNA_API_KEY", "sk-test-123")
|
||||
assert cm.get_llm_api_key() == "sk-test-123"
|
||||
assert cm.get_llm_api_key() == "local-key"
|
||||
|
||||
def test_get_llm_api_key_none_when_unset(self, temp_config_dir, monkeypatch):
|
||||
def test_get_llm_api_key_none_when_unset(self, temp_config_dir):
|
||||
write_llm_profile_settings(
|
||||
temp_config_dir,
|
||||
profiles={
|
||||
"local": {
|
||||
"label": "DGX Spark Local",
|
||||
"base_url": "http://localhost:8000/v1",
|
||||
"model": "local-llm",
|
||||
"api_key": "",
|
||||
"mode": "small",
|
||||
}
|
||||
},
|
||||
)
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
monkeypatch.delenv("BNA_API_KEY", raising=False)
|
||||
assert cm.get_llm_api_key() is None
|
||||
|
||||
def test_get_fingerprint_thresholds(self, temp_config_dir):
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
auto, suggest = cm.get_fingerprint_thresholds()
|
||||
assert auto == 80 and suggest == 60
|
||||
|
||||
def test_resolve_llm_profile_local(self, temp_config_dir):
|
||||
write_llm_profile_settings(temp_config_dir, active_profile="local")
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
resolved = cm.resolve_llm_connection_config()
|
||||
|
||||
assert resolved is not None
|
||||
assert resolved["profile"] == "local"
|
||||
assert resolved["label"] == "DGX Spark Local"
|
||||
assert resolved["mode"] == "small"
|
||||
assert resolved["api_key"] == "local-key"
|
||||
assert resolved["base_url"] == "http://localhost:8000/v1"
|
||||
assert resolved["model"] == "local-llm"
|
||||
assert resolved["timeout_seconds"] == 60
|
||||
assert resolved["ssl_verify"] is True
|
||||
assert resolved["stream_response"] is True
|
||||
assert resolved["source"] == "project"
|
||||
assert resolved["budgets"] == {
|
||||
"max_sheet_rows": 80,
|
||||
"max_sheet_cols": 30,
|
||||
"max_candidates_per_sheet": 4,
|
||||
"sample_rows_per_candidate": 4,
|
||||
"max_mapping_columns": 40,
|
||||
}
|
||||
|
||||
def test_resolve_llm_profile_cloud(self, temp_config_dir):
|
||||
write_llm_profile_settings(temp_config_dir, active_profile="cloud")
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
resolved = cm.resolve_llm_connection_config()
|
||||
|
||||
assert resolved is not None
|
||||
assert resolved["profile"] == "cloud"
|
||||
assert resolved["label"] == "Cloud AI"
|
||||
assert resolved["mode"] == "large"
|
||||
assert resolved["api_key"] == "cloud-key"
|
||||
assert resolved["base_url"] == "https://api.deepseek.com/v1"
|
||||
assert resolved["model"] == "deepseek-chat"
|
||||
assert resolved["timeout_seconds"] == 90
|
||||
assert resolved["stream_response"] is True
|
||||
assert resolved["budgets"]["max_sheet_rows"] == 200
|
||||
assert resolved["budgets"]["max_mapping_columns"] == 100
|
||||
|
||||
def test_resolve_llm_connection_preserves_ssl_verify_false_for_internal_https(self, temp_config_dir):
|
||||
write_llm_profile_settings(
|
||||
temp_config_dir,
|
||||
profiles={
|
||||
"local": {
|
||||
"label": "Internal HTTPS",
|
||||
"base_url": "https://bnaai02.bhk.local/v1",
|
||||
"model": "gemma4:latest",
|
||||
"api_key": "settings-test-key",
|
||||
"ssl_verify": False,
|
||||
"stream_response": False,
|
||||
"mode": "small",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
resolved = cm.resolve_llm_connection_config()
|
||||
|
||||
assert resolved is not None
|
||||
assert resolved["base_url"] == "https://bnaai02.bhk.local/v1"
|
||||
assert resolved["model"] == "gemma4:latest"
|
||||
assert resolved["ssl_verify"] is False
|
||||
assert resolved["stream_response"] is False
|
||||
|
||||
def test_resolve_llm_connection_defaults_ssl_verify_false_when_omitted(self, temp_config_dir):
|
||||
write_llm_profile_settings(
|
||||
temp_config_dir,
|
||||
profiles={
|
||||
"local": {
|
||||
"label": "Internal HTTPS",
|
||||
"base_url": "https://bnaai02.bhk.local/v1",
|
||||
"model": "gemma4:latest",
|
||||
"api_key": "settings-test-key",
|
||||
"stream_response": False,
|
||||
"mode": "small",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
resolved = cm.resolve_llm_connection_config()
|
||||
|
||||
assert resolved is not None
|
||||
assert resolved["ssl_verify"] is False
|
||||
|
||||
def test_resolve_llm_connection_missing_active_profile_returns_none(self, temp_config_dir):
|
||||
write_llm_profile_settings(temp_config_dir, active_profile="missing")
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
assert cm.get_llm_api_key() is None
|
||||
assert cm.resolve_llm_connection_config() is None
|
||||
|
||||
def test_resolve_llm_connection_missing_key_or_base_url_returns_none(self, temp_config_dir):
|
||||
write_llm_profile_settings(
|
||||
temp_config_dir,
|
||||
profiles={
|
||||
"local": {
|
||||
"label": "DGX Spark Local",
|
||||
"base_url": "",
|
||||
"model": "local-llm",
|
||||
"api_key": "",
|
||||
"mode": "small",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
assert cm.get_llm_api_key() is None
|
||||
assert cm.resolve_llm_connection_config() is None
|
||||
|
||||
def test_redacted_placeholder_key_is_ignored(self, temp_config_dir):
|
||||
write_llm_profile_settings(
|
||||
temp_config_dir,
|
||||
profiles={
|
||||
"local": {
|
||||
"label": "DGX Spark Local",
|
||||
"base_url": "http://localhost:8000/v1",
|
||||
"model": "local-llm",
|
||||
"api_key": "«redacted:sk-…»",
|
||||
"mode": "small",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
assert cm.get_llm_api_key() is None
|
||||
assert cm.resolve_llm_connection_config() is None
|
||||
|
||||
def test_resolve_llm_connection_disabled_returns_none(self, temp_config_dir):
|
||||
write_llm_profile_settings(temp_config_dir, enabled=False)
|
||||
cm = ConfigManager(config_dir=temp_config_dir)
|
||||
assert cm.resolve_llm_connection_config() is None
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Tests for the English-only Streamlit copy registry."""
|
||||
|
||||
from ui.copy import DEFAULT_LANGUAGE, current_language, t
|
||||
|
||||
|
||||
def test_copy_registry_has_one_runtime_language():
|
||||
assert DEFAULT_LANGUAGE == "en"
|
||||
assert current_language() == "en"
|
||||
assert t("step.preview") == "Preview"
|
||||
|
||||
|
||||
def test_copy_registry_formats_named_values():
|
||||
assert t("preview.rows", count=3) == "Merged rows"
|
||||
assert "42.0%" in t("upload.basic_progress", score=42.0)
|
||||
@@ -1,120 +0,0 @@
|
||||
"""Tests for DataProcessor."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import pytest
|
||||
from services.config_manager import ConfigManager
|
||||
from services.excel_parser import ParsedWorkbook, ParsedSheet
|
||||
from services.fuzzy_matcher import MatchResult, FormFieldMatch
|
||||
from services.data_processor import DataProcessor, ProcessedData, DroppedRow
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config_manager():
|
||||
return ConfigManager()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def processor(config_manager):
|
||||
return DataProcessor(config_manager)
|
||||
|
||||
|
||||
def make_workbook(headers: list[str], rows: list[list], sheet_name="Data"):
|
||||
"""Helper to create a minimal ParsedWorkbook."""
|
||||
wb = ParsedWorkbook(file_name="test.xlsx")
|
||||
sheet = ParsedSheet(
|
||||
name=sheet_name,
|
||||
rows=len(headers) + len(rows),
|
||||
cols=len(headers),
|
||||
header_row=1,
|
||||
data_start_row=2,
|
||||
data_end_row=1 + len(rows),
|
||||
detected_headers=headers,
|
||||
raw_data=[list(headers)] + [list(r) for r in rows],
|
||||
)
|
||||
wb.sheets.append(sheet)
|
||||
return wb
|
||||
|
||||
|
||||
class TestDataProcessor:
|
||||
def test_basic_transform(self, processor):
|
||||
"""Simple 1:1 mapping should produce correct rows."""
|
||||
wb = make_workbook(
|
||||
headers=["JAN", "Name"],
|
||||
rows=[["123", "Item A"], ["456", "Item B"]],
|
||||
)
|
||||
match_results = [
|
||||
MatchResult(source_header="JAN", matched_target="generated_barcode", confidence=95),
|
||||
MatchResult(source_header="Name", matched_target="item_name_eng", confidence=90),
|
||||
]
|
||||
result = processor.process(wb, match_results, [])
|
||||
assert len(result.rows) == 2
|
||||
assert result.rows[0]["generated_barcode"] == "123"
|
||||
assert result.rows[0]["item_name_eng"] == "Item A"
|
||||
assert len(result.dropped_rows) == 0
|
||||
|
||||
def test_flags_all_key_fields_missing(self, processor):
|
||||
"""Row with ALL key fields (barcode, name_eng, name_jap) empty → flagged."""
|
||||
wb = make_workbook(
|
||||
headers=["JAN", "Name ENG", "Name JAP"],
|
||||
rows=[["", "", ""], ["456", "Item B", "アイテムB"]],
|
||||
)
|
||||
match_results = [
|
||||
MatchResult(source_header="JAN", matched_target="generated_barcode", confidence=95),
|
||||
MatchResult(source_header="Name ENG", matched_target="item_name_eng", confidence=90),
|
||||
MatchResult(source_header="Name JAP", matched_target="item_name_jap", confidence=90),
|
||||
]
|
||||
result = processor.process(wb, match_results, [])
|
||||
assert len(result.rows) == 1 # second row kept: has all three
|
||||
assert len(result.dropped_rows) == 1 # first row dropped: all empty
|
||||
assert "key field" in result.dropped_rows[0].drop_reason.lower()
|
||||
|
||||
def test_keeps_row_with_at_least_one_key(self, processor):
|
||||
"""Row with only item_name_eng (but no barcode) should be KEPT."""
|
||||
wb = make_workbook(
|
||||
headers=["JAN", "Name ENG", "Name JAP"],
|
||||
rows=[["", "Just a Name", ""]],
|
||||
)
|
||||
match_results = [
|
||||
MatchResult(source_header="JAN", matched_target="generated_barcode", confidence=95),
|
||||
MatchResult(source_header="Name ENG", matched_target="item_name_eng", confidence=90),
|
||||
MatchResult(source_header="Name JAP", matched_target="item_name_jap", confidence=90),
|
||||
]
|
||||
result = processor.process(wb, match_results, [])
|
||||
# item_name_eng present → should be kept despite missing barcode
|
||||
assert len(result.rows) == 1
|
||||
assert len(result.dropped_rows) == 0
|
||||
|
||||
def test_restore_dropped_row(self, processor):
|
||||
wb = make_workbook(
|
||||
headers=["JAN", "Name ENG", "Name JAP"],
|
||||
rows=[["", "", ""]],
|
||||
)
|
||||
match_results = [
|
||||
MatchResult(source_header="JAN", matched_target="generated_barcode", confidence=95),
|
||||
MatchResult(source_header="Name ENG", matched_target="item_name_eng", confidence=90),
|
||||
MatchResult(source_header="Name JAP", matched_target="item_name_jap", confidence=90),
|
||||
]
|
||||
result = processor.process(wb, match_results, [])
|
||||
assert len(result.dropped_rows) == 1
|
||||
result = processor.restore_row(result, 0)
|
||||
assert len(result.dropped_rows) == 0
|
||||
assert len(result.rows) == 1
|
||||
|
||||
def test_form_field_propagation(self, processor):
|
||||
"""Form field value should be applied to all rows."""
|
||||
wb = make_workbook(
|
||||
headers=["Name"],
|
||||
rows=[["Item A"], ["Item B"]],
|
||||
)
|
||||
match_results = [
|
||||
MatchResult(source_header="Name", matched_target="item_name_eng", confidence=90),
|
||||
]
|
||||
form_matches = [
|
||||
FormFieldMatch(label="JAN CODE", value="SHARED_JAN", matched_target="generated_barcode", confidence=95),
|
||||
]
|
||||
result = processor.process(wb, match_results, form_matches)
|
||||
assert len(result.rows) == 2
|
||||
assert result.rows[0]["generated_barcode"] == "SHARED_JAN"
|
||||
assert result.rows[1]["generated_barcode"] == "SHARED_JAN"
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Dependency guardrails for noisy Streamlit runtime warnings."""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from importlib import metadata
|
||||
|
||||
from packaging.version import Version
|
||||
|
||||
|
||||
def test_requests_import_does_not_emit_dependency_warning():
|
||||
"""Old requests + newer urllib3/chardet combinations warn at app startup."""
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-W",
|
||||
"error::requests.exceptions.RequestsDependencyWarning",
|
||||
"-c",
|
||||
"import requests; print(requests.__version__)",
|
||||
],
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert Version(result.stdout.strip()) >= Version("2.34.2")
|
||||
|
||||
|
||||
def test_python_multipart_version_has_boundary_warning_fix():
|
||||
"""python-multipart 0.0.18 falsely logged 'Skipping data after last boundary'."""
|
||||
assert Version(metadata.version("python-multipart")) >= Version("0.0.32")
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Docker Compose deployment file tests."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
PROJECT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def test_dockerfile_serves_streamlit_on_8501():
|
||||
dockerfile = PROJECT / "Dockerfile"
|
||||
assert dockerfile.exists()
|
||||
text = dockerfile.read_text(encoding="utf-8")
|
||||
assert "FROM python:3.11-slim" in text
|
||||
assert "EXPOSE 8501" in text
|
||||
assert "streamlit" in text
|
||||
assert "--server.port=8501" in text
|
||||
|
||||
|
||||
def test_docker_compose_mounts_config_and_data_and_exposes_8501():
|
||||
compose_path = PROJECT / "docker-compose.yml"
|
||||
assert compose_path.exists()
|
||||
compose = yaml.safe_load(compose_path.read_text(encoding="utf-8"))
|
||||
service = compose["services"]["nbd-preitemmaster"]
|
||||
assert "8501:8501" in service["ports"]
|
||||
assert "./config:/app/config" in service["volumes"]
|
||||
assert "./data:/app/data" in service["volumes"]
|
||||
env = service.get("environment") or []
|
||||
assert any(str(item).startswith("ADMIN_PASSWORD_HASH=") for item in env)
|
||||
|
||||
|
||||
def test_dockerignore_excludes_runtime_secrets_and_local_artifacts():
|
||||
ignore_path = PROJECT / ".dockerignore"
|
||||
assert ignore_path.exists()
|
||||
text = ignore_path.read_text(encoding="utf-8")
|
||||
assert "config/settings.yaml" in text
|
||||
assert ".venv" in text
|
||||
assert "data/" in text
|
||||
+14
-142
@@ -9,9 +9,8 @@ import pytest
|
||||
import openpyxl
|
||||
from services.config_manager import ConfigManager
|
||||
from services.excel_parser import ExcelParser
|
||||
from services.fuzzy_matcher import FuzzyMatcher
|
||||
from services.data_processor import DataProcessor
|
||||
from services.export_service import ExportService
|
||||
from services.export_models import ProcessedData
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -30,147 +29,20 @@ def kuji_path():
|
||||
class TestE2E:
|
||||
"""Full pipeline integration test with real sample data."""
|
||||
|
||||
def test_full_pipeline_kuji_bna(self, config_manager, kuji_path):
|
||||
"""Run the full pipeline: parse → match → process → export."""
|
||||
# Stage 1: Parse
|
||||
parser = ExcelParser(config_manager)
|
||||
parsed = parser.parse(kuji_path, type_id="kuji_bna")
|
||||
|
||||
assert len(parsed.sheets) > 0, "Should have at least one sheet"
|
||||
sheet_names = [s.name for s in parsed.sheets]
|
||||
assert "Item detail" in sheet_names, "Should find the Item detail sheet"
|
||||
|
||||
# Stage 2: Match — collect headers from all sheets
|
||||
matcher = FuzzyMatcher(config_manager)
|
||||
all_headers = []
|
||||
for sheet in parsed.sheets:
|
||||
for h in sheet.detected_headers:
|
||||
if h and h not in all_headers:
|
||||
all_headers.append(h)
|
||||
|
||||
match_results = matcher.match(all_headers, type_id="kuji_bna")
|
||||
matched = [mr for mr in match_results if mr.matched_target]
|
||||
|
||||
# At least one column should match
|
||||
assert len(matched) > 0, "At least one column should be auto-matched"
|
||||
|
||||
# Stage 3: Process
|
||||
all_form_fields = []
|
||||
for sheet in parsed.sheets:
|
||||
all_form_fields.extend(sheet.form_fields)
|
||||
form_matches = matcher.match_form_fields(all_form_fields, type_id="kuji_bna")
|
||||
|
||||
processor = DataProcessor(config_manager)
|
||||
processed = processor.process(parsed, match_results, form_matches, type_id="kuji_bna")
|
||||
|
||||
total = len(processed.rows) + len(processed.dropped_rows)
|
||||
assert total > 0, "Should process at least one row"
|
||||
|
||||
# Stage 4: Export — verify it produces valid xlsx
|
||||
svc = ExportService()
|
||||
excel_bytes = svc.export_to_bytes(processed)
|
||||
assert len(excel_bytes) > 0, "Should produce non-empty export"
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(excel_bytes))
|
||||
assert wb.sheetnames == [config_manager.get_target_table_name()]
|
||||
exported_ws = wb[config_manager.get_target_table_name()]
|
||||
assert exported_ws.max_row >= 1, "Should have at least a header row"
|
||||
|
||||
# Write diagnostics to temp file (avoids console Unicode issues on Windows)
|
||||
diag_path = Path("test_e2e_diagnostics.txt")
|
||||
with open(diag_path, "w", encoding="utf-8") as f:
|
||||
f.write(f"=== E2E Pipeline Diagnostics ===\n\n")
|
||||
f.write(f"Sheets: {sheet_names}\n\n")
|
||||
for sheet in parsed.sheets:
|
||||
f.write(f" {sheet.name}: header_row={sheet.header_row}, "
|
||||
f"data rows={sheet.data_start_row}-{sheet.data_end_row}\n")
|
||||
f.write(f" headers={sheet.detected_headers!r}\n")
|
||||
f.write(f" form_fields={[(ff.label, ff.value) for ff in sheet.form_fields]}\n\n")
|
||||
f.write(f"Matched columns: {len(matched)}/{len(match_results)}\n")
|
||||
for mr in matched:
|
||||
f.write(f" {mr.source_header!r} → {mr.matched_target} ({mr.confidence:.0f}%)\n")
|
||||
f.write(f"\nRows kept: {len(processed.rows)}, dropped: {len(processed.dropped_rows)}\n")
|
||||
f.write(f"Warnings: {processed.warnings}\n")
|
||||
diag_path.unlink(missing_ok=True)
|
||||
|
||||
def test_auto_detect_finds_type(self, config_manager, kuji_path):
|
||||
"""Auto-detect should identify a type from the sample file."""
|
||||
parser = ExcelParser(config_manager)
|
||||
parsed = parser.parse(kuji_path, type_id=None)
|
||||
|
||||
matcher = FuzzyMatcher(config_manager)
|
||||
detected = matcher.auto_detect_type(parsed)
|
||||
|
||||
# Should auto-detect a type (at least 2 keyword hits from kuji_bntw)
|
||||
assert detected is not None, "Should auto-detect a type"
|
||||
|
||||
def test_export_contains_required_columns(self, config_manager, kuji_path):
|
||||
"""Exported data should list all target columns as headers."""
|
||||
parser = ExcelParser(config_manager)
|
||||
parsed = parser.parse(kuji_path, type_id="kuji_bna")
|
||||
|
||||
matcher = FuzzyMatcher(config_manager)
|
||||
all_headers = []
|
||||
for sheet in parsed.sheets:
|
||||
for h in sheet.detected_headers:
|
||||
if h and h not in all_headers:
|
||||
all_headers.append(h)
|
||||
match_results = matcher.match(all_headers, type_id="kuji_bna")
|
||||
|
||||
processor = DataProcessor(config_manager)
|
||||
processed = processor.process(parsed, match_results, [], type_id="kuji_bna")
|
||||
|
||||
svc = ExportService()
|
||||
excel_bytes = svc.export_to_bytes(processed)
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(excel_bytes))
|
||||
assert wb.sheetnames == [config_manager.get_target_table_name()]
|
||||
ws = wb[config_manager.get_target_table_name()]
|
||||
header_row = [ws.cell(row=1, column=c).value for c in range(1, ws.max_column + 1)]
|
||||
assert header_row == config_manager.get_target_column_names()
|
||||
|
||||
def test_pipeline_with_matching_service_fallback(self, config_manager, kuji_path):
|
||||
"""Full pipeline via MatchingService with LLM off -> fuzzy fallback path."""
|
||||
from services.matching_service import MatchingService
|
||||
from services.data_processor import DataProcessor
|
||||
from services.export_service import ExportService
|
||||
from services.excel_parser import ExcelParser
|
||||
|
||||
parser = ExcelParser(config_manager)
|
||||
parsed = parser.parse(kuji_path, type_id="kuji_bna")
|
||||
|
||||
svc = MatchingService(config_manager)
|
||||
results = svc.match(parsed, type_id="kuji_bna")
|
||||
matched = [r for r in results if r.matched_target]
|
||||
assert len(matched) > 0, "fuzzy fallback should still match columns"
|
||||
assert all(r.engine in ("llm", "fuzzy", "") for r in results)
|
||||
|
||||
processor = DataProcessor(config_manager)
|
||||
processed = processor.process(parsed, results, [], type_id="kuji_bna")
|
||||
assert (len(processed.rows) + len(processed.dropped_rows)) > 0
|
||||
|
||||
svc_export = ExportService()
|
||||
assert len(svc_export.export_to_bytes(processed)) > 0
|
||||
|
||||
|
||||
def test_analyzer_fallback_when_llm_off(self, config_manager, kuji_path):
|
||||
"""WorkbookAnalyzer with LLM off returns fuzzy engine + warning."""
|
||||
from services.workbook_analyzer import WorkbookAnalyzer
|
||||
old = os.environ.pop("BNA_API_KEY", None)
|
||||
parsed = ExcelParser(config_manager).parse(kuji_path, type_id="kuji_bna")
|
||||
# Patch is_llm_enabled for this test only
|
||||
orig = config_manager.is_llm_enabled
|
||||
try:
|
||||
parsed = ExcelParser(config_manager).parse(kuji_path, type_id="kuji_bna")
|
||||
# Patch is_llm_enabled for this test only
|
||||
orig = config_manager.is_llm_enabled
|
||||
config_manager.is_llm_enabled = lambda: False
|
||||
analyzer = WorkbookAnalyzer(config_manager)
|
||||
result = analyzer.analyze(parsed)
|
||||
assert result.engine in ("fuzzy", "yaml")
|
||||
assert len(result.warnings) >= 1
|
||||
|
||||
finally:
|
||||
config_manager.is_llm_enabled = orig
|
||||
if old is not None:
|
||||
os.environ["BNA_API_KEY"] = old
|
||||
|
||||
def test_merge_engine_value_token_on_real_data(self, config_manager, kuji_path):
|
||||
"""MergeEngine joins STYLE 'A' into name 'GRADE A:Figure' rows."""
|
||||
@@ -185,14 +57,14 @@ class TestE2E:
|
||||
assert out[0]["SIZE"] == "H:16cm"
|
||||
assert out[1]["SIZE"] == "H:18cm"
|
||||
|
||||
def test_v2_kuji_bntw_exports_pre_item_master_excel(self, config_manager, kuji_path):
|
||||
def test_kuji_bntw_exports_pre_item_master_excel(self, config_manager, kuji_path):
|
||||
"""Real sample should export an .xlsx shaped exactly like pre_item_master SQL."""
|
||||
from io import BytesIO
|
||||
from services.fingerprint import Fingerprint
|
||||
from services.workbook_analyzer import WorkbookAnalyzer
|
||||
from services.data_processor import ProcessedData
|
||||
from services.export_service import ExportService
|
||||
from ui.preview_page_v2 import _build_merged_rows
|
||||
from ui.preview_page import _build_merged_rows
|
||||
from services.field_transformer import transform_field_value
|
||||
|
||||
parser = ExcelParser(config_manager)
|
||||
fingerprint = Fingerprint(config_manager)
|
||||
@@ -210,7 +82,7 @@ class TestE2E:
|
||||
"mappings": analysis.mappings,
|
||||
})
|
||||
target_cols = config_manager.get_target_column_names()
|
||||
filled = [{c: row.get(c) for c in target_cols} for row in rows]
|
||||
filled = [{c: transform_field_value(config_manager, c, row.get(c)) for c in target_cols} for row in rows]
|
||||
processed = ProcessedData(rows=filled, dropped_rows=[], warnings=[], target_columns=target_cols)
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(ExportService().export_to_bytes(processed)))
|
||||
@@ -220,19 +92,19 @@ class TestE2E:
|
||||
|
||||
assert exported_headers == target_cols
|
||||
|
||||
assert ws.cell(row=2, column=target_cols.index("generated_barcode") + 1).value == "457310268 211 6"
|
||||
assert ws.cell(row=2, column=target_cols.index("generated_barcode") + 1).value == "4573102682116"
|
||||
assert ws.cell(row=3, column=target_cols.index("package_style") + 1).value == "A"
|
||||
assert ws.cell(row=3, column=target_cols.index("package_size") + 1).value == "H:16cm"
|
||||
assert ws.cell(row=3, column=target_cols.index("item_name_eng") + 1).value == "GRADE A:Figure"
|
||||
|
||||
def test_v2_kuji_bntw_2_uses_dynamic_sheet_relation(self, config_manager):
|
||||
def test_kuji_bntw_2_uses_dynamic_sheet_relation(self, config_manager):
|
||||
"""A same-format workbook with a different product sheet name should still merge dynamically."""
|
||||
from io import BytesIO
|
||||
from services.fingerprint import Fingerprint
|
||||
from services.workbook_analyzer import WorkbookAnalyzer
|
||||
from services.data_processor import ProcessedData
|
||||
from services.export_service import ExportService
|
||||
from ui.preview_page_v2 import _build_merged_rows
|
||||
from services.field_transformer import transform_field_value
|
||||
from ui.preview_page import _build_merged_rows
|
||||
|
||||
kuji2_path = Path(__file__).resolve().parent.parent / "ref_files" / "kuji_bntw_2.xlsx"
|
||||
if not kuji2_path.exists():
|
||||
@@ -256,7 +128,7 @@ class TestE2E:
|
||||
"mappings": analysis.mappings,
|
||||
})
|
||||
target_cols = config_manager.get_target_column_names()
|
||||
filled = [{c: row.get(c) for c in target_cols} for row in rows]
|
||||
filled = [{c: transform_field_value(config_manager, c, row.get(c)) for c in target_cols} for row in rows]
|
||||
processed = ProcessedData(rows=filled, dropped_rows=[], warnings=[], target_columns=target_cols)
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(ExportService().export_to_bytes(processed)))
|
||||
@@ -266,7 +138,7 @@ class TestE2E:
|
||||
|
||||
assert exported_headers == target_cols
|
||||
assert ws.max_row - 1 == 12
|
||||
assert ws.cell(row=2, column=target_cols.index("generated_barcode") + 1).value == "457310272 614 8"
|
||||
assert ws.cell(row=2, column=target_cols.index("generated_barcode") + 1).value == "4573102726148"
|
||||
assert ws.cell(row=3, column=target_cols.index("item_name_jap") + 1).value == "A賞POTEPOTTEぬいぐるみ キュレネ"
|
||||
assert ws.cell(row=3, column=target_cols.index("item_name_eng") + 1).value == "GRADE A:Plush"
|
||||
assert ws.cell(row=3, column=target_cols.index("package_style") + 1).value == "A"
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Export-page blueprint proposal handoff tests."""
|
||||
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
|
||||
|
||||
|
||||
class _FakeConfig:
|
||||
def __init__(self, tmp_dir: Path):
|
||||
self.tmp_dir = tmp_dir
|
||||
|
||||
def get_tmp_blueprints_dir(self) -> Path:
|
||||
return self.tmp_dir
|
||||
|
||||
|
||||
def test_export_save_writes_temporary_proposal_not_type_config(tmp_path: Path):
|
||||
cm = _FakeConfig(tmp_path / "tmp_blueprints")
|
||||
blueprint = {
|
||||
"summaries": [],
|
||||
"groups": [],
|
||||
"mappings": [{"excel_column": "JAN", "sql_target": "generated_barcode", "confidence": 0.95, "reason": "operator confirmed"}],
|
||||
}
|
||||
|
||||
ref = save_export_blueprint_proposal(
|
||||
cm,
|
||||
blueprint=blueprint,
|
||||
proposal_name="New Prize Format",
|
||||
source_workbook_name="offer.xlsx",
|
||||
selected_type="kuji_tw",
|
||||
analysis_engine="hybrid",
|
||||
)
|
||||
|
||||
assert ref.path.parent == tmp_path / "tmp_blueprints"
|
||||
assert ref.path.exists()
|
||||
assert not (tmp_path / "types").exists()
|
||||
payload = load_blueprint_proposal(ref.path)
|
||||
assert payload["intended_action"] == "admin_review_required"
|
||||
assert payload["source_workbook_name"] == "offer.xlsx"
|
||||
assert payload["selected_type"] == "kuji_tw"
|
||||
assert payload["blueprint"]["mappings"][0]["sql_target"] == "generated_barcode"
|
||||
@@ -6,7 +6,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
from services.data_processor import ProcessedData, DroppedRow
|
||||
from services.export_models import ProcessedData, DroppedRow
|
||||
from services.export_service import ExportService
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Tests for schema-aware output field transforms."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.field_transformer import transform_field_value
|
||||
|
||||
|
||||
def test_generated_barcode_removes_all_whitespace():
|
||||
cm = ConfigManager()
|
||||
assert transform_field_value(cm, "generated_barcode", " 457310268 211 6 ") == "4573102682116"
|
||||
|
||||
|
||||
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"
|
||||
+24
-15
@@ -3,6 +3,7 @@ from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import yaml
|
||||
import pytest
|
||||
from services.config_manager import ConfigManager
|
||||
from services.fingerprint import Fingerprint, FingerprintMatch
|
||||
@@ -11,7 +12,7 @@ from services.excel_parser import ParsedWorkbook, ParsedSheet
|
||||
|
||||
@pytest.fixture
|
||||
def cm():
|
||||
return ConfigManager() # real project config - has 6 seed types
|
||||
return ConfigManager()
|
||||
|
||||
|
||||
def make_workbook(sheet_name, headers):
|
||||
@@ -32,7 +33,6 @@ class TestFingerprint:
|
||||
assert "SALES JAN CODE" in sig["Data"]
|
||||
|
||||
def test_recognize_scores_known_type_high(self, cm):
|
||||
# kuji_bna source_patterns include SALES JAN CODE, Product contents, ITEM SIZE
|
||||
wb = make_workbook("DISNEY", ["SALES JAN CODE", "Product contents", "ITEM SIZE", "Age Ratings"])
|
||||
fp = Fingerprint(cm)
|
||||
sig = fp.compute_signature(wb)
|
||||
@@ -42,16 +42,25 @@ class TestFingerprint:
|
||||
assert isinstance(best, FingerprintMatch)
|
||||
assert best.score > 0
|
||||
|
||||
def test_save_and_get_signature(self, cm, tmp_path, monkeypatch):
|
||||
fp = Fingerprint(cm)
|
||||
fake_path = tmp_path / "fingerprints.json"
|
||||
monkeypatch.setattr(fp, "cache_path", fake_path)
|
||||
sig = {"Data": ["A", "B", "C"]}
|
||||
fp.save("custom_format", sig)
|
||||
loaded = fp.get_saved("custom_format")
|
||||
assert loaded == sig
|
||||
|
||||
def test_get_saved_returns_none_when_missing(self, cm, tmp_path, monkeypatch):
|
||||
fp = Fingerprint(cm)
|
||||
monkeypatch.setattr(fp, "cache_path", tmp_path / "fingerprints.json")
|
||||
assert fp.get_saved("nonexistent") is None
|
||||
def test_recognize_uses_config_fingerprint_headers_not_runtime_cache(self, tmp_path):
|
||||
types_dir = tmp_path / "types"
|
||||
types_dir.mkdir(parents=True)
|
||||
(tmp_path / "settings.yaml").write_text("llm: {}\n", encoding="utf-8")
|
||||
cfg = {
|
||||
"type_id": "demo",
|
||||
"label": "Demo",
|
||||
"category": "test",
|
||||
"fingerprint_headers": ["Header A", "Header B"],
|
||||
"mapping": [{"source_patterns": ["Other"], "target": "generated_barcode"}],
|
||||
}
|
||||
(types_dir / "demo.yaml").write_text(
|
||||
yaml.dump(cfg, allow_unicode=True, sort_keys=False), encoding="utf-8"
|
||||
)
|
||||
# A legacy-looking cache file must not affect recognition.
|
||||
(tmp_path / "fingerprints.json").write_text(
|
||||
'{"demo": {"Data": ["Wrong Header"]}}', encoding="utf-8"
|
||||
)
|
||||
fp = Fingerprint(ConfigManager(config_dir=tmp_path))
|
||||
matches = fp.recognize({"Data": ["Header A", "Header B"]})
|
||||
assert matches[0].type_id == "demo"
|
||||
assert matches[0].score == 100.0
|
||||
@@ -5,7 +5,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import pytest
|
||||
from services.config_manager import ConfigManager
|
||||
from services.fuzzy_matcher import FuzzyMatcher, MatchResult, FormFieldMatch
|
||||
from services.fuzzy_matcher import FuzzyMatcher
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -63,33 +63,3 @@ class TestFuzzyMatcher:
|
||||
assert len(results) == 1
|
||||
assert results[0].matched_target == "jp_bai_launch"
|
||||
|
||||
def test_get_unmatched_targets(self, matcher):
|
||||
"""Unmatched targets should list DB columns with no source."""
|
||||
results = [
|
||||
MatchResult(source_header="A", matched_target="generated_barcode", confidence=95),
|
||||
MatchResult(source_header="B", matched_target="item_name_eng", confidence=90),
|
||||
]
|
||||
unmatched = matcher.get_unmatched_targets(results)
|
||||
assert "generated_barcode" not in unmatched
|
||||
assert "item_name_eng" not in unmatched
|
||||
assert "item_name_jap" in unmatched # not mapped
|
||||
|
||||
def test_auto_detect_type(self, matcher, config_manager):
|
||||
"""Auto-detect should find a kuji type from matching headers."""
|
||||
from services.excel_parser import ParsedWorkbook, ParsedSheet
|
||||
wb = ParsedWorkbook(file_name="test.xlsx")
|
||||
sheet = ParsedSheet(
|
||||
name="Data",
|
||||
rows=5, cols=4,
|
||||
header_row=1,
|
||||
data_start_row=2,
|
||||
data_end_row=5,
|
||||
detected_headers=["SALES JAN CODE", "Product contents", "ITEM SIZE", "Age Ratings"],
|
||||
raw_data=[["SALES JAN CODE", "Product contents", "ITEM SIZE", "Age Ratings"], ["123", "Item A", "10", "15"]],
|
||||
)
|
||||
wb.sheets.append(sheet)
|
||||
result = matcher.auto_detect_type(wb)
|
||||
# kuji_bna has keywords matching these headers (SALES, JAN, CODE, Product, etc.)
|
||||
assert result is not None
|
||||
assert "kuji" in result.lower()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Bilingual handover documentation tests."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
PROJECT = Path(__file__).resolve().parent.parent
|
||||
REQUIRED_DOCS = [
|
||||
"SPEC.md",
|
||||
"WORKFLOW.md",
|
||||
"BUSINESS_FLOW.md",
|
||||
"CONFIG.md",
|
||||
"OPERATIONS.md",
|
||||
"TROUBLESHOOTING.md",
|
||||
"DEPLOYMENT.md",
|
||||
"DATA_DICTIONARY.md",
|
||||
]
|
||||
|
||||
|
||||
def test_bilingual_handover_docs_exist_with_required_sections():
|
||||
for name in REQUIRED_DOCS:
|
||||
path = PROJECT / "docs" / name
|
||||
assert path.exists(), f"missing {name}"
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert "## English" in text
|
||||
assert "## 繁體中文" in text
|
||||
assert "Admin" in text or "管理員" in text
|
||||
|
||||
|
||||
def test_retired_split_language_docs_are_removed():
|
||||
assert not (PROJECT / "docs" / "SPEC_CHT.md").exists()
|
||||
assert not (PROJECT / "docs" / "WORKFLOW_CHT.md").exists()
|
||||
|
||||
|
||||
def test_data_dictionary_matches_db_schema_stub():
|
||||
schema = yaml.safe_load((PROJECT / "config" / "db_schema.yaml").read_text(encoding="utf-8"))
|
||||
doc = (PROJECT / "docs" / "DATA_DICTIONARY.md").read_text(encoding="utf-8")
|
||||
assert schema["table"] in doc
|
||||
for column in schema["columns"]:
|
||||
assert f"`{column['name']}`" in doc
|
||||
assert column["type"] in doc
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Tests for learned Match Blueprint → reusable type config conversion."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from services.learned_blueprint import (
|
||||
build_blueprint_summary,
|
||||
build_learned_type_config,
|
||||
dump_learned_type_yaml,
|
||||
slugify_type_id,
|
||||
)
|
||||
from services.llm_stages import ColumnMapping, MergeGroup, MergeLink, SheetSummary
|
||||
|
||||
|
||||
def make_blueprint():
|
||||
return {
|
||||
"summaries": [
|
||||
SheetSummary(
|
||||
sheet_name="DISNEY",
|
||||
header_row=1,
|
||||
sheet_type="detail",
|
||||
columns=[{"header": "STYLE"}, {"header": "Product contents"}],
|
||||
shared_values=[{"label": "SALES JAN CODE", "value": "123"}],
|
||||
),
|
||||
SheetSummary(
|
||||
sheet_name="Item detail",
|
||||
header_row=1,
|
||||
sheet_type="definition",
|
||||
columns=[{"header": "商品名/英語"}],
|
||||
shared_values=[],
|
||||
),
|
||||
],
|
||||
"groups": [
|
||||
MergeGroup(
|
||||
sheets=["DISNEY", "Item detail"],
|
||||
master_sheet="DISNEY",
|
||||
master_reason="STYLE is the output row key",
|
||||
links=[
|
||||
MergeLink(
|
||||
from_sheet="Item detail",
|
||||
from_column="商品名/英語",
|
||||
to_sheet="DISNEY",
|
||||
to_column="STYLE",
|
||||
key_pattern="grade letters",
|
||||
match_strategy="value_token",
|
||||
confidence=0.88,
|
||||
reason="same grade token",
|
||||
)
|
||||
],
|
||||
)
|
||||
],
|
||||
"mappings": [
|
||||
ColumnMapping("STYLE", "package_style", 0.95, "style code"),
|
||||
ColumnMapping("Product contents", "item_name_eng", 0.88, "english name"),
|
||||
ColumnMapping("SALES JAN CODE", "generated_barcode", 1.0, "shared barcode"),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_slugify_type_id_is_safe_for_yaml_filename():
|
||||
assert slugify_type_id("My Format / BNA 2026") == "my_format_bna_2026"
|
||||
assert slugify_type_id(" ") == "learned_format"
|
||||
|
||||
|
||||
def test_build_blueprint_summary_counts_visible_bits():
|
||||
summary = build_blueprint_summary(make_blueprint())
|
||||
assert summary == {"sheets": 2, "links": 1, "mappings": 3}
|
||||
|
||||
|
||||
def test_build_learned_type_config_matches_existing_type_schema():
|
||||
cfg = build_learned_type_config("My Format", make_blueprint())
|
||||
|
||||
assert cfg["type_id"] == "my_format"
|
||||
assert cfg["category"] == "learned"
|
||||
assert cfg["structure"]["header_pattern"]["strategy"] == "max_keyword_match"
|
||||
assert "Product contents" in cfg["structure"]["header_pattern"]["keywords"]
|
||||
assert "fingerprint_headers" in cfg
|
||||
assert "STYLE" in cfg["fingerprint_headers"]
|
||||
assert "SALES JAN CODE" in cfg["fingerprint_headers"]
|
||||
|
||||
mapping = {entry["source_patterns"][0]: entry for entry in cfg["mapping"]}
|
||||
assert mapping["STYLE"]["target"] == "package_style"
|
||||
assert mapping["STYLE"]["required"] is True
|
||||
assert mapping["Product contents"]["target"] == "item_name_eng"
|
||||
|
||||
assert cfg["form_fields"] == [{
|
||||
"source_patterns": ["SALES JAN CODE"],
|
||||
"target": "generated_barcode",
|
||||
"propagate": True,
|
||||
}]
|
||||
|
||||
rel = cfg["sheet_relations"][0]
|
||||
assert rel["source"] == {"sheet_pattern": "DISNEY", "key_column": "STYLE"}
|
||||
assert rel["target"]["sheet_pattern"] == "Item detail"
|
||||
assert rel["target"]["match_rules"] == [{"column": "商品名/英語", "strategy": "token_match"}]
|
||||
|
||||
|
||||
def test_dump_learned_type_yaml_is_human_readable():
|
||||
text = dump_learned_type_yaml(build_learned_type_config("My Format", make_blueprint()))
|
||||
assert "type_id: my_format" in text
|
||||
assert "source_patterns:" in text
|
||||
assert "sheet_relations:" in text
|
||||
@@ -1,156 +0,0 @@
|
||||
"""Tests for LLMMatcher — HTTP mocked, never hits real server."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import json
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import pytest
|
||||
from services.config_manager import ConfigManager
|
||||
from services.llm_matcher import LLMMatcher, LLMColumnMatch, LLMRelation
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cm_enabled(monkeypatch):
|
||||
"""ConfigManager with LLM enabled + fake API key."""
|
||||
cm = ConfigManager()
|
||||
# Force enabled by patching get_llm_config
|
||||
real_cfg = cm.get_llm_config()
|
||||
real_cfg["enabled"] = True
|
||||
real_cfg["base_url"] = "https://fake.local/v1"
|
||||
monkeypatch.setattr(cm, "get_llm_config", lambda: real_cfg)
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
monkeypatch.setattr(cm, "get_llm_api_key", lambda: "sk-fake")
|
||||
return cm
|
||||
|
||||
|
||||
def _mock_response(payload: dict):
|
||||
"""Build a fake requests.Response object."""
|
||||
class FakeResp:
|
||||
def __init__(self, data):
|
||||
self.status_code = 200
|
||||
self._data = data
|
||||
def json(self):
|
||||
return self._data
|
||||
@property
|
||||
def text(self):
|
||||
return json.dumps(self._data)
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
return FakeResp(payload)
|
||||
|
||||
|
||||
class TestMatchColumns:
|
||||
def test_returns_matches_when_api_ok(self, cm_enabled, monkeypatch):
|
||||
api_reply = {
|
||||
"choices": [{"message": {"content": json.dumps({
|
||||
"matches": [
|
||||
{"source": "商品名/英語", "target": "item_name_eng", "confidence": 0.95, "reason": "英文商品名"},
|
||||
{"source": "STYLE", "target": "package_style", "confidence": 0.80, "reason": "款式代碼"}
|
||||
]
|
||||
})}}]
|
||||
}
|
||||
captured = {}
|
||||
def fake_post(url, **kwargs):
|
||||
captured["url"] = url
|
||||
captured["kwargs"] = kwargs
|
||||
return _mock_response(api_reply)
|
||||
monkeypatch.setattr("services.llm_matcher.requests.post", fake_post)
|
||||
|
||||
matcher = LLMMatcher(cm_enabled)
|
||||
result = matcher.match_columns(
|
||||
source_columns=[
|
||||
{"header": "商品名/英語", "samples": ["GRADE A:Figure", "GRADE B:Figure"]},
|
||||
{"header": "STYLE", "samples": ["A", "B"]},
|
||||
],
|
||||
target_columns=[
|
||||
{"name": "item_name_eng", "description": "Item Name English"},
|
||||
{"name": "package_style", "description": "Package Style"},
|
||||
],
|
||||
)
|
||||
assert len(result) == 2
|
||||
assert isinstance(result[0], LLMColumnMatch)
|
||||
assert result[0].source_header == "商品名/英語"
|
||||
assert result[0].target == "item_name_eng"
|
||||
assert result[0].confidence == 0.95
|
||||
assert result[0].reason == "英文商品名"
|
||||
# Called the right endpoint
|
||||
assert "/chat/completions" in captured["url"]
|
||||
|
||||
def test_returns_empty_when_disabled(self, monkeypatch):
|
||||
cm = ConfigManager()
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: False)
|
||||
matcher = LLMMatcher(cm)
|
||||
result = matcher.match_columns(
|
||||
source_columns=[{"header": "X", "samples": []}],
|
||||
target_columns=[{"name": "y", "description": ""}],
|
||||
)
|
||||
assert result == []
|
||||
|
||||
def test_returns_empty_on_http_exception(self, cm_enabled, monkeypatch):
|
||||
def fake_post(url, **kwargs):
|
||||
raise ConnectionError("server down")
|
||||
monkeypatch.setattr("services.llm_matcher.requests.post", fake_post)
|
||||
matcher = LLMMatcher(cm_enabled)
|
||||
result = matcher.match_columns(
|
||||
source_columns=[{"header": "X", "samples": []}],
|
||||
target_columns=[{"name": "y", "description": ""}],
|
||||
)
|
||||
assert result == [] # graceful fallback, no raise
|
||||
|
||||
def test_returns_empty_on_non_json_content(self, cm_enabled, monkeypatch):
|
||||
api_reply = {"choices": [{"message": {"content": "I cannot do that"}}]}
|
||||
monkeypatch.setattr("services.llm_matcher.requests.post",
|
||||
lambda url, **kw: _mock_response(api_reply))
|
||||
matcher = LLMMatcher(cm_enabled)
|
||||
result = matcher.match_columns(
|
||||
source_columns=[{"header": "X", "samples": []}],
|
||||
target_columns=[{"name": "y", "description": ""}],
|
||||
)
|
||||
assert result == []
|
||||
|
||||
def test_skips_matches_with_unknown_target(self, cm_enabled, monkeypatch):
|
||||
api_reply = {"choices": [{"message": {"content": json.dumps({
|
||||
"matches": [
|
||||
{"source": "X", "target": "item_name_eng", "confidence": 0.9, "reason": "ok"},
|
||||
{"source": "Y", "target": "not_a_real_column", "confidence": 0.9, "reason": "bad"},
|
||||
]
|
||||
})}}]}
|
||||
monkeypatch.setattr("services.llm_matcher.requests.post",
|
||||
lambda url, **kw: _mock_response(api_reply))
|
||||
matcher = LLMMatcher(cm_enabled)
|
||||
result = matcher.match_columns(
|
||||
source_columns=[{"header": "X", "samples": []}, {"header": "Y", "samples": []}],
|
||||
target_columns=[{"name": "item_name_eng", "description": ""}],
|
||||
)
|
||||
assert len(result) == 1 # unknown target dropped
|
||||
assert result[0].target == "item_name_eng"
|
||||
|
||||
|
||||
class TestDetectRelations:
|
||||
def test_detects_cross_sheet_relation(self, cm_enabled, monkeypatch):
|
||||
api_reply = {"choices": [{"message": {"content": json.dumps({
|
||||
"relations": [
|
||||
{"source_sheet": "DISNEY", "source_column": "STYLE",
|
||||
"target_sheet": "Item detail", "target_column": "商品名/日本語",
|
||||
"confidence": 0.85, "reason": "STYLE A/B/C 對應 A賞/B賞"}
|
||||
]
|
||||
})}}]}
|
||||
monkeypatch.setattr("services.llm_matcher.requests.post",
|
||||
lambda url, **kw: _mock_response(api_reply))
|
||||
matcher = LLMMatcher(cm_enabled)
|
||||
result = matcher.detect_relations(sheets_info=[
|
||||
{"name": "DISNEY", "columns": [{"header": "STYLE", "samples": ["A", "B"]}]},
|
||||
{"name": "Item detail", "columns": [{"header": "商品名/日本語", "samples": ["A賞", "B賞"]}]},
|
||||
])
|
||||
assert len(result) == 1
|
||||
assert isinstance(result[0], LLMRelation)
|
||||
assert result[0].source_column == "STYLE"
|
||||
assert result[0].target_column == "商品名/日本語"
|
||||
assert result[0].confidence == 0.85
|
||||
|
||||
def test_detect_relations_empty_when_only_one_sheet(self, cm_enabled):
|
||||
matcher = LLMMatcher(cm_enabled)
|
||||
result = matcher.detect_relations(sheets_info=[
|
||||
{"name": "Only", "columns": [{"header": "X", "samples": []}]}
|
||||
])
|
||||
assert result == [] # no relations possible with one sheet
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Tests for LLM prompt builders."""
|
||||
from __future__ import annotations
|
||||
|
||||
from services.llm_prompts import build_schema_mapping_prompt, build_validation_retry_prompt
|
||||
|
||||
|
||||
def test_schema_mapping_prompt_includes_type_support_notes_when_provided():
|
||||
prompt = build_schema_mapping_prompt(
|
||||
[{"header": "商品名/英語", "samples": ["GRADE A"]}],
|
||||
[{"name": "item_name_eng", "description": "English name"}],
|
||||
type_support_notes={
|
||||
"source_type": "kuji_tw",
|
||||
"notes": {
|
||||
"header_aliases": [{
|
||||
"sql_target": "item_name_eng",
|
||||
"preferred_headers": ["商品名/英語"],
|
||||
"reason": "Exact English name mapping",
|
||||
}],
|
||||
"join_hints": [],
|
||||
"mapping_guidance": [],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert "TYPE SUPPORT NOTES" in prompt
|
||||
assert "item_name_eng" in prompt
|
||||
assert "商品名/英語" in prompt
|
||||
|
||||
|
||||
def test_schema_mapping_prompt_omits_type_support_section_when_absent():
|
||||
prompt = build_schema_mapping_prompt(
|
||||
[{"header": "ITEM NAME", "samples": ["A"]}],
|
||||
[{"name": "item_name_eng", "description": "English name"}],
|
||||
)
|
||||
|
||||
assert "TYPE SUPPORT NOTES" not in prompt
|
||||
|
||||
|
||||
def test_schema_mapping_prompt_keeps_known_mappings_out_of_review_scope():
|
||||
prompt = build_schema_mapping_prompt(
|
||||
[
|
||||
{"header": "STYLE", "samples": ["A"]},
|
||||
{"header": "QTY(pcs)", "samples": ["1"]},
|
||||
],
|
||||
[
|
||||
{"name": "package_style", "description": "Style code"},
|
||||
{"name": "pcs_dp", "description": "Pieces per display"},
|
||||
],
|
||||
known_mappings=[{"excel": "STYLE", "sql": "package_style", "confidence": 1.0, "reason": "Known type"}],
|
||||
)
|
||||
|
||||
review_section = prompt.split("Available SQL target names not already filled:", 1)[0]
|
||||
target_section = prompt.split("Already-applied known exact mappings:", 1)[0]
|
||||
assert "Known exact mappings are authoritative" in prompt
|
||||
assert '"header": "QTY(pcs)"' in review_section
|
||||
assert '"header": "STYLE"' not in review_section
|
||||
assert '"pcs_dp"' in target_section
|
||||
assert '"package_style"' not in target_section
|
||||
assert "Do NOT repeat already-applied" in prompt
|
||||
|
||||
|
||||
def test_validation_retry_prompt_preserves_output_contract_tail_for_long_prompts():
|
||||
long_prompt = "HEAD" + ("x" * 6000) + "Return this exact JSON shape: {\"mapping\": [], \"conflicts\": []}"
|
||||
|
||||
retry = build_validation_retry_prompt(long_prompt, "<bad>", ["response must be a JSON object"])
|
||||
|
||||
assert "HEAD" in retry
|
||||
assert "[middle omitted for retry prompt]" in retry
|
||||
assert "Return this exact JSON shape" in retry
|
||||
assert '"conflicts"' in retry
|
||||
+344
-4
@@ -20,6 +20,15 @@ def cm_enabled(monkeypatch):
|
||||
monkeypatch.setattr(cm, "get_llm_config", lambda: real_cfg)
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
monkeypatch.setattr(cm, "get_llm_api_key", lambda: "sk-fake")
|
||||
monkeypatch.setattr(cm, "resolve_llm_connection_config", lambda: {
|
||||
"api_key": "sk-fake",
|
||||
"base_url": "https://fake.local/v1",
|
||||
"model": real_cfg.get("model", "deepseek-chat"),
|
||||
"timeout_seconds": real_cfg.get("timeout_seconds", 30),
|
||||
"temperature": real_cfg.get("temperature", 0.1),
|
||||
"ssl_verify": real_cfg.get("ssl_verify", True),
|
||||
"source": "project",
|
||||
})
|
||||
return cm
|
||||
|
||||
|
||||
@@ -33,7 +42,210 @@ def _mock_resp(payload):
|
||||
return R()
|
||||
|
||||
|
||||
def _mock_stream_resp(chunks):
|
||||
class R:
|
||||
status_code = 200
|
||||
@property
|
||||
def text(self):
|
||||
return "<streaming response>"
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
def iter_lines(self, decode_unicode=False):
|
||||
for chunk in chunks:
|
||||
payload = {"choices": [{"delta": {"content": chunk}}]}
|
||||
line = "data: " + json.dumps(payload)
|
||||
yield line if decode_unicode else line.encode("utf-8")
|
||||
done = "data: [DONE]"
|
||||
yield done if decode_unicode else done.encode("utf-8")
|
||||
return R()
|
||||
|
||||
|
||||
def test_extract_json_accepts_fenced_arrays_for_semantic_validation():
|
||||
parsed = LLMStages._extract_json('```json\n[{"Excel column":"STYLE","Target column":null}]\n```')
|
||||
|
||||
assert isinstance(parsed, list)
|
||||
assert parsed[0]["Excel column"] == "STYLE"
|
||||
|
||||
|
||||
class TestStage1:
|
||||
|
||||
def test_uses_effective_llm_connection_config(self, cm_enabled, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(cm_enabled, "resolve_llm_connection_config", lambda: {
|
||||
"api_key": "sk-effective",
|
||||
"base_url": "https://deepseek.example/v1",
|
||||
"model": "deepseek-v4-pro",
|
||||
"timeout_seconds": 9,
|
||||
"temperature": 0.2,
|
||||
"ssl_verify": True,
|
||||
"source": "project",
|
||||
})
|
||||
api_reply = {"choices": [{"message": {"content": json.dumps({
|
||||
"header_row": 1,
|
||||
"sheet_type": "detail",
|
||||
"columns": [],
|
||||
"shared_values": [],
|
||||
})}}]}
|
||||
|
||||
def fake_post(url, **kw):
|
||||
calls.append((url, kw))
|
||||
return _mock_resp(api_reply)
|
||||
|
||||
monkeypatch.setattr("services.llm_stages.requests.post", fake_post)
|
||||
summary = LLMStages(cm_enabled).stage1_read_sheet("S", [["a"]])
|
||||
|
||||
assert summary is not None
|
||||
assert calls[0][0] == "https://deepseek.example/v1/chat/completions"
|
||||
assert calls[0][1]["headers"]["Authorization"] == "Bearer sk-effective"
|
||||
assert calls[0][1]["json"]["model"] == "deepseek-v4-pro"
|
||||
assert calls[0][1]["json"]["temperature"] == 0.2
|
||||
assert calls[0][1]["timeout"] == 9
|
||||
|
||||
|
||||
def test_streams_openai_chunks_to_event_callback(self, cm_enabled, monkeypatch):
|
||||
calls = []
|
||||
events = []
|
||||
payload = json.dumps({
|
||||
"header_row": 1,
|
||||
"sheet_type": "detail",
|
||||
"columns": [{"header": "GL品番", "samples": ["SAP001"], "meaning": "sap"}],
|
||||
"shared_values": [],
|
||||
})
|
||||
|
||||
monkeypatch.setattr(cm_enabled, "resolve_llm_connection_config", lambda: {
|
||||
"api_key": "sk-effective",
|
||||
"base_url": "https://deepseek.example/v1",
|
||||
"model": "deepseek-v4-pro",
|
||||
"timeout_seconds": 9,
|
||||
"temperature": 0.2,
|
||||
"ssl_verify": True,
|
||||
"stream_response": True,
|
||||
"source": "project",
|
||||
})
|
||||
|
||||
def fake_post(url, **kw):
|
||||
calls.append((url, kw))
|
||||
return _mock_stream_resp([payload[:20], payload[20:]])
|
||||
|
||||
monkeypatch.setattr("services.llm_stages.requests.post", fake_post)
|
||||
summary = LLMStages(cm_enabled, event_callback=events.append).stage1_read_sheet(
|
||||
"Item detail", [["GL品番"], ["SAP001"]]
|
||||
)
|
||||
|
||||
assert summary is not None
|
||||
assert summary.columns[0]["header"] == "GL品番"
|
||||
assert calls[0][1]["json"]["stream"] is True
|
||||
assert calls[0][1]["stream"] is True
|
||||
assert any(e.get("kind") == "llm_stream" for e in events)
|
||||
assert any("Streaming completed" in e.get("title", "") for e in events)
|
||||
prompt_event = next(e for e in events if e.get("kind") == "prompt")
|
||||
stream_event = next(e for e in events if e.get("kind") == "llm_stream" and e.get("stream_text"))
|
||||
response_event = next(e for e in events if e.get("kind") == "model_response")
|
||||
validation_event = next(e for e in events if e.get("kind") == "validation_result")
|
||||
assert prompt_event["stage"] == "sheet_structure"
|
||||
assert prompt_event["stage_index"] == 1
|
||||
assert prompt_event["stage_total"] == 3
|
||||
assert 0 < prompt_event["percent"] < stream_event["percent"] < response_event["percent"] <= validation_event["percent"] <= 100
|
||||
|
||||
|
||||
def test_streaming_success_does_not_read_response_text_before_iterating_chunks(self, cm_enabled, monkeypatch):
|
||||
events = []
|
||||
payload = json.dumps({
|
||||
"header_row": 1,
|
||||
"sheet_type": "detail",
|
||||
"columns": [{"header": "GL品番", "samples": ["SAP001"], "meaning": "sap"}],
|
||||
"shared_values": [],
|
||||
})
|
||||
|
||||
monkeypatch.setattr(cm_enabled, "resolve_llm_connection_config", lambda: {
|
||||
"api_key": "sk-effective",
|
||||
"base_url": "https://deepseek.example/v1",
|
||||
"model": "deepseek-v4-pro",
|
||||
"timeout_seconds": 9,
|
||||
"temperature": 0.2,
|
||||
"ssl_verify": True,
|
||||
"stream_response": True,
|
||||
"source": "project",
|
||||
})
|
||||
|
||||
class StreamingResp:
|
||||
status_code = 200
|
||||
|
||||
@property
|
||||
def text(self):
|
||||
raise AssertionError("streaming success path must not read resp.text")
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
def iter_lines(self, decode_unicode=False):
|
||||
for chunk in [payload[:20], payload[20:]]:
|
||||
line = "data: " + json.dumps({"choices": [{"delta": {"content": chunk}}]})
|
||||
yield line if decode_unicode else line.encode("utf-8")
|
||||
done = "data: [DONE]"
|
||||
yield done if decode_unicode else done.encode("utf-8")
|
||||
|
||||
monkeypatch.setattr("services.llm_stages.requests.post", lambda url, **kw: StreamingResp())
|
||||
|
||||
summary = LLMStages(cm_enabled, event_callback=events.append).stage1_read_sheet(
|
||||
"Item detail", [["GL品番"], ["SAP001"]]
|
||||
)
|
||||
|
||||
assert summary is not None
|
||||
http_event = next(e for e in events if e.get("kind") == "llm_http")
|
||||
assert http_event["status_code"] == 200
|
||||
assert "response_preview" not in http_event
|
||||
|
||||
|
||||
def test_streaming_unavailable_falls_back_to_non_streaming_response(self, cm_enabled, monkeypatch):
|
||||
calls = []
|
||||
events = []
|
||||
payload = {
|
||||
"header_row": 1,
|
||||
"sheet_type": "detail",
|
||||
"columns": [{"header": "GL品番", "samples": ["SAP001"], "meaning": "sap"}],
|
||||
"shared_values": [],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(cm_enabled, "resolve_llm_connection_config", lambda: {
|
||||
"api_key": "sk-effective",
|
||||
"base_url": "https://deepseek.example/v1",
|
||||
"model": "deepseek-v4-pro",
|
||||
"timeout_seconds": 9,
|
||||
"temperature": 0.2,
|
||||
"ssl_verify": True,
|
||||
"stream_response": True,
|
||||
"source": "project",
|
||||
})
|
||||
|
||||
class StreamingUnsupported:
|
||||
status_code = 400
|
||||
text = "streaming unsupported"
|
||||
def raise_for_status(self):
|
||||
raise RuntimeError("streaming unsupported")
|
||||
def iter_lines(self, decode_unicode=False):
|
||||
return iter(())
|
||||
|
||||
def fake_post(url, **kw):
|
||||
calls.append((url, kw))
|
||||
if kw.get("stream") is True:
|
||||
return StreamingUnsupported()
|
||||
return _mock_resp({"choices": [{"message": {"content": json.dumps(payload)}}]})
|
||||
|
||||
monkeypatch.setattr("services.llm_stages.requests.post", fake_post)
|
||||
summary = LLMStages(cm_enabled, max_retries=0, event_callback=events.append).stage1_read_sheet(
|
||||
"Item detail", [["GL品番"], ["SAP001"]]
|
||||
)
|
||||
|
||||
assert summary is not None
|
||||
assert summary.columns[0]["header"] == "GL品番"
|
||||
assert len(calls) == 2
|
||||
assert calls[0][1]["json"]["stream"] is True
|
||||
assert calls[0][1]["stream"] is True
|
||||
assert calls[1][1].get("stream") is None
|
||||
assert "stream" not in calls[1][1]["json"]
|
||||
assert any("Streaming unavailable" in e.get("title", "") for e in events)
|
||||
|
||||
def test_reads_sheet_structure(self, cm_enabled, monkeypatch):
|
||||
api_reply = {"choices": [{"message": {"content": json.dumps({
|
||||
"header_row": 1,
|
||||
@@ -52,6 +264,71 @@ class TestStage1:
|
||||
assert summary.sheet_type == "detail"
|
||||
assert len(summary.columns) == 1
|
||||
|
||||
|
||||
def test_emits_visible_model_response_and_validation_result(self, cm_enabled, monkeypatch):
|
||||
events = []
|
||||
payload = {
|
||||
"header_row": 1,
|
||||
"sheet_type": "detail",
|
||||
"columns": [{"header": "GL品番", "samples": ["SAP001"], "meaning": "sap"}],
|
||||
"shared_values": [],
|
||||
}
|
||||
|
||||
monkeypatch.setattr("services.llm_stages.requests.post",
|
||||
lambda url, **kw: _mock_resp({"choices": [{"message": {"content": json.dumps(payload)}}]}))
|
||||
summary = LLMStages(cm_enabled, event_callback=events.append).stage1_read_sheet(
|
||||
"Item detail", [["GL品番"], ["SAP001"]]
|
||||
)
|
||||
|
||||
assert summary is not None
|
||||
response_events = [e for e in events if e.get("kind") == "model_response"]
|
||||
validation_events = [e for e in events if e.get("kind") == "validation_result"]
|
||||
assert response_events
|
||||
assert response_events[0]["label"] == "Stage 1 sheet 'Item detail'"
|
||||
assert "GL品番" in response_events[0]["content_preview"]
|
||||
assert validation_events
|
||||
assert validation_events[0]["validation_status"] == "passed"
|
||||
assert "GL品番" in validation_events[0]["normalized_preview"]
|
||||
|
||||
|
||||
def test_stage1_retries_with_validation_feedback_then_accepts_corrected_json(self, cm_enabled, monkeypatch):
|
||||
calls = []
|
||||
replies = [
|
||||
{"header_row": 99, "sheet_type": "cover", "columns": [{"header": "Invented", "samples": []}], "shared_values": []},
|
||||
{"header_row": 1, "sheet_type": "detail", "columns": [{"header": "GL品番", "samples": ["SAP001"], "meaning": "sap"}], "shared_values": []},
|
||||
]
|
||||
|
||||
def fake_post(url, **kw):
|
||||
calls.append(kw["json"]["messages"][0]["content"])
|
||||
return _mock_resp({"choices": [{"message": {"content": json.dumps(replies.pop(0))}}]})
|
||||
|
||||
monkeypatch.setattr("services.llm_stages.requests.post", fake_post)
|
||||
stages = LLMStages(cm_enabled, max_retries=1)
|
||||
summary = stages.stage1_read_sheet("Item detail", [["GL品番"], ["SAP001"]])
|
||||
|
||||
assert summary is not None
|
||||
assert summary.header_row == 1
|
||||
assert summary.columns[0]["header"] == "GL品番"
|
||||
assert len(calls) == 2
|
||||
assert "Your previous JSON was invalid" in calls[1]
|
||||
assert "header_row 99" in calls[1]
|
||||
assert "Invented" in calls[1]
|
||||
|
||||
def test_stage1_returns_none_after_validation_retry_fails(self, cm_enabled, monkeypatch):
|
||||
calls = []
|
||||
invalid = {"header_row": 99, "sheet_type": "cover", "columns": [{"header": "Invented", "samples": []}], "shared_values": []}
|
||||
|
||||
def fake_post(url, **kw):
|
||||
calls.append(kw["json"]["messages"][0]["content"])
|
||||
return _mock_resp({"choices": [{"message": {"content": json.dumps(invalid)}}]})
|
||||
|
||||
monkeypatch.setattr("services.llm_stages.requests.post", fake_post)
|
||||
stages = LLMStages(cm_enabled, max_retries=1)
|
||||
|
||||
assert stages.stage1_read_sheet("Item detail", [["GL品番"], ["SAP001"]]) is None
|
||||
assert len(calls) == 2
|
||||
assert "Your previous JSON was invalid" in calls[1]
|
||||
|
||||
def test_returns_none_on_http_failure(self, cm_enabled, monkeypatch):
|
||||
def boom(url, **kw):
|
||||
raise ConnectionError("down")
|
||||
@@ -93,14 +370,40 @@ class TestStage2:
|
||||
monkeypatch.setattr("services.llm_stages.requests.post",
|
||||
lambda url, **kw: _mock_resp(api_reply))
|
||||
stages = LLMStages(cm_enabled)
|
||||
summaries = [SheetSummary("DISNEY", 1, "definition", [], []),
|
||||
SheetSummary("Item detail", 1, "detail", [], [])]
|
||||
summaries = [
|
||||
SheetSummary("DISNEY", 1, "definition", [{"header": "STYLE"}], []),
|
||||
SheetSummary("Item detail", 1, "detail", [{"header": "商品名"}], []),
|
||||
]
|
||||
groups = stages.stage2_find_links(summaries)
|
||||
assert len(groups) == 1
|
||||
assert isinstance(groups[0], MergeGroup)
|
||||
assert groups[0].master_sheet == "Item detail"
|
||||
assert groups[0].links[0].match_strategy == "value_token"
|
||||
|
||||
def test_stage2_rejects_invented_sheet_and_column(self, cm_enabled, monkeypatch):
|
||||
api_reply = {"choices": [{"message": {"content": json.dumps({
|
||||
"groups": [{
|
||||
"sheets": ["Invented"],
|
||||
"master_sheet": "Invented",
|
||||
"master_reason": "guess",
|
||||
"links": [{
|
||||
"from_sheet": "DISNEY", "from_column": "Invented",
|
||||
"to_sheet": "Item detail", "to_column": "商品名",
|
||||
"key_pattern": "guess", "match_strategy": "magic",
|
||||
"confidence": 2, "reason": "guess"
|
||||
}]
|
||||
}]
|
||||
})}}]}
|
||||
monkeypatch.setattr("services.llm_stages.requests.post",
|
||||
lambda url, **kw: _mock_resp(api_reply))
|
||||
stages = LLMStages(cm_enabled, max_retries=0)
|
||||
summaries = [
|
||||
SheetSummary("DISNEY", 1, "definition", [{"header": "STYLE"}], []),
|
||||
SheetSummary("Item detail", 1, "detail", [{"header": "商品名"}], []),
|
||||
]
|
||||
|
||||
assert stages.stage2_find_links(summaries) == []
|
||||
|
||||
def test_single_sheet_no_groups(self, cm_enabled):
|
||||
stages = LLMStages(cm_enabled)
|
||||
summaries = [SheetSummary("Only", 1, "detail", [], [])]
|
||||
@@ -128,7 +431,43 @@ class TestStage3:
|
||||
assert mappings[0].excel_column == "商品名/英語"
|
||||
assert mappings[0].sql_target == "item_name_eng"
|
||||
|
||||
def test_drops_unknown_sql_target(self, cm_enabled, monkeypatch):
|
||||
def test_stage3_retries_with_validation_feedback_then_accepts_corrected_mapping(self, cm_enabled, monkeypatch):
|
||||
calls = []
|
||||
replies = [
|
||||
{"mapping": [{"excel": "Invented Excel", "sql": "not_real", "confidence": 3, "reason": "guess"}]},
|
||||
{"mapping": [{"excel": "GL品番", "sql": "sap", "confidence": 0.94, "reason": "grounded"}]},
|
||||
]
|
||||
|
||||
def fake_post(url, **kw):
|
||||
calls.append(kw["json"]["messages"][0]["content"])
|
||||
return _mock_resp({"choices": [{"message": {"content": json.dumps(replies.pop(0))}}]})
|
||||
|
||||
monkeypatch.setattr("services.llm_stages.requests.post", fake_post)
|
||||
stages = LLMStages(cm_enabled, max_retries=1)
|
||||
summaries = [SheetSummary("S", 1, "detail", [{"header": "GL品番"}], [])]
|
||||
schema = [{"name": "sap", "description": ""}]
|
||||
|
||||
mappings = stages.stage3_map_columns(summaries, [], schema)
|
||||
|
||||
assert len(mappings) == 1
|
||||
assert mappings[0].excel_column == "GL品番"
|
||||
assert mappings[0].sql_target == "sap"
|
||||
assert len(calls) == 2
|
||||
assert "Your previous JSON was invalid" in calls[1]
|
||||
assert "Invented Excel" in calls[1]
|
||||
assert "not_real" in calls[1]
|
||||
|
||||
def test_stage3_returns_empty_when_validation_retry_fails(self, cm_enabled, monkeypatch):
|
||||
invalid = {"mapping": [{"excel": "Invented Excel", "sql": "not_real", "confidence": 3, "reason": "guess"}]}
|
||||
monkeypatch.setattr("services.llm_stages.requests.post",
|
||||
lambda url, **kw: _mock_resp({"choices": [{"message": {"content": json.dumps(invalid)}}]}))
|
||||
stages = LLMStages(cm_enabled, max_retries=1)
|
||||
summaries = [SheetSummary("S", 1, "detail", [{"header": "GL品番"}], [])]
|
||||
schema = [{"name": "sap", "description": ""}]
|
||||
|
||||
assert stages.stage3_map_columns(summaries, [], schema) == []
|
||||
|
||||
def test_salvages_valid_rows_when_one_mapping_has_unknown_sql_target(self, cm_enabled, monkeypatch):
|
||||
api_reply = {"choices": [{"message": {"content": json.dumps({
|
||||
"mapping": [
|
||||
{"excel": "X", "sql": "item_name_eng", "confidence": 0.9, "reason": ""},
|
||||
@@ -137,10 +476,11 @@ class TestStage3:
|
||||
})}}]}
|
||||
monkeypatch.setattr("services.llm_stages.requests.post",
|
||||
lambda url, **kw: _mock_resp(api_reply))
|
||||
stages = LLMStages(cm_enabled)
|
||||
stages = LLMStages(cm_enabled, max_retries=0)
|
||||
schema = [{"name": "item_name_eng", "description": ""}]
|
||||
mappings = stages.stage3_map_columns(
|
||||
[SheetSummary("S", 1, "detail", [{"header": "X"}, {"header": "Y"}], [])],
|
||||
[], schema)
|
||||
assert len(mappings) == 1
|
||||
assert mappings[0].excel_column == "X"
|
||||
assert mappings[0].sql_target == "item_name_eng"
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Tests for semantic validation of LLM stage outputs."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from services.llm_stages import SheetSummary
|
||||
from services.llm_validation import (
|
||||
validate_sheet_structure,
|
||||
validate_sheet_links,
|
||||
validate_schema_mapping,
|
||||
)
|
||||
|
||||
|
||||
def test_validate_sheet_structure_accepts_grounded_output():
|
||||
raw_rows = [["Title"], ["GL品番", "Material"], ["SAP001", "PVC"]]
|
||||
data = {
|
||||
"header_row": 2,
|
||||
"sheet_type": "detail",
|
||||
"columns": [
|
||||
{"header": "GL品番", "samples": ["SAP001"], "meaning": "SAP item"},
|
||||
{"header": "Material", "samples": ["PVC"], "meaning": "material"},
|
||||
],
|
||||
"shared_values": [{"label": "Title", "value": "Example"}],
|
||||
}
|
||||
|
||||
result = validate_sheet_structure("Item detail", raw_rows, data)
|
||||
|
||||
assert result.valid is True
|
||||
assert result.data["header_row"] == 2
|
||||
assert result.data["sheet_type"] == "detail"
|
||||
assert result.errors == []
|
||||
|
||||
|
||||
def test_validate_sheet_structure_rejects_invented_row_type_and_header():
|
||||
raw_rows = [["GL品番", "Material"], ["SAP001", "PVC"]]
|
||||
data = {
|
||||
"header_row": 99,
|
||||
"sheet_type": "cover",
|
||||
"columns": [{"header": "Invented Column", "samples": [], "meaning": ""}],
|
||||
"shared_values": [],
|
||||
}
|
||||
|
||||
result = validate_sheet_structure("Item detail", raw_rows, data)
|
||||
|
||||
assert result.valid is False
|
||||
assert any("header_row" in e and "outside" in e for e in result.errors)
|
||||
assert any("sheet_type" in e for e in result.errors)
|
||||
assert any("Invented Column" in e for e in result.errors)
|
||||
|
||||
|
||||
def test_validate_sheet_links_rejects_invented_sheet_column_strategy_and_confidence():
|
||||
summaries = [
|
||||
SheetSummary("Item detail", 2, "detail", [{"header": "GL品番"}], []),
|
||||
SheetSummary("Product", 1, "definition", [{"header": "STYLE"}], []),
|
||||
]
|
||||
data = {
|
||||
"groups": [{
|
||||
"sheets": ["Item detail", "Invented Sheet"],
|
||||
"master_sheet": "Invented Sheet",
|
||||
"master_reason": "guess",
|
||||
"links": [{
|
||||
"from_sheet": "Product",
|
||||
"from_column": "Invented Column",
|
||||
"to_sheet": "Item detail",
|
||||
"to_column": "GL品番",
|
||||
"key_pattern": "guess",
|
||||
"match_strategy": "magic",
|
||||
"confidence": 3,
|
||||
"reason": "guess",
|
||||
}],
|
||||
}]
|
||||
}
|
||||
|
||||
result = validate_sheet_links(summaries, data)
|
||||
|
||||
assert result.valid is False
|
||||
assert any("Invented Sheet" in e for e in result.errors)
|
||||
assert any("Invented Column" in e for e in result.errors)
|
||||
assert any("match_strategy" in e for e in result.errors)
|
||||
assert any("confidence" in e for e in result.errors)
|
||||
|
||||
|
||||
def test_validate_schema_mapping_rejects_invented_excel_sql_and_confidence():
|
||||
summaries = [SheetSummary("S", 1, "detail", [{"header": "GL品番"}], [])]
|
||||
schema = [{"name": "sap", "description": "SAP item number"}]
|
||||
data = {
|
||||
"mapping": [
|
||||
{"excel": "Invented Excel", "sql": "not_real", "confidence": -0.1, "reason": "guess"}
|
||||
]
|
||||
}
|
||||
|
||||
result = validate_schema_mapping(summaries, schema, data)
|
||||
|
||||
assert result.valid is False
|
||||
assert any("Invented Excel" in e for e in result.errors)
|
||||
assert any("not_real" in e for e in result.errors)
|
||||
assert any("confidence" in e for e in result.errors)
|
||||
|
||||
|
||||
def test_validate_schema_mapping_accepts_known_excel_and_sql():
|
||||
summaries = [SheetSummary("S", 1, "detail", [{"header": "GL品番"}], [])]
|
||||
schema = [{"name": "sap", "description": "SAP item number"}]
|
||||
data = {"mapping": [{"excel": "GL品番", "sql": "sap", "confidence": 0.94, "reason": "exact meaning"}]}
|
||||
|
||||
result = validate_schema_mapping(summaries, schema, data)
|
||||
|
||||
assert result.valid is True
|
||||
assert result.data["mapping"][0]["excel"] == "GL品番"
|
||||
assert result.data["mapping"][0]["sql"] == "sap"
|
||||
|
||||
|
||||
def test_validate_schema_mapping_normalizes_unambiguous_excel_width_variants():
|
||||
summaries = [SheetSummary("S", 1, "detail", [{"header": "QTY(pcs)"}], [])]
|
||||
schema = [{"name": "pcs_dp", "description": "Pieces per display/product"}]
|
||||
data = {"mapping": [{"excel": "QTY(pcs)", "sql": "pcs_dp", "confidence": 1.0, "reason": "same header punctuation"}]}
|
||||
|
||||
result = validate_schema_mapping(summaries, schema, data)
|
||||
|
||||
assert result.valid is True
|
||||
assert result.errors == []
|
||||
assert result.data["mapping"] == [
|
||||
{"excel": "QTY(pcs)", "sql": "pcs_dp", "confidence": 1.0, "reason": "same header punctuation"}
|
||||
]
|
||||
@@ -1,105 +0,0 @@
|
||||
"""Tests for MatchingService orchestrator (LLM primary, fuzzy fallback)."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import pytest
|
||||
from services.config_manager import ConfigManager
|
||||
from services.matching_service import MatchingService
|
||||
from services.excel_parser import ParsedWorkbook, ParsedSheet
|
||||
from services.llm_matcher import LLMColumnMatch
|
||||
|
||||
|
||||
def make_workbook(headers, rows):
|
||||
wb = ParsedWorkbook(file_name="t.xlsx")
|
||||
wb.sheets.append(ParsedSheet(
|
||||
name="S", rows=len(headers)+len(rows), cols=len(headers),
|
||||
header_row=1, data_start_row=2, data_end_row=1+len(rows),
|
||||
detected_headers=headers, raw_data=[list(headers)] + [list(r) for r in rows]))
|
||||
return wb
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cm():
|
||||
return ConfigManager()
|
||||
|
||||
|
||||
class TestMatchingService:
|
||||
def test_uses_llm_results_when_available(self, cm, monkeypatch):
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
svc = MatchingService(cm)
|
||||
monkeypatch.setattr(svc.llm, "generate_config", lambda src, tgt, sheets: None) # skip config gen
|
||||
monkeypatch.setattr(svc.llm, "match_columns", lambda src, tgt: [
|
||||
LLMColumnMatch("商品名/英語", "item_name_eng", 0.95, "英文商品名"),
|
||||
])
|
||||
monkeypatch.setattr(svc.llm, "detect_relations", lambda sheets: [])
|
||||
wb = make_workbook(["商品名/英語"], [["GRADE A:Figure"]])
|
||||
results = svc.match(wb, type_id=None)
|
||||
assert len(results) >= 1
|
||||
eng = [r for r in results if r.source_header == "商品名/英語"][0]
|
||||
assert eng.matched_target == "item_name_eng"
|
||||
assert eng.engine == "llm"
|
||||
assert eng.confidence == 95.0 # 0.95 * 100
|
||||
assert eng.reason == "英文商品名"
|
||||
|
||||
def test_falls_back_to_fuzzy_when_llm_returns_empty(self, cm, monkeypatch):
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
svc = MatchingService(cm)
|
||||
monkeypatch.setattr(svc.llm, "generate_config", lambda src, tgt, sheets: None) # skip config gen
|
||||
monkeypatch.setattr(svc.llm, "match_columns", lambda src, tgt: [])
|
||||
monkeypatch.setattr(svc.llm, "detect_relations", lambda sheets: [])
|
||||
wb = make_workbook(["SALES JAN CODE"], [["123"]])
|
||||
results = svc.match(wb, type_id="kuji_bna")
|
||||
matched = [r for r in results if r.matched_target]
|
||||
assert len(matched) >= 1
|
||||
assert all(r.engine == "fuzzy" for r in matched)
|
||||
|
||||
def test_falls_back_to_fuzzy_when_llm_disabled(self, cm, monkeypatch):
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: False)
|
||||
svc = MatchingService(cm)
|
||||
wb = make_workbook(["SALES JAN CODE"], [["123"]])
|
||||
results = svc.match(wb, type_id="kuji_bna")
|
||||
matched = [r for r in results if r.matched_target]
|
||||
assert len(matched) >= 1
|
||||
assert all(r.engine == "fuzzy" for r in matched)
|
||||
|
||||
def test_uses_generated_config_when_available(self, cm, monkeypatch):
|
||||
"""When generate_config returns a full config, its mappings are used."""
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
svc = MatchingService(cm)
|
||||
monkeypatch.setattr(svc.llm, "generate_config", lambda src, tgt, sheets: {
|
||||
"mapping": [
|
||||
{"source_patterns": ["商品名/英語"], "target": "item_name_eng"},
|
||||
{"source_patterns": ["STYLE"], "target": "package_style"},
|
||||
],
|
||||
"sheet_relations": [
|
||||
{"source_sheet": "D", "source_key": "STYLE",
|
||||
"target_sheet": "I", "target_column": "商品名/日本語",
|
||||
"match_strategy": "prefix", "join_type": "lookup",
|
||||
"reason": "grades match"},
|
||||
],
|
||||
"form_fields": [],
|
||||
"structure_keywords": ["SALES"],
|
||||
"analysis": "a kuji type variant",
|
||||
})
|
||||
wb = make_workbook(["商品名/英語", "STYLE"], [["GRADE A:Figure", "A"]])
|
||||
results = svc.match(wb)
|
||||
matched = [r for r in results if r.matched_target]
|
||||
assert len(matched) == 2
|
||||
assert matched[0].engine == "llm"
|
||||
assert matched[0].reason == "a kuji type variant"
|
||||
# Relations should come from generated config, not LLM detect
|
||||
rels = svc.detect_relations(wb)
|
||||
assert len(rels) == 1
|
||||
assert rels[0].reason == "grades match"
|
||||
|
||||
def test_detect_relations_delegates_to_llm(self, cm, monkeypatch):
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
svc = MatchingService(cm)
|
||||
from services.llm_matcher import LLMRelation
|
||||
stub = [LLMRelation("DISNEY", "STYLE", "Item detail", "商品名/日本語", 0.85, "r")]
|
||||
monkeypatch.setattr(svc.llm, "detect_relations", lambda sheets: stub)
|
||||
wb = make_workbook(["STYLE"], [["A"]])
|
||||
rels = svc.detect_relations(wb)
|
||||
assert len(rels) == 1
|
||||
assert rels[0].source_column == "STYLE"
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Static guards that keep the retired pipeline from returning."""
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PROJECT = Path(__file__).resolve().parent.parent
|
||||
RUNTIME_DIRS = (PROJECT / "app.py", PROJECT / "ui", PROJECT / "services")
|
||||
RETIRED_MARKERS = (
|
||||
"preview_page_v2",
|
||||
"export_page_v2",
|
||||
"services.data_processor",
|
||||
"services.matching_service",
|
||||
"services.llm_matcher",
|
||||
"services.value_matcher",
|
||||
"ui.i18n",
|
||||
"use_container_width",
|
||||
)
|
||||
|
||||
|
||||
def _runtime_python() -> str:
|
||||
files = [RUNTIME_DIRS[0]]
|
||||
for directory in RUNTIME_DIRS[1:]:
|
||||
files.extend(directory.glob("*.py"))
|
||||
return "\n".join(path.read_text(encoding="utf-8") for path in files)
|
||||
|
||||
|
||||
def test_runtime_has_no_retired_imports_or_apis():
|
||||
source = _runtime_python()
|
||||
for marker in RETIRED_MARKERS:
|
||||
assert marker not in source
|
||||
|
||||
|
||||
def test_retired_modules_are_absent():
|
||||
retired = (
|
||||
"ui/structure_review.py",
|
||||
"ui/mapping_review.py",
|
||||
"ui/cross_sheet_page.py",
|
||||
"ui/data_preview.py",
|
||||
"services/data_processor.py",
|
||||
"services/matching_service.py",
|
||||
"services/llm_matcher.py",
|
||||
"services/value_matcher.py",
|
||||
)
|
||||
assert all(not (PROJECT / relative).exists() for relative in retired)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Tests for simplified Review-stage helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
from services.excel_parser import ParsedSheet
|
||||
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.workbook_analyzer import AnalysisResult
|
||||
from ui.confirm_page import (
|
||||
_build_mapping_editor_rows,
|
||||
_build_sheet_cursor_preview,
|
||||
_operator_alert_warnings,
|
||||
build_ai_recommendation,
|
||||
)
|
||||
from ui.preview_page import resolve_preview_back_step
|
||||
|
||||
|
||||
def test_apply_header_row_override_rebuilds_headers_and_data_start():
|
||||
sheet = ParsedSheet(
|
||||
name="Items",
|
||||
rows=4,
|
||||
cols=3,
|
||||
header_row=1,
|
||||
data_start_row=2,
|
||||
data_end_row=4,
|
||||
raw_data=[
|
||||
["Report title", None, None],
|
||||
["STYLE", "JAN", "NAME"],
|
||||
["A", "123", "Prize A"],
|
||||
["B", "456", "Prize B"],
|
||||
],
|
||||
detected_headers=["Report title", "", ""],
|
||||
col_headers={0: "Report title"},
|
||||
)
|
||||
|
||||
updated = apply_header_row_override(sheet, 2)
|
||||
|
||||
assert updated.header_row == 2
|
||||
assert updated.data_start_row == 3
|
||||
assert updated.detected_headers == ["STYLE", "JAN", "NAME"]
|
||||
assert updated.col_headers == {0: "STYLE", 1: "JAN", 2: "NAME"}
|
||||
|
||||
|
||||
def test_header_cursor_preview_marks_selected_dataframe_row():
|
||||
sheet = ParsedSheet(
|
||||
name="Items",
|
||||
rows=4,
|
||||
cols=3,
|
||||
header_row=2,
|
||||
data_start_row=3,
|
||||
data_end_row=4,
|
||||
raw_data=[
|
||||
["Report title", None, None],
|
||||
["STYLE", "JAN", "NAME"],
|
||||
["A", "123", "Prize A"],
|
||||
["B", "456", "Prize B"],
|
||||
],
|
||||
)
|
||||
|
||||
preview = _build_sheet_cursor_preview(sheet, 2, window_before=1, window_after=1)
|
||||
|
||||
assert preview["Row"].tolist() == [1, 2, 3]
|
||||
assert preview.loc[1, "Cursor"] == "▶ Header"
|
||||
assert preview.loc[1, "A"] == "STYLE"
|
||||
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"},
|
||||
)
|
||||
|
||||
assert rows == [
|
||||
{"Excel Column": "STYLE", "Database Column": "package_name"},
|
||||
{"Excel Column": "JAN", "Database Column": "generated_barcode"},
|
||||
]
|
||||
|
||||
|
||||
def test_known_format_fallback_note_is_not_operator_alert():
|
||||
warnings = [
|
||||
"Using known format 'KUJI TW' as fallback",
|
||||
"Stage 1 failed for every sheet",
|
||||
]
|
||||
|
||||
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")],
|
||||
engine="yaml",
|
||||
)
|
||||
|
||||
updated = build_column_mapping_result(
|
||||
original,
|
||||
{"STYLE": "package_name", "JAN": "generated_barcode", "IGNORE ME": ""},
|
||||
)
|
||||
|
||||
assert [(m.excel_column, m.sql_target) for m in updated.mappings] == [
|
||||
("STYLE", "package_name"),
|
||||
("JAN", "generated_barcode"),
|
||||
]
|
||||
assert updated.engine == "manual"
|
||||
|
||||
|
||||
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"},
|
||||
{"generated_barcode": "subtotal", "item_name_eng": "", "package_size": ""},
|
||||
{"generated_barcode": "222", "item_name_eng": "Prize B", "package_size": "L"},
|
||||
]
|
||||
|
||||
result = split_rows_by_quality(rows, key_columns=["generated_barcode"], restore_indexes={1})
|
||||
|
||||
assert [r.index for r in result.dropped] == [1]
|
||||
assert "Only 1 populated field" in result.dropped[0].reason
|
||||
assert [r.index for r in result.export_rows] == [0, 1, 2]
|
||||
|
||||
|
||||
def test_build_ai_recommendation_only_suggests_ai_when_basic_review_needs_help():
|
||||
strong = AnalysisResult(mappings=[ColumnMapping("JAN", "generated_barcode", 0.95, "Exact")])
|
||||
weak = AnalysisResult(warnings=["No mapping found"])
|
||||
|
||||
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
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Admin password hashing and verification tests."""
|
||||
from __future__ import annotations
|
||||
|
||||
from services.security import hash_password, verify_password, is_configured_hash
|
||||
|
||||
|
||||
def test_hash_password_round_trip_and_rejects_wrong_password():
|
||||
encoded = hash_password("correct horse battery staple", salt=b"fixed-salt-for-test", iterations=1200)
|
||||
assert encoded.startswith("pbkdf2_sha256$1200$")
|
||||
assert "correct" not in encoded
|
||||
assert verify_password("correct horse battery staple", encoded)
|
||||
assert not verify_password("wrong", encoded)
|
||||
|
||||
|
||||
def test_blank_or_malformed_hash_is_not_configured_and_never_verifies():
|
||||
assert not is_configured_hash("")
|
||||
assert not is_configured_hash("not-a-real-hash")
|
||||
assert not verify_password("anything", "")
|
||||
assert not verify_password("anything", "not-a-real-hash")
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Safety checks for runtime settings and template config."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
PROJECT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def test_settings_example_exists_and_is_safe_template():
|
||||
path = PROJECT / "config" / "settings.example.yaml"
|
||||
assert path.exists(), "config/settings.example.yaml must be the committed 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", "") == ""
|
||||
for profile in (data.get("llm", {}).get("profiles") or {}).values():
|
||||
assert str(profile.get("api_key", "")) == ""
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert not re.search(r"sk-[A-Za-z0-9_\-]{12,}", text)
|
||||
assert "«redacted" not in text
|
||||
|
||||
|
||||
def test_runtime_settings_yaml_is_ignored_and_not_tracked():
|
||||
ignore_text = (PROJECT / ".gitignore").read_text(encoding="utf-8")
|
||||
assert "config/settings.yaml" in ignore_text
|
||||
result = subprocess.run(
|
||||
["git", "ls-files", "config/settings.yaml"],
|
||||
cwd=PROJECT,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert result.stdout.strip() == ""
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Live Streamlit UI smoke test for primary buttons and workflow."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from services.security import hash_password
|
||||
|
||||
PROJECT = Path(__file__).resolve().parent.parent
|
||||
SAMPLE = PROJECT / "ref_files" / "kuji_bntw.xlsx"
|
||||
ADMIN_PASSWORD = "streamlit-smoke-admin-password"
|
||||
ADMIN_PASSWORD_HASH = hash_password(ADMIN_PASSWORD, salt=b"streamlit-smoke-salt", iterations=1200)
|
||||
|
||||
|
||||
def _admin_env() -> dict[str, str]:
|
||||
env = os.environ.copy()
|
||||
env["ADMIN_PASSWORD_HASH"] = ADMIN_PASSWORD_HASH
|
||||
return env
|
||||
|
||||
|
||||
def _unlock_admin(page) -> None:
|
||||
page.locator('[data-testid="stExpander"]').first.click()
|
||||
page.get_by_label("Admin password").fill(ADMIN_PASSWORD)
|
||||
page.locator("button").filter(has_text="Unlock admin").last.click()
|
||||
page.wait_for_selector("text=Type configuration", timeout=30000)
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return int(sock.getsockname()[1])
|
||||
|
||||
|
||||
def _wait_ready(url: str, timeout: float = 40.0) -> None:
|
||||
deadline = time.time() + timeout
|
||||
last_error: Exception | None = None
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=2) as resp:
|
||||
if resp.status == 200:
|
||||
return
|
||||
except Exception as exc: # pragma: no cover - diagnostic path
|
||||
last_error = exc
|
||||
time.sleep(0.5)
|
||||
raise AssertionError(f"Streamlit not ready: {last_error!r}")
|
||||
|
||||
|
||||
def _assert_no_streamlit_error(page) -> None:
|
||||
body = page.locator("body").inner_text()
|
||||
assert "StreamlitAPIException" not in body
|
||||
assert "Traceback" not in body
|
||||
assert "st.session_state" not in body
|
||||
|
||||
|
||||
def _assert_layout_safe(page) -> None:
|
||||
metrics = page.evaluate("""() => {
|
||||
const block = document.querySelector('.block-container');
|
||||
const style = block ? window.getComputedStyle(block) : null;
|
||||
return {
|
||||
innerWidth: window.innerWidth,
|
||||
bodyScrollWidth: document.body.scrollWidth,
|
||||
stepperCount: document.querySelectorAll('.nbd-stepper').length,
|
||||
blockPaddingTop: style ? parseFloat(style.paddingTop) : 999,
|
||||
};
|
||||
}""")
|
||||
assert metrics["stepperCount"] == 0
|
||||
assert metrics["bodyScrollWidth"] <= metrics["innerWidth"] + 1
|
||||
assert metrics["blockPaddingTop"] <= 40
|
||||
|
||||
|
||||
def _assert_sidebar_wizard(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 'Select type' not in body
|
||||
assert 'Join review' not in body
|
||||
assert 'Mapping review' not in body
|
||||
assert 'AI summary' not in body
|
||||
|
||||
|
||||
@pytest.mark.skipif(not SAMPLE.exists(), reason="kuji_bntw.xlsx fixture missing")
|
||||
def test_streamlit_primary_buttons_do_not_raise_errors():
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
port = _free_port()
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
proc = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"streamlit",
|
||||
"run",
|
||||
"app.py",
|
||||
"--server.headless",
|
||||
"true",
|
||||
"--server.address",
|
||||
"127.0.0.1",
|
||||
"--server.port",
|
||||
str(port),
|
||||
"--server.fileWatcherType",
|
||||
"none",
|
||||
],
|
||||
cwd=PROJECT,
|
||||
env=_admin_env(),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
try:
|
||||
_wait_ready(url)
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={"width": 1280, "height": 900}, device_scale_factor=1)
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
page.wait_for_selector('text=Upload a workbook', timeout=30000)
|
||||
_assert_no_streamlit_error(page)
|
||||
_assert_layout_safe(page)
|
||||
_assert_sidebar_wizard(page)
|
||||
|
||||
# Sidebar buttons / admin pages. Basic users should not see technical AI status controls.
|
||||
assert 'Recheck AI' not in page.locator('body').inner_text()
|
||||
_unlock_admin(page)
|
||||
|
||||
page.locator('button').filter(has_text='Type configuration').first.click()
|
||||
page.wait_for_selector('text=Type Config', timeout=30000)
|
||||
_assert_no_streamlit_error(page)
|
||||
page.locator('button').filter(has_text='Back to App').first.click()
|
||||
page.wait_for_selector('text=Upload a workbook', timeout=30000)
|
||||
|
||||
page.locator('button').filter(has_text='Synonym dictionary').first.click()
|
||||
page.wait_for_selector('text=Synonym Dictionary', timeout=30000)
|
||||
_assert_no_streamlit_error(page)
|
||||
page.locator('button').filter(has_text='Back to App').first.click()
|
||||
page.wait_for_selector('text=Upload a workbook', timeout=30000)
|
||||
|
||||
page.locator('button').filter(has_text='AI configuration').first.click()
|
||||
page.wait_for_selector('text=one credential field only', timeout=30000)
|
||||
_assert_no_streamlit_error(page)
|
||||
admin_text = page.locator('body').inner_text()
|
||||
assert 'Active profile' in admin_text
|
||||
assert 'API key' in admin_text
|
||||
assert 'Stream AI response to UI' in admin_text
|
||||
assert 'Max candidates per sheet' not in admin_text
|
||||
assert 'Sample rows per candidate' not in admin_text
|
||||
assert 'Environment variable' not in admin_text
|
||||
assert 'Credential source' not in admin_text
|
||||
page.locator('button').filter(has_text='Back to App').first.click()
|
||||
page.wait_for_selector('text=Upload a workbook', timeout=30000)
|
||||
|
||||
page.locator('button').filter(has_text='Blueprint proposals').first.click()
|
||||
page.wait_for_selector('text=Blueprint proposals', timeout=30000)
|
||||
_assert_no_streamlit_error(page)
|
||||
page.locator('button').filter(has_text='Back to App').first.click()
|
||||
page.wait_for_selector('text=Upload a workbook', timeout=30000)
|
||||
|
||||
# Main workbook flow.
|
||||
page.locator('input[type="file"]').set_input_files(str(SAMPLE))
|
||||
page.wait_for_selector('text=Basic type confidence', timeout=60000)
|
||||
_assert_no_streamlit_error(page)
|
||||
assert '100.0%' 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)
|
||||
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 '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)
|
||||
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()
|
||||
page.locator('button').filter(has_text='Back to review').first.click()
|
||||
page.wait_for_selector('text=Review 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()
|
||||
page.wait_for_selector('text=Workbook ready', timeout=60000)
|
||||
|
||||
_assert_no_streamlit_error(page)
|
||||
_assert_layout_safe(page)
|
||||
|
||||
# Main-page New upload button should reset without touching widget state.
|
||||
page.locator('button').filter(has_text='New upload').last.click()
|
||||
page.wait_for_selector('text=Upload a workbook', timeout=30000)
|
||||
_assert_no_streamlit_error(page)
|
||||
|
||||
# Sidebar New upload should also be safe.
|
||||
page.locator('button').filter(has_text='New upload').first.click()
|
||||
page.wait_for_selector('text=Upload a workbook', timeout=30000)
|
||||
_assert_no_streamlit_error(page)
|
||||
browser.close()
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=8)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait(timeout=8)
|
||||
@@ -0,0 +1,84 @@
|
||||
"""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
|
||||
|
||||
|
||||
def _sample_result() -> AnalysisResult:
|
||||
return AnalysisResult(
|
||||
summaries=[SheetSummary(sheet_name="Item detail", header_row=1, sheet_type="detail", columns=[
|
||||
{"header": "商品名/英語", "meaning": "English item name", "samples": ["GRADE A"]}
|
||||
])],
|
||||
groups=[MergeGroup(
|
||||
sheets=["Item detail", "DISNEY PRINCESS"],
|
||||
master_sheet="Item detail",
|
||||
master_reason="Product rows live here",
|
||||
links=[MergeLink("DISNEY PRINCESS", "STYLE", "Item detail", "商品名/英語", "GRADE", "value_token", 0.96, "Grade token joins definition sheet")],
|
||||
)],
|
||||
mappings=[ColumnMapping("商品名/英語", "item_name_eng", 0.99, "Exact English name mapping")],
|
||||
engine="hybrid",
|
||||
)
|
||||
|
||||
|
||||
def test_build_type_support_notes_keeps_reusable_guidance_only():
|
||||
report = {
|
||||
"mapping_decisions": [{
|
||||
"sql_target": "item_name_eng",
|
||||
"chosen_source": "商品名/英語",
|
||||
"reason": "Exact English name mapping",
|
||||
"evidence": "English item name",
|
||||
}],
|
||||
"join_decisions": [{
|
||||
"master_sheet": "Item detail",
|
||||
"linked_sheet": "DISNEY PRINCESS",
|
||||
"join_key": "DISNEY PRINCESS.STYLE ↔ Item detail.商品名/英語",
|
||||
"strategy": "value_token",
|
||||
"reason": "Grade token joins definition sheet",
|
||||
}],
|
||||
}
|
||||
|
||||
notes = build_type_support_notes("kuji_tw", "kuji_bntw.xlsx", _sample_result(), report)
|
||||
text = yaml.safe_dump(notes, allow_unicode=True)
|
||||
|
||||
assert notes["source_type"] == "kuji_tw"
|
||||
assert notes["learned_from"]["workbook_name"] == "kuji_bntw.xlsx"
|
||||
assert notes["notes"]["header_aliases"][0]["sql_target"] == "item_name_eng"
|
||||
assert notes["notes"]["header_aliases"][0]["preferred_headers"] == ["商品名/英語"]
|
||||
assert notes["notes"]["join_hints"][0]["strategy"] == "value_token"
|
||||
assert "api_key" not in text.lower()
|
||||
assert "token:" not in text.lower()
|
||||
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"}],
|
||||
"join_decisions": [],
|
||||
})
|
||||
|
||||
prompt_text = render_support_notes_for_prompt(notes)
|
||||
|
||||
assert "TYPE SUPPORT NOTES" in prompt_text
|
||||
assert "item_name_eng" in prompt_text
|
||||
assert "商品名/英語" in prompt_text
|
||||
assert len(prompt_text) < 2500
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Low-confidence upload confirmation policy tests."""
|
||||
from __future__ import annotations
|
||||
|
||||
from ui.upload_page import _can_continue_basic, _needs_low_confidence_confirmation
|
||||
|
||||
|
||||
class _PolicyConfig:
|
||||
def __init__(self, threshold: float = 40.0, require: bool = True):
|
||||
self.threshold = threshold
|
||||
self.require = require
|
||||
|
||||
def get_low_confidence_warning_threshold(self) -> float:
|
||||
return self.threshold
|
||||
|
||||
def should_require_low_confidence_confirmation(self) -> bool:
|
||||
return self.require
|
||||
|
||||
|
||||
def test_below_40_percent_requires_confirmation_before_continue():
|
||||
cm = _PolicyConfig(threshold=40.0, require=True)
|
||||
result = object()
|
||||
|
||||
assert _needs_low_confidence_confirmation(cm, 39.9) is True
|
||||
assert _can_continue_basic("kuji_tw", result, cm, 39.9, confirmed_low_confidence=False) is False
|
||||
assert _can_continue_basic("kuji_tw", result, cm, 39.9, confirmed_low_confidence=True) is True
|
||||
|
||||
|
||||
def test_40_percent_or_above_can_continue_without_extra_confirmation():
|
||||
cm = _PolicyConfig(threshold=40.0, require=True)
|
||||
result = object()
|
||||
|
||||
assert _needs_low_confidence_confirmation(cm, 40.0) is False
|
||||
assert _can_continue_basic("kuji_tw", result, cm, 40.0, confirmed_low_confidence=False) is True
|
||||
|
||||
|
||||
def test_confirmation_can_be_disabled_by_settings():
|
||||
cm = _PolicyConfig(threshold=40.0, require=False)
|
||||
result = object()
|
||||
|
||||
assert _needs_low_confidence_confirmation(cm, 10.0) is False
|
||||
assert _can_continue_basic("kuji_tw", result, cm, 10.0, confirmed_low_confidence=False) is True
|
||||
@@ -1,136 +0,0 @@
|
||||
"""Tests for ValueMatcher — cross-sheet value matching engine."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import pytest
|
||||
from services.value_matcher import ValueMatcher, ValueMatch
|
||||
|
||||
|
||||
class TestValueMatcher:
|
||||
def test_prefix_match(self):
|
||||
vm = ValueMatcher()
|
||||
matches = vm.match(
|
||||
"A", # key
|
||||
[["A賞", "GRADE A:Figure"], ["B賞", "GRADE B:Figure"]], # target rows
|
||||
["商品名/日本語", "商品名/英語"], # target headers
|
||||
[{"column": "商品名/日本語", "strategy": "prefix"}],
|
||||
)
|
||||
assert len(matches) == 1
|
||||
assert matches[0].matched_value == "A賞"
|
||||
assert matches[0].strategy == "prefix"
|
||||
assert matches[0].target_row_idx == 0
|
||||
|
||||
def test_token_match(self):
|
||||
vm = ValueMatcher()
|
||||
matches = vm.match(
|
||||
"A",
|
||||
[["A賞", "GRADE A:Figure"], ["B賞", "GRADE B:Figure"]],
|
||||
["商品名/日本語", "商品名/英語"],
|
||||
[{"column": "商品名/英語", "strategy": "token_match"}],
|
||||
)
|
||||
assert len(matches) == 1
|
||||
assert matches[0].matched_value == "GRADE A:Figure"
|
||||
assert matches[0].target_row_idx == 0
|
||||
|
||||
def test_multiple_rules(self):
|
||||
"""Both rules should find matches."""
|
||||
vm = ValueMatcher()
|
||||
matches = vm.match(
|
||||
"A",
|
||||
[["A賞", "GRADE A:Figure"]],
|
||||
["商品名/日本語", "商品名/英語"],
|
||||
[
|
||||
{"column": "商品名/日本語", "strategy": "prefix"},
|
||||
{"column": "商品名/英語", "strategy": "token_match"},
|
||||
],
|
||||
)
|
||||
assert len(matches) == 2
|
||||
|
||||
def test_fullwidth_normalization(self):
|
||||
"""Full-width F should match half-width F."""
|
||||
vm = ValueMatcher()
|
||||
matches = vm.match(
|
||||
"F", # full-width
|
||||
[["F賞"]],
|
||||
["Col"],
|
||||
[{"column": "Col", "strategy": "prefix"}],
|
||||
)
|
||||
assert len(matches) == 1
|
||||
|
||||
def test_exact_match(self):
|
||||
vm = ValueMatcher()
|
||||
matches = vm.match(
|
||||
"1",
|
||||
[["2", "Item A"], ["1", "Item B"]],
|
||||
["種類", "Name"],
|
||||
[{"column": "種類", "strategy": "exact"}],
|
||||
)
|
||||
assert len(matches) == 1
|
||||
assert matches[0].target_row_idx == 1
|
||||
|
||||
def test_empty_key_returns_empty(self):
|
||||
vm = ValueMatcher()
|
||||
matches = vm.match("", [["A"]], ["X"], [{"column": "X", "strategy": "prefix"}])
|
||||
assert matches == []
|
||||
|
||||
def test_column_not_found(self):
|
||||
vm = ValueMatcher()
|
||||
matches = vm.match("A", [["A賞"]], ["WrongCol"], [{"column": "RightCol", "strategy": "prefix"}])
|
||||
assert matches == []
|
||||
|
||||
|
||||
class TestReverseLookup:
|
||||
def test_reverse_token_match(self):
|
||||
"""Reverse token match: scan target STYLE values, find which
|
||||
one appears as a token in the source cell 'GRADE A:Figure'."""
|
||||
vm = ValueMatcher()
|
||||
# Simulate Item detail → DISNEY PRINCESS:
|
||||
# source_value = "GRADE A:Figure" (from item name)
|
||||
# target STYLE column has ["A", "B", "C", ...]
|
||||
result = vm.reverse_lookup(
|
||||
source_value="GRADE A:Figure",
|
||||
target_rows=[["A", "H:16cm", "2"], ["B", "H:18cm", "1"], ["C", "H:17cm", "1"]],
|
||||
target_headers=["STYLE", "ITEM SIZE", "QTY"],
|
||||
match_rules=[{"column": "STYLE", "strategy": "token_match"}],
|
||||
)
|
||||
assert result is not None
|
||||
assert result.key == "A"
|
||||
assert result.target_row_idx == 0
|
||||
assert result.strategy == "reverse_token_match"
|
||||
|
||||
def test_reverse_prefix_match(self):
|
||||
"""Reverse prefix: 'GRADE A:Figure' contains 'A' at start? No.
|
||||
But source 'A賞...' scanned against STYLE='A' → prefix? 'A賞' starts with 'A' = yes.
|
||||
Actually in reverse mode: does STYLE 'A' appear as prefix in 'A賞〈ベル〉...'? Yes."""
|
||||
vm = ValueMatcher()
|
||||
result = vm.reverse_lookup(
|
||||
source_value="A賞〈ベル〉フィギュア",
|
||||
target_rows=[["A"], ["B"], ["C"]],
|
||||
target_headers=["STYLE"],
|
||||
match_rules=[{"column": "STYLE", "strategy": "prefix"}],
|
||||
)
|
||||
assert result is not None
|
||||
assert result.key == "A"
|
||||
|
||||
def test_reverse_lookup_no_match(self):
|
||||
vm = ValueMatcher()
|
||||
result = vm.reverse_lookup(
|
||||
source_value="XYZ_UNMATCHED",
|
||||
target_rows=[["A"], ["B"], ["C"]],
|
||||
target_headers=["STYLE"],
|
||||
match_rules=[{"column": "STYLE", "strategy": "token_match"}],
|
||||
)
|
||||
assert result is None
|
||||
|
||||
def test_reverse_lookup_fullwidth(self):
|
||||
"""Full-width F in STYLE should match GRADE F:Glass after normalization."""
|
||||
vm = ValueMatcher()
|
||||
result = vm.reverse_lookup(
|
||||
source_value="GRADE F:Glass",
|
||||
target_rows=[["F", "H:14cm"]], # full-width F
|
||||
target_headers=["STYLE", "ITEM SIZE"],
|
||||
match_rules=[{"column": "STYLE", "strategy": "token_match"}],
|
||||
)
|
||||
assert result is not None
|
||||
assert result.key == "F" # original cell value preserved
|
||||
@@ -39,6 +39,25 @@ class TestWorkbookAnalyzer:
|
||||
mapped = {m.excel_column: m.sql_target for m in result.mappings}
|
||||
assert mapped["name"] == "item_name_eng"
|
||||
|
||||
def test_llm_progress_callback_reports_stages(self, cm, monkeypatch):
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
analyzer = WorkbookAnalyzer(cm)
|
||||
from services.llm_stages import SheetSummary, ColumnMapping
|
||||
monkeypatch.setattr(analyzer.stages, "stage1_read_sheet",
|
||||
lambda name, rows: SheetSummary(name, 1, "detail", [{"header": "name"}], []))
|
||||
monkeypatch.setattr(analyzer.stages, "stage2_find_links", lambda sums: [])
|
||||
monkeypatch.setattr(analyzer.stages, "stage3_map_columns",
|
||||
lambda sums, groups, schema: [ColumnMapping("name", "item_name_eng", 0.9, "r")])
|
||||
events = []
|
||||
|
||||
result = analyzer.analyze(make_workbook(), progress_callback=events.append)
|
||||
|
||||
assert result.mappings
|
||||
assert events[0]["title"] == "Preparing deterministic fallback"
|
||||
assert any("Stage 1" in e["title"] for e in events)
|
||||
assert any("Stage 3" in e["title"] for e in events)
|
||||
assert events[-1]["percent"] == 100
|
||||
|
||||
def test_falls_back_when_llm_disabled(self, cm, monkeypatch):
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: False)
|
||||
analyzer = WorkbookAnalyzer(cm)
|
||||
@@ -46,6 +65,23 @@ class TestWorkbookAnalyzer:
|
||||
assert result.engine == "fuzzy"
|
||||
assert len(result.warnings) >= 1
|
||||
|
||||
def test_basic_analysis_skips_llm_even_when_enabled(self, cm, monkeypatch):
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
analyzer = WorkbookAnalyzer(cm)
|
||||
called = {"stage1": False}
|
||||
|
||||
def fail_if_called(name, rows):
|
||||
called["stage1"] = True
|
||||
raise AssertionError("LLM stage should not be called for basic analysis")
|
||||
|
||||
monkeypatch.setattr(analyzer.stages, "stage1_read_sheet", fail_if_called)
|
||||
events = []
|
||||
result = analyzer.analyze(make_workbook(), progress_callback=events.append, use_llm=False)
|
||||
|
||||
assert result.engine == "fuzzy"
|
||||
assert called["stage1"] is False
|
||||
assert events[-1]["title"] == "Basic analysis ready"
|
||||
|
||||
def test_falls_back_when_stage1_all_fail(self, cm, monkeypatch):
|
||||
monkeypatch.setattr(cm, "is_llm_enabled", lambda: True)
|
||||
analyzer = WorkbookAnalyzer(cm)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Tests for workbook sheet-selection helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
from services.excel_parser import ParsedSheet, ParsedWorkbook
|
||||
from services.workbook_selection import filter_parsed_workbook_sheets
|
||||
|
||||
|
||||
def test_filter_parsed_workbook_sheets_keeps_workbook_order_and_metadata():
|
||||
workbook = ParsedWorkbook(
|
||||
file_name="sample.xlsx",
|
||||
sheets=[
|
||||
ParsedSheet(name="Cover"),
|
||||
ParsedSheet(name="Item detail"),
|
||||
ParsedSheet(name="Product"),
|
||||
],
|
||||
)
|
||||
|
||||
filtered = filter_parsed_workbook_sheets(workbook, ["Product", "Missing", "Item detail"])
|
||||
|
||||
assert filtered.file_name == "sample.xlsx"
|
||||
assert [sheet.name for sheet in filtered.sheets] == ["Item detail", "Product"]
|
||||
assert [sheet.name for sheet in workbook.sheets] == ["Cover", "Item detail", "Product"]
|
||||
|
||||
|
||||
def test_filter_parsed_workbook_sheets_returns_all_when_selection_is_none():
|
||||
workbook = ParsedWorkbook(file_name="sample.xlsx", sheets=[ParsedSheet(name="A"), ParsedSheet(name="B")])
|
||||
|
||||
filtered = filter_parsed_workbook_sheets(workbook, None)
|
||||
|
||||
assert [sheet.name for sheet in filtered.sheets] == ["A", "B"]
|
||||
@@ -0,0 +1 @@
|
||||
"""Streamlit page modules for the NBD Pre-Item Master app."""
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Streamlit admin unlock helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
import streamlit as st
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.security import is_configured_hash, verify_password
|
||||
|
||||
ADMIN_UNLOCK_KEY = "admin_unlocked"
|
||||
|
||||
|
||||
def is_admin_unlocked() -> bool:
|
||||
"""Return whether this Streamlit browser session has unlocked admin mode."""
|
||||
return bool(st.session_state.get(ADMIN_UNLOCK_KEY, False))
|
||||
|
||||
|
||||
def lock_admin() -> None:
|
||||
"""Lock admin mode for the current Streamlit session."""
|
||||
st.session_state[ADMIN_UNLOCK_KEY] = False
|
||||
|
||||
|
||||
def render_admin_unlock(cm: ConfigManager) -> bool:
|
||||
"""Render the Basic-sidebar admin unlock control. Returns True when state changed."""
|
||||
if is_admin_unlocked():
|
||||
return False
|
||||
with st.expander("🔐 Unlock admin", expanded=False):
|
||||
stored_hash = cm.get_admin_password_hash()
|
||||
if not is_configured_hash(stored_hash):
|
||||
st.warning("Admin password is not configured. Ask IT to set security.admin_password_hash in config/settings.yaml.")
|
||||
st.caption("Generate a hash with: python scripts/hash_admin_password.py")
|
||||
return False
|
||||
password = st.text_input("Admin password", type="password", key="admin_unlock_password")
|
||||
if st.button("Unlock admin", key="admin_unlock_button", width="stretch"):
|
||||
if verify_password(password, stored_hash):
|
||||
st.session_state[ADMIN_UNLOCK_KEY] = True
|
||||
st.success("Admin unlocked for this session.")
|
||||
return True
|
||||
st.error("Wrong admin password.")
|
||||
return False
|
||||
|
||||
|
||||
def require_admin_page(cm: ConfigManager) -> bool:
|
||||
"""Guard a direct admin route."""
|
||||
if is_admin_unlocked():
|
||||
return True
|
||||
st.title("🔐 Admin locked")
|
||||
st.info("Unlock admin from the sidebar before opening system settings.")
|
||||
render_admin_unlock(cm)
|
||||
return False
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Admin UI for reviewing temporary blueprint proposals."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import streamlit as st
|
||||
|
||||
from services.blueprint_proposals import (
|
||||
archive_blueprint_proposal,
|
||||
build_type_config_from_proposal,
|
||||
list_blueprint_proposals,
|
||||
load_blueprint_proposal,
|
||||
)
|
||||
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 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.")
|
||||
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}.")
|
||||
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)]
|
||||
payload = load_blueprint_proposal(ref.path)
|
||||
|
||||
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', '')}`
|
||||
"""
|
||||
)
|
||||
|
||||
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
|
||||
else:
|
||||
cfg["type_id"] = slugify_type_id(type_name)
|
||||
|
||||
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))
|
||||
|
||||
if validation.errors:
|
||||
for error in validation.errors:
|
||||
st.error(error)
|
||||
for warning in validation.warnings:
|
||||
st.warning(warning)
|
||||
|
||||
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:
|
||||
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}.")
|
||||
st.rerun()
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Reusable Streamlit guards for admin write actions."""
|
||||
from __future__ import annotations
|
||||
|
||||
import streamlit as st
|
||||
|
||||
from services.config_manager import ConfigManager
|
||||
from services.security import verify_password
|
||||
|
||||
|
||||
def admin_reauth_ok(cm: ConfigManager, key: str, *, destructive: bool = False) -> bool:
|
||||
"""Render password/confirmation controls and return whether a mutation may run."""
|
||||
if not cm.admin_reauth_required_for_mutations():
|
||||
return True
|
||||
password = st.text_input("Confirm admin password", type="password", key=f"admin_reauth_{key}")
|
||||
confirmed = True
|
||||
if destructive:
|
||||
confirmed = st.checkbox("I understand this will change system configuration.", key=f"admin_confirm_{key}")
|
||||
if not password:
|
||||
return False
|
||||
return bool(confirmed and verify_password(password, cm.get_admin_password_hash()))
|
||||
|
||||
|
||||
def show_reauth_error() -> None:
|
||||
"""Show a standard message after a guarded action was attempted."""
|
||||
st.error("Admin password confirmation is required before changing system settings.")
|
||||
+361
-53
@@ -1,35 +1,74 @@
|
||||
"""Admin pages — Type Config management (Hybrid Form + Live Preview) and Synonym Dictionary."""
|
||||
import copy
|
||||
import re
|
||||
|
||||
import streamlit as st
|
||||
import yaml
|
||||
|
||||
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
|
||||
|
||||
# ── Public entry points ─────────────────────────────────────────────
|
||||
|
||||
def render_admin_page(tab: str = "types"):
|
||||
"""Top-level admin page with tab selector."""
|
||||
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.rerun()
|
||||
|
||||
tab_options = ["📋 Type Config", "📖 Synonym Dictionary", "🤖 AI Configuration", "🧩 Blueprint Proposals"]
|
||||
default_index = {"types": 0, "synonyms": 1, "llm": 2, "blueprints": 3}.get(tab, 0)
|
||||
admin_tab = st.radio(
|
||||
"Select admin section",
|
||||
options=["📋 Type Config", "📖 Synonym Dictionary"],
|
||||
options=tab_options,
|
||||
horizontal=True,
|
||||
index=0 if tab == "types" else 1,
|
||||
index=default_index,
|
||||
)
|
||||
|
||||
if "📋 Type Config" in admin_tab:
|
||||
_render_type_config_hybrid()
|
||||
else:
|
||||
elif "📖 Synonym" in admin_tab:
|
||||
_render_synonym_dict()
|
||||
elif "🤖 AI" in admin_tab:
|
||||
_render_llm_config()
|
||||
else:
|
||||
render_blueprint_proposals(cm)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
# Type Config — Hybrid Form + Live Preview
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
def _admin_widget_scope(raw: str) -> str:
|
||||
"""Return a stable, widget-key-safe scope for dependent admin controls."""
|
||||
text = re.sub(r"[^a-zA-Z0-9_]+", "_", str(raw or "blank")).strip("_")
|
||||
return text or "blank"
|
||||
|
||||
|
||||
def _type_key(scope: str, name: str) -> str:
|
||||
"""Namespace Type Config child widgets by selected type to avoid stale values."""
|
||||
return f"admin_type_{scope}_{name}"
|
||||
|
||||
|
||||
def _profile_key(scope: str, name: str) -> str:
|
||||
"""Namespace LLM profile widgets by selected profile to avoid stale values."""
|
||||
return f"llm_profile_{scope}_{name}"
|
||||
|
||||
|
||||
def _option_index(options: list[str], value: str, default: int = 0) -> int:
|
||||
"""Return index of value in options, falling back safely."""
|
||||
return options.index(value) if value in options else default
|
||||
|
||||
|
||||
def _render_type_config_hybrid():
|
||||
"""Render the editable type-config admin screen with form controls and YAML preview."""
|
||||
cm: ConfigManager = st.session_state.config_manager
|
||||
type_list = cm.get_type_list()
|
||||
validator = ConfigValidator(valid_target_columns=cm.get_target_column_names())
|
||||
@@ -60,16 +99,17 @@ def _render_type_config_hybrid():
|
||||
st.session_state.admin_validation = None
|
||||
|
||||
draft: dict = st.session_state.admin_draft
|
||||
scope = _admin_widget_scope(selected)
|
||||
|
||||
# ── Two-column layout: Form | Preview ──
|
||||
left, right = st.columns([3, 2])
|
||||
|
||||
with left:
|
||||
st.caption(f"Editing: **{cfg.get('label', selected)}**")
|
||||
_render_basic_info(draft)
|
||||
_render_structure_form(draft)
|
||||
_render_mapping_form(draft)
|
||||
_render_sheet_relations_form(draft)
|
||||
st.caption(f"Editing: **{draft.get('label') or cfg.get('label', selected)}**")
|
||||
_render_basic_info(draft, scope)
|
||||
_render_structure_form(draft, scope)
|
||||
_render_mapping_form(draft, scope)
|
||||
_render_sheet_relations_form(draft, scope)
|
||||
|
||||
with right:
|
||||
st.subheader("👁️ Live Preview")
|
||||
@@ -91,45 +131,55 @@ def _render_type_config_hybrid():
|
||||
|
||||
# ── Action buttons ──
|
||||
st.divider()
|
||||
st.caption("System-setting changes require admin password confirmation.")
|
||||
can_mutate = admin_reauth_ok(cm, f"type_{scope}", destructive=False)
|
||||
col_a, col_b, col_c, col_d = st.columns([1, 1, 1, 1])
|
||||
with col_a:
|
||||
if st.button("🔍 Validate", use_container_width=True):
|
||||
if st.button("🔍 Validate", width="stretch"):
|
||||
vr = validator.validate(draft)
|
||||
st.session_state.admin_validation = vr
|
||||
st.rerun()
|
||||
with col_b:
|
||||
if st.button("💾 Save", type="primary", use_container_width=True):
|
||||
vr = validator.validate(draft)
|
||||
st.session_state.admin_validation = vr
|
||||
if vr.errors:
|
||||
st.error("❌ Cannot save — fix validation errors first.")
|
||||
if st.button("💾 Save", type="primary", width="stretch"):
|
||||
if not can_mutate:
|
||||
show_reauth_error()
|
||||
else:
|
||||
cm.save_type_config(selected, draft)
|
||||
st.session_state.admin_draft_id = None
|
||||
st.success(f"✅ Saved '{selected}'")
|
||||
st.rerun()
|
||||
vr = validator.validate(draft)
|
||||
st.session_state.admin_validation = vr
|
||||
if vr.errors:
|
||||
st.error("❌ Cannot save — fix validation errors first.")
|
||||
else:
|
||||
cm.save_type_config(selected, draft)
|
||||
st.session_state.admin_draft_id = None
|
||||
st.success(f"✅ Saved '{selected}'")
|
||||
st.rerun()
|
||||
with col_c:
|
||||
if st.button("🗑️ Delete Type", use_container_width=True):
|
||||
cm.delete_type_config(selected)
|
||||
st.session_state.admin_draft_id = None
|
||||
st.success(f"Deleted '{selected}'")
|
||||
st.rerun()
|
||||
if st.button("🗑️ Delete Type", width="stretch"):
|
||||
if not can_mutate:
|
||||
show_reauth_error()
|
||||
else:
|
||||
cm.delete_type_config(selected)
|
||||
st.session_state.admin_draft_id = None
|
||||
st.success(f"Deleted '{selected}'")
|
||||
st.rerun()
|
||||
with col_d:
|
||||
if st.button("← Back to App", use_container_width=True):
|
||||
if st.button("← Back to App", width="stretch"):
|
||||
st.session_state.current_step = "upload"
|
||||
st.rerun()
|
||||
|
||||
|
||||
# ── Section renderers ──────────────────────────────────────────────
|
||||
|
||||
def _render_basic_info(draft: dict):
|
||||
def _render_basic_info(draft: dict, scope: str):
|
||||
"""Render simple identity fields for the selected workbook type."""
|
||||
with st.expander("📝 Basic Info", expanded=True):
|
||||
draft["type_id"] = st.text_input("Type ID", value=draft.get("type_id", ""), key="bi_type_id")
|
||||
draft["label"] = st.text_input("Label", value=draft.get("label", ""), key="bi_label")
|
||||
draft["category"] = st.text_input("Category", value=draft.get("category", ""), key="bi_category")
|
||||
draft["type_id"] = st.text_input("Type ID", value=draft.get("type_id", ""), key=_type_key(scope, "bi_type_id"))
|
||||
draft["label"] = st.text_input("Label", value=draft.get("label", ""), key=_type_key(scope, "bi_label"))
|
||||
draft["category"] = st.text_input("Category", value=draft.get("category", ""), key=_type_key(scope, "bi_category"))
|
||||
|
||||
|
||||
def _render_structure_form(draft: dict):
|
||||
def _render_structure_form(draft: dict, scope: str):
|
||||
"""Render controls that describe where headers/data rows begin."""
|
||||
with st.expander("🔍 Structure Detection", expanded=False):
|
||||
struct = draft.setdefault("structure", {"header_pattern": {"keywords": [], "strategy": "max_keyword_match"}, "data_start_offset": 1})
|
||||
hp = struct.setdefault("header_pattern", {"keywords": [], "strategy": "max_keyword_match"})
|
||||
@@ -137,19 +187,31 @@ def _render_structure_form(draft: dict):
|
||||
kw_text = st.text_area(
|
||||
"Header Keywords (one per line or comma-separated)",
|
||||
value=", ".join(hp.get("keywords", [])),
|
||||
key="struct_keywords",
|
||||
key=_type_key(scope, "struct_keywords"),
|
||||
height=80,
|
||||
)
|
||||
hp["keywords"] = [k.strip() for k in kw_text.replace("\n", ",").split(",") if k.strip()]
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
with col1:
|
||||
hp["strategy"] = st.selectbox("Detection Strategy", options=["max_keyword_match"], key="struct_strat")
|
||||
strategies = ["max_keyword_match"]
|
||||
hp["strategy"] = st.selectbox(
|
||||
"Detection Strategy",
|
||||
options=strategies,
|
||||
index=_option_index(strategies, str(hp.get("strategy", "max_keyword_match"))),
|
||||
key=_type_key(scope, "struct_strat"),
|
||||
)
|
||||
with col2:
|
||||
struct["data_start_offset"] = st.number_input("Data Start Offset (rows after header)", value=struct.get("data_start_offset", 1), min_value=0, key="struct_offset")
|
||||
struct["data_start_offset"] = st.number_input(
|
||||
"Data Start Offset (rows after header)",
|
||||
value=struct.get("data_start_offset", 1),
|
||||
min_value=0,
|
||||
key=_type_key(scope, "struct_offset"),
|
||||
)
|
||||
|
||||
|
||||
def _render_mapping_form(draft: dict):
|
||||
def _render_mapping_form(draft: dict, scope: str):
|
||||
"""Render editable Excel-header to SQL-column mapping rows."""
|
||||
with st.expander("🔗 Column Mappings", expanded=True):
|
||||
mappings: list = draft.setdefault("mapping", [])
|
||||
target_names = _get_target_names()
|
||||
@@ -163,7 +225,7 @@ def _render_mapping_form(draft: dict):
|
||||
patterns_text = st.text_input(
|
||||
"Source Patterns (comma-separated)",
|
||||
value=", ".join(m.get("source_patterns", [])),
|
||||
key=f"map_src_{i}",
|
||||
key=_type_key(scope, f"map_src_{i}"),
|
||||
)
|
||||
m["source_patterns"] = [p.strip() for p in patterns_text.split(",") if p.strip()]
|
||||
with col2:
|
||||
@@ -173,21 +235,21 @@ def _render_mapping_form(draft: dict):
|
||||
"→ Target Column",
|
||||
options=["(select)"] + target_names,
|
||||
index=target_idx,
|
||||
key=f"map_tgt_{i}",
|
||||
key=_type_key(scope, f"map_tgt_{i}"),
|
||||
)
|
||||
if new_target and new_target != "(select)":
|
||||
m["target"] = new_target
|
||||
with col3:
|
||||
m["required"] = st.checkbox("Required", value=m.get("required", False), key=f"map_req_{i}")
|
||||
m["required"] = st.checkbox("Required", value=m.get("required", False), key=_type_key(scope, f"map_req_{i}"))
|
||||
st.caption(f"Weight: {m.get('fuzzy_weight', 0.8)}")
|
||||
if st.button("🗑️", key=f"map_del_{i}"):
|
||||
if st.button("🗑️", key=_type_key(scope, f"map_del_{i}")):
|
||||
to_delete = i
|
||||
|
||||
if to_delete is not None:
|
||||
mappings.pop(to_delete)
|
||||
st.rerun()
|
||||
|
||||
if st.button("➕ Add Mapping", key="add_mapping"):
|
||||
if st.button("➕ Add Mapping", key=_type_key(scope, "add_mapping")):
|
||||
mappings.append({
|
||||
"source_patterns": [],
|
||||
"target": target_names[0] if target_names else "",
|
||||
@@ -198,7 +260,8 @@ def _render_mapping_form(draft: dict):
|
||||
st.rerun()
|
||||
|
||||
|
||||
def _render_sheet_relations_form(draft: dict):
|
||||
def _render_sheet_relations_form(draft: dict, scope: str):
|
||||
"""Render cross-sheet lookup relation controls for a type config."""
|
||||
with st.expander("🔀 Sheet Relations (Cross-Sheet Value Matching)", expanded=False):
|
||||
relations: list = draft.setdefault("sheet_relations", [])
|
||||
|
||||
@@ -209,29 +272,35 @@ def _render_sheet_relations_form(draft: dict):
|
||||
st.markdown(f"**Relation {i+1}:** {rel.get('name', '(unnamed)')}")
|
||||
col_a, col_b = st.columns([2, 1])
|
||||
with col_a:
|
||||
rel["name"] = st.text_input("Relation Name", value=rel.get("name", ""), key=f"rel_name_{i}")
|
||||
rel["description"] = st.text_input("Description", value=rel.get("description", ""), key=f"rel_desc_{i}")
|
||||
rel["name"] = st.text_input("Relation Name", value=rel.get("name", ""), key=_type_key(scope, f"rel_name_{i}"))
|
||||
rel["description"] = st.text_input("Description", value=rel.get("description", ""), key=_type_key(scope, f"rel_desc_{i}"))
|
||||
with col_b:
|
||||
join_cfg = rel.setdefault("join", {"type": "lookup", "columns": "all"})
|
||||
join_cfg["type"] = st.selectbox("Join Type", options=["lookup", "inner"], index=0 if join_cfg.get("type") == "lookup" else 1, key=f"rel_join_{i}")
|
||||
join_cfg["type"] = st.selectbox("Join Type", options=["lookup", "inner"], index=0 if join_cfg.get("type") == "lookup" else 1, key=_type_key(scope, f"rel_join_{i}"))
|
||||
|
||||
# Source section
|
||||
st.caption("Source")
|
||||
src = rel.setdefault("source", {"sheet_pattern": "", "key_column": ""})
|
||||
col1, col2 = st.columns(2)
|
||||
with col1:
|
||||
src["sheet_pattern"] = st.text_input("Sheet Pattern", value=src.get("sheet_pattern", ""), placeholder="e.g. DISNEY*", key=f"rel_ssp_{i}")
|
||||
src["sheet_pattern"] = st.text_input("Sheet Pattern", value=src.get("sheet_pattern", ""), placeholder="e.g. DISNEY*", key=_type_key(scope, f"rel_ssp_{i}"))
|
||||
with col2:
|
||||
src["key_column"] = st.text_input("Key Column", value=src.get("key_column", ""), placeholder="e.g. STYLE", key=f"rel_skc_{i}")
|
||||
src["key_column"] = st.text_input("Key Column", value=src.get("key_column", ""), placeholder="e.g. STYLE", key=_type_key(scope, f"rel_skc_{i}"))
|
||||
|
||||
# Target section
|
||||
st.caption("Target")
|
||||
tgt = rel.setdefault("target", {"sheet_pattern": "", "match_rules": [], "multiple": "one_to_one"})
|
||||
col1, col2 = st.columns(2)
|
||||
with col1:
|
||||
tgt["sheet_pattern"] = st.text_input("Sheet Pattern", value=tgt.get("sheet_pattern", ""), placeholder="e.g. Item detail", key=f"rel_tsp_{i}")
|
||||
tgt["sheet_pattern"] = st.text_input("Sheet Pattern", value=tgt.get("sheet_pattern", ""), placeholder="e.g. Item detail", key=_type_key(scope, f"rel_tsp_{i}"))
|
||||
with col2:
|
||||
tgt["multiple"] = st.selectbox("Cardinality", options=["one_to_one", "one_to_many"], index=0, key=f"rel_mult_{i}")
|
||||
cardinality_options = ["one_to_one", "one_to_many"]
|
||||
tgt["multiple"] = st.selectbox(
|
||||
"Cardinality",
|
||||
options=cardinality_options,
|
||||
index=_option_index(cardinality_options, str(tgt.get("multiple", "one_to_one"))),
|
||||
key=_type_key(scope, f"rel_mult_{i}"),
|
||||
)
|
||||
|
||||
# Match rules
|
||||
match_rules = tgt.setdefault("match_rules", [])
|
||||
@@ -240,33 +309,33 @@ def _render_sheet_relations_form(draft: dict):
|
||||
for j, rule in enumerate(match_rules):
|
||||
c1, c2, c3, c4 = st.columns([2, 2, 1, 0.5])
|
||||
with c1:
|
||||
rule["column"] = st.text_input("Column", value=rule.get("column", ""), key=f"rel_mrc_{i}_{j}", label_visibility="collapsed", placeholder="Column")
|
||||
rule["column"] = st.text_input("Column", value=rule.get("column", ""), key=_type_key(scope, f"rel_mrc_{i}_{j}"), label_visibility="collapsed", placeholder="Column")
|
||||
with c2:
|
||||
strategies = ["prefix", "suffix", "contains", "token_match", "exact", "pattern"]
|
||||
sidx = strategies.index(rule.get("strategy", "contains")) if rule.get("strategy", "contains") in strategies else 0
|
||||
rule["strategy"] = st.selectbox("Strategy", options=strategies, index=sidx, key=f"rel_mrs_{i}_{j}", label_visibility="collapsed")
|
||||
rule["strategy"] = st.selectbox("Strategy", options=strategies, index=sidx, key=_type_key(scope, f"rel_mrs_{i}_{j}"), label_visibility="collapsed")
|
||||
with c3:
|
||||
if rule.get("strategy") == "pattern":
|
||||
rule["pattern"] = st.text_input("Pattern", value=rule.get("pattern", ""), key=f"rel_mrp_{i}_{j}", label_visibility="collapsed", placeholder="GRADE {key}:*")
|
||||
rule["pattern"] = st.text_input("Pattern", value=rule.get("pattern", ""), key=_type_key(scope, f"rel_mrp_{i}_{j}"), label_visibility="collapsed", placeholder="GRADE {key}:*")
|
||||
with c4:
|
||||
if st.button("🗑️", key=f"rel_delmr_{i}_{j}"):
|
||||
if st.button("🗑️", key=_type_key(scope, f"rel_delmr_{i}_{j}")):
|
||||
to_del_mr = j
|
||||
if to_del_mr is not None:
|
||||
match_rules.pop(to_del_mr)
|
||||
st.rerun()
|
||||
|
||||
if st.button("➕ Add Match Rule", key=f"rel_addmr_{i}"):
|
||||
if st.button("➕ Add Match Rule", key=_type_key(scope, f"rel_addmr_{i}")):
|
||||
match_rules.append({"column": "", "strategy": "contains"})
|
||||
st.rerun()
|
||||
|
||||
if st.button("🗑️ Delete Relation", key=f"rel_del_{i}"):
|
||||
if st.button("🗑️ Delete Relation", key=_type_key(scope, f"rel_del_{i}")):
|
||||
to_delete_rel = i
|
||||
|
||||
if to_delete_rel is not None:
|
||||
relations.pop(to_delete_rel)
|
||||
st.rerun()
|
||||
|
||||
if st.button("➕ Add Sheet Relation", key="add_relation"):
|
||||
if st.button("➕ Add Sheet Relation", key=_type_key(scope, "add_relation")):
|
||||
relations.append({
|
||||
"name": "",
|
||||
"description": "",
|
||||
@@ -280,12 +349,16 @@ def _render_sheet_relations_form(draft: dict):
|
||||
def _render_new_type_form(cm: ConfigManager):
|
||||
"""Form to create a new type from scratch."""
|
||||
st.subheader("➕ Create New Type")
|
||||
can_mutate = admin_reauth_ok(cm, "new_type")
|
||||
with st.form("new_type_form"):
|
||||
new_id = st.text_input("Type ID", placeholder="lowercase_with_underscores")
|
||||
new_label = st.text_input("Label", placeholder="Human-readable name")
|
||||
new_cat = st.text_input("Category", placeholder="e.g. kuji, prize")
|
||||
submitted = st.form_submit_button("Create")
|
||||
if submitted and new_id and new_label:
|
||||
if not can_mutate:
|
||||
show_reauth_error()
|
||||
return
|
||||
cfg = {
|
||||
"type_id": new_id,
|
||||
"label": new_label,
|
||||
@@ -306,11 +379,13 @@ def _render_new_type_form(cm: ConfigManager):
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
def _render_synonym_dict():
|
||||
"""Render the synonym dictionary editor used by fuzzy matching."""
|
||||
st.subheader("📖 Synonym Dictionary")
|
||||
cm: ConfigManager = st.session_state.config_manager
|
||||
synonyms = cm.get_synonyms()
|
||||
|
||||
search = st.text_input("🔍 Search synonyms", placeholder="Type to filter...")
|
||||
can_mutate = admin_reauth_ok(cm, "synonyms")
|
||||
|
||||
for target, syn_list in sorted(synonyms.items()):
|
||||
if search and search.lower() not in target.lower() and not any(search.lower() in s.lower() for s in syn_list):
|
||||
@@ -324,6 +399,9 @@ def _render_synonym_dict():
|
||||
key=f"syn_{target}",
|
||||
)
|
||||
if st.button(f"💾 Save {target}", key=f"save_syn_{target}"):
|
||||
if not can_mutate:
|
||||
show_reauth_error()
|
||||
continue
|
||||
new_list = [s.strip() for s in new_text.split("\n") if s.strip()]
|
||||
synonyms[target] = sorted(set(new_list))
|
||||
cm.save_synonyms(synonyms)
|
||||
@@ -336,6 +414,9 @@ def _render_synonym_dict():
|
||||
tf = st.selectbox("Target field", options=list(synonyms.keys()))
|
||||
ns = st.text_input("New synonym", placeholder="e.g. 'New Column Name'")
|
||||
if st.form_submit_button("Add"):
|
||||
if not can_mutate:
|
||||
show_reauth_error()
|
||||
return
|
||||
if ns and tf:
|
||||
synonyms.setdefault(tf, [])
|
||||
if ns.strip() not in synonyms[tf]:
|
||||
@@ -350,6 +431,233 @@ def _render_synonym_dict():
|
||||
st.rerun()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
# LLM Configuration
|
||||
# ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
def _render_llm_config():
|
||||
"""Render project-owned profile-based LLM configuration as an admin page."""
|
||||
cm: ConfigManager = st.session_state.config_manager
|
||||
cfg = cm.get_llm_config()
|
||||
profiles = copy.deepcopy(cfg.get("profiles") or {})
|
||||
if not profiles:
|
||||
profiles = {
|
||||
"local": {
|
||||
"label": "DGX Spark Local",
|
||||
"base_url": "http://localhost:8000/v1",
|
||||
"model": "local-model-name",
|
||||
"api_key": "",
|
||||
"timeout_seconds": 60,
|
||||
"temperature": 0.1,
|
||||
"ssl_verify": False,
|
||||
"stream_response": True,
|
||||
"mode": "small",
|
||||
"max_sheet_rows": 80,
|
||||
"max_sheet_cols": 30,
|
||||
"max_candidates_per_sheet": 4,
|
||||
"sample_rows_per_candidate": 4,
|
||||
"max_mapping_columns": 40,
|
||||
}
|
||||
}
|
||||
active_profile = str(cfg.get("active_profile", "local") or "local")
|
||||
if active_profile not in profiles:
|
||||
active_profile = next(iter(profiles))
|
||||
|
||||
st.subheader("🤖 AI Configuration")
|
||||
st.caption(
|
||||
"AI analysis is optional. Basic analysis works without it. "
|
||||
"This admin page uses one credential field only: API key in the active AI profile."
|
||||
)
|
||||
|
||||
effective = cm.resolve_llm_connection_config()
|
||||
if effective:
|
||||
st.success(
|
||||
f"Configured: {effective.get('label')} ({effective.get('profile')}, {effective.get('mode')}) "
|
||||
f"— {effective.get('model')} @ {effective.get('base_url')}"
|
||||
)
|
||||
elif cfg.get("enabled"):
|
||||
st.warning("LLM is enabled but incomplete. Set base URL, model, and API key for the active profile.")
|
||||
else:
|
||||
st.info("LLM is disabled. Users can still continue with deterministic basic analysis.")
|
||||
|
||||
profile_ids = list(profiles.keys())
|
||||
selected_profile = st.selectbox(
|
||||
"Active profile",
|
||||
options=profile_ids,
|
||||
index=profile_ids.index(active_profile),
|
||||
format_func=lambda pid: f"{profiles[pid].get('label', pid)} ({pid})",
|
||||
key="llm_active_profile_select",
|
||||
help="Changing profile immediately refreshes the editable fields below.",
|
||||
)
|
||||
editing = copy.deepcopy(profiles[selected_profile])
|
||||
profile_scope = _admin_widget_scope(selected_profile)
|
||||
direct_key = str(editing.get("api_key", "") or "").strip()
|
||||
can_mutate = admin_reauth_ok(cm, f"ai_{profile_scope}")
|
||||
# Preserve legacy metadata fields, but do not expose them as controls until
|
||||
# they affect runtime behavior. Showing no-op controls makes tuning confusing.
|
||||
mode = str(editing.get("mode", "small") or "small")
|
||||
max_candidates_per_sheet = int(editing.get("max_candidates_per_sheet", 4) or 4)
|
||||
sample_rows_per_candidate = int(editing.get("sample_rows_per_candidate", 4) or 4)
|
||||
|
||||
with st.form("llm_admin_form"):
|
||||
enabled = st.checkbox(
|
||||
"Enable optional AI analysis",
|
||||
value=bool(cfg.get("enabled", False)),
|
||||
key=_profile_key(profile_scope, "enabled"),
|
||||
)
|
||||
|
||||
st.markdown(f"**Editing profile:** `{selected_profile}`")
|
||||
label = st.text_input(
|
||||
"Label",
|
||||
value=str(editing.get("label", selected_profile) or selected_profile),
|
||||
key=_profile_key(profile_scope, "label"),
|
||||
)
|
||||
base_url = st.text_input(
|
||||
"Base URL",
|
||||
value=str(editing.get("base_url", "") or ""),
|
||||
placeholder="https://example.local/v1",
|
||||
key=_profile_key(profile_scope, "base_url"),
|
||||
)
|
||||
model = st.text_input(
|
||||
"Model",
|
||||
value=str(editing.get("model", "") or "deepseek-chat"),
|
||||
key=_profile_key(profile_scope, "model"),
|
||||
)
|
||||
api_key_input = st.text_input(
|
||||
"API key",
|
||||
type="password",
|
||||
value="",
|
||||
placeholder="Leave blank to keep the existing stored key",
|
||||
key=_profile_key(profile_scope, "api_key"),
|
||||
)
|
||||
st.caption("Stored key: set. Leave blank to keep it." if direct_key else "Stored key: not set.")
|
||||
|
||||
col_a, col_b = st.columns(2)
|
||||
with col_a:
|
||||
timeout_seconds = st.number_input(
|
||||
"Timeout seconds",
|
||||
min_value=5,
|
||||
max_value=300,
|
||||
value=int(editing.get("timeout_seconds", 60) or 60),
|
||||
key=_profile_key(profile_scope, "timeout_seconds"),
|
||||
)
|
||||
temperature = st.number_input(
|
||||
"Temperature",
|
||||
min_value=0.0,
|
||||
max_value=2.0,
|
||||
value=float(editing.get("temperature", 0.1) or 0.1),
|
||||
step=0.1,
|
||||
key=_profile_key(profile_scope, "temperature"),
|
||||
)
|
||||
with col_b:
|
||||
ssl_verify = st.checkbox(
|
||||
"Verify SSL certificate",
|
||||
value=bool(editing.get("ssl_verify", False)),
|
||||
help="Turn on only when the AI endpoint has a trusted public/internal CA certificate.",
|
||||
key=_profile_key(profile_scope, "ssl_verify"),
|
||||
)
|
||||
stream_response = st.checkbox(
|
||||
"Stream AI response to UI",
|
||||
value=bool(editing.get("stream_response", True)),
|
||||
help="Show live response/progress chunks during optional AI analysis. Disable if an internal provider times out before streaming chunks.",
|
||||
key=_profile_key(profile_scope, "stream_response"),
|
||||
)
|
||||
|
||||
with st.expander("Prompt budget", expanded=False):
|
||||
max_sheet_rows = st.number_input("Max sheet rows", min_value=10, max_value=1000, value=int(editing.get("max_sheet_rows", 80) or 80), key=_profile_key(profile_scope, "max_sheet_rows"))
|
||||
max_sheet_cols = st.number_input("Max sheet columns", min_value=5, max_value=200, value=int(editing.get("max_sheet_cols", 30) or 30), key=_profile_key(profile_scope, "max_sheet_cols"))
|
||||
max_mapping_columns = st.number_input("Max mapping columns", min_value=5, max_value=300, value=int(editing.get("max_mapping_columns", 40) or 40), key=_profile_key(profile_scope, "max_mapping_columns"))
|
||||
|
||||
submitted = st.form_submit_button("💾 Save AI configuration", type="primary", width="stretch")
|
||||
|
||||
if submitted:
|
||||
if not can_mutate:
|
||||
show_reauth_error()
|
||||
return
|
||||
settings_path = cm.config_dir / "settings.yaml"
|
||||
settings = yaml.safe_load(settings_path.read_text(encoding="utf-8")) if settings_path.exists() else {}
|
||||
settings = settings or {}
|
||||
profiles[selected_profile] = {
|
||||
"label": label.strip() or selected_profile,
|
||||
"base_url": base_url.strip(),
|
||||
"model": model.strip(),
|
||||
"api_key": api_key_input.strip() or str(editing.get("api_key", "") or ""),
|
||||
"timeout_seconds": int(timeout_seconds),
|
||||
"temperature": float(temperature),
|
||||
"ssl_verify": bool(ssl_verify),
|
||||
"stream_response": bool(stream_response),
|
||||
"mode": mode,
|
||||
"max_sheet_rows": int(max_sheet_rows),
|
||||
"max_sheet_cols": int(max_sheet_cols),
|
||||
"max_candidates_per_sheet": int(max_candidates_per_sheet),
|
||||
"sample_rows_per_candidate": int(sample_rows_per_candidate),
|
||||
"max_mapping_columns": int(max_mapping_columns),
|
||||
}
|
||||
settings["llm"] = {
|
||||
"enabled": enabled,
|
||||
"active_profile": selected_profile,
|
||||
"profiles": profiles,
|
||||
"auto_apply_confidence": cfg.get("auto_apply_confidence", 0.9),
|
||||
"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")
|
||||
cm._load_settings()
|
||||
st.session_state.llm_status = None
|
||||
st.success("✅ Saved to config/settings.yaml")
|
||||
st.rerun()
|
||||
|
||||
col1, col2 = st.columns([1, 1])
|
||||
with col1:
|
||||
if st.button("🔌 Test current connection", width="stretch"):
|
||||
_test_llm_connection(cm)
|
||||
with col2:
|
||||
if st.button("← Back to App", width="stretch"):
|
||||
st.session_state.current_step = "upload"
|
||||
st.rerun()
|
||||
|
||||
|
||||
def _test_llm_connection(cm: ConfigManager) -> None:
|
||||
"""Test the currently saved LLM config without exposing credentials."""
|
||||
conn = cm.resolve_llm_connection_config()
|
||||
if not conn:
|
||||
st.error("LLM is not configured: enable it and set base URL, model, and one credential source.")
|
||||
return
|
||||
try:
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
verify = conn.get("ssl_verify", False)
|
||||
if not verify:
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
resp = requests.post(
|
||||
conn["base_url"].rstrip("/") + "/chat/completions",
|
||||
headers={
|
||||
"Authorization": f"Bearer {conn['api_key']}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": conn["model"],
|
||||
"messages": [{"role": "user", "content": "say OK"}],
|
||||
"max_tokens": 5,
|
||||
},
|
||||
timeout=10,
|
||||
verify=verify,
|
||||
)
|
||||
if resp.ok:
|
||||
st.success(f"✅ Connection OK ({resp.status_code}) — {conn['model']}")
|
||||
else:
|
||||
st.error(f"❌ {resp.status_code}: {resp.text[:160]}")
|
||||
except requests.exceptions.SSLError as e:
|
||||
st.error(
|
||||
"❌ SSL certificate verification failed. For internal self-signed endpoints, "
|
||||
"turn off certificate verification and save, or install the internal CA certificate.\n\n"
|
||||
f"{e}"
|
||||
)
|
||||
except Exception as e:
|
||||
st.error(f"❌ Cannot connect: {e}")
|
||||
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────
|
||||
|
||||
@st.cache_data
|
||||
|
||||
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user