Metadata-Version: 2.4
Name: ttclips
Version: 1.1.0
Summary: Fully local clip reposter: YouTube highlight clips + generated shorts, auto-posted to TikTok and YouTube Shorts.
License-Expression: MIT
Keywords: tiktok,youtube,shorts,clips,automation,yt-dlp,whisper,ffmpeg
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: End Users/Desktop
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Multimedia :: Video
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: yt-dlp>=2024.1.1
Requires-Dist: faster-whisper>=1.0.0
Requires-Dist: google-genai>=1.0.0
Requires-Dist: edge-tts>=7.3.1
Requires-Dist: tiktok-uploader>=1.2.0
Requires-Dist: playwright>=1.58.0
Requires-Dist: httpx>=0.27
Requires-Dist: prompt_toolkit>=3.0.36
Requires-Dist: opencv-python-headless>=4.8
Requires-Dist: numpy>=1.24
Provides-Extra: api
Requires-Dist: google-api-python-client>=2.100; extra == "api"
Requires-Dist: google-auth-oauthlib>=1.2; extra == "api"
Requires-Dist: google-auth-httplib2>=0.2; extra == "api"
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Dynamic: license-file

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/kamzysert3/ttclips/main/assets/logo-dark.svg">
    <img src="https://raw.githubusercontent.com/kamzysert3/ttclips/main/assets/logo.svg" alt="ttclips" width="440">
  </picture>
</p>

# ttclips

