Compare commits

..

1 Commits

33 changed files with 2606 additions and 2151 deletions

View File

@@ -1,75 +0,0 @@
# Manually bump package version and open a PR to main.
# Actions → Bump version → Run workflow → choose patch / minor / major.
name: Bump version
on:
workflow_dispatch:
inputs:
part:
description: Version part to bump
required: true
type: choice
options:
- patch
- minor
- major
default: patch
permissions:
contents: write
pull-requests: write
concurrency:
group: bump-version
cancel-in-progress: false
jobs:
bump:
runs-on: ubuntu-latest
steps:
- name: Checkout main
uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Bump version
id: bump
run: |
set -euo pipefail
OLD=$(uvx --from bump-my-version bump-my-version show current_version)
uvx --from bump-my-version bump-my-version bump "${{ inputs.part }}" --no-commit --no-tag
NEW=$(uvx --from bump-my-version bump-my-version show current_version)
echo "old=${OLD}" >> "$GITHUB_OUTPUT"
echo "new=${NEW}" >> "$GITHUB_OUTPUT"
echo "Bumped ${OLD} → ${NEW} (${{ inputs.part }})"
- name: Create pull request
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
OLD="${{ steps.bump.outputs.old }}"
NEW="${{ steps.bump.outputs.new }}"
BRANCH="chore/bump-version-${NEW}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git checkout -b "$BRANCH"
git add pyproject.toml
git commit -m "Bump version: ${OLD} → ${NEW}"
git push -u origin "$BRANCH"
gh pr create \
--base main \
--head "$BRANCH" \
--title "Bump version to ${NEW}" \
--body "## Summary
Automated \`${{ inputs.part }}\` bump: \`${OLD}\` → \`${NEW}\`.
Source: \`[project].version\` in \`pyproject.toml\` (via bump-my-version)."

View File

@@ -1,42 +0,0 @@
# Mirror all branches and tags from GitHub → Gitea after every ref change.
# Requires repo secret GITEA_TOKEN (Gitea PAT with write:repository on rhino/xlsx-clean).
name: Mirror to Gitea
on:
push:
delete:
create:
workflow_dispatch:
concurrency:
group: mirror-to-gitea
cancel-in-progress: true
jobs:
mirror:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Mirror repository to Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
if [ -z "${GITEA_TOKEN:-}" ]; then
echo "Missing secret GITEA_TOKEN (Gitea PAT with write:repository)." >&2
exit 1
fi
git clone --mirror \
"https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" \
mirror.git
cd mirror.git
# Push only branches/tags. Never push GitHub refs/pull/* — Gitea
# rejects those with "hook declined" and fails the whole mirror.
git push --prune \
"https://rhino:${GITEA_TOKEN}@git.faryad.top/rhino/xlsx-clean.git" \
"+refs/heads/*:refs/heads/*" \
"+refs/tags/*:refs/tags/*"

View File

@@ -4,7 +4,7 @@
configured directory, clearing/resetting specific cells. Interfaces:
- CLI: `src/xlsx_clean/clean_cells.py` (`beaupy`)
- GUI: `src/xlsx_clean/gui_app.py` (PyWebView cross-platform desktop window with a local HTML/CSS/JS frontend)
- Web UI: `src/xlsx_clean/web_app.py` (NiceGUI; default **native** single window via pywebview)
## Backends
@@ -15,33 +15,40 @@ configured directory, clearing/resetting specific cells. Interfaces:
only). Preserves non-worksheet parts (styles, connections/Power Query definitions,
drawings, etc.). Does not calculate formulas or refresh queries.
Select with `--backend com|ooxml` (CLI) or `config.toml`.
Select with `--backend com|ooxml` (CLI) or the Backend dropdown (web UI).
## Cursor Cloud Specific Instructions
## Cursor Cloud specific instructions
### Platform Notes
### Platform notes
- `pywin32` has no Linux wheels and is declared as Windows-only
(`pywin32>=312; sys_platform == 'win32'`). It is intentionally **not** installed here.
- End-to-end COM automation needs Windows + desktop Excel and does not run on this VM.
- On Linux, the **ooxml** backend can clear/set cells and write a new workbook when
sample files and `XLSX_CLEAN_ROOT` point at a real tree. Without those data files,
interactive selection still works for config loading, but globbing finds no templates.
- PyWebView supports Windows (Edge WebView2), Linux (WebKitGTK), and macOS (WKWebView).
Windows needs the separately-installed Microsoft Edge WebView2 Runtime; `pythonnet`
does not install it. Linux needs `python3-gi`, GTK, and WebKitGTK typelibs; use the
system Python with `--system-site-packages` so apt-provided `gi` remains importable.
- On headless machines without a display server the GUI cannot open a native window.
- NiceGUI defaults to a native window (`pywebview`). On Linux that needs **system**
GTK/WebKit packages (`python3-gi`, `gir1.2-gtk-3.0`, `gir1.2-webkit2-4.1` via apt) —
not installable with `uv`. Prefer `./desktop/setup_linux.sh`, which recreates
`.venv` with **OS** `/usr/bin/python3` (`--no-managed-python --system-site-packages`).
A uv-managed CPython (e.g. from `~/.local/share/uv/python`) cannot load apt
`_gi` even with system-site-packages. `setup_linux.sh` always uses
`/usr/bin/python3`, not PATH `python3`. `.python-version` is `3.12` (minor pin)
so sync can use the OS interpreter. On this headless/cloud VM native mode is
often unavailable; the app falls back to the browser, or use `--no-browser`
/ `--browser`.
### Environment
- Prefer **uv** for all installs (`uv` in `~/.local/bin`, on PATH via `~/.bashrc`).
- Rye is **not** used (`requirements.lock` removed). Use `uv.lock` + `uv sync`.
```bash
# Linux desktop (system WebKitGTK deps + venv + Desktop shortcut):
# Linux desktop (native window + Desktop shortcut):
./desktop/setup_linux.sh
# Dependencies and test tooling (any OS):
# Deps only (any OS). For Linux native window use OS python3, not managed:
uv sync
# or:
uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages && uv sync
```
- Run Python via the venv interpreter: `.venv/bin/python`.
@@ -49,17 +56,19 @@ Select with `--backend com|ooxml` (CLI) or `config.toml`.
- Note: the `uv`-created `.venv` does not include `pip`; use `uv pip ...` / `uv sync`
for package operations.
### Lint / Test / Build
- Tests use `pytest`; run `uv run pytest -q`.
- `pyproject.toml` uses `hatchling` as the build backend; build a wheel with `uv build`.
### Lint / test / build
- There is **no lint config, no test suite, and no build step** in this repo (no ruff/flake8,
no pytest, no CI). Don't invent one unless asked.
- `pyproject.toml` uses `hatchling` as the build backend; there is nothing to "build" for dev.
### Running / Verifying
### Running / verifying
- CLI: `.venv/bin/python -m xlsx_clean.clean_cells` (defaults to `ooxml` on Linux).
- GUI: `.venv/bin/python -m xlsx_clean.gui_app [--width 800 --height 600]`.
- Linux setup: `./desktop/setup_linux.sh` (GTK/WebKitGTK check, uv sync).
- Windows shop-floor: double-click `desktop/Setup.bat` (uv sync), or build
- Web UI: `.venv/bin/python -m xlsx_clean.web_app` (native window) or
`--no-browser` / `--browser` on headless / for default browser.
- Linux setup: `./desktop/setup_linux.sh` (apt + OS Python venv + shortcut).
- Desktop shortcut (Linux): `.venv/bin/python desktop/install_desktop_shortcut.py`
- Windows shop-floor: double-click `desktop/Setup.bat` (uv sync + shortcut), or build
an exe with `desktop/build_windows_exe.bat` **on a Windows PC** (cannot build Windows
exe here).
- Operators create their own shortcut to the GUI launcher (no installer script).
- Sanity-check imports:
`.venv/bin/python -c "import webview, beaupy; from xlsx_clean import hello; from xlsx_clean.core import load_config, list_sets; from xlsx_clean.ooxml_backend import expand_a1_range; print(webview, hello(), expand_a1_range('A1:B2'))"`.
`.venv/bin/python -c "import pandas, beaupy, nicegui; from xlsx_clean import hello; from xlsx_clean.ooxml_backend import expand_a1_range; print(hello(), expand_a1_range('A1:B2'))"`.

114
README.md
View File

@@ -5,26 +5,31 @@ Operator-facing name: **New QC Sheet**.
Create a new QC datasheet from the latest matching workbook: clear configured cells,
blank notes, write the batch serial, and save under a new `[SERIAL]` name.
Everyday use opens a **single app window** (Set -> Ink -> Serial -> Create).
Everyday use is a **Desktop icon** that opens a **single app window**
(Set → Ink → Serial → Create) — not your full browser with all tabs.
No terminal commands are required for operators.
## Quick start (Windows operators)
1. One-time setup (IT / first install): install [uv](https://docs.astral.sh/uv/getting-started/installation/), clone/copy this project, then double-click
1. One-time setup (IT / first install): install [uv](https://docs.astral.sh/uv/getting-started/installation/), clone/copy this project, then double-click
**`desktop\Setup.bat`**
2. Every day: launch the app via the **New QC Sheet** shortcut
2. Every day: double-click the **New QC Sheet** icon on the Desktop
3. In the app window: choose **Set**, **Ink color**, enter **Serial**, click **Create datasheet**
`Setup.bat` creates `.venv` with uv and installs the package. Operators create their own
shortcut to `desktop\XlsxClean.vbs` (uses the modern icon in `desktop\xlsx-clean.ico`).
On Windows, install the Microsoft Edge WebView2 Runtime separately before opening the
PyWebView GUI; `pythonnet` does not install it. The shortcut runs `desktop\XlsxClean.vbs`
which launches the GUI window. Closing that window stops the app.
`Setup.bat` creates `.venv` with uv, installs the package, and adds the Desktop shortcut
(using the modern icon in `desktop\xlsx-clean.ico`).
The shortcut runs `desktop\XlsxClean.vbs` and opens one dedicated window (via pywebview).
Closing that window stops the app.
When you **Create** with the **com** backend, Excel is maximized and brought to the front
after the new workbook is saved.
If something fails, use **`desktop\XlsxClean.bat`** instead - it shows a console with errors.
If something fails, use **`desktop\XlsxClean.bat`** instead — it shows a console with errors.
To force the old “open in default browser” behavior for debugging:
```bat
.venv\Scripts\python.exe -m xlsx_clean.web_app --browser
```
## Standalone Windows exe (optional)
@@ -32,7 +37,7 @@ To put a self-contained app on other PCs (build **on Windows**):
1. Install [uv](https://docs.astral.sh/uv/getting-started/installation/) if needed
2. Double-click **`desktop\build_windows_exe.bat`**
3. It creates `dist\New QC Sheet\New QC Sheet.exe`
3. It creates `dist\New QC Sheet\New QC Sheet.exe` and a Desktop shortcut
4. Copy the whole **`dist\New QC Sheet\`** folder when moving to another machine (keep files together)
## What the app does
@@ -51,7 +56,7 @@ To put a self-contained app on other PCs (build **on Windows**):
| Windows | `com` | Uses Microsoft Excel + add-ins from `strings.txt`; leaves Excel open |
| Linux / macOS | `ooxml` | Surgical `.xlsx` edit; keeps formulas, formatting, and queries on disk |
Choose the backend in the `config.toml` file, or override with CLI `--backend com|ooxml`.
Choose the backend in the web UI dropdown, or with CLI `--backend com\|ooxml`.
**Limits of `ooxml`:** does not refresh Power Query, calculate formulas, or load `.xlam`/`.xla`
add-ins. Open the file in Excel afterward for refresh/calc. Prefer **`com` on Windows** when
@@ -71,35 +76,51 @@ chmod +x desktop/setup_linux.sh
./desktop/setup_linux.sh
```
That installs the required GTK/WebKitGTK packages, creates a venv that can import the
apt-provided `gi` bindings, and runs `uv sync`. It uses WebKit2 4.1 when available and
supports distro packages that provide WebKit2 4.0. Operators create their own shortcut
to `.venv/bin/python -m xlsx_clean.gui_app`.
That installs apt GTK/WebKit packages if needed, recreates `.venv` with
**`/usr/bin/python3`** (`--no-managed-python --system-site-packages` so apt
`python3-gi` / `_gi` loads), runs `uv sync`, and creates a Desktop shortcut.
It ignores PATH `python3` when that points at a uv-managed build under
`~/.local/share/uv/python/` (common with an activated `.venv`).
**Manual / macOS:**
The macOS backend defaults to **`ooxml`** (no Excel/COM on macOS). WKWebView is built into
macOS, so no extra system packages are needed beyond Python 3.12+ and `uv`.
From the project root:
**Manual / macOS** (deps only; on Linux this alone is not enough for a native window):
```bash
uv sync
```
That creates `.venv` and installs locked deps from `uv.lock` (including the `pyobjc`
bindings used by PyWebView).
That creates `.venv` and installs locked deps from `uv.lock`.
To create a double-clickable Finder launcher that runs the GUI:
### Linux single app window (native mode)
Prefer **`./desktop/setup_linux.sh`** (above). Native mode uses **pywebview**,
which needs **system** GTK/WebKit packages (`uv sync` cannot install these).
Manual equivalent:
```bash
chmod +x desktop/XlsxClean.command
# Ubuntu / Debian (names may vary by release: webkit2-4.0 vs 4.1)
sudo apt install python3-gi gir1.2-gtk-3.0 gir1.2-webkit2-4.1
rm -rf .venv
# Must be OS python3 — `uv venv --python python3` may pick a managed build
# that cannot load apt _gi.
uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages
uv sync
.venv/bin/python -m xlsx_clean.web_app
```
Then double-click **`desktop/XlsxClean.command`** in Finder. The first launch may require
right-click → Open (Gatekeeper) once. The script opens the app window in a new Terminal
window; closing that window stops the app. Operators create their own shortcut to this
executable.
If you already have a normal isolated `.venv`, the app will still try to load
system `python3-gi` from `/usr/lib/python3/dist-packages` when those apt packages
are installed. Without GTK/WebKit (or on a headless machine with no display), it
falls back to opening the default browser, or you can force:
```bash
.venv/bin/python -m xlsx_clean.web_app --browser
.venv/bin/python -m xlsx_clean.web_app --no-browser
```
**Windows** native mode uses Edge/WebView2 and does **not** need the apt packages above.
Before building the standalone exe:
@@ -107,17 +128,27 @@ Before building the standalone exe:
uv sync --extra desktop
```
Optional: Edit `~/.xlsx-clean/config.toml` (created automatically on first run) if workbooks are not under the default `D:\\OpenCloud` paths.
Then create the Desktop shortcut (if you did not use `Setup.bat`):
- **Windows:** double-click `desktop\Install-DesktopShortcut.bat`
- **Linux:** `./desktop/setup_linux.sh` (preferred), or
`.venv/bin/python desktop/install_desktop_shortcut.py`
Optional: set `XLSX_CLEAN_ROOT` if workbooks are not under `D:\OpenCloud`
(e.g. `set XLSX_CLEAN_ROOT=D:\OpenCloud` or `export XLSX_CLEAN_ROOT=/mnt/opencloud`).
## Developer interfaces
These are optional; operators use the shortcut to the app executable.
These are optional; operators should use the Desktop icon.
**GUI (desktop window)**
**App window (default: native single window)**
```bash
.venv/bin/python -m xlsx_clean.gui_app --width 800 --height 600
# Windows: .venv\Scripts\python.exe -m xlsx_clean.gui_app --width 800 --height 600
.venv/bin/python -m xlsx_clean.web_app
# Windows: .venv\Scripts\python.exe -m xlsx_clean.web_app
# Optional: open in the default browser instead
.venv/bin/python -m xlsx_clean.web_app --browser
```
**CLI**
@@ -132,19 +163,20 @@ Windows CLI helper: `src\xlsx_clean\new_xslx.bat`
| File | Purpose |
|------|---------|
| `config.toml` | Backend choice and root directory path for each set (auto-generated in `~/.xlsx-clean/` on first run) |
| `src/xlsx_clean/file_data.csv` | Relative product folders, filename patterns, cells to clear/set |
| `src/xlsx_clean/file_data.csv` | Product folders, filename patterns, cells to clear/set |
| `src/xlsx_clean/strings.txt` | UI prompts + Windows Excel add-in paths (`com` only) |
| `XLSX_CLEAN_ROOT` (env) | Replaces the `D:\OpenCloud\...` root in CSV paths |
## Project layout (launchers)
| Path | Purpose |
|------|---------|
| `desktop/xlsx-clean.ico` | Modern Windows Desktop / exe icon |
| `desktop/Setup.bat` | Windows one-time setup via uv |
| `desktop/setup_linux.sh` | Linux one-time setup (uv sync) |
| `desktop/XlsxClean.command` | macOS double-click launcher (opens GUI in Terminal) |
| `desktop/XlsxClean.vbs` | Silent Windows double-click launcher |
| `desktop/XlsxClean.bat` | Windows launcher with visible console |
| `desktop/Setup.bat` | Windows one-time setup via uv + Desktop shortcut |
| `desktop/setup_linux.sh` | Linux one-time setup (apt + OS Python venv + shortcut) |
| `desktop/Install-DesktopShortcut.bat` | Create Desktop icon only (Windows) |
| `desktop/XlsxClean.vbs` | Silent double-click launcher |
| `desktop/XlsxClean.bat` | Launcher with visible console |
| `desktop/build_windows_exe.bat` | Build standalone `New QC Sheet.exe` with uv |
| `desktop/install_desktop_shortcut.py` | Create Desktop shortcut (Linux) |
| `packaging/xlsx_clean.spec` | PyInstaller spec |

View File

@@ -0,0 +1,13 @@
@echo off
REM Create a Desktop shortcut that points at desktop\XlsxClean.vbs
setlocal
cd /d "%~dp0\.."
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-DesktopShortcut.ps1"
if errorlevel 1 (
echo Failed to create desktop shortcut.
pause
exit /b 1
)
echo Desktop shortcut created: New QC Sheet
pause

View File

@@ -0,0 +1,29 @@
# Creates %USERPROFILE%\Desktop\New QC Sheet.lnk -> desktop\XlsxClean.vbs
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$target = Join-Path $PSScriptRoot "XlsxClean.vbs"
$desktop = [Environment]::GetFolderPath("Desktop")
$shortcutPath = Join-Path $desktop "New QC Sheet.lnk"
if (-not (Test-Path $target)) {
throw "Launcher not found: $target"
}
# Remove older shortcut name if present
$legacy = Join-Path $desktop "XlsxClean.lnk"
if (Test-Path $legacy) {
Remove-Item $legacy -Force
}
$wsh = New-Object -ComObject WScript.Shell
$shortcut = $wsh.CreateShortcut($shortcutPath)
$shortcut.TargetPath = $target
$shortcut.WorkingDirectory = $repoRoot
$shortcut.WindowStyle = 7
$shortcut.Description = "Open New QC Sheet"
$iconCandidate = Join-Path $PSScriptRoot "xlsx-clean.ico"
if (Test-Path $iconCandidate) {
$shortcut.IconLocation = "$iconCandidate,0"
}
$shortcut.Save()
Write-Host "Created $shortcutPath"

View File

@@ -1,5 +1,5 @@
@echo off
REM One-time Windows setup with uv: sync deps from uv.lock.
REM One-time Windows setup with uv: sync deps from uv.lock, Desktop shortcut.
setlocal
cd /d "%~dp0\.."
@@ -20,6 +20,14 @@ if errorlevel 1 (
exit /b 1
)
echo Creating Desktop shortcut...
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-DesktopShortcut.ps1"
if errorlevel 1 (
echo Desktop shortcut step failed.
pause
exit /b 1
)
echo.
echo Setup complete. Create your own shortcut to desktop\XlsxClean.vbs.
echo Setup complete. Double-click the New QC Sheet icon on your Desktop.
pause

View File

@@ -1,10 +1,12 @@
@echo off
REM Double-click launcher with visible console (useful for troubleshooting).
REM Default: single native app window. To use the browser instead, add --browser
setlocal
cd /d "%~dp0\.."
set PORT=8080
if exist ".venv\Scripts\python.exe" (
".venv\Scripts\python.exe" -m xlsx_clean.gui_app %*
".venv\Scripts\python.exe" -m xlsx_clean.web_app --host 127.0.0.1 --port %PORT% %*
) else (
py -3 -m xlsx_clean.gui_app %*
py -3 -m xlsx_clean.web_app --host 127.0.0.1 --port %PORT% %*
)

View File

@@ -1,14 +0,0 @@
#!/usr/bin/env bash
# Operator launcher for New QC Sheet on macOS.
# Double-click in Finder (or run from Terminal). Opens the GUI in a new Terminal window.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
if [[ ! -x .venv/bin/python ]]; then
echo "Virtual environment not found. Run 'uv sync' first, or use desktop/setup_macos.sh." >&2
exit 1
fi
exec ./.venv/bin/python -m xlsx_clean.gui_app

View File

@@ -1,13 +1,14 @@
' XlsxClean.vbs - double-click launcher (no console window)
' XlsxClean.vbs — double-click launcher (no console window)
' Resolves repo root from this script's folder (desktop\ -> repo root).
Option Explicit
Dim fso, sh, scriptDir, root, pythonExe, cmd
Dim fso, sh, scriptDir, root, pythonExe, cmd, port
Set fso = CreateObject("Scripting.FileSystemObject")
Set sh = CreateObject("WScript.Shell")
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
root = fso.GetParentFolderName(scriptDir)
port = "8080"
' Prefer project venv, then py launcher, then python on PATH.
pythonExe = root & "\.venv\Scripts\pythonw.exe"
@@ -19,10 +20,10 @@ If Not fso.FileExists(pythonExe) Then
End If
sh.CurrentDirectory = root
' Window style 0 = hidden.
cmd = """" & pythonExe & """ -m xlsx_clean.gui_app"
' Window style 0 = hidden. Opens browser via NiceGUI show=True.
cmd = """" & pythonExe & """ -m xlsx_clean.web_app --host 127.0.0.1 --port " & port
If pythonExe = "py" Then
cmd = "py -3 -m xlsx_clean.gui_app"
cmd = "py -3 -m xlsx_clean.web_app --host 127.0.0.1 --port " & port
End If
sh.Run cmd, 0, False

View File

@@ -0,0 +1,82 @@
"""Install a Desktop shortcut that launches New QC Sheet."""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
DESKTOP_DIR = Path(__file__).resolve().parent
APP_DISPLAY_NAME = "New QC Sheet"
def _user_desktop() -> Path:
if sys.platform == "win32":
return Path(os.environ.get("USERPROFILE", str(Path.home()))) / "Desktop"
# Linux / macOS
xdg = os.environ.get("XDG_DESKTOP_DIR")
if xdg:
return Path(xdg)
return Path.home() / "Desktop"
def install_windows() -> Path:
ps1 = DESKTOP_DIR / "Install-DesktopShortcut.ps1"
subprocess.run(
[
"powershell",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
str(ps1),
],
check=True,
)
return _user_desktop() / f"{APP_DISPLAY_NAME}.lnk"
def install_linux() -> Path:
desktop = _user_desktop()
desktop.mkdir(parents=True, exist_ok=True)
python = REPO_ROOT / ".venv" / "bin" / "python"
if not python.is_file():
python = Path(sys.executable)
out = desktop / f"{APP_DISPLAY_NAME}.desktop"
legacy = desktop / "XlsxClean.desktop"
if legacy.is_file():
legacy.unlink()
exec_line = (
f"{python} -m xlsx_clean.web_app --host 127.0.0.1 --port 8080"
)
icon_png = DESKTOP_DIR / "xlsx-clean.png"
icon_line = str(icon_png) if icon_png.is_file() else "applications-office"
content = f"""[Desktop Entry]
Type=Application
Version=1.0
Name={APP_DISPLAY_NAME}
Comment=Create a new QC datasheet
Exec={exec_line}
Path={REPO_ROOT}
Icon={icon_line}
Terminal=false
Categories=Office;
StartupNotify=true
"""
out.write_text(content, encoding="utf-8")
out.chmod(out.stat().st_mode | 0o111)
return out
def main() -> None:
if sys.platform == "win32":
path = install_windows()
else:
path = install_linux()
print(f"Desktop shortcut created: {path}")
if __name__ == "__main__":
main()

View File

@@ -1,107 +1,131 @@
#!/usr/bin/env bash
# Operator setup for New QC Sheet on Debian/Ubuntu Linux desktops.
# Operator setup for New QC Sheet on Ubuntu/Debian desktops.
# Installs system GTK/WebKit bindings, creates a uv venv that uses the OS
# Python (so apt python3-gi/_gi loads), syncs deps, and installs a Desktop shortcut.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
SYS_PY=/usr/bin/python3
APT_PACKAGES=(python3-gi gir1.2-gtk-3.0 gir1.2-webkit2-4.1)
need_apt=()
for pkg in "${APT_PACKAGES[@]}"; do
if ! dpkg -s "$pkg" >/dev/null 2>&1; then
need_apt+=("$pkg")
fi
done
if ((${#need_apt[@]})); then
echo "Missing system packages for the native window: ${need_apt[*]}"
echo "Installing with apt (sudo)..."
sudo apt-get update
sudo apt-get install -y "${need_apt[@]}"
else
echo "System GTK/WebKit packages already installed."
fi
if ! command -v uv >/dev/null 2>&1; then
echo "uv not found on PATH. Install uv first: https://docs.astral.sh/uv/" >&2
exit 1
fi
if ! command -v apt-get >/dev/null 2>&1; then
echo "This setup script requires apt-get (Debian/Ubuntu). Install python3-gi,"
echo "gir1.2-gtk-3.0, and gir1.2-webkit2-4.1 (or WebKit2 4.0) manually." >&2
exit 1
fi
if [[ ! -x "$SYS_PY" ]]; then
echo "System Python not found at $SYS_PY" >&2
exit 1
fi
packages=(python3-gi gir1.2-gtk-3.0)
if apt-cache show gir1.2-webkit2-4.1 >/dev/null 2>&1; then
packages+=(gir1.2-webkit2-4.1)
elif apt-cache show gir1.2-webkit2-4.0 >/dev/null 2>&1; then
packages+=(gir1.2-webkit2-4.0)
else
echo "Neither gir1.2-webkit2-4.1 nor gir1.2-webkit2-4.0 is available." >&2
exit 1
fi
missing=()
for package in "${packages[@]}"; do
if ! dpkg-query -W -f='${db:Status-Status}' "$package" 2>/dev/null | grep -qx installed; then
missing+=("$package")
fi
done
if ((${#missing[@]})); then
echo "Installing GTK/WebKitGTK requirements: ${missing[*]}"
sudo apt-get update
sudo apt-get install -y "${missing[@]}"
else
echo "GTK/WebKitGTK requirements already installed."
fi
if ! "$SYS_PY" -c 'import gi' >/dev/null 2>&1; then
echo "System $SYS_PY cannot import gi. Install python3-gi." >&2
exit 1
fi
enable_system_site_packages() {
local cfg=.venv/pyvenv.cfg
if [[ ! -f "$cfg" ]]; then
return 1
fi
if grep -q '^include-system-site-packages' "$cfg"; then
sed -i 's/^include-system-site-packages = .*/include-system-site-packages = true/' "$cfg"
else
printf '\ninclude-system-site-packages = true\n' >> "$cfg"
fi
# Must use the OS interpreter that apt's python3-gi/_gi was built for.
# Never use `command -v python3`: with an activated .venv or uv on PATH it often
# resolves to ~/.local/share/uv/python/... which cannot import apt gi.
resolve_os_python() {
local candidate resolved
for candidate in /usr/bin/python3 /usr/local/bin/python3; do
if [[ -x "$candidate" ]]; then
resolved="$(readlink -f "$candidate")"
# Reject uv-managed installs even if somehow symlinked here.
if [[ "$resolved" == *"/uv/python/"* ]] || [[ "$resolved" == *".local/share/uv/"* ]]; then
continue
fi
printf '%s\n' "$resolved"
return 0
fi
done
return 1
}
if [[ ! -x .venv/bin/python ]] || ! .venv/bin/python -c 'import gi' >/dev/null 2>&1; then
echo "Creating venv with the system Python and system site packages..."
rm -rf .venv
uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages
fi
echo "Syncing dependencies..."
# Pin the same interpreter so uv does not honor .python-version (3.12) and
# recreate a managed venv without apt gi (python3-gi).
uv sync --python /usr/bin/python3 --no-managed-python
if ! .venv/bin/python -c 'import gi' >/dev/null 2>&1; then
echo "Restoring system site packages on .venv so apt gi is importable..."
enable_system_site_packages
fi
venv_ver="$(.venv/bin/python -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
sys_ver="$("$SYS_PY" -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
if [[ "$venv_ver" != "$sys_ver" ]]; then
echo "venv Python $venv_ver does not match system Python $sys_ver at $SYS_PY." >&2
echo "uv likely honored .python-version instead of the system interpreter." >&2
if ! SYSTEM_PYTHON="$(resolve_os_python)"; then
echo "OS Python not found at /usr/bin/python3." >&2
echo "Install python3 from apt, then re-run. Do not rely on uv-managed Python." >&2
exit 1
fi
echo "Verifying GTK and WebKit2 bindings..."
.venv/bin/python -c '
SYSTEM_VERSION="$("$SYSTEM_PYTHON" -c 'import sys; print(sys.version.split()[0])')"
echo "Using OS Python: ${SYSTEM_PYTHON} (${SYSTEM_VERSION})"
if PATH_PYTHON="$(command -v python3 2>/dev/null || true)"; then
PATH_PYTHON_RESOLVED="$(readlink -f "$PATH_PYTHON" 2>/dev/null || true)"
if [[ -n "$PATH_PYTHON_RESOLVED" && "$PATH_PYTHON_RESOLVED" != "$SYSTEM_PYTHON" ]]; then
echo "Note: PATH python3 is ${PATH_PYTHON_RESOLVED} (ignored; apt gi needs OS Python)."
fi
fi
echo "Preflight: system Python must import Gtk/WebKit..."
if ! "$SYSTEM_PYTHON" - <<'PY'
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
try:
gi.require_version("WebKit2", "4.1")
except ValueError:
gi.require_version("WebKit2", "4.0")
from gi.repository import Gtk, WebKit2
print("GTK/WebKit2 bindings available")
'
from gi.repository import Gtk, WebKit2 # noqa: F401
print("System gi OK")
PY
then
echo "System Python cannot import Gtk/WebKit. Install:" >&2
echo " sudo apt install ${APT_PACKAGES[*]}" >&2
exit 1
fi
echo "Creating .venv with system-site-packages (OS Python only)..."
rm -rf .venv
# --no-managed-python: refuse uv-managed builds that break apt _gi.
# Also pass it to sync — otherwise uv may recreate .venv from a managed
# download (see .python-version) and undo the system interpreter.
uv venv --python "$SYSTEM_PYTHON" --no-managed-python --system-site-packages
uv sync --python "$SYSTEM_PYTHON" --no-managed-python
echo "Checking native-window bindings in .venv..."
if ! .venv/bin/python - <<'PY'
import sys
sys.path.insert(0, "src")
from xlsx_clean.web_app import (
_linux_has_display,
_linux_webview_libs_available,
_NATIVE_DIAG,
)
ok_libs = _linux_webview_libs_available()
ok_display = _linux_has_display()
print(f"Python: {sys.version.split()[0]} ({sys.executable})")
print(f"GTK/WebKit usable: {ok_libs}")
print(f"Display available: {ok_display}")
if not ok_libs:
if _NATIVE_DIAG:
print(f"Detail: {_NATIVE_DIAG}", file=sys.stderr)
sys.exit(2)
PY
then
echo "ERROR: GTK/WebKit still not usable from .venv." >&2
echo "The venv Python must be the same build as apt python3-gi." >&2
echo "Retry: rm -rf .venv && uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages && uv sync" >&2
exit 1
fi
echo "Native window libraries look OK."
echo "Installing Desktop shortcut..."
.venv/bin/python desktop/install_desktop_shortcut.py
echo
echo "Done. Launch with:"
echo " .venv/bin/python -m xlsx_clean.gui_app"
echo "Create your own shortcut to that command."
echo " .venv/bin/python -m xlsx_clean.web_app"
echo "or use the Desktop shortcut."

View File

@@ -0,0 +1,12 @@
[Desktop Entry]
Type=Application
Version=1.0
Name=New QC Sheet
Comment=Create a new QC datasheet
# Exec is filled by install_desktop_shortcut.py; placeholder for manual edits:
Exec=bash -lc 'cd "$(dirname "%k")/.." && (.venv/bin/python -m xlsx_clean.web_app --host 127.0.0.1 --port 8080)'
Path=
Icon=applications-office
Terminal=false
Categories=Office;
StartupNotify=true

View File

@@ -8,47 +8,37 @@ Or manually:
pyinstaller packaging/xlsx_clean.spec
"""
import os
import sys
from PyInstaller.utils.hooks import collect_all
block_cipher = None
# SPECPATH is set by PyInstaller to the folder containing this spec file
ROOT_DIR = os.path.abspath(os.path.join(SPECPATH, ".."))
datas = [
(os.path.join(ROOT_DIR, "src", "xlsx_clean", "file_data.csv"), "xlsx_clean"),
(os.path.join(ROOT_DIR, "src", "xlsx_clean", "strings.txt"), "xlsx_clean"),
(os.path.join(ROOT_DIR, "src", "xlsx_clean", "fonts"), "xlsx_clean/fonts"),
(os.path.join(ROOT_DIR, "src", "xlsx_clean", "ui"), "xlsx_clean/ui"),
("src/xlsx_clean/file_data.csv", "xlsx_clean"),
("src/xlsx_clean/strings.txt", "xlsx_clean"),
]
binaries = []
hiddenimports = [
"xlsx_clean",
"xlsx_clean.core",
"xlsx_clean.gui_app",
"xlsx_clean.web_app",
"xlsx_clean.clean_cells",
"xlsx_clean.ooxml_backend",
"xlsx_clean.com_backend",
"xlsx_clean.paths",
]
webview_ret = collect_all("webview")
datas += webview_ret[0]
binaries += webview_ret[1]
hiddenimports += webview_ret[2]
tmp_ret = collect_all("nicegui")
datas += tmp_ret[0]
binaries += tmp_ret[1]
hiddenimports += tmp_ret[2]
if sys.platform == "win32":
clr_ret = collect_all("clr_loader")
datas += clr_ret[0]
binaries += clr_ret[1]
hiddenimports += clr_ret[2]
hiddenimports += ["clr", "clr_loader", "pythonnet"]
tmp_ret = collect_all("webview")
datas += tmp_ret[0]
binaries += tmp_ret[1]
hiddenimports += tmp_ret[2]
a = Analysis(
[os.path.join(ROOT_DIR, "src", "xlsx_clean", "gui_app.py")],
pathex=[ROOT_DIR],
["src/xlsx_clean/web_app.py"],
pathex=["."],
binaries=binaries,
datas=datas,
hiddenimports=hiddenimports,
@@ -64,6 +54,7 @@ a = Analysis(
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
# onedir is more reliable than onefile for NiceGUI assets
exe = EXE(
pyz,
a.scripts,
@@ -74,13 +65,13 @@ exe = EXE(
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False,
console=False, # no black console window
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=os.path.join(ROOT_DIR, "desktop", "xlsx-clean.ico"),
icon="desktop/xlsx-clean.ico",
)
coll = COLLECT(

View File

@@ -1,13 +1,15 @@
[project]
name = "xlsx-clean"
version = "1.0.0"
version = "0.1.0"
description = "Create a new QC datasheet from the latest matching workbook"
authors = [
{ name = "Diaco Soltanpour", email = "dyaco8464@yahoo.com" }
]
dependencies = [
"beaupy>=3.12.0",
"pywebview>=5.0",
"nicegui>=3.14.0",
"pandas>=3.0.3",
"pywebview>=6.2.1",
"pywin32>=312; sys_platform == 'win32'",
]
readme = "README.md"
@@ -15,7 +17,7 @@ requires-python = ">=3.12"
[project.scripts]
xlsx-clean = "xlsx_clean.clean_cells:main"
xlsx-clean-gui = "xlsx_clean.gui_app:main"
xlsx-clean-web = "xlsx_clean.web_app:main"
[project.optional-dependencies]
desktop = [
@@ -37,30 +39,5 @@ packages = ["src/xlsx_clean"]
"src/xlsx_clean/strings.txt" = "xlsx_clean/strings.txt"
"src/xlsx_clean/new_xslx.bat" = "xlsx_clean/new_xslx.bat"
[dependency-groups]
test = [
"pytest>=8.0",
]
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.uv]
package = true
default-groups = ["test"]
# Version bumps: `uvx bump-my-version bump patch|minor|major`
# current_version falls back to [project].version above.
[tool.bumpversion]
commit = false
tag = false
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
serialize = ["{major}.{minor}.{patch}"]
message = "Bump version: {current_version} → {new_version}"
tag_name = "v{new_version}"
tag_message = "Bump version: {current_version} → {new_version}"
[[tool.bumpversion.files]]
filename = "pyproject.toml"
search = 'version = "{current_version}"'
replace = 'version = "{new_version}"'

View File

@@ -1,50 +0,0 @@
"""Append-only file logging for QC datasheet creation."""
from __future__ import annotations
import logging
import os
import sys
from pathlib import Path
_LOGGER_NAME = "xlsx_clean.create"
_configured = False
def default_log_path() -> Path:
"""Resolve the log file path.
Order:
1. ``XLSX_CLEAN_LOG`` env var (file path)
2. Next to the frozen executable (PyInstaller)
3. ``~/.xlsx-clean/xlsx-clean.log``
"""
env = os.environ.get("XLSX_CLEAN_LOG")
if env:
return Path(env)
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent / "xlsx-clean.log"
return Path.home() / ".xlsx-clean" / "xlsx-clean.log"
def get_logger() -> logging.Logger:
"""Return a logger that appends timestamped lines to the log file."""
global _configured
logger = logging.getLogger(_LOGGER_NAME)
if not _configured:
log_path = default_log_path()
log_path.parent.mkdir(parents=True, exist_ok=True)
handler = logging.FileHandler(log_path, encoding="utf-8")
handler.setFormatter(
logging.Formatter(
fmt="%(asctime)s %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
_configured = True
return logger

View File

@@ -1,19 +1,200 @@
"""Interactive CLI: select set/ink/serial, create a cleaned QC workbook."""
"""Interactive CLI: copy latest QC workbook, clear cells, stamp serial."""
from __future__ import annotations
import argparse
import shutil
import tempfile
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import pandas
from beaupy import prompt, select
from rich.console import Console
from xlsx_clean.core import (
create_datasheet,
list_ink_colors,
list_sets,
load_config,
from xlsx_clean.paths import (
default_backend,
get_opencloud_root,
package_file,
remap_opencloud_path,
resolve_backend,
)
from xlsx_clean.paths import default_backend, resolve_backend
NEW_VALUE = ""
@dataclass(frozen=True)
class CreateResult:
ok: bool
message: str
template: Path | None = None
destination: Path | None = None
backend: str | None = None
skipped: bool = False
def find_last_workbook(files: list[str]) -> str:
return sorted(files)[-1]
def get_workbook_names(
files: list[str],
batch_serial: str,
source_dir: Path,
pattern: str,
) -> tuple[str, Path]:
last_workbook = find_last_workbook(files)
path_of_the_year = Path(str(source_dir).replace("2025", str(datetime.now().year)))
return last_workbook, path_of_the_year / pattern.replace(
"[SERIAL]", batch_serial.split("/")[0]
)
def load_config() -> tuple[list[str], pandas.DataFrame]:
strings_path = package_file("strings.txt")
with open(strings_path, encoding="utf-8") as f:
content = [line.strip() for line in f.readlines()]
path_df = pandas.read_csv(package_file("file_data.csv"))
root = get_opencloud_root()
path_df["dir"] = [
str(remap_opencloud_path(path, root)) for path in path_df["dir"]
]
return content, path_df
def list_sets(path_df: pandas.DataFrame) -> list[str]:
return list(
path_df.drop_duplicates(subset=["set_name"], keep="first")["set_name"]
)
def list_ink_colors(path_df: pandas.DataFrame, selected_set: str) -> list[str]:
return [
Path(path).stem
for path in list(path_df[path_df["set_name"] == selected_set]["dir"])
]
def create_datasheet(
selected_set: str,
selected_dir: str,
batch_serial: str,
backend: str | None = None,
path_df: pandas.DataFrame | None = None,
addin_paths: list[str] | None = None,
) -> CreateResult:
"""Create a cleaned QC workbook for the given selection.
Shared by the CLI and the NiceGUI web UI.
"""
if not selected_set:
return CreateResult(ok=False, message="Select a set.")
if not selected_dir:
return CreateResult(ok=False, message="Select an ink color.")
if not batch_serial or not str(batch_serial).strip():
return CreateResult(ok=False, message="Enter a serial.")
batch_serial = str(batch_serial).strip()
try:
resolved_backend = resolve_backend(backend)
except (ValueError, RuntimeError) as exc:
return CreateResult(ok=False, message=str(exc))
if path_df is None or addin_paths is None:
content, loaded_df = load_config()
if path_df is None:
path_df = loaded_df
if addin_paths is None:
addin_paths = content[3:5] if len(content) >= 5 else []
matches = path_df[
(path_df["set_name"] == selected_set)
& (path_df["dir"].str.endswith(selected_dir))
]
if matches.empty:
return CreateResult(
ok=False,
message=f"No config row for set={selected_set!r} ink={selected_dir!r}.",
)
row = matches.iloc[0]
path_ = Path(row["dir"])
pattern = row["pattern"]
search_pattern = pattern.replace("[SERIAL]", "*")
files = [str(x) for x in path_.glob(search_pattern) if x.is_file()]
if not files:
return CreateResult(
ok=False,
message=f"No workbooks matching {search_pattern!r} in {path_}",
backend=resolved_backend,
)
ref_workbook_name, new_workbook_name = get_workbook_names(
files, batch_serial, path_, pattern
)
template = Path(ref_workbook_name)
if new_workbook_name.is_file():
return CreateResult(
ok=True,
skipped=True,
message=f"Destination already exists, skipped: {new_workbook_name}",
template=template,
destination=new_workbook_name,
backend=resolved_backend,
)
cells_to_clear = row["cells_to_clear"]
notes_cell = row["notes_cell"]
serial_cell = row["serial_cell"]
try:
if resolved_backend == "com":
from xlsx_clean.com_backend import clean_workbook_com
with tempfile.TemporaryDirectory(prefix="xlsx_clean_") as tmp:
temp_workbook = Path(tmp) / "temp_workbook.xlsx"
shutil.copyfile(ref_workbook_name, temp_workbook)
clean_workbook_com(
source=temp_workbook,
destination=new_workbook_name,
cells_to_clear=cells_to_clear,
notes_cell=notes_cell,
serial_cell=serial_cell,
batch_serial=batch_serial,
addin_paths=addin_paths or [],
notes_value=NEW_VALUE,
)
else:
from xlsx_clean.ooxml_backend import clean_workbook_ooxml
clean_workbook_ooxml(
source=ref_workbook_name,
destination=new_workbook_name,
cells_to_clear=cells_to_clear,
notes_cell=notes_cell,
serial_cell=serial_cell,
batch_serial=batch_serial,
notes_value=NEW_VALUE,
)
except Exception as exc: # noqa: BLE001 - surface to CLI/UI
return CreateResult(
ok=False,
message=f"Failed to create workbook: {exc}",
template=template,
destination=new_workbook_name,
backend=resolved_backend,
)
return CreateResult(
ok=True,
message=f"Wrote {new_workbook_name}",
template=template,
destination=new_workbook_name,
backend=resolved_backend,
)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
@@ -29,58 +210,41 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
default=None,
help=(
"Excel edit backend: 'com' (Windows Excel + add-ins) or "
f"'ooxml' (surgical zip edit). Default: {default_backend()} (Overrides config.toml)."
f"'ooxml' (surgical zip edit). Default: {default_backend()}."
),
)
parser.add_argument(
"--root",
type=str,
default=None,
help="Override the root directory for the selected set.",
)
return parser.parse_args(argv)
def run(argv: list[str] | None = None) -> int:
from pathlib import Path
args = parse_args(argv)
content, rows, config = load_config()
# Validate early so CLI fails fast on unsupported COM.
try:
backend = resolve_backend(args.backend, config.get("backend"))
backend = resolve_backend(args.backend)
except (ValueError, RuntimeError) as exc:
Console().print(f"[red]{exc}[/red]")
return 1
content, path_df = load_config()
q1, q2, q3 = content[0], content[1], content[2]
addin_paths = content[3:5] if len(content) >= 5 else []
console = Console()
console.print(q1)
selected_set = select(list_sets(rows), cursor_style="cyan")
selected_set = select(list_sets(path_df), cursor_style="cyan")
console.print(q2)
selected_dir = select(list_ink_colors(rows, selected_set))
selected_dir = select(list_ink_colors(path_df, selected_set))
console.print(f"Selected: {selected_dir}")
if args.root:
for r in rows:
if r["set_name"] == selected_set:
r["dir"] = str(Path(args.root) / r["rel_dir"])
batch_serial = prompt(q3, target_type=str)
result = create_datasheet(
selected_set=selected_set,
selected_dir=selected_dir,
batch_serial=batch_serial,
backend=backend,
rows=rows,
path_df=path_df,
addin_paths=addin_paths,
config=config,
)
if result.template is not None:

View File

@@ -2,78 +2,17 @@
from __future__ import annotations
import logging
import shutil
import sys
from pathlib import Path
# Excel xlMaximized — avoid win32.constants when gen_py early-binding cache is corrupt.
_XL_MAXIMIZED = -4137
_log = logging.getLogger("xlsx_clean.create")
def _is_gen_py_cache_error(exc: BaseException) -> bool:
"""True for the known corrupt gen_py AttributeError (CLSIDTo*Map missing)."""
if not isinstance(exc, AttributeError):
return False
msg = str(exc)
return "CLSIDToClassMap" in msg or "CLSIDToPackageMap" in msg
def _clear_gen_py_cache() -> Path | None:
"""Remove win32com's generated typelib cache and drop it from sys.modules."""
import win32com
gen_path = Path(win32com.__gen_path__)
for name in [m for m in sys.modules if m.startswith("win32com.gen_py")]:
del sys.modules[name]
if gen_path.is_dir():
shutil.rmtree(gen_path, ignore_errors=True)
return gen_path
return None
def _excel_application():
"""Return Excel.Application, recovering from a corrupt win32com gen_py cache.
``gencache.EnsureDispatch`` writes early-binding wrappers under ``%TEMP%\\gen_py``.
Interrupted or partial writes leave modules without ``CLSIDToClassMap`` /
``CLSIDToPackageMap``; deleting that folder and retrying fixes it (same as the
manual workaround). Falls back to late-bound ``Dispatch`` if rebuild still fails.
"""
import win32com.client as win32
try:
return win32.gencache.EnsureDispatch("Excel.Application")
except AttributeError as exc:
if not _is_gen_py_cache_error(exc):
raise
cleared = _clear_gen_py_cache()
_log.warning(
"Corrupt win32com gen_py cache (%s); cleared %s and retrying",
exc,
cleared or "(missing)",
)
try:
return win32.gencache.EnsureDispatch("Excel.Application")
except AttributeError as retry_exc:
if not _is_gen_py_cache_error(retry_exc):
raise
_log.warning(
"EnsureDispatch still failing after cache clear (%s); using late-bound Dispatch",
retry_exc,
)
return win32.Dispatch("Excel.Application")
def _bring_excel_to_front(excel, workbook) -> None:
"""Maximize and force Excel ahead of other windows (e.g. NiceGUI)."""
import win32com.client as win32
import win32con
import win32gui
excel.Visible = True
excel.WindowState = _XL_MAXIMIZED
excel.WindowState = win32.constants.xlMaximized
try:
workbook.Activate()
except Exception:
@@ -118,12 +57,16 @@ def clean_workbook_com(
maximize: bool = True,
) -> None:
"""Clear/set cells via Excel COM, SaveAs destination, leave Excel open."""
# Lazy import so Linux never loads pywin32 (only needed if callers import helpers).
# Lazy import so Linux never loads pywin32.
import win32com.client as win32
source = Path(source)
destination = Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
excel = _excel_application()
# AttributeError: ... has no attribute 'CLSIDToClassMap'
# https://stackoverflow.com/questions/52889704
excel = win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = visible
workbook = excel.Workbooks.Open(str(source.resolve()))

View File

@@ -1,263 +0,0 @@
"""Core business logic for xlsx_clean."""
from __future__ import annotations
import csv
import shutil
import tempfile
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import tomllib
from xlsx_clean.app_logging import get_logger
from xlsx_clean.paths import (
default_config_path,
package_file,
resolve_backend,
)
DEFAULT_CONFIG_CONTENT = """\
# Configuration for xlsx_clean
# backend options:
# - "com": Use Microsoft Excel COM (Windows only, keeps Excel visible)
# - "ooxml": Surgical zip edit (Cross-platform, very fast, preserves non-worksheet data)
backend = "com"
[sets]
"Kimia Razi" = "D:\\\\OpenCloud\\\\Kimia Razi"
"inco" = "D:\\\\OpenCloud\\\\inco"
"""
NEW_VALUE = ""
@dataclass(frozen=True)
class CreateResult:
ok: bool
message: str
template: Path | None = None
destination: Path | None = None
backend: str | None = None
skipped: bool = False
def find_last_workbook(files: list[str]) -> str:
return sorted(files)[-1]
def get_workbook_names(
files: list[str],
batch_serial: str,
source_dir: Path,
pattern: str,
) -> tuple[str, Path]:
last_workbook = find_last_workbook(files)
path_of_the_year = Path(str(source_dir).replace("2025", str(datetime.now().year)))
return last_workbook, path_of_the_year / pattern.replace(
"[SERIAL]", batch_serial.split("/")[0]
)
def load_config() -> tuple[list[str], list[dict], dict]:
config_path = default_config_path()
if not config_path.exists():
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(DEFAULT_CONFIG_CONTENT, encoding="utf-8")
with open(config_path, "rb") as f:
config = tomllib.load(f)
strings_path = package_file("strings.txt")
with open(strings_path, encoding="utf-8") as f:
content = [line.strip() for line in f.readlines()]
csv_path = package_file("file_data.csv")
rows = []
set_roots = config.get("sets", {})
with open(csv_path, encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
set_name = row["set_name"]
rel_dir = row["dir"].replace("\\", "/")
row["rel_dir"] = rel_dir
root_str = set_roots.get(set_name, "")
if root_str:
row["dir"] = str(Path(root_str) / rel_dir)
else:
row["dir"] = str(Path(rel_dir))
rows.append(row)
return content, rows, config
def list_sets(rows: list[dict]) -> list[str]:
return list(dict.fromkeys(r["set_name"] for r in rows))
import re
def _sort_key(name: str):
match = re.search(r'\d+', name)
num = int(match.group()) if match else 0
return (num, name)
def list_ink_colors(rows: list[dict], selected_set: str) -> list[str]:
inks = (Path(r["dir"]).stem for r in rows if r["set_name"] == selected_set)
return sorted(inks, key=_sort_key)
def create_datasheet(
selected_set: str,
selected_dir: str,
batch_serial: str,
backend: str | None = None,
rows: list[dict] | None = None,
addin_paths: list[str] | None = None,
config: dict | None = None,
) -> CreateResult:
log = get_logger()
ctx = f"set={selected_set!r} ink={selected_dir!r} serial={batch_serial!r}"
if not selected_set:
message = "Select a set."
log.error("Create failed: %s (%s)", message, ctx)
return CreateResult(ok=False, message=message)
if not selected_dir:
message = "Select an ink color."
log.error("Create failed: %s (%s)", message, ctx)
return CreateResult(ok=False, message=message)
if not batch_serial or not str(batch_serial).strip():
message = "Enter a serial."
log.error("Create failed: %s (%s)", message, ctx)
return CreateResult(ok=False, message=message)
batch_serial = str(batch_serial).strip()
ctx = f"set={selected_set!r} ink={selected_dir!r} serial={batch_serial!r}"
if config is None:
content, loaded_rows, config = load_config()
if rows is None:
rows = loaded_rows
if addin_paths is None:
addin_paths = content[3:5] if len(content) >= 5 else []
try:
resolved_backend = resolve_backend(backend, config.get("backend"))
except (ValueError, RuntimeError) as exc:
log.error("Create failed: %s (%s)", exc, ctx)
return CreateResult(ok=False, message=str(exc))
ctx = f"{ctx} backend={resolved_backend}"
matches = [r for r in rows if r["set_name"] == selected_set and r["dir"].endswith(selected_dir)]
if not matches:
message = f"No config row for set={selected_set!r} ink={selected_dir!r}."
log.error("Create failed: %s (%s)", message, ctx)
return CreateResult(ok=False, message=message)
row = matches[0]
path_ = Path(row["dir"])
pattern = row["pattern"]
search_pattern = pattern.replace("[SERIAL]", "*")
files = [str(x) for x in path_.glob(search_pattern) if x.is_file()]
if not files:
message = f"No workbooks matching {search_pattern!r} in {path_}"
log.error("Create failed: %s (%s)", message, ctx)
return CreateResult(
ok=False,
message=message,
backend=resolved_backend,
)
ref_workbook_name, new_workbook_name = get_workbook_names(
files, batch_serial, path_, pattern
)
template = Path(ref_workbook_name)
if new_workbook_name.is_file():
message = f"Destination already exists, skipped: {new_workbook_name}"
log.info(
"Create skipped: %s (template=%s destination=%s %s)",
message,
template,
new_workbook_name,
ctx,
)
return CreateResult(
ok=True,
skipped=True,
message=message,
template=template,
destination=new_workbook_name,
backend=resolved_backend,
)
cells_to_clear = row["cells_to_clear"]
notes_cell = row["notes_cell"]
serial_cell = row["serial_cell"]
try:
if resolved_backend == "com":
from xlsx_clean.com_backend import clean_workbook_com
with tempfile.TemporaryDirectory(prefix="xlsx_clean_") as tmp:
temp_workbook = Path(tmp) / "temp_workbook.xlsx"
shutil.copyfile(ref_workbook_name, temp_workbook)
clean_workbook_com(
source=temp_workbook,
destination=new_workbook_name,
cells_to_clear=cells_to_clear,
notes_cell=notes_cell,
serial_cell=serial_cell,
batch_serial=batch_serial,
addin_paths=addin_paths or [],
notes_value=NEW_VALUE,
)
else:
from xlsx_clean.ooxml_backend import clean_workbook_ooxml
clean_workbook_ooxml(
source=ref_workbook_name,
destination=new_workbook_name,
cells_to_clear=cells_to_clear,
notes_cell=notes_cell,
serial_cell=serial_cell,
batch_serial=batch_serial,
notes_value=NEW_VALUE,
)
except Exception as exc: # noqa: BLE001 - surface to CLI/UI
message = f"Failed to create workbook: {exc}"
log.exception(
"Create failed: %s (template=%s destination=%s %s)",
message,
template,
new_workbook_name,
ctx,
)
return CreateResult(
ok=False,
message=message,
template=template,
destination=new_workbook_name,
backend=resolved_backend,
)
message = f"Wrote {new_workbook_name}"
log.info(
"Create succeeded: %s (template=%s destination=%s %s)",
message,
template,
new_workbook_name,
ctx,
)
return CreateResult(
ok=True,
message=message,
template=template,
destination=new_workbook_name,
backend=resolved_backend,
)

View File

@@ -1,25 +1,25 @@
dir,pattern,set_name,cells_to_clear,serial_cell,notes_cell
Production\QC Datasheet\1403\KRCY1100T Blue,KRCY1100T Blue [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRBK1300T Black,KRBK1300T Black [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRBK1314T Black,KRBK1314T Black [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!G12:I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRBR1200T Brown,KRBR1200T Brown [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRBR1201T Brown,KRBR1201T Brown [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRYL1400T Yellow,KRYL1400T Yellow [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRYL1401T Yellow,KRYL1401T Yellow [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRBG1600T Beige,KRBG1600T Beige [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRPK1500T Pink,KRPK1500T Pink [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
Production\QC Datasheet\1403\KRHN1700T Honey,KRHN1700T Honey [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
Quality control data sheet\2025\ICJ108 Beige,ICJ_108 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2026\ICJ610 Black,ICJ_610 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2026\ICJ308 Blue,ICJ_308 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2026\ICJEH680 Black,ICJ_EH680 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2026\ICJEH630 Black,ICJ_EH630 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2025\ICJEH600 Black,ICJ_EH600 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2025\ICJ407 Brown,ICJ_407 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D24
Quality control data sheet\2025\ICJ408 Brown,ICJ_408 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D24
Quality control data sheet\2026\ICJ435 Beige,ICJ_435 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D24
Quality control data sheet\2025\ICJ107 Yellow,ICJ_107 yellow op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2025\ICJ703 Pink,ICJ_703 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2024\ICJ309 Cyan,ICJ_309 cyan op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2025\ICJ109 Golden Yellow,ICJ_109 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
Quality control data sheet\2026\ICJ152 Yellow,ICJ_152 yellow op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
dir,pattern,set_name,cells_to_clear,serial_cell,notes_cell
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRCY1100T Blue","KRCY1100T Blue [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBK1300T Black","KRBK1300T Black [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBK1314T Black","KRBK1314T Black [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12:I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBR1200T Brown","KRBR1200T Brown [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBR1201T Brown","KRBR1201T Brown [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRYL1400T Yellow","KRYL1400T Yellow [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRYL1401T Yellow","KRYL1401T Yellow [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBG1600T Beige","KRBG1600T Beige [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRPK1500T Pink","KRPK1500T Pink [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRHN1700T Honey","KRHN1700T Honey [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ108 Beige","ICJ_108 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJ610 Black","ICJ_610 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJ308 Blue","ICJ_308 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJEH680 Black","ICJ_EH680 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJEH630 Black","ICJ_EH630 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJEH600 Black","ICJ_EH600 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ407 Brown","ICJ_407 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D24"
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ408 Brown","ICJ_408 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D24"
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJ435 Beige","ICJ_435 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D24"
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ107 Yellow","ICJ_107 yellow op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ703 Pink","ICJ_703 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2024\ICJ309 Cyan","ICJ_309 cyan op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ109 Golden Yellow","ICJ_109 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJ152 Yellow","ICJ_152 yellow op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
1 dir pattern set_name cells_to_clear serial_cell notes_cell
2 Production\QC Datasheet\1403\KRCY1100T Blue D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRCY1100T Blue KRCY1100T Blue [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11 Batch!D3 Batch!D25
3 Production\QC Datasheet\1403\KRBK1300T Black D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBK1300T Black KRBK1300T Black [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11 Batch!D3 Batch!D25
4 Production\QC Datasheet\1403\KRBK1314T Black D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBK1314T Black KRBK1314T Black [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!G12:I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11 Batch!D3 Batch!D25
5 Production\QC Datasheet\1403\KRBR1200T Brown D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBR1200T Brown KRBR1200T Brown [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11 Batch!D3 Batch!D25
6 Production\QC Datasheet\1403\KRBR1201T Brown D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBR1201T Brown KRBR1201T Brown [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11 Batch!D3 Batch!D25
7 Production\QC Datasheet\1403\KRYL1400T Yellow D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRYL1400T Yellow KRYL1400T Yellow [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11 Batch!D3 Batch!D25
8 Production\QC Datasheet\1403\KRYL1401T Yellow D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRYL1401T Yellow KRYL1401T Yellow [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11 Batch!D3 Batch!D25
9 Production\QC Datasheet\1403\KRBG1600T Beige D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBG1600T Beige KRBG1600T Beige [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11 Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11 Batch!D3 Batch!D25
10 Production\QC Datasheet\1403\KRPK1500T Pink D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRPK1500T Pink KRPK1500T Pink [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11 Batch!D3 Batch!D25
11 Production\QC Datasheet\1403\KRHN1700T Honey D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRHN1700T Honey KRHN1700T Honey [SERIAL].xlsx Kimia Razi Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11 Batch!D3 Batch!D25
12 Quality control data sheet\2025\ICJ108 Beige D:\OpenCloud\inco\Quality control data sheet\2025\ICJ108 Beige ICJ_108 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
13 Quality control data sheet\2026\ICJ610 Black D:\OpenCloud\inco\Quality control data sheet\2026\ICJ610 Black ICJ_610 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
14 Quality control data sheet\2026\ICJ308 Blue D:\OpenCloud\inco\Quality control data sheet\2026\ICJ308 Blue ICJ_308 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
15 Quality control data sheet\2026\ICJEH680 Black D:\OpenCloud\inco\Quality control data sheet\2026\ICJEH680 Black ICJ_EH680 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
16 Quality control data sheet\2026\ICJEH630 Black D:\OpenCloud\inco\Quality control data sheet\2026\ICJEH630 Black ICJ_EH630 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
17 Quality control data sheet\2025\ICJEH600 Black D:\OpenCloud\inco\Quality control data sheet\2025\ICJEH600 Black ICJ_EH600 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
18 Quality control data sheet\2025\ICJ407 Brown D:\OpenCloud\inco\Quality control data sheet\2025\ICJ407 Brown ICJ_407 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D24
19 Quality control data sheet\2025\ICJ408 Brown D:\OpenCloud\inco\Quality control data sheet\2025\ICJ408 Brown ICJ_408 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D24
20 Quality control data sheet\2026\ICJ435 Beige D:\OpenCloud\inco\Quality control data sheet\2026\ICJ435 Beige ICJ_435 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D24
21 Quality control data sheet\2025\ICJ107 Yellow D:\OpenCloud\inco\Quality control data sheet\2025\ICJ107 Yellow ICJ_107 yellow op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
22 Quality control data sheet\2025\ICJ703 Pink D:\OpenCloud\inco\Quality control data sheet\2025\ICJ703 Pink ICJ_703 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
23 Quality control data sheet\2024\ICJ309 Cyan D:\OpenCloud\inco\Quality control data sheet\2024\ICJ309 Cyan ICJ_309 cyan op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
24 Quality control data sheet\2025\ICJ109 Golden Yellow D:\OpenCloud\inco\Quality control data sheet\2025\ICJ109 Golden Yellow ICJ_109 op. [SERIAL].xlsx inco Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25
25 Quality control data sheet\2026\ICJ152 Yellow D:\OpenCloud\inco\Quality control data sheet\2026\ICJ152 Yellow ICJ_152 yellow op. [SERIAL].xlsx inco Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11 Batch!D3 Batch!D25

Binary file not shown.

View File

@@ -1,139 +0,0 @@
"""PyWebView desktop GUI for New QC Sheet."""
from __future__ import annotations
import argparse
from importlib.metadata import PackageNotFoundError, version as package_version
import webview
from xlsx_clean.core import create_datasheet, list_ink_colors, list_sets, load_config
from xlsx_clean.app_logging import get_logger
from xlsx_clean.paths import package_file
try:
_VERSION = package_version("xlsx-clean")
except PackageNotFoundError:
_VERSION = "dev"
class Api:
"""Python functions exposed to JavaScript via ``window.pywebview.api``."""
def __init__(self) -> None:
self.rows: list[dict] = []
self.addin_paths: list[str] = []
self.config: dict = {}
self._initial_data: dict | None = None
self._initialization_error: Exception | None = None
def initialize(self) -> None:
"""Load configuration before the local frontend is opened."""
if self._initial_data is not None or self._initialization_error is not None:
return
try:
content, self.rows, self.config = load_config()
sets = list_sets(self.rows)
self.addin_paths = content[3:5] if len(content) >= 5 else []
self._initial_data = {
"sets": sets,
"inks": list_ink_colors(self.rows, sets[0]) if sets else [],
"labels": {
"set": content[0] if len(content) > 0 else "Select Set",
"ink": content[1] if len(content) > 1 else "Select Ink Color",
"serial": content[2] if len(content) > 2 else "Serial:",
},
"version": _VERSION,
}
except Exception as exc: # noqa: BLE001 - serialize bridge failures to JS
self._initialization_error = exc
def get_initial_data(self) -> dict:
"""Return configuration-derived values for the initial page render."""
self.initialize()
if self._initialization_error is not None:
raise self._initialization_error
assert self._initial_data is not None
return self._initial_data
def get_inks(self, selected_set: str) -> list[str]:
"""Return ink colors for a selected set."""
return list_ink_colors(self.rows, selected_set)
def create(
self, selected_set: str, selected_dir: str, batch_serial: str
) -> dict:
"""Create a datasheet and return a JSON-safe result.
Unexpected exceptions are serialized into the result contract so the
frontend always sees the same shape, regardless of platform-specific
bridge behavior.
"""
log = get_logger()
try:
result = create_datasheet(
selected_set=selected_set,
selected_dir=selected_dir,
batch_serial=batch_serial,
backend=None,
rows=self.rows,
addin_paths=self.addin_paths,
config=self.config,
)
except Exception as exc: # noqa: BLE001 - serialize bridge failures to JS
log.exception(
"Unexpected error in Api.create(set=%r, dir=%r, serial=%r)",
selected_set,
selected_dir,
batch_serial,
)
return {
"ok": False,
"skipped": False,
"message": f"Unexpected error: {exc}",
"template": None,
"destination": None,
"backend": None,
}
return {
"ok": result.ok,
"skipped": result.skipped,
"message": result.message,
"template": str(result.template) if result.template is not None else None,
"destination": (
str(result.destination) if result.destination is not None else None
),
"backend": result.backend,
}
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse GUI dimensions without changing process-global arguments."""
parser = argparse.ArgumentParser(
description="Start the New QC Sheet PyWebView interface."
)
parser.add_argument("--width", type=int, default=800, help="Window width")
parser.add_argument("--height", type=int, default=600, help="Window height")
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> None:
"""Open the native PyWebView window."""
args = parse_args(argv)
api = Api()
api.initialize()
index_html = package_file("ui/index.html")
webview.create_window(
title=f"New QC Sheet · v{_VERSION}",
url=index_html.as_uri(),
js_api=api,
width=args.width,
height=args.height,
min_size=(450, 400),
background_color="#0b0e14",
)
webview.start()
if __name__ == "__main__":
main()

View File

@@ -19,29 +19,52 @@ def _package_dir() -> Path:
PACKAGE_DIR = _package_dir()
# Historical Windows root used in file_data.csv
DEFAULT_OPENCLOUD_ROOT = Path(r"D:\OpenCloud")
OPENCLOUD_MARKER = "OpenCloud"
def package_file(name: str) -> Path:
return PACKAGE_DIR / name
def default_config_path() -> Path:
"""Resolve the default location for the TOML configuration file."""
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent / "config.toml"
return Path.home() / ".xlsx-clean" / "config.toml"
def get_opencloud_root() -> Path:
"""Workbook tree root from XLSX_CLEAN_ROOT, else D:\\OpenCloud on Windows."""
env = os.environ.get("XLSX_CLEAN_ROOT")
if env:
return Path(env)
return DEFAULT_OPENCLOUD_ROOT
def remap_opencloud_path(path_str: str, root: Path | None = None) -> Path:
"""Map a CSV path under OpenCloud onto the configured root.
Examples:
D:\\OpenCloud\\inco\\... + root=/data -> /data/inco/...
Relative paths without OpenCloud are returned as-is (Path).
"""
if root is None:
root = get_opencloud_root()
normalized = path_str.replace("\\", "/")
# Case-insensitive marker search
lower = normalized.lower()
marker = f"{OPENCLOUD_MARKER.lower()}/"
idx = lower.find(marker)
if idx != -1:
rel = normalized[idx + len(marker) :]
return root / rel
# Already relative to root-style path without drive
return Path(path_str)
def default_backend() -> str:
return "com" if sys.platform == "win32" else "ooxml"
def resolve_backend(requested: str | None, config_backend: str | None = None) -> str:
"""Resolve backend using explicitly requested, config file, or system default."""
if requested:
backend = requested.lower()
elif config_backend:
backend = config_backend.lower()
else:
backend = default_backend().lower()
def resolve_backend(requested: str | None) -> str:
backend = (requested or default_backend()).lower()
if backend not in {"com", "ooxml"}:
raise ValueError(f"Unknown backend {backend!r}; use 'com' or 'ooxml'")
if backend == "com" and sys.platform != "win32":

View File

@@ -1,758 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>New QC Sheet</title>
<script>
try {
if (localStorage.getItem("xlsx-clean-theme") === "light") {
document.documentElement.setAttribute("data-theme", "light");
}
} catch (error) {
/* localStorage may be unavailable in some WebView embeds */
}
</script>
<style>
@font-face {
font-family: "Inter";
src: url("../fonts/Inter-Regular.ttf") format("truetype");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Inter";
src: url("../fonts/Inter-Bold.ttf") format("truetype");
font-weight: 700;
font-style: normal;
font-display: swap;
}
:root {
--primary: #e54d5e;
--primary-hover: #c93d4e;
--accent: #6366f1;
--accent-2: #8b5cf6;
--accent-3: #a855f7;
--success: #22c55e;
--warning: #f59e0b;
--error: #ef4444;
--bg: #0b0e14;
--bg-alt: #111520;
--surface: #161b22;
--surface-2: #1c2230;
--border: rgba(255, 255, 255, 0.08);
--border-strong: rgba(255, 255, 255, 0.14);
--grid-line: rgba(255, 255, 255, 0.06);
--grid-size: 32px;
--text: #e6e6ef;
--text-muted: #8b8b9e;
--text-dim: #5a5a6e;
--grad-brand: linear-gradient(135deg, var(--primary), var(--accent-3));
--grad-soft: linear-gradient(135deg, rgba(229, 77, 94, 0.12), rgba(168, 85, 247, 0.12));
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
--font-mono: ui-monospace, "JetBrains Mono", "Fira Code", "SF Mono", monospace;
--radius: 14px;
--radius-sm: 9px;
--ease: cubic-bezier(0.22, 1, 0.36, 1);
--status-ready: transparent;
--status-success: rgba(34, 197, 94, 0.12);
--status-skipped: rgba(245, 158, 11, 0.12);
--status-error: rgba(239, 68, 68, 0.12);
--label-bg: rgba(11, 14, 20, 0.5);
}
html[data-theme="light"] {
--bg: #f9f9fb;
--bg-alt: #f0f0f5;
--surface: #ffffff;
--surface-2: #f5f5fa;
--border: rgba(0, 0, 0, 0.08);
--border-strong: rgba(0, 0, 0, 0.14);
--grid-line: rgba(0, 0, 0, 0.07);
--text: #1a1a2e;
--text-muted: #71717a;
--text-dim: #9a9aa5;
--grad-soft: linear-gradient(135deg, rgba(229, 77, 94, 0.08), rgba(168, 85, 247, 0.08));
--status-success: rgba(34, 197, 94, 0.1);
--status-skipped: rgba(245, 158, 11, 0.12);
--status-error: rgba(239, 68, 68, 0.1);
--label-bg: rgba(249, 249, 251, 0.5);
}
* { box-sizing: border-box; }
body {
min-height: 100vh;
margin: 0;
background: var(--bg);
color: var(--text);
font-family: var(--font-sans);
font-size: 15px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
body::before {
content: "";
position: fixed;
inset: 0;
z-index: -1;
pointer-events: none;
background-image:
linear-gradient(to right, var(--grid-line) 1px, transparent 1px),
linear-gradient(to bottom, var(--grid-line) 1px, transparent 1px);
background-size: var(--grid-size) var(--grid-size);
}
.page {
display: flex;
min-height: 100vh;
padding: 24px;
}
.panel {
display: flex;
flex-direction: column;
width: min(100%, 36rem);
margin: auto;
background: transparent;
}
.heading-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.theme-toggle {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
min-width: 52px;
height: 28px;
margin-top: 2px;
padding: 0 8px;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--surface-2);
color: var(--text);
cursor: pointer;
font: inherit;
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
line-height: 1;
}
.theme-toggle:hover {
background: var(--bg-alt);
border-color: var(--border-strong);
}
.theme-toggle:focus-visible {
outline: 2px solid var(--accent-3);
outline-offset: 2px;
}
.eyebrow {
margin: 0 0 8px;
color: var(--primary);
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
h1 {
margin: 0;
color: var(--text);
font-size: 1.875rem;
font-weight: 700;
line-height: 1.15;
letter-spacing: -0.02em;
}
.subtitle {
margin: 8px 0 22px;
color: var(--text-muted);
line-height: 1.5;
}
.fields { display: grid; gap: 18px; }
.field {
position: relative;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
}
.field-label {
z-index: 1;
margin-left: 4px;
padding: 0 4px;
background: var(--label-bg);
color: var(--primary);
font-size: 0.75rem;
line-height: 1.2;
pointer-events: none;
}
select, input {
width: 100%;
align-self: stretch;
min-height: 54px;
padding: 16px 12px;
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
outline: none;
background: var(--surface-2);
color: var(--text);
font: inherit;
transition: border-color 150ms var(--ease), box-shadow 150ms var(--ease);
}
.combobox-input {
padding-right: 36px;
cursor: text;
}
.combobox { position: relative; }
.combobox > select {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
border: 0;
background: transparent;
}
.combobox-caret {
position: absolute;
right: 12px;
bottom: 0;
display: flex;
align-items: center;
height: 54px;
color: var(--text-muted);
pointer-events: none;
font-size: 0.75rem;
}
.combobox-panel {
position: absolute;
top: calc(100% + 4px);
left: 0;
right: 0;
z-index: 5;
max-height: 220px;
overflow-y: auto;
padding: 4px 0;
background: var(--surface-2);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
box-shadow: 0 12px 32px rgb(0 0 0 / 35%);
}
.combobox-panel[hidden] { display: none; }
.combobox-option {
padding: 8px 12px;
cursor: pointer;
color: var(--text);
line-height: 1.25;
}
.combobox-option[aria-selected="true"],
.combobox-option:hover {
background: var(--grad-soft);
color: var(--text);
}
.combobox-option[hidden] { display: none; }
.combobox-empty {
padding: 8px 12px;
color: var(--text-muted);
font-style: italic;
}
select:focus, input:focus,
.combobox-input:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgb(99 102 241 / 28%);
}
select:disabled, input:disabled,
.combobox-input:disabled {
cursor: not-allowed;
background: var(--bg-alt);
color: var(--text-dim);
}
.divider {
height: 1px;
margin: 22px 0;
background: var(--border);
}
#create-button {
width: 100%;
min-height: 44px;
border: 0;
border-radius: var(--radius-sm);
background: var(--grad-brand);
color: #fff;
cursor: pointer;
font: inherit;
font-size: 0.875rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
box-shadow: 0 8px 22px -10px var(--primary);
transition: transform 150ms var(--ease), box-shadow 150ms var(--ease), filter 150ms var(--ease);
}
#create-button:hover:not(:disabled) {
filter: brightness(1.06);
box-shadow: 0 10px 26px -8px var(--primary);
}
#create-button:focus-visible {
outline: 2px solid var(--accent-3);
outline-offset: 2px;
}
#create-button:disabled { cursor: not-allowed; opacity: 0.65; }
.status {
min-height: 48px;
margin-top: 16px;
padding: 12px;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--text-muted);
font-family: var(--font-mono);
font-size: 0.8rem;
line-height: 1.45;
white-space: pre-wrap;
}
.status::before {
content: "$ ";
color: var(--primary);
font-weight: 700;
}
.status-ready { background: var(--status-ready); }
.status-success { background: var(--status-success); color: var(--success); }
.status-skipped { background: var(--status-skipped); color: var(--warning); }
.status-error { background: var(--status-error); color: var(--error); }
.version {
margin-top: 16px;
color: var(--text-dim);
font-family: var(--font-mono);
font-size: 0.75rem;
text-align: right;
}
@media (max-width: 480px) {
.page { padding: 14px; }
h1 { font-size: 1.5rem; }
}
</style>
</head>
<body>
<main class="page">
<section class="panel" aria-labelledby="heading">
<div class="heading-row">
<div>
<p class="eyebrow">QC datasheet</p>
<h1 id="heading">New QC Sheet</h1>
</div>
<button
id="theme-toggle"
class="theme-toggle"
type="button"
aria-label="Switch to light theme"
title="Switch theme">
Aa
</button>
</div>
<p class="subtitle">Create a new QC datasheet from the latest matching workbook.</p>
<div class="fields">
<label class="field combobox" for="set-dropdown-input">
<span id="set-label" class="field-label">Select Set</span>
<input
id="set-dropdown-input"
class="combobox-input"
type="text"
autocomplete="off"
spellcheck="false"
role="combobox"
aria-expanded="false"
aria-controls="set-dropdown-panel"
aria-autocomplete="list"
aria-labelledby="set-label"
placeholder=" ">
<select id="set-dropdown" aria-labelledby="set-label" tabindex="-1"></select>
<span class="combobox-caret" aria-hidden="true">&#9662;</span>
<div id="set-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="set-label" hidden></div>
</label>
<label class="field combobox" for="ink-dropdown-input">
<span id="ink-label" class="field-label">Select Ink Color</span>
<input
id="ink-dropdown-input"
class="combobox-input"
type="text"
autocomplete="off"
spellcheck="false"
role="combobox"
aria-expanded="false"
aria-controls="ink-dropdown-panel"
aria-autocomplete="list"
aria-labelledby="ink-label"
placeholder=" ">
<select id="ink-dropdown" aria-labelledby="ink-label" tabindex="-1"></select>
<span class="combobox-caret" aria-hidden="true">&#9662;</span>
<div id="ink-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="ink-label" hidden></div>
</label>
<label class="field" for="serial-input">
<span id="serial-label" class="field-label">Serial:</span>
<input id="serial-input" type="text" placeholder="e.g. 1234/A" aria-labelledby="serial-label">
</label>
</div>
<div class="divider"></div>
<button id="create-button" type="button">Create datasheet</button>
<div id="status" class="status status-ready" role="status">Loading configuration...</div>
<p id="version" class="version"></p>
</section>
</main>
<script>
const setDropdown = document.getElementById("set-dropdown");
const inkDropdown = document.getElementById("ink-dropdown");
const setInput = document.getElementById("set-dropdown-input");
const inkInput = document.getElementById("ink-dropdown-input");
const setPanel = document.getElementById("set-dropdown-panel");
const inkPanel = document.getElementById("ink-dropdown-panel");
const serialInput = document.getElementById("serial-input");
const createBtn = document.getElementById("create-button");
const status = document.getElementById("status");
const themeToggle = document.getElementById("theme-toggle");
function isLightTheme() {
return document.documentElement.getAttribute("data-theme") === "light";
}
function syncThemeToggle() {
const light = isLightTheme();
themeToggle.setAttribute(
"aria-label",
light ? "Switch to dark theme" : "Switch to light theme"
);
themeToggle.textContent = light ? "Dark" : "Light";
}
function applyTheme(theme) {
if (theme === "light") {
document.documentElement.setAttribute("data-theme", "light");
} else {
document.documentElement.removeAttribute("data-theme");
}
try {
localStorage.setItem("xlsx-clean-theme", theme);
} catch (error) {
/* ignore quota / privacy mode */
}
syncThemeToggle();
}
themeToggle.addEventListener("click", () => {
applyTheme(isLightTheme() ? "dark" : "light");
});
syncThemeToggle();
// Builds a searchable combobox. The underlying <select> stays as the
// semantic source of truth; the visible widget is a text <input> plus a
// listbox panel that filters options as the user types.
function createCombobox(selectEl, inputEl, panelEl) {
let openState = false;
let inputDirty = false;
const visibleOptions = () =>
Array.from(panelEl.querySelectorAll(".combobox-option")).filter(
(node) => !node.hidden
);
const open = () => {
if (openState || inputEl.disabled) return;
openState = true;
panelEl.hidden = false;
inputEl.setAttribute("aria-expanded", "true");
filter();
};
const close = () => {
if (!openState) return;
openState = false;
panelEl.hidden = true;
inputEl.setAttribute("aria-expanded", "false");
inputEl.removeAttribute("aria-activedescendant");
for (const node of panelEl.querySelectorAll(".combobox-option")) {
node.setAttribute("aria-selected", "false");
}
};
const setActive = (idx) => {
const options = visibleOptions();
for (const node of panelEl.querySelectorAll(".combobox-option")) {
node.setAttribute("aria-selected", "false");
}
if (idx < 0 || idx >= options.length) {
inputEl.removeAttribute("aria-activedescendant");
return;
}
const node = options[idx];
node.setAttribute("aria-selected", "true");
node.scrollIntoView({ block: "nearest" });
inputEl.setAttribute("aria-activedescendant", node.id);
};
const filter = () => {
const needle = inputDirty ? inputEl.value.trim().toLowerCase() : "";
let firstVisible = -1;
let count = 0;
for (const node of panelEl.querySelectorAll(".combobox-option")) {
const value = (node.dataset.value || "").toLowerCase();
const match = !needle || value.includes(needle);
node.hidden = !match;
if (match) {
if (firstVisible === -1) firstVisible = count;
count += 1;
}
}
const empty = panelEl.querySelector(".combobox-empty");
if (empty) empty.hidden = count > 0;
setActive(firstVisible === -1 ? -1 : 0);
};
const selectValue = (value) => {
if (selectEl.value !== value) {
selectEl.value = value;
selectEl.dispatchEvent(new Event("change", { bubbles: true }));
}
inputEl.value = value;
inputDirty = false;
close();
inputEl.focus();
};
const syncDisabled = () => {
inputEl.disabled = selectEl.disabled;
if (selectEl.disabled) close();
};
const rebuild = () => {
panelEl.replaceChildren();
const values = Array.from(selectEl.options).map((o) => o.value);
for (const value of values) {
const node = document.createElement("div");
node.className = "combobox-option";
node.id = `${selectEl.id}-opt-${CSS.escape(value)}`;
node.setAttribute("role", "option");
node.setAttribute("aria-selected", "false");
node.dataset.value = value;
node.textContent = value;
node.addEventListener("mousedown", (event) => {
// mousedown (not click) so we beat the input's blur handler.
event.preventDefault();
selectValue(value);
});
panelEl.append(node);
}
const empty = document.createElement("div");
empty.className = "combobox-empty";
empty.textContent = "No matches";
empty.hidden = true;
panelEl.append(empty);
inputEl.value = selectEl.value || "";
inputDirty = false;
syncDisabled();
};
inputEl.addEventListener("focus", open);
inputEl.addEventListener("mousedown", () => {
open();
});
inputEl.addEventListener("input", () => {
inputDirty = true;
if (!openState) open();
filter();
});
inputEl.addEventListener("blur", () => {
// Defer close so a mousedown on a panel option can fire first.
setTimeout(() => {
if (inputEl.value !== selectEl.value) {
inputEl.value = selectEl.value || "";
inputDirty = false;
}
close();
}, 0);
});
inputEl.addEventListener("keydown", (event) => {
const options = visibleOptions();
if (event.key === "ArrowDown") {
event.preventDefault();
if (!openState) open();
const idx = options.findIndex(
(n) => n.getAttribute("aria-selected") === "true"
);
setActive(Math.min(idx + 1, options.length - 1));
} else if (event.key === "ArrowUp") {
event.preventDefault();
if (!openState) open();
const idx = options.findIndex(
(n) => n.getAttribute("aria-selected") === "true"
);
setActive(Math.max(idx - 1, 0));
} else if (event.key === "Home") {
if (openState) {
event.preventDefault();
setActive(0);
}
} else if (event.key === "End") {
if (openState) {
event.preventDefault();
setActive(options.length - 1);
}
} else if (event.key === "Enter") {
if (openState) {
event.preventDefault();
const node = panelEl.querySelector(
'.combobox-option[aria-selected="true"]'
);
if (node) selectValue(node.dataset.value);
}
} else if (event.key === "Escape") {
if (openState) {
event.preventDefault();
close();
}
}
});
// Click outside closes the panel.
document.addEventListener("mousedown", (event) => {
if (!openState) return;
if (!inputEl.parentElement.contains(event.target)) close();
});
return { rebuild, syncDisabled };
}
const setCombobox = createCombobox(setDropdown, setInput, setPanel);
const inkCombobox = createCombobox(inkDropdown, inkInput, inkPanel);
function populateDropdown(dropdown, combobox, values) {
dropdown.replaceChildren();
for (const value of values) {
const option = document.createElement("option");
option.value = value;
option.textContent = value;
dropdown.append(option);
}
dropdown.disabled = values.length === 0;
combobox.rebuild();
}
function populateDropdowns(sets, inks) {
populateDropdown(setDropdown, setCombobox, sets);
populateDropdown(inkDropdown, inkCombobox, inks);
}
function populateInkDropdown(inks) {
populateDropdown(inkDropdown, inkCombobox, inks);
}
function setLabels(labels) {
document.getElementById("set-label").textContent = labels.set;
document.getElementById("ink-label").textContent = labels.ink;
document.getElementById("serial-label").textContent = labels.serial;
}
function setVersion(version) {
document.getElementById("version").textContent = `v${version}`;
}
function showStatus(result) {
const details = [result.message];
if (result.template) details.push(`Template: ${result.template}`);
if (result.destination) details.push(`Output: ${result.destination}`);
if (result.backend) details.push(`Backend: ${result.backend}`);
status.textContent = details.join("\n");
status.className = "status";
if (result.skipped) {
status.classList.add("status-skipped");
} else if (result.ok) {
status.classList.add("status-success");
} else {
status.classList.add("status-error");
}
}
async function initialize() {
try {
const data = await window.pywebview.api.get_initial_data();
populateDropdowns(data.sets, data.inks);
setLabels(data.labels);
setVersion(data.version);
showStatus({ message: "Ready.", ok: true, skipped: false });
} catch (error) {
showStatus({ message: `Failed to load configuration: ${error}`, ok: false, skipped: false });
createBtn.disabled = true;
}
}
setDropdown.addEventListener("change", async () => {
try {
const inks = await window.pywebview.api.get_inks(setDropdown.value);
populateInkDropdown(inks);
} catch (error) {
showStatus({ message: `Failed to load ink colors: ${error}`, ok: false, skipped: false });
}
});
createBtn.addEventListener("click", async () => {
createBtn.disabled = true;
try {
const result = await window.pywebview.api.create(
setDropdown.value, inkDropdown.value, serialInput.value
);
showStatus(result);
} catch (error) {
showStatus({ message: `Failed to create datasheet: ${error}`, ok: false, skipped: false });
} finally {
createBtn.disabled = false;
}
});
window.addEventListener("pywebviewready", initialize);
</script>
</body>
</html>

335
src/xlsx_clean/web_app.py Normal file
View File

@@ -0,0 +1,335 @@
"""NiceGUI web UI for selecting set / ink / serial and creating a datasheet."""
from __future__ import annotations
import argparse
import os
import sys
from importlib.metadata import PackageNotFoundError, version as package_version
from nicegui import ui
from xlsx_clean.clean_cells import (
create_datasheet,
list_ink_colors,
list_sets,
load_config,
)
from xlsx_clean.paths import default_backend
APP_DISPLAY_NAME = "New QC Sheet"
_PACKAGE_NAME = "xlsx-clean"
def _app_version() -> str:
"""Installed package version from metadata (pyproject.toml)."""
try:
return package_version(_PACKAGE_NAME)
except PackageNotFoundError:
return "0.1.0"
def _app_title(version: str | None = None) -> str:
ver = version if version is not None else _app_version()
return f"{APP_DISPLAY_NAME} · {ver}"
# Last native-check diagnostic (Python version + import/typelib error).
_NATIVE_DIAG: str | None = None
def _linux_native_hint(detail: str | None = None) -> str:
lines = [
"Linux native window needs system GTK/WebKit packages "
"(uv cannot install them), e.g.:",
" sudo apt install python3-gi gir1.2-gtk-3.0 gir1.2-webkit2-4.1",
"Recommended one-shot setup:",
" ./desktop/setup_linux.sh",
"Recreate the venv with the OS Python (not a uv-managed build):",
" rm -rf .venv && uv venv --python /usr/bin/python3 "
"--no-managed-python --system-site-packages && uv sync",
]
if detail:
lines.append(f"Detail: {detail}")
detail_l = detail.lower()
if "_gi" in detail_l or "partially initialized" in detail_l:
lines.append(
"This usually means the venv Python does not match apt "
"python3-gi (uv-managed CPython on PATH, e.g. "
"~/.local/share/uv/python/...). Re-run ./desktop/setup_linux.sh "
"so .venv uses /usr/bin/python3 (not PATH python3)."
)
lines.append(
"Falling back to the default browser. "
"Use --no-browser for server-only."
)
return "\n".join(lines)
def _linux_has_display() -> bool:
return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
def _linux_system_dist_packages() -> list[str]:
"""Debian/Ubuntu (and similar) PyGObject install locations."""
major, minor = sys.version_info[:2]
return [
"/usr/lib/python3/dist-packages",
f"/usr/lib/python{major}.{minor}/dist-packages",
f"/usr/local/lib/python{major}.{minor}/dist-packages",
]
def _ensure_linux_system_gi_path() -> None:
"""Make system python3-gi visible inside an isolated uv/venv.
apt installs PyGObject into dist-packages; plain `uv sync` venvs do not
include system site-packages, so `import gi` fails and NiceGUI falls back
to the browser. Exposing dist-packages is enough when typelibs are installed.
"""
if not sys.platform.startswith("linux"):
return
for path in _linux_system_dist_packages():
if os.path.isdir(path) and path not in sys.path:
sys.path.append(path)
def _gi_gtk_webkit_probe() -> str | None:
"""Return None if pywebview's GTK backend is usable, else an error detail."""
try:
import gi
except ImportError as exc:
return f"import gi failed ({exc})"
try:
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
except (ValueError, AttributeError) as exc:
return f"Gtk/Gdk typelib unavailable ({exc})"
try:
gi.require_version("WebKit2", "4.1")
except ValueError:
try:
gi.require_version("WebKit2", "4.0")
except ValueError as exc:
return f"WebKit2 typelib unavailable ({exc})"
return None
def _linux_webview_libs_available() -> bool:
"""True if GTK (gi) or Qt (qtpy) Python bindings are usable for pywebview."""
global _NATIVE_DIAG
_ensure_linux_system_gi_path()
gi_err = _gi_gtk_webkit_probe()
if gi_err is None:
_NATIVE_DIAG = None
return True
try:
import qtpy # noqa: F401
_NATIVE_DIAG = None
return True
except ImportError as qt_exc:
_NATIVE_DIAG = (
f"Python {sys.version.split()[0]}; {gi_err}; "
f"qtpy also unavailable ({qt_exc})"
)
return False
def _native_mode_available() -> bool:
"""Whether pywebview is likely able to open a native window."""
global _NATIVE_DIAG
if sys.platform == "win32" or sys.platform == "darwin":
_NATIVE_DIAG = None
return True
if sys.platform.startswith("linux"):
if not _linux_has_display():
_NATIVE_DIAG = (
f"Python {sys.version.split()[0]}; "
"no DISPLAY/WAYLAND_DISPLAY (headless?)"
)
return False
return _linux_webview_libs_available()
return _linux_webview_libs_available()
def _build_page() -> None:
content, path_df = load_config()
q1, q2, q3 = content[0], content[1], content[2]
sets = list_sets(path_df)
initial_set = sets[0] if sets else None
initial_inks = list_ink_colors(path_df, initial_set) if initial_set else []
app_version = _app_version()
ui.page_title(_app_title(app_version))
ui.colors(primary="#0f766e", secondary="#115e59", accent="#14b8a6")
with ui.column().classes("w-full max-w-xl mx-auto p-6 gap-4"):
ui.label(APP_DISPLAY_NAME).classes("text-3xl font-bold text-teal-800")
ui.label(
"Create a new QC datasheet from the latest matching workbook."
).classes("text-gray-600")
ink_ref: dict = {}
def on_set_change(e) -> None:
selected = e.value
inks = list_ink_colors(path_df, selected) if selected else []
ink = ink_ref["select"]
ink.options = inks
ink.value = inks[0] if inks else None
ink.update()
set_select = ui.select(
options=sets,
value=initial_set,
label=q1,
with_input=True,
on_change=on_set_change,
).classes("w-full")
ink_select = ui.select(
options=initial_inks,
value=initial_inks[0] if initial_inks else None,
label=q2,
with_input=True,
).classes("w-full")
ink_ref["select"] = ink_select
serial_input = ui.input(label=q3, placeholder="e.g. 1234/A").classes("w-full")
backend_select = ui.select(
options=["ooxml", "com"],
value=default_backend(),
label="Backend",
).classes("w-full")
if sys.platform != "win32":
ui.label(
"COM backend requires Windows with Microsoft Excel; use ooxml here."
).classes("text-sm text-amber-700")
status = ui.markdown("Ready.").classes("w-full p-3 rounded bg-gray-50")
def on_create() -> None:
result = create_datasheet(
selected_set=set_select.value or "",
selected_dir=ink_select.value or "",
batch_serial=serial_input.value or "",
backend=backend_select.value,
path_df=path_df,
addin_paths=content[3:5] if len(content) >= 5 else [],
)
lines = [result.message]
if result.template is not None:
lines.append(f"**Template:** `{result.template.name}`")
if result.destination is not None:
lines.append(f"**Output:** `{result.destination}`")
if result.backend is not None:
lines.append(f"**Backend:** `{result.backend}`")
status.set_content("\n\n".join(lines))
if result.ok and not result.skipped:
status.classes(replace="w-full p-3 rounded bg-teal-50")
elif result.skipped:
status.classes(replace="w-full p-3 rounded bg-amber-50")
else:
status.classes(replace="w-full p-3 rounded bg-red-50")
ui.button("Create datasheet", on_click=on_create).props("unelevated").classes(
"w-full"
)
ui.label(f"v{app_version}").classes(
"w-full text-right text-xs text-gray-400"
)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=f"Start the {APP_DISPLAY_NAME} NiceGUI interface."
)
parser.add_argument(
"--host",
default="127.0.0.1",
help="Bind address (default: 127.0.0.1).",
)
parser.add_argument(
"--port",
type=int,
default=8080,
help="Port (default: 8080; native mode may pick a free port).",
)
parser.add_argument(
"--reload",
action="store_true",
help="Enable NiceGUI auto-reload (dev only; ignored in native mode).",
)
mode = parser.add_mutually_exclusive_group()
mode.add_argument(
"--browser",
action="store_true",
help="Open in the default web browser instead of a native app window.",
)
mode.add_argument(
"--no-browser",
action="store_true",
help="Run the server only; do not open a window or browser.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> None:
args = parse_args(argv)
_build_page()
frozen = getattr(sys, "frozen", False)
use_native = not args.browser and not args.no_browser
if use_native and not _native_mode_available():
if os.environ.get("XLSX_CLEAN_NATIVE_FALLBACK") != "1":
print(_linux_native_hint(_NATIVE_DIAG), file=sys.stderr)
os.environ["XLSX_CLEAN_NATIVE_FALLBACK"] = "1"
use_native = False
args.browser = True
run_kwargs: dict = {
"host": args.host,
"port": args.port,
"reload": False if frozen or use_native else args.reload,
"title": _app_title(),
}
if args.no_browser:
run_kwargs["show"] = False
run_kwargs["native"] = False
elif use_native:
# Single dedicated window (pywebview), not the default browser with tabs.
run_kwargs["native"] = True
run_kwargs["window_size"] = (900, 700)
run_kwargs["show"] = False
else:
run_kwargs["show"] = True
run_kwargs["native"] = False
try:
ui.run(**run_kwargs)
except Exception as exc:
# Native mode can still fail at runtime (e.g. missing WebKit gir).
msg = str(exc).lower()
if run_kwargs.get("native") and (
"gtk" in msg or "qt" in msg or "webview" in msg or "gi" in msg
):
print(
_linux_native_hint(
f"Python {sys.version.split()[0]}; native start failed: {exc}"
),
file=sys.stderr,
)
run_kwargs["native"] = False
run_kwargs.pop("window_size", None)
run_kwargs["show"] = True
run_kwargs["reload"] = False if frozen else args.reload
ui.run(**run_kwargs)
else:
raise
if __name__ in {"__main__", "__mp_main__"}:
# NiceGUI may re-import as __mp_main__ when reload is enabled.
main()

View File

@@ -1,105 +0,0 @@
"""Tests for win32com gen_py cache recovery (no real Excel required)."""
from __future__ import annotations
import sys
from types import ModuleType, SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from xlsx_clean.com_backend import (
_clear_gen_py_cache,
_excel_application,
_is_gen_py_cache_error,
)
def _install_fake_win32com(*, ensure, dispatch=None, gen_path="/tmp/gen_py"):
"""Put fake win32com + win32com.client modules into sys.modules."""
win32com = ModuleType("win32com")
win32com.__gen_path__ = gen_path
client = ModuleType("win32com.client")
client.gencache = SimpleNamespace(EnsureDispatch=ensure)
client.Dispatch = dispatch if dispatch is not None else MagicMock()
return patch.dict(sys.modules, {"win32com": win32com, "win32com.client": client})
def test_is_gen_py_cache_error_matches_known_messages():
assert _is_gen_py_cache_error(
AttributeError(
"module 'win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9' "
"has no attribute 'CLSIDToPackageMap'"
)
)
assert _is_gen_py_cache_error(
AttributeError("... has no attribute 'CLSIDToClassMap'")
)
assert not _is_gen_py_cache_error(AttributeError("something else"))
assert not _is_gen_py_cache_error(RuntimeError("CLSIDToPackageMap"))
def test_clear_gen_py_cache_removes_modules_and_directory(tmp_path):
gen_root = tmp_path / "gen_py"
bad = gen_root / "00020813-0000-0000-C000-000000000046x0x1x9"
bad.mkdir(parents=True)
(bad / "__init__.py").write_text("# corrupt", encoding="utf-8")
mod_name = "win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9"
fake_mod = ModuleType(mod_name)
fake_win32com = ModuleType("win32com")
fake_win32com.__gen_path__ = str(gen_root)
with patch.dict(sys.modules, {"win32com": fake_win32com, mod_name: fake_mod}):
cleared = _clear_gen_py_cache()
assert cleared == gen_root
assert not gen_root.exists()
assert mod_name not in sys.modules
def test_excel_application_clears_cache_and_retries_ensure_dispatch():
excel = object()
ensure = MagicMock(
side_effect=[
AttributeError(
"module 'win32com.gen_py.00020813x0x1x9' has no attribute 'CLSIDToPackageMap'"
),
excel,
]
)
with (
_install_fake_win32com(ensure=ensure),
patch("xlsx_clean.com_backend._clear_gen_py_cache", return_value=None) as clear,
):
result = _excel_application()
assert result is excel
assert ensure.call_count == 2
clear.assert_called_once_with()
def test_excel_application_falls_back_to_dispatch_after_second_failure():
excel = object()
err = AttributeError("has no attribute 'CLSIDToClassMap'")
ensure = MagicMock(side_effect=[err, err])
dispatch = MagicMock(return_value=excel)
with (
_install_fake_win32com(ensure=ensure, dispatch=dispatch),
patch("xlsx_clean.com_backend._clear_gen_py_cache", return_value=None),
):
result = _excel_application()
assert result is excel
dispatch.assert_called_once_with("Excel.Application")
def test_excel_application_rethrows_unrelated_attribute_error():
ensure = MagicMock(side_effect=AttributeError("unrelated"))
with (
_install_fake_win32com(ensure=ensure),
pytest.raises(AttributeError, match="unrelated"),
):
_excel_application()

View File

@@ -1,127 +0,0 @@
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from xlsx_clean.gui_app import Api
def test_initial_data_stores_state_and_uses_first_set_inks():
rows = [{"set_name": "Set A"}]
config = {"backend": "ooxml"}
with patch(
"xlsx_clean.gui_app.load_config",
return_value=(["Set", "Ink", "Serial", "addin-a", "addin-b"], rows, config),
), patch("xlsx_clean.gui_app.list_sets", return_value=["Set A"]), patch(
"xlsx_clean.gui_app.list_ink_colors", return_value=["Blue"]
) as inks:
api = Api()
data = api.get_initial_data()
assert data["sets"] == ["Set A"]
assert data["inks"] == ["Blue"]
assert data["labels"] == {"set": "Set", "ink": "Ink", "serial": "Serial"}
assert api.rows == rows
assert api.addin_paths == ["addin-a", "addin-b"]
assert api.config == config
inks.assert_called_once_with(rows, "Set A")
def test_initial_data_uses_safe_label_fallbacks_and_empty_inks():
with (
patch("xlsx_clean.gui_app.load_config", return_value=([], [], {})),
patch("xlsx_clean.gui_app.list_sets", return_value=[]),
patch("xlsx_clean.gui_app.list_ink_colors") as inks,
):
data = Api().get_initial_data()
assert data["labels"] == {
"set": "Select Set",
"ink": "Select Ink Color",
"serial": "Serial:",
}
assert data["inks"] == []
inks.assert_not_called()
def test_get_inks_uses_initialized_rows():
api = Api()
api.rows = [{"set_name": "Set A"}]
with patch("xlsx_clean.gui_app.list_ink_colors", return_value=["Blue"]) as inks:
assert api.get_inks("Set A") == ["Blue"]
inks.assert_called_once_with(api.rows, "Set A")
def test_create_passes_core_arguments_and_serializes_paths():
api = Api()
api.rows = [{"set_name": "Set A"}]
api.addin_paths = ["addin-a"]
api.config = {"backend": "ooxml"}
result = SimpleNamespace(
ok=True,
skipped=False,
message="Wrote workbook",
template=Path("template.xlsx"),
destination=Path("output.xlsx"),
backend="ooxml",
)
with patch("xlsx_clean.gui_app.create_datasheet", return_value=result) as create:
response = api.create("Set A", "Blue", "1234/A")
create.assert_called_once_with(
selected_set="Set A",
selected_dir="Blue",
batch_serial="1234/A",
backend=None,
rows=api.rows,
addin_paths=api.addin_paths,
config=api.config,
)
assert response == {
"ok": True,
"skipped": False,
"message": "Wrote workbook",
"template": "template.xlsx",
"destination": "output.xlsx",
"backend": "ooxml",
}
def test_create_serializes_missing_paths_for_error_or_skipped_result():
api = Api()
result = SimpleNamespace(
ok=False,
skipped=False,
message="Select a set.",
template=None,
destination=None,
backend=None,
)
with patch("xlsx_clean.gui_app.create_datasheet", return_value=result):
response = api.create("", "", "")
assert response["template"] is None
assert response["destination"] is None
assert response["ok"] is False
def test_create_serializes_unexpected_exceptions_into_result_contract():
api = Api()
api.rows = [{"set_name": "Set A"}]
api.addin_paths = []
api.config = {"backend": "ooxml"}
def boom(**kwargs):
raise RuntimeError("backend exploded")
with patch("xlsx_clean.gui_app.create_datasheet", side_effect=boom):
response = api.create("Set A", "Blue", "1234/A")
assert response == {
"ok": False,
"skipped": False,
"message": "Unexpected error: backend exploded",
"template": None,
"destination": None,
"backend": None,
}

View File

@@ -1,44 +0,0 @@
from pathlib import Path
from unittest.mock import MagicMock, patch
from xlsx_clean import gui_app
def test_parse_args_uses_default_dimensions():
args = gui_app.parse_args([])
assert (args.width, args.height) == (800, 600)
def test_main_initializes_api_before_opening_window():
index_html = Path("/tmp/index.html")
events = []
api = MagicMock()
def create_window(**kwargs):
events.append(("create_window", kwargs))
with (
patch("xlsx_clean.gui_app.Api", return_value=api),
patch("xlsx_clean.gui_app.package_file", return_value=index_html) as package_file,
patch("xlsx_clean.gui_app.webview.create_window", side_effect=create_window),
patch("xlsx_clean.gui_app.webview.start", side_effect=lambda: events.append(("start",))),
):
gui_app.main(["--width", "900", "--height", "700"])
package_file.assert_called_once_with("ui/index.html")
api.initialize.assert_called_once_with()
assert events == [
(
"create_window",
{
"title": f"New QC Sheet · v{gui_app._VERSION}",
"url": index_html.as_uri(),
"js_api": api,
"width": 900,
"height": 700,
"min_size": (450, 400),
"background_color": "#0b0e14",
},
),
("start",),
]

View File

@@ -1,14 +0,0 @@
from pathlib import Path
def test_pyinstaller_spec_collects_webview_and_local_assets():
spec = Path("packaging/xlsx_clean.spec").read_text(encoding="utf-8")
assert 'collect_all("webview")' in spec
assert 'collect_all("dearpygui")' not in spec
assert '"ui"), "xlsx_clean/ui")' in spec
assert '"fonts"), "xlsx_clean/fonts")' in spec
assert 'if sys.platform == "win32":' in spec
assert 'collect_all("clr_loader")' in spec
for hidden_import in ('"clr"', '"clr_loader"', '"pythonnet"'):
assert hidden_import in spec

View File

@@ -1,19 +0,0 @@
from pathlib import Path
def test_setup_linux_pins_system_python_for_uv_sync():
script = Path("desktop/setup_linux.sh").read_text(encoding="utf-8")
assert "uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages" in script
sync_lines = [
line.strip()
for line in script.splitlines()
if line.strip().startswith("uv sync")
]
assert sync_lines == [
"uv sync --python /usr/bin/python3 --no-managed-python"
]
assert "--python-preference" not in script
assert "uv sync --active" not in script
assert "include-system-site-packages = true" in script

View File

@@ -1,63 +0,0 @@
import re
from html.parser import HTMLParser
from pathlib import Path
from xlsx_clean.paths import package_file
class StrictHtmlParser(HTMLParser):
def error(self, message):
raise AssertionError(message)
def test_ui_asset_exists_and_has_required_bridge_content():
html_path = package_file("ui/index.html")
assert html_path.is_file()
content = html_path.read_text(encoding="utf-8")
for expected in (
"New QC Sheet",
"Create a new QC datasheet from the latest matching workbook.",
'id="set-label"',
'id="ink-label"',
'id="serial-label"',
"Create datasheet",
"status-ready",
"status-success",
"status-skipped",
"status-error",
'id="version"',
"pywebviewready",
"get_initial_data()",
"get_inks(setDropdown.value)",
"api.create(",
"finally",
'inputEl.value = selectEl.value || ""',
'inputEl.addEventListener("mousedown", () => {\n open();\n });',
):
assert expected in content
assert "tailwind" not in content.lower()
assert "quasar" not in content.lower()
assert "cdn" not in content.lower()
assert not re.search(r"https?://", content)
assert "#0b0e14" in content
assert "#e54d5e" in content
assert "background-size: var(--grid-size) var(--grid-size)" in content
assert "background: transparent" in content
assert "tl-red" not in content
assert 'class="chrome"' not in content
StrictHtmlParser().feed(content)
def test_ui_font_sources_are_bundled_locally():
content = package_file("ui/index.html").read_text(encoding="utf-8")
font_urls = re.findall(r'url\("([^\"]+\.ttf)"\)', content)
assert font_urls == ["../fonts/Inter-Regular.ttf", "../fonts/Inter-Bold.ttf"]
for font_url in font_urls:
assert (package_file("ui") / font_url).resolve().is_file()
def test_demo_html_is_not_shipped():
assert not Path("desktop/demo.html").exists()

1723
uv.lock generated

File diff suppressed because it is too large Load Diff