-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubtool.sh
More file actions
executable file
·5756 lines (5181 loc) · 240 KB
/
Copy pathsubtool.sh
File metadata and controls
executable file
·5756 lines (5181 loc) · 240 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
set -euo pipefail
VERSION="1.21.1"
SCRIPT_NAME="$(basename "$0")"
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/subtool"
CONFIG_FILE="$CONFIG_DIR/config"
CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/subtool"
# ── Colors ────────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
# ── Defaults ──────────────────────────────────────────────────────────────────
LANG_TARGET=""
AI_PROVIDER="google"
SEARCH_QUERY=""
IMDB_ID=""
FILE_PATH=""
SCAN_DIR=""
SEASON=""
EPISODE=""
OUTPUT_DIR="."
FORCE_TRANSLATE=false
KEEP_FILES=false
SOURCES="opensubtitles-org"
FALLBACK_LANGS="en,de,es,pt"
MAX_EPISODE=20
AI_MODEL=""
AI_MODEL_EXPLICIT=false
TRUST_CODEX_INPUT=false
AUTO_SELECT=false
AUTO_EMBED=false
NO_EMBED=false
FORCE_EMBED=true
DRY_RUN=false
JSON_OUTPUT=false
VERBOSE=false
QUIET=false
SUBTITLE_URL=""
TRANSCRIBE_PROVIDER="whisper"
WHISPER_MODEL=""
TRANSLATE_CHUNK_SIZE=""
MAX_TOKENS=""
NO_TRANSCRIBE=false
FORCE_TRANSCRIBE=false
CLAUDE_EFFORT=""
SKIP_STEPS=""
TRANSLATE_MAX_PARALLEL=""
AUTO_SYNC_SHIFT=""
# Set by _auto_sync after each invocation. Lets callers (e.g. _auto_mix) detect
# sub-to-sub sync failure and choose an appropriate fallback.
_LAST_SYNC_OK=false
NO_RESUME=true
PLAYLIST_FILE=""
DIFF_FILE=""
MIX_FILE=""
MIX_MODE=false
MIX_LANG=""
MIX_TRANSLATE=false
SWAP_MIX=false
STRIP_EXISTING=false
# ── Default models ────────────────────────────────────────────────────────────
MODEL_ZAI_CODEPLAN="glm-4.7"
MODEL_OPENAI="gpt-5-mini"
MODEL_CLAUDE="claude-haiku-4-5"
MODEL_MISTRAL="mistral-small-latest"
MODEL_GEMINI="gemini-2.5-flash"
# ── Helpers ───────────────────────────────────────────────────────────────────
log() { { $QUIET && return; printf "${GREEN}[+]${NC} %s\n" "$*" >&2; } || true; }
warn() { { $QUIET && return; printf "${YELLOW}[!]${NC} %s\n" "$*" >&2; } || true; }
err() { printf "${RED}[x]${NC} %s\n" "$*" >&2; }
info() { { $QUIET && return; printf "${CYAN}[i]${NC} %s\n" "$*" >&2; } || true; }
debug() { $VERBOSE && printf "${BLUE}[D]${NC} %s\n" "$*" >&2 || true; }
header() { { $QUIET && return; printf "\n${BOLD}${BLUE}── %s ──${NC}\n" "$*" >&2; } || true; }
die() { err "$1"; exit 1; }
# Progress bar: progress <current> <total> [label]
progress() {
$QUIET && return || true
local current="$1" total="$2" label="${3:-}"
[[ $total -le 0 ]] && return || true
local pct=$((current * 100 / total))
local filled=$((pct / 2))
local empty=$((50 - filled))
local bar
bar=$(printf '%*s' "$filled" '' | tr ' ' '█')$(printf '%*s' "$empty" '' | tr ' ' '░')
printf "\r %s [%s] %d%% (%d/%d) " "$label" "$bar" "$pct" "$current" "$total" >&2
[[ $current -ge $total ]] && printf "\n" >&2 || true
}
# Multi-language dispatch: if LANG_TARGET has commas, loop over each language
# Usage: _multi_lang_dispatch <function_name> && return
_multi_lang_dispatch() {
local func="$1"
[[ "$LANG_TARGET" != *,* ]] && return 1
local saved_lang="$LANG_TARGET"
IFS=',' read -ra _ml_langs <<< "$saved_lang"
for _ml_lang in "${_ml_langs[@]}"; do
_ml_lang=$(echo "$_ml_lang" | tr -d ' ')
[[ -z "$_ml_lang" ]] && continue
printf "\n${BOLD}${BLUE}── Language: %s ──${NC}\n" "$_ml_lang" >&2
LANG_TARGET="$_ml_lang"
"$func" || warn "Failed for language: $_ml_lang"
done
LANG_TARGET="$saved_lang"
return 0
}
# URL encode (pure bash via jq)
urlencode() { jq -sRr @uri <<< "$1" | sed 's/%0A$//'; }
# Retry wrapper for API calls (handles 429 / transient errors)
# Usage: api_retry curl -sf "https://..."
api_retry() {
local max_retries=3 retry_delay=2 attempt=0
local output rc
while [[ $attempt -lt $max_retries ]]; do
output=$("$@" 2>&1) && { echo "$output"; return 0; }
rc=$?
if echo "$output" | grep -q "429\|rate.limit\|Too Many"; then
((attempt++)) || true
debug "Rate limited, retry $attempt/$max_retries in ${retry_delay}s..."
sleep "$retry_delay"
retry_delay=$((retry_delay * 2))
else
echo "$output"
return $rc
fi
done
echo "$output"
return 1
}
# Detect language from subtitle text via translate-shell (Google API), with offline fallback
detect_lang() {
local sample="$1"
[[ -z "$sample" ]] && return
# Primary: use translate-shell (Google Translate API, already a required dependency)
if command -v trans &>/dev/null; then
local detected=""
detected=$(trans -id -no-ansi "$sample" 2>/dev/null | grep "^Code" | awk '{print $2}') || true
if [[ -n "$detected" && "$detected" != "null" ]]; then
# Normalize regional variants (pt-BR -> pt, zh-CN -> zh, etc.)
detected="${detected%%-*}"
echo "$detected"
return
fi
fi
# Fallback: offline scoring (no network / trans unavailable)
_detect_lang_offline "$sample"
}
# Offline language detection fallback (scoring-based)
_detect_lang_offline() {
local sample="$1"
local all_langs="en fr de es it pt ru pl nl sv da no fi tr"
local best_lang="" best_score=0
local lang char_pattern word_pattern char_count word_count score
for lang in $all_langs; do
char_pattern=""
case "$lang" in
de) char_pattern='ß|ü|Ü' ;;
fr) char_pattern='[àâ]|[éèêë]|[ùû]|[îï]|œ|«|»' ;;
es) char_pattern='ñ|¿|¡' ;;
pt) char_pattern='[ãõ]' ;;
it) char_pattern='[ìòù]' ;;
pl) char_pattern='[ąćęłńóśźż]|[ĄĆĘŁŃÓŚŹŻ]' ;;
sv) char_pattern='[åÅ]' ;;
da) char_pattern='[æøÆØ]' ;;
no) char_pattern='[æøåÆØÅ]' ;;
fi) char_pattern='ää|öö' ;;
tr) char_pattern='[şŞğĞıİ]|[çÇ]' ;;
ru) char_pattern='[а-яА-ЯёЁ]' ;;
esac
case "$lang" in
en) word_pattern='\b(the|you|and|this|that|have|with|what|would|there|been|they|your|just|like|about|know|could|should|where|their|because|which|into|before|after|between|those|these|very|when|will|than|only|other|were|them|then|also|going|really|right|think|want|doesn|didn|can|our|she|his|her)\b' ;;
fr) word_pattern='\b(nous|vous|avec|dans|cette|mais|sont|pour|tout|elle|elles|aussi|comme|fait|avoir|être|même|encore|alors|rien|bien|très|peut|sans|faire|quel|dont|leur|quoi|jamais|toujours|après|avant|parce|depuis|comment|pourquoi|personne|quelque|maintenant|seulement)\b' ;;
de) word_pattern='\b(ich|und|nicht|sich|auch|noch|wir|wenn|aber|dann|schon|wird|haben|kann|mein|dein|hier|dass|jetzt|immer|wieder|diese|keine|doch|sein|nach|beim|einen|einem|einer|alles|warum|nichts|etwas|vielleicht|natürlich|zwischen|müssen|können|werden|wollen|sollen)\b' ;;
es) word_pattern='\b(pero|esto|tiene|muy|todo|están|porque|aquí|ahora|siempre|nunca|también|puede|hacer|ellos|nosotros|ustedes|bueno|cuando|donde|quien|nada|algo|mucho|todos|todas|después|antes|quiero|puedo|tengo|creo|estoy|vamos|verdad|entonces)\b' ;;
it) word_pattern='\b(sono|questo|anche|loro|della|quello|tutto|perché|dove|quando|ancora|sempre|fatto|stato|bene|dopo|prima|adesso|niente|qualcosa|troppo|proprio|siamo|abbiamo|voglio|posso|stai|cosa|allora|grazie|senza|ogni|deve|hanno)\b' ;;
pt) word_pattern='\b(isso|ele|ela|tem|muito|quando|ainda|agora|aqui|todo|todos|porque|depois|antes|sempre|nunca|nada|algo|mesmo|nossa|nosso|vocês|fazer|pode|obrigado|então|também|tudo|onde|quem|estou|tenho|acho|preciso)\b' ;;
ru) word_pattern='\b(что|это|как|так|все|они|мне|его|она|было|уже|мой|тебя|если|нет|вот|тут|есть|был|еще|тоже|только|когда|потому|может|будет|надо|знаю|ничего|очень|сейчас|здесь|почему|хорошо|ладно|давай|пожалуйста|спасибо|никогда|всегда)\b' ;;
pl) word_pattern='\b(jest|nie|tak|ale|jak|się|czy|już|jeszcze|tylko|tutaj|teraz|kiedy|dlaczego|gdzie|zawsze|nigdy|może|muszę|bardzo|dobrze|proszę|dzięki|wszystko|nic|ktoś|coś|trochę|właśnie|naprawdę|chcę|wiem|myślę|przepraszam|zobaczmy)\b' ;;
nl) word_pattern='\b(het|een|van|dat|zijn|niet|met|wat|maar|ook|als|nog|wel|naar|hij|zij|dit|werd|hebben|deze|hun|zou|waar|daar|moet|goed|geen|hier|toen|heel|waarom|alles|niets|altijd|nooit|misschien|kunnen|willen|moeten|omdat)\b' ;;
sv) word_pattern='\b(det|att|och|den|som|har|inte|med|för|var|kan|ska|vill|han|hon|alla|från|efter|bara|här|där|mycket|aldrig|alltid|varför|redan|sedan|kanske|ganska|också|igen|något|ingenting|behöver|gärna|tack)\b' ;;
da) word_pattern='\b(det|og|har|ikke|med|den|som|kan|han|hun|vil|skal|var|fra|her|der|men|alle|efter|bare|hvad|hvor|hvorfor|aldrig|altid|noget|ingenting|måske|også|igen|allerede|fordi|godt|meget|lidt|velkommen|tak)\b' ;;
no) word_pattern='\b(det|og|har|ikke|med|den|som|kan|han|hun|vil|skal|var|fra|her|der|men|alle|etter|bare|hva|hvor|hvorfor|aldri|alltid|kanskje|også|igjen|allerede|fordi|veldig|mye|litt|velkommen|takk|noen|noe|ingenting)\b' ;;
fi) word_pattern='\b(hän|mutta|niin|myös|vain|tämä|nyt|kun|jos|tai|ovat|ole|miksi|missä|sitten|vielä|aina|koskaan|ehkä|hyvin|paljon|kiitos|anteeksi|tiedän|haluan|pitää|minun|sinun|meidän|täällä|siellä|kaikki|mitään|jotain|mikään|olet|olen|emme|eivät|minä|sinä|hyvä|pois|heitä|meillä|heillä|tämän|tuolla|täytyy|tarpeeksi|ymmärrän)\b' ;;
tr) word_pattern='\b(bir|ben|sen|biz|siz|var|yok|ama|için|ile|gibi|daha|çok|kadar|sonra|önce|şimdi|burada|orada|neden|nasıl|nerede|zaman|hiç|hep|belki|tamam|teşekkür|lütfen|evet|hayır|bence|iyi|kötü|güzel)\b' ;;
esac
char_count=0
if [[ -n "$char_pattern" ]]; then
char_count=$(printf '%s\n' "$sample" | grep -oE "$char_pattern" 2>/dev/null | wc -l | tr -d ' ') || true
fi
word_count=$(printf '%s\n' "$sample" | grep -oiE "$word_pattern" 2>/dev/null | wc -l | tr -d ' ') || true
score=$((char_count * 3 + word_count))
if [[ $score -gt $best_score ]]; then
best_score=$score
best_lang="$lang"
fi
done
[[ $best_score -ge 3 ]] && echo "$best_lang"
return 0
}
# Validate SRT format (returns 0 if valid, 1 if broken)
validate_srt() {
local file="$1"
[[ ! -s "$file" ]] && return 1
# Must have at least one timestamp line
grep -qE '[0-9]{2}:[0-9]{2}:[0-9]{2}[,\.][0-9]{3} --> [0-9]{2}:[0-9]{2}:[0-9]{2}[,\.][0-9]{3}' "$file" || return 1
# Must have at least one numeric index (tolerate BOM and \r)
grep -qE '^(\xef\xbb\xbf)?[0-9]+\r?$' "$file" || return 1
return 0
}
# ── Config ────────────────────────────────────────────────────────────────────
init_config() {
mkdir -p "$CONFIG_DIR" "$CACHE_DIR"
if [[ ! -f "$CONFIG_FILE" ]]; then
cat > "$CONFIG_FILE" << 'CONF'
# subtool configuration
# API keys for AI translation (optional — claude-code and codex work without API keys)
OPENAI_API_KEY=""
ANTHROPIC_API_KEY=""
MISTRAL_API_KEY=""
GEMINI_API_KEY=""
ZAI_API_KEY=""
# Separate API key for transcription (falls back to OPENAI_API_KEY if empty)
OPENAI_WHISPER_API_KEY=""
# Default language (e.g., fr, en, de — so you don't need -l every time)
DEFAULT_LANG=""
# Default AI provider: codex, claude-code, zai-codeplan, openai, claude, mistral, gemini
DEFAULT_AI_PROVIDER="google" # or: codex, claude-code, zai-codeplan, openai, claude, mistral, gemini
# Default models (leave empty to use defaults)
MODEL_CLAUDE_CODE=""
MODEL_ZAI_CODEPLAN=""
MODEL_OPENAI=""
MODEL_CLAUDE=""
MODEL_MISTRAL=""
MODEL_GEMINI=""
# Default transcription provider: whisper, openai-api
DEFAULT_TRANSCRIBE_PROVIDER=""
# Whisper model (tiny, base, small, medium, large) — leave empty for "small"
WHISPER_MODEL=""
# Translation chunk size (lines per chunk) — leave empty for defaults (80 google, 500 LLM)
TRANSLATE_CHUNK_SIZE=""
# Max output tokens for LLM translation — leave empty for auto (based on provider/model)
MAX_TOKENS=""
# Claude Code effort level (low, medium, high) — leave empty for "low"
CLAUDE_EFFORT=""
# Max parallel translation chunks — leave empty for defaults (3 LLM, 8 google)
TRANSLATE_MAX_PARALLEL=""
# Extra constant shift in ms applied after ffsubsync in auto mode (e.g., -2000)
AUTO_SYNC_SHIFT=""
CONF
info "Config created: $CONFIG_FILE"
fi
}
load_config() {
init_config
# Save existing env vars before source
local _saved_openai="${OPENAI_API_KEY:-}"
local _saved_anthropic="${ANTHROPIC_API_KEY:-}"
local _saved_mistral="${MISTRAL_API_KEY:-}"
local _saved_gemini="${GEMINI_API_KEY:-}"
local _saved_zai="${ZAI_API_KEY:-}"
local _saved_openai_whisper="${OPENAI_WHISPER_API_KEY:-}"
# shellcheck source=/dev/null
[[ -f "$CONFIG_FILE" ]] && source "$CONFIG_FILE"
# Env vars take priority over config file
[[ -n "$_saved_openai" ]] && OPENAI_API_KEY="$_saved_openai"
[[ -n "$_saved_anthropic" ]] && ANTHROPIC_API_KEY="$_saved_anthropic"
[[ -n "$_saved_mistral" ]] && MISTRAL_API_KEY="$_saved_mistral"
[[ -n "$_saved_gemini" ]] && GEMINI_API_KEY="$_saved_gemini"
[[ -n "$_saved_zai" ]] && ZAI_API_KEY="$_saved_zai"
[[ -n "$_saved_openai_whisper" ]] && OPENAI_WHISPER_API_KEY="$_saved_openai_whisper"
# Restore default models if config set them empty
[[ -z "${MODEL_CLAUDE_CODE:-}" ]] && MODEL_CLAUDE_CODE="haiku"
[[ -z "$MODEL_ZAI_CODEPLAN" ]] && MODEL_ZAI_CODEPLAN="glm-4.7"
[[ -z "$MODEL_OPENAI" ]] && MODEL_OPENAI="gpt-5-mini"
[[ -z "$MODEL_CLAUDE" ]] && MODEL_CLAUDE="claude-haiku-4-5"
[[ -z "$MODEL_MISTRAL" ]] && MODEL_MISTRAL="mistral-small-latest"
[[ -z "$MODEL_GEMINI" ]] && MODEL_GEMINI="gemini-2.5-flash"
AI_PROVIDER="${DEFAULT_AI_PROVIDER:-google}"
TRANSCRIBE_PROVIDER="${DEFAULT_TRANSCRIBE_PROVIDER:-whisper}"
[[ -z "${WHISPER_MODEL:-}" ]] && WHISPER_MODEL="small"
[[ -z "${CLAUDE_EFFORT:-}" ]] && CLAUDE_EFFORT="low"
# Apply default language from config (CLI -l flag overrides later in parse_args)
[[ -z "$LANG_TARGET" && -n "${DEFAULT_LANG:-}" ]] && LANG_TARGET="$DEFAULT_LANG" || true
}
# ── OpenSubtitles.org (free, no API key) ──────────────────────────────────────
search_opensubtitles_org() {
local query="$1" lang="$2" imdb_id="${3:-}" season="${4:-}" episode="${5:-}"
# Language -> 3-letter code mapping for OpenSubtitles
local lang3
case "$lang" in
fr|fre|fra) lang3="fre" ;; en|eng) lang3="eng" ;; es|spa) lang3="spa" ;;
de|ger|deu) lang3="ger" ;; it|ita) lang3="ita" ;; pt|por) lang3="por" ;;
ru|rus) lang3="rus" ;; ar|ara) lang3="ara" ;; ja|jpn) lang3="jpn" ;;
ko|kor) lang3="kor" ;; zh|chi|zho) lang3="chi" ;; nl|dut|nld) lang3="dut" ;;
pl|pol) lang3="pol" ;; sv|swe) lang3="swe" ;; da|dan) lang3="dan" ;;
fi|fin) lang3="fin" ;; no|nor) lang3="nor" ;; tr|tur) lang3="tur" ;;
*) lang3="$lang" ;;
esac
# The .org API requires lowercase, otherwise 302 to invalid host
local lower_query
lower_query=$(echo "$query" | tr '[:upper:]' '[:lower:]')
local encoded_query
encoded_query=$(urlencode "$lower_query")
# Build URL with path segments in alphabetical order (API requires this)
local url="https://rest.opensubtitles.org/search/"
[[ -n "$episode" ]] && url+="episode-${episode}/"
url+="query-${encoded_query}/"
[[ -n "$season" ]] && url+="season-${season}/"
url+="sublanguageid-${lang3}"
local resp
resp=$(api_retry curl -sf "$url" -H "User-Agent: subtool v${VERSION}") || return 1
local count
count=$(echo "$resp" | jq 'length' 2>/dev/null) || true
[[ "$count" == "0" || -z "$count" ]] && return 1
local filtered="$resp"
echo "$filtered" | jq -c '.[] | {
id: .SubDownloadLink,
name: .SubFileName,
lang: .LanguageName,
source: "opensubtitles-org",
downloads: (.SubDownloadsCnt | tonumber),
rating: (.SubRating | tonumber)
}' 2>/dev/null || true
}
download_opensubtitles_org() {
local download_link="$1" output="$2"
local tmp_gz="$CACHE_DIR/osorg_$$.gz"
curl -sf -o "$tmp_gz" "$download_link" \
-H "User-Agent: subtool v${VERSION}" 2>/dev/null || return 1
gunzip -f "$tmp_gz" 2>/dev/null || return 1
mv "${tmp_gz%.gz}" "$output" 2>/dev/null || return 1
}
# ── Download from OpenSubtitles.org page URL ──────────────────────────────────
download_from_url() {
local url="$1" output="$2"
# Accept various opensubtitles.org URL formats:
# https://www.opensubtitles.org/en/subtitles/1234567/...
# https://www.opensubtitles.org/en/subtitleserve/sub/1234567
# https://dl.opensubtitles.org/en/download/sub/1234567
local sub_id=""
if [[ "$url" =~ opensubtitles\.org/[a-z]{2}/subtitles/([0-9]+) ]]; then
sub_id="${BASH_REMATCH[1]}"
elif [[ "$url" =~ opensubtitles\.org/[a-z]{2}/subtitleserve/sub/([0-9]+) ]]; then
sub_id="${BASH_REMATCH[1]}"
elif [[ "$url" =~ opensubtitles\.org/[a-z]{2}/download/sub/([0-9]+) ]]; then
sub_id="${BASH_REMATCH[1]}"
elif [[ "$url" =~ ^https?:// ]]; then
# Generic URL — try direct download (might be .srt, .gz, .zip)
local tmp_file="$CACHE_DIR/url_download_$$"
curl -sfL -o "$tmp_file" "$url" -H "User-Agent: subtool v${VERSION}" 2>/dev/null || { err "Download failed: $url"; return 1; }
# Detect file type
local ftype
ftype=$(file -b "$tmp_file" 2>/dev/null)
if [[ "$ftype" == *gzip* ]]; then
mv "$tmp_file" "${tmp_file}.gz"
gunzip -f "${tmp_file}.gz" 2>/dev/null || { rm -f "${tmp_file}.gz"; return 1; }
mv "$tmp_file" "$output"
elif [[ "$ftype" == *Zip* ]]; then
local tmp_dir="$CACHE_DIR/url_extract_$$"
mkdir -p "$tmp_dir"
unzip -qo "$tmp_file" -d "$tmp_dir" 2>/dev/null
local srt_found
srt_found=$(find "$tmp_dir" -iname "*.srt" | head -1)
if [[ -n "$srt_found" ]]; then
mv "$srt_found" "$output"
fi
rm -rf "$tmp_dir" "$tmp_file"
else
mv "$tmp_file" "$output"
fi
[[ -s "$output" ]] && return 0 || return 1
else
err "Unrecognized URL: $url"
return 1
fi
# OpenSubtitles.org subtitle ID download
if [[ -n "$sub_id" ]]; then
local dl_url="https://dl.opensubtitles.org/en/download/sub/${sub_id}"
local tmp_gz="$CACHE_DIR/url_${sub_id}_$$.gz"
curl -sfL -o "$tmp_gz" "$dl_url" -H "User-Agent: subtool v${VERSION}" 2>/dev/null || { err "Download failed: $dl_url"; return 1; }
# The response might be a zip file
local ftype
ftype=$(file -b "$tmp_gz" 2>/dev/null)
if [[ "$ftype" == *gzip* ]]; then
gunzip -f "$tmp_gz" 2>/dev/null || return 1
mv "${tmp_gz%.gz}" "$output" 2>/dev/null || return 1
elif [[ "$ftype" == *Zip* ]]; then
local tmp_dir="$CACHE_DIR/url_extract_$$"
mkdir -p "$tmp_dir"
unzip -qo "$tmp_gz" -d "$tmp_dir" 2>/dev/null
local srt_found
srt_found=$(find "$tmp_dir" -iname "*.srt" | head -1)
if [[ -n "$srt_found" ]]; then
mv "$srt_found" "$output"
fi
rm -rf "$tmp_dir" "$tmp_gz"
[[ -s "$output" ]] || return 1
else
mv "$tmp_gz" "$output" 2>/dev/null || return 1
fi
fi
}
# ── Podnapisi ─────────────────────────────────────────────────────────────────
search_podnapisi() {
local query="$1" lang="$2"
local lang_code
# Podnapisi uses language-specific codes
case "$lang" in
fr|fre|fra) lang_code="8" ;;
en|eng) lang_code="2" ;;
es|spa) lang_code="28" ;;
de|ger|deu) lang_code="5" ;;
it|ita) lang_code="9" ;;
pt|por) lang_code="23" ;;
ru|rus) lang_code="27" ;;
ar|ara) lang_code="26" ;;
ja|jpn) lang_code="11" ;;
ko|kor) lang_code="4" ;;
zh|chi|zho) lang_code="17" ;;
*) lang_code="$lang" ;;
esac
local encoded_query
encoded_query=$(urlencode "$query")
local resp
resp=$(api_retry curl -sf "https://www.podnapisi.net/subtitles/search/old?keywords=$encoded_query&language=$lang_code&output_type=json") || return 1
local count
count=$(echo "$resp" | jq '.subtitles | length' 2>/dev/null)
[[ "$count" == "0" || -z "$count" ]] && return 1
echo "$resp" | jq -c '.subtitles[]? | {
id: .id,
name: .release,
lang: .languageName,
source: "podnapisi",
downloads: .downloads,
rating: .rating
}' 2>/dev/null
}
download_podnapisi() {
local sub_id="$1" output="$2"
local tmp_zip="$CACHE_DIR/podnapisi_${sub_id}.zip"
curl -sf -o "$tmp_zip" "https://www.podnapisi.net/subtitles/${sub_id}/download" 2>/dev/null || return 1
local tmp_dir="$CACHE_DIR/podnapisi_extract_$$"
mkdir -p "$tmp_dir"
unzip -qo "$tmp_zip" -d "$tmp_dir" 2>/dev/null || { rm -rf "$tmp_dir" "$tmp_zip"; return 1; }
local srt_file
srt_file=$(find "$tmp_dir" -name "*.srt" -o -name "*.ass" -o -name "*.sub" | head -1)
if [[ -n "$srt_file" ]]; then
mv "$srt_file" "$output" && rm -rf "$tmp_dir" "$tmp_zip"
else
rm -rf "$tmp_dir" "$tmp_zip"
return 1
fi
}
# ── Fuzzy search normalization ────────────────────────────────────────────────
# Strips accents, common punctuation, normalizes spaces — tolerates typos in queries
_fuzzy_normalize() {
local q="$1"
# Strip accents using iconv (transliterate to ASCII)
if command -v iconv &>/dev/null; then
q=$(echo "$q" | iconv -f UTF-8 -t ASCII//TRANSLIT 2>/dev/null || echo "$q")
fi
# Collapse common separators (dots, underscores, dashes) to spaces
q=$(echo "$q" | sed -E 's/[._-]+/ /g')
# Remove non-alphanumeric except spaces
q=$(echo "$q" | sed -E 's/[^[:alnum:] ]//g')
# Collapse multiple spaces
q=$(echo "$q" | tr -s ' ')
# Trim
q=$(echo "$q" | sed -E 's/^[[:space:]]+|[[:space:]]+$//g')
echo "$q"
}
# ── Multi-source search ───────────────────────────────────────────────────────
search_all_sources() {
local query="$1" lang="$2" imdb_id="${3:-}" season="${4:-}" episode="${5:-}"
local results=""
local found=false
# Normalize query for fuzzy matching
query=$(_fuzzy_normalize "$query")
debug "Fuzzy-normalized query: '$query'" || true
IFS=',' read -ra source_list <<< "$SOURCES"
for source in "${source_list[@]}"; do
source=$(echo "$source" | tr -d ' ')
printf "${CYAN}[i]${NC} Searching on ${BOLD}%s${NC}...\n" "$source" >&2
local result=""
case "$source" in
opensubtitles-org)
result=$(search_opensubtitles_org "$query" "$lang" "$imdb_id" "$season" "$episode") ;;
podnapisi)
result=$(search_podnapisi "$query" "$lang") ;;
*)
warn "Unknown source: $source" ;;
esac
if [[ -n "$result" ]]; then
found=true
results+="$result"$'\n'
fi
done
if $found; then
echo "$results"
fi
$found
}
# ── Interactive selection ─────────────────────────────────────────────────────
select_subtitle() {
local results="$1"
local entries=()
local i=1
while IFS= read -r line; do
[[ -z "$line" ]] && continue
local name src_name downloads
name=$(echo "$line" | jq -r '.name // "N/A"' 2>/dev/null)
src_name=$(echo "$line" | jq -r '.source // "?"' 2>/dev/null)
downloads=$(echo "$line" | jq -r '.downloads // 0' 2>/dev/null)
[[ -z "$name" || "$name" == "null" ]] && continue
entries+=("$line")
((i++)) || true
done <<< "$results"
if [[ ${#entries[@]} -eq 0 ]]; then
return 1
fi
# Sort entries by downloads (descending) so --auto picks the most downloaded
local sorted_entries=()
while IFS= read -r line; do
[[ -z "$line" ]] && continue
sorted_entries+=("$line")
done <<< "$(printf '%s\n' "${entries[@]}" | jq -s -c 'sort_by(-.downloads)[]' 2>/dev/null)"
if [[ ${#sorted_entries[@]} -gt 0 ]]; then
entries=("${sorted_entries[@]}")
fi
# JSON output mode
if $JSON_OUTPUT; then
printf '['
for ((j=0; j<${#entries[@]}; j++)); do
[[ $j -gt 0 ]] && printf ','
echo "${entries[$j]}"
done
printf ']\n'
return 0 # don't proceed to download in JSON mode
fi
# Auto-select first result
if $AUTO_SELECT; then
debug "Auto-select: first result"
echo "${entries[0]}"
return 0
fi
# Dry-run: just display results (to stderr so $() capture doesn't swallow them)
if $DRY_RUN; then
header "Subtitles found" >&2
for ((j=0; j<${#entries[@]}; j++)); do
local name src_name downloads
name=$(echo "${entries[$j]}" | jq -r '.name // "N/A"' 2>/dev/null)
src_name=$(echo "${entries[$j]}" | jq -r '.source // "?"' 2>/dev/null)
downloads=$(echo "${entries[$j]}" | jq -r '.downloads // 0' 2>/dev/null)
printf " ${BOLD}%2d${NC}) [${CYAN}%-15s${NC}] %s ${YELLOW}(%s DL)${NC}\n" "$((j+1))" "$src_name" "$name" "$downloads" >&2
done
return 1
fi
# Interactive selection (display to stderr so $() capture doesn't swallow them)
header "Subtitles found" >&2
for ((j=0; j<${#entries[@]}; j++)); do
local name src_name downloads
name=$(echo "${entries[$j]}" | jq -r '.name // "N/A"' 2>/dev/null)
src_name=$(echo "${entries[$j]}" | jq -r '.source // "?"' 2>/dev/null)
downloads=$(echo "${entries[$j]}" | jq -r '.downloads // 0' 2>/dev/null)
printf " ${BOLD}%2d${NC}) [${CYAN}%-15s${NC}] %s ${YELLOW}(%s DL)${NC}\n" "$((j+1))" "$src_name" "$name" "$downloads" >&2
done
printf "\n" >&2
local choice
read -rp "$(printf "${BOLD}Choice [1-${#entries[@]}]:${NC} ")" choice
[[ -z "$choice" ]] && choice=1
if [[ "$choice" -ge 1 && "$choice" -le ${#entries[@]} ]] 2>/dev/null; then
echo "${entries[$((choice-1))]}"
else
err "Invalid choice"
return 1
fi
}
# ── Download dispatcher ──────────────────────────────────────────────────────
download_subtitle() {
local entry="$1" output="$2"
local source id
source=$(echo "$entry" | jq -r '.source')
id=$(echo "$entry" | jq -r '.id')
case "$source" in
opensubtitles-org) download_opensubtitles_org "$id" "$output" ;;
podnapisi) download_podnapisi "$id" "$output" ;;
*) err "Unknown source: $source"; return 1 ;;
esac
}
# ── AI Translation ────────────────────────────────────────────────────────────
# Split an SRT file into chunks to avoid exceeding API limits
chunk_srt() {
local file="$1" max_lines="${2:-200}"
local chunk_num=0
local line_count=0
local current_chunk=""
while IFS= read -r line || [[ -n "$line" ]]; do
current_chunk+="$line"$'\n'
((line_count++))
# Split on SRT block boundary (blank line) when we have enough lines
if [[ "$line" =~ ^[[:space:]]*$ ]] && [[ $line_count -ge $max_lines ]]; then
printf '%s' "$current_chunk" > "$CACHE_DIR/chunk_${chunk_num}.srt"
((chunk_num++))
line_count=0
current_chunk=""
fi
done < "$file"
# Last chunk
if [[ -n "$current_chunk" ]]; then
printf '%s' "$current_chunk" > "$CACHE_DIR/chunk_${chunk_num}.srt"
((chunk_num++))
fi
echo "$chunk_num"
}
# Extract text from SRT for LLM translation (text-only, no timestamps)
# Saves timestamp structure to structure_file, numbered text to text_file
# Returns block count via stdout
_srt_extract_for_translation() {
local input="$1" structure_file="$2" text_file="$3"
: > "$structure_file"
: > "$text_file"
local in_text=false timestamp="" text_buf="" block_num=0
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%$'\r'}"
if [[ "$line" =~ ^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}\ --\>\ [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} ]]; then
timestamp="$line"
in_text=true
text_buf=""
elif $in_text && [[ -z "$line" || "$line" =~ ^[[:space:]]*$ ]]; then
if [[ -n "$text_buf" ]]; then
((block_num++)) || true
echo "$timestamp" >> "$structure_file"
echo "${block_num}: ${text_buf}" >> "$text_file"
fi
in_text=false
text_buf=""
elif $in_text && ! [[ "$line" =~ ^[0-9]+[[:space:]]*$ ]]; then
if [[ -n "$text_buf" ]]; then
text_buf="${text_buf} <br> ${line}"
else
text_buf="$line"
fi
fi
done < "$input"
# Handle last block (no trailing newline)
if $in_text && [[ -n "$text_buf" ]]; then
((block_num++)) || true
echo "$timestamp" >> "$structure_file"
echo "${block_num}: ${text_buf}" >> "$text_file"
fi
echo "$block_num"
}
# Rebuild SRT from timestamp structure + translated text lines
_srt_rebuild_from_translation() {
local structure_file="$1" translated_file="$2" output="$3" original_text="${4:-}"
: > "$output"
# Read timestamps
local -a timestamps=()
while IFS= read -r ts; do
timestamps+=("$ts")
done < "$structure_file"
if [[ ${#timestamps[@]} -eq 0 ]]; then
warn "No timestamps found — cannot rebuild SRT"
return 1
fi
# Read original text lines (for fallback if translation is incomplete)
local -a orig_texts=()
if [[ -n "$original_text" && -f "$original_text" ]]; then
while IFS= read -r ol; do
ol="${ol%$'\r'}"
[[ -z "$ol" ]] && continue
local ot="$ol"
if [[ "$ot" =~ ^[0-9]+:[[:space:]](.+)$ ]]; then
ot="${BASH_REMATCH[1]}"
fi
orig_texts+=("$ot")
done < "$original_text"
fi
# Read translated lines, strip number prefix, rebuild SRT
local idx=0
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%$'\r'}"
# Skip empty lines and markdown fences
[[ -z "$line" || "$line" =~ ^\`\`\` ]] && continue
# Strip "N: " prefix if present
local text="$line"
if [[ "$text" =~ ^[0-9]+:[[:space:]](.+)$ ]]; then
text="${BASH_REMATCH[1]}"
fi
if [[ $idx -lt ${#timestamps[@]} ]]; then
printf '%d\n%s\n' "$((idx+1))" "${timestamps[$idx]}" >> "$output"
# Restore <br> markers to actual newlines
echo "$text" | sed 's/ <br> /\n/g' >> "$output"
printf '\n' >> "$output"
fi
((idx++)) || true
done < "$translated_file"
# Fill missing blocks with original text (e.g. LLM truncated output)
if [[ $idx -lt ${#timestamps[@]} ]]; then
warn "Translation returned $idx/$((${#timestamps[@]})) blocks — filling missing with original"
while [[ $idx -lt ${#timestamps[@]} ]]; do
local fallback_text=""
if [[ $idx -lt ${#orig_texts[@]} ]]; then
fallback_text="${orig_texts[$idx]}"
fi
printf '%d\n%s\n' "$((idx+1))" "${timestamps[$idx]}" >> "$output"
if [[ -n "$fallback_text" ]]; then
echo "$fallback_text" | sed 's/ <br> /\n/g' >> "$output"
fi
printf '\n' >> "$output"
((idx++)) || true
done
fi
debug "SRT rebuild: $idx/${#timestamps[@]} blocks" || true
}
# Get max_tokens for a provider, respecting user override
_max_tokens_for() {
local provider="$1"
# User override takes priority
[[ -n "${MAX_TOKENS:-}" ]] && { echo "$MAX_TOKENS"; return; }
# Sensible defaults per provider (output tokens for API calls)
case "$provider" in
claude) echo 16384 ;;
openai) echo 16384 ;;
mistral) echo 16384 ;;
gemini) echo 65536 ;;
*) echo 16384 ;;
esac
}
_translate_prompt() {
cat <<PROMPT
Translate the following numbered subtitle lines from $1 to $2.
Rules:
- Keep the exact numbering format (N: translated text)
- Preserve <br> markers exactly as-is (they are line break markers)
- Translate ONLY the text after the number
- Output one line per input line, nothing else
- Do NOT add any explanation, markdown formatting, or code blocks
PROMPT
}
translate_with_google() {
local input="$1" output="$2" src_lang="$3" target_lang="$4"
if ! command -v trans &>/dev/null; then
err "translate-shell required. Install it: brew install translate-shell"
return 1
fi
# Step 1: Extract only text lines from SRT (skip indices, timestamps, blanks)
# Store line numbers to map back later
local text_file="$CACHE_DIR/trans_text_$$.txt"
local map_file="$CACHE_DIR/trans_map_$$.txt"
: > "$text_file"
: > "$map_file"
local lineno=0
while IFS= read -r line || [[ -n "$line" ]]; do
((lineno++)) || true
line="${line%$'\r'}"
# Skip: blank lines, subtitle indices (bare numbers), timestamps
if [[ -z "$line" ]] || [[ "$line" =~ ^[[:space:]]*[0-9]+[[:space:]]*$ ]] || [[ "$line" =~ ^[0-9]{2}:[0-9]{2}:[0-9]{2} ]]; then
continue
fi
echo "$line" >> "$text_file"
echo "$lineno" >> "$map_file"
done < "$input"
local total_text
total_text=$(wc -l < "$text_file" | tr -d ' ')
info "Google Translate: $total_text text lines to translate"
# Step 2: Split text into chunks and translate in parallel
local chunk_size="${TRANSLATE_CHUNK_SIZE:-80}"
local num_chunks=$(( (total_text + chunk_size - 1) / chunk_size ))
local max_parallel="${TRANSLATE_MAX_PARALLEL:-8}"
info "$num_chunks chunks (max $max_parallel in parallel)"
# Split text file into chunks (PID-suffixed to avoid race conditions)
local chunk_prefix="$CACHE_DIR/trans_chunk_$$"
local i=0
while ((i < num_chunks)); do
local start=$((i * chunk_size + 1))
sed -n "${start},$((start + chunk_size - 1))p" "$text_file" > "${chunk_prefix}_${i}.txt"
((i++)) || true
done
# Translate chunks in parallel
for ((batch=0; batch<num_chunks; batch+=max_parallel)); do
local pids=()
local bend=$((batch + max_parallel))
[[ $bend -gt $num_chunks ]] && bend=$num_chunks
for ((j=batch; j<bend; j++)); do
(
trans -b "${src_lang}:${target_lang}" -i "${chunk_prefix}_${j}.txt" \
> "${chunk_prefix}_${j}_out.txt" 2>/dev/null
) &
pids+=($!)
done
for pid in "${pids[@]}"; do
wait "$pid" || true
done
progress "$bend" "$num_chunks" "Translating"
done
# A failed translate-shell process still leaves an empty redirected file.
# Do not rebuild an apparently successful SRT entirely from source text.
local translated_chunks=0
for ((i=0; i<num_chunks; i++)); do
[[ -s "${chunk_prefix}_${i}_out.txt" ]] && ((translated_chunks++)) || true
done
if [[ $translated_chunks -eq 0 ]]; then
rm -f "$text_file" "$map_file" "${chunk_prefix}"_*.txt 2>/dev/null || true
err "Google Translate produced no translated output"
return 1
fi
# Step 3+4: Map translations back per-chunk
# (avoids line-count drift when trans adds/removes trailing blank lines)
local -a orig_line_nums=()
while IFS= read -r ln; do
orig_line_nums+=("$ln")
done < "$map_file"
local -a replacements=()
local map_idx=0
for ((i=0; i<num_chunks; i++)); do
local chunk_out="${chunk_prefix}_${i}_out.txt"
local chunk_in="${chunk_prefix}_${i}.txt"
if [[ ! -f "$chunk_in" ]]; then
warn "Chunk $((i+1)) input missing — skipping"
local chunk_lines="${TRANSLATE_CHUNK_SIZE:-80}"
((map_idx += chunk_lines)) || true
continue
fi
# Read original chunk lines
local -a orig_lines=()
while IFS= read -r ol; do
orig_lines+=("$ol")
done < "$chunk_in"
# Read translated chunk lines (if available)
local -a trans_lines=()
if [[ -s "$chunk_out" ]]; then
while IFS= read -r tl; do
trans_lines+=("$tl")
done < "$chunk_out"
fi
# Map each input line to its translation (or keep original if missing)
for ((j=0; j<${#orig_lines[@]}; j++)); do
if [[ $map_idx -lt ${#orig_line_nums[@]} ]]; then
if [[ $j -lt ${#trans_lines[@]} ]]; then
replacements[${orig_line_nums[$map_idx]}]="${trans_lines[$j]}"
else
replacements[${orig_line_nums[$map_idx]}]="${orig_lines[$j]}"
fi
fi
((map_idx++)) || true
done
rm -f "$chunk_in" "$chunk_out"
done
# Write output: copy original, replacing text lines
local lineno=0
while IFS= read -r line || [[ -n "$line" ]]; do
((lineno++)) || true
if [[ -n "${replacements[$lineno]+x}" ]]; then
printf '%s\n' "${replacements[$lineno]}"
else
printf '%s\n' "$line"
fi
done < "$input" > "$output"
# Normalize: strip BOM + fix line endings to LF (ffmpeg chokes on mixed CRLF/LF and BOM)
if [[ -s "$output" ]]; then
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' -e '1s/^\xef\xbb\xbf//' -e $'s/\r$//' "$output"
else
sed -i -e '1s/^\xef\xbb\xbf//' -e $'s/\r$//' "$output"
fi
fi
# Cleanup
rm -f "$text_file" "$map_file"
rm -f "$CACHE_DIR"/trans_chunk_$$_*.txt 2>/dev/null || true
}
translate_with_claude_code() {
local input="$1" output="$2" src_lang="$3" target_lang="$4"
local model="${AI_MODEL:-$MODEL_CLAUDE_CODE}"
local effort="${CLAUDE_EFFORT:-low}"
info "Translating with Claude Code ($model, effort $effort)..."
if ! command -v claude &>/dev/null; then
err "claude CLI not installed. Install it: npm install -g @anthropic-ai/claude-code"
return 1
fi
# Build input file on disk (avoid bash variable limitations with large content)
local tmp_input="${CACHE_DIR}/claude_input_$$.txt"
_translate_prompt "$src_lang" "$target_lang" > "$tmp_input"
printf '\n\n' >> "$tmp_input"
cat "$input" >> "$tmp_input"
local claude_err="${output}.claude_err"
local exit_code=0