[![PyPI - Version](https://img.shields.io/pypi/v/ttclips.svg?logo=pypi&logoColor=white)](https://pypi.org/project/ttclips/)
[![PyPI - Python Versions](https://img.shields.io/pypi/pyversions/ttclips.svg?logo=python&logoColor=white)](https://pypi.org/project/ttclips/)
[![CI](https://img.shields.io/github/actions/workflow/status/kamzysert3/ttclips/ci.yml.svg?branch=main&logo=github)](https://github.com/kamzysert3/ttclips/actions?query=workflow%3ACI)
[![License](https://img.shields.io/github/license/kamzysert3/ttclips.svg)](https://github.com/kamzysert3/ttclips/blob/main/LICENSE)
[![Sponsor](https://img.shields.io/badge/Sponsor-%E2%9D%A4-F0643F.svg?logo=github)](https://github.com/sponsors/kamzysert3)

Turn **your own YouTube channel** into TikTok content automatically. ttclips
monitors your channel(s), detects the highlight moments, cuts them into vertical
9:16 clips with face-aware framing and punchy word-synced captions, and posts them to
TikTok **and/or YouTube Shorts** on a schedule — no TikTok API approval, no
Google Cloud project, no manual editing, fully local.

Point it at channels you own or have rights to: this is a repurposing tool for
creators, not a content scraper (see
[Legal & operational notes](#legal--operational-notes)).

- **Fully local and free** — no clip-hosting service, no paid APIs required.
- **AI-ranked highlights** — whisper transcription + Gemini highlight ranking.
- **Smart framing** — follows the speaker's face, or stacks facecam over
  gameplay, instead of a blind centre crop.
- **Short-form captions** — bold 2–3 word phrases in the platform-safe zone;
  the spoken word pops in colour, plus a hook card on the opening seconds.
- **Cookie-based auth** — no TikTok developer approval / API key needed.
- **Official APIs when you want them** — optional TikTok Content Posting API
  and YouTube Data API v3 backends: no cookies, no brittle UI automation.
- **Two independent targets** — TikTok and YouTube Shorts, each with its own
  schedule tracking and dedup state; post to one, the other, or both.
- **Self-healing** — model fallback chains, cached downloads, graceful b-roll fallback.

---

## Table of contents

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quickstart](#quickstart)
- [How it works](#how-it-works)
- [Command-line reference](#command-line-reference)
- [Configuration](#configuration)
  - [Target channels (`config/channels.json`)](#target-channels)
  - [Posting window (`config/posting_window.json`)](#posting-window)
  - [Platforms (`config/platforms.json`)](#platforms)
  - [TikTok upload settings (`config/tiktok.json`)](#tiktok-upload-settings)
  - [YouTube Shorts settings (`config/youtube.json`)](#youtube-upload-settings)
  - [Stream topics (`config/streams.json`)](#stream-topics)
  - [Environment variables (`.env`)](#environment-variables)
- [State and data](#state-and-data)
- [Automation (Windows Task Scheduler)](#automation)
- [Frequently asked questions](#faq)
- [Development](#development)
- [Releasing](#releasing)
- [Legal & operational notes](#legal--operational-notes)
- [Support the project](#support-the-project)
- [License](#license)

---

## Features

- **YouTube monitoring** — polls channel RSS feeds and queues new videos that
  match your keyword filters.
- **Highlight detection** — `faster-whisper` transcribes the audio; Gemini
  ranks the strongest 20–70 second moments with hooks, captions and hashtags.
- **Vertical clip production** — each clip is reframed to 1080×1920 (9:16)
  with face-aware framing, captioned, loudness-normalised and trimmed onto
  word boundaries. See [Clip look](#clip-look).
- **Original content mode** — Gemini writes a script, `edge-tts` narrates it,
  stock b-roll (Pexels) or an animated gradient backs the clip.
- **Scheduled posting** — up to 8 posts/day at configurable times, with
  catch-up for missed slots.
- **Resilient uploads** — Playwright-driven TikTok *and* YouTube Studio uploads
  with human-like delays, exponential backoff retries, and an isolated
  subprocess so a crashed upload can never take the scheduler down.
- **Reusable state** — never re-downloads a video or reposts the same moment.

## Requirements

- **Python 3.10+**
- **ffmpeg + ffprobe** (required to merge streams and render clips):
  - Windows: `winget install Gyan.FFmpeg`
  - macOS: `brew install ffmpeg`
  - Debian/Ubuntu: `sudo apt install ffmpeg`
  - Alternative: set ``FFMPEG_BIN`` / ``FFPROBE_BIN`` in `.env` to point at
    your own binaries.
- **Playwright Chromium** — installed once, see [Installation](#installation).
- **A Gemini API key** — free at <https://aistudio.google.com/apikey>.
- **TikTok cookies** (only needed for the TikTok upload step) — see
  [Quickstart](#quickstart).
- **Google cookies** (only needed for the YouTube Shorts upload step) — see
  [Quickstart](#quickstart).

## Installation

```bash
pip install ttclips
```

Then install the Playwright browser (one-time):

```bash
playwright install chromium
```

> On Windows, `pip install` puts the `ttclips` command in
> `%LOCALAPPDATA%\Programs\Python\Python312\Scripts` (add it to `PATH` if the
> command isn't found).

### Where config and data live

`ttclips` resolves its working directory as follows:

1. `$TTCLIPS_HOME` if set, otherwise
2. the current working directory.

All `config/`, `data/` and `.env` paths are relative to that directory, so the
same installation can run multiple independent projects.

## Quickstart

### 1. Initialise a project folder

```bash
mkdir my-clips && cd my-clips
ttclips --init --yes
```

This creates `config/` (default channels, posting window, TikTok + YouTube
settings, platform defaults) and `.env.example`. The `--yes` flag acknowledges
that you own (or have rights to) the channels you will repost — see
[`docs/LEGAL.md`](https://github.com/kamzysert3/ttclips/blob/main/docs/LEGAL.md).

### 2. Configure secrets

```bash
cp .env.example .env    # Windows: copy .env.example .env
```

Edit `.env` and set at minimum:

```ini
GEMINI_API_KEY=your_gemini_api_key_here
```

Optionally set `PEXELS_API_KEY` (free at <https://www.pexels.com/api/>) to
power stock-video backgrounds for generated clips. Without it, generated clips
use an animated gradient background.

### 3. Provide TikTok cookies (for posting)

TikTok uploads use browser session cookies instead of an API key:

1. Log in to tiktok.com in Chrome.
2. Export cookies in Netscape format (e.g. the *"Get cookies.txt LOCALLY"*
   browser extension).
3. Save as `data/cookies.txt` in the project folder.

Re-export roughly monthly, as sessions drift.

### 4. Provide Google cookies (only for YouTube Shorts)

YouTube Shorts are posted through **YouTube Studio** with the same
cookie-auth approach:

1. Log in to <https://studio.youtube.com> in Chrome.
2. Export cookies in Netscape format (the *"Get cookies.txt LOCALLY"* extension
   works for Google as well).
3. Save as `data/youtube_cookies.txt` in the project folder.

No Google Cloud project, no OAuth app and no API audit are needed — Studio
uploads are ordinary uploads. See
[Why not the YouTube Data API?](#why-not-the-youtube-data-api).

### 5. Verify and run

```bash
ttclips --validate-session        # TikTok cookies OK?
ttclips --validate-youtube        # YouTube cookies OK?
ttclips --monitor                 # build the watch queue from YouTube feeds
ttclips --once --dry-run          # full pipeline, no upload
ttclips --once --slot 12:00       # post one slot now
ttclips --once --slot 12:00 --no-upload    # render only, don't post
ttclips --once --target youtube   # post the slot to YouTube Shorts instead
```

Pick the default target in `config/platforms.json` (`tiktok`, `youtube` or
`both`) or override it per run with `--target`.

## How it works

```
YouTube RSS feeds ─────────────────▶ monitor (queue of new videos)
                                     │
                          yt-dlp + ffmpeg (download, merge, cache)
                                     ▼
                          faster-whisper (transcription + word timestamps)
                                     ▼
                          Gemini (probe → fallback chain) highlight ranking
                                     ▼
                          face-aware 9:16 framing + animated captions (FFmpeg)
                                     ▼
   two pipelines:    repost clips            OR        generated original clips
              Gemini highlights        Gemini script → edge-tts narration →
              cut_and_crop_clip        stock b-roll + captions
                                        (gradient fallback)
                                     ▼
                          one clip, fanned out to the target platforms
                                     ▼
            Playwright → TikTok upload        Playwright → YouTube Studio upload
              (data/cookies.txt)                 (data/youtube_cookies.txt)
```

Default posting schedule (`config/posting_window.json`):

| Time  | Type      |
|-------|-----------|
| 08:00 | repost    |
| 10:00 | repost    |
| 12:00 | generated |
| 14:00 | repost    |
| 16:00 | generated |
| 18:00 | repost    |
| 20:00 | generated |
| 22:00 | repost    |

## Command-line reference

| Command | Description |
|---------|-------------|
| `ttclips` | Post the current/upcoming slot (if not already posted today) |
| `ttclips --init --yes` | Scaffold `config/` + `.env.example` into the project folder; `--yes` acknowledges you own the content you will repost |
| `ttclips --monitor` | Refresh the YouTube watch queue only |
| `ttclips --validate-session` | Check whether the TikTok cookie session is alive |
| `ttclips --validate-youtube` | Check whether the YouTube (Studio) cookie session is alive |
| `ttclips --once` | Post the current/upcoming slot, then exit |
| `ttclips --once --slot 12:00` | Post a specific slot |
| `ttclips --once --type generated` | Force a content type (`repost`/`generated`) |
| `ttclips --once --target youtube` | Post to YouTube Shorts (`tiktok`, `youtube` or `both`) |
| `ttclips --target both --catchup` | Fill every missed slot on both platforms |
| `ttclips --catchup` | Post all missed slots for today |
| `ttclips --dry-run` | Full pipeline, skip upload |
| `ttclips --no-upload` | Render the real 9:16 MP4 but don't post |
| `ttclips --post-file <path>` | Upload an already-rendered clip, skipping the pipeline |
| `ttclips --post-file <path> --caption "..."` | ...with a custom caption |
| `ttclips --url <link>` | Clip one specific video instead of the monitored channels: a YouTube or Twitch (VOD/clip) link, anything yt-dlp supports, or a local video file |
| `ttclips --url <link> --clips 3` | ...cut the top 3 highlights (1–5) |
| `ttclips --streams` | Discover streams for the topics in `config/streams.json` and queue allowlisted ones |
| `ttclips --stream-candidates` | List discovered streamers waiting for approval |
| `ttclips --approve-streamer NAME` | Allowlist a streamer and queue their pending clips/VODs |
| `ttclips --review` | Before each upload, edit the caption and press Enter to post (works with every posting command) |
| `ttclips-upload --auth` | TikTok API backend: one-time sign-in |
| `ttclips-youtube --auth` | YouTube API backend: one-time sign-in |
| `ttclips --version` | Print the installed version |
| `ttclips-gemini --probe` | Ping candidate Gemini models and report status |
| `ttclips-init --home <dir> --yes [--force]` | Scaffold config into a specific directory |
| `ttclips-youtube --probe` | Dump the YouTube Studio DOM (diagnostic, never posts) |
| `ttclips-youtube --validate-session` | Check the YouTube session from the terminal |

Posting flags compose: `--dry-run` skips the upload, `--no-upload` renders the
clip but doesn't post, and `--post-file` uploads an existing clip directly
(recording it in `data/posted.json` so it is never reposted).

### Clip any video (`--url`)

```bash
ttclips --url "https://www.youtube.com/watch?v=VIDEO_ID"
ttclips --url "https://www.twitch.tv/videos/123456789" --clips 3 --target both
ttclips --url "https://clips.twitch.tv/SomeClipSlug" --no-upload   # render only
ttclips --url "D:\recordings\podcast-ep12.mp4" --review
```

The link goes through the normal pipeline (download → transcribe → rank →
9:16 captions → upload). It is a one-off: the monitored queue isn't touched,
and posts are recorded with slot `manual`. Duplicate detection still applies,
so re-running the same link only posts highlights that aren't up yet.
Playlist and channel links are rejected; pass a single video. Only use links
to content you own or have rights to (see [`docs/LEGAL.md`](docs/LEGAL.md)).

### Review captions before posting (`--review`)

Add `--review` to any posting command. For each clip and platform, ttclips
shows the title and hashtags pre-filled, ready to edit in place:

```text
── Review · TikTok ──────────────────────────────
Clip  twitchvod_v123_610_640.mp4  (30.0s)
Title     › This is the best moment ever
Hashtags  › #funny #fyp #viral
── Will post ──
This is the best moment ever

#funny #fyp #viral
(48/2200 chars)
[Enter] upload  [e] edit  [p] play clip  [s] skip  [q] quit ›
```

Press Enter on each field to keep it, then Enter to upload. `p` opens the
clip in your video player, `s` skips this platform, and `q` stops the run
without posting anything else. Clearing the hashtags line posts with no
hashtags. `--review` waits for input, so it refuses to start in a
non-interactive session such as Task Scheduler.

## Configuration

### Target channels (`config/channels.json`)

Each channel entry:

| Field | Description |
|-------|-------------|
| `name` | Human-readable label (logging) |
| `channel_id` | YouTube channel ID |
| `enabled` | `true`/`false` to toggle a channel |
| `keywords` | Only accept uploads whose title matches at least one keyword; empty = accept all |
| `max_moments` | Max clips to post per video (1–5) |

Top-level options:

| Key | Description |
|-----|-------------|
| `excluded_keywords` | Titles containing these are skipped (`live`, `stream`, ...) |
| `min_duration_sec` / `max_duration_sec` | Accepted video length window |

### Posting window (`config/posting_window.json`)

A list of `{"time": "HH:MM", "type": "repost"|"generated", "hint": ""}` slots.
`hint` feeds the script prompt for generated-content slots. An optional
`"targets"` key overrides the platform(s) for that single slot
(`"targets": "youtube"`), e.g.:

```json
{ "time": "12:00", "type": "generated", "hint": "", "targets": "both" }
```

### Platforms (`config/platforms.json`)

| Key | Description |
|-----|-------------|
| `default_target` | `tiktok` (default), `youtube` or `both` |

The two platforms are **independent**: each keeps its own per-day slot
tracking and its own dedup records in `data/posted.json`, so a source video
posted to TikTok is still eligible for a YouTube Short. The CLI flag
`--target tiktok|youtube|both` overrides the config for a single run.

`default_target` is also the **queue policy**: a source video stays in
`data/queue.json` until every configured platform has it.

| `default_target` | Queue behaviour |
|------------------|-----------------|
| `tiktok` | the source leaves the queue after its TikTok posts (legacy behaviour) |
| `both` | the source stays queued until TikTok *and* YouTube have it |

To run the two platforms from **separate** scheduled tasks, set
`default_target` to `both` and give each task its own `--target`:

```powershell
# Task Scheduler -> ttclips-poster
ttclips --once --target tiktok
# Task Scheduler -> ttclips-poster-youtube
ttclips --once --target youtube
```

Both tasks then work off the same queue without evicting each other's work —
a one-off `--target` run never removes a source another platform still owes.

### TikTok upload settings (`config/tiktok.json`)

| Key | Description |
|-----|-------------|
| `headless` | Keep `false` — TikTok's bot detection is stricter headless |
| `min/max_action_delay_sec` | Human-like pause range between upload actions |
| `retries` | Upload attempts per clip |
| `retry_wait_initial_sec` / `retry_wait_backoff` / `retry_wait_max_sec` | Exponential backoff between attempts |
| `upload_timeout_sec` | Page-load budget |
| `user_agent` | Keep a recent desktop Chrome UA (stale UAs get reset by TikTok's WAF) |
| `default_hashtags` | Hashtags appended to every caption |
| `backend` | `browser` (default — Playwright + cookies) or `api` (official Content Posting API, see below) |
| `api.api_mode` | `inbox` (default — draft goes to your TikTok inbox) or `direct` (posts immediately) |
| `api.privacy_level` | Optional override; by default follows `visibility`, falling back to `SELF_ONLY` when the account doesn't allow it |
| `api.disable_comment` / `disable_duet` / `disable_stitch` | Interaction toggles (your own TikTok settings always win) |
| `api.chunk_size_mb`, `api.status_timeout_sec`, `api.token_file` | Upload chunking, processing wait, token location |

#### Official API backend (`"backend": "api"`)

Posts through TikTok's [Content Posting API](https://developers.tiktok.com/doc/content-posting-api-get-started)
instead of a browser: no cookies to re-export, no UI changes to break uploads,
chunked uploads with automatic retry, and AI-generated clips labelled as such.

1. Create an app at <https://developers.tiktok.com/> and add **Login Kit**
   (Desktop) and **Content Posting API**. Register the redirect URI
   `http://localhost:*/callback/` (wildcard port).
2. Add the keys to `.env`:

   ```ini
   TIKTOK_CLIENT_KEY=...
   TIKTOK_CLIENT_SECRET=...
   ```

3. Set `"backend": "api"` in `config/tiktok.json`, then run once:

   ```bash
   ttclips-upload --auth                # browser consent; token saved + auto-refreshed
   ttclips --validate-session           # confirms the token works
   ```

**Which mode?**

| | `inbox` (default) | `direct` |
|---|---|---|
| What happens | Draft lands in your TikTok inbox; you tap **Post** in the app | Published immediately |
| Needs TikTok's app audit | No | Yes, for anything but private posts |
| Before the audit | Works normally | Account must be **private**; posts are `SELF_ONLY` |

Inbox mode keeps ttclips' scheduling, clipping and captioning fully automatic
and leaves the final tap to you. TikTok's audit expects a person to approve
each direct post, so `inbox` is the realistic choice for most creators.

### YouTube Shorts settings (`config/youtube.json`)

| Key | Description |
|-----|-------------|
| `backend` | `studio` (default — Playwright + cookies) or `api` (official YouTube Data API v3, see below) |
| `client_secrets_file` | API backend: OAuth *Desktop app* client JSON (`config/client_secret.json`) |
| `token_file` | API backend: where the refresh token is saved (`data/youtube_token.json`) |
| `headless` | Keep `false` — Studio's upload dialog is flaky headless |
| `channel_id` | Optional `UC…` channel id; skips the "CREATE → Upload videos" clicks |
| `cookies_file` | Path to the exported Google cookies (`data/youtube_cookies.txt`) |
| `visibility` | `public` (default), `unlisted` or `private` |
| `made_for_kids` | `false` by default |
| `default_hashtags` | Hashtags added to every Short (`#Shorts` is appended automatically) |
| `include_source_link` | Adds the original YouTube URL to the description of reposts |
| `max_duration_sec` | `180` — the Shorts length limit |
| `min/max_action_delay_sec`, `retries`, `retry_wait_*`, `upload_timeout_sec`, `user_agent` | Same meaning as in `config/tiktok.json` |
| `selectors` | Override any Studio CSS selector when YouTube changes its markup |

`selectors` accepts a single CSS selector or a list of alternatives, e.g.:

```json
{ "selectors": { "post_button": ["ytcp-post-button", "button.post-button"] } }
```

When Studio changes its layout, run `ttclips-youtube --probe` — it writes
`data/cache/probe/{dom.html,elements.json,screen.png}` so the new selectors can
be picked without reading the code.

#### Official API backend (`"backend": "api"`)

Uploads through the YouTube Data API v3 instead of driving the Studio UI: no
cookies to re-export, no selectors that break when Studio changes, and
resumable uploads with automatic retry on 429/5xx errors.

1. `pip install "ttclips[api]"`
2. In [Google Cloud Console](https://console.cloud.google.com/), create a
   project, enable **YouTube Data API v3**, and create an OAuth client of type
   **Desktop app**. Save its JSON as `config/client_secret.json`.
3. Set `"backend": "api"` in `config/youtube.json`, then run once:

   ```bash
   ttclips-youtube --auth      # opens a browser for consent, saves the token
   ttclips --validate-youtube  # confirms the token and prints your channel
   ```

> **Audit caveat:** until your Cloud project passes YouTube's
> [API compliance audit](https://support.google.com/youtube/contact/yt_api_form),
> every video it uploads is locked to **private**. ttclips logs a warning when
> this happens. Use the `studio` backend until the audit is approved.

<a id="stream-topics"></a>
### Stream topics (`config/streams.json`)

Follow a *topic* (a game, an event) across Twitch and YouTube instead of a
fixed list of channels. When `"enabled": true`, every `--monitor` run (and
`--streams`) looks for:

- **Twitch clips** in the topic's category from the last `lookback_hours`,
  most viewed first. Viewers already picked the moment, so each clip is
  reframed, captioned and posted **whole**, with no Gemini ranking.
- **Finished streams**: Twitch archive VODs in the category and YouTube live
  broadcasts that have ended. These go through the normal highlight pipeline
  (`max_moments` clips each). Streams that are still live are skipped until
  they end, and VODs longer than `max_vod_hours` are skipped.

```json
{
  "enabled": true,
  "require_allowlist": true,
  "allowed_streamers": ["your_twitch_login", "UCyourYouTubeChannelId"],
  "max_vod_hours": 4,
  "topics": [{
    "name": "GTA6",
    "twitch_category": "Grand Theft Auto VI",
    "youtube_query": "GTA 6",
    "modes": ["clips", "vods"],
    "language": "en",
    "lookback_hours": 24,
    "min_clip_views": 200,
    "min_vod_views": 500,
    "max_moments": 2,
    "max_queue_per_run": 3,
    "hashtags": ["gta6", "gaming"]
  }]
}
```

**Allowlist (rights guardrail).** Only streamers listed in
`allowed_streamers` (Twitch login/display name, YouTube channel title or id,
case-insensitive) are queued. Everything else goes to
`data/stream_candidates.json`. List those with `ttclips --stream-candidates`,
and once you have permission from a streamer, run
`ttclips --approve-streamer NAME`. That adds them to the allowlist and queues
their pending items. Set `"require_allowlist": false` only if you have rights
to everything in the category.

Credentials go in `.env`, and a platform without them is skipped:
`TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` (a free app at
<https://dev.twitch.tv/console>), and `YOUTUBE_API_KEY` (a YouTube Data API
v3 key; each topic search uses about 101 of the 10,000 free daily quota
units). Topic hashtags lead each caption, and Gemini's or the platform
defaults fill the rest.

### Environment variables (`.env`)

| Variable | Default | Purpose |
|----------|---------|---------|
| `GEMINI_API_KEY` | — | **Required.** Google AI Studio key |
| `GEMINI_MODEL` | `gemini-3.6-flash` | Primary ranking/script model |
| `GEMINI_FALLBACK_MODELS` | `gemini-3.5-flash-lite,gemini-3.1-flash-lite` | Ordered fallbacks tried on 503/429 |
| `GEMINI_MAX_RETRIES` | `6` | Retries per model before switching |
| `GEMINI_RETRY_DELAY` | `3` | Initial backoff seconds |
| `GEMINI_RETRY_MAX_DELAY` | `45` | Backoff cap |
| `GEMINI_RETRY_TIMEOUT` | `90` | Hard cap on total retry time per model |
| `WHISPER_MODEL` | `small` | `tiny`/`base`/`small`/`medium`/`large-v3` |
| `WHISPER_DEVICE` | `auto` | Compute device |
| `TTS_VOICE` | `en-US-AvaNeural` | edge-tts narration voice |
| `PEXELS_API_KEY` | — | Optional stock b-roll background source |
| `TWITCH_CLIENT_ID` / `TWITCH_CLIENT_SECRET` | — | [Stream topics](#stream-topics): Twitch clips + VODs |
| `YOUTUBE_API_KEY` | — | [Stream topics](#stream-topics): finished YouTube live streams |
| `FFMPEG_BIN` / `FFPROBE_BIN` | — | Optional explicit binary paths |
| `COOKIES_FILE` | `data/cookies.txt` | TikTok session cookies (Netscape format) |
| `YOUTUBE_COOKIES_FILE` | `data/youtube_cookies.txt` | Google session cookies (Netscape format) |
| `CLIP_LAYOUT` | `auto` | Framing: `auto`/`track`/`stack`/`blur`/`crop` — see [Clip look](#clip-look) |
| `CLIP_FALLBACK_LAYOUT` | `crop` | What `auto` uses when no face is found (`crop`/`blur`) |
| `STACK_SPLIT` | `0.36` | Share of the height given to the facecam in `stack` |
| `CAPTION_STYLE` | `pop` | Caption preset: `pop`/`word`/`clean` |
| `CAPTION_FONT` | `Montserrat Black` | Bundled font, or any font installed on the PC |
| `CAPTION_FONT_SIZE` | `92` | Caption size |
| `CAPTION_MAX_WORDS` | `3` | Words per caption phrase |
| `CAPTION_MAX_LINE_CHARS` | `13` | Characters per line before wrapping/shrinking |
| `CAPTION_Y` | `0.68` | Caption centre, `0` = top … `1` = bottom |
| `CAPTION_UPPERCASE` / `CAPTION_HIGHLIGHT` | `1` / `1` | Uppercase text / colour the spoken word |
| `CAPTION_WORD_POP` | `110` | % size of the spoken word (`100` = off) |
| `CAPTION_COLOUR` / `HIGHLIGHT_COLOUR` / `CAPTION_OUTLINE_COLOUR` | `#FFFFFF` / `#FFE600` / `#000000` | Colours (`#RRGGBB`) |
| `CAPTION_OUTLINE` / `CAPTION_SHADOW` | `7` / `3` | Outline/shadow width |
| `HOOK_SECONDS` / `HOOK_Y` | `3.0` / `0.15` | Hook card duration (`0` = off) and position |
| `SNAP_TO_WORDS` | `1` | Trim clip bounds onto word boundaries |
| `AUDIO_NORMALIZE` | `1` | Loudness-normalise audio to −14 LUFS |
| `VIDEO_CRF` / `VIDEO_PRESET` / `VIDEO_MAX_FPS` | `18` / `veryfast` / `60` | x264 quality, speed, frame-rate cap |

### Clip look

**Framing.** Landscape sources are analysed before they are cut (`ttclips/framing.py`). With `CLIP_LAYOUT=auto` each clip gets one of:

| Layout | When `auto` picks it | Result |
|---|---|---|
| `track` | A face is on screen most of the time | 9:16 crop that follows the speaker — held still while they barely move, snapped (not slid) across scene cuts |
| `stack` | A small face parked in a corner (facecam over gameplay) | Facecam on top, gameplay underneath, captions on the seam |
| `crop` / `blur` | No steady face (`CLIP_FALLBACK_LAYOUT`) | Centre crop, or the whole picture over a blurred copy |

Set `CLIP_LAYOUT` to one of those names to force it for every clip. Sources
that are already vertical are left alone. Face detection uses OpenCV with a
bundled YuNet model; if OpenCV is missing, clips fall back to the centre crop.

**Captions.** Words are grouped into short phrases that break on pauses and
punctuation, set in the bundled Montserrat Black, and placed at 68% of the
frame height — below faces, above the platform's caption/button chrome. The
spoken word is coloured and pops; phrases hold through small gaps and clear
during real pauses. The clip title is shown as a hook card for the first
seconds. Pick a preset with `CAPTION_STYLE` (`pop`, `word`, `clean`) and
override any detail with the variables above.

Preview the look without posting: `ttclips --no-upload` (or
`ttclips --url <video> --no-upload`).

## State and data

| Path | Content |
|------|---------|
| `data/queue.json` | Discovered videos awaiting processing |
| `data/stream_candidates.json` | Discovered stream items from streamers not yet approved |
| `data/posted.json` | Post history / dedup, per platform (never reposts the same moment twice) |
| `data/cookies.txt` | TikTok session cookies (git-ignored) |
| `data/youtube_cookies.txt` | Google session cookies (git-ignored) |
| `data/downloads/` | Merged MP4s (reused on retry — no re-download) |
| `data/clips/` | Rendered vertical clips |
| `data/cache/` | Cached transcripts + highlight rankings (so a second platform run is cheap) |
| `data/broll/` | Cached stock backgrounds for generated clips |
| `data/logs/ttclips.log` | Full log |

## Automation

For unattended daily operation on Windows, register two tasks in **Task
Scheduler** (set the task *Start in* folder to the project directory, or define
`TTCLIPS_HOME`):

| Task | Trigger | Action |
|------|---------|--------|
| `ttclips-monitor` | Daily 06:00 | `ttclips --monitor` |
| `ttclips-poster` | Hourly 07:00→23:00 | `ttclips --once` |
| `ttclips-poster-youtube` | Hourly 07:00→23:00 | `ttclips --once --target youtube` |

The scheduler posts each slot at most once per day **per platform**. After the
machine was off, run `ttclips --catchup` to fill the missed slots for today
(add `--target youtube` for the YouTube-only variant).

To let the two platform tasks share one queue, set `"default_target": "both"`
in `config/platforms.json` — see
[Platforms](#platforms).

## FAQ

<details>
<summary><b>Do I need a TikTok API key?</b></summary>

No. Uploads use Playwright browser automation with your exported session
cookies — no developer approval or API key is required.
</details>

<details>
<summary><b>Why not the YouTube Data API?</b></summary>

Since 28 July 2020, videos uploaded through the YouTube Data API by a project
that has **not** completed YouTube's compliance audit are locked as *private*
and cannot be published — not even by hand in Studio. Passing that audit takes
weeks and usually requires a Google Cloud project.

ttclips therefore drives **YouTube Studio** with Playwright, using the same
cookie-based approach as TikTok. A Studio upload is an ordinary upload: it is
public immediately and needs no Google Cloud project, no OAuth app and no API
review.
</details>

<details>
<summary><b>Do I need a Google Cloud project or API key for Shorts?</b></summary>

No. Only exported browser cookies for a logged-in `studio.youtube.com` session
(`data/youtube_cookies.txt`). There is no OAuth client, no quota and no audit.
</details>

<details>
<summary><b>How do TikTok and YouTube Shorts interact?</b></summary>

They are independent targets. Each platform tracks its own slots per day and
its own dedup records in `data/posted.json`, so a source video posted to
TikTok can still be posted as a Short, and a clip that failed on one platform
is retried on that platform only. `--target both` renders a clip once and
uploads it to both. A source only leaves the queue once **every** platform
listed in `config/platforms.json` has it.
</details>

<details>
<summary><b>The YouTube upload clicks the wrong button / can't find the fields.</b></summary>

YouTube Studio's markup changes from time to time. Run
`ttclips-youtube --probe` and inspect `data/cache/probe/elements.json` for the
current element names, then override the selector in `config/youtube.json`
under `"selectors"` — no code change needed.
</details>

<details>
<summary><b>Why does the upload fail or hang?</b></summary>

TikTok's bot detection is aggressive. Keep `headless: false` in
`config/tiktok.json`, use a recent desktop Chrome `user_agent`, and re-export
cookies monthly. Retries use exponential backoff; a CAPTCHA fails the run
loudly rather than silently posting. The same applies to YouTube Studio —
keep `headless: false` in `config/youtube.json` and re-export the Google
cookies when the session expires (`ttclips --validate-youtube`).
</details>

<details>
<summary><b>Why does it need ffmpeg?</b></summary>

ffmpeg merges YouTube video+audio streams, reframes to 9:16, and burns in the
captions. `ffmpeg` plus `ffprobe` must resolve on `PATH` (or via
`FFMPEG_BIN`/`FFPROBE_BIN`).
</details>

<details>
<summary><b>Gemini keeps erroring (503 / 429 / high demand)?</b></summary>

The runtime probes candidate models at startup and promotes the healthiest one;
the fallback chain walks through the remaining models with jittered backoff
bounded by `GEMINI_RETRY_TIMEOUT`. Older `flash` models return 404 for new
free-tier keys — use the models listed in `.env.example`.
</details>

<details>
<summary><b>How do I uninstall?</b></summary>

```bash
pip uninstall ttclips
```

State under `data/` and `.env` are not removed.
</details>

## Development

```bash
git clone https://github.com/kamzysert3/ttclips.git
cd ttclips
python -m venv .venv
.\.venv\Scripts\activate        # Windows (PowerShell)
source .venv/bin/activate       # macOS/Linux
pip install -e .
playwright install chromium
```

One-command setup on Windows: `powershell -ExecutionPolicy Bypass -File scripts\setup.ps1`
(creates the venv, installs the package, Playwright, ffmpeg via winget, and
`.env` from the example).

Run the test suite (offline, no cookies or API keys; CI runs it on Windows
and Linux for Python 3.10 and 3.12):

```bash
pip install -e ".[dev,api]"
python -m pytest
```

It covers state durability (atomic writes, cross-process locking,
corrupt-file quarantine), per-platform dedup and slot fairness, target
resolution, scaffolding, YouTube metadata, and the Data API backend with a
stubbed service. Three end-to-end simulations also ship with the repo:

```bash
.\.venv\Scripts\python.exe scripts\check_targets.py       # platform-aware state + metadata
.\.venv\Scripts\python.exe scripts\check_repost_flow.py   # cross-post fan-out with stubbed uploaders
.\.venv\Scripts\python.exe scripts\check_youtube_flow.py  # Studio automation against a mock DOM
```

Contributions are welcome via pull request — keep changes consistent with the
existing structure and style, and keep `pyproject.toml` + `ttclips/__init__.py`
versions in sync.

## Releasing

Pushing a version tag builds the distributions and publishes them to PyPI
automatically (GitHub Actions):

```bash
git add . && git commit -m "Release v1.1.0"
git tag v1.1.0
git push origin main --tags
```

The release pipeline verifies the tag matches the version in both
`pyproject.toml` and `ttclips/__init__.py`, builds the wheel + sdist, runs
`twine check`, and publishes via trusted publishing (OIDC) — no API tokens.

## Legal & operational notes

- **Terms & privacy:** <https://kamzysert3.github.io/ttclips/terms.html> ·
  <https://kamzysert3.github.io/ttclips/privacy.html> — ttclips runs locally and
  the project operates no server; those pages spell out what stays on your
  machine and what goes to TikTok, Google or Pexels.
- **Own your content:** ttclips is a repurposing tool — configure only channels
  you own or have rights to repost. `ttclips --init --yes` records that
  acknowledgement. Clipping channels without permission can violate YouTube ToS
  and creators' rights; see
  [`docs/LEGAL.md`](https://github.com/kamzysert3/ttclips/blob/main/docs/LEGAL.md).
- **TikTok ToS:** browser automation to post content is personal-use and
  may not be permitted for commercial accounts — verify your own risk.
- **YouTube ToS:** posting to YouTube Studio is done with browser automation
  on your own account. Automated posting can breach YouTube's Terms of
  Service, and re-uploading content you do not own is a copyright violation.
- **UI changes:** TikTok's and YouTube Studio's uploader selectors can change;
  pin dependency versions, re-export cookies regularly and use the
  `selectors` overrides in the config files.
- **Free-tier limits:** the Gemini free tier handles dozens of calls/day —
  comfortable for a few daily clips.

## Support the project

If ttclips saves you time, consider sponsoring its development:

❤️ **[Sponsor ttclips on GitHub](https://github.com/sponsors/kamzysert3)**

Sponsorships fund maintenance, new features, and documentation.

## License

[MIT](https://github.com/kamzysert3/ttclips/blob/main/LICENSE) — see the
`LICENSE` file for full terms.
