Compare commits
7 Commits
cursor/fil
...
bump-versi
| Author | SHA1 | Date | |
|---|---|---|---|
| 95e0acbe71 | |||
| a39cccb0dc | |||
| 5d827ae70d | |||
|
|
8ee6cebea3 | ||
| a07d3b46dc | |||
|
|
78d1a0a5fc | ||
| 89bb9689e9 |
75
.github/workflows/bump-version.yml
vendored
Normal file
75
.github/workflows/bump-version.yml
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
# 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)."
|
||||
29
AGENTS.md
29
AGENTS.md
@@ -4,7 +4,7 @@
|
||||
configured directory, clearing/resetting specific cells. Interfaces:
|
||||
|
||||
- CLI: `src/xlsx_clean/clean_cells.py` (`beaupy`)
|
||||
- Web UI: `src/xlsx_clean/web_app.py` (NiceGUI; default **native** single window via pywebview)
|
||||
- GUI: `src/xlsx_clean/gui_app.py` (Dear PyGui cross-platform desktop window)
|
||||
|
||||
## Backends
|
||||
|
||||
@@ -15,7 +15,7 @@ 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 the Backend dropdown (web UI).
|
||||
Select with `--backend com|ooxml` (CLI) or the Backend dropdown (GUI).
|
||||
|
||||
## Cursor Cloud specific instructions
|
||||
|
||||
@@ -26,29 +26,19 @@ Select with `--backend com|ooxml` (CLI) or the Backend dropdown (web UI).
|
||||
- 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.
|
||||
- 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`.
|
||||
- The Dear PyGui GUI runs cross-platform with no system dependencies beyond Python.
|
||||
On headless VMs without a display server the GUI cannot open a window.
|
||||
|
||||
### 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 (native window + Desktop shortcut):
|
||||
# Linux desktop (deps + Desktop shortcut):
|
||||
./desktop/setup_linux.sh
|
||||
|
||||
# Deps only (any OS). For Linux native window use OS python3, not managed:
|
||||
# Deps only (any OS):
|
||||
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`.
|
||||
@@ -63,12 +53,11 @@ Select with `--backend com|ooxml` (CLI) or the Backend dropdown (web UI).
|
||||
|
||||
### Running / verifying
|
||||
- CLI: `.venv/bin/python -m xlsx_clean.clean_cells` (defaults to `ooxml` on Linux).
|
||||
- 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).
|
||||
- GUI: `.venv/bin/python -m xlsx_clean.gui_app`.
|
||||
- Linux setup: `./desktop/setup_linux.sh` (uv sync + 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).
|
||||
- Sanity-check imports:
|
||||
`.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'))"`.
|
||||
`.venv/bin/python -c "import dearpygui, 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(hello(), expand_a1_range('A1:B2'))"`.
|
||||
|
||||
75
README.md
75
README.md
@@ -6,30 +6,25 @@ Create a new QC datasheet from the latest matching workbook: clear configured ce
|
||||
blank notes, write the batch serial, and save under a new `[SERIAL]` name.
|
||||
|
||||
Everyday use is a **Desktop icon** that opens a **single app window**
|
||||
(Set → Ink → Serial → Create) — not your full browser with all tabs.
|
||||
(Set -> Ink -> Serial -> Create).
|
||||
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: double-click the **New QC Sheet** icon on the Desktop
|
||||
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, 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).
|
||||
The shortcut runs `desktop\XlsxClean.vbs` which launches the GUI window.
|
||||
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.
|
||||
To force the old “open in default browser” behavior for debugging:
|
||||
|
||||
```bat
|
||||
.venv\Scripts\python.exe -m xlsx_clean.web_app --browser
|
||||
```
|
||||
If something fails, use **`desktop\XlsxClean.bat`** instead - it shows a console with errors.
|
||||
|
||||
## Standalone Windows exe (optional)
|
||||
|
||||
@@ -56,7 +51,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 web UI dropdown, or with CLI `--backend com\|ooxml`.
|
||||
Choose the backend in the `config.toml` file, or override 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
|
||||
@@ -76,13 +71,9 @@ chmod +x desktop/setup_linux.sh
|
||||
./desktop/setup_linux.sh
|
||||
```
|
||||
|
||||
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`).
|
||||
That runs `uv sync` and creates a Desktop shortcut.
|
||||
|
||||
**Manual / macOS** (deps only; on Linux this alone is not enough for a native window):
|
||||
**Manual / macOS:**
|
||||
|
||||
```bash
|
||||
uv sync
|
||||
@@ -90,38 +81,6 @@ uv sync
|
||||
|
||||
That creates `.venv` and installs locked deps from `uv.lock`.
|
||||
|
||||
### 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
|
||||
# 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
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
@@ -134,21 +93,17 @@ Then create the Desktop shortcut (if you did not use `Setup.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`).
|
||||
Optional: Edit `~/.xlsx-clean/config.toml` (created automatically on first run) if workbooks are not under the default `D:\\OpenCloud` paths.
|
||||
|
||||
## Developer interfaces
|
||||
|
||||
These are optional; operators should use the Desktop icon.
|
||||
|
||||
**App window (default: native single window)**
|
||||
**GUI (desktop window)**
|
||||
|
||||
```bash
|
||||
.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
|
||||
.venv/bin/python -m xlsx_clean.gui_app
|
||||
# Windows: .venv\Scripts\python.exe -m xlsx_clean.gui_app
|
||||
```
|
||||
|
||||
**CLI**
|
||||
@@ -163,9 +118,9 @@ Windows CLI helper: `src\xlsx_clean\new_xslx.bat`
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `src/xlsx_clean/file_data.csv` | Product folders, filename patterns, cells to clear/set |
|
||||
| `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/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)
|
||||
|
||||
@@ -173,7 +128,7 @@ Windows CLI helper: `src\xlsx_clean\new_xslx.bat`
|
||||
|------|---------|
|
||||
| `desktop/xlsx-clean.ico` | Modern Windows Desktop / exe icon |
|
||||
| `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/setup_linux.sh` | Linux one-time setup (uv sync + shortcut) |
|
||||
| `desktop/Install-DesktopShortcut.bat` | Create Desktop icon only (Windows) |
|
||||
| `desktop/XlsxClean.vbs` | Silent double-click launcher |
|
||||
| `desktop/XlsxClean.bat` | Launcher with visible console |
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
@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.web_app --host 127.0.0.1 --port %PORT% %*
|
||||
".venv\Scripts\python.exe" -m xlsx_clean.gui_app %*
|
||||
) else (
|
||||
py -3 -m xlsx_clean.web_app --host 127.0.0.1 --port %PORT% %*
|
||||
py -3 -m xlsx_clean.gui_app %*
|
||||
)
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
' 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, port
|
||||
Dim fso, sh, scriptDir, root, pythonExe, cmd
|
||||
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"
|
||||
@@ -20,10 +19,10 @@ If Not fso.FileExists(pythonExe) Then
|
||||
End If
|
||||
|
||||
sh.CurrentDirectory = root
|
||||
' Window style 0 = hidden. Opens browser via NiceGUI show=True.
|
||||
cmd = """" & pythonExe & """ -m xlsx_clean.web_app --host 127.0.0.1 --port " & port
|
||||
' Window style 0 = hidden.
|
||||
cmd = """" & pythonExe & """ -m xlsx_clean.gui_app"
|
||||
If pythonExe = "py" Then
|
||||
cmd = "py -3 -m xlsx_clean.web_app --host 127.0.0.1 --port " & port
|
||||
cmd = "py -3 -m xlsx_clean.gui_app"
|
||||
End If
|
||||
|
||||
sh.Run cmd, 0, False
|
||||
|
||||
@@ -48,9 +48,7 @@ def install_linux() -> Path:
|
||||
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"
|
||||
)
|
||||
exec_line = f"{python} -m xlsx_clean.gui_app"
|
||||
icon_png = DESKTOP_DIR / "xlsx-clean.png"
|
||||
icon_line = str(icon_png) if icon_png.is_file() else "applications-office"
|
||||
content = f"""[Desktop Entry]
|
||||
|
||||
@@ -1,131 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# 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.
|
||||
# Operator setup for New QC Sheet on Linux desktops.
|
||||
# Installs deps with uv and creates a Desktop shortcut.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
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
|
||||
|
||||
# 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 ! 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
|
||||
|
||||
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 # 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 "Syncing dependencies..."
|
||||
uv sync
|
||||
|
||||
echo "Installing Desktop shortcut..."
|
||||
.venv/bin/python desktop/install_desktop_shortcut.py
|
||||
|
||||
echo
|
||||
echo "Done. Launch with:"
|
||||
echo " .venv/bin/python -m xlsx_clean.web_app"
|
||||
echo " .venv/bin/python -m xlsx_clean.gui_app"
|
||||
echo "or use the Desktop shortcut."
|
||||
|
||||
@@ -4,7 +4,7 @@ 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)'
|
||||
Exec=bash -lc 'cd "$(dirname "%k")/.." && .venv/bin/python -m xlsx_clean.gui_app'
|
||||
Path=
|
||||
Icon=applications-office
|
||||
Terminal=false
|
||||
|
||||
@@ -15,29 +15,26 @@ block_cipher = None
|
||||
datas = [
|
||||
("src/xlsx_clean/file_data.csv", "xlsx_clean"),
|
||||
("src/xlsx_clean/strings.txt", "xlsx_clean"),
|
||||
("src/xlsx_clean/fonts", "xlsx_clean/fonts"),
|
||||
]
|
||||
binaries = []
|
||||
hiddenimports = [
|
||||
"xlsx_clean",
|
||||
"xlsx_clean.web_app",
|
||||
"xlsx_clean.core",
|
||||
"xlsx_clean.gui_app",
|
||||
"xlsx_clean.clean_cells",
|
||||
"xlsx_clean.ooxml_backend",
|
||||
"xlsx_clean.com_backend",
|
||||
"xlsx_clean.paths",
|
||||
]
|
||||
|
||||
tmp_ret = collect_all("nicegui")
|
||||
datas += tmp_ret[0]
|
||||
binaries += tmp_ret[1]
|
||||
hiddenimports += tmp_ret[2]
|
||||
|
||||
tmp_ret = collect_all("webview")
|
||||
tmp_ret = collect_all("dearpygui")
|
||||
datas += tmp_ret[0]
|
||||
binaries += tmp_ret[1]
|
||||
hiddenimports += tmp_ret[2]
|
||||
|
||||
a = Analysis(
|
||||
["src/xlsx_clean/web_app.py"],
|
||||
["src/xlsx_clean/gui_app.py"],
|
||||
pathex=["."],
|
||||
binaries=binaries,
|
||||
datas=datas,
|
||||
@@ -54,7 +51,6 @@ 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,
|
||||
@@ -65,7 +61,7 @@ exe = EXE(
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=True,
|
||||
console=False, # no black console window
|
||||
console=False,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
[project]
|
||||
name = "xlsx-clean"
|
||||
version = "0.1.0"
|
||||
version = "1.0.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",
|
||||
"nicegui>=3.14.0",
|
||||
"pandas>=3.0.3",
|
||||
"pywebview>=6.2.1",
|
||||
"dearpygui>=2.0.0",
|
||||
"pywin32>=312; sys_platform == 'win32'",
|
||||
]
|
||||
readme = "README.md"
|
||||
@@ -17,7 +15,7 @@ requires-python = ">=3.12"
|
||||
|
||||
[project.scripts]
|
||||
xlsx-clean = "xlsx_clean.clean_cells:main"
|
||||
xlsx-clean-web = "xlsx_clean.web_app:main"
|
||||
xlsx-clean-gui = "xlsx_clean.gui_app:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
desktop = [
|
||||
@@ -38,6 +36,23 @@ packages = ["src/xlsx_clean"]
|
||||
"src/xlsx_clean/file_data.csv" = "xlsx_clean/file_data.csv"
|
||||
"src/xlsx_clean/strings.txt" = "xlsx_clean/strings.txt"
|
||||
"src/xlsx_clean/new_xslx.bat" = "xlsx_clean/new_xslx.bat"
|
||||
"src/xlsx_clean/fonts" = "xlsx_clean/fonts"
|
||||
|
||||
[tool.uv]
|
||||
package = true
|
||||
|
||||
# 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}"'
|
||||
|
||||
@@ -1,239 +1,19 @@
|
||||
"""Interactive CLI: copy latest QC workbook, clear cells, stamp serial."""
|
||||
"""Interactive CLI: select set/ink/serial, create a cleaned QC workbook."""
|
||||
|
||||
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.app_logging import get_logger
|
||||
from xlsx_clean.paths import (
|
||||
default_backend,
|
||||
get_opencloud_root,
|
||||
package_file,
|
||||
remap_opencloud_path,
|
||||
resolve_backend,
|
||||
from xlsx_clean.core import (
|
||||
create_datasheet,
|
||||
list_ink_colors,
|
||||
list_sets,
|
||||
load_config,
|
||||
)
|
||||
|
||||
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.
|
||||
"""
|
||||
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}"
|
||||
try:
|
||||
resolved_backend = resolve_backend(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}"
|
||||
|
||||
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:
|
||||
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.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:
|
||||
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,
|
||||
)
|
||||
from xlsx_clean.paths import default_backend, resolve_backend
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
@@ -249,41 +29,58 @@ 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()}."
|
||||
f"'ooxml' (surgical zip edit). Default: {default_backend()} (Overrides config.toml)."
|
||||
),
|
||||
)
|
||||
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)
|
||||
backend = resolve_backend(args.backend, config.get("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(path_df), cursor_style="cyan")
|
||||
selected_set = select(list_sets(rows), cursor_style="cyan")
|
||||
|
||||
console.print(q2)
|
||||
selected_dir = select(list_ink_colors(path_df, selected_set))
|
||||
selected_dir = select(list_ink_colors(rows, 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,
|
||||
path_df=path_df,
|
||||
rows=rows,
|
||||
addin_paths=addin_paths,
|
||||
config=config,
|
||||
)
|
||||
|
||||
if result.template is not None:
|
||||
|
||||
263
src/xlsx_clean/core.py
Normal file
263
src/xlsx_clean/core.py
Normal file
@@ -0,0 +1,263 @@
|
||||
"""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,
|
||||
)
|
||||
@@ -1,25 +1,25 @@
|
||||
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!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"
|
||||
"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"
|
||||
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
|
||||
|
||||
|
BIN
src/xlsx_clean/fonts/Inter-Bold.ttf
Normal file
BIN
src/xlsx_clean/fonts/Inter-Bold.ttf
Normal file
Binary file not shown.
BIN
src/xlsx_clean/fonts/Inter-Regular.ttf
Normal file
BIN
src/xlsx_clean/fonts/Inter-Regular.ttf
Normal file
Binary file not shown.
298
src/xlsx_clean/gui_app.py
Normal file
298
src/xlsx_clean/gui_app.py
Normal file
@@ -0,0 +1,298 @@
|
||||
"""Cross-platform Dear PyGui desktop GUI for New QC Sheet."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from importlib.metadata import PackageNotFoundError, version as package_version
|
||||
|
||||
import dearpygui.dearpygui as dpg
|
||||
|
||||
from xlsx_clean.core import (
|
||||
create_datasheet,
|
||||
list_ink_colors,
|
||||
list_sets,
|
||||
load_config,
|
||||
)
|
||||
from xlsx_clean.paths import default_backend, package_file
|
||||
|
||||
try:
|
||||
_VERSION = package_version('xlsx-clean')
|
||||
except PackageNotFoundError:
|
||||
_VERSION = 'dev'
|
||||
|
||||
# Module-level variables
|
||||
rows = []
|
||||
addin_paths = []
|
||||
config = {}
|
||||
|
||||
|
||||
# Tags
|
||||
SET_COMBO = "set_combo"
|
||||
INK_COMBO = "ink_combo"
|
||||
SERIAL_INPUT = "serial_input"
|
||||
STATUS_TEXT = "status_text"
|
||||
HEADING_FONT = "heading_font"
|
||||
|
||||
def on_set_change(sender, app_data):
|
||||
"""Callback when the set combo changes."""
|
||||
new_inks = list_ink_colors(rows, app_data)
|
||||
dpg.configure_item(INK_COMBO, items=new_inks)
|
||||
dpg.set_value(INK_COMBO, new_inks[0] if new_inks else '')
|
||||
|
||||
def on_create(sender, app_data):
|
||||
"""Callback for the Create datasheet button."""
|
||||
selected_set = dpg.get_value(SET_COMBO)
|
||||
selected_dir = dpg.get_value(INK_COMBO)
|
||||
batch_serial = dpg.get_value(SERIAL_INPUT)
|
||||
|
||||
try:
|
||||
result = create_datasheet(
|
||||
selected_set=selected_set,
|
||||
selected_dir=selected_dir,
|
||||
batch_serial=batch_serial,
|
||||
backend=None,
|
||||
rows=rows,
|
||||
addin_paths=addin_paths,
|
||||
config=config
|
||||
)
|
||||
|
||||
msg = result.message
|
||||
if result.template:
|
||||
msg += f"\nTemplate: {result.template}"
|
||||
if result.destination:
|
||||
msg += f"\nDestination: {result.destination}"
|
||||
if result.backend:
|
||||
msg += f"\nBackend: {result.backend}"
|
||||
|
||||
dpg.set_value(STATUS_TEXT, msg)
|
||||
|
||||
if result.skipped:
|
||||
dpg.configure_item(STATUS_TEXT, color=(230, 180, 30)) # Yellow
|
||||
elif result.ok:
|
||||
dpg.configure_item(STATUS_TEXT, color=(0, 200, 80)) # Green
|
||||
else:
|
||||
dpg.configure_item(STATUS_TEXT, color=(220, 60, 60)) # Red
|
||||
except Exception as e:
|
||||
dpg.set_value(STATUS_TEXT, f"Error: {e}")
|
||||
dpg.configure_item(STATUS_TEXT, color=(220, 60, 60))
|
||||
|
||||
def _create_modern_theme() -> int:
|
||||
"""Build a global theme that gives DPG widgets a modern, web-like feel, matching the HTML demo."""
|
||||
with dpg.theme() as theme:
|
||||
with dpg.theme_component(dpg.mvAll):
|
||||
# Rounded corners (like CSS border-radius)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 4)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_PopupRounding, 4)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_WindowRounding, 8)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_GrabRounding, 4)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_TabRounding, 4)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_ChildRounding, 4)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_ScrollbarRounding, 4)
|
||||
|
||||
# Generous padding (like CSS padding)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_FramePadding, 12, 10)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_ItemSpacing, 10, 10)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_ItemInnerSpacing, 8, 6)
|
||||
dpg.add_theme_style(dpg.mvStyleVar_WindowPadding, 48, 48)
|
||||
|
||||
# Scrollbar
|
||||
dpg.add_theme_style(dpg.mvStyleVar_ScrollbarSize, 12)
|
||||
|
||||
# Colors from demo.html
|
||||
bg = (248, 250, 252, 255) # Slate 50 (#f8fafc)
|
||||
surface = (255, 255, 255, 255) # White (#ffffff)
|
||||
frame = (255, 255, 255, 255) # White (inputs)
|
||||
frame_hover = (240, 253, 250, 255) # Teal 50 (#f0fdfa)
|
||||
frame_active = (204, 251, 241, 255) # Teal 100 (#ccfbf1)
|
||||
accent = (15, 118, 110, 255) # Teal 700 (#0f766e) - Primary
|
||||
accent_hover = (17, 94, 89, 255) # Teal 800 (#115e59) - Secondary
|
||||
accent_active = (19, 78, 74, 255) # Teal 900 (#134e4a)
|
||||
text = (15, 23, 42, 255) # Slate 900 (#0f172a)
|
||||
text_dim = (100, 116, 139, 255) # Slate 500 (#64748b)
|
||||
border = (203, 213, 225, 255) # Slate 300 (#cbd5e1)
|
||||
popup_bg = (255, 255, 255, 255) # White dropdowns
|
||||
|
||||
# Window
|
||||
dpg.add_theme_color(dpg.mvThemeCol_WindowBg, bg)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_PopupBg, popup_bg)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_TitleBg, bg)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_TitleBgActive, bg)
|
||||
|
||||
# Frame (combos, inputs)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_FrameBg, frame)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_FrameBgHovered, frame_hover)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_FrameBgActive, frame_active)
|
||||
|
||||
# Border
|
||||
dpg.add_theme_color(dpg.mvThemeCol_Border, border)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_BorderShadow, (0, 0, 0, 0))
|
||||
dpg.add_theme_style(dpg.mvStyleVar_FrameBorderSize, 1)
|
||||
|
||||
# Button (Combo box drop arrows) - blend into frame
|
||||
dpg.add_theme_color(dpg.mvThemeCol_Button, frame)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, frame_hover)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, frame_active)
|
||||
|
||||
# Header (combo dropdown items on hover)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_Header, frame_hover)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_HeaderHovered, frame_active)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_HeaderActive, accent)
|
||||
|
||||
# Text
|
||||
dpg.add_theme_color(dpg.mvThemeCol_Text, text)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_TextDisabled, text_dim)
|
||||
|
||||
# Separator
|
||||
dpg.add_theme_color(dpg.mvThemeCol_Separator, border)
|
||||
|
||||
# Scrollbar
|
||||
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarBg, bg)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrab, border)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrabHovered, text_dim)
|
||||
dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrabActive, text)
|
||||
|
||||
# Check mark / selection
|
||||
dpg.add_theme_color(dpg.mvThemeCol_CheckMark, accent)
|
||||
|
||||
return theme
|
||||
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="New QC Sheet — Dear PyGui desktop application.",
|
||||
)
|
||||
parser.add_argument('--width', type=int, default=650, help='Window width')
|
||||
parser.add_argument('--height', type=int, default=700, help='Window height')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
global rows, addin_paths, config
|
||||
args = parse_args()
|
||||
|
||||
dpg.create_context()
|
||||
|
||||
# --- Modern theme ---------------------------------------------------
|
||||
modern_theme = _create_modern_theme()
|
||||
dpg.bind_theme(modern_theme)
|
||||
|
||||
# --- Load Inter font ------------------------------------------------
|
||||
font_regular = package_file("fonts/Inter-Regular.ttf")
|
||||
font_bold = package_file("fonts/Inter-Bold.ttf")
|
||||
default_font = None
|
||||
heading_font = None
|
||||
label_font = None
|
||||
if font_regular.is_file():
|
||||
with dpg.font_registry():
|
||||
default_font = dpg.add_font(str(font_regular), 18)
|
||||
label_font = dpg.add_font(str(font_regular), 14)
|
||||
if font_bold.is_file():
|
||||
heading_font = dpg.add_font(str(font_bold), 28, tag=HEADING_FONT)
|
||||
|
||||
# Load config and initialize variables
|
||||
sets = []
|
||||
initial_inks = []
|
||||
error_msg = ""
|
||||
|
||||
label_set = 'Select Set'
|
||||
label_ink = 'Select Ink Color'
|
||||
label_serial = 'Serial:'
|
||||
|
||||
try:
|
||||
content, loaded_rows, loaded_config = load_config()
|
||||
rows = loaded_rows
|
||||
config = loaded_config
|
||||
if len(content) >= 5:
|
||||
label_set = content[0]
|
||||
label_ink = content[1]
|
||||
label_serial = content[2]
|
||||
addin_paths = content[3:5]
|
||||
|
||||
sets = list_sets(rows)
|
||||
if sets:
|
||||
initial_inks = list_ink_colors(rows, sets[0])
|
||||
except Exception as e:
|
||||
error_msg = f"Failed to load config: {e}"
|
||||
|
||||
with dpg.theme() as tight_theme:
|
||||
with dpg.theme_component(dpg.mvAll):
|
||||
dpg.add_theme_style(dpg.mvStyleVar_ItemSpacing, 10, -8)
|
||||
|
||||
with dpg.theme() as normal_spacing_theme:
|
||||
with dpg.theme_component(dpg.mvAll):
|
||||
dpg.add_theme_style(dpg.mvStyleVar_ItemSpacing, 10, 10)
|
||||
|
||||
with dpg.theme() as btn_theme:
|
||||
with dpg.theme_component(dpg.mvButton):
|
||||
dpg.add_theme_color(dpg.mvThemeCol_Text, (255, 255, 255, 255))
|
||||
dpg.add_theme_color(dpg.mvThemeCol_Button, (15, 118, 110, 255))
|
||||
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (17, 94, 89, 255))
|
||||
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (19, 78, 74, 255))
|
||||
|
||||
with dpg.window(tag="primary_window"):
|
||||
if default_font:
|
||||
dpg.bind_font(default_font)
|
||||
|
||||
title = dpg.add_text('New QC Sheet', color=(17, 94, 89, 255))
|
||||
if heading_font:
|
||||
dpg.bind_item_font(title, heading_font)
|
||||
dpg.add_text(f"v{_VERSION}", color=(100, 106, 120))
|
||||
dpg.add_spacer(height=4)
|
||||
dpg.add_separator()
|
||||
dpg.add_spacer(height=10)
|
||||
|
||||
def add_floating_label(text):
|
||||
lbl = dpg.add_text(text, color=(15, 118, 110, 255))
|
||||
if label_font:
|
||||
dpg.bind_item_font(lbl, label_font)
|
||||
|
||||
with dpg.group() as g1:
|
||||
add_floating_label(label_set)
|
||||
c1 = dpg.add_combo(items=sets, default_value=sets[0] if sets else '',
|
||||
tag=SET_COMBO, callback=on_set_change, width=-1)
|
||||
dpg.bind_item_theme(c1, normal_spacing_theme)
|
||||
dpg.bind_item_theme(g1, tight_theme)
|
||||
dpg.add_spacer(height=8)
|
||||
|
||||
with dpg.group() as g2:
|
||||
add_floating_label(label_ink)
|
||||
c2 = dpg.add_combo(items=initial_inks,
|
||||
default_value=initial_inks[0] if initial_inks else '',
|
||||
tag=INK_COMBO, width=-1)
|
||||
dpg.bind_item_theme(c2, normal_spacing_theme)
|
||||
dpg.bind_item_theme(g2, tight_theme)
|
||||
dpg.add_spacer(height=8)
|
||||
|
||||
with dpg.group() as g3:
|
||||
add_floating_label(label_serial)
|
||||
c3 = dpg.add_input_text(tag=SERIAL_INPUT, width=-1, hint="e.g. 1234/A")
|
||||
dpg.bind_item_theme(c3, normal_spacing_theme)
|
||||
dpg.bind_item_theme(g3, tight_theme)
|
||||
dpg.add_spacer(height=10)
|
||||
|
||||
dpg.add_separator()
|
||||
dpg.add_spacer(height=10)
|
||||
|
||||
btn = dpg.add_button(label='Create datasheet', width=-1, height=38,
|
||||
callback=on_create)
|
||||
dpg.bind_item_theme(btn, btn_theme)
|
||||
dpg.add_spacer(height=14)
|
||||
|
||||
dpg.add_text(error_msg, tag=STATUS_TEXT, wrap=args.width - 40)
|
||||
if error_msg:
|
||||
dpg.configure_item(STATUS_TEXT, color=(220, 60, 60))
|
||||
|
||||
dpg.create_viewport(title=f'New QC Sheet · v{_VERSION}',
|
||||
width=args.width, height=args.height)
|
||||
dpg.setup_dearpygui()
|
||||
dpg.show_viewport()
|
||||
dpg.set_primary_window("primary_window", True)
|
||||
dpg.start_dearpygui()
|
||||
dpg.destroy_context()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -19,52 +19,29 @@ 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 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_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 default_backend() -> str:
|
||||
return "com" if sys.platform == "win32" else "ooxml"
|
||||
|
||||
|
||||
def resolve_backend(requested: str | None) -> str:
|
||||
backend = (requested or default_backend()).lower()
|
||||
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()
|
||||
|
||||
if backend not in {"com", "ooxml"}:
|
||||
raise ValueError(f"Unknown backend {backend!r}; use 'com' or 'ooxml'")
|
||||
if backend == "com" and sys.platform != "win32":
|
||||
|
||||
@@ -1,335 +0,0 @@
|
||||
"""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()
|
||||
Reference in New Issue
Block a user