Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

feat: timestamps support, srt embed improvements, agent skills, and multi-lang docs update

wulienb45f914c7358
diff --git a/.gitignore b/.gitignore
index 0b733c66..eba4f809 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,7 @@
.claude/
.github/
docs/plans/
+docs/superpowers/
tasks/
cookies.txt
.vscode/
@@ -20,3 +21,6 @@ dist/
.DS_Store
._*
KrillinAI.exe
+.codegraph/
+.deepseek/
+run.log
diff --git a/cmd/cli/main.go b/cmd/cli/main.go
index 3e8de737..40d6e297 100644
--- a/cmd/cli/main.go
+++ b/cmd/cli/main.go
@@ -21,6 +21,10 @@ func main() {
if err != nil {
writeAndExit(errorResponse(err, pipeline.ErrorKindUsage))
}
+ if cmd.Help {
+ fmt.Print(cli.Help(cmd))
+ return
+ }
if cmd.DryRun {
writeAndExit(cli.Execute(context.Background(), nil, cmd))
return
diff --git a/docs/ar/README.md b/docs/ar/README.md
index 2814158e..0b628d4e 100644
--- a/docs/ar/README.md
+++ b/docs/ar/README.md
@@ -168,6 +168,77 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
يدعم هذا المشروع نشر Docker؛ يرجى الرجوع إلى [تعليمات نشر Docker](./docker.md)
+### استخدام CLI
+
+يوفر KrillinAI الآن واجهة أوامر مرحلية مناسبة للسكريبتات وخطوط الأتمتة ووكلاء الذكاء الاصطناعي. تعمل الأوامر بشكل متزامن افتراضيًا، وتطبع في stdout سطر JSON واحدًا عند الانتهاء، وتكتب `krillinai_manifest.json` في مجلد العمل حتى تتمكن المراحل اللاحقة من إعادة استخدام المخرجات.
+
+بناء CLI من المصدر:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+نظرة عامة على الأوامر:
+
+| الأمر | الغرض | المخرجات الشائعة |
+|---|---|---|
+| `subtitle` | إنشاء ترجمات من رابط YouTube / Bilibili أو فيديو محلي؛ يفضل تنزيل ترجمات المنصة ثم يعود إلى Whisper عند الفشل | `origin_language_srt.srt`، `target_language_srt.srt`، `bilingual_srt.srt`، `short_origin_mixed_srt.srt` |
+| `tts` | إنشاء دبلجة باللغة الهدف من الترجمة الهدف | `tts_final_audio.wav`، `video_with_tts.mp4` |
+| `render-horizontal` | إنشاء فيديو أفقي: الفيديو الأصلي + ترجمة ثنائية، أو فيديو مدبلج + ترجمة باللغة الهدف | `horizontal_bilingual.mp4` |
+| `render-vertical` | إنشاء فيديو عمودي: تحويل الفيديو الأصلي إلى عمودي + ترجمة قصيرة، أو فيديو مدبلج + ترجمة باللغة الهدف | `transferred_vertical_video.mp4`، `vertical_bilingual.mp4` |
+| `pipeline` | ربط عدة مراحل حسب قيمة outputs | يعتمد على المراحل المحددة |
+| `cover` | إنشاء غلاف من غلاف الفيديو الأصلي وقالب prompt | `generated_cover.png` |
+
+سير عمل نموذجي:
+
+```bash
+# 1. إنشاء ترجمات المصدر والهدف والترجمة الثنائية والترجمة القصيرة للفيديو العمودي
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. إنشاء الدبلجة من ترجمة اللغة الهدف
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. إنشاء فيديو أفقي بترجمة ثنائية
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. إنشاء فيديو عمودي بترجمة ثنائية قصيرة
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "موضوع اليوم" \
+ --minor-title "AI Video"
+```
+
+اتفاقيات تكامل Agent:
+
+- اقرأ آخر سطر JSON في stdout وملف `krillinai_manifest.json` أولًا؛ لا تعتمد على تحليل السجلات العادية.
+- يسجل حقل `outputs` مسارات المخرجات، ويمكن للأوامر اللاحقة استخدام `--workdir` فقط لإعادة استخدام manifest.
+- يدعم `--dry-run` للتحقق من المعلمات وإنشاء manifest دون تنزيل فيديو أو استدعاء خدمات ذكاء اصطناعي خارجية.
+- عالج الأخطاء حسب `error.kind`: `usage` لتصحيح المعلمات، و`retryable` لإعادة المحاولة، و`dependency` لتثبيت `ffmpeg` / `ffprobe` / `yt-dlp`.
+
+للحصول على شرح أكثر تفصيلًا للمعلمات، راجع [ملخص قدرات CLI](../zh/cli.md).
+
+### Agent Skills
+
+يوفر المستودع أيضًا Skills جاهزة للاستخدام داخل `skills/` حتى تتمكن الوكلاء من استدعاء CLI وفق اتفاقيات مستقرة:
+
+- [`krillinai-cli`](../../skills/krillinai-cli/SKILL.md): skill المدخل العام لاختيار سير عمل الترجمة، TTS، التصيير، pipeline أو الغلاف.
+- [`krillinai-subtitle`](../../skills/krillinai-subtitle/SKILL.md)، [`krillinai-tts`](../../skills/krillinai-tts/SKILL.md)، [`krillinai-render-horizontal`](../../skills/krillinai-render-horizontal/SKILL.md)، و[`krillinai-render-vertical`](../../skills/krillinai-render-vertical/SKILL.md): أدلة تشغيل خاصة بكل مرحلة.
+- [`krillinai-pipeline`](../../skills/krillinai-pipeline/SKILL.md) و[`krillinai-cover`](../../skills/krillinai-cover/SKILL.md): أدلة تخطيط/واجهات محجوزة لتنظيم pipeline وتوليد الغلاف إلى أن يتم توصيل مسارات التنفيذ بالكامل.
+- [`cli-contract.md`](../../skills/krillinai-cli/references/cli-contract.md): عقد JSON وmanifest والمخرجات ومعالجة الأخطاء المشترك.
+
استنادًا إلى ملف التكوين المقدم، إليك قسم "مساعدة التكوين (يجب قراءته)" المحدث لملف README الخاص بك:
### مساعدة التكوين (يجب قراءته)
@@ -215,4 +286,4 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
## تاريخ النجوم
-[![مخطط تاريخ النجوم](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![مخطط تاريخ النجوم](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/de/README.md b/docs/de/README.md
index f40cffc2..aed5f8d7 100644
--- a/docs/de/README.md
+++ b/docs/de/README.md
@@ -168,6 +168,77 @@ Diese Software ist nicht signiert, daher müssen Sie beim Ausführen auf macOS n
Dieses Projekt unterstützt die Docker-Bereitstellung; bitte beziehen Sie sich auf die [Docker-Bereitstellungsanweisungen](./docker.md)
+### CLI-Verwendung
+
+KrillinAI bietet jetzt eine stufenbasierte CLI für Skripte, Automatisierungspipelines und AI Agents. Die CLI läuft standardmäßig synchron, gibt nach Abschluss eine JSON-Zeile über stdout aus und schreibt `krillinai_manifest.json` in das Arbeitsverzeichnis, damit spätere Stufen vorhandene Artefakte wiederverwenden können.
+
+CLI aus dem Quellcode bauen:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+Befehlsübersicht:
+
+| Befehl | Zweck | Häufige Artefakte |
+|---|---|---|
+| `subtitle` | Untertitel aus YouTube-/Bilibili-Links oder lokalen Videos erzeugen; Plattformuntertitel werden bevorzugt, bei Fehlschlag wird auf Whisper zurückgegriffen | `origin_language_srt.srt`, `target_language_srt.srt`, `bilingual_srt.srt`, `short_origin_mixed_srt.srt` |
+| `tts` | Zielsprachige Vertonung aus Zieluntertiteln erzeugen | `tts_final_audio.wav`, `video_with_tts.mp4` |
+| `render-horizontal` | Querformatvideo erzeugen: Originalvideo + zweisprachige Untertitel oder vertontes Video + Zielsprachenuntertitel | `horizontal_bilingual.mp4` |
+| `render-vertical` | Hochformatvideo erzeugen: Originalvideo ins Hochformat umwandeln + kurze Untertitel oder vertontes Video + Zielsprachenuntertitel | `transferred_vertical_video.mp4`, `vertical_bilingual.mp4` |
+| `pipeline` | Mehrere Stufen anhand von outputs verbinden | Abhängig von den gewählten Stufen |
+| `cover` | Cover aus dem ursprünglichen Videocover und einer Prompt-Vorlage erzeugen | `generated_cover.png` |
+
+Typischer Workflow:
+
+```bash
+# 1. Quell-, Ziel-, zweisprachige und kurze Hochformat-Untertitel erzeugen
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. Vertonung aus Zielsprachenuntertiteln erzeugen
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. Querformatvideo mit zweisprachigen Untertiteln erzeugen
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. Hochformatvideo mit kurzen zweisprachigen Untertiteln erzeugen
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "Heutiges Thema" \
+ --minor-title "AI Video"
+```
+
+Agent-Integrationsregeln:
+
+- Zuerst die letzte JSON-Zeile in stdout und `krillinai_manifest.json` auswerten; normale Logs nicht parsen.
+- Das Feld `outputs` enthält Artefaktpfade; spätere Befehle können nur mit `--workdir` das Manifest wiederverwenden.
+- `--dry-run` prüft Parameter und erzeugt ein Manifest, ohne Videos herunterzuladen oder externe AI-Dienste aufzurufen.
+- Fehler nach `error.kind` behandeln: `usage` bedeutet Parameter korrigieren, `retryable` bedeutet erneut versuchen, `dependency` bedeutet `ffmpeg` / `ffprobe` / `yt-dlp` installieren.
+
+Weitere Parameterdetails finden Sie in der [CLI-Funktionsübersicht](../zh/cli.md).
+
+### Agent Skills
+
+Das Repository enthält außerdem sofort nutzbare Agent Skills unter `skills/`, damit Agents die CLI mit stabilen Konventionen aufrufen können:
+
+- [`krillinai-cli`](../../skills/krillinai-cli/SKILL.md): zentrale Routing-Skill zur Auswahl von Untertitel-, TTS-, Render-, Pipeline- oder Cover-Workflows.
+- [`krillinai-subtitle`](../../skills/krillinai-subtitle/SKILL.md), [`krillinai-tts`](../../skills/krillinai-tts/SKILL.md), [`krillinai-render-horizontal`](../../skills/krillinai-render-horizontal/SKILL.md) und [`krillinai-render-vertical`](../../skills/krillinai-render-vertical/SKILL.md): stufenspezifische Betriebsanleitungen.
+- [`krillinai-pipeline`](../../skills/krillinai-pipeline/SKILL.md) und [`krillinai-cover`](../../skills/krillinai-cover/SKILL.md): Planungs-/Reservierungsleitfäden für Pipeline-Orchestrierung und Cover-Erzeugung, bis diese Ausführungspfade vollständig verdrahtet sind.
+- [`cli-contract.md`](../../skills/krillinai-cli/references/cli-contract.md): gemeinsamer Vertrag für JSON, Manifest, Ausgaben und Fehlerbehandlung.
+
Basierend auf der bereitgestellten Konfigurationsdatei finden Sie hier den aktualisierten Abschnitt "Konfigurationshilfe (Unbedingt lesen)" für Ihre README-Datei:
### Konfigurationshilfe (Unbedingt lesen)
@@ -215,4 +286,4 @@ Bitte besuchen Sie die [Häufig gestellten Fragen](./faq.md)
## Star-Historie
-[![Star-Historien-Diagramm](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![Star-Historien-Diagramm](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/es/README.md b/docs/es/README.md
index 57a3087c..3e1f93cd 100644
--- a/docs/es/README.md
+++ b/docs/es/README.md
@@ -168,6 +168,77 @@ Este software no está firmado, por lo que al ejecutarlo en macOS, después de c
Este proyecto soporta el despliegue en Docker; por favor consulta las [Instrucciones de Despliegue en Docker](./docker.md)
+### Uso de CLI
+
+KrillinAI ahora ofrece una CLI por etapas, adecuada para scripts, pipelines de automatización y agentes de IA. La CLI se ejecuta de forma síncrona por defecto, imprime una línea JSON en stdout al finalizar y escribe `krillinai_manifest.json` en el directorio de trabajo para que las etapas posteriores puedan reutilizar los artefactos existentes.
+
+Compilar la CLI desde el código fuente:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+Resumen de comandos:
+
+| Comando | Uso | Artefactos comunes |
+|---|---|---|
+| `subtitle` | Genera subtítulos desde enlaces de YouTube / Bilibili o videos locales; primero intenta usar subtítulos de la plataforma y, si falla, recurre a Whisper | `origin_language_srt.srt`, `target_language_srt.srt`, `bilingual_srt.srt`, `short_origin_mixed_srt.srt` |
+| `tts` | Genera doblaje en el idioma destino a partir de los subtítulos destino | `tts_final_audio.wav`, `video_with_tts.mp4` |
+| `render-horizontal` | Genera video horizontal: video original + subtítulos bilingües, o video doblado + subtítulos en el idioma destino | `horizontal_bilingual.mp4` |
+| `render-vertical` | Genera video vertical: video original convertido a vertical + subtítulos cortos, o video doblado + subtítulos en el idioma destino | `transferred_vertical_video.mp4`, `vertical_bilingual.mp4` |
+| `pipeline` | Encadena varias etapas según outputs | Depende de las etapas seleccionadas |
+| `cover` | Genera una portada a partir de la portada original del video y una plantilla de prompt | `generated_cover.png` |
+
+Flujo de trabajo típico:
+
+```bash
+# 1. Generar subtítulos de origen, destino, bilingües y cortos para vertical
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. Generar doblaje desde los subtítulos del idioma destino
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. Generar video horizontal con subtítulos bilingües
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. Generar video vertical con subtítulos bilingües cortos
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "Tema de hoy" \
+ --minor-title "AI Video"
+```
+
+Convenciones de integración para Agent:
+
+- Lee primero la última línea JSON de stdout y `krillinai_manifest.json`; no analices logs normales.
+- El campo `outputs` registra las rutas de los artefactos; los comandos posteriores pueden reutilizar el manifest pasando solo `--workdir`.
+- `--dry-run` valida parámetros y genera el manifest sin descargar videos ni llamar servicios externos de IA.
+- Maneja errores según `error.kind`: `usage` corrige parámetros, `retryable` permite reintentar, `dependency` requiere instalar `ffmpeg` / `ffprobe` / `yt-dlp`.
+
+Para una explicación más completa de los parámetros, consulta el [resumen de capacidades de la CLI](../zh/cli.md).
+
+### Agent Skills
+
+El repositorio también incluye Agent Skills listas para usar en `skills/`, para que los agentes puedan llamar la CLI con convenciones estables:
+
+- [`krillinai-cli`](../../skills/krillinai-cli/SKILL.md): skill de entrada principal para elegir flujos de subtítulos, TTS, renderizado, pipeline o portada.
+- [`krillinai-subtitle`](../../skills/krillinai-subtitle/SKILL.md), [`krillinai-tts`](../../skills/krillinai-tts/SKILL.md), [`krillinai-render-horizontal`](../../skills/krillinai-render-horizontal/SKILL.md) y [`krillinai-render-vertical`](../../skills/krillinai-render-vertical/SKILL.md): guías operativas específicas de cada etapa.
+- [`krillinai-pipeline`](../../skills/krillinai-pipeline/SKILL.md) y [`krillinai-cover`](../../skills/krillinai-cover/SKILL.md): guías de planificación/reserva para orquestación de pipeline y generación de portada hasta que esas rutas de ejecución estén completamente conectadas.
+- [`cli-contract.md`](../../skills/krillinai-cli/references/cli-contract.md): contrato compartido de JSON, manifest, outputs y manejo de errores.
+
Basado en el archivo de configuración proporcionado, aquí está la sección actualizada "Ayuda de Configuración (Debe Leer)" para tu archivo README:
### Ayuda de Configuración (Debe Leer)
@@ -215,4 +286,4 @@ Por favor visita [Preguntas Frecuentes](./faq.md)
## Historial de Estrellas
-[![Gráfico de Historial de Estrellas](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![Gráfico de Historial de Estrellas](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/fr/README.md b/docs/fr/README.md
index bdd9864f..e051c5e6 100644
--- a/docs/fr/README.md
+++ b/docs/fr/README.md
@@ -168,6 +168,77 @@ Ce logiciel n'est pas signé, donc lors de l'exécution sur macOS, après avoir
Ce projet prend en charge le déploiement Docker ; veuillez vous référer aux [Instructions de déploiement Docker](./docker.md)
+### Utilisation de la CLI
+
+KrillinAI propose désormais une CLI par étapes, adaptée aux scripts, aux pipelines d'automatisation et aux agents IA. Par défaut, la CLI s'exécute de manière synchrone, imprime une ligne JSON sur stdout à la fin, et écrit `krillinai_manifest.json` dans le répertoire de travail afin que les étapes suivantes puissent réutiliser les artefacts existants.
+
+Compiler la CLI depuis le code source :
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+Résumé des commandes :
+
+| Commande | Usage | Artefacts courants |
+|---|---|---|
+| `subtitle` | Génère des sous-titres depuis un lien YouTube / Bilibili ou une vidéo locale ; tente d'abord les sous-titres de la plateforme, puis revient à Whisper en cas d'échec | `origin_language_srt.srt`, `target_language_srt.srt`, `bilingual_srt.srt`, `short_origin_mixed_srt.srt` |
+| `tts` | Génère un doublage dans la langue cible à partir des sous-titres cibles | `tts_final_audio.wav`, `video_with_tts.mp4` |
+| `render-horizontal` | Génère une vidéo horizontale : vidéo originale + sous-titres bilingues, ou vidéo doublée + sous-titres en langue cible | `horizontal_bilingual.mp4` |
+| `render-vertical` | Génère une vidéo verticale : vidéo originale convertie en vertical + sous-titres courts, ou vidéo doublée + sous-titres en langue cible | `transferred_vertical_video.mp4`, `vertical_bilingual.mp4` |
+| `pipeline` | Enchaîne plusieurs étapes selon outputs | Dépend des étapes sélectionnées |
+| `cover` | Génère une couverture à partir de la couverture originale de la vidéo et d'un modèle de prompt | `generated_cover.png` |
+
+Flux de travail typique :
+
+```bash
+# 1. Générer les sous-titres source, cible, bilingues et courts pour vertical
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. Générer le doublage à partir des sous-titres de la langue cible
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. Générer une vidéo horizontale avec sous-titres bilingues
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. Générer une vidéo verticale avec sous-titres bilingues courts
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "Sujet du jour" \
+ --minor-title "AI Video"
+```
+
+Conventions d'intégration pour les agents :
+
+- Lire en priorité la dernière ligne JSON de stdout et `krillinai_manifest.json` ; ne pas analyser les logs ordinaires.
+- Le champ `outputs` enregistre les chemins des artefacts ; les commandes suivantes peuvent réutiliser le manifest avec seulement `--workdir`.
+- `--dry-run` valide les paramètres et génère le manifest sans télécharger de vidéo ni appeler de service IA externe.
+- Traiter les erreurs selon `error.kind` : `usage` pour corriger les paramètres, `retryable` pour réessayer, `dependency` pour installer `ffmpeg` / `ffprobe` / `yt-dlp`.
+
+Pour une description plus complète des paramètres, consultez le [résumé des capacités CLI](../zh/cli.md).
+
+### Agent Skills
+
+Le dépôt inclut également des Agent Skills prêts à l'emploi dans `skills/`, afin que les agents puissent appeler la CLI avec des conventions stables :
+
+- [`krillinai-cli`](../../skills/krillinai-cli/SKILL.md) : skill d'entrée principale pour choisir les workflows de sous-titres, TTS, rendu, pipeline ou couverture.
+- [`krillinai-subtitle`](../../skills/krillinai-subtitle/SKILL.md), [`krillinai-tts`](../../skills/krillinai-tts/SKILL.md), [`krillinai-render-horizontal`](../../skills/krillinai-render-horizontal/SKILL.md) et [`krillinai-render-vertical`](../../skills/krillinai-render-vertical/SKILL.md) : guides opérationnels propres à chaque étape.
+- [`krillinai-pipeline`](../../skills/krillinai-pipeline/SKILL.md) et [`krillinai-cover`](../../skills/krillinai-cover/SKILL.md) : guides de planification/réservation pour l'orchestration pipeline et la génération de couverture tant que ces chemins d'exécution ne sont pas entièrement connectés.
+- [`cli-contract.md`](../../skills/krillinai-cli/references/cli-contract.md) : contrat partagé pour JSON, manifest, outputs et gestion des erreurs.
+
Basé sur le fichier de configuration fourni, voici la section mise à jour "Aide à la configuration (À lire absolument)" pour votre fichier README :
### Aide à la configuration (À lire absolument)
@@ -215,4 +286,4 @@ Veuillez visiter [Questions Fréquemment Posées](./faq.md)
## Historique des étoiles
-[![Graphique de l'historique des étoiles](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![Graphique de l'historique des étoiles](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/jp/README.md b/docs/jp/README.md
index 601819d7..802098c3 100644
--- a/docs/jp/README.md
+++ b/docs/jp/README.md
@@ -168,6 +168,77 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
このプロジェクトはDocker展開をサポートしています。詳細は[Docker展開手順](./docker.md)を参照してください。
+### CLIの使い方
+
+KrillinAI は、スクリプト、自動化パイプライン、AI Agent から呼び出しやすい段階型 CLI を提供しています。CLI はデフォルトで同期実行され、完了時に stdout に 1 行の JSON を出力し、作業ディレクトリに `krillinai_manifest.json` を書き込みます。これにより、後続の段階で既存の成果物を再利用できます。
+
+ソースから CLI をビルドします:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+コマンド概要:
+
+| コマンド | 用途 | 主な成果物 |
+|---|---|---|
+| `subtitle` | YouTube / Bilibili リンクまたはローカル動画から字幕を生成します。まずプラットフォーム字幕を取得し、失敗した場合は Whisper にフォールバックします | `origin_language_srt.srt`、`target_language_srt.srt`、`bilingual_srt.srt`、`short_origin_mixed_srt.srt` |
+| `tts` | 目標言語字幕から目標言語の吹き替え音声を生成します | `tts_final_audio.wav`、`video_with_tts.mp4` |
+| `render-horizontal` | 横向き動画を生成します:元動画 + 二言語字幕、または吹き替え動画 + 目標言語字幕 | `horizontal_bilingual.mp4` |
+| `render-vertical` | 縦向き動画を生成します:元動画を縦向きに変換 + 短い字幕、または吹き替え動画 + 目標言語字幕 | `transferred_vertical_video.mp4`、`vertical_bilingual.mp4` |
+| `pipeline` | outputs に基づいて複数段階を連結します | 選択した段階によって異なります |
+| `cover` | 元動画のカバー画像と prompt テンプレートからカバーを生成します | `generated_cover.png` |
+
+典型的なワークフロー:
+
+```bash
+# 1. 元言語、目標言語、二言語字幕、縦向き用短字幕を生成
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. 目標言語字幕から吹き替えを生成
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. 二言語字幕付きの横向き動画を生成
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. 短い二言語字幕付きの縦向き動画を生成
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "今日の話題" \
+ --minor-title "AI Video"
+```
+
+Agent 連携の規約:
+
+- stdout の最後の JSON 行と `krillinai_manifest.json` を優先して読み取ってください。通常ログは解析しないでください。
+- `outputs` フィールドには成果物パスが記録されます。後続コマンドは `--workdir` だけで manifest を再利用できます。
+- `--dry-run` は、動画ダウンロードや外部 AI サービス呼び出しを行わずに、引数検証と manifest 生成を行います。
+- `error.kind` に応じてエラーを処理します:`usage` は引数修正、`retryable` は再試行、`dependency` は `ffmpeg` / `ffprobe` / `yt-dlp` のインストールが必要です。
+
+より詳しいパラメータ説明は、[CLI 機能概要](../zh/cli.md)を参照してください。
+
+### Agent Skills
+
+このリポジトリには、Agent が安定した規約で CLI を呼び出せるように、`skills/` 配下にすぐ使える Agent Skills も含まれています:
+
+- [`krillinai-cli`](../../skills/krillinai-cli/SKILL.md):字幕、TTS、レンダリング、pipeline、カバーのワークフローを選択するための総合入口 skill。
+- [`krillinai-subtitle`](../../skills/krillinai-subtitle/SKILL.md)、[`krillinai-tts`](../../skills/krillinai-tts/SKILL.md)、[`krillinai-render-horizontal`](../../skills/krillinai-render-horizontal/SKILL.md)、[`krillinai-render-vertical`](../../skills/krillinai-render-vertical/SKILL.md):各段階に特化した操作ガイド。
+- [`krillinai-pipeline`](../../skills/krillinai-pipeline/SKILL.md) と [`krillinai-cover`](../../skills/krillinai-cover/SKILL.md):pipeline 編成とカバー生成のための計画/予約済みガイド。対応する実行パスが完全に接続されるまでは計画用途として扱います。
+- [`cli-contract.md`](../../skills/krillinai-cli/references/cli-contract.md):JSON、manifest、outputs、エラー処理に関する共通契約。
+
提供された設定ファイルに基づいて、READMEファイルの「設定ヘルプ(必読)」セクションを更新しました:
### 設定ヘルプ(必読)
@@ -215,4 +286,4 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
## スター履歴
-[![スター履歴チャート](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![スター履歴チャート](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/kr/README.md b/docs/kr/README.md
index e4c14439..d656253d 100644
--- a/docs/kr/README.md
+++ b/docs/kr/README.md
@@ -168,6 +168,77 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
이 프로젝트는 Docker 배포를 지원합니다. [Docker 배포 지침](./docker.md)을 참조하세요.
+### CLI 사용법
+
+KrillinAI는 스크립트, 자동화 파이프라인, AI Agent가 호출하기 쉬운 단계형 CLI를 제공합니다. CLI는 기본적으로 동기 실행되며, 완료 후 stdout에 JSON 한 줄을 출력하고 작업 디렉터리에 `krillinai_manifest.json`을 기록하여 이후 단계가 기존 산출물을 재사용할 수 있게 합니다.
+
+소스에서 CLI 빌드:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+명령 개요:
+
+| 명령 | 용도 | 주요 산출물 |
+|---|---|---|
+| `subtitle` | YouTube / Bilibili 링크 또는 로컬 영상에서 자막을 생성합니다. 플랫폼 자막을 우선 다운로드하고 실패하면 Whisper 전사로 대체합니다 | `origin_language_srt.srt`, `target_language_srt.srt`, `bilingual_srt.srt`, `short_origin_mixed_srt.srt` |
+| `tts` | 목표 언어 자막을 기반으로 목표 언어 더빙을 생성합니다 | `tts_final_audio.wav`, `video_with_tts.mp4` |
+| `render-horizontal` | 가로 영상을 생성합니다: 원본 영상 + 이중 언어 자막, 또는 더빙 영상 + 목표 언어 자막 | `horizontal_bilingual.mp4` |
+| `render-vertical` | 세로 영상을 생성합니다: 원본 영상을 세로로 변환 + 짧은 자막, 또는 더빙 영상 + 목표 언어 자막 | `transferred_vertical_video.mp4`, `vertical_bilingual.mp4` |
+| `pipeline` | outputs에 따라 여러 단계를 연결합니다 | 선택한 단계에 따라 다름 |
+| `cover` | 원본 영상 커버와 prompt 템플릿으로 커버를 생성합니다 | `generated_cover.png` |
+
+일반적인 워크플로:
+
+```bash
+# 1. 원본 언어, 목표 언어, 이중 언어 자막, 세로 영상용 짧은 자막 생성
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. 목표 언어 자막으로 더빙 생성
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. 이중 언어 자막이 포함된 가로 영상 생성
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. 짧은 이중 언어 자막이 포함된 세로 영상 생성
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "오늘의 주제" \
+ --minor-title "AI Video"
+```
+
+Agent 통합 규칙:
+
+- stdout의 마지막 JSON 줄과 `krillinai_manifest.json`을 우선 읽으세요. 일반 로그를 파싱하지 마세요.
+- `outputs` 필드는 산출물 경로를 기록하며, 이후 명령은 `--workdir`만 전달해 manifest를 재사용할 수 있습니다.
+- `--dry-run`은 영상을 다운로드하거나 외부 AI 서비스를 호출하지 않고 매개변수를 검증하고 manifest를 생성합니다.
+- `error.kind`에 따라 오류를 처리하세요: `usage`는 매개변수 수정, `retryable`은 재시도, `dependency`는 `ffmpeg` / `ffprobe` / `yt-dlp` 설치가 필요합니다.
+
+더 자세한 매개변수 설명은 [CLI 기능 요약](../zh/cli.md)을 참고하세요.
+
+### Agent Skills
+
+이 저장소는 Agent가 안정적인 규칙으로 CLI를 호출할 수 있도록 `skills/` 아래에 바로 사용할 수 있는 Agent Skills도 제공합니다:
+
+- [`krillinai-cli`](../../skills/krillinai-cli/SKILL.md): 자막, TTS, 렌더링, pipeline 또는 커버 워크플로를 선택하는 최상위 진입 skill입니다.
+- [`krillinai-subtitle`](../../skills/krillinai-subtitle/SKILL.md), [`krillinai-tts`](../../skills/krillinai-tts/SKILL.md), [`krillinai-render-horizontal`](../../skills/krillinai-render-horizontal/SKILL.md), [`krillinai-render-vertical`](../../skills/krillinai-render-vertical/SKILL.md): 단계별 운영 가이드입니다.
+- [`krillinai-pipeline`](../../skills/krillinai-pipeline/SKILL.md) 및 [`krillinai-cover`](../../skills/krillinai-cover/SKILL.md): pipeline 오케스트레이션과 커버 생성을 위한 계획/예약 가이드이며, 해당 실행 경로가 완전히 연결될 때까지 계획 용도로 사용합니다.
+- [`cli-contract.md`](../../skills/krillinai-cli/references/cli-contract.md): JSON, manifest, outputs, 오류 처리에 대한 공통 계약입니다.
+
제공된 구성 파일을 기반으로, README 파일의 "구성 도움말(반드시 읽어야 함)" 섹션을 업데이트한 내용은 다음과 같습니다:
### 구성 도움말 (반드시 읽어야 함)
@@ -215,4 +286,4 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
## 스타 역사
-[![스타 역사 차트](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![스타 역사 차트](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/pt/README.md b/docs/pt/README.md
index 3c5b4918..dc877b63 100644
--- a/docs/pt/README.md
+++ b/docs/pt/README.md
@@ -168,6 +168,68 @@ Este software não está assinado, então ao executá-lo no macOS, após complet
Este projeto suporta implantação com Docker; consulte as [Instruções de Implantação com Docker](./docker.md)
+### Uso da CLI
+
+O KrillinAI agora oferece uma CLI em etapas, adequada para scripts, pipelines de automação e agentes de IA. Por padrão, a CLI executa de forma síncrona, imprime uma linha JSON no stdout ao concluir e grava `krillinai_manifest.json` no diretório de trabalho para que etapas posteriores possam reutilizar artefatos existentes.
+
+Compile a CLI a partir do código-fonte:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+Resumo dos comandos:
+
+| Comando | Uso | Artefatos comuns |
+|---|---|---|
+| `subtitle` | Gera legendas a partir de links do YouTube / Bilibili ou vídeos locais; tenta primeiro baixar legendas da plataforma e recorre ao Whisper se falhar | `origin_language_srt.srt`, `target_language_srt.srt`, `bilingual_srt.srt`, `short_origin_mixed_srt.srt` |
+| `tts` | Gera dublagem no idioma de destino a partir das legendas de destino | `tts_final_audio.wav`, `video_with_tts.mp4` |
+| `render-horizontal` | Gera vídeo horizontal: vídeo original + legendas bilíngues, ou vídeo dublado + legendas no idioma de destino | `horizontal_bilingual.mp4` |
+| `render-vertical` | Gera vídeo vertical: vídeo original convertido para vertical + legendas curtas, ou vídeo dublado + legendas no idioma de destino | `transferred_vertical_video.mp4`, `vertical_bilingual.mp4` |
+| `pipeline` | Encadeia várias etapas de acordo com outputs | Depende das etapas selecionadas |
+| `cover` | Gera uma capa a partir da capa original do vídeo e de um modelo de prompt | `generated_cover.png` |
+
+Fluxo de trabalho típico:
+
+```bash
+# 1. Gerar legendas de origem, destino, bilíngues e curtas para vertical
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. Gerar dublagem a partir das legendas no idioma de destino
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. Gerar vídeo horizontal com legendas bilíngues
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. Gerar vídeo vertical com legendas bilíngues curtas
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "Tema de hoje" \
+ --minor-title "AI Video"
+```
+
+Convenções de integração para Agent:
+
+- Leia primeiro a última linha JSON do stdout e `krillinai_manifest.json`; não analise logs comuns.
+- O campo `outputs` registra os caminhos dos artefatos, e comandos posteriores podem reutilizar o manifest passando apenas `--workdir`.
+- `--dry-run` valida parâmetros e gera o manifest sem baixar vídeo nem chamar serviços externos de IA.
+- Trate erros por `error.kind`: `usage` corrige parâmetros, `retryable` permite tentar novamente, `dependency` exige instalar `ffmpeg` / `ffprobe` / `yt-dlp`.
+
+Para uma explicação mais completa dos parâmetros, consulte o [resumo de capacidades da CLI](../zh/cli.md).
+
Com base no arquivo de configuração fornecido, aqui está a seção atualizada "Ajuda de Configuração (Leitura Obrigatória)" para o seu arquivo README:
### Ajuda de Configuração (Leitura Obrigatória)
@@ -215,4 +277,4 @@ Por favor, visite [Perguntas Frequentes](./faq.md)
## Histórico de Estrelas
-[![Gráfico de Histórico de Estrelas](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![Gráfico de Histórico de Estrelas](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/rus/README.md b/docs/rus/README.md
index 50fba864..ef04afee 100644
--- a/docs/rus/README.md
+++ b/docs/rus/README.md
@@ -168,6 +168,68 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
Этот проект поддерживает развертывание с помощью Docker; пожалуйста, обратитесь к [Инструкциям по развертыванию Docker](./docker.md)
+### Использование CLI
+
+KrillinAI теперь предоставляет поэтапный CLI, удобный для скриптов, автоматизированных пайплайнов и AI Agent. По умолчанию CLI выполняется синхронно, после завершения выводит одну строку JSON в stdout и записывает `krillinai_manifest.json` в рабочий каталог, чтобы последующие этапы могли переиспользовать уже созданные артефакты.
+
+Сборка CLI из исходного кода:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+Обзор команд:
+
+| Команда | Назначение | Основные артефакты |
+|---|---|---|
+| `subtitle` | Создает субтитры из ссылок YouTube / Bilibili или локального видео; сначала пытается скачать субтитры платформы, а при неудаче переходит к транскрибации Whisper | `origin_language_srt.srt`, `target_language_srt.srt`, `bilingual_srt.srt`, `short_origin_mixed_srt.srt` |
+| `tts` | Создает озвучку на целевом языке по целевым субтитрам | `tts_final_audio.wav`, `video_with_tts.mp4` |
+| `render-horizontal` | Создает горизонтальное видео: оригинальное видео + двуязычные субтитры или видео с озвучкой + субтитры на целевом языке | `horizontal_bilingual.mp4` |
+| `render-vertical` | Создает вертикальное видео: оригинальное видео, преобразованное в вертикальный формат + короткие субтитры, или видео с озвучкой + субтитры на целевом языке | `transferred_vertical_video.mp4`, `vertical_bilingual.mp4` |
+| `pipeline` | Связывает несколько этапов согласно outputs | Зависит от выбранных этапов |
+| `cover` | Создает обложку на основе исходной обложки видео и шаблона prompt | `generated_cover.png` |
+
+Типичный рабочий процесс:
+
+```bash
+# 1. Создать исходные, целевые, двуязычные и короткие вертикальные субтитры
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. Создать озвучку по субтитрам целевого языка
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. Создать горизонтальное видео с двуязычными субтитрами
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. Создать вертикальное видео с короткими двуязычными субтитрами
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "Тема дня" \
+ --minor-title "AI Video"
+```
+
+Правила интеграции для Agent:
+
+- Сначала читайте последнюю строку JSON из stdout и `krillinai_manifest.json`; не анализируйте обычные логи.
+- Поле `outputs` хранит пути к артефактам, поэтому последующие команды могут переиспользовать manifest, передав только `--workdir`.
+- `--dry-run` проверяет параметры и создает manifest без загрузки видео и без вызова внешних AI-сервисов.
+- Обрабатывайте ошибки по `error.kind`: `usage` означает исправить параметры, `retryable` означает повторить попытку, `dependency` означает установить `ffmpeg` / `ffprobe` / `yt-dlp`.
+
+Более подробное описание параметров смотрите в [сводке возможностей CLI](../zh/cli.md).
+
На основе предоставленного конфигурационного файла вот обновленный раздел "Помощь по конфигурации (обязательно к прочтению)" для вашего файла README:
### Помощь по конфигурации (обязательно к прочтению)
@@ -215,4 +277,4 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
## История звезд
-[![График истории звезд](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![График истории звезд](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/vi/README.md b/docs/vi/README.md
index db9a7898..5fb4b637 100644
--- a/docs/vi/README.md
+++ b/docs/vi/README.md
@@ -168,6 +168,68 @@ Phần mềm này không được ký, vì vậy khi chạy trên macOS, sau khi
Dự án này hỗ trợ triển khai Docker; vui lòng tham khảo [Hướng Dẫn Triển Khai Docker](./docker.md)
+### Cách dùng CLI
+
+KrillinAI hiện cung cấp CLI theo từng giai đoạn, phù hợp cho script, pipeline tự động hóa và AI Agent. Theo mặc định, CLI chạy đồng bộ, in một dòng JSON ra stdout khi hoàn tất và ghi `krillinai_manifest.json` vào thư mục làm việc để các giai đoạn sau có thể tái sử dụng các sản phẩm đã tạo.
+
+Biên dịch CLI từ mã nguồn:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+Tổng quan lệnh:
+
+| Lệnh | Mục đích | Sản phẩm thường gặp |
+|---|---|---|
+| `subtitle` | Tạo phụ đề từ liên kết YouTube / Bilibili hoặc video cục bộ; ưu tiên tải phụ đề nền tảng, nếu thất bại sẽ dùng Whisper để nhận diện | `origin_language_srt.srt`, `target_language_srt.srt`, `bilingual_srt.srt`, `short_origin_mixed_srt.srt` |
+| `tts` | Tạo lồng tiếng bằng ngôn ngữ đích từ phụ đề đích | `tts_final_audio.wav`, `video_with_tts.mp4` |
+| `render-horizontal` | Tạo video ngang: video gốc + phụ đề song ngữ, hoặc video đã lồng tiếng + phụ đề ngôn ngữ đích | `horizontal_bilingual.mp4` |
+| `render-vertical` | Tạo video dọc: chuyển video gốc sang dọc + phụ đề ngắn, hoặc video đã lồng tiếng + phụ đề ngôn ngữ đích | `transferred_vertical_video.mp4`, `vertical_bilingual.mp4` |
+| `pipeline` | Kết nối nhiều giai đoạn theo outputs | Phụ thuộc vào các giai đoạn được chọn |
+| `cover` | Tạo ảnh bìa từ ảnh bìa video gốc và mẫu prompt | `generated_cover.png` |
+
+Quy trình điển hình:
+
+```bash
+# 1. Tạo phụ đề ngôn ngữ gốc, ngôn ngữ đích, song ngữ và phụ đề ngắn cho video dọc
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. Tạo lồng tiếng từ phụ đề ngôn ngữ đích
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. Tạo video ngang với phụ đề song ngữ
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. Tạo video dọc với phụ đề song ngữ ngắn
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "Chủ đề hôm nay" \
+ --minor-title "AI Video"
+```
+
+Quy ước tích hợp cho Agent:
+
+- Ưu tiên đọc dòng JSON cuối cùng trong stdout và `krillinai_manifest.json`; không phân tích log thông thường.
+- Trường `outputs` ghi lại đường dẫn sản phẩm, các lệnh sau có thể tái sử dụng manifest chỉ bằng cách truyền `--workdir`.
+- `--dry-run` xác thực tham số và tạo manifest mà không tải video hoặc gọi dịch vụ AI bên ngoài.
+- Xử lý lỗi theo `error.kind`: `usage` là sửa tham số, `retryable` là có thể thử lại, `dependency` là cần cài `ffmpeg` / `ffprobe` / `yt-dlp`.
+
+Để biết mô tả tham số đầy đủ hơn, xem [tóm tắt khả năng CLI](../zh/cli.md).
+
Dựa trên tệp cấu hình đã cung cấp, đây là phần "Hỗ Trợ Cấu Hình (Cần Đọc)" đã được cập nhật cho tệp README của bạn:
### Hỗ Trợ Cấu Hình (Cần Đọc)
@@ -215,4 +277,4 @@ Vui lòng truy cập [Câu Hỏi Thường Gặp](./faq.md)
## Lịch Sử Sao
-[![Biểu Đồ Lịch Sử Sao](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
\ No newline at end of file
+[![Biểu Đồ Lịch Sử Sao](https://api.star-history.com/svg?repos=KrillinAI/KlicStudio&type=Date)](https://star-history.com/#KrillinAI/KlicStudio&Date)
diff --git a/docs/zh/README.md b/docs/zh/README.md
index 8d302fd6..f7f0c6d4 100644
--- a/docs/zh/README.md
+++ b/docs/zh/README.md
@@ -170,16 +170,74 @@ sudo chmod +x ./KlicStudio_1.0.0_desktop_macOS_arm64
### CLI 用法
-KrillinAI 提供阶段化 CLI,适合脚本和 Agent 调用。每个命令默认同步执行,完成后输出 JSON。
+KrillinAI 现在提供阶段化 CLI,适合脚本、自动化流水线和 AI Agent 调用。CLI 默认同步执行,完成后在 stdout 输出一行 JSON,并在工作目录写入 `krillinai_manifest.json`,方便后续阶段复用已有产物。
+
+从源码构建 CLI:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+命令总览:
+
+| 命令 | 用途 | 常见产物 |
+|---|---|---|
+| `subtitle` | 从 YouTube / Bilibili 链接或本地视频生成字幕;优先下载平台字幕,失败时回退 Whisper 转录 | `origin_language_srt.srt`、`target_language_srt.srt`、`bilingual_srt.srt`、`short_origin_mixed_srt.srt` |
+| `tts` | 根据目标字幕生成目标语言配音 | `tts_final_audio.wav`、`video_with_tts.mp4` |
+| `render-horizontal` | 生成横屏视频:原视频 + 双语字幕,或配音视频 + 目标语言字幕 | `horizontal_bilingual.mp4` |
+| `render-vertical` | 生成竖屏视频:原视频转竖屏 + 短字幕,或配音视频 + 目标语言字幕 | `transferred_vertical_video.mp4`、`vertical_bilingual.mp4` |
+| `pipeline` | 按 outputs 串联多个阶段 | 由所选阶段决定 |
+| `cover` | 根据原视频封面和提示词模板生成封面 | `generated_cover.png` |
+
+典型工作流:
```bash
-krillinai subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" --origin-lang en --target-lang zh_cn --workdir tasks/demo
-krillinai tts --workdir tasks/demo --input-srt tasks/demo/target_language_srt.srt --line-mode target-only
-krillinai render-horizontal --workdir tasks/demo --video tasks/demo/origin_video.mp4 --subtitle tasks/demo/bilingual_srt.srt
-krillinai render-vertical --workdir tasks/demo --video tasks/demo/origin_video.mp4 --subtitle tasks/demo/short_origin_mixed_srt.srt
+# 1. 生成字幕:源语言、目标语言、双语字幕、竖屏短字幕
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=dQw4w9WgXcQ" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+# 2. 根据目标语言字幕生成配音
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+
+# 3. 生成横屏双语字幕视频
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+
+# 4. 生成竖屏双语短字幕视频
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "今日话题" \
+ --minor-title "AI Video"
```
-Agent 应优先读取 stdout JSON 和 `krillinai_manifest.json`,不要解析普通日志。
+Agent 集成约定:
+
+- 优先解析 stdout 最后一行 JSON 和 `krillinai_manifest.json`,不要解析普通日志。
+- `outputs` 字段会记录阶段产物路径,后续命令可以只传 `--workdir` 复用 manifest。
+- 支持 `--dry-run` 校验参数并生成 manifest,不会下载视频或调用外部 AI 服务。
+- 根据 `error.kind` 处理错误:`usage` 修正参数,`retryable` 可重试,`dependency` 需要安装 `ffmpeg` / `ffprobe` / `yt-dlp`。
+
+更完整的参数说明请参考 [CLI 能力总结](./cli.md)。
+
+### Agent Skills
+
+仓库还在 `skills/` 目录下提供了可直接给 Agent 使用的 Skills,用于按稳定约定调用 CLI:
+
+- [`krillinai-cli`](../../skills/krillinai-cli/SKILL.md):总入口 skill,用于选择字幕、TTS、渲染、pipeline 或封面工作流。
+- [`krillinai-subtitle`](../../skills/krillinai-subtitle/SKILL.md)、[`krillinai-tts`](../../skills/krillinai-tts/SKILL.md)、[`krillinai-render-horizontal`](../../skills/krillinai-render-horizontal/SKILL.md)、[`krillinai-render-vertical`](../../skills/krillinai-render-vertical/SKILL.md):各阶段的调用指南。
+- [`krillinai-pipeline`](../../skills/krillinai-pipeline/SKILL.md) 和 [`krillinai-cover`](../../skills/krillinai-cover/SKILL.md):pipeline 编排和封面生成的规划/预留指南,等对应执行路径完全接通后再用于真实执行。
+- [`cli-contract.md`](../../skills/krillinai-cli/references/cli-contract.md):共享的 JSON、manifest、产物路径和错误处理约定。
根据提供的配置文件,以下是您 README 文件中更新的“配置帮助(必读)”部分:
diff --git a/go.mod b/go.mod
index 72049de2..b95a3400 100644
--- a/go.mod
+++ b/go.mod
@@ -8,6 +8,7 @@ require (
github.com/aliyun/alibaba-cloud-sdk-go v1.63.72
github.com/aliyun/alibabacloud-oss-go-sdk-v2 v1.1.3
github.com/gin-gonic/gin v1.10.0
+ github.com/go-ego/gse v1.0.2
github.com/go-resty/resty/v2 v2.7.0
github.com/google/uuid v1.4.0
github.com/gorilla/websocket v1.5.0
@@ -64,6 +65,7 @@ require (
github.com/stretchr/testify v1.9.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
+ github.com/vcaesar/cedar v0.30.0 // indirect
github.com/yuin/goldmark v1.7.1 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
diff --git a/go.sum b/go.sum
index 99d51ab4..e128c07c 100644
--- a/go.sum
+++ b/go.sum
@@ -111,6 +111,8 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
+github.com/go-ego/gse v1.0.2 h1:+27lYFPhQEhA9igtdOsJPRKYL/k3TwYsxBF5jr6KFv4=
+github.com/go-ego/gse v1.0.2/go.mod h1:Fy35G+q7VV7Et1zIKO8o/sW1kkugV3znXap/lF/11zc=
github.com/go-gl/gl v0.0.0-20211210172815-726fda9656d6 h1:zDw5v7qm4yH7N8C8uWd+8Ii9rROdgWxQuGoJ9WDXxfk=
github.com/go-gl/gl v0.0.0-20211210172815-726fda9656d6/go.mod h1:9YTyiznxEY1fVinfM7RvRcjRHbw2xLBJ3AAGIT0I4Nw=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
@@ -374,6 +376,10 @@ github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVK
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
+github.com/vcaesar/cedar v0.30.0 h1:9fSDpM7FTjjUdPiBUUa0MWYMRGSEcqgFXvppZcZ4d7Y=
+github.com/vcaesar/cedar v0.30.0/go.mod h1:lyuGvALuZZDPNXwpzv/9LyxW+8Y6faN7zauFezNsnik=
+github.com/vcaesar/tt v0.20.1 h1:D/jUeeVCNbq3ad8M7hhtB3J9x5RZ6I1n1eZ0BJp7M+4=
+github.com/vcaesar/tt v0.20.1/go.mod h1:cH2+AwGAJm19Wa6xvEa+0r+sXDJBT0QgNQey6mwqLeU=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
diff --git a/internal/cli/commands.go b/internal/cli/commands.go
index efa5b616..56790d63 100644
--- a/internal/cli/commands.go
+++ b/internal/cli/commands.go
@@ -13,6 +13,7 @@ import (
type Command struct {
Name string
+ Help bool
DryRun bool
Subtitle pipeline.SubtitleRequest
TTS pipeline.TTSRequest
@@ -25,6 +26,9 @@ func Parse(args []string) (Command, error) {
return Command{}, errors.New("missing command")
}
name := args[0]
+ if isHelpArg(name) {
+ return Command{Help: true}, nil
+ }
switch name {
case "subtitle":
return parseSubtitle(name, args[1:])
@@ -37,12 +41,118 @@ func Parse(args []string) (Command, error) {
case "pipeline":
return parsePipeline(name, args[1:])
case "cover", "status":
+ if hasHelpArg(args[1:]) {
+ return Command{Name: name, Help: true}, nil
+ }
return Command{Name: name}, nil
default:
return Command{}, fmt.Errorf("unknown command: %s", name)
}
}
+func Help(cmd Command) string {
+ switch cmd.Name {
+ case "subtitle":
+ return `Usage:
+ krillinai-cli subtitle <input> --origin-lang <lang> --target-lang <lang> --workdir <dir> [flags]
+
+Flags:
+ --origin-lang <lang> Source language, such as en, zh, ja
+ --target-lang <lang> Target language, such as zh_cn
+ --user-lang <lang> UI language for generated messages
+ --workdir <dir> Task working directory
+ --task-id <id> Optional task id
+ --caption-source <source> any, manual, auto, or whisper
+ --bilingual-top Put target subtitle on top (default true)
+ --max-word-one-line <n> Max words per subtitle line
+ --dry-run Validate and write manifest without external calls
+ -h, --help Show this help
+`
+ case "tts":
+ return `Usage:
+ krillinai-cli tts --workdir <dir> --input-srt <file> [flags]
+
+Flags:
+ --workdir <dir> Task working directory
+ --task-id <id> Optional task id
+ --input-srt <file> SRT file to synthesize
+ --line-mode <mode> target-only, bilingual-target-top, or bilingual-target-bottom
+ --video <file> Optional source video for dubbed output
+ --voice <voice> Provider-specific voice
+ --voice-clone-source <source> Optional voice clone source
+ --dry-run Validate and write manifest without external calls
+ -h, --help Show this help
+`
+ case "render-horizontal":
+ return `Usage:
+ krillinai-cli render-horizontal --workdir <dir> --video <file> --subtitle <file> [flags]
+
+Flags:
+ --workdir <dir> Task working directory
+ --task-id <id> Optional task id
+ --video <file> Input video
+ --audio <file> Optional input audio
+ --subtitle <file> Subtitle file to burn in
+ --dubbed Render dubbed variant
+ --dry-run Validate and write manifest without external calls
+ -h, --help Show this help
+`
+ case "render-vertical":
+ return `Usage:
+ krillinai-cli render-vertical --workdir <dir> --video <file> --subtitle <file> [flags]
+
+Flags:
+ --workdir <dir> Task working directory
+ --task-id <id> Optional task id
+ --video <file> Input video
+ --audio <file> Optional input audio
+ --subtitle <file> Subtitle file to burn in
+ --dubbed Render dubbed variant
+ --major-title <text> Vertical video major title
+ --minor-title <text> Vertical video minor title
+ --dry-run Validate and write manifest without external calls
+ -h, --help Show this help
+`
+ case "pipeline":
+ return `Usage:
+ krillinai-cli pipeline --outputs <list> [flags]
+
+Flags:
+ --outputs <list> Comma-separated outputs, such as subtitle,tts,vertical-bilingual
+ --async Run asynchronously when supported
+ --dry-run Validate requested outputs
+ -h, --help Show this help
+`
+ case "cover":
+ return `Usage:
+ krillinai-cli cover
+
+Cover generation is a reserved/planned CLI surface in the current implementation.
+`
+ case "status":
+ return `Usage:
+ krillinai-cli status
+
+Status query is a reserved/planned CLI surface in the current implementation.
+`
+ default:
+ return `Usage:
+ krillinai-cli <command> [flags]
+
+Commands:
+ subtitle Generate source, target, bilingual, and short vertical subtitles
+ tts Generate target-language dubbing from SRT subtitles
+ render-horizontal Render landscape subtitle or dubbed videos
+ render-vertical Render portrait subtitle or dubbed videos
+ pipeline Plan or run multi-stage workflows when supported
+ cover Reserved cover generation surface
+ status Reserved status query surface
+
+Run "krillinai-cli <command> --help" for command-specific flags.
+`
+ }
+}
+
func Execute(ctx context.Context, svc pipeline.StageService, cmd Command) pipeline.Response {
if cmd.DryRun {
return dryRun(cmd)
@@ -70,6 +180,9 @@ func Execute(ctx context.Context, svc pipeline.StageService, cmd Command) pipeli
}
func parseSubtitle(name string, args []string) (Command, error) {
+ if hasHelpArg(args) {
+ return Command{Name: name, Help: true}, nil
+ }
fs := newFlagSet(name)
originLang := fs.String("origin-lang", "", "origin language")
targetLang := fs.String("target-lang", "", "target language")
@@ -77,7 +190,7 @@ func parseSubtitle(name string, args []string) (Command, error) {
workdir := fs.String("workdir", "", "workdir")
taskID := fs.String("task-id", "", "task id")
captionSource := fs.String("caption-source", string(pipeline.CaptionSourceAny), "caption source")
- bilingualTop := fs.Bool("bilingual-top", false, "put target subtitle on top")
+ bilingualTop := fs.Bool("bilingual-top", true, "put target subtitle on top")
maxWordOneLine := fs.Int("max-word-one-line", 0, "max words per line")
dryRun := fs.Bool("dry-run", false, "validate command without running external services")
input := ""
@@ -113,6 +226,9 @@ func parseSubtitle(name string, args []string) (Command, error) {
}
func parseTTS(name string, args []string) (Command, error) {
+ if hasHelpArg(args) {
+ return Command{Name: name, Help: true}, nil
+ }
fs := newFlagSet(name)
workdir := fs.String("workdir", "", "workdir")
taskID := fs.String("task-id", "", "task id")
@@ -144,6 +260,9 @@ func parseTTS(name string, args []string) (Command, error) {
}
func parseRender(name string, args []string, horizontal bool) (Command, error) {
+ if hasHelpArg(args) {
+ return Command{Name: name, Help: true}, nil
+ }
fs := newFlagSet(name)
workdir := fs.String("workdir", "", "workdir")
taskID := fs.String("task-id", "", "task id")
@@ -175,6 +294,9 @@ func parseRender(name string, args []string, horizontal bool) (Command, error) {
}
func parsePipeline(name string, args []string) (Command, error) {
+ if hasHelpArg(args) {
+ return Command{Name: name, Help: true}, nil
+ }
fs := newFlagSet(name)
outputs := fs.String("outputs", "subtitle", "outputs")
async := fs.Bool("async", false, "run async")
@@ -268,6 +390,19 @@ func newFlagSet(name string) *flag.FlagSet {
return fs
}
+func hasHelpArg(args []string) bool {
+ for _, arg := range args {
+ if isHelpArg(arg) {
+ return true
+ }
+ }
+ return false
+}
+
+func isHelpArg(arg string) bool {
+ return arg == "-h" || arg == "--help" || arg == "help"
+}
+
func responseWithError(resp pipeline.Response, err error) pipeline.Response {
if err == nil {
return resp
diff --git a/internal/cli/commands_test.go b/internal/cli/commands_test.go
index 717092da..66f2dcbb 100644
--- a/internal/cli/commands_test.go
+++ b/internal/cli/commands_test.go
@@ -3,6 +3,7 @@ package cli
import (
"context"
"krillin-ai/internal/pipeline"
+ "strings"
"testing"
)
@@ -27,6 +28,26 @@ func TestParseSubtitleCommand(t *testing.T) {
if cmd.Subtitle.Workdir != "tasks/demo" {
t.Fatalf("Workdir = %q", cmd.Subtitle.Workdir)
}
+ if !cmd.Subtitle.BilingualTop {
+ t.Fatalf("BilingualTop = false, want true by default")
+ }
+}
+
+func TestParseSubtitleCommandCanPutTargetLanguageOnBottom(t *testing.T) {
+ cmd, err := Parse([]string{
+ "subtitle",
+ "https://www.youtube.com/watch?v=abc",
+ "--origin-lang", "en",
+ "--target-lang", "zh_cn",
+ "--workdir", "tasks/demo",
+ "--bilingual-top=false",
+ })
+ if err != nil {
+ t.Fatalf("Parse() error = %v", err)
+ }
+ if cmd.Subtitle.BilingualTop {
+ t.Fatalf("BilingualTop = true, want false when explicitly disabled")
+ }
}
func TestParseTTSCommandRequiresInputSRT(t *testing.T) {
@@ -36,6 +57,48 @@ func TestParseTTSCommandRequiresInputSRT(t *testing.T) {
}
}
+func TestParseRootHelp(t *testing.T) {
+ cmd, err := Parse([]string{"--help"})
+ if err != nil {
+ t.Fatalf("Parse() error = %v", err)
+ }
+ if !cmd.Help || cmd.Name != "" {
+ t.Fatalf("Command = %#v, want root help", cmd)
+ }
+ help := Help(cmd)
+ if !strings.Contains(help, "Usage:") || !strings.Contains(help, "subtitle") {
+ t.Fatalf("Help() = %q, want root usage with commands", help)
+ }
+}
+
+func TestParseSubcommandHelp(t *testing.T) {
+ cmd, err := Parse([]string{"subtitle", "--help"})
+ if err != nil {
+ t.Fatalf("Parse() error = %v", err)
+ }
+ if !cmd.Help || cmd.Name != "subtitle" {
+ t.Fatalf("Command = %#v, want subtitle help", cmd)
+ }
+ help := Help(cmd)
+ if !strings.Contains(help, "Usage:") || !strings.Contains(help, "--origin-lang") {
+ t.Fatalf("Help() = %q, want subtitle usage with flags", help)
+ }
+}
+
+func TestParseReservedCommandHelp(t *testing.T) {
+ cmd, err := Parse([]string{"cover", "--help"})
+ if err != nil {
+ t.Fatalf("Parse() error = %v", err)
+ }
+ if !cmd.Help || cmd.Name != "cover" {
+ t.Fatalf("Command = %#v, want cover help", cmd)
+ }
+ help := Help(cmd)
+ if !strings.Contains(help, "reserved/planned") {
+ t.Fatalf("Help() = %q, want reserved command notice", help)
+ }
+}
+
func TestExecuteDryRunSubtitleReturnsJSONReadyResponse(t *testing.T) {
cmd, err := Parse([]string{
"subtitle",
diff --git a/internal/pipeline/subtitle.go b/internal/pipeline/subtitle.go
index 2779448b..e6fd450c 100644
--- a/internal/pipeline/subtitle.go
+++ b/internal/pipeline/subtitle.go
@@ -56,6 +56,9 @@ func GenerateSubtitles(ctx context.Context, svc StageService, req SubtitleReques
}
if err == nil {
manifest.CaptionSource = "youtube_vtt"
+ if err := prepareOriginalMediaForRendering(ctx, svc, stepParam); err != nil {
+ return failSubtitleStage(req, manifest, ErrorKindRetryable, "prepare_media_for_render_failed", err)
+ }
return saveSubtitleSuccess(manifest, req, CaptionSource("youtube_vtt"))
}
if req.CaptionSource != CaptionSourceAny {
@@ -120,6 +123,12 @@ func subtitleStepParam(req SubtitleRequest) *types.SubtitleTaskStepParam {
}
}
+func prepareOriginalMediaForRendering(ctx context.Context, svc StageService, stepParam *types.SubtitleTaskStepParam) error {
+ stepParam.VttSwitch = false
+ stepParam.EmbedSubtitleVideoType = "all"
+ return svc.PrepareMedia(ctx, stepParam)
+}
+
func subtitleYouTubeReq(req SubtitleRequest, taskPtr *types.SubtitleTask) *service.YoutubeSubtitleReq {
return &service.YoutubeSubtitleReq{
TaskBasePath: req.Workdir,
diff --git a/internal/pipeline/subtitle_test.go b/internal/pipeline/subtitle_test.go
index fde5b363..718fbc21 100644
--- a/internal/pipeline/subtitle_test.go
+++ b/internal/pipeline/subtitle_test.go
@@ -9,16 +9,18 @@ import (
)
type fakeStageService struct {
- downloadErr error
- processErr error
- calls []string
- prepareVTT []bool
- lastSpeech *types.SubtitleTaskStepParam
+ downloadErr error
+ processErr error
+ calls []string
+ prepareVTT []bool
+ prepareEmbedTypes []string
+ lastSpeech *types.SubtitleTaskStepParam
}
func (f *fakeStageService) PrepareMedia(_ context.Context, p *types.SubtitleTaskStepParam) error {
f.calls = append(f.calls, "prepare")
f.prepareVTT = append(f.prepareVTT, p.VttSwitch)
+ f.prepareEmbedTypes = append(f.prepareEmbedTypes, p.EmbedSubtitleVideoType)
return nil
}
@@ -121,9 +123,43 @@ func TestGenerateSubtitlesYouTubeCaptionsDoNotUseAudio(t *testing.T) {
if resp.CaptionSource == "" {
t.Fatalf("CaptionSource is empty")
}
- if got := fake.calls; len(got) != 3 || got[0] != "prepare" || got[1] != "download-youtube" || got[2] != "process-youtube" {
+ if got := fake.calls; len(got) != 4 || got[0] != "prepare" || got[1] != "download-youtube" || got[2] != "process-youtube" || got[3] != "prepare" {
t.Fatalf("calls = %v", got)
}
+ for _, call := range fake.calls {
+ if call == "audio" {
+ t.Fatalf("calls = %v, did not expect audio transcription", fake.calls)
+ }
+ }
+}
+
+func TestGenerateSubtitlesYouTubeCaptionsPrepareOriginalMediaForRendering(t *testing.T) {
+ dir := t.TempDir()
+ fake := &fakeStageService{}
+ req := SubtitleRequest{
+ Input: "https://www.youtube.com/watch?v=abc",
+ Workdir: dir,
+ TaskID: "demo",
+ OriginLang: "en",
+ TargetLang: "zh_cn",
+ CaptionSource: CaptionSourceAny,
+ }
+ resp, err := GenerateSubtitles(context.Background(), fake, req)
+ if err != nil {
+ t.Fatalf("GenerateSubtitles() error = %v", err)
+ }
+ if !resp.OK {
+ t.Fatalf("OK = false, want true")
+ }
+ if got := fake.calls; len(got) != 4 || got[0] != "prepare" || got[1] != "download-youtube" || got[2] != "process-youtube" || got[3] != "prepare" {
+ t.Fatalf("calls = %v", got)
+ }
+ if got := fake.prepareVTT; len(got) != 2 || got[0] != true || got[1] != false {
+ t.Fatalf("prepare VttSwitch values = %v, want [true false]", got)
+ }
+ if got := fake.prepareEmbedTypes; len(got) != 2 || got[1] != "all" {
+ t.Fatalf("prepare EmbedSubtitleVideoType values = %v, want second value all", got)
+ }
}
func TestGenerateSubtitlesWhisperSkipsYouTubeDownload(t *testing.T) {
diff --git a/internal/service/render_stage.go b/internal/service/render_stage.go
index 92afd7d0..02982bf0 100644
--- a/internal/service/render_stage.go
+++ b/internal/service/render_stage.go
@@ -60,10 +60,22 @@ func renderSubtitleFile(ctx context.Context, req RenderVideoRequest) (string, er
stepParam := req.StepParam
if stepParam == nil {
stepParam = &types.SubtitleTaskStepParam{TaskBasePath: req.Workdir}
+ req.StepParam = stepParam
}
if err := srtToAss(req.SubtitleFile, assPath, req.Horizontal, stepParam); err != nil {
return "", fmt.Errorf("renderSubtitleFile srtToAss error: %w", err)
}
+ if !req.Horizontal {
+ width, height, err := getResolution(req.InputVideo)
+ if err != nil {
+ return "", fmt.Errorf("renderSubtitleFile getResolution error: %w", err)
+ }
+ inputVideo, err := prepareRenderVideoInput(req, width, height, convertToVertical)
+ if err != nil {
+ return "", fmt.Errorf("renderSubtitleFile prepare vertical input error: %w", err)
+ }
+ req.InputVideo = inputVideo
+ }
args, _ := buildEmbedSubtitleArgs(req)
cmd := exec.CommandContext(ctx, storage.FfmpegPath, args...)
output, err := cmd.CombinedOutput()
@@ -72,3 +84,24 @@ func renderSubtitleFile(ctx context.Context, req RenderVideoRequest) (string, er
}
return req.OutputFile, nil
}
+
+type verticalConverter func(inputVideo, outputVideo, majorTitle, minorTitle string) error
+
+func prepareRenderVideoInput(req RenderVideoRequest, width, height int, convert verticalConverter) (string, error) {
+ if req.Horizontal || width <= height {
+ return req.InputVideo, nil
+ }
+ majorTitle, minorTitle := "", ""
+ if req.StepParam != nil {
+ majorTitle = req.StepParam.VerticalVideoMajorTitle
+ minorTitle = req.StepParam.VerticalVideoMinorTitle
+ }
+ output := filepath.Join(req.Workdir, types.SubtitleTaskTransferredVerticalVideoFileName)
+ if err := convert(req.InputVideo, output, majorTitle, minorTitle); err != nil {
+ return "", err
+ }
+ if req.StepParam != nil {
+ req.StepParam.InputVideoPath = output
+ }
+ return output, nil
+}
diff --git a/internal/service/render_stage_test.go b/internal/service/render_stage_test.go
index 4ffc89b5..5875f404 100644
--- a/internal/service/render_stage_test.go
+++ b/internal/service/render_stage_test.go
@@ -1,6 +1,7 @@
package service
import (
+ "krillin-ai/internal/types"
"path/filepath"
"strings"
"testing"
@@ -50,3 +51,76 @@ func TestEscapeAssFilterPathEscapesWindowsDriveAndSeparators(t *testing.T) {
t.Fatalf("escapeAssFilterPath() = %q, want %q", got, want)
}
}
+
+func TestPrepareRenderVideoInputConvertsHorizontalVerticalRequest(t *testing.T) {
+ workdir := filepath.Join("tasks", "demo")
+ req := RenderVideoRequest{
+ Workdir: workdir,
+ InputVideo: filepath.Join(workdir, "origin_video.mp4"),
+ Horizontal: false,
+ StepParam: &types.SubtitleTaskStepParam{
+ TaskBasePath: workdir,
+ },
+ }
+
+ got, err := prepareRenderVideoInput(req, 1280, 720, func(input, output, majorTitle, minorTitle string) error {
+ if input != req.InputVideo {
+ t.Fatalf("convert input = %q, want %q", input, req.InputVideo)
+ }
+ wantOutput := filepath.Join(workdir, types.SubtitleTaskTransferredVerticalVideoFileName)
+ if output != wantOutput {
+ t.Fatalf("convert output = %q, want %q", output, wantOutput)
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("prepareRenderVideoInput() error = %v", err)
+ }
+ want := filepath.Join(workdir, types.SubtitleTaskTransferredVerticalVideoFileName)
+ if got != want {
+ t.Fatalf("prepareRenderVideoInput() = %q, want %q", got, want)
+ }
+ if req.StepParam.InputVideoPath != want {
+ t.Fatalf("StepParam.InputVideoPath = %q, want %q", req.StepParam.InputVideoPath, want)
+ }
+}
+
+func TestGetFontPathsUsesChineseCapableFontsOnDarwin(t *testing.T) {
+ bold, regular, err := fontPathsForOS("darwin", func(path string) bool {
+ return strings.Contains(path, "Hiragino Sans GB")
+ })
+ if err != nil {
+ t.Fatalf("fontPathsForOS() error = %v", err)
+ }
+ if !strings.Contains(bold, "Arial Unicode") && !strings.Contains(bold, "Hiragino") && !strings.Contains(bold, "Heiti") {
+ t.Fatalf("bold font %q does not look Chinese-capable", bold)
+ }
+ if !strings.Contains(regular, "Arial Unicode") && !strings.Contains(regular, "Hiragino") && !strings.Contains(regular, "Heiti") {
+ t.Fatalf("regular font %q does not look Chinese-capable", regular)
+ }
+}
+
+func TestGetFontPathsUsesChineseCapableFontsOnWindows(t *testing.T) {
+ bold, regular, err := fontPathsForOS("windows", func(path string) bool {
+ return strings.Contains(path, "msyh")
+ })
+ if err != nil {
+ t.Fatalf("fontPathsForOS() error = %v", err)
+ }
+ if !strings.Contains(bold, "msyh") || !strings.Contains(regular, "msyh") {
+ t.Fatalf("windows fonts = %q, %q; want Microsoft YaHei candidates", bold, regular)
+ }
+}
+
+func TestBuildVerticalFilterEscapesTitleTextAndUsesCompactHeader(t *testing.T) {
+ filter := buildVerticalFilter("CLI 集成测试: A's", "副标题", "/fonts/chinese.ttf", "/fonts/chinese.ttf")
+ if !strings.Contains(filter, "drawbox=y=0:h=250") {
+ t.Fatalf("filter should use compact 250px title header: %s", filter)
+ }
+ if !strings.Contains(filter, "fontsize=44") {
+ t.Fatalf("filter should use smaller title font size: %s", filter)
+ }
+ if !strings.Contains(filter, `CLI 集成测试\: A\\'s`) {
+ t.Fatalf("filter did not escape title text safely: %s", filter)
+ }
+}
diff --git a/internal/service/srt_embed.go b/internal/service/srt_embed.go
index b7339be6..47051e17 100644
--- a/internal/service/srt_embed.go
+++ b/internal/service/srt_embed.go
@@ -4,11 +4,13 @@ import (
"bufio"
"bytes"
"context"
+ "errors"
"fmt"
"krillin-ai/internal/storage"
"krillin-ai/internal/types"
"krillin-ai/log"
"krillin-ai/pkg/util"
+ "math"
"os"
"os/exec"
"path/filepath"
@@ -16,11 +18,21 @@ import (
"runtime"
"strconv"
"strings"
+ "sync"
"time"
+ "github.com/go-ego/gse"
"go.uber.org/zap"
)
+var (
+ chineseSegmenterOnce sync.Once
+ chineseSegmenter gse.Segmenter
+ chineseSegmenterErr error
+)
+
+const verticalChineseMaxRunesPerLine = 18
+
func (s Service) embedSubtitles(ctx context.Context, stepParam *types.SubtitleTaskStepParam) error {
var err error
if stepParam.EmbedSubtitleVideoType == "horizontal" || stepParam.EmbedSubtitleVideoType == "vertical" || stepParam.EmbedSubtitleVideoType == "all" {
@@ -115,18 +127,207 @@ func splitMajorTextInHorizontal(text string, language types.StandardLanguageCode
}
func splitChineseText(text string, maxWordLine int) []string {
+ text = util.CleanPunction(strings.TrimSpace(text))
+ if text == "" {
+ return nil
+ }
+ maxWidthPerLine := maxWordLine * 2
+ if maxWordLine <= 0 || subtitleTextDisplayWidth(text) <= maxWidthPerLine {
+ return []string{text}
+ }
+ if tokens := segmentChineseText(text); len(tokens) > 0 {
+ return splitChineseTokens(tokens, maxWordLine)
+ }
+ return splitChineseTextByRune([]rune(text), maxWordLine)
+}
+
+func splitChineseTextByRune(runes []rune, maxWordLine int) []string {
+ tokens := make([]string, 0, len(runes))
+ for _, r := range runes {
+ tokens = append(tokens, string(r))
+ }
+ return splitChineseSegmentsByDisplayWidth(tokens, maxWordLine)
+}
+
+func segmentChineseText(text string) []string {
+ chineseSegmenterOnce.Do(func() {
+ chineseSegmenter, chineseSegmenterErr = gse.NewEmbed("zh")
+ })
+ if chineseSegmenterErr != nil {
+ log.GetLogger().Warn("中文分词器初始化失败,回退到字符断句", zap.Error(chineseSegmenterErr))
+ return nil
+ }
+ return normalizeChineseTokens(chineseSegmenter.Cut(text, true))
+}
+
+func normalizeChineseTokens(tokens []string) []string {
+ result := make([]string, 0, len(tokens))
+ for _, token := range tokens {
+ token = strings.TrimSpace(token)
+ if token == "" {
+ continue
+ }
+ result = append(result, token)
+ }
+ return result
+}
+
+func splitChineseTokens(tokens []string, maxWordLine int) []string {
+ return splitChineseSegmentsByDisplayWidth(tokens, maxWordLine)
+}
+
+func splitChineseSegmentsByDisplayWidth(segments []string, maxWordLine int) []string {
+ maxWidthPerLine := maxWordLine * 2
+ totalWidth := 0
+ for _, segment := range segments {
+ totalWidth += subtitleTextDisplayWidth(segment)
+ }
+ if totalWidth <= maxWidthPerLine {
+ return []string{util.CleanPunction(strings.Join(segments, ""))}
+ }
+
+ numLines := int(math.Ceil(float64(totalWidth) / float64(maxWidthPerLine)))
+ if numLines < 1 {
+ numLines = 1
+ }
+ widthPerLine := totalWidth / numLines
+ if widthPerLine < 1 {
+ widthPerLine = maxWidthPerLine
+ }
+
var lines []string
- words := []rune(text)
- for i := 0; i < len(words); i += maxWordLine {
- end := i + maxWordLine
- if end > len(words) {
- end = len(words)
+ var current strings.Builder
+ currentWidth := 0
+
+ for _, segment := range segments {
+ segmentWidth := subtitleTextDisplayWidth(segment)
+ if !isTrailingSubtitlePunctuation(segment) &&
+ currentWidth > 0 &&
+ currentWidth+segmentWidth > widthPerLine &&
+ len(lines) < numLines-1 {
+ lines = append(lines, util.CleanPunction(current.String()))
+ current.Reset()
+ currentWidth = 0
+ }
+ current.WriteString(segment)
+ currentWidth += segmentWidth
+ }
+
+ if current.Len() > 0 {
+ lines = append(lines, util.CleanPunction(current.String()))
+ }
+ return rebalanceShortChineseTrailingLine(lines)
+}
+
+func subtitleTextDisplayWidth(text string) int {
+ width := 0
+ for _, r := range text {
+ if r >= '\u4e00' && r <= '\u9fff' {
+ width += 2
+ } else {
+ width++
+ }
+ }
+ return width
+}
+
+func isTrailingSubtitlePunctuation(segment string) bool {
+ for _, r := range segment {
+ if !strings.ContainsRune(",,.。!?”\"》", r) {
+ return false
}
- lines = append(lines, string(words[i:end]))
}
+ return segment != ""
+}
+
+func rebalanceShortChineseTrailingLine(lines []string) []string {
+ if len(lines) < 2 {
+ return lines
+ }
+
+ last := []rune(lines[len(lines)-1])
+ if len(last) == 0 || len(last) > 3 {
+ return lines
+ }
+
+ prevIndex := len(lines) - 2
+ prev := []rune(lines[prevIndex])
+ totalLen := len(prev) + len(last)
+ if totalLen < 6 {
+ return lines
+ }
+
+ combined := append(append([]rune{}, prev...), last...)
+ splitAt := bestChineseSplitIndex(combined, totalLen/2)
+ lines[prevIndex] = string(combined[:splitAt])
+ lines[len(lines)-1] = string(combined[splitAt:])
return lines
}
+func bestChineseSplitIndex(runes []rune, maxWordLine int) int {
+ if len(runes) <= maxWordLine {
+ return len(runes)
+ }
+ minSplit := maxWordLine * 3 / 5
+ if minSplit < 1 {
+ minSplit = 1
+ }
+ best := maxWordLine
+ for i := maxWordLine; i >= minSplit; i-- {
+ if isPreferredChineseBreak(runes, i) {
+ return i
+ }
+ }
+ for hasAwkwardChineseBreak(runes, best) && best > minSplit {
+ best--
+ }
+ return best
+}
+
+func isPreferredChineseBreak(runes []rune, index int) bool {
+ if index <= 0 || index >= len(runes) {
+ return false
+ }
+ prev := runes[index-1]
+ next := runes[index]
+ if strings.ContainsRune(",。!?;:、,.!?;:", prev) {
+ return true
+ }
+ if strings.ContainsRune("的了着过呢吗吧啊呀和与或但而就都也", prev) {
+ return true
+ }
+ if strings.ContainsRune(",。!?;:、,.!?;:", next) {
+ return false
+ }
+ return false
+}
+
+func hasAwkwardChineseBreak(runes []rune, index int) bool {
+ if index <= 0 || index >= len(runes) {
+ return false
+ }
+ pair := string([]rune{runes[index-1], runes[index]})
+ if isProtectedChinesePair(pair) {
+ return true
+ }
+ if index >= 2 {
+ triple := string([]rune{runes[index-2], runes[index-1], runes[index]})
+ if triple == "每一小" {
+ return true
+ }
+ }
+ return false
+}
+
+func isProtectedChinesePair(pair string) bool {
+ switch pair {
+ case "小时", "分钟", "秒钟", "今天", "明天", "自己", "人生", "目标", "规则", "注意", "未来", "屏幕":
+ return true
+ default:
+ return false
+ }
+}
+
func parseSrtTime(timeStr string) (time.Duration, error) {
timeStr = strings.Replace(timeStr, ",", ".", 1)
parts := strings.Split(timeStr, ":")
@@ -278,22 +479,20 @@ func srtToAss(inputSRT, outputASS string, isHorizontal bool, stepParam *types.Su
if content == "" {
continue
}
- totalTime := endTime - startTime
if !util.ContainsAlphabetic(content) {
// 处理中文字幕
- chineseLines := splitChineseText(content, 10)
+ chineseLines := splitChineseText(content, verticalChineseMaxRunesPerLine)
+ totalTime := endTime - startTime
for i, line := range chineseLines {
iStart := startTime + time.Duration(float64(i)*float64(totalTime)/float64(len(chineseLines)))
iEnd := startTime + time.Duration(float64(i+1)*float64(totalTime)/float64(len(chineseLines)))
if iEnd > endTime {
iEnd = endTime
}
-
startFormatted := formatTimestamp(iStart)
endFormatted := formatTimestamp(iEnd)
- cleanedText := util.CleanPunction(line)
- combinedText := fmt.Sprintf("{\\an2}{\\rMajor}%s", cleanedText)
+ combinedText := fmt.Sprintf("{\\an2}{\\rMajor}%s", line)
_, _ = assFile.WriteString(fmt.Sprintf("Dialogue: 0,%s,%s,Major,,0,0,0,,%s\n", startFormatted, endFormatted, combinedText))
}
} else {
@@ -331,16 +530,70 @@ func embedSubtitles(stepParam *types.SubtitleTaskStepParam, isHorizontal bool, w
}
func getFontPaths() (string, string, error) {
- switch runtime.GOOS {
+ return fontPathsForOS(runtime.GOOS, pathExists)
+}
+
+func fontPathsForOS(goos string, exists func(string) bool) (string, string, error) {
+ if exists == nil {
+ exists = pathExists
+ }
+ candidates, err := fontCandidatesForOS(goos)
+ if err != nil {
+ return "", "", err
+ }
+ return chooseFontPair(candidates, exists)
+}
+
+type fontPair struct {
+ bold string
+ regular string
+}
+
+func fontCandidatesForOS(goos string) ([]fontPair, error) {
+ switch goos {
case "windows":
- return "C\\:/Windows/Fonts/msyhbd.ttc", "C\\:/Windows/Fonts/msyh.ttc", nil // 在ffmpeg参数里必须这样写
+ return []fontPair{
+ {bold: "C\\:/Windows/Fonts/msyhbd.ttc", regular: "C\\:/Windows/Fonts/msyh.ttc"},
+ {bold: "C\\:/Windows/Fonts/simhei.ttf", regular: "C\\:/Windows/Fonts/msyh.ttc"},
+ {bold: "C\\:/Windows/Fonts/simsun.ttc", regular: "C\\:/Windows/Fonts/simsun.ttc"},
+ }, nil
case "darwin":
- return "/System/Library/Fonts/Supplemental/Arial Bold.ttf", "/System/Library/Fonts/Supplemental/Arial.ttf", nil
+ return []fontPair{
+ {bold: "/System/Library/Fonts/Hiragino Sans GB.ttc", regular: "/System/Library/Fonts/Hiragino Sans GB.ttc"},
+ {bold: "/System/Library/Fonts/Supplemental/Arial Unicode.ttf", regular: "/System/Library/Fonts/Supplemental/Arial Unicode.ttf"},
+ {bold: "/System/Library/Fonts/STHeiti Medium.ttc", regular: "/System/Library/Fonts/STHeiti Light.ttc"},
+ {bold: "/System/Library/Fonts/Supplemental/Songti.ttc", regular: "/System/Library/Fonts/Supplemental/Songti.ttc"},
+ }, nil
case "linux":
- return "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", nil
+ return []fontPair{
+ {bold: "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc", regular: "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"},
+ {bold: "/usr/share/fonts/truetype/noto/NotoSansCJK-Bold.ttc", regular: "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc"},
+ {bold: "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", regular: "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc"},
+ {bold: "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", regular: "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"},
+ }, nil
default:
- return "", "", fmt.Errorf("unsupported OS: %s", runtime.GOOS)
+ return nil, fmt.Errorf("unsupported OS: %s", goos)
+ }
+}
+
+func chooseFontPair(candidates []fontPair, exists func(string) bool) (string, string, error) {
+ for _, candidate := range candidates {
+ if exists(candidate.bold) && exists(candidate.regular) {
+ return candidate.bold, candidate.regular, nil
+ }
+ }
+ if len(candidates) == 0 {
+ return "", "", errors.New("no font candidates configured")
}
+ // Fall back to the first candidate so containerized builds can still run when
+ // font discovery is unavailable, while normal hosts use existing fonts.
+ return candidates[0].bold, candidates[0].regular, nil
+}
+
+func pathExists(path string) bool {
+ normalized := strings.ReplaceAll(path, `C\:/`, `C:/`)
+ _, err := os.Stat(normalized)
+ return err == nil
}
func getResolution(inputVideo string) (int, int, error) {
@@ -391,8 +644,7 @@ func convertToVertical(inputVideo, outputVideo, majorTitle, minorTitle string) e
cmdArgs := []string{
"-i", inputVideo,
- "-vf", fmt.Sprintf("scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)*2/5,drawbox=y=0:h=100:c=black@1:t=fill,drawtext=text='%s':x=(w-text_w)/2:y=210:fontsize=55:fontcolor=yellow:box=1:[email protected]:fontfile='%s',drawtext=text='%s':x=(w-text_w)/2:y=280:fontsize=40:fontcolor=yellow:box=1:[email protected]:fontfile='%s'",
- majorTitle, fontBold, minorTitle, fontRegular),
+ "-vf", buildVerticalFilter(majorTitle, minorTitle, fontBold, fontRegular),
"-r", "30",
"-b:v", "7587k",
"-c:a", "aac",
@@ -413,3 +665,29 @@ func convertToVertical(inputVideo, outputVideo, majorTitle, minorTitle string) e
fmt.Printf("竖屏视频已保存到: %s\n", outputVideo)
return nil
}
+
+func buildVerticalFilter(majorTitle, minorTitle, fontBold, fontRegular string) string {
+ return fmt.Sprintf(
+ "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:250,drawbox=y=0:h=250:c=black@1:t=fill,drawtext=text='%s':x=(w-text_w)/2:y=120:fontsize=44:fontcolor=yellow:box=0:fontfile='%s',drawtext=text='%s':x=(w-text_w)/2:y=178:fontsize=30:fontcolor=yellow:box=0:fontfile='%s'",
+ escapeDrawtextText(majorTitle),
+ escapeFilterPath(fontBold),
+ escapeDrawtextText(minorTitle),
+ escapeFilterPath(fontRegular),
+ )
+}
+
+func escapeDrawtextText(text string) string {
+ replacer := strings.NewReplacer(
+ `\\`, `\\\\`,
+ `'`, `\\'`,
+ `:`, `\:`,
+ `,`, `\,`,
+ `[`, `\[`,
+ `]`, `\]`,
+ )
+ return replacer.Replace(text)
+}
+
+func escapeFilterPath(path string) string {
+ return strings.ReplaceAll(path, ":", `\:`)
+}
diff --git a/internal/service/srt_embed_test.go b/internal/service/srt_embed_test.go
new file mode 100644
index 00000000..0f5aea47
--- /dev/null
+++ b/internal/service/srt_embed_test.go
@@ -0,0 +1,110 @@
+package service
+
+import (
+ "math"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "krillin-ai/internal/types"
+)
+
+func TestSplitChineseTextDoesNotBreakCommonWords(t *testing.T) {
+ got := splitChineseText("你花在刷屏上的每一小时", 10)
+ joined := strings.Join(got, "\n")
+ if strings.Contains(joined, "小\n时") {
+ t.Fatalf("splitChineseText broke 小时: %q", joined)
+ }
+ if strings.Contains(joined, "每一小\n时") {
+ t.Fatalf("splitChineseText broke 每一小时: %q", joined)
+ }
+}
+
+func TestSplitChineseTextAvoidsShortTrailingLine(t *testing.T) {
+ got := splitChineseText("你每小时花在划屏上的时间", 10)
+ joined := strings.Join(got, "\n")
+ if strings.HasSuffix(joined, "\n时间") {
+ t.Fatalf("splitChineseText created a short trailing line: %q", joined)
+ }
+ if len(got) != 2 {
+ t.Fatalf("line count = %d, want 2; lines = %#v", len(got), got)
+ }
+}
+
+func TestSplitChineseTextBalancesDisplayWidth(t *testing.T) {
+ got := splitChineseText("你花在刷屏上的每一小时都会从未来的自己那里借走注意力", 10)
+ if len(got) < 2 {
+ t.Fatalf("line count = %d, want at least 2; lines = %#v", len(got), got)
+ }
+
+ firstWidth := subtitleDisplayWidth(got[0])
+ secondWidth := subtitleDisplayWidth(got[1])
+ if math.Abs(float64(firstWidth-secondWidth)) > 6 {
+ t.Fatalf("line widths are not balanced: lines=%#v widths=%d,%d", got, firstWidth, secondWidth)
+ }
+}
+
+func TestVerticalAssKeepsChineseLineInSingleDialogueWithLineBreak(t *testing.T) {
+ dir := t.TempDir()
+ in := filepath.Join(dir, "short.srt")
+ out := filepath.Join(dir, "short.ass")
+ content := "1\n00:00:28,600 --> 00:00:30,190\n大多数人看完这个视频后什么也不会做。\n\n"
+ if err := os.WriteFile(in, []byte(content), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ err := srtToAss(in, out, false, &types.SubtitleTaskStepParam{TaskBasePath: dir})
+ if err != nil {
+ t.Fatalf("srtToAss() error = %v", err)
+ }
+ data, err := os.ReadFile(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ass := string(data)
+ if count := strings.Count(ass, "Dialogue:"); count != 1 {
+ t.Fatalf("Dialogue count = %d, want 1; ass = %s", count, ass)
+ }
+ if strings.Contains(ass, `\N`) {
+ t.Fatalf("moderate vertical Chinese subtitle should stay on one line: %s", ass)
+ }
+}
+
+func subtitleDisplayWidth(text string) int {
+ width := 0
+ for _, r := range text {
+ if r >= '\u4e00' && r <= '\u9fff' {
+ width += 2
+ } else {
+ width++
+ }
+ }
+ return width
+}
+
+func TestVerticalAssSplitsLongChineseAcrossTime(t *testing.T) {
+ dir := t.TempDir()
+ in := filepath.Join(dir, "short.srt")
+ out := filepath.Join(dir, "short.ass")
+ content := "1\n00:00:28,600 --> 00:00:30,190\n你花在刷屏上的每一小时都会从未来的自己那里借走注意力。\n\n"
+ if err := os.WriteFile(in, []byte(content), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ err := srtToAss(in, out, false, &types.SubtitleTaskStepParam{TaskBasePath: dir})
+ if err != nil {
+ t.Fatalf("srtToAss() error = %v", err)
+ }
+ data, err := os.ReadFile(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ass := string(data)
+ if count := strings.Count(ass, "Dialogue:"); count < 2 {
+ t.Fatalf("Dialogue count = %d, want at least 2 for time-sliced Chinese lines; ass = %s", count, ass)
+ }
+ if strings.Contains(ass, `\N`) {
+ t.Fatalf("long vertical Chinese subtitle should be split across time, not stacked with line breaks: %s", ass)
+ }
+}
diff --git a/internal/service/youtube_subtitle.go b/internal/service/youtube_subtitle.go
index 6e15ad81..67325c33 100644
--- a/internal/service/youtube_subtitle.go
+++ b/internal/service/youtube_subtitle.go
@@ -3322,7 +3322,33 @@ func (s *YouTubeSubtitleService) groupWordsByCharLength(words []VttWord, maxChar
groups = append(groups, currentGroup)
}
- return groups
+ return mergeShortTrailingWordGroup(groups)
+}
+
+func mergeShortTrailingWordGroup(groups [][]VttWord) [][]VttWord {
+ if len(groups) < 2 {
+ return groups
+ }
+
+ last := groups[len(groups)-1]
+ if len(last) > 1 || wordGroupTextLength(last) > 12 {
+ return groups
+ }
+
+ prevIndex := len(groups) - 2
+ groups[prevIndex] = append(groups[prevIndex], last...)
+ return groups[:len(groups)-1]
+}
+
+func wordGroupTextLength(words []VttWord) int {
+ length := 0
+ for i, word := range words {
+ if i > 0 {
+ length++
+ }
+ length += len([]rune(word.Text))
+ }
+ return length
}
// writeShortSubtitleFile 生成短字幕文件(中文完整 + 英文拆分)
diff --git a/internal/service/youtube_subtitle_fix_test.go b/internal/service/youtube_subtitle_fix_test.go
index c758a7b0..8177b3f3 100644
--- a/internal/service/youtube_subtitle_fix_test.go
+++ b/internal/service/youtube_subtitle_fix_test.go
@@ -94,14 +94,33 @@ func TestParseVttTime(t *testing.T) {
}
}
+func TestGroupWordsByCharLengthMergesShortTrailingWord(t *testing.T) {
+ s := &YouTubeSubtitleService{}
+ words := []VttWord{
+ {Text: "Every", Start: "00:00:28.600", End: "00:00:28.780"},
+ {Text: "hour", Start: "00:00:28.780", End: "00:00:28.960"},
+ {Text: "you", Start: "00:00:28.960", End: "00:00:29.120"},
+ {Text: "spend", Start: "00:00:29.120", End: "00:00:29.360"},
+ {Text: "scrolling,", Start: "00:00:29.360", End: "00:00:30.190"},
+ }
+
+ groups := s.groupWordsByCharLength(words, 20)
+ if len(groups) != 1 {
+ t.Fatalf("group count = %d, want 1; groups = %#v", len(groups), groups)
+ }
+ if got := groups[0][len(groups[0])-1].Text; got != "scrolling," {
+ t.Fatalf("last word = %q, want scrolling,", got)
+ }
+}
+
func TestTimeRangeMatching(t *testing.T) {
// 测试时间范围匹配逻辑
tests := []struct {
- name string
- srtStart float64
- vttStart float64
- shouldMatch bool
- description string
+ name string
+ srtStart float64
+ vttStart float64
+ shouldMatch bool
+ description string
}{
{
name: "Exact match",
diff --git a/internal/types/embed_subtitle.go b/internal/types/embed_subtitle.go
index 90293201..1f319cb9 100644
--- a/internal/types/embed_subtitle.go
+++ b/internal/types/embed_subtitle.go
@@ -23,8 +23,8 @@ PlayDepth: 0
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
-Style: Major,Arial,15,&H00BFFF,&H000000FF,&H00000000,&H64000000,-1,0,0,0,100,100,-10,0,1,2.5,1.5,2,10,10,80,1
-Style: Minor,Arial,8,&H00BFFF,&H000000FF,&H00000000,&H64000000,-1,0,0,0,100,100,-10,0,1,2.5,1.5,2,10,10,100,1
+Style: Major,Arial,12,&H00BFFF,&H000000FF,&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,2.2,1.2,2,10,10,92,1
+Style: Minor,Arial,7,&H00BFFF,&H000000FF,&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,2.0,1.0,2,10,10,101,1
[Events]
diff --git a/internal/types/embed_subtitle_test.go b/internal/types/embed_subtitle_test.go
new file mode 100644
index 00000000..66c897da
--- /dev/null
+++ b/internal/types/embed_subtitle_test.go
@@ -0,0 +1,45 @@
+package types
+
+import (
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestAssHeaderVerticalUsesSmallerReadableChineseStyle(t *testing.T) {
+ if !strings.Contains(AssHeaderVertical, "Style: Major,Arial,12,") {
+ t.Fatalf("vertical major subtitle style should use smaller font size 12")
+ }
+ if strings.Contains(AssHeaderVertical, ",-10,0,1,") {
+ t.Fatalf("vertical subtitle style should not use negative letter spacing")
+ }
+}
+
+func TestAssHeaderVerticalKeepsBilingualLinesCloseTogether(t *testing.T) {
+ majorMargin := styleMarginV(t, AssHeaderVertical, "Major")
+ minorMargin := styleMarginV(t, AssHeaderVertical, "Minor")
+ if minorMargin-majorMargin > 10 {
+ t.Fatalf("vertical bilingual subtitle gap too large: major MarginV=%d minor MarginV=%d", majorMargin, minorMargin)
+ }
+}
+
+func styleMarginV(t *testing.T, header, styleName string) int {
+ t.Helper()
+ for _, line := range strings.Split(header, "\n") {
+ prefix := "Style: " + styleName + ","
+ if !strings.HasPrefix(line, prefix) {
+ continue
+ }
+ fields := strings.Split(strings.TrimPrefix(line, "Style: "), ",")
+ if len(fields) < 22 {
+ t.Fatalf("style %s has %d fields, want at least 22: %q", styleName, len(fields), line)
+ }
+ marginV, err := strconv.Atoi(fields[21])
+ if err != nil {
+ t.Fatalf("style %s MarginV = %q: %v", styleName, fields[21], err)
+ }
+ return marginV
+ }
+ t.Fatalf("style %s not found", styleName)
+ return 0
+}
diff --git a/skills/krillinai-cli/SKILL.md b/skills/krillinai-cli/SKILL.md
new file mode 100644
index 00000000..759012c6
--- /dev/null
+++ b/skills/krillinai-cli/SKILL.md
@@ -0,0 +1,63 @@
+---
+name: krillinai-cli
+description: Use when an agent needs to operate KrillinAI through its CLI, choose the right stage command, inspect CLI outputs, or run subtitle, TTS, landscape render, and portrait render tasks from a YouTube/local video input.
+---
+
+# KrillinAI CLI
+
+Use this as the top-level routing skill for KrillinAI command-line work.
+
+## Quick Start
+
+Prefer the repo-local binary:
+
+```bash
+./build/krillinai-cli <command> [flags]
+```
+
+If it does not exist, build it first:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+For common JSON, manifest, outputs, and error semantics, read:
+
+```text
+skills/krillinai-cli/references/cli-contract.md
+```
+
+## Choose The Command
+
+| User intent | Command / skill |
+|---|---|
+| Generate source, target, bilingual, and short vertical subtitles | `subtitle`; use `krillinai-subtitle` |
+| Generate target-language dubbing from subtitles | `tts`; use `krillinai-tts` |
+| Create landscape videos | `render-horizontal`; use `krillinai-render-horizontal` |
+| Create portrait/short-form videos | `render-vertical`; use `krillinai-render-vertical` |
+
+`pipeline`, `cover`, and `status` are planned/reserved surfaces in the current CLI. Use their skills for planning or dry-run documentation only unless the implementation has been wired in.
+
+## Operating Rules For Agents
+
+- Use a dedicated `--workdir`; do not scatter outputs in the repo root.
+- Prefer `--dry-run` when validating command shape or planning a run.
+- Parse stdout JSON and `krillinai_manifest.json`; do not parse normal logs.
+- Reuse manifest outputs for later stages instead of guessing filenames.
+- If a command fails, classify by `error.kind`: `usage`, `retryable`, `dependency`, or `internal`.
+- Avoid rerunning expensive stages if the manifest already has valid upstream outputs.
+
+## Minimal Workflow
+
+```bash
+./build/krillinai-cli subtitle "https://www.youtube.com/watch?v=VIDEO_ID" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt
+```
diff --git a/skills/krillinai-cli/references/cli-contract.md b/skills/krillinai-cli/references/cli-contract.md
new file mode 100644
index 00000000..eb97c3e6
--- /dev/null
+++ b/skills/krillinai-cli/references/cli-contract.md
@@ -0,0 +1,110 @@
+# KrillinAI CLI Contract
+
+## Binary
+
+Build from repo root:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+Run with:
+
+```bash
+./build/krillinai-cli <command> [flags]
+```
+
+## Commands
+
+| Command | Purpose |
+|---|---|
+| `subtitle` | Generate source-language, target-language, bilingual, and short vertical subtitles |
+| `tts` | Generate TTS audio and optional dubbed video |
+| `render-horizontal` | Render landscape subtitle/dubbed videos |
+| `render-vertical` | Render portrait subtitle/dubbed videos |
+| `pipeline` | Planned orchestration surface; currently safe for planning/dry-run only unless execution is wired in |
+| `cover` | Planned cover generation surface; currently manifest/output schema is reserved |
+| `status` | Reserved status query |
+
+## Manifest
+
+Every working directory should contain:
+
+```text
+krillinai_manifest.json
+```
+
+Read this file to locate stage outputs. Important default paths:
+
+| Output key | Default path |
+|---|---|
+| `origin_video` | `<workdir>/origin_video.mp4` |
+| `origin_audio` | `<workdir>/origin_audio.mp3` |
+| `origin_srt` | `<workdir>/origin_language_srt.srt` |
+| `target_srt` | `<workdir>/target_language_srt.srt` |
+| `bilingual_srt` | `<workdir>/bilingual_srt.srt` |
+| `short_origin_mixed_srt` | `<workdir>/short_origin_mixed_srt.srt` |
+| `tts_audio` | `<workdir>/tts_final_audio.wav` |
+| `video_with_tts` | `<workdir>/video_with_tts.mp4` |
+| `horizontal_video` | `<workdir>/horizontal_bilingual.mp4` |
+| `vertical_video` | `<workdir>/vertical_bilingual.mp4` |
+| `transferred_vertical_video` | `<workdir>/transferred_vertical_video.mp4` |
+| `origin_cover` | `<workdir>/origin_cover.jpg` |
+| `generated_cover` | `<workdir>/generated_cover.png` |
+| `cover_prompt` | `<workdir>/cover_prompt.final.txt` |
+
+## JSON Output
+
+Commands print normal logs and one JSON response. Agents should parse the JSON response and manifest, not logs.
+
+Success shape:
+
+```json
+{
+ "ok": true,
+ "stage": "subtitle",
+ "workdir": "tasks/demo",
+ "task_id": "demo",
+ "outputs": {}
+}
+```
+
+Failure shape:
+
+```json
+{
+ "ok": false,
+ "error": {
+ "kind": "retryable",
+ "code": "audio_transcription_failed",
+ "message": "connection timeout",
+ "retryable": true
+ }
+}
+```
+
+## Exit Codes
+
+| Code | Meaning |
+|---|---|
+| `0` | Success |
+| `1` | Usage error |
+| `2` | Retryable error |
+| `3` | Dependency error |
+
+## Error Handling
+
+- `usage`: fix flags or missing input.
+- `retryable`: retry after delay or switch provider/source.
+- `dependency`: install or expose `ffmpeg`, `ffprobe`, or `yt-dlp`.
+- `internal`: inspect logs and generated files.
+
+## Verification
+
+For command-shape checks:
+
+```bash
+./build/krillinai-cli subtitle local:demo.mp4 --origin-lang en --target-lang zh_cn --workdir /tmp/krillinai-check --dry-run
+```
+
+For rendered media, inspect the output file and optionally extract preview frames with `ffmpeg`.
diff --git a/skills/krillinai-cover/SKILL.md b/skills/krillinai-cover/SKILL.md
new file mode 100644
index 00000000..12271ef4
--- /dev/null
+++ b/skills/krillinai-cover/SKILL.md
@@ -0,0 +1,35 @@
+---
+name: krillinai-cover
+description: Use when planning or documenting KrillinAI cover generation from an original video cover and prompt templates; the current CLI cover command is a reserved/planned surface unless implementation is wired in.
+---
+
+# KrillinAI Cover
+
+Use this skill for cover generation planning. In the current CLI, `cover` is a reserved/planned surface; verify implementation before running it as a real stage.
+
+## Command
+
+```bash
+./build/krillinai-cli cover
+```
+
+Treat this as planned until execution is wired in. The intended cover stage is manifest-driven and should run from a prepared workdir after upstream stages populate `krillinai_manifest.json`.
+
+## Inputs
+
+- `origin_cover.jpg`
+- prompt template / final prompt
+- optional translated title or summary from previous stages
+
+## Outputs
+
+- `generated_cover.png`
+- `cover_prompt.final.txt`
+
+## Agent Guidance
+
+- Read `krillinai_manifest.json` to locate cover inputs and outputs.
+- Preserve the original cover as source material; write generated images to the workdir.
+- If the command returns `unsupported_command`, report that cover execution is not yet wired into the CLI.
+- If image generation credentials or provider config are missing after cover support is wired in, return a dependency/configuration issue rather than silently skipping.
+- For shared CLI response semantics, read `skills/krillinai-cli/references/cli-contract.md`.
diff --git a/skills/krillinai-pipeline/SKILL.md b/skills/krillinai-pipeline/SKILL.md
new file mode 100644
index 00000000..00056526
--- /dev/null
+++ b/skills/krillinai-pipeline/SKILL.md
@@ -0,0 +1,44 @@
+---
+name: krillinai-pipeline
+description: Use when planning multi-stage KrillinAI CLI workflows such as subtitle plus TTS plus horizontal or vertical render; current pipeline execution is a reserved/planned surface unless implementation is wired in.
+---
+
+# KrillinAI Pipeline
+
+Use this skill for end-to-end or multi-stage planning. In the current CLI, `pipeline` has output planning support but execution may not be wired in; prefer individual commands for real work unless verified.
+
+## Command
+
+```bash
+./build/krillinai-cli pipeline --outputs "subtitle,tts,vertical-bilingual"
+```
+
+## Outputs Values
+
+| Output | Stage |
+|---|---|
+| `subtitle` | Generate subtitle files |
+| `tts` | Generate dubbing |
+| `horizontal-bilingual` | Render landscape bilingual video |
+| `horizontal-dubbed` | Render landscape dubbed video |
+| `vertical-bilingual` | Render portrait bilingual video |
+| `vertical-dubbed` | Render portrait dubbed video |
+| `cover` | Generate cover |
+
+## When To Use Pipeline
+
+Use pipeline when the user asks for a complete result and the CLI implementation supports executing it. Prefer individual commands now for real runs, debugging, testing, or recovering a failed stage.
+
+## Recovery Strategy
+
+- If `subtitle` succeeds and render fails, rerun only render with the same `--workdir`.
+- If TTS fails, keep subtitle outputs and rerun `tts` after fixing provider config.
+- Read `krillinai_manifest.json` before rerunning to avoid repeating expensive work.
+
+## Verification
+
+- If the command returns `unsupported_command`, run the stages individually.
+- Confirm stdout JSON success when pipeline execution is wired in.
+- Confirm manifest stages for requested outputs are marked successful.
+- Inspect final requested media/cover files, not only intermediate outputs.
+- For shared CLI details, read `skills/krillinai-cli/references/cli-contract.md`.
diff --git a/skills/krillinai-render-horizontal/SKILL.md b/skills/krillinai-render-horizontal/SKILL.md
new file mode 100644
index 00000000..954af3a6
--- /dev/null
+++ b/skills/krillinai-render-horizontal/SKILL.md
@@ -0,0 +1,46 @@
+---
+name: krillinai-render-horizontal
+description: Use when rendering landscape videos with KrillinAI CLI, including original video plus bilingual subtitles or dubbed video plus target-language subtitles.
+---
+
+# KrillinAI Render Horizontal
+
+Use this skill for `render-horizontal`.
+
+## Bilingual Subtitle Video
+
+```bash
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/bilingual_srt.srt
+```
+
+## Dubbed Video
+
+```bash
+./build/krillinai-cli render-horizontal \
+ --workdir tasks/demo \
+ --video tasks/demo/video_with_tts.mp4 \
+ --subtitle tasks/demo/target_language_srt.srt \
+ --dubbed
+```
+
+## Inputs
+
+- `--video`: source video, or omit when manifest has the correct input.
+- `--subtitle`: usually `bilingual_srt.srt` for bilingual, `target_language_srt.srt` for dubbed.
+- `--workdir`: directory containing `krillinai_manifest.json`.
+
+## Outputs
+
+- `horizontal_bilingual.mp4`
+- Future/variant dubbed outputs may also be listed in manifest.
+
+## Verification
+
+- Confirm stdout JSON is successful.
+- Confirm output video exists and has video/audio streams.
+- Extract a preview frame when checking subtitle placement.
+- For manifest and error handling, read `skills/krillinai-cli/references/cli-contract.md`.
+
diff --git a/skills/krillinai-render-vertical/SKILL.md b/skills/krillinai-render-vertical/SKILL.md
new file mode 100644
index 00000000..82c34b2e
--- /dev/null
+++ b/skills/krillinai-render-vertical/SKILL.md
@@ -0,0 +1,57 @@
+---
+name: krillinai-render-vertical
+description: Use when rendering portrait videos with KrillinAI CLI, including converting source video to vertical format, adding short bilingual subtitles, rendering dubbed vertical videos, and checking vertical subtitle readability.
+---
+
+# KrillinAI Render Vertical
+
+Use this skill for `render-vertical`.
+
+## Bilingual Short-Subtitle Video
+
+```bash
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/origin_video.mp4 \
+ --subtitle tasks/demo/short_origin_mixed_srt.srt \
+ --major-title "今日话题" \
+ --minor-title "AI Video"
+```
+
+## Dubbed Vertical Video
+
+```bash
+./build/krillinai-cli render-vertical \
+ --workdir tasks/demo \
+ --video tasks/demo/video_with_tts.mp4 \
+ --subtitle tasks/demo/target_language_srt.srt \
+ --dubbed \
+ --major-title "今日话题" \
+ --minor-title "AI Video"
+```
+
+## Subtitle Behavior
+
+The Go renderer follows the good behavior from `vertical_srt.py`:
+
+- Chinese uses word segmentation before line decisions.
+- Display width is used for line splitting: Chinese counts as width 2, other text as width 1.
+- Long Chinese subtitles are split across time into multiple `Dialogue` entries instead of stacked with `\N`.
+- The goal is to keep the screen to one English line plus one Chinese line when possible.
+
+## Outputs
+
+- `transferred_vertical_video.mp4`: source converted to portrait format.
+- `vertical_bilingual.mp4`: final vertical video with subtitles.
+
+## Verification
+
+Use text and visual checks:
+
+```bash
+rg -n -F '\\N' tasks/demo/formatted_vertical_bilingual.ass
+ffmpeg -y -ss 00:00:01 -i tasks/demo/vertical_bilingual.mp4 -frames:v 1 tasks/demo/vertical_preview_%03d.jpg
+```
+
+Check that moderate Chinese subtitles do not become two stacked Chinese lines and that titles are not garbled.
+
diff --git a/skills/krillinai-subtitle/SKILL.md b/skills/krillinai-subtitle/SKILL.md
new file mode 100644
index 00000000..b10992b6
--- /dev/null
+++ b/skills/krillinai-subtitle/SKILL.md
@@ -0,0 +1,61 @@
+---
+name: krillinai-subtitle
+description: Use when generating subtitles with KrillinAI CLI from a YouTube link, Bilibili/local video, or existing media, including platform caption download, Whisper fallback, translation, bilingual SRT, and short vertical subtitle output.
+---
+
+# KrillinAI Subtitle
+
+Use this skill for the `subtitle` stage.
+
+## Command
+
+```bash
+./build/krillinai-cli subtitle "<input>" \
+ --origin-lang en \
+ --target-lang zh_cn \
+ --workdir tasks/demo \
+ --caption-source any
+```
+
+Build the CLI first if needed:
+
+```bash
+go build -o build/krillinai-cli ./cmd/cli
+```
+
+## Inputs
+
+- YouTube URL: prefer `--caption-source any`; platform captions are used first, then Whisper fallback.
+- Local file: use `local:/abs/path/video.mp4` or a path accepted by the CLI.
+- Bilibili or other yt-dlp supported links: use when media download works; platform caption behavior may differ, so expect transcription fallback.
+
+## Important Flags
+
+| Flag | Use |
+|---|---|
+| `--origin-lang` | Source language, such as `en`, `zh`, `ja` |
+| `--target-lang` | Target language, such as `zh_cn` |
+| `--workdir` | Dedicated task directory |
+| `--caption-source any` | Prefer platform captions, fallback to transcription |
+| `--caption-source whisper` | Force transcription |
+| `--bilingual-top=true` | Put target language on top in bilingual SRT |
+| `--dry-run` | Validate without downloads or AI calls |
+
+## Outputs
+
+Read paths from `krillinai_manifest.json`. Main files:
+
+- `origin_language_srt.srt`
+- `target_language_srt.srt`
+- `bilingual_srt.srt`
+- `short_origin_mixed_srt.srt`
+- `origin_video.mp4`
+- `origin_audio.mp3`
+
+## Verification
+
+- Confirm stdout JSON has `"ok": true`.
+- Confirm `krillinai_manifest.json` exists under `--workdir`.
+- Spot-check `bilingual_srt.srt` ordering and `short_origin_mixed_srt.srt` readability.
+- For Agent integration details, read `skills/krillinai-cli/references/cli-contract.md`.
+
diff --git a/skills/krillinai-tts/SKILL.md b/skills/krillinai-tts/SKILL.md
new file mode 100644
index 00000000..a2d5f72e
--- /dev/null
+++ b/skills/krillinai-tts/SKILL.md
@@ -0,0 +1,51 @@
+---
+name: krillinai-tts
+description: Use when generating target-language dubbing with KrillinAI CLI from SRT subtitles, including TTS audio creation and optional dubbed video generation.
+---
+
+# KrillinAI TTS
+
+Use this skill for the `tts` stage.
+
+## Command
+
+```bash
+./build/krillinai-cli tts \
+ --workdir tasks/demo \
+ --input-srt tasks/demo/target_language_srt.srt \
+ --line-mode target-only \
+ --video tasks/demo/origin_video.mp4
+```
+
+## Inputs
+
+- `--input-srt` is required. Usually use `target_language_srt.srt`.
+- `--video` is optional but needed when generating `video_with_tts.mp4`.
+- TTS provider must be configured in `config/config.toml`.
+
+## Important Flags
+
+| Flag | Use |
+|---|---|
+| `--input-srt` | SRT to synthesize |
+| `--line-mode target-only` | Use target-language lines only |
+| `--line-mode bilingual-target-top` | Bilingual mode with target on top |
+| `--line-mode bilingual-target-bottom` | Bilingual mode with target on bottom |
+| `--voice` | Provider-specific voice |
+| `--voice-clone-source` | Voice clone source audio URL/path when supported |
+| `--dry-run` | Validate command shape |
+
+## Outputs
+
+Read paths from manifest:
+
+- `tts_final_audio.wav`
+- `video_with_tts.mp4` when a video input is available
+
+## Verification
+
+- Confirm stdout JSON has `"ok": true`.
+- Confirm `tts_final_audio.wav` exists and has non-zero size.
+- If `video_with_tts.mp4` is produced, inspect duration and audio stream with `ffprobe`.
+- For JSON/error contract, read `skills/krillinai-cli/references/cli-contract.md`.
+