feat(channels): store channel profiles in local SQLite with CRUD API
Replace the committed channels/<slug>.json files as the runtime source of truth with a local SQLite database at the repo root (clipwright.db), overridable via CLIPWRIGHT_DB. Existing JSON profiles are imported once on first bootstrap, then the store is authoritative. - add clipwright/storage/channel_profiles.py (stdlib sqlite3, WAL + lock) - add Profile/TitleRules/ThumbnailRules.to_dict() for round-tripping - load_profile/list_profiles read the store; channels_dir stays a file seam - /api/channels CRUD plus import/export endpoints - untrack channels/*.json, ignore the DB files - seed a temp DB in tests/conftest.py
This commit is contained in:
parent
9823e8fe69
commit
ab5cdb87a9
11 changed files with 779 additions and 109 deletions
8
.gitignore
vendored
8
.gitignore
vendored
|
|
@ -16,6 +16,14 @@ __pycache__/
|
|||
uploads/
|
||||
output/
|
||||
|
||||
# Legacy channel profile source (migrated into clipwright.db on first run)
|
||||
channels/
|
||||
|
||||
# Local SQLite runtime state
|
||||
clipwright.db
|
||||
clipwright.db-wal
|
||||
clipwright.db-shm
|
||||
|
||||
# OS / IDE
|
||||
.DS_Store
|
||||
.idea/
|
||||
|
|
|
|||
|
|
@ -1,30 +0,0 @@
|
|||
{
|
||||
"name": "cseea",
|
||||
"language": "en",
|
||||
"tone": "nostalgic and calm; curious, never hype",
|
||||
"title_rules": {
|
||||
"max_chars": 60,
|
||||
"mobile_chars": 38,
|
||||
"banned_patterns": ["in this video", "tutorial", "let's play", "how to"],
|
||||
"keyword_position": "start",
|
||||
"number_policy": "avoid",
|
||||
"required_signal": "curiosity",
|
||||
"banned_openers": ["Exploring", "Building", "Playing", "A look at"]
|
||||
},
|
||||
"hook_patterns": [
|
||||
"this shouldn't be possible in Alpha",
|
||||
"the mechanic Mojang forgot to remove",
|
||||
"you were never supposed to see this",
|
||||
"I broke the world in one block"
|
||||
],
|
||||
"hook_style": "visual impossibility at frame 0; show the glitch before any words",
|
||||
"description_template": "{hook}\n\nFull video: {link}\n\n#minecraft #alpha #retro",
|
||||
"links": ["https://www.youtube.com/@cseea"],
|
||||
"thumbnail": {
|
||||
"role_order": ["curiosity", "emotion", "technical"],
|
||||
"palette": ["mossy green", "cobblestone grey", "torch orange"],
|
||||
"presenter_photo": false
|
||||
},
|
||||
"default_postiz_integration_id": null,
|
||||
"published_video_history": []
|
||||
}
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
{
|
||||
"name": "Pedro Bento",
|
||||
"language": "en",
|
||||
"tone": "technical, direct, engineering-focused",
|
||||
"title_rules": {
|
||||
"max_chars": 70,
|
||||
"mobile_chars": 42,
|
||||
"banned_patterns": ["in this video", "for beginners", "quick tip"],
|
||||
"keyword_position": "start",
|
||||
"number_policy": "allow",
|
||||
"required_signal": "consequence",
|
||||
"banned_openers": ["Explaining", "Discussing", "Talking about"]
|
||||
},
|
||||
"hook_patterns": [
|
||||
"it crashes the moment you resize",
|
||||
"watch the benchmark number change",
|
||||
"the bug that survived three rewrites",
|
||||
"this one syscall cost 40% throughput"
|
||||
],
|
||||
"hook_style": "show the working demo or the bug first, then state the stake in one line",
|
||||
"description_template": "{hook}\n\nChapters and source: {link}\n\n#c #linux #systems",
|
||||
"links": ["https://github.com/pbento"],
|
||||
"thumbnail": {
|
||||
"role_order": ["technical", "curiosity", "emotion"],
|
||||
"palette": ["terminal black", "signal amber", "trace red"],
|
||||
"presenter_photo": true
|
||||
},
|
||||
"default_postiz_integration_id": null,
|
||||
"published_video_history": []
|
||||
}
|
||||
|
|
@ -20,7 +20,7 @@ from datetime import datetime, timezone, timedelta
|
|||
from dotenv import load_dotenv
|
||||
from typing import Any, Dict, Optional, List
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks
|
||||
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks, Body
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
|
@ -1782,13 +1782,103 @@ async def list_channels():
|
|||
"""The channel profiles a job can be tagged with (PLAN #1).
|
||||
|
||||
Each entry is ``{"slug", "name"}`` for the dashboard's profile selector:
|
||||
``slug`` is the ``channels/<slug>.json`` filename stem and ``name`` is the
|
||||
profile's display name, falling back to the slug when the file omits it.
|
||||
Malformed profile files are skipped by the loader, so the selector always
|
||||
receives a usable list.
|
||||
``slug`` is the profile's id and ``name`` is its display name, falling back
|
||||
to the slug when unset. Profiles live in the SQLite store
|
||||
(``clipwright.storage.channel_profiles``); malformed legacy files are
|
||||
skipped once at import, so the selector always receives a usable list.
|
||||
"""
|
||||
return {"channels": profiles.list_profiles()}
|
||||
|
||||
|
||||
# NOTE: the static export/import routes must stay ABOVE ``/api/channels/{slug}``
|
||||
# or FastAPI would match ``export``/``import`` as a slug.
|
||||
@app.get("/api/channels/export")
|
||||
async def export_channels(slug: Optional[str] = None):
|
||||
"""Download all profiles (or one, with ``?slug=``) as a portable JSON file."""
|
||||
if slug:
|
||||
try:
|
||||
payload = profiles.profile_payload(slug)
|
||||
except profiles.ProfileError:
|
||||
raise HTTPException(status_code=404, detail=f"channel profile not found: {slug}")
|
||||
body = {"version": 1, "profiles": [payload]}
|
||||
filename = f"channel-profile-{slug}.json"
|
||||
else:
|
||||
body = profiles.export_payload()
|
||||
filename = "channel-profiles.json"
|
||||
return JSONResponse(
|
||||
body,
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/channels/import")
|
||||
async def import_channels(payload: Any = Body(...)):
|
||||
"""Import profiles from an export document, a bare list or a single dict."""
|
||||
try:
|
||||
return profiles.import_payload(payload)
|
||||
except profiles.ProfileError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/api/channels/{slug}")
|
||||
async def get_channel(slug: str):
|
||||
"""One profile in its full API shape, or 404."""
|
||||
try:
|
||||
return profiles.profile_payload(slug)
|
||||
except profiles.ProfileError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
|
||||
|
||||
@app.post("/api/channels")
|
||||
async def create_channel(payload: dict = Body(...)):
|
||||
"""Create a new profile; 409 when the slug is already taken."""
|
||||
slug = str(payload.get("slug") or "").strip() if isinstance(payload, dict) else ""
|
||||
if not slug:
|
||||
raise HTTPException(status_code=400, detail="slug is required")
|
||||
try:
|
||||
profiles.load_profile(slug)
|
||||
exists = True
|
||||
except profiles.ProfileError:
|
||||
exists = False
|
||||
if exists:
|
||||
raise HTTPException(
|
||||
status_code=409, detail=f"channel profile already exists: {slug}"
|
||||
)
|
||||
data = {key: value for key, value in payload.items() if key != "slug"}
|
||||
try:
|
||||
profiles.save_profile(slug, data)
|
||||
return profiles.profile_payload(slug)
|
||||
except profiles.ProfileError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@app.put("/api/channels/{slug}")
|
||||
async def update_channel(slug: str, payload: dict = Body(...)):
|
||||
"""Create or replace a profile under the path slug."""
|
||||
data = (
|
||||
{key: value for key, value in payload.items() if key != "slug"}
|
||||
if isinstance(payload, dict)
|
||||
else {}
|
||||
)
|
||||
try:
|
||||
profiles.save_profile(slug, data)
|
||||
return profiles.profile_payload(slug)
|
||||
except profiles.ProfileError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@app.delete("/api/channels/{slug}")
|
||||
async def delete_channel(slug: str):
|
||||
"""Delete a profile, or 404 when it does not exist."""
|
||||
try:
|
||||
deleted = profiles.delete_profile(slug)
|
||||
except profiles.ProfileError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail=f"channel profile not found: {slug}")
|
||||
return {"deleted": True}
|
||||
|
||||
|
||||
async def _probe_youtube_quality(url: str) -> dict:
|
||||
"""Run quality_probe.py in a worker thread; {} on any failure (fail-open)."""
|
||||
def _run():
|
||||
|
|
|
|||
|
|
@ -6,11 +6,14 @@ later items (#3, #4, #6, #10) read. This v0 defines the schema, the validating
|
|||
loader and the ``CHANNEL_PROFILE`` plumbing only -- nothing here changes how
|
||||
titles, hooks or descriptions are generated yet.
|
||||
|
||||
Files live at ``<repo>/channels/<slug>.json``. Every field is optional and
|
||||
falls back to a sensible default, so a minimal ``{"language": "en"}`` file
|
||||
loads. Unknown keys are ignored so a newer profile can ship ahead of the code;
|
||||
known keys with the wrong type or an out-of-domain enum are refused with a
|
||||
message that names the exact path.
|
||||
The runtime source of truth is the SQLite store in
|
||||
``clipwright.storage.channel_profiles`` (``<repo>/clipwright.db``). A one-time
|
||||
migration imports the legacy ``<repo>/channels/<slug>.json`` files on first
|
||||
bootstrap; ``channels_dir`` remains a test/embedding seam that reads straight
|
||||
from a directory. Every field is optional and falls back to a sensible default,
|
||||
so a minimal ``{"language": "en"}`` profile loads. Unknown keys are ignored so a
|
||||
newer profile can ship ahead of the code; known keys with the wrong type or an
|
||||
out-of-domain enum are refused with a message that names the exact path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
|
@ -165,6 +168,18 @@ class TitleRules:
|
|||
),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""Serialise to the exact shape :meth:`from_dict` accepts."""
|
||||
return {
|
||||
"max_chars": self.max_chars,
|
||||
"mobile_chars": self.mobile_chars,
|
||||
"banned_patterns": list(self.banned_patterns),
|
||||
"keyword_position": self.keyword_position,
|
||||
"number_policy": self.number_policy,
|
||||
"required_signal": self.required_signal,
|
||||
"banned_openers": list(self.banned_openers),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ThumbnailRules:
|
||||
|
|
@ -190,6 +205,14 @@ class ThumbnailRules:
|
|||
),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""Serialise to the exact shape :meth:`from_dict` accepts."""
|
||||
return {
|
||||
"role_order": list(self.role_order),
|
||||
"palette": list(self.palette),
|
||||
"presenter_photo": self.presenter_photo,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Profile:
|
||||
|
|
@ -236,24 +259,30 @@ class Profile:
|
|||
),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""Serialise every field except ``slug``.
|
||||
|
||||
def load_profile(slug: str | None = None, channels_dir: str | os.PathLike | None = None) -> Profile:
|
||||
"""Load and validate ``channels/<slug>.json``.
|
||||
The result matches :meth:`from_dict`'s expected shapes exactly, so
|
||||
``Profile.from_dict(p.to_dict(), p.slug)`` round-trips.
|
||||
"""
|
||||
return {
|
||||
"name": self.name,
|
||||
"language": self.language,
|
||||
"tone": self.tone,
|
||||
"title_rules": self.title_rules.to_dict(),
|
||||
"hook_patterns": list(self.hook_patterns),
|
||||
"hook_style": self.hook_style,
|
||||
"description_template": self.description_template,
|
||||
"links": list(self.links),
|
||||
"thumbnail": self.thumbnail.to_dict(),
|
||||
"default_postiz_integration_id": self.default_postiz_integration_id,
|
||||
"published_video_history": [dict(item) for item in self.published_video_history],
|
||||
}
|
||||
|
||||
``slug`` wins; when it is omitted the ``CHANNEL_PROFILE`` env var is used.
|
||||
``channels_dir`` is test/embedding seam -- it defaults to the repo's
|
||||
``channels/`` directory.
|
||||
"""
|
||||
resolved = slug or os.environ.get(ENV_VAR) or None
|
||||
if not resolved:
|
||||
raise ProfileError(f"no channel profile selected; pass a slug or set {ENV_VAR}")
|
||||
if not _SLUG_RE.match(resolved):
|
||||
raise ProfileError(
|
||||
f"invalid channel slug {resolved!r}; expected letters, digits, '-' or '_'"
|
||||
)
|
||||
|
||||
directory = Path(channels_dir) if channels_dir is not None else CHANNELS_DIR
|
||||
path = directory / f"{resolved}.json"
|
||||
def _load_profile_file(slug: str, directory: Path) -> Profile:
|
||||
"""Read and validate ``<directory>/<slug>.json`` (file-backed seam)."""
|
||||
path = directory / f"{slug}.json"
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
|
|
@ -266,19 +295,11 @@ def load_profile(slug: str | None = None, channels_dir: str | os.PathLike | None
|
|||
except json.JSONDecodeError as e:
|
||||
raise ProfileError(f"malformed JSON in {path}: {e}")
|
||||
|
||||
return Profile.from_dict(data, resolved)
|
||||
return Profile.from_dict(data, slug)
|
||||
|
||||
|
||||
def list_profiles(channels_dir: str | os.PathLike | None = None) -> list[dict]:
|
||||
"""List the loadable channel profiles as ``[{"slug", "name"}]``.
|
||||
|
||||
Best-effort by design: every ``channels/*.json`` that validates is included
|
||||
(sorted by slug) and everything else is skipped, so one malformed profile
|
||||
cannot break a selector. ``slug`` is the filename stem and ``name`` is the
|
||||
profile's display name, falling back to ``slug`` when the file omits it.
|
||||
``channels_dir`` is the same test/embedding seam as :func:`load_profile`.
|
||||
"""
|
||||
directory = Path(channels_dir) if channels_dir is not None else CHANNELS_DIR
|
||||
def _list_profiles_dir(directory: Path) -> list[dict]:
|
||||
"""Best-effort ``[{"slug", "name"}]`` scan of a ``channels/`` directory."""
|
||||
if not directory.is_dir():
|
||||
return []
|
||||
|
||||
|
|
@ -288,8 +309,126 @@ def list_profiles(channels_dir: str | os.PathLike | None = None) -> list[dict]:
|
|||
if not _SLUG_RE.match(slug):
|
||||
continue
|
||||
try:
|
||||
profile = load_profile(slug, channels_dir=directory)
|
||||
profile = _load_profile_file(slug, directory)
|
||||
except ProfileError:
|
||||
continue
|
||||
out.append({"slug": slug, "name": profile.name or slug})
|
||||
return out
|
||||
|
||||
|
||||
def load_profile(slug: str | None = None, channels_dir: str | os.PathLike | None = None) -> Profile:
|
||||
"""Load and validate a channel profile.
|
||||
|
||||
``slug`` wins; when it is omitted the ``CHANNEL_PROFILE`` env var is used.
|
||||
With ``channels_dir`` the legacy ``<dir>/<slug>.json`` file is read; without
|
||||
it the SQLite store is the source of truth.
|
||||
"""
|
||||
resolved = slug or os.environ.get(ENV_VAR) or None
|
||||
if not resolved:
|
||||
raise ProfileError(f"no channel profile selected; pass a slug or set {ENV_VAR}")
|
||||
if not _SLUG_RE.match(resolved):
|
||||
raise ProfileError(
|
||||
f"invalid channel slug {resolved!r}; expected letters, digits, '-' or '_'"
|
||||
)
|
||||
|
||||
if channels_dir is not None:
|
||||
return _load_profile_file(resolved, Path(channels_dir))
|
||||
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
raw = store.get_raw(resolved)
|
||||
if raw is None:
|
||||
raise ProfileError(f"channel profile not found: {resolved}")
|
||||
return Profile.from_dict(raw, resolved)
|
||||
|
||||
|
||||
def list_profiles(channels_dir: str | os.PathLike | None = None) -> list[dict]:
|
||||
"""List the loadable channel profiles as ``[{"slug", "name"}]``.
|
||||
|
||||
With ``channels_dir`` this scans that directory; otherwise it reads the
|
||||
SQLite store. Best-effort by design: a malformed legacy file is skipped
|
||||
rather than breaking a selector, and ``name`` falls back to ``slug`` when a
|
||||
profile omits its display name.
|
||||
"""
|
||||
if channels_dir is not None:
|
||||
return _list_profiles_dir(Path(channels_dir))
|
||||
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
return store.list_summaries()
|
||||
|
||||
|
||||
def save_profile(slug: str, data: Mapping) -> Profile:
|
||||
"""Validate ``data`` and upsert it into the store under ``slug``."""
|
||||
if not isinstance(slug, str) or not _SLUG_RE.match(slug):
|
||||
raise ProfileError(
|
||||
f"invalid channel slug {slug!r}; expected letters, digits, '-' or '_'"
|
||||
)
|
||||
profile = Profile.from_dict(data, slug)
|
||||
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
store.upsert(slug, profile.name or slug, profile.to_dict())
|
||||
return profile
|
||||
|
||||
|
||||
def delete_profile(slug: str) -> bool:
|
||||
"""Delete a stored profile; ``True`` when it existed."""
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
return store.delete(slug)
|
||||
|
||||
|
||||
def profile_payload(slug: str) -> dict:
|
||||
"""The API shape for one profile: ``{"slug", **profile.to_dict()}``."""
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
raw = store.get_raw(slug)
|
||||
if raw is None:
|
||||
raise ProfileError(f"channel profile not found: {slug}")
|
||||
return {"slug": slug, **Profile.from_dict(raw, slug).to_dict()}
|
||||
|
||||
|
||||
def export_payload() -> dict:
|
||||
"""A portable export document: ``{"version": 1, "profiles": [...]}``."""
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
profiles_out: list[dict] = []
|
||||
for raw in store.list_raw():
|
||||
slug = raw["slug"]
|
||||
profiles_out.append({"slug": slug, **Profile.from_dict(raw, slug).to_dict()})
|
||||
return {"version": 1, "profiles": profiles_out}
|
||||
|
||||
|
||||
def import_payload(payload: Any) -> dict:
|
||||
"""Import profiles from an export document, a bare list or a single dict.
|
||||
|
||||
Bad items are reported in ``failed`` instead of aborting the batch; a
|
||||
payload that is neither a JSON object nor array raises :class:`ProfileError`.
|
||||
"""
|
||||
if isinstance(payload, dict):
|
||||
raw_items = payload.get("profiles")
|
||||
items = raw_items if isinstance(raw_items, list) else [payload]
|
||||
elif isinstance(payload, list):
|
||||
items = payload
|
||||
else:
|
||||
raise ProfileError("channel profile import must be a JSON object or array")
|
||||
|
||||
imported = 0
|
||||
failed: list[dict] = []
|
||||
for item in items:
|
||||
if not isinstance(item, Mapping):
|
||||
failed.append({"slug": "", "error": "profile entry must be a JSON object"})
|
||||
continue
|
||||
slug = item.get("slug")
|
||||
if not isinstance(slug, str) or not slug:
|
||||
failed.append({"slug": "", "error": "profile entry is missing a slug"})
|
||||
continue
|
||||
data = {key: value for key, value in item.items() if key != "slug"}
|
||||
try:
|
||||
save_profile(slug, data)
|
||||
except ProfileError as e:
|
||||
failed.append({"slug": slug, "error": str(e)})
|
||||
continue
|
||||
imported += 1
|
||||
return {"imported": imported, "failed": failed}
|
||||
|
|
|
|||
6
clipwright/storage/__init__.py
Normal file
6
clipwright/storage/__init__.py
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
"""Local persistence helpers for the Clipwright backend.
|
||||
|
||||
Right now this package holds the SQLite-backed channel profile store; future
|
||||
runtime state can follow the same shape (stdlib ``sqlite3``, one file at the
|
||||
repo root, lazily created schema).
|
||||
"""
|
||||
176
clipwright/storage/channel_profiles.py
Normal file
176
clipwright/storage/channel_profiles.py
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
"""SQLite-backed channel profile store.
|
||||
|
||||
This is the runtime source of truth for channel profiles. It replaces the
|
||||
committed ``channels/<slug>.json`` files: on the very first bootstrap (the
|
||||
``seeded`` key is absent from ``meta``) any profile files that the file loader
|
||||
still accepts are imported once, then the guard is set so later runs never
|
||||
re-read the directory. Set ``CLIPWRIGHT_DB`` to move the database; otherwise it
|
||||
lives at ``<repo>/clipwright.db``.
|
||||
|
||||
Threading: FastAPI sync endpoints run in a threadpool, so every public
|
||||
operation is serialized by a module-level re-entrant lock. The pipeline runs in
|
||||
a separate process and relies on SQLite's own locking (WAL + busy timeout).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
|
||||
from clipwright.core.paths import REPO_ROOT
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS channel_profiles (
|
||||
slug TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
data TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def db_path() -> Path:
|
||||
"""Location of the profile database (``CLIPWRIGHT_DB`` overrides)."""
|
||||
override = os.environ.get("CLIPWRIGHT_DB")
|
||||
if override:
|
||||
return Path(override)
|
||||
return REPO_ROOT / "clipwright.db"
|
||||
|
||||
|
||||
def _connect() -> sqlite3.Connection:
|
||||
path = db_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(path, timeout=15)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA busy_timeout=15000")
|
||||
return conn
|
||||
|
||||
|
||||
def _bootstrap(conn: sqlite3.Connection) -> None:
|
||||
"""Create the schema if missing and run the one-time file import."""
|
||||
conn.executescript(_SCHEMA)
|
||||
_seed_if_needed(conn)
|
||||
|
||||
|
||||
def _seed_if_needed(conn: sqlite3.Connection) -> None:
|
||||
seeded = conn.execute("SELECT value FROM meta WHERE key = 'seeded'").fetchone()
|
||||
if seeded is not None:
|
||||
return
|
||||
|
||||
# Lazy import: profiles imports this module from inside its own functions,
|
||||
# so a top-level import here would be circular.
|
||||
from clipwright.pipeline import profiles
|
||||
|
||||
directory = profiles.CHANNELS_DIR
|
||||
if directory.is_dir():
|
||||
for path in sorted(directory.glob("*.json")):
|
||||
slug = path.stem
|
||||
try:
|
||||
profile = profiles.load_profile(slug, channels_dir=directory)
|
||||
except profiles.ProfileError:
|
||||
continue
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO channel_profiles (slug, name, data) "
|
||||
"VALUES (?, ?, ?)",
|
||||
(slug, profile.name or slug, json.dumps(profile.to_dict(), ensure_ascii=False)),
|
||||
)
|
||||
conn.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('seeded', '1')")
|
||||
|
||||
|
||||
def _row_to_dict(row: sqlite3.Row) -> dict:
|
||||
data = json.loads(row["data"])
|
||||
data["slug"] = row["slug"]
|
||||
return data
|
||||
|
||||
|
||||
def get_raw(slug: str) -> dict | None:
|
||||
"""Return the stored profile dict (with ``slug`` injected) or ``None``."""
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
conn.commit()
|
||||
row = conn.execute(
|
||||
"SELECT slug, data FROM channel_profiles WHERE slug = ?", (slug,)
|
||||
).fetchone()
|
||||
return _row_to_dict(row) if row is not None else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_raw() -> list[dict]:
|
||||
"""Every stored profile as a parsed dict with ``slug`` injected."""
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
conn.commit()
|
||||
rows = conn.execute(
|
||||
"SELECT slug, data FROM channel_profiles ORDER BY slug"
|
||||
).fetchall()
|
||||
return [_row_to_dict(row) for row in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_summaries() -> list[dict]:
|
||||
"""``[{"slug", "name"}]`` for every profile, sorted by slug."""
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
conn.commit()
|
||||
rows = conn.execute(
|
||||
"SELECT slug, name FROM channel_profiles ORDER BY slug"
|
||||
).fetchall()
|
||||
return [{"slug": row["slug"], "name": row["name"] or row["slug"]} for row in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert(slug: str, name: str, data: Mapping) -> None:
|
||||
"""Insert or replace a profile row (``updated_at`` is bumped on replace)."""
|
||||
payload = json.dumps(dict(data), ensure_ascii=False)
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO channel_profiles (slug, name, data)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(slug) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
data = excluded.data,
|
||||
updated_at = datetime('now')
|
||||
""",
|
||||
(slug, name, payload),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def delete(slug: str) -> bool:
|
||||
"""Delete a profile; ``True`` when a row was removed."""
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
cursor = conn.execute("DELETE FROM channel_profiles WHERE slug = ?", (slug,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
finally:
|
||||
conn.close()
|
||||
72
tests/_channel_seed.py
Normal file
72
tests/_channel_seed.py
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
"""Seed data for the channel-profile store, mirroring ``channels/*.json``.
|
||||
|
||||
The runtime source of truth moved into SQLite, so the integration tests seed
|
||||
the temp database from here via ``profiles.save_profile`` instead of relying on
|
||||
the (now git-ignored) ``channels/*.json`` files. Values match those files
|
||||
exactly because existing prompt/validator tests assert on them.
|
||||
"""
|
||||
|
||||
SEED = {
|
||||
"cseea": {
|
||||
"name": "cseea",
|
||||
"language": "en",
|
||||
"tone": "nostalgic and calm; curious, never hype",
|
||||
"title_rules": {
|
||||
"max_chars": 60,
|
||||
"mobile_chars": 38,
|
||||
"banned_patterns": ["in this video", "tutorial", "let's play", "how to"],
|
||||
"keyword_position": "start",
|
||||
"number_policy": "avoid",
|
||||
"required_signal": "curiosity",
|
||||
"banned_openers": ["Exploring", "Building", "Playing", "A look at"],
|
||||
},
|
||||
"hook_patterns": [
|
||||
"this shouldn't be possible in Alpha",
|
||||
"the mechanic Mojang forgot to remove",
|
||||
"you were never supposed to see this",
|
||||
"I broke the world in one block",
|
||||
],
|
||||
"hook_style": ("visual impossibility at frame 0; show the glitch before any words"),
|
||||
"description_template": "{hook}\n\nFull video: {link}\n\n#minecraft #alpha #retro",
|
||||
"links": ["https://www.youtube.com/@cseea"],
|
||||
"thumbnail": {
|
||||
"role_order": ["curiosity", "emotion", "technical"],
|
||||
"palette": ["mossy green", "cobblestone grey", "torch orange"],
|
||||
"presenter_photo": False,
|
||||
},
|
||||
"default_postiz_integration_id": None,
|
||||
"published_video_history": [],
|
||||
},
|
||||
"pedro": {
|
||||
"name": "Pedro Bento",
|
||||
"language": "en",
|
||||
"tone": "technical, direct, engineering-focused",
|
||||
"title_rules": {
|
||||
"max_chars": 70,
|
||||
"mobile_chars": 42,
|
||||
"banned_patterns": ["in this video", "for beginners", "quick tip"],
|
||||
"keyword_position": "start",
|
||||
"number_policy": "allow",
|
||||
"required_signal": "consequence",
|
||||
"banned_openers": ["Explaining", "Discussing", "Talking about"],
|
||||
},
|
||||
"hook_patterns": [
|
||||
"it crashes the moment you resize",
|
||||
"watch the benchmark number change",
|
||||
"the bug that survived three rewrites",
|
||||
"this one syscall cost 40% throughput",
|
||||
],
|
||||
"hook_style": (
|
||||
"show the working demo or the bug first, then state the stake in one line"
|
||||
),
|
||||
"description_template": "{hook}\n\nChapters and source: {link}\n\n#c #linux #systems",
|
||||
"links": ["https://github.com/pbento"],
|
||||
"thumbnail": {
|
||||
"role_order": ["technical", "curiosity", "emotion"],
|
||||
"palette": ["terminal black", "signal amber", "trace red"],
|
||||
"presenter_photo": True,
|
||||
},
|
||||
"default_postiz_integration_id": None,
|
||||
"published_video_history": [],
|
||||
},
|
||||
}
|
||||
|
|
@ -15,11 +15,16 @@ developer machine with the real deps installed are unaffected).
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
import _channel_seed
|
||||
|
||||
|
||||
class _FakeYOLO:
|
||||
def __init__(self, *args, **kwargs):
|
||||
|
|
@ -87,3 +92,26 @@ def _install_heavy_stubs() -> None:
|
|||
|
||||
|
||||
_install_heavy_stubs()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _channel_profile_db(tmp_path_factory):
|
||||
"""Point channel-profile storage at a temp SQLite DB seeded with cseea/pedro.
|
||||
|
||||
Autouse and session-scoped so every test (including ``tests/e2e/**``, which
|
||||
inherits this conftest) reads the same DB-backed profiles instead of the
|
||||
legacy ``channels/*.json`` files. The ``CLIPWRIGHT_DB`` override is removed
|
||||
on teardown so nothing leaks into a later run.
|
||||
"""
|
||||
from clipwright.pipeline import profiles
|
||||
|
||||
db_dir = tmp_path_factory.mktemp("channel-db")
|
||||
os.environ["CLIPWRIGHT_DB"] = str(db_dir / "clipwright.db")
|
||||
try:
|
||||
# First ``save_profile`` also runs the one-time file migration, but we
|
||||
# seed explicitly so the DB never depends on the checkout's files.
|
||||
for slug, data in _channel_seed.SEED.items():
|
||||
profiles.save_profile(slug, data)
|
||||
yield
|
||||
finally:
|
||||
os.environ.pop("CLIPWRIGHT_DB", None)
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
"""GET /api/channels (PLAN #1, dashboard profile selector).
|
||||
"""GET/POST/PUT/DELETE /api/channels (PLAN #1, dashboard profile selector).
|
||||
|
||||
Pins the response shape ``{"channels": [{"slug", "name"}]}``, that the seeded
|
||||
profiles show up with their display names, and that a malformed profile file is
|
||||
skipped instead of breaking the list.
|
||||
profiles show up with their display names, and the full CRUD + import/export
|
||||
surface backed by the SQLite store (``tests/conftest.py`` seeds a temp DB).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
|
@ -12,15 +13,19 @@ import pytest
|
|||
app_module = pytest.importorskip("clipwright.api.app")
|
||||
|
||||
|
||||
def _get(path):
|
||||
def _request(method, path, **kwargs):
|
||||
async def _do():
|
||||
transport = httpx.ASGITransport(app=app_module.app)
|
||||
async with httpx.AsyncClient(transport=transport,
|
||||
base_url="http://testserver") as client:
|
||||
return await client.get(path)
|
||||
return await client.request(method, path, **kwargs)
|
||||
return asyncio.run(_do())
|
||||
|
||||
|
||||
def _get(path):
|
||||
return _request("GET", path)
|
||||
|
||||
|
||||
def test_returns_seeded_profiles_with_display_names():
|
||||
resp = _get("/api/channels")
|
||||
assert resp.status_code == 200
|
||||
|
|
@ -32,10 +37,168 @@ def test_returns_seeded_profiles_with_display_names():
|
|||
assert all(set(item) == {"slug", "name"} for item in data["channels"])
|
||||
|
||||
|
||||
def test_skips_malformed_profile_files(monkeypatch, tmp_path):
|
||||
(tmp_path / "good.json").write_text('{"name": "Good"}', encoding="utf-8")
|
||||
(tmp_path / "broken.json").write_text("{ not json", encoding="utf-8")
|
||||
monkeypatch.setattr(app_module.profiles, "CHANNELS_DIR", tmp_path)
|
||||
resp = _get("/api/channels")
|
||||
def test_list_reflects_store_changes():
|
||||
created = _request(
|
||||
"POST", "/api/channels",
|
||||
json={"slug": "listed", "name": "Listed One"})
|
||||
assert created.status_code == 200, created.text
|
||||
try:
|
||||
listed = {i["slug"]: i["name"] for i in _get("/api/channels").json()["channels"]}
|
||||
assert listed["listed"] == "Listed One"
|
||||
finally:
|
||||
_request("DELETE", "/api/channels/listed")
|
||||
listed = {i["slug"] for i in _get("/api/channels").json()["channels"]}
|
||||
assert "listed" not in listed
|
||||
|
||||
|
||||
# --- read one ---------------------------------------------------------------
|
||||
|
||||
def test_get_one_profile_returns_full_payload():
|
||||
resp = _get("/api/channels/cseea")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == {"channels": [{"slug": "good", "name": "Good"}]}
|
||||
body = resp.json()
|
||||
assert body["slug"] == "cseea"
|
||||
assert body["tone"] == "nostalgic and calm; curious, never hype"
|
||||
assert body["title_rules"]["mobile_chars"] == 38
|
||||
assert body["thumbnail"]["palette"] == [
|
||||
"mossy green", "cobblestone grey", "torch orange"]
|
||||
|
||||
|
||||
def test_get_missing_profile_is_404():
|
||||
resp = _get("/api/channels/does-not-exist")
|
||||
assert resp.status_code == 404
|
||||
assert "not found" in resp.json()["detail"]
|
||||
|
||||
|
||||
# --- create -----------------------------------------------------------------
|
||||
|
||||
def test_create_profile_returns_payload():
|
||||
body = {"slug": "created", "name": "Created", "tone": "calm"}
|
||||
resp = _request("POST", "/api/channels", json=body)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["slug"] == "created"
|
||||
assert resp.json()["tone"] == "calm"
|
||||
_request("DELETE", "/api/channels/created")
|
||||
|
||||
|
||||
def test_create_duplicate_is_409():
|
||||
resp = _request("POST", "/api/channels", json={"slug": "cseea", "name": "Dup"})
|
||||
assert resp.status_code == 409
|
||||
assert "already exists" in resp.json()["detail"]
|
||||
|
||||
|
||||
def test_create_without_slug_is_400():
|
||||
resp = _request("POST", "/api/channels", json={"name": "No Slug"})
|
||||
assert resp.status_code == 400
|
||||
assert "slug is required" in resp.json()["detail"]
|
||||
|
||||
|
||||
def test_create_with_bad_slug_is_400():
|
||||
resp = _request("POST", "/api/channels", json={"slug": "../evil", "name": "Bad"})
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
# --- update -----------------------------------------------------------------
|
||||
|
||||
def test_put_updates_existing_profile():
|
||||
_request("PUT", "/api/channels/updateme", json={"name": "Before", "tone": "a"})
|
||||
try:
|
||||
resp = _request(
|
||||
"PUT", "/api/channels/updateme",
|
||||
json={"name": "After", "tone": "b"})
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["name"] == "After"
|
||||
assert _get("/api/channels/updateme").json()["tone"] == "b"
|
||||
finally:
|
||||
_request("DELETE", "/api/channels/updateme")
|
||||
|
||||
|
||||
def test_put_ignores_body_slug():
|
||||
try:
|
||||
resp = _request(
|
||||
"PUT", "/api/channels/pathed",
|
||||
json={"slug": "other", "name": "Pathed"})
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["slug"] == "pathed"
|
||||
assert _get("/api/channels/other").status_code == 404
|
||||
finally:
|
||||
_request("DELETE", "/api/channels/pathed")
|
||||
|
||||
|
||||
# --- delete -----------------------------------------------------------------
|
||||
|
||||
def test_delete_removes_profile():
|
||||
_request("POST", "/api/channels", json={"slug": "deleteme", "name": "D"})
|
||||
resp = _request("DELETE", "/api/channels/deleteme")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == {"deleted": True}
|
||||
assert _get("/api/channels/deleteme").status_code == 404
|
||||
|
||||
|
||||
def test_delete_missing_is_404():
|
||||
resp = _request("DELETE", "/api/channels/nope-nope")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
# --- export / import --------------------------------------------------------
|
||||
|
||||
def test_export_all_shape_and_headers():
|
||||
resp = _get("/api/channels/export")
|
||||
assert resp.status_code == 200
|
||||
assert resp.headers["content-disposition"] == (
|
||||
'attachment; filename="channel-profiles.json"')
|
||||
body = resp.json()
|
||||
assert body["version"] == 1
|
||||
slugs = {p["slug"] for p in body["profiles"]}
|
||||
assert {"cseea", "pedro"} <= slugs
|
||||
assert all(p["slug"] for p in body["profiles"])
|
||||
|
||||
|
||||
def test_export_single_profile_and_missing_404():
|
||||
resp = _get("/api/channels/export?slug=cseea")
|
||||
assert resp.status_code == 200
|
||||
assert resp.headers["content-disposition"] == (
|
||||
'attachment; filename="channel-profile-cseea.json"')
|
||||
body = resp.json()
|
||||
assert [p["slug"] for p in body["profiles"]] == ["cseea"]
|
||||
|
||||
missing = _get("/api/channels/export?slug=absent")
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
def test_import_valid_payload():
|
||||
payload = {"version": 1, "profiles": [
|
||||
{"slug": "imported", "name": "Imported", "tone": "fresh"},
|
||||
]}
|
||||
resp = _request("POST", "/api/channels/import", json=payload)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json() == {"imported": 1, "failed": []}
|
||||
try:
|
||||
assert _get("/api/channels/imported").json()["tone"] == "fresh"
|
||||
finally:
|
||||
_request("DELETE", "/api/channels/imported")
|
||||
|
||||
|
||||
def test_import_partial_failure_does_not_abort():
|
||||
payload = [
|
||||
{"slug": "good-import", "name": "Good"},
|
||||
{"name": "missing slug"},
|
||||
{"slug": "bad-enum", "title_rules": {"required_signal": "profit"}},
|
||||
]
|
||||
resp = _request("POST", "/api/channels/import", json=payload)
|
||||
assert resp.status_code == 200, resp.text
|
||||
result = resp.json()
|
||||
assert result["imported"] == 1
|
||||
assert [f["slug"] for f in result["failed"]] == ["", "bad-enum"]
|
||||
try:
|
||||
assert _get("/api/channels/good-import").status_code == 200
|
||||
finally:
|
||||
_request("DELETE", "/api/channels/good-import")
|
||||
|
||||
|
||||
def test_import_non_object_payload_is_400():
|
||||
resp = _request(
|
||||
"POST", "/api/channels/import",
|
||||
content=json.dumps("not-a-profile"),
|
||||
headers={"content-type": "application/json"})
|
||||
assert resp.status_code == 400
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@
|
|||
|
||||
Covers the happy path, the defaults for a minimal file, the failure modes a
|
||||
bad ``channels/<slug>.json`` produces, slug hardening, and the
|
||||
``CHANNEL_PROFILE`` env fallback. Also asserts the two seeded profiles load.
|
||||
``CHANNEL_PROFILE`` env fallback. Also asserts the two seeded profiles load
|
||||
from the SQLite store, plus the store's save/load/delete and export/import
|
||||
round-trips.
|
||||
"""
|
||||
import json
|
||||
|
||||
|
|
@ -212,3 +214,49 @@ def test_list_profiles_skips_malformed_files(tmp_path):
|
|||
|
||||
def test_list_profiles_missing_dir_is_empty(tmp_path):
|
||||
assert profiles.list_profiles(channels_dir=tmp_path / "absent") == []
|
||||
|
||||
|
||||
# --- to_dict / from_dict round-trip ----------------------------------------
|
||||
|
||||
def test_full_profile_to_dict_round_trips():
|
||||
profile = profiles.Profile.from_dict(FULL, "full")
|
||||
serialised = profile.to_dict()
|
||||
assert "slug" not in serialised
|
||||
assert profiles.Profile.from_dict(serialised, "full") == profile
|
||||
|
||||
|
||||
def test_minimal_profile_to_dict_round_trips():
|
||||
profile = profiles.Profile.from_dict({}, "bare")
|
||||
assert profiles.Profile.from_dict(profile.to_dict(), "bare") == profile
|
||||
|
||||
|
||||
# --- the SQLite store (runtime source of truth) ----------------------------
|
||||
|
||||
def test_db_save_load_delete_round_trip():
|
||||
profiles.save_profile("dbtmp", FULL)
|
||||
try:
|
||||
loaded = profiles.load_profile("dbtmp")
|
||||
assert loaded.slug == "dbtmp"
|
||||
assert loaded.name == "Full Channel"
|
||||
assert loaded.title_rules.max_chars == 55
|
||||
assert {"slug": "dbtmp", "name": "Full Channel"} in profiles.list_profiles()
|
||||
assert profiles.profile_payload("dbtmp")["name"] == "Full Channel"
|
||||
finally:
|
||||
assert profiles.delete_profile("dbtmp") is True
|
||||
with pytest.raises(profiles.ProfileError):
|
||||
profiles.load_profile("dbtmp")
|
||||
assert profiles.delete_profile("dbtmp") is False
|
||||
|
||||
|
||||
def test_missing_db_profile_raises_clear_error():
|
||||
with pytest.raises(profiles.ProfileError) as exc:
|
||||
profiles.load_profile("no-such-profile")
|
||||
assert "not found" in str(exc.value)
|
||||
assert "no-such-profile" in str(exc.value)
|
||||
|
||||
|
||||
def test_save_profile_rejects_bad_slug():
|
||||
with pytest.raises(profiles.ProfileError) as exc:
|
||||
profiles.save_profile("../../etc/passwd", {})
|
||||
assert "invalid channel slug" in str(exc.value)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue