monitor-app 0.1.9__tar.gz → 2.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. monitor_app-2.3.0/PKG-INFO +242 -0
  2. monitor_app-2.3.0/README.md +196 -0
  3. monitor_app-2.3.0/monitor_app/__init__.py +33 -0
  4. monitor_app-2.3.0/monitor_app/api/__init__.py +1 -0
  5. monitor_app-2.3.0/monitor_app/api/deps.py +140 -0
  6. monitor_app-2.3.0/monitor_app/api/errors.py +39 -0
  7. monitor_app-2.3.0/monitor_app/api/routers/__init__.py +1 -0
  8. monitor_app-2.3.0/monitor_app/api/routers/alerts.py +18 -0
  9. monitor_app-2.3.0/monitor_app/api/routers/audit.py +23 -0
  10. monitor_app-2.3.0/monitor_app/api/routers/auth.py +51 -0
  11. monitor_app-2.3.0/monitor_app/api/routers/crud.py +85 -0
  12. monitor_app-2.3.0/monitor_app/api/routers/ingest.py +32 -0
  13. monitor_app-2.3.0/monitor_app/api/routers/meta.py +39 -0
  14. monitor_app-2.3.0/monitor_app/api/routers/pages.py +282 -0
  15. monitor_app-2.3.0/monitor_app/api/routers/views.py +179 -0
  16. monitor_app-2.3.0/monitor_app/api/schemas.py +53 -0
  17. monitor_app-2.3.0/monitor_app/cli.py +202 -0
  18. monitor_app-2.3.0/monitor_app/db/__init__.py +7 -0
  19. monitor_app-2.3.0/monitor_app/db/engine.py +60 -0
  20. monitor_app-2.3.0/monitor_app/db/ingest_state.py +49 -0
  21. monitor_app-2.3.0/monitor_app/db/registry.py +87 -0
  22. monitor_app-2.3.0/monitor_app/db/repository.py +94 -0
  23. monitor_app-2.3.0/monitor_app/exceptions.py +42 -0
  24. monitor_app-2.3.0/monitor_app/integrations/__init__.py +53 -0
  25. monitor_app-2.3.0/monitor_app/integrations/netdiag.py +166 -0
  26. monitor_app-2.3.0/monitor_app/integrations/network_checker.py +192 -0
  27. monitor_app-2.3.0/monitor_app/integrations/procdiag.py +281 -0
  28. monitor_app-2.3.0/monitor_app/logging_conf.py +41 -0
  29. monitor_app-2.3.0/monitor_app/main.py +181 -0
  30. monitor_app-2.3.0/monitor_app/scaffold/README.md +36 -0
  31. monitor_app-2.3.0/monitor_app/scaffold/config.py +154 -0
  32. monitor_app-2.3.0/monitor_app/scaffold/env.example +42 -0
  33. monitor_app-2.3.0/monitor_app/services/__init__.py +7 -0
  34. monitor_app-2.3.0/monitor_app/services/alert_scheduler.py +73 -0
  35. monitor_app-2.3.0/monitor_app/services/alert_service.py +203 -0
  36. monitor_app-2.3.0/monitor_app/services/audit_service.py +105 -0
  37. monitor_app-2.3.0/monitor_app/services/coercion.py +45 -0
  38. monitor_app-2.3.0/monitor_app/services/connectors.py +439 -0
  39. monitor_app-2.3.0/monitor_app/services/crud_service.py +200 -0
  40. monitor_app-2.3.0/monitor_app/services/importer.py +182 -0
  41. monitor_app-2.3.0/monitor_app/services/ingest_watcher.py +138 -0
  42. monitor_app-2.3.0/monitor_app/services/kpi_service.py +79 -0
  43. monitor_app-2.3.0/monitor_app/services/notifiers/__init__.py +47 -0
  44. monitor_app-2.3.0/monitor_app/services/notifiers/base.py +20 -0
  45. monitor_app-2.3.0/monitor_app/services/notifiers/email.py +27 -0
  46. monitor_app-2.3.0/monitor_app/services/notifiers/webhook.py +19 -0
  47. monitor_app-2.3.0/monitor_app/services/view_cache.py +39 -0
  48. monitor_app-2.3.0/monitor_app/services/view_service.py +107 -0
  49. monitor_app-2.3.0/monitor_app/settings/__init__.py +18 -0
  50. monitor_app-2.3.0/monitor_app/settings/declarative.py +323 -0
  51. monitor_app-2.3.0/monitor_app/settings/loader.py +110 -0
  52. monitor_app-2.3.0/monitor_app/settings/runtime.py +67 -0
  53. monitor_app-2.3.0/monitor_app/web/static/css/app.css +571 -0
  54. monitor_app-2.3.0/monitor_app/web/static/css/dashboard.css +147 -0
  55. monitor_app-2.3.0/monitor_app/web/static/css/kiosk.css +189 -0
  56. monitor_app-2.3.0/monitor_app/web/static/js/alerts-ui.js +87 -0
  57. monitor_app-2.3.0/monitor_app/web/static/js/app.js +152 -0
  58. monitor_app-2.3.0/monitor_app/web/static/js/chart-view.js +195 -0
  59. monitor_app-2.3.0/monitor_app/web/static/js/chart.umd.min.js +14 -0
  60. monitor_app-2.3.0/monitor_app/web/static/js/dashboard.js +193 -0
  61. monitor_app-2.3.0/monitor_app/web/static/js/form.js +66 -0
  62. monitor_app-2.3.0/monitor_app/web/static/js/kiosk.js +220 -0
  63. monitor_app-2.3.0/monitor_app/web/static/js/kpis.js +104 -0
  64. monitor_app-2.3.0/monitor_app/web/static/js/table-render.js +87 -0
  65. monitor_app-2.3.0/monitor_app/web/static/js/theme.js +73 -0
  66. monitor_app-2.3.0/monitor_app/web/templates/base.html +110 -0
  67. monitor_app-2.3.0/monitor_app/web/templates/form.html +54 -0
  68. monitor_app-2.3.0/monitor_app/web/templates/index.html +116 -0
  69. monitor_app-2.3.0/monitor_app/web/templates/kiosk.html +75 -0
  70. monitor_app-2.3.0/monitor_app/web/templates/login.html +49 -0
  71. monitor_app-2.3.0/monitor_app/web/templates/table.html +100 -0
  72. monitor_app-2.3.0/pyproject.toml +100 -0
  73. monitor_app-0.1.9/PKG-INFO +0 -804
  74. monitor_app-0.1.9/README.md +0 -776
  75. monitor_app-0.1.9/monitor_app/__init__.py +0 -0
  76. monitor_app-0.1.9/monitor_app/app.py +0 -564
  77. monitor_app-0.1.9/monitor_app/cli.py +0 -208
  78. monitor_app-0.1.9/monitor_app/config/config.py +0 -134
  79. monitor_app-0.1.9/monitor_app/csv/data.csv +0 -5
  80. monitor_app-0.1.9/monitor_app/csv_to_db.py +0 -92
  81. monitor_app-0.1.9/monitor_app/instances/database.db +0 -0
  82. monitor_app-0.1.9/monitor_app/static/css/jquery.datatables.min.css +0 -19
  83. monitor_app-0.1.9/monitor_app/static/js/bootstrap.bundle.min.js +0 -7
  84. monitor_app-0.1.9/monitor_app/static/js/jquery.datatables.min.js +0 -26
  85. monitor_app-0.1.9/monitor_app/static/js/jquery.min.js +0 -2
  86. monitor_app-0.1.9/monitor_app/static/js/refresh_table.js +0 -29
  87. monitor_app-0.1.9/monitor_app/templates/base.html +0 -90
  88. monitor_app-0.1.9/monitor_app/templates/index.html +0 -14
  89. monitor_app-0.1.9/monitor_app/templates/table.html +0 -166
  90. monitor_app-0.1.9/pyproject.toml +0 -48
  91. {monitor_app-0.1.9 → monitor_app-2.3.0}/LICENSE +0 -0
  92. {monitor_app-0.1.9/monitor_app → monitor_app-2.3.0/monitor_app/scaffold}/csv/orders.csv +0 -0
  93. {monitor_app-0.1.9/monitor_app → monitor_app-2.3.0/monitor_app/scaffold}/csv/products.csv +0 -0
  94. {monitor_app-0.1.9/monitor_app → monitor_app-2.3.0/monitor_app/scaffold}/csv/users.csv +0 -0
  95. {monitor_app-0.1.9/monitor_app → monitor_app-2.3.0/monitor_app/web}/static/css/bootstrap.min.css +0 -0
  96. {monitor_app-0.1.9/monitor_app → monitor_app-2.3.0/monitor_app/web}/static/img/background.webp +0 -0
  97. {monitor_app-0.1.9/monitor_app/static → monitor_app-2.3.0/monitor_app/web/static/img}/favicon.ico +0 -0
  98. {monitor_app-0.1.9/monitor_app → monitor_app-2.3.0/monitor_app/web}/static/img/logo.webp +0 -0
@@ -0,0 +1,242 @@
1
+ Metadata-Version: 2.4
2
+ Name: monitor-app
3
+ Version: 2.3.0
4
+ Summary: Drop in a CSV, write one config file, and get a live-updating Web UI + REST API. FastAPI-based data monitoring for shop floors and small teams.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: dashboard,monitoring,csv,fastapi,andon,spc,manufacturing
8
+ Author: hardwork9047
9
+ Author-email: tomatosimple1104@gmail.com
10
+ Requires-Python: >=3.10
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Intended Audience :: Manufacturing
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Scientific/Engineering :: Visualization
17
+ Classifier: Topic :: Database :: Front-Ends
18
+ Classifier: Natural Language :: Japanese
19
+ Classifier: Natural Language :: English
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Provides-Extra: xlsx
27
+ Requires-Dist: click (>=8.1,<8.2)
28
+ Requires-Dist: fastapi (>=0.115,<1.0)
29
+ Requires-Dist: jinja2 (>=3.1,<4.0)
30
+ Requires-Dist: openpyxl (>=3.1,<4.0) ; extra == "xlsx"
31
+ Requires-Dist: pg8000 (>=1.30,<2.0)
32
+ Requires-Dist: pydantic (>=2.7,<3.0)
33
+ Requires-Dist: pydantic-settings (>=2.3,<3.0)
34
+ Requires-Dist: pymysql (>=1.1,<2.0)
35
+ Requires-Dist: python-multipart (>=0.0.9)
36
+ Requires-Dist: sqlalchemy (>=2.0,<3.0)
37
+ Requires-Dist: sse-starlette (>=2.1,<3.0)
38
+ Requires-Dist: typer (>=0.12,<1.0)
39
+ Requires-Dist: uvicorn[standard] (>=0.30,<1.0)
40
+ Project-URL: Changelog, https://github.com/mikawa-bushi/monitor-app/blob/main/CHANGELOG.md
41
+ Project-URL: Documentation, https://github.com/mikawa-bushi/monitor-app#readme
42
+ Project-URL: Homepage, https://github.com/mikawa-bushi/monitor-app
43
+ Project-URL: Repository, https://github.com/mikawa-bushi/monitor-app
44
+ Description-Content-Type: text/markdown
45
+
46
+ # Monitor App 🚀
47
+
48
+ [![PyPI version](https://img.shields.io/pypi/v/monitor-app.svg)](https://pypi.org/project/monitor-app/)
49
+ [![Python versions](https://img.shields.io/pypi/pyversions/monitor-app.svg)](https://pypi.org/project/monitor-app/)
50
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/mikawa-bushi/monitor-app/blob/main/LICENSE)
51
+
52
+ **Drop in a CSV, write one config file, and get a live-updating Web UI + REST API.**
53
+
54
+ Monitor App is a FastAPI-based data monitoring tool designed for shop floors, labs, and small teams. Define your tables and views declaratively in a single `config.py` (validated by Pydantic at startup), and Monitor App serves a real-time dashboard, full CRUD REST API with Swagger docs, threshold alerts, and an Andon-style wallboard — no frontend build, no Node.js, fully offline-capable.
55
+
56
+ 日本語のドキュメントは [README_ja.md](https://github.com/mikawa-bushi/monitor-app/blob/main/README_ja.md) を参照してください。
57
+
58
+ ---
59
+
60
+ ## ✨ Features
61
+
62
+ - **CSV → Web app in 3 commands** — place CSV files, run the server, see your data
63
+ - **Type-safe declarative config** — tables, views, styles, alerts in one Pydantic-validated `config.py`; typos are caught at startup with friendly messages (`monitor-app check`)
64
+ - **Live-updating views** — Server-Sent Events push changes to the browser; polling fallback
65
+ - **Full REST API** — CRUD per table, bulk ingest, automatic Swagger UI at `/docs`
66
+ - **SQLite / MySQL / PostgreSQL** — switch with a single `DATABASE_URL` environment variable
67
+ - **Conditional cell styling** — color-code values by thresholds, no code required
68
+ - **No frontend toolchain** — vanilla JS + bundled assets; works on offline factory networks
69
+
70
+ ### 🏭 Built for the shop floor (v2.1)
71
+
72
+ | Feature | What it does | How to enable |
73
+ |---|---|---|
74
+ | Auto data ingest | Watches `csv/` for changes; `POST /api/ingest/{table}` for sensors/PLC/MES | `MONITOR_INGEST_WATCH` / always on |
75
+ | Threshold alerts | On-screen banner + browser notification, Webhook (Slack/Teams), e-mail; edge-triggered | `alerts=[AlertRule(...)]` |
76
+ | Andon wallboard | Full-screen rotating views with a green/amber/red status light at `/kiosk` | `kiosk=KioskConfig(...)` |
77
+ | Trend / SPC charts | Line & bar charts with UCL/LCL/target lines, out-of-control points highlighted | `ViewDef(chart=ChartDef(...))` |
78
+ | Dashboard | Home page shows mini-chart grid (columns=1–4) for chart-enabled views; non-chart views listed below | `dashboard=DashboardConfig(columns=2)` |
79
+ | Group navigation | Sidebar and view list support named groups; `ViewDef(group="...")` | `ViewDef(group=...)` |
80
+ | Dark theme | Toggle between light and dark; persisted in `localStorage["monitor-theme"]`; `<html data-theme="dark">` | theme-toggle button (☀️/🌙) |
81
+ | KPI cards | Scalar SQL (counts, rates, OEE) as color-coded cards on the home page | `kpis={...}` |
82
+ | Operator entry forms | Touch-friendly forms generated from your table schema at `/form/{table}` | `TableDef(form=FormDef(...))` |
83
+ | Audit log | Who changed what and when, for every write | `MONITOR_AUDIT_ENABLED` |
84
+ | Export | Download any view as CSV or Excel | `/api/views/{view}/export` |
85
+
86
+ ---
87
+
88
+ ## 🚀 Installation
89
+
90
+ ```sh
91
+ pip install monitor-app
92
+ ```
93
+
94
+ With Excel export support:
95
+
96
+ ```sh
97
+ pip install "monitor-app[xlsx]"
98
+ ```
99
+
100
+ ## 🔧 Quick start
101
+
102
+ ```sh
103
+ # 1. Create a project (config.py + sample CSVs, ready to run)
104
+ monitor-app startproject myproject
105
+ cd myproject
106
+
107
+ # 2. Import CSVs and start the server
108
+ monitor-app runserver --import-csv
109
+
110
+ # 3. Open http://127.0.0.1:9990 (Swagger UI at /docs)
111
+ ```
112
+
113
+ ### CLI commands
114
+
115
+ | Command | Description |
116
+ |---|---|
117
+ | `monitor-app startproject <name>` | Generate a project skeleton |
118
+ | `monitor-app runserver [--import-csv] [--reload] [--host H] [--port P]` | Start the web server |
119
+ | `monitor-app import-csv [--keep]` | Import `csv/` into the database (`--keep` appends) |
120
+ | `monitor-app check` | Validate `config.py` without starting the server |
121
+
122
+ ## 📝 Configuration
123
+
124
+ Everything lives in one `config.py`. Mistakes are reported at startup, not at runtime:
125
+
126
+ ```python
127
+ from monitor_app import (
128
+ AlertRule, CellStyle, ChartDef, FormDef, KioskConfig,
129
+ KpiCard, MonitorConfig, TableDef, Threshold, ViewDef,
130
+ )
131
+
132
+ config = MonitorConfig(
133
+ app_title="Line Monitor",
134
+ refresh_interval_ms=2000,
135
+ # CRUD tables — column types are inferred (or written explicitly)
136
+ tables={
137
+ "measurements": TableDef(
138
+ columns={"id": "int", "ts": "str", "temp": "float"},
139
+ form=FormDef(labels={"temp": "Temperature"}), # operator entry form
140
+ ),
141
+ },
142
+ # Display views — any SELECT, including JOINs and aggregation
143
+ views={
144
+ "temp_trend": ViewDef(
145
+ query="SELECT ts, temp FROM measurements ORDER BY id",
146
+ title="Temperature trend",
147
+ chart=ChartDef(type="line", x="ts", y="temp", ucl=80, lcl=20),
148
+ styles={"temp": CellStyle(
149
+ greater_than=Threshold(value=80, **{"class": "bg-danger text-white"}),
150
+ )},
151
+ ),
152
+ },
153
+ # Threshold alerts with notifications
154
+ alerts=[
155
+ AlertRule(view="temp_trend", column="temp", op=">", value=80,
156
+ level="critical", notify=["webhook"]),
157
+ ],
158
+ # KPI cards and Andon wallboard
159
+ kpis={"count": KpiCard(title="Samples", query="SELECT COUNT(*) FROM measurements")},
160
+ kiosk=KioskConfig(rotate_seconds=15, theme="dark"),
161
+ )
162
+ ```
163
+
164
+ Environment-specific values (never in `config.py`) go in `.env`:
165
+
166
+ ```sh
167
+ MONITOR_DATABASE_URL=postgresql+pg8000://user:pass@db:5432/monitor # default: SQLite
168
+ MONITOR_API_KEY=change-me # enables X-API-Key auth on writes
169
+ MONITOR_INGEST_WATCH=true # auto-import csv/ on change
170
+ MONITOR_AUDIT_ENABLED=true # record change history
171
+ MONITOR_WEBHOOK_URL=https://hooks.slack.com/services/...
172
+ ```
173
+
174
+ ## 🌐 Endpoints
175
+
176
+ | Path | Description |
177
+ |---|---|
178
+ | `/` | Home: dashboard with mini-charts, KPI cards, and view list |
179
+ | `/table/{view}` | Live table / chart page |
180
+ | `/kiosk` | Andon wallboard (full screen, auto-rotating) |
181
+ | `/form/{table}` | Operator entry form |
182
+ | `/docs`, `/redoc` | OpenAPI documentation |
183
+ | `/api/tables/{table}` | CRUD (GET/POST/PUT/DELETE) |
184
+ | `/api/ingest/{table}` | Bulk ingest for sensors/PLC |
185
+ | `/api/views/{view}` | View data (+ `/stream` for SSE, `/export` for CSV/Excel) |
186
+ | `/api/kpis`, `/api/alerts`, `/api/audit`, `/api/schema`, `/api/health` | KPIs, active alerts, audit log, schema, health |
187
+
188
+ ## 🔌 External tool integrations (v2.2)
189
+
190
+ Connect procdiag, netdiag, and network-checker to Monitor App with a few lines — no changes to the external tools required (read-only, pull-based).
191
+
192
+ ```python
193
+ from monitor_app.integrations import procdiag, netdiag, network_checker
194
+
195
+ config = procdiag.attach(config, db_path="/opt/procdiag/data/procdiag.db")
196
+ config = netdiag.attach(config)
197
+ config = network_checker.attach(config, hosts=["plc-01", "gateway"])
198
+ ```
199
+
200
+ Each `attach()` call merges tables, views, KPIs, and alert rules into your existing config. Run `monitor-app sync-sources` to ingest on demand, or set `MONITOR_INGEST_WATCH=1` for continuous polling.
201
+
202
+ Full reference: [docs/integrations_v2_2.md](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/integrations_v2_2.md)
203
+
204
+ ---
205
+
206
+ ## 🔄 Migrating from v0.x
207
+
208
+ v2 was rebuilt on FastAPI + Pydantic. The legacy dict-style `config.py`
209
+ (`ALLOWED_TABLES` / `VIEW_TABLES` / `TABLE_CELL_STYLES`) **still loads** through a
210
+ compatibility shim, but new projects should use `MonitorConfig`. Key changes:
211
+
212
+ - `python app.py runserver` → `monitor-app runserver` (the app no longer lives in your project)
213
+ - DB settings (`DB_TYPE`, passwords) → `MONITOR_DATABASE_URL` environment variable
214
+ - API paths: `/api/<table>` → `/api/tables/{table}`, `/api/view/<v>` → `/api/views/{view}`
215
+
216
+ Details: [redesign notes](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/redesign_v2.md) ·
217
+ [v2.1 feature design](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/feature_expansion_v2.1.md) ·
218
+ [v2.2 integrations](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/integrations_v2_2.md) ·
219
+ [v2.3 UI redesign](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/ui_redesign_v2_3.md)
220
+
221
+ ## 🐳 Docker
222
+
223
+ ```sh
224
+ docker build -t monitor-app -f docker/Dockerfile .
225
+ docker run -v $(pwd)/myproject:/project -p 9990:9990 monitor-app
226
+ ```
227
+
228
+ ## 🛠 Development
229
+
230
+ ```sh
231
+ git clone https://github.com/mikawa-bushi/monitor-app.git
232
+ cd monitor-app
233
+ poetry install
234
+ poetry run pytest
235
+ ```
236
+
237
+ Contributions are welcome — see [CONTRIBUTING.md](https://github.com/mikawa-bushi/monitor-app/blob/main/CONTRIBUTING.md).
238
+
239
+ ## 📜 License
240
+
241
+ [MIT](https://github.com/mikawa-bushi/monitor-app/blob/main/LICENSE)
242
+
@@ -0,0 +1,196 @@
1
+ # Monitor App 🚀
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/monitor-app.svg)](https://pypi.org/project/monitor-app/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/monitor-app.svg)](https://pypi.org/project/monitor-app/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/mikawa-bushi/monitor-app/blob/main/LICENSE)
6
+
7
+ **Drop in a CSV, write one config file, and get a live-updating Web UI + REST API.**
8
+
9
+ Monitor App is a FastAPI-based data monitoring tool designed for shop floors, labs, and small teams. Define your tables and views declaratively in a single `config.py` (validated by Pydantic at startup), and Monitor App serves a real-time dashboard, full CRUD REST API with Swagger docs, threshold alerts, and an Andon-style wallboard — no frontend build, no Node.js, fully offline-capable.
10
+
11
+ 日本語のドキュメントは [README_ja.md](https://github.com/mikawa-bushi/monitor-app/blob/main/README_ja.md) を参照してください。
12
+
13
+ ---
14
+
15
+ ## ✨ Features
16
+
17
+ - **CSV → Web app in 3 commands** — place CSV files, run the server, see your data
18
+ - **Type-safe declarative config** — tables, views, styles, alerts in one Pydantic-validated `config.py`; typos are caught at startup with friendly messages (`monitor-app check`)
19
+ - **Live-updating views** — Server-Sent Events push changes to the browser; polling fallback
20
+ - **Full REST API** — CRUD per table, bulk ingest, automatic Swagger UI at `/docs`
21
+ - **SQLite / MySQL / PostgreSQL** — switch with a single `DATABASE_URL` environment variable
22
+ - **Conditional cell styling** — color-code values by thresholds, no code required
23
+ - **No frontend toolchain** — vanilla JS + bundled assets; works on offline factory networks
24
+
25
+ ### 🏭 Built for the shop floor (v2.1)
26
+
27
+ | Feature | What it does | How to enable |
28
+ |---|---|---|
29
+ | Auto data ingest | Watches `csv/` for changes; `POST /api/ingest/{table}` for sensors/PLC/MES | `MONITOR_INGEST_WATCH` / always on |
30
+ | Threshold alerts | On-screen banner + browser notification, Webhook (Slack/Teams), e-mail; edge-triggered | `alerts=[AlertRule(...)]` |
31
+ | Andon wallboard | Full-screen rotating views with a green/amber/red status light at `/kiosk` | `kiosk=KioskConfig(...)` |
32
+ | Trend / SPC charts | Line & bar charts with UCL/LCL/target lines, out-of-control points highlighted | `ViewDef(chart=ChartDef(...))` |
33
+ | Dashboard | Home page shows mini-chart grid (columns=1–4) for chart-enabled views; non-chart views listed below | `dashboard=DashboardConfig(columns=2)` |
34
+ | Group navigation | Sidebar and view list support named groups; `ViewDef(group="...")` | `ViewDef(group=...)` |
35
+ | Dark theme | Toggle between light and dark; persisted in `localStorage["monitor-theme"]`; `<html data-theme="dark">` | theme-toggle button (☀️/🌙) |
36
+ | KPI cards | Scalar SQL (counts, rates, OEE) as color-coded cards on the home page | `kpis={...}` |
37
+ | Operator entry forms | Touch-friendly forms generated from your table schema at `/form/{table}` | `TableDef(form=FormDef(...))` |
38
+ | Audit log | Who changed what and when, for every write | `MONITOR_AUDIT_ENABLED` |
39
+ | Export | Download any view as CSV or Excel | `/api/views/{view}/export` |
40
+
41
+ ---
42
+
43
+ ## 🚀 Installation
44
+
45
+ ```sh
46
+ pip install monitor-app
47
+ ```
48
+
49
+ With Excel export support:
50
+
51
+ ```sh
52
+ pip install "monitor-app[xlsx]"
53
+ ```
54
+
55
+ ## 🔧 Quick start
56
+
57
+ ```sh
58
+ # 1. Create a project (config.py + sample CSVs, ready to run)
59
+ monitor-app startproject myproject
60
+ cd myproject
61
+
62
+ # 2. Import CSVs and start the server
63
+ monitor-app runserver --import-csv
64
+
65
+ # 3. Open http://127.0.0.1:9990 (Swagger UI at /docs)
66
+ ```
67
+
68
+ ### CLI commands
69
+
70
+ | Command | Description |
71
+ |---|---|
72
+ | `monitor-app startproject <name>` | Generate a project skeleton |
73
+ | `monitor-app runserver [--import-csv] [--reload] [--host H] [--port P]` | Start the web server |
74
+ | `monitor-app import-csv [--keep]` | Import `csv/` into the database (`--keep` appends) |
75
+ | `monitor-app check` | Validate `config.py` without starting the server |
76
+
77
+ ## 📝 Configuration
78
+
79
+ Everything lives in one `config.py`. Mistakes are reported at startup, not at runtime:
80
+
81
+ ```python
82
+ from monitor_app import (
83
+ AlertRule, CellStyle, ChartDef, FormDef, KioskConfig,
84
+ KpiCard, MonitorConfig, TableDef, Threshold, ViewDef,
85
+ )
86
+
87
+ config = MonitorConfig(
88
+ app_title="Line Monitor",
89
+ refresh_interval_ms=2000,
90
+ # CRUD tables — column types are inferred (or written explicitly)
91
+ tables={
92
+ "measurements": TableDef(
93
+ columns={"id": "int", "ts": "str", "temp": "float"},
94
+ form=FormDef(labels={"temp": "Temperature"}), # operator entry form
95
+ ),
96
+ },
97
+ # Display views — any SELECT, including JOINs and aggregation
98
+ views={
99
+ "temp_trend": ViewDef(
100
+ query="SELECT ts, temp FROM measurements ORDER BY id",
101
+ title="Temperature trend",
102
+ chart=ChartDef(type="line", x="ts", y="temp", ucl=80, lcl=20),
103
+ styles={"temp": CellStyle(
104
+ greater_than=Threshold(value=80, **{"class": "bg-danger text-white"}),
105
+ )},
106
+ ),
107
+ },
108
+ # Threshold alerts with notifications
109
+ alerts=[
110
+ AlertRule(view="temp_trend", column="temp", op=">", value=80,
111
+ level="critical", notify=["webhook"]),
112
+ ],
113
+ # KPI cards and Andon wallboard
114
+ kpis={"count": KpiCard(title="Samples", query="SELECT COUNT(*) FROM measurements")},
115
+ kiosk=KioskConfig(rotate_seconds=15, theme="dark"),
116
+ )
117
+ ```
118
+
119
+ Environment-specific values (never in `config.py`) go in `.env`:
120
+
121
+ ```sh
122
+ MONITOR_DATABASE_URL=postgresql+pg8000://user:pass@db:5432/monitor # default: SQLite
123
+ MONITOR_API_KEY=change-me # enables X-API-Key auth on writes
124
+ MONITOR_INGEST_WATCH=true # auto-import csv/ on change
125
+ MONITOR_AUDIT_ENABLED=true # record change history
126
+ MONITOR_WEBHOOK_URL=https://hooks.slack.com/services/...
127
+ ```
128
+
129
+ ## 🌐 Endpoints
130
+
131
+ | Path | Description |
132
+ |---|---|
133
+ | `/` | Home: dashboard with mini-charts, KPI cards, and view list |
134
+ | `/table/{view}` | Live table / chart page |
135
+ | `/kiosk` | Andon wallboard (full screen, auto-rotating) |
136
+ | `/form/{table}` | Operator entry form |
137
+ | `/docs`, `/redoc` | OpenAPI documentation |
138
+ | `/api/tables/{table}` | CRUD (GET/POST/PUT/DELETE) |
139
+ | `/api/ingest/{table}` | Bulk ingest for sensors/PLC |
140
+ | `/api/views/{view}` | View data (+ `/stream` for SSE, `/export` for CSV/Excel) |
141
+ | `/api/kpis`, `/api/alerts`, `/api/audit`, `/api/schema`, `/api/health` | KPIs, active alerts, audit log, schema, health |
142
+
143
+ ## 🔌 External tool integrations (v2.2)
144
+
145
+ Connect procdiag, netdiag, and network-checker to Monitor App with a few lines — no changes to the external tools required (read-only, pull-based).
146
+
147
+ ```python
148
+ from monitor_app.integrations import procdiag, netdiag, network_checker
149
+
150
+ config = procdiag.attach(config, db_path="/opt/procdiag/data/procdiag.db")
151
+ config = netdiag.attach(config)
152
+ config = network_checker.attach(config, hosts=["plc-01", "gateway"])
153
+ ```
154
+
155
+ Each `attach()` call merges tables, views, KPIs, and alert rules into your existing config. Run `monitor-app sync-sources` to ingest on demand, or set `MONITOR_INGEST_WATCH=1` for continuous polling.
156
+
157
+ Full reference: [docs/integrations_v2_2.md](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/integrations_v2_2.md)
158
+
159
+ ---
160
+
161
+ ## 🔄 Migrating from v0.x
162
+
163
+ v2 was rebuilt on FastAPI + Pydantic. The legacy dict-style `config.py`
164
+ (`ALLOWED_TABLES` / `VIEW_TABLES` / `TABLE_CELL_STYLES`) **still loads** through a
165
+ compatibility shim, but new projects should use `MonitorConfig`. Key changes:
166
+
167
+ - `python app.py runserver` → `monitor-app runserver` (the app no longer lives in your project)
168
+ - DB settings (`DB_TYPE`, passwords) → `MONITOR_DATABASE_URL` environment variable
169
+ - API paths: `/api/<table>` → `/api/tables/{table}`, `/api/view/<v>` → `/api/views/{view}`
170
+
171
+ Details: [redesign notes](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/redesign_v2.md) ·
172
+ [v2.1 feature design](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/feature_expansion_v2.1.md) ·
173
+ [v2.2 integrations](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/integrations_v2_2.md) ·
174
+ [v2.3 UI redesign](https://github.com/mikawa-bushi/monitor-app/blob/main/docs/ui_redesign_v2_3.md)
175
+
176
+ ## 🐳 Docker
177
+
178
+ ```sh
179
+ docker build -t monitor-app -f docker/Dockerfile .
180
+ docker run -v $(pwd)/myproject:/project -p 9990:9990 monitor-app
181
+ ```
182
+
183
+ ## 🛠 Development
184
+
185
+ ```sh
186
+ git clone https://github.com/mikawa-bushi/monitor-app.git
187
+ cd monitor-app
188
+ poetry install
189
+ poetry run pytest
190
+ ```
191
+
192
+ Contributions are welcome — see [CONTRIBUTING.md](https://github.com/mikawa-bushi/monitor-app/blob/main/CONTRIBUTING.md).
193
+
194
+ ## 📜 License
195
+
196
+ [MIT](https://github.com/mikawa-bushi/monitor-app/blob/main/LICENSE)
@@ -0,0 +1,33 @@
1
+ """monitor-app: CSV を置くだけで Web UI と REST API が生えるデータ監視ツール。
2
+
3
+ 公開 API として、ユーザーが ``config.py`` で使う宣言モデルを再エクスポートする。
4
+ """
5
+
6
+ from .settings.declarative import (
7
+ AlertRule,
8
+ CellStyle,
9
+ ChartDef,
10
+ FormDef,
11
+ KioskConfig,
12
+ KpiCard,
13
+ MonitorConfig,
14
+ TableDef,
15
+ Threshold,
16
+ ViewDef,
17
+ )
18
+
19
+ __version__ = "2.1.0"
20
+
21
+ __all__ = [
22
+ "AlertRule",
23
+ "CellStyle",
24
+ "ChartDef",
25
+ "FormDef",
26
+ "KioskConfig",
27
+ "KpiCard",
28
+ "MonitorConfig",
29
+ "TableDef",
30
+ "Threshold",
31
+ "ViewDef",
32
+ "__version__",
33
+ ]
@@ -0,0 +1 @@
1
+ """API 層。FastAPI ルーター・依存・スキーマ・例外ハンドラ。"""
@@ -0,0 +1,140 @@
1
+ """FastAPI 依存。アプリ状態(app.state)へのアクセスと API キー / セッション検証。
2
+
3
+ 認証(#11): 書き込み系は ``api_key`` 設定時に必須、読み取り系は ``protect_reads``
4
+ 有効時に必須。クライアントは **X-API-Key ヘッダ** か **セッション Cookie** の
5
+ どちらかで認証できる。Cookie は同梱 Web UI がブラウザから認証するための経路で、
6
+ ``/api/login`` がキー検証後に発行する(値はキーの HMAC で、生キーは保存しない)。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import hmac
13
+ import secrets
14
+
15
+ from fastapi import Depends, HTTPException, Request, Security
16
+ from fastapi.security import APIKeyHeader
17
+
18
+ from ..services.crud_service import CrudService
19
+ from ..services.view_service import ViewService
20
+ from ..settings.declarative import MonitorConfig
21
+ from ..settings.runtime import AppSettings
22
+
23
+ _api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
24
+
25
+ #: セッション Cookie 名(#11)。
26
+ SESSION_COOKIE = "monitor_session"
27
+
28
+
29
+ def session_token(api_key: str) -> str:
30
+ """API キーから導出する署名付きセッショントークン。
31
+
32
+ 生キーを Cookie に置かないための HMAC。ステートレスなので再起動・多ワーカーでも
33
+ 一貫して検証できる。"""
34
+ return hmac.new(
35
+ api_key.encode("utf-8"), b"monitor-session", hashlib.sha256
36
+ ).hexdigest()
37
+
38
+
39
+ def get_settings(request: Request) -> AppSettings:
40
+ return request.app.state.settings
41
+
42
+
43
+ def get_config(request: Request) -> MonitorConfig:
44
+ return request.app.state.config
45
+
46
+
47
+ def get_crud_service(request: Request) -> CrudService:
48
+ return request.app.state.crud_service
49
+
50
+
51
+ def get_view_service(request: Request) -> ViewService:
52
+ return request.app.state.view_service
53
+
54
+
55
+ def get_alert_engine(request: Request):
56
+ """AlertEngine を返す(フェーズ1・A)。"""
57
+ return request.app.state.alert_engine
58
+
59
+
60
+ def get_kpi_service(request: Request):
61
+ """KpiService を返す(フェーズ2・E)。"""
62
+ return request.app.state.kpi_service
63
+
64
+
65
+ def get_audit_service(request: Request):
66
+ """AuditService を返す(フェーズ4・G)。"""
67
+ return request.app.state.audit_service
68
+
69
+
70
+ def _is_authed(settings: AppSettings, request: Request, provided: str | None) -> bool:
71
+ """ヘッダ or セッション Cookie で認証済みか。api_key 未設定なら常に True。"""
72
+ if settings.api_key is None:
73
+ return True
74
+ if provided and secrets.compare_digest(provided, settings.api_key):
75
+ return True
76
+ cookie = request.cookies.get(SESSION_COOKIE)
77
+ if cookie and secrets.compare_digest(cookie, session_token(settings.api_key)):
78
+ return True
79
+ return False
80
+
81
+
82
+ def get_actor(
83
+ request: Request,
84
+ provided: str | None = Security(_api_key_header),
85
+ ) -> str:
86
+ """監査用の実行主体を表す文字列(フェーズ4・G)。
87
+
88
+ ヘッダ認証なら "api"、Cookie セッションなら "ui"、いずれも無ければ "anon"。
89
+ クライアント IP を添える。
90
+ """
91
+ client = request.client.host if request.client else "unknown"
92
+ if provided:
93
+ who = "api"
94
+ elif request.cookies.get(SESSION_COOKIE):
95
+ who = "ui"
96
+ else:
97
+ who = "anon"
98
+ return f"{who}@{client}"
99
+
100
+
101
+ def _check_auth(settings: AppSettings, request: Request, provided: str | None) -> None:
102
+ if not _is_authed(settings, request, provided):
103
+ raise HTTPException(
104
+ status_code=401,
105
+ detail={"code": "UNAUTHORIZED", "message": "API キーが無効です"},
106
+ )
107
+
108
+
109
+ def require_write_auth(
110
+ request: Request,
111
+ settings: AppSettings = Depends(get_settings),
112
+ provided: str | None = Security(_api_key_header),
113
+ ) -> None:
114
+ """書き込み系(POST/PUT/DELETE)で必須。api_key 未設定なら素通り。"""
115
+ _check_auth(settings, request, provided)
116
+
117
+
118
+ def require_read_auth(
119
+ request: Request,
120
+ settings: AppSettings = Depends(get_settings),
121
+ provided: str | None = Security(_api_key_header),
122
+ ) -> None:
123
+ """読み取り系。protect_reads=True かつ api_key 設定時のみ検証。"""
124
+ if settings.protect_reads:
125
+ _check_auth(settings, request, provided)
126
+
127
+
128
+ class RedirectToLogin(Exception):
129
+ """HTML ページが未認証のとき送出。/login へのリダイレクトに変換される(#11)。"""
130
+
131
+
132
+ def page_auth_guard(
133
+ request: Request,
134
+ settings: AppSettings = Depends(get_settings),
135
+ provided: str | None = Security(_api_key_header),
136
+ ) -> None:
137
+ """HTML ページ用ガード。protect_reads+api_key 有効かつ未認証なら /login へ。"""
138
+ if settings.protect_reads and settings.api_key:
139
+ if not _is_authed(settings, request, provided):
140
+ raise RedirectToLogin()
@@ -0,0 +1,39 @@
1
+ """ドメイン例外を JSON レスポンスに変換するハンドラ。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import uuid
7
+
8
+ from fastapi import FastAPI, Request
9
+ from fastapi.responses import JSONResponse, RedirectResponse
10
+
11
+ from ..exceptions import MonitorAppError
12
+ from .deps import RedirectToLogin
13
+
14
+ logger = logging.getLogger("monitor_app.api")
15
+
16
+
17
+ def _body(code: str, message: str) -> dict:
18
+ return {"detail": {"code": code, "message": message}}
19
+
20
+
21
+ def register_exception_handlers(app: FastAPI) -> None:
22
+ @app.exception_handler(MonitorAppError)
23
+ async def _handle_domain(_request: Request, exc: MonitorAppError):
24
+ # 500 系は内部詳細を漏らさず、相関 ID だけ返してログに残す。
25
+ if exc.status_code >= 500:
26
+ ref = uuid.uuid4().hex[:8]
27
+ logger.error("[%s] %s: %s", ref, exc.code, exc.message, exc_info=exc)
28
+ return JSONResponse(
29
+ status_code=exc.status_code,
30
+ content=_body(exc.code, f"内部エラーが発生しました (ref={ref})"),
31
+ )
32
+ return JSONResponse(
33
+ status_code=exc.status_code, content=_body(exc.code, exc.message)
34
+ )
35
+
36
+ @app.exception_handler(RedirectToLogin)
37
+ async def _handle_login_redirect(_request: Request, _exc: RedirectToLogin):
38
+ # 未認証の HTML ページアクセスはログインページへ誘導する(#11)。
39
+ return RedirectResponse(url="/login", status_code=303)
@@ -0,0 +1 @@
1
+ """FastAPI ルーター群。"""
@@ -0,0 +1,18 @@
1
+ """アラート閲覧エンドポイント(フェーズ1・A)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import APIRouter, Depends
6
+
7
+ from ..deps import get_alert_engine, require_read_auth
8
+
9
+ router = APIRouter(prefix="/api/alerts", tags=["Alerts"])
10
+
11
+
12
+ @router.get("")
13
+ def list_active_alerts(
14
+ engine=Depends(get_alert_engine),
15
+ _: None = Depends(require_read_auth),
16
+ ):
17
+ """現在アクティブな(発火中の)アラート一覧。"""
18
+ return {"alerts": engine.active_alerts()}