Aashish-po/clip-grid
حول
Local-first AI clip generator that turns long videos and live streams into captioned 9:16 shorts with automated, policy-controlled publishing.
التصميم والوسائطالنمو المقاس للنجوم
- خلال 24 ساعة
- +٦
- خلال 7 أيام
- جارٍ جمع السجل
- خلال 15 يومًا
- جارٍ جمع السجل
- خلال شهر
- جارٍ جمع السجل
تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.
README.md
الأصلClipGrid

ClipGrid turns long-form videos and live streams into 1080 × 1920 (9:16) vertical clips with word-timed captions, hooks, titles, and policy-controlled publishing for YouTube Shorts, Instagram Reels, TikTok, and other short-form platforms.
Local-first, private, and fork-and-run: Your media, transcripts, signal tracks, database, and credentials stay on your own machine—no cloud relay or AI markup fees.
- Ingest: Paste a YouTube, Twitch, or Kick URL, upload a local recording, or monitor a creator channel live.
- Score & Rank: Combines speech transcription, audio intensity, unique-chatter velocity, and optional AI reranking to surface self-contained highlights.
- Render 9:16: Produces
1080 × 1920vertical videos with word-timed captions, gameplay/facecam layouts, hooks, and titles. - Review & Publish: Refine trims and captions in the Clip Inbox, or automate posting with built-in autonomy levels, source rights enforcement, and daily caps.
Why ClipGrid?
Most creators produce hours of content but only publish a handful of shareable moments. ClipGrid automates the entire repurposing workflow locally:
- Highlight Detection: Fuses audio spikes, laughter, unique-chatter velocity, and transcript scoring—with optional LLM reranking.
- Live Stream Governor: Monitors streams with a disk-backed ring buffer and automatically defers heavy renders while you are gaming so FPS stays untouched.
- Safe Automation & Rights Policy: Enforces source permissions (
owned,authorized,unverified), daily posting caps, minimum spacing, quiet hours, veto windows, and a global kill switch. - Bring Your Own AI & Credentials: Connect your own AI keys and platform developer credentials with zero usage markups.
- Crash-Safe Resume: Stage-level content-addressed caching and an idempotent posting outbox ensure crashes never duplicate posts or repeat paid AI/ASR work.
Features
Process Live or Recorded Content
- Supported Sources: YouTube videos and live streams, Twitch streams (EventSub WebSocket + IRC), Kick streams, uploaded recordings, and monitored creator channels.
- Live Ring Buffer: Captures live streams into rolling 4-second
.tssegments capped by both disk size and duration (with a free-disk safety margin), flagging any network gaps rather than silently stitching broken footage. - Smart Live Triggers: Detects chat-velocity z-scores (counted by unique chatters to ignore bot spam), audio spikes, laughter,
!clipcommands (broadcaster/mod-restricted), and hotkeys with a 30-second deduplication cooldown.
Discover the Best Moments
- Multi-Signal Scoring Core: Runs fast numeric extractors across the full video, snaps boundaries to sentence edges and silence gaps, and verifies that clips are self-contained without needing prior context.
- Optional LLM Reranking: Only candidate windows are sent to your chosen LLM for hook generation, title writing, and final ranking—keeping token costs low. Works completely offline without an AI key using transcript and loudness scoring.
- Quality Gate: Evaluated against a labeled golden set (precision@k, recall, mid-sentence boundary rate, cost, and latency per video-hour).
Gaming Mode & Resource Governor
- Game-Aware Shorts: Automatic game detection, game-specific titles and hashtags, chat-participant analysis, and webcam/gameplay split layouts (supporting GTA V/VI, Fortnite, Minecraft, Valorant, League of Legends, Counter-Strike, Rocket League, Apex Legends, Elden Ring, Call of Duty, and more).
- Zero-Impact Live Governor: Continuously samples CPU, GPU (NVML), and fullscreen game state with 30-second hysteresis:
IDLE/STREAM_LIGHT: Runs signals, live ASR, and low-priority rendering.STREAM_HEAVY: Collects lightweight audio/chat triggers only and automatically defers heavy ASR/rendering untilPOST_STREAM.
Learn more in GAMING.md.
Create & Refine Platform-Ready Vertical Clips
- Generates
1080 × 1920(9:16) vertical videos with word-timed captions, multiple caption styles, facecam/gameplay layouts, and editable trims, hooks, and titles in the Clip Inbox.
Policy-Controlled Publishing
- Autonomy Levels (
L0–L3): Choose between manual library-only (L0), inbox review (L1), auto-post with a timed veto window (L2), or full autopilot (L3). - Hard Rights Ceilings: Maximum allowed autonomy is enforced in pure code by
(source_rights, platform)pairs—unverifiedsources are restricted toL0,authorizedsources cap atL1(orL0on TikTok), andownedsources unlock up toL3where permitted. - Platform Support: Direct resumable uploads to YouTube Shorts and Instagram Reels, with TikTok and Facebook Reels supported through ClipGrid's extensible platform adapter layer.
- Exactly-Once Outbox: Tracks
idempotency_keyand persistsremote_handlebefore final commit so retries or crashes reconcile cleanly and never double-post.
Bring Your Own AI & Credentials
- AI Providers: Google Gemini, OpenAI, Anthropic Claude, xAI Grok, Groq, OpenRouter, local Ollama (100% on-device), or any OpenAI-compatible endpoint.
- No Hosted Relay: You create your own developer/OAuth apps once (YouTube Data API v3, Twitch, Meta, TikTok). Tokens are stored locally in your OS Keychain (
keyring)—never in plaintext config files.
How It Works
flowchart TD
subgraph Start ["1. Source"]
A[URL / Upload / Live Stream]
end
subgraph Ingest ["2. Ingest & Ring Buffer"]
B[Ingest & Ring Buffer]
end
subgraph Signals ["3. Signals & ASR"]
C[Signals & ASR<br/>Whisper / Local / Remote GPU]
end
subgraph Scoring ["4. Pure Scoring Core + LLM Rerank"]
D[Pure Scoring Core<br/>+ Optional LLM Rerank]
end
subgraph Render ["5. Render 9:16 + Captions"]
E[Render 9:16 + Captions]
end
subgraph Policy ["6. Policy Engine<br/>Rights × Autonomy × Caps × Kill Switch"]
F[Policy Engine]
end
subgraph Inbox ["Clip Inbox"]
G[Manual Review / Trim / Edit]
end
subgraph Outbox ["Publishing Outbox"]
H[Scheduled / Veto Window / Auto-Post]
end
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
F --> H
style A fill:#0B100E,stroke:#17C37B,color:#EAF0ED
style B fill:#0B100E,stroke:#17C37B,color:#EAF0ED
style C fill:#0B100E,stroke:#17C37B,color:#EAF0ED
style D fill:#0B100E,stroke:#17C37B,color:#EAF0ED
style E fill:#0B100E,stroke:#17C37B,color:#EAF0ED
style F fill:#0B100E,stroke:#F0A93B,color:#EAF0ED
style G fill:#0B100E,stroke:#17C37B,color:#EAF0ED
style H fill:#0B100E,stroke:#17C37B,color:#EAF0ED
Quick Start (Local Setup)
Requirements
- Python 3.10+ (Python 3.11 recommended)
- FFmpeg (with NVENC support optional for hardware-accelerated rendering)
- Git
Windows Tip: Install into a short path such as
C:\clipgridto avoid Windows 260-character path limits during media processing.
1. Clone & Run Setup
# Windows (Git Bash) — install prerequisites if needed:
# winget install Gyan.FFmpeg Python.Python.3.11 Git.Git
git clone <your-fork-url> C:/clipgrid
cd C:/clipgrid
bash scripts/setup.sh
The setup script creates .venv, installs pinned dependencies, downloads the English speech model (~480 MB, one-time download with SHA-256 verification), and runs environment self-checks (Python version, FFmpeg/NVENC availability, free disk space, path length, and writable data directory).
(Manual setup alternative: python -m venv .venv && pip install -r requirements.txt)
2. Launch ClipGrid
python -m app.server
Open http://127.0.0.1:8090 in your browser and follow the setup wizard to:
- Add an AI provider in Settings -> AI (optional—ClipGrid runs without AI using numeric signal scoring).
- Connect your platform credentials using Bring-Your-Own developer apps (e.g., Google Cloud desktop OAuth
client_secret.jsonfor YouTube Data API v3, Twitch client ID/secret for live streams). - Configure source rights (
owned/authorized/unverified) and posting autonomy levels.
Deployment Modes
ClipGrid runs the exact same pipeline across three deployment configurations:
| Mode | Database | Auth & Network | Best For |
|---|---|---|---|
| Local (Default) | SQLite (WAL mode) | Bound to 127.0.0.1, OS Keychain |
Single streamer running on one PC |
| Local + GPU Worker | SQLite (WAL mode) | Token-authenticated remote asr_worker |
Gaming PC + secondary machine for ASR |
| Server / Production | PostgreSQL | User accounts enabled (CLIPGRID_ACCOUNTS=1) + Caddy HTTPS |
Multi-user or dedicated Linux host (docker compose) |
For full Linux server and Docker Compose deployment instructions, see DEPLOY.md.
Privacy & Security
- Local by Default: Raw video, audio, transcripts, signal tracks, and SQLite databases never leave your machine.
- Minimal Egress: Only short candidate transcript excerpts are sent to your configured LLM provider (or stay 100% on-device if using Ollama).
- Privacy Ledger: Every outbound network request (provider, purpose, byte count) is recorded locally in
egress_logand visible in Settings. Zero telemetry is collected by default. - OS Keychain Storage: OAuth refresh tokens and API keys are stored via the system credential manager (
keyring), never committed to git or stored in plaintext JSON. - Prompt & Network Hardening: Untrusted video/chat text is sanitized before/after LLM prompts (
_safe/_text), URL ingestion is restricted to allowlisted domains with private IP ranges blocked, and mutating requests enforceHost/Originchecks on127.0.0.1.
Architecture & Project Layout
clipgrid/
├─ app/ # Active backend runtime (server, ingest, ASR, live, scoring, rendering, publishing)
├─ ui/ # Frontend UI (Clip Inbox, Live Console, Settings, Autopilot views)
├─ infra/ # Reverse proxy configs (Nginx, Traefik) and GPU ASR worker Docker setup
├─ tools/ # Maintenance, evaluation, and developer utility scripts
├─ tests/ # End-to-end, unit, golden-set, and regression test suites
├─ Dockerfile # Application container build definition
├─ docker-compose.yml # Production multi-service stack (app, PostgreSQL, Caddy)
├─ pyproject.toml # Project metadata, linter, and import-linter layer rules
├─ requirements.txt # Pinned Python dependencies
├─ .env.example # Environment variable template
├─ AGENTS.md # Contributor and AI assistant coding conventions
├─ DEPLOY.md # Linux server Docker Compose deployment guide
├─ GAMING.md # Gaming Mode detection, layouts, and stream behavior
└─ README.md # Project overview and quick-start guide
Architecture Diagrams
System Context
flowchart LR
subgraph Sources
TW[Twitch]:::ext
KI[Kick]:::ext
YL[YouTube Live / VOD]:::ext
UP[Uploaded File]:::ext
end
subgraph Local["User Machine (ClipGrid)"]
ING[Ingest + Ring Buffer]
SIG[Signal Extractors]
SCO[Scoring Core - Pure]
PIPE[Pipeline Stages]
POL[Policy Engine - Pure]
PUB[Publisher + Outbox]
DB[(SQLite / PostgreSQL + Media)]
UI[Web UI: Inbox, Live Console, Editor]
GOV[Resource Governor]
end
subgraph External["User-Configured Services"]
LLM[LLM Provider]:::ext
YT[YouTube]:::ext
IG[Instagram]:::ext
TT[TikTok]:::ext
end
TW & KI & YL & UP --> ING --> SIG --> SCO --> PIPE
PIPE <--> DB
PIPE -- Candidate transcript excerpts only --> LLM
PIPE --> POL --> PUB
PUB --> YT & IG & TT
UI <--> DB
GOV -. Throttles .-> ING & PIPE
classDef ext fill:#1A2320,stroke:#657770,color:#EAF0ED;
Trust Boundary: Source media, transcripts, signal tracks, databases, and credentials remain inside the local boundary. Outbound network calls only cross when explicitly triggered (LLM reranking, platform uploads, OAuth refreshes, optional update checks) and are recorded in the privacy ledger.
Post Lifecycle State Machine
stateDiagram-v2
[*] --> pending_review
pending_review --> scheduled: Approved or auto-scheduled
pending_review --> cancelled: Rejected
scheduled --> cancelled: Vetoed or kill switch
scheduled --> uploading: Due time reached
uploading --> processing: Upload accepted
uploading --> retry_wait: Transient or rate-limit error
uploading --> needs_reauth: Auth error
uploading --> failed: Permanent error
processing --> published: Platform confirms
processing --> failed: Platform rejects
retry_wait --> uploading: Backoff elapsed
needs_reauth --> scheduled: User reconnects account
published --> [*]
failed --> [*]
cancelled --> [*]
VOD Detection Pipeline
flowchart LR
A[URL / Upload] --> B[Ingest: MP4 + 16 kHz WAV]
B --> C[Transcribe]
B --> D[Signals: Audio, Laughter, Visual, Facecam, Quality]
E[Chat Log / Replay] --> D
C --> D
D --> F[Scoring: Normalize + Fuse]
F --> G[Top Candidates ~30/hr]
G --> H[Snap to Sentence & Silence]
H --> I[Self-Contained Context Check]
I --> J[LLM Rerank: Hook, Title, Reason]
J --> K[Blend Fused + LLM Score]
K --> L[Render 9:16 + Captions]
L --> M[Policy Engine -> Inbox / Schedule]
- Cost & Context Efficiency: Cheap numeric extractors scan the full video; the LLM evaluates only candidate windows (~30/hour) with signal attributions.
- Boundary & Context Quality: Cuts snap to sentence edges and silence gaps, then pass a self-contained check (extending or dropping clips that depend on missing context).
- Graceful Degradation: LLM timeouts or invalid JSON retry twice before falling back to the numeric fused score (
scored without AI). Individual signal extractor failures renormalize remaining weights; only zero active tracks fails the job. - Evaluation Gate:
scoring/evaluation.pyruns against a labeled golden set (20–30 videos across podcasts, gaming, interviews, and streams), trackingprecision@k, recall, mid-sentence cut rate, token cost, and latency per video-hour.
Live Stream Path
sequenceDiagram
participant S as Stream (Twitch/YT/Kick)
participant I as Ingest (Streamlink/yt-dlp + FFmpeg)
participant R as Disk Ring Buffer
participant G as Resource Governor
participant T as Trigger Detector
participant P as Pipeline
participant O as Policy + Publisher
S->>I: Live video stream
I->>R: 4s .ts segments (sequence-numbered)
S->>T: Chat / events (EventSub WS, IRC, Chat API)
R->>T: Per-segment audio levels
T->>T: Unique-chatter z-score, !clip, hotkey, laughter
T->>P: Trigger (strength, timestamp t)
P->>R: Wait for post-roll, extract [t-45s, t+15s]
P->>G: Request render permission
alt Governor allows
G-->>P: Approved (NVENC, low priority)
P->>O: Rendered clip -> Inbox / Schedule
else Heavy game load
G-->>P: Defer to post-stream queue
P->>O: Metadata placeholder ("rendering after stream")
end
- Ring Buffer & Gap Safety: At ~6 Mbps (
0.75 MB/s), a 30-minute ring buffer uses~1.35 GB(~45 MB/min). The buffer is bounded by both byte size and duration, enforces a free-disk safety floor (default10 GB), evicts oldest segments first, and trackslast_segment_seqso clips spanning dropped segments are explicitly flagged rather than silently stitched. - Latency & Backpressure: Minimum cut latency is governed by post-roll (
15 s) plus segment close (up to 4 s), totaling~19 sbefore render. When the bounded render queue saturates, lowest-strengthtriggers are shed (decision='shed') so live ingest is never blocked. - Trigger Deduplication: Combines unique-chatter velocity z-scores (resistant to single-user bot floods), audio peaks, laughter, mod/broadcaster
!clipcommands, hotkeys, and optional Twitch clip cross-checks within a 30-second per-session cooldown.
Job Engine & Stage Idempotency
Scope Note: Stage idempotency and resume is implemented on top of the existing in-process queue. The database-backed
jobstable, lease heartbeats, and reaper ship after day 30.
Atomic Job Claiming
SQLite enforces single-writer semantics; workers claim tasks atomically via UPDATE ... RETURNING (requires SQLite 3.35+ with PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA synchronous=NORMAL;):
UPDATE jobs
SET state = 'running',
worker = :worker,
lease_until = :now + :lease_s,
attempts = attempts + 1
WHERE id = (
SELECT id FROM jobs
WHERE pool = :pool AND state = 'queued' AND run_after <= :now
ORDER BY priority DESC, run_after, id
LIMIT 1
)
RETURNING *;
Leases, Heartbeats & Reaper
Active workers extend lease_until every 10 seconds. A background reaper scans every 30 seconds to requeue expired leases and transition rows exceeding max_attempts to failed.
Stage Cache Keys
Each pipeline stage writes artifacts to content-addressed storage keyed by deterministic inputs. Re-executing a stage with an identical key returns the cached output immediately:
| Stage | Cache Key |
|---|---|
ingest |
source_sha256 |
transcribe |
(source_sha256, asr_engine, model) |
signals |
(source_sha256, signal_name, extractor_version) |
candidates |
run_config_hash (weights, thresholds) |
rerank |
(candidate_id, prompt_version, model) |
render |
(clip_id, clip_version, render_preset) |
publish |
posts.idempotency_key |
Fairness, Pools & UI Sync
- Pools:
asr,render,io, andlive. Thelivepool maintains reserved capacity so VOD jobs never starve live stream capture. - Fairness: Within equal priority levels, jobs schedule round-robin across users by least-recently-served timestamp.
- UI Sync: State mutations increment
ctx.bump(), which clients poll via/api/sync. Post-day-30,api/events.pyadds Server-Sent Events (SSE) for sub-second Live Console updates.
Privacy & Security Controls
Data Egress Inventory
| Data Category | Local Only | Outbound Conditions |
|---|---|---|
| Source video/audio, full transcripts, signal tracks, DB | Yes | Never leaves machine |
| Candidate transcript windows | Optional | Sent only to user-configured LLM provider (stays local when using Ollama) |
| Rendered vertical clips | Until published | Uploaded only to user-authorized target platforms |
| OAuth & API credentials | Yes (OS keychain) | Sent only to the issuing platform/provider |
| Update check | Opt-out | Sends commit hashes to GitHub unless CLIPGRID_UPDATE_CHECK=0 |
| Telemetry | Yes | None collected by default |
All outbound HTTP traffic logs (ts, provider, purpose, bytes) to egress_log (surfaced in Settings) and supports optional host allowlisting.
Threat Mitigations
- Local API CSRF / Cross-Origin Access: Binds to
127.0.0.1, validatesHostandOriginheaders on mutating endpoints, and uses per-install API tokens. - Prompt Injection: All transcript and chat text passes through
_safebefore prompt insertion and_texton output; LLM responses are schema-validated and never executed. - SSRF: URL ingestion enforces
CLIPGRID_ALLOWED_SITESand blocks private/loopback IP ranges post-DNS resolution. - Media Processing Safety: FFmpeg runs as a bounded subprocess with timeouts after input probe validation.
- Supply Chain: Dependencies are pinned;
yt-dlpupdates pass a canary test suite before adoption.
Reliability, Observability & Scalability
Failure Mitigation Matrix
| Failure Mode | Mitigation Strategy |
|---|---|
yt-dlp extractor breakage |
Pinned versions, canary-tested updates, typed errors; manual file uploads remain unaffected. |
| ASR / GPU OOM on long media | Chunk audio into 10-minute overlapping windows, stitch word timestamps, retry with smaller batch size. |
| LLM timeout or invalid JSON | Schema validation + 2 retries, then fallback to numeric fused score. |
| Signal extractor failure | Drop failed track and renormalize remaining weights; fail only if zero tracks succeed. |
| Disk exhaustion | Byte/duration caps on ring buffer, render TTL (default 14 days), reject new jobs above 90% disk usage. |
| Retry double-posting | Unique idempotency_key + remote_handle status reconciliation. |
| Token expiration / revocation | Transition account to needs_reauth, surface reconnect banner, isolate other accounts. |
| Process crash / power loss | Stage cache keys resume at failed stage; outbox reconciler heals in-flight uploads. |
| System clock drift | Use monotonic clocks for leases and cooldowns; wall clocks only for scheduled publish times. |
Observability & Service Targets
- Local Diagnostics: Structured JSON rotating logs, per-stage
stage_runs.metrics(wall time, GPU seconds, tokens, cost), a Diagnostics UI page (queue depths, governor state, account health, FFmpeg/yt-dlpversions), and a secret-redacted support bundle export. - Targets:
100%exactly-once post delivery (0 duplicates/losses in soak tests),100%explicit gap flagging on live stream reconnects (0 silent stitches), and crash recovery without re-running completed paid stages.
Capacity & Scaling Order
- Resource Estimates: Scoring runs in $O(T \cdot n)$ (~20 ms for a 10-hour video). A 30-minute 6 Mbps live buffer requires
~1.35 GB. A 60-second1080 × 1920clip at 8 Mbps is~60 MB(~1.4 GB/dayat 4 clips/hr over 6 hours). - Bottleneck Progression: Scale only when metrics identify saturation: (1) single local machine -> (2) offload ASR to remote GPU
asr_worker-> (3) PostgreSQL + dedicated render worker in server mode -> (4) split worker pools across hosts.
Configuration
Copy .env.example to .env to customize runtime behavior:
cp .env.example .env
Key configuration categories include:
- Database & Storage: SQLite path or PostgreSQL connection, render retention TTL (default 14 days), ring buffer byte/duration caps
- Live & Resource Governor: CPU/GPU throttling thresholds, remote
CLIPGRID_ASR_URLandCLIPGRID_ASR_TOKENworker settings - Security & Networking: Allowed source domains (
CLIPGRID_ALLOWED_SITES), multi-user account mode (CLIPGRID_ACCOUNTS), update check toggle (CLIPGRID_UPDATE_CHECK), andsecrets/directory for local credentials - Publishing Limits: Default daily posting caps, minimum spacing, quiet hours, and rate-limit controls
Documentation
| Document | Description |
|---|---|
| AGENTS.md | Contributor guidelines, coding standards, and AI assistant conventions |
| DEPLOY.md | Production Linux Docker Compose deployment guide (App + PostgreSQL + Caddy) |
| GAMING.md | Gaming Mode detection, layouts, and stream behavior |
| LICENSE | MIT License |
Contributing
Contributions are welcome. Before opening a pull request, ensure all checks pass:
# Run end-to-end test suite
python tests/run.py
# Run pure scoring & policy unit and property tests
pytest tests/unit
# Verify architectural layer boundaries
lint-imports
# Run frontend checks (if modifying ui/)
cd ui && npm run lint && npm run build
See AGENTS.md for architecture rules, golden-set evaluation gates, and project conventions.
Development Principles
ClipGrid prioritizes:
- Reliability
- User data safety
- Predictable behavior
- Maintainability
- Performance
- Feature growth
Every contribution should preserve existing user workflows and avoid introducing unnecessary complexity.
License & Responsible Use
ClipGrid is open-source software released under the MIT License. You are free to use, modify, distribute, self-host, and commercially use the software under its terms.
Only clip, repurpose, or publish content that you own or have explicit authorization to use. Always comply with platform Terms of Service, copyright laws, and creator permissions—responsibility for published content remains with the user.
Built for creators who would rather create than spend hours searching for clips
استكشف مشاريع مشابهة ومرتبطة
جارٍ التحميل…