-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapp.py
More file actions
1534 lines (1257 loc) · 50.5 KB
/
app.py
File metadata and controls
1534 lines (1257 loc) · 50.5 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
import os
import uuid
from flask import Flask, request, jsonify
from flask_cors import CORS
from dotenv import load_dotenv
from werkzeug.utils import secure_filename
# Load environment variables
load_dotenv()
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
# Configure upload folder
UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024 * 1024 # 5GB max
# Import services
from services.transcript import process_transcript, generate_chapters, chat_with_transcript
from services.youtube_live import check_live_status, get_channel_info, get_channel_context
from services.discord_notify import send_discord_notification
from services.shorts import (
process_video_for_shorts,
detect_interesting_moments,
clip_all_moments,
process_clip_to_vertical,
process_clips_to_vertical,
process_clip_to_vertical_with_captions,
process_clips_to_vertical_with_captions,
remove_silence_from_video
)
from services.idea_generator import process_video_for_ideas, generate_video_ideas, chat_with_ideas
from services.channel_improver import analyze_video_for_improvements
from services.audio_mixer import (
check_demucs_status,
separate_video_audio,
process_video_audio
)
from services.bestof import (
get_transcript_for_highlights,
detect_highlight_moments,
create_bestof_compilation,
process_video_for_bestof
)
from services.concat import concatenate_videos
# Environment variable definitions for the config endpoint
ENV_VAR_CONFIG = {
"GEMINI_API_KEY": {
"configured": bool(os.environ.get("GEMINI_API_KEY")),
"required_for": ["transcript"],
"description": "Google Gemini API key for AI chapter generation"
},
"YOUTUBE_API_KEY": {
"configured": bool(os.environ.get("YOUTUBE_API_KEY")),
"required_for": ["live-checker"],
"description": "YouTube Data API v3 key"
},
"YOUTUBE_CHANNEL_ID": {
"configured": bool(os.environ.get("YOUTUBE_CHANNEL_ID")),
"required_for": ["live-checker"],
"description": "Your YouTube channel ID to monitor"
},
"DISCORD_BOT_TOKEN": {
"configured": bool(os.environ.get("DISCORD_BOT_TOKEN")),
"required_for": ["live-checker-notify"],
"description": "Discord bot token for notifications"
},
"DISCORD_YOUTUBE_CHANNEL_ID": {
"configured": bool(os.environ.get("DISCORD_YOUTUBE_CHANNEL_ID")),
"required_for": ["live-checker-notify"],
"description": "Discord channel ID for notifications"
},
"OPENAI_API_KEY": {
"configured": bool(os.environ.get("OPENAI_API_KEY")),
"required_for": ["shorts-captions"],
"description": "OpenAI API key for Whisper transcription (animated captions)"
}
}
@app.route('/api/health', methods=['GET'])
def health():
return jsonify({"status": "ok"})
@app.route('/api/config', methods=['GET'])
def get_config():
"""Returns which environment variables are configured (not the values)."""
return jsonify(ENV_VAR_CONFIG)
# --- Transcript Tool Routes ---
@app.route('/api/transcript', methods=['POST'])
def get_transcript():
"""
Fetch transcript and generate chapters for a YouTube video,
or process a custom transcript.
Request body (YouTube mode):
{
"url": "https://youtube.com/watch?v=...",
"custom_instructions": "..." // Optional style guidance for chapters
}
Request body (Custom mode):
{
"custom_transcript": "...", // Plain text transcript
"custom_instructions": "..." // Optional style guidance for chapters
}
Returns transcript with AI-generated chapters.
"""
if not os.environ.get("GEMINI_API_KEY"):
return jsonify({
"error": "GEMINI_API_KEY not configured",
"missing_env": "GEMINI_API_KEY"
}), 400
data = request.json
video_url = data.get('url')
custom_transcript = data.get('custom_transcript')
custom_instructions = data.get('custom_instructions')
# Custom transcript mode
if custom_transcript:
# Generate chapters using Gemini directly from the text
from services.transcript import generate_chapters
chapters = generate_chapters(custom_transcript, custom_instructions)
return jsonify({
"transcript": [],
"chapters": chapters,
"video_id": None,
"source": "custom"
})
# YouTube mode
if not video_url:
return jsonify({"error": "No URL or custom transcript provided"}), 400
result = process_transcript(video_url, custom_instructions)
if "error" in result:
return jsonify(result), 400
result['source'] = 'youtube'
return jsonify(result)
@app.route('/api/transcript/chat', methods=['POST'])
def transcript_chat():
"""
Chat with Gemini about transcript content using Gemini 2.5 Flash.
Request body:
{
"message": "User's question about the transcript",
"context": "The full transcript text",
"history": [ // Optional - previous messages
{"role": "user", "content": "..."},
{"role": "assistant", "content": "..."}
]
}
Returns AI response about the transcript content.
"""
if not os.environ.get("GEMINI_API_KEY"):
return jsonify({
"error": "GEMINI_API_KEY not configured",
"missing_env": "GEMINI_API_KEY"
}), 400
data = request.json
message = data.get('message')
context = data.get('context')
history = data.get('history', [])
if not message:
return jsonify({"error": "No message provided"}), 400
if not context:
return jsonify({"error": "No transcript context provided"}), 400
result = chat_with_transcript(message, context, history)
if "error" in result:
return jsonify(result), 400
return jsonify(result)
# --- YouTube Live Check Routes ---
@app.route('/api/youtube/live-status', methods=['GET'])
def youtube_live_status():
"""Check if the configured YouTube channel is currently live."""
youtube_api_key = os.environ.get("YOUTUBE_API_KEY")
youtube_channel_id = os.environ.get("YOUTUBE_CHANNEL_ID")
missing = []
if not youtube_api_key:
missing.append("YOUTUBE_API_KEY")
if not youtube_channel_id:
missing.append("YOUTUBE_CHANNEL_ID")
if missing:
return jsonify({
"error": f"Missing environment variables: {', '.join(missing)}",
"missing_env": missing
}), 400
result = check_live_status(youtube_channel_id)
return jsonify(result)
@app.route('/api/youtube/channel-info', methods=['GET'])
def youtube_channel_info():
"""Get info about the configured YouTube channel."""
youtube_api_key = os.environ.get("YOUTUBE_API_KEY")
youtube_channel_id = os.environ.get("YOUTUBE_CHANNEL_ID")
missing = []
if not youtube_api_key:
missing.append("YOUTUBE_API_KEY")
if not youtube_channel_id:
missing.append("YOUTUBE_CHANNEL_ID")
if missing:
return jsonify({
"error": f"Missing environment variables: {', '.join(missing)}",
"missing_env": missing
}), 400
result = get_channel_info(youtube_channel_id)
return jsonify(result)
@app.route('/api/discord/notify', methods=['POST'])
def discord_notify():
"""Send a notification to Discord about live status."""
discord_token = os.environ.get("DISCORD_BOT_TOKEN")
discord_channel = os.environ.get("DISCORD_YOUTUBE_CHANNEL_ID")
missing = []
if not discord_token:
missing.append("DISCORD_BOT_TOKEN")
if not discord_channel:
missing.append("DISCORD_YOUTUBE_CHANNEL_ID")
if missing:
return jsonify({
"error": f"Missing environment variables: {', '.join(missing)}",
"missing_env": missing
}), 400
data = request.json or {}
message = data.get('message', '')
if not message:
# Default: check live status and create message
youtube_channel_id = os.environ.get("YOUTUBE_CHANNEL_ID")
if youtube_channel_id:
live_result = check_live_status(youtube_channel_id)
if live_result.get('is_live') and live_result.get('streams'):
stream = live_result['streams'][0]
message = f"🔴 **Now LIVE!**\n\n**{stream['title']}**\n{stream['url']}"
else:
return jsonify({"error": "Channel is not currently live"}), 400
else:
return jsonify({
"error": "YOUTUBE_CHANNEL_ID not configured",
"missing_env": ["YOUTUBE_CHANNEL_ID"]
}), 400
result = send_discord_notification(discord_token, discord_channel, message)
return jsonify(result)
# --- Shorts Clipper Routes ---
@app.route('/api/shorts/upload', methods=['POST'])
def upload_video():
"""
Upload a video file for processing.
Returns the server path to use for clipping.
"""
if 'video' not in request.files:
return jsonify({"error": "No video file provided"}), 400
file = request.files['video']
if file.filename == '':
return jsonify({"error": "No file selected"}), 400
# Create unique filename to avoid collisions
filename = secure_filename(file.filename)
unique_id = str(uuid.uuid4())[:8]
name, ext = os.path.splitext(filename)
unique_filename = f"{name}_{unique_id}{ext}"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
file.save(filepath)
return jsonify({
"success": True,
"video_path": filepath,
"filename": unique_filename
})
def find_wake_word_timestamps(transcript_text, wake_word):
"""
Find all occurrences of a wake word in a timestamped transcript and return their timestamps.
Args:
transcript_text: Transcript with timestamps in format "[MM:SS] text" or "[H:MM:SS] text"
wake_word: Word/phrase to search for
Returns:
List of timestamps where the wake word appears, e.g., ["5:23", "12:45"]
"""
if not wake_word or not wake_word.strip():
return []
wake_word_lower = wake_word.lower().strip()
timestamps = []
# Parse transcript line by line to find timestamps
import re
# Match timestamps like [0:00], [5:23], [1:23:45]
timestamp_pattern = r'\[(\d+:?\d*:\d+)\]'
lines = transcript_text.split('\n')
current_timestamp = None
for line in lines:
# Extract timestamp from line
match = re.search(timestamp_pattern, line)
if match:
current_timestamp = match.group(1)
# Check if wake word is in this line
if current_timestamp and wake_word_lower in line.lower():
if current_timestamp not in timestamps:
timestamps.append(current_timestamp)
print(f"[wake_word] Found '{wake_word}' at timestamp {current_timestamp}")
print(f"[wake_word] Total: Found '{wake_word}' at {len(timestamps)} unique timestamps")
return timestamps
def generate_wake_word_moments(transcript_text, wake_word, num_clips, timestamps_found):
"""
Use AI to generate clip moments around wake word occurrences.
If there are multiple occurrences, create clips around each.
If there's only one occurrence but multiple clips requested, create variations.
Args:
transcript_text: Full transcript with timestamps
wake_word: The wake word/phrase
num_clips: Number of clips requested
timestamps_found: List of timestamps where wake word appears
Returns:
Dict with 'moments' list
"""
from services.shorts import detect_interesting_moments
if not timestamps_found:
return {"moments": [], "error": f"Wake word '{wake_word}' not found in transcript"}
num_occurrences = len(timestamps_found)
# Build a custom prompt that tells AI exactly where to focus
timestamp_list = ", ".join(timestamps_found)
if num_occurrences == 1:
# Only 1 occurrence - create variations around it
custom_prompt = f"""
The user wants {num_clips} clips around the phrase "{wake_word}" which appears at timestamp {timestamps_found[0]}.
Create {num_clips} different clip variations around this moment, each with different start/end times:
- Mix of short clips (~20-30s), medium clips (~45-60s), and longer clips (~60-90s)
- All clips must include the "{wake_word}" moment
Create exactly {num_clips} clips.
"""
else:
# Multiple occurrences - spread clips across them
custom_prompt = f"""
The user wants {num_clips} clips around the phrase "{wake_word}" which appears at these timestamps: {timestamp_list}
Create {num_clips} clips spread across these occurrences. Don't put all clips on the same timestamp - distribute them.
Each clip should be 30-90 seconds and include one of the "{wake_word}" moments.
Create exactly {num_clips} clips.
"""
print(f"[wake_word] Generating {num_clips} clips around {num_occurrences} occurrences of '{wake_word}'")
# Use the existing moment detection with our custom prompt
result = detect_interesting_moments(
transcript_text,
num_clips=num_clips,
custom_prompt=custom_prompt,
curator_mode=False
)
return result
@app.route('/api/shorts/detect-moments', methods=['POST'])
def detect_moments():
"""
Detect interesting moments from a YouTube video transcript or custom transcript.
Request body (YouTube mode):
{
"url": "https://youtube.com/watch?v=...",
"num_clips": 3, // Optional, 1-10 (or 1-15 in curator mode), default 3
"custom_prompt": "Focus on funny moments...", // Optional custom instructions
"curator_mode": false, // Optional, if true allows up to 15 clips for user selection
"wake_word": "clip that", // Optional, find moments containing this word/phrase
"only_wake_word_clips": false // Optional, if true only return moments with wake word
}
Request body (Custom transcript mode):
{
"custom_transcript": "...", // Plain text transcript
"num_clips": 3,
"custom_prompt": "...",
"curator_mode": false,
"wake_word": "...",
"only_wake_word_clips": false
}
Returns detected moments with timestamps and viral scores.
"""
if not os.environ.get("GEMINI_API_KEY"):
return jsonify({
"error": "GEMINI_API_KEY not configured",
"missing_env": "GEMINI_API_KEY"
}), 400
data = request.json
video_url = data.get('url')
custom_transcript = data.get('custom_transcript')
num_clips = data.get('num_clips', 3)
custom_prompt = data.get('custom_prompt')
curator_mode = data.get('curator_mode', False)
wake_word = data.get('wake_word', '')
only_wake_word_clips = data.get('only_wake_word_clips', False)
# Validate num_clips (15 max in curator mode, 10 otherwise)
max_clips = 15 if curator_mode else 10
try:
num_clips = int(num_clips)
num_clips = max(1, min(max_clips, num_clips))
except (ValueError, TypeError):
num_clips = 3
# Custom transcript mode
if custom_transcript:
# If wake word is specified with only_wake_word_clips, use wake word targeting
if wake_word and only_wake_word_clips:
# Find all timestamps where the wake word appears
timestamps_found = find_wake_word_timestamps(custom_transcript, wake_word)
if not timestamps_found:
return jsonify({
"video_id": None,
"moments": [],
"transcript_preview": custom_transcript[:500] + "..." if len(custom_transcript) > 500 else custom_transcript,
"full_transcript": custom_transcript,
"source": "custom",
"wake_word_filter": {
"wake_word": wake_word,
"only_wake_word_clips": True,
"timestamps_found": [],
"error": f"Wake word '{wake_word}' not found in transcript"
}
})
# Generate moments specifically around the wake word occurrences
moments_result = generate_wake_word_moments(
custom_transcript,
wake_word,
num_clips,
timestamps_found
)
if "error" in moments_result and not moments_result.get("moments"):
return jsonify(moments_result), 400
return jsonify({
"video_id": None,
"moments": moments_result.get('moments', []),
"transcript_preview": custom_transcript[:500] + "..." if len(custom_transcript) > 500 else custom_transcript,
"full_transcript": custom_transcript,
"source": "custom",
"wake_word_filter": {
"wake_word": wake_word,
"only_wake_word_clips": True,
"timestamps_found": timestamps_found,
"occurrences": len(timestamps_found),
"clips_requested": num_clips
}
})
# Standard mode - use AI to find interesting moments
moments_result = detect_interesting_moments(
custom_transcript,
num_clips=num_clips,
custom_prompt=custom_prompt,
curator_mode=curator_mode
)
if "error" in moments_result:
return jsonify(moments_result), 400
return jsonify({
"video_id": None,
"moments": moments_result['moments'],
"transcript_preview": custom_transcript[:500] + "..." if len(custom_transcript) > 500 else custom_transcript,
"full_transcript": custom_transcript,
"source": "custom"
})
# YouTube mode
if not video_url:
return jsonify({"error": "No URL or custom transcript provided"}), 400
# First get the transcript so we can search for wake word
result = process_video_for_shorts(video_url, num_clips=num_clips, custom_prompt=custom_prompt, curator_mode=curator_mode)
if "error" in result:
return jsonify(result), 400
# If wake word is specified with only_wake_word_clips, regenerate moments around wake word
if wake_word and only_wake_word_clips:
transcript = result.get('full_transcript', result.get('transcript_preview', ''))
timestamps_found = find_wake_word_timestamps(transcript, wake_word)
if not timestamps_found:
result['moments'] = []
result['wake_word_filter'] = {
"wake_word": wake_word,
"only_wake_word_clips": True,
"timestamps_found": [],
"error": f"Wake word '{wake_word}' not found in transcript"
}
else:
# Generate moments specifically around the wake word occurrences
moments_result = generate_wake_word_moments(
transcript,
wake_word,
num_clips,
timestamps_found
)
result['moments'] = moments_result.get('moments', [])
result['wake_word_filter'] = {
"wake_word": wake_word,
"only_wake_word_clips": True,
"timestamps_found": timestamps_found,
"occurrences": len(timestamps_found),
"clips_requested": num_clips
}
result['source'] = 'youtube'
return jsonify(result)
@app.route('/api/shorts/clip', methods=['POST'])
def clip_shorts_endpoint():
"""
Clip video segments based on detected moments.
Request body:
{
"video_path": "/path/to/uploaded/video.mp4",
"moments": [...] # Array of moments from detect-moments endpoint
}
Returns clip results with base64 video data for each clip.
"""
data = request.json
video_path = data.get('video_path')
moments = data.get('moments')
if not video_path:
return jsonify({"error": "No video_path provided"}), 400
if not moments:
return jsonify({"error": "No moments provided"}), 400
if not os.path.exists(video_path):
return jsonify({"error": f"Video file not found: {video_path}"}), 400
try:
result = clip_all_moments(video_path, moments)
return jsonify(result)
finally:
# Clean up the uploaded video file after processing
try:
if os.path.exists(video_path):
os.remove(video_path)
except Exception as e:
print(f"Warning: Failed to clean up uploaded file {video_path}: {e}")
@app.route('/api/shorts/process-vertical', methods=['POST'])
def process_vertical_shorts():
"""
Process clipped videos into vertical shorts with stacked or PiP layout.
Optionally adds animated captions if caption_options.enabled is true.
Optionally removes silence/gaps if silence_removal.enabled is true.
Request body:
{
"clips": [...], # Array of clips from /api/shorts/clip endpoint
"regions": [
{"id": "content", "x": 5, "y": 5, "width": 60, "height": 90},
{"id": "webcam", "x": 70, "y": 60, "width": 25, "height": 35}
],
"layout_mode": "stack", # "stack" or "pip"
"layout": { # For stack mode
"topRegionId": "content",
"splitRatio": 0.6
},
"pip_settings": { # For pip mode
"backgroundRegionId": "content",
"overlayRegionId": "webcam",
"position": "bottom-right",
"size": 25,
"shape": "rounded",
"margin": 5
},
"caption_options": { # Optional - for animated captions
"enabled": true,
"words_per_group": 3,
"silence_threshold": 0.5,
"font_size": 56,
"primary_color": "white",
"highlight_color": "yellow",
"highlight_scale": 1.3
},
"silence_removal": { # Optional - remove gaps/pauses
"enabled": false,
"min_gap_duration": 0.4,
"padding": 0.05
},
"all_clip_titles": ["Title for clip 1", "Title for clip 2", ...] # Optional per-clip titles
}
Returns processed vertical shorts as base64 video data.
"""
data = request.json
clips = data.get('clips')
# Support per-clip regions (new) or single regions array (legacy)
all_clip_regions = data.get('all_clip_regions') # Array of region arrays, one per clip
regions = data.get('regions') # Legacy: same regions for all clips
layout_mode = data.get('layout_mode', 'stack')
layout = data.get('layout')
pip_settings = data.get('pip_settings')
caption_options = data.get('caption_options')
silence_removal = data.get('silence_removal')
all_clip_titles = data.get('all_clip_titles', []) # Per-clip titles array
title_font_size = data.get('title_font_size', 48) # Font size for titles
title_highlight_color = data.get('title_highlight_color', '#FBBF24') # Highlight color for {bracketed} text
# Debug logging
print(f"[process-vertical] layout_mode: {layout_mode}")
if all_clip_regions:
print(f"[process-vertical] Using per-clip regions for {len(all_clip_regions)} clips")
if pip_settings:
print(f"[process-vertical] pip_settings: {pip_settings}")
if caption_options:
print(f"[process-vertical] caption_options: {caption_options}")
if silence_removal:
print(f"[process-vertical] silence_removal options: {silence_removal}")
if all_clip_titles and any(all_clip_titles):
print(f"[process-vertical] all_clip_titles: {all_clip_titles}")
if not clips:
return jsonify({"error": "No clips provided"}), 400
# Validate regions - either all_clip_regions or legacy regions
if all_clip_regions:
# Validate per-clip regions
if len(all_clip_regions) != len(clips):
return jsonify({"error": f"Mismatch: {len(clips)} clips but {len(all_clip_regions)} region sets"}), 400
for i, clip_regions in enumerate(all_clip_regions):
if not clip_regions or len(clip_regions) < 2:
return jsonify({"error": f"Two regions required for clip {i+1}"}), 400
elif regions:
# Legacy mode: use same regions for all clips
if len(regions) < 2:
return jsonify({"error": "Two regions required"}), 400
# Convert to per-clip format for uniform processing
all_clip_regions = [regions for _ in clips]
else:
return jsonify({"error": "No regions provided"}), 400
if not layout:
layout = {"topRegionId": "content", "splitRatio": 0.6}
# Check if silence removal or captions are requested (both need OpenAI API)
needs_openai = (
(caption_options and caption_options.get('enabled', False)) or
(silence_removal and silence_removal.get('enabled', False))
)
if needs_openai and not os.environ.get("OPENAI_API_KEY"):
return jsonify({
"error": "OPENAI_API_KEY not configured. Captions and silence removal require OpenAI Whisper API.",
"missing_env": "OPENAI_API_KEY"
}), 400
# Process clips based on layout mode
# Pass all_clip_regions for per-clip region support
if layout_mode == "pip" and pip_settings:
# Import PiP processing function
from services.shorts import process_clips_to_pip, process_clips_to_pip_with_captions
if caption_options and caption_options.get('enabled', False):
result = process_clips_to_pip_with_captions(clips, None, pip_settings, caption_options, all_clip_regions=all_clip_regions, all_clip_titles=all_clip_titles, title_font_size=title_font_size, title_highlight_color=title_highlight_color)
else:
result = process_clips_to_pip(clips, None, pip_settings, all_clip_regions=all_clip_regions, all_clip_titles=all_clip_titles, title_font_size=title_font_size, title_highlight_color=title_highlight_color)
else:
# Stack mode (default)
if caption_options and caption_options.get('enabled', False):
result = process_clips_to_vertical_with_captions(clips, None, layout, caption_options, all_clip_regions=all_clip_regions, all_clip_titles=all_clip_titles, title_font_size=title_font_size, title_highlight_color=title_highlight_color)
else:
result = process_clips_to_vertical(clips, None, layout, all_clip_regions=all_clip_regions, all_clip_titles=all_clip_titles, title_font_size=title_font_size, title_highlight_color=title_highlight_color)
# Apply silence removal if requested (after vertical processing)
if silence_removal and silence_removal.get('enabled', False):
processed_clips = result.get('processed_clips', [])
min_gap = silence_removal.get('min_gap_duration', 0.4)
padding = silence_removal.get('padding', 0.05)
for clip_data in processed_clips:
processed = clip_data.get('processed', {})
if processed.get('success') and processed.get('video_data'):
print(f"[process-vertical] Applying silence removal to clip...")
silence_result = remove_silence_from_video(
processed['video_data'],
min_gap_duration=min_gap,
padding=padding
)
if silence_result.get('success'):
# Update the processed video with silence-removed version
processed['video_data'] = silence_result['video_data']
processed['file_size'] = silence_result.get('file_size', processed.get('file_size'))
processed['silence_removed'] = silence_result.get('silence_removed', False)
processed['gaps_removed'] = silence_result.get('gaps_removed', 0)
processed['time_removed_seconds'] = silence_result.get('time_removed_seconds', 0)
else:
# Log error but don't fail the whole request
print(f"[process-vertical] Silence removal failed: {silence_result.get('error')}")
processed['silence_removal_error'] = silence_result.get('error')
return jsonify(result)
# --- Video Idea Generator Routes ---
@app.route('/api/ideas/channel-context', methods=['POST'])
def fetch_channel_context():
"""
Fetch channel info for idea generation context.
Request body:
{
"channel_url": "https://youtube.com/@handle"
}
Returns channel name, description, and recent video titles.
"""
if not os.environ.get("YOUTUBE_API_KEY"):
return jsonify({
"error": "YOUTUBE_API_KEY not configured",
"missing_env": "YOUTUBE_API_KEY"
}), 400
data = request.json
channel_url = data.get('channel_url')
if not channel_url:
return jsonify({"error": "No channel URL provided"}), 400
result = get_channel_context(channel_url, num_recent_videos=2)
if "error" in result:
return jsonify(result), 400
return jsonify(result)
@app.route('/api/ideas/generate', methods=['POST'])
def generate_ideas():
"""
Generate video and shorts ideas from a YouTube video transcript.
Request body:
{
"url": "https://youtube.com/watch?v=...",
"num_video_ideas": 10, // Optional, 1-10, default 10
"num_shorts_ideas": 10, // Optional, 1-10, default 10
"custom_instructions": "...", // Optional style guidance
"channel_context": { // Optional channel info
"name": "Channel Name",
"description": "Channel description",
"recent_videos": [{"title": "..."}]
}
}
Returns generated content ideas.
"""
if not os.environ.get("GEMINI_API_KEY"):
return jsonify({
"error": "GEMINI_API_KEY not configured",
"missing_env": "GEMINI_API_KEY"
}), 400
data = request.json
video_url = data.get('url')
num_video_ideas = data.get('num_video_ideas', 10)
num_shorts_ideas = data.get('num_shorts_ideas', 10)
custom_instructions = data.get('custom_instructions')
channel_context = data.get('channel_context')
# Validate counts
try:
num_video_ideas = max(1, min(10, int(num_video_ideas)))
num_shorts_ideas = max(1, min(10, int(num_shorts_ideas)))
except (ValueError, TypeError):
num_video_ideas = 10
num_shorts_ideas = 10
if not video_url:
return jsonify({"error": "No URL provided"}), 400
result = process_video_for_ideas(
video_url,
num_video_ideas=num_video_ideas,
num_shorts_ideas=num_shorts_ideas,
custom_instructions=custom_instructions,
channel_context=channel_context
)
if "error" in result and "missing_env" not in result:
return jsonify(result), 400
return jsonify(result)
@app.route('/api/ideas/regenerate', methods=['POST'])
def regenerate_ideas():
"""
Regenerate ideas from an existing transcript.
Request body:
{
"transcript": "...", // Full transcript text
"num_video_ideas": 10,
"num_shorts_ideas": 10,
"custom_instructions": "..."
}
"""
if not os.environ.get("GEMINI_API_KEY"):
return jsonify({
"error": "GEMINI_API_KEY not configured",
"missing_env": "GEMINI_API_KEY"
}), 400
data = request.json
transcript = data.get('transcript')
num_video_ideas = data.get('num_video_ideas', 10)
num_shorts_ideas = data.get('num_shorts_ideas', 10)
custom_instructions = data.get('custom_instructions')
if not transcript:
return jsonify({"error": "No transcript provided"}), 400
# Validate counts
try:
num_video_ideas = max(1, min(10, int(num_video_ideas)))
num_shorts_ideas = max(1, min(10, int(num_shorts_ideas)))
except (ValueError, TypeError):
num_video_ideas = 10
num_shorts_ideas = 10
result = generate_video_ideas(
transcript,
num_video_ideas=num_video_ideas,
num_shorts_ideas=num_shorts_ideas,
custom_instructions=custom_instructions
)
if "error" in result:
return jsonify(result), 400
return jsonify(result)
@app.route('/api/ideas/chat', methods=['POST'])
def ideas_chat():
"""
Chat with Gemini about video ideas using Gemini 2.5 Flash.
Request body:
{
"message": "User's question",
"context": "Transcript and ideas context",
"history": [...] // Optional previous messages
}
"""
if not os.environ.get("GEMINI_API_KEY"):
return jsonify({
"error": "GEMINI_API_KEY not configured",
"missing_env": "GEMINI_API_KEY"
}), 400
data = request.json
message = data.get('message')
context = data.get('context')
history = data.get('history', [])
if not message:
return jsonify({"error": "No message provided"}), 400
if not context:
return jsonify({"error": "No context provided"}), 400
result = chat_with_ideas(message, context, history)
if "error" in result:
return jsonify(result), 400
return jsonify(result)
@app.route('/api/shorts/process-single', methods=['POST'])
def process_single_vertical():
"""
Process a single video into a vertical short.
Request body:
{
"video_data": "base64...", # Base64 encoded video
"regions": [...],
"layout": {...}
}
Returns processed vertical short as base64.
"""
data = request.json
video_data = data.get('video_data')
regions = data.get('regions')
layout = data.get('layout')
if not video_data:
return jsonify({"error": "No video_data provided"}), 400
if not regions or len(regions) < 2:
return jsonify({"error": "Two regions required"}), 400
if not layout:
layout = {"topRegionId": "content", "splitRatio": 0.6}
result = process_clip_to_vertical(video_data, regions, layout)
return jsonify(result)
# --- Channel Improver Routes ---
@app.route('/api/channel/analyze', methods=['POST'])
def analyze_channel():
"""
Analyze a video transcript and provide improvement suggestions
based on the creator's channel context and goals.
Request body:
{
"url": "https://youtube.com/watch?v=...",
"channel_context": {
"goal": "marketing my products", // Primary goal
"channel_description": "I make coding tutorials",
"target_audience": "beginner developers",
"recent_titles": ["Title 1", "Title 2"], // Optional
"improvement_focus": ["content", "branding"] // Optional
}
}
Returns categorized improvement suggestions.
"""
if not os.environ.get("GEMINI_API_KEY"):
return jsonify({
"error": "GEMINI_API_KEY not configured",
"missing_env": "GEMINI_API_KEY"
}), 400
data = request.json
video_url = data.get('url')
channel_context = data.get('channel_context', {})
if not video_url:
return jsonify({"error": "No URL provided"}), 400