Metadata-Version: 2.4
Name: meteorlens
Version: 0.0.0
Summary: Local-first meteor detection from IP cameras
Author: MeteorLens contributors
License: MIT
Project-URL: Homepage, https://github.com/svatec/meteorlens
Keywords: meteor,astronomy,opencv,rtsp,camera,detection
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Astronomy
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: numpy>=1.26
Requires-Dist: opencv-python-headless>=4.9
Requires-Dist: flask>=3.0
Provides-Extra: calibrate
Requires-Dist: scipy>=1.11; extra == "calibrate"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Dynamic: license-file

# MeteorLens

Local-first meteor detection from IP cameras. MeteorLens records RTSP segments,
detects meteors with OpenCV, stores events in SQLite, and serves a dashboard,
a detections gallery, and a small control/settings page.

The project is an early community edition (v0.1.0, alpha). The detection core is
shared with a private production deployment; the community edition deliberately
drops publishing features (Instagram Reels, stories, timelapse) and keeps the
pipeline easy to run and extend.

## Requirements

- Python 3.11 or newer
- `ffmpeg` and `ffprobe` on `PATH`
- An RTSP camera (tested with Tapo C325WB; any camera that exposes H.264 over RTSP
  should work, but thresholds and masks are scene-specific), or a folder with
  existing MKV segments for analysis-only use

## Quick start

```bash
git clone https://github.com/svatec/meteorlens.git
cd meteorlens
python3 -m venv .venv
. .venv/bin/activate
pip install -e ".[dev]"

meteorlens serve
```

Open <http://127.0.0.1:8765>. On a fresh home MeteorLens starts the setup wizard
instead of the dashboard:

1. choose an RTSP camera or a folder with existing MKV segments,
2. set the observing location,
3. test the camera stream (codec, resolution, frame rate, bitrate),
4. pick storage and recording defaults,
5. choose a detection profile.

The wizard writes `config.ini` atomically with mode `0600` and creates the data
directories. An existing file is backed up to `config.ini.bak`; the camera URL is
never shown again. Re-run the wizard from Settings or `/setup`.
[Setup wizard screenshot](docs/screenshots/setup.png).

To configure manually instead:

```bash
cp config.example.ini config.ini
# edit camera.rtsp_url, location.latitude and location.longitude
meteorlens serve
```

The dashboard and gallery are read-only until you start recording or analysis
from the control page.

Run the recorder and the analyzer as separate long-lived processes:

```bash
meteorlens record          # capture RTSP segments while it is dark
meteorlens run             # analyse new segments (cron/systemd timer or manually)
```

`meteorlens serve` is a local tool: it binds to `127.0.0.1` by default, has no
authentication and must not be exposed to the internet without a reverse proxy
and access control.

## Demo data and screenshots

You do not need a camera to explore the UI. The demo builder creates three
deterministic synthetic clips, runs the real analyser, labels two meteors and
one aircraft candidate, and exports the demo home:

```bash
python docs/demo/make_demo.py --home /tmp/meteorlens-demo
METEORLENS_HOME=/tmp/meteorlens-demo meteorlens serve
```

The demo home contains no personal data; delete it when done. Screenshots from
this demo: [Dashboard](docs/screenshots/dashboard.png),
[Detections](docs/screenshots/detections.png),
[Settings](docs/screenshots/settings.png). The live panel shows "Camera
unavailable" because the demo has no RTSP camera, and the sky map falls back to
the camera axis because the demo has no calibration.

## Configuration

MeteorLens reads `config.ini` from `METEORLENS_HOME` (default: the current
directory). Relative paths in `[paths]` are resolved against the same directory.

- `[camera]` is never shown in the UI and never written by the settings page.
  The first-run wizard is the only web path that writes it; the file is mode `0600`.
- `[detect]` contains the detection thresholds. Change them only together with
  the regression tests; the project treats threshold changes as behaviour changes.
- `[calibration]` is optional. Without it, events have no azimuth/altitude angles
  and the sky map falls back to the camera axis.
- `[showers]` enables meteor-shower association from the bundled IAU-derived
  catalogue.

Runtime layout:

```
config.ini
data/
  recordings/active/       # segment being written
  recordings/ready/        # finished MKV segments (UTC names)
  detections/              # clips, thumbnails, events.csv, tracks.csv
  state/                   # SQLite database, logs, locks, control state
```

## Commands

| Command | Description |
|---|---|
| `meteorlens record` | Record RTSP segments while the Sun is below the configured altitude. |
| `meteorlens run` | Analyse new segments. `--reprocess`, `--before`, `--after` control the range. |
| `meteorlens file FILE` | Analyse one file; `-v` prints rejected tracks, `--dry` writes nothing. |
| `meteorlens snapshot [FILE]` | Save a frame as `mask_template.png` for drawing a sky mask. |
| `meteorlens serve` | Start the local web UI; an incomplete config opens the setup wizard. |
| `meteorlens index` | Rebuild the static `detections/index.html` page. |
| `meteorlens export` | Export the SQLite database to CSV/JSON. |
| `meteorlens purge [--dry]` | Delete events labelled as insect/aircraft/cloud/satellite. |
| `meteorlens bench FILE` | Measure analysis speed and suggest worker settings. |
| `meteorlens-calibrate` | Solve the camera model from stars (requires `pip install -e ".[calibrate]"`). |

## Calibration and masks

The bundled mask is only an example. For your own camera:

```bash
meteorlens snapshot data/recordings/ready/YYYYMMDD_HHMMSS.mkv
# paint everything except the sky black, save as mask.png, then set in config.ini:
# [detect] mask = mask.png
```

Camera calibration (focal length, orientation) is optional and uses `scipy`:

```bash
pip install -e ".[calibrate]"
meteorlens-calibrate solve --video FILE --at 60 --lat 48.0 --lon 17.0 \
  --az 270 --alt 35 --out calibration.json
# then set [calibration] file = calibration.json
```

## Architecture

```
camera --RTSP--> meteorlens record --> data/recordings/ready/*.mkv
                                          |
                                          v
                                   meteorlens run (multiprocessing)
                                          |
                          SQLite + clips/thumbnails + CSV exports
                                          |
                                          v
                             meteorlens serve (Flask, localhost)
```

- `capture.py` - ffmpeg segment recorder and disk guard.
- `detect.py` - frame differencing, blob tracking, track classification.
- `astrometry.py`, `showers.py` - angles, radiant and shower association.
- `store.py` - SQLite schema, migrations, queries and exports.
- `runner.py` - parallel segment processing, clip cutting, retention/purge.
- `web/` - Flask app factory, first-run setup wizard, `routes/` blueprints (pages,
  API, control, media), Jinja templates and static CSS/JS assets.
- `control.py` - starts/stops recorder and analyzer subprocesses.

Long-running work stays in subprocesses so ffmpeg and OpenCV cannot block the
web UI. The web process only reads the database and file outputs.

## Development

```bash
pip install -e ".[dev]"
pytest
ruff check .
```

The regression suite uses synthetic meteors inserted into a noisy background,
so it runs without a camera. `pytest tests/test_e2e.py` exercises the real CLI
(`file`, `run`, `snapshot`, `index`, `export`, `purge --dry`) in a temporary
`METEORLENS_HOME`; recorder startup is covered with a mock ffmpeg process. A
real reference clip can be provided out of band:

```bash
METEORLENS_REF_CLIP=/path/to/reference.mkv pytest tests/test_reference_clip.py
```

Detection thresholds are scene-specific, so tune them by measuring instead of
guessing. The development tools in `tools/` are not part of the package:

```bash
# one row per clip with the current config (no database writes)
python -m tools.sweep --clips data/recordings/ready --out /tmp/tune/baseline.csv

# grid over two thresholds; score the result against known counts
python -m tools.sweep --clips tests/clips --grid diff_threshold=14,18,22 \
    --grid min_speed=100,120 --out /tmp/tune/grid.csv --detail /tmp/tune/events.csv
python -m tools.score --sweep /tmp/tune/grid.csv --expect tests/clips/expected.json
```

`--detail` writes one row per accepted and rejected track (span, speed, peak,
duration, reason), which is usually enough to see whether a false positive comes
from noise, a cloud edge, or the track-linking limits. A combination that scores
well belongs in `tests/clips/expected.json`; the clips themselves stay local
(`*.mkv`, `*.mp4` are ignored by git).

Do not commit camera recordings, `config.ini`, the database, or generated clips.

## Troubleshooting

**`Missing configuration`** - `meteorlens run/file/record` read `config.ini` from
`METEORLENS_HOME` (default: current directory). Run `meteorlens serve` once:
without a complete config it opens the setup wizard at `/setup`, which writes
the file and creates the data directories. For analysis-only setups choose
"Existing recordings" and point the wizard at the MKV folder.

**`ffmpeg` or `ffprobe` not found** - install both and make sure they are on
`PATH`. Use `meteorlens bench FILE` to compare decoders and estimate worker
counts.

**The camera is unavailable** - test the stream outside MeteorLens
(`ffprobe -rtsp_transport tcp rtsp_url`). Try switching `camera.rtsp_transport`
between `udp` and `tcp`; UDP is usually better on lossy Wi-Fi, TCP on stable
networks. Credentials stay in `config.ini` and are never shown in the UI.

**No detections** - check focus, exposure and that the sky is dark; inspect
`meteorlens file CLIP -v` for rejected tracks. A scene mask and calibration
usually improve results. Detection thresholds are scene-specific; do not tune
them without running the regression suite.

**Sky map says calibration or location is missing** - the map needs
`[calibration] file` and `[location] latitude/longitude`. Without calibration,
events have no angles and the map falls back to the camera axis.

**Calibration fails with a scipy error** - install the optional extra:
`pip install -e ".[calibrate]"`.

**The web page has no styling or JavaScript** - the templates and static assets
must be installed with the package; reinstall with `pip install -e .` (or a
wheel built from this repository). Check `/static/app.css` returns 200.

**Port 8765 is already in use** - start with another port, for example
`meteorlens serve --port 8766`.

**`purge` refuses to run** - analysis or another purge holds `run.lock`; wait
for it to finish. Use `purge --dry` to see what would be deleted.

## Data and licence

Code is released under the MIT licence (see `LICENSE`). Bundled catalogues are
described in `NOTICE`; keep that notice when redistributing.
