File size: 36,924 Bytes
d9ccbf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re
import uuid
import json
import time
import random
import shutil
import requests
import asyncio
import gradio as gr
from pathlib import Path
import edge_tts
from gtts import gTTS
import numpy as np
import g4f
from g4f.client import Client
import assemblyai as aai
from moviepy.editor import *
from moviepy.video.fx.all import crop
from moviepy.audio.fx.all import volumex
from concurrent.futures import ThreadPoolExecutor

# Constants
TEMP_DIR = Path("temp")
OUTPUT_DIR = Path("output")
MUSIC_DIR = Path("music")

# Ensure directories exist
TEMP_DIR.mkdir(exist_ok=True)
OUTPUT_DIR.mkdir(exist_ok=True)
MUSIC_DIR.mkdir(exist_ok=True)

# Add a sample music file if none exists
if not list(MUSIC_DIR.glob("*.mp3")):
    # Create a simple silent audio file as placeholder
    silent_clip = AudioClip(lambda t: 0, duration=10)
    silent_clip.write_audiofile(MUSIC_DIR / "silence.mp3", fps=44100)

# Utility functions
def info(msg):
    return gr.Info(msg)

def warning(msg):
    return gr.Warning(msg)

def error(msg):
    return gr.Error(msg)

def generate_id():
    return str(uuid.uuid4())

def choose_random_music():
    music_files = list(MUSIC_DIR.glob("*.mp3"))
    if not music_files:
        return MUSIC_DIR / "silence.mp3"
    return random.choice(music_files)

def parse_model(model_name):
    """Parse model name for g4f"""
    if model_name == "gpt-4":
        return g4f.models.gpt_4
    elif model_name == "gpt-3.5-turbo":
        return g4f.models.gpt_35_turbo
    else:
        return model_name

class YouTubeGenerator:
    def __init__(self):
        self.reset()
    
    def reset(self):
        """Reset all generation state"""
        self.subject = ""
        self.script = ""
        self.metadata = {"title": "", "description": ""}
        self.image_prompts = []
        self.images = []
        self.tts_path = ""
        self.video_path = ""
    
    def clean_temp_files(self, keep_video=False):
        """Clean temporary files except final video if requested"""
        for img in self.images:
            if os.path.exists(img):
                os.remove(img)
        
        if self.tts_path and os.path.exists(self.tts_path):
            os.remove(self.tts_path)
            
        if not keep_video and self.video_path and os.path.exists(self.video_path):
            os.remove(self.video_path)
    
    def generate_response(self, prompt, model="gpt-4"):
        """Generate response using G4F"""
        try:
            response = g4f.ChatCompletion.create(
                model=parse_model(model),
                messages=[{"role": "user", "content": prompt}]
            )
            return response
        except Exception as e:
            error(f"Error generating response: {str(e)}")
            return ""

    def generate_topic(self, niche):
        """Generate a topic based on the niche"""
        prompt = f"Please generate a specific video idea that takes about the following topic: {niche}. Make it exactly one sentence. Only return the topic, nothing else."
        completion = self.generate_response(prompt)
        
        if not completion:
            raise ValueError("Failed to generate topic")
            
        self.subject = completion
        return completion

    def generate_script(self, subject, language):
        """Generate video script based on subject"""
        prompt = f"""
        Generate a script for youtube shorts video, depending on the subject of the video.

        The script is to be returned as a string with the specified number of paragraphs.

        Here is an example of a string:
        "This is an example string."

        Do not under any circumstance reference this prompt in your response.

        Get straight to the point, don't start with unnecessary things like, "welcome to this video".

        Obviously, the script should be related to the subject of the video.
        
        YOU MUST NOT INCLUDE ANY TYPE OF MARKDOWN OR FORMATTING IN THE SCRIPT, NEVER USE A TITLE.
        YOU MUST WRITE THE SCRIPT IN THE LANGUAGE SPECIFIED IN [LANGUAGE].
        ONLY RETURN THE RAW CONTENT OF THE SCRIPT. DO NOT INCLUDE "VOICEOVER", "NARRATOR" OR SIMILAR INDICATORS OF WHAT SHOULD BE SPOKEN AT THE BEGINNING OF EACH PARAGRAPH OR LINE. YOU MUST NOT MENTION THE PROMPT, OR ANYTHING ABOUT THE SCRIPT ITSELF. ALSO, NEVER TALK ABOUT THE AMOUNT OF PARAGRAPHS OR LINES. JUST WRITE THE SCRIPT
        
        Subject: {subject}
        Language: {language}
        """
        completion = self.generate_response(prompt)
        
        # Apply regex to remove *
        completion = re.sub(r"\*", "", completion)
        
        if not completion:
            raise ValueError("The generated script is empty")
        
        if len(completion) > 5000:
            raise ValueError("Generated script is too long (>5000 chars)")
        
        self.script = completion
        return completion

    def generate_metadata(self, subject):
        """Generate title and description"""
        title_prompt = f"Please generate a YouTube Video Title for the following subject, including hashtags: {subject}. Only return the title, nothing else. Limit the title under 100 characters."
        title = self.generate_response(title_prompt)
        
        if len(title) > 100:
            title = title[:97] + "..."
        
        desc_prompt = f"Please generate a YouTube Video Description for the following script: {self.script}. Only return the description, nothing else."
        description = self.generate_response(desc_prompt)
        
        self.metadata = {
            "title": title,
            "description": description
        }
        
        return self.metadata

    def generate_prompts(self, subject, script):
        """Generate image prompts for the script"""
        n_prompts = 5
        prompt = f"""
        Generate {n_prompts} Image Prompts for AI Image Generation,
        depending on the subject of a video.
        Subject: {subject}

        The image prompts are to be returned as
        a JSON-Array of strings.

        Each search term should consist of a full sentence,
        always add the main subject of the video.

        Be emotional and use interesting adjectives to make the
        Image Prompt as detailed as possible.
        
        YOU MUST ONLY RETURN THE JSON-ARRAY OF STRINGS.
        YOU MUST NOT RETURN ANYTHING ELSE. 
        YOU MUST NOT RETURN THE SCRIPT.
        
        The search terms must be related to the subject of the video.
        Here is an example of a JSON-Array of strings:
        ["image prompt 1", "image prompt 2", "image prompt 3"]

        For context, here is the full text:
        {script}
        """
        
        completion = str(self.generate_response(prompt, model="gpt-4"))
        completion = completion.replace("```json", "").replace("```", "")
        
        image_prompts = []
        
        try:
            # First try to parse as JSON directly
            image_prompts = json.loads(completion)
            if isinstance(image_prompts, dict) and "image_prompts" in image_prompts:
                image_prompts = image_prompts["image_prompts"]
        except Exception:
            # If that fails, try to extract array from the text
            try:
                # Get everything between [ and ], and turn it into a list
                r = re.compile(r"\[.*\]", re.DOTALL)
                matches = r.findall(completion)
                if matches:
                    image_prompts = json.loads(matches[0])
            except Exception as e:
                raise ValueError(f"Failed to parse image prompts: {str(e)}")
        
        # Ensure we have prompts and they're in the right format
        if not image_prompts or not isinstance(image_prompts, list):
            raise ValueError("No valid image prompts were generated")
            
        # Limit to 5 prompts
        image_prompts = image_prompts[:5]
        
        self.image_prompts = image_prompts
        return image_prompts

    def generate_image(self, prompt, provider="g4f", model="sdxl-turbo"):
        """Generate an image using the specified provider"""
        try:
            if provider == "g4f":
                client = Client()
                response = client.images.generate(
                    model=model,
                    prompt=prompt,
                    response_format="url"
                )
                
                if response and response.data and len(response.data) > 0:
                    image_url = response.data[0].url
                    image_response = requests.get(image_url)
                    
                    if image_response.status_code == 200:
                        image_path = str(TEMP_DIR / f"{generate_id()}.png")
                        with open(image_path, "wb") as f:
                            f.write(image_response.content)
                        self.images.append(image_path)
                        return image_path
                    
                raise ValueError(f"Failed to download image from {image_url}")
                        
            elif provider == "prodia":
                s = requests.Session()
                headers = {
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
                }
                
                # Generate job
                resp = s.get(
                    "https://api.prodia.com/generate",
                    params={
                        "new": "true",
                        "prompt": prompt,
                        "model": model,
                        "negative_prompt": "verybadimagenegative_v1.3",
                        "steps": "20",
                        "cfg": "7",
                        "seed": random.randint(1, 10000),
                        "sample": "DPM++ 2M Karras",
                        "aspect_ratio": "square"
                    },
                    headers=headers
                )
                
                job_id = resp.json().get('job')
                if not job_id:
                    raise ValueError("Failed to get job ID from Prodia")
                
                # Wait for job to complete
                for _ in range(30):  # Timeout after 30 attempts (150 seconds)
                    time.sleep(5)
                    status = s.get(f"https://api.prodia.com/job/{job_id}", headers=headers).json()
                    if status.get("status") == "succeeded":
                        img_data = s.get(f"https://images.prodia.xyz/{job_id}.png?download=1", headers=headers).content
                        image_path = str(TEMP_DIR / f"{generate_id()}.png")
                        with open(image_path, "wb") as f:
                            f.write(img_data)
                        self.images.append(image_path)
                        return image_path
                
                raise ValueError("Prodia image generation timed out")
                
            elif provider == "pollinations":
                response = requests.get(f"https://image.pollinations.ai/prompt/{prompt}{random.randint(1,10000)}")
                if response.status_code == 200:
                    image_path = str(TEMP_DIR / f"{generate_id()}.png")
                    with open(image_path, "wb") as f:
                        f.write(response.content)
                    self.images.append(image_path)
                    return image_path
                else:
                    raise ValueError(f"Pollinations request failed: {response.status_code}")
                    
            else:
                raise ValueError(f"Unsupported image provider: {provider}")
                
        except Exception as e:
            raise ValueError(f"Image generation failed: {str(e)}")

    async def generate_edge_tts(self, text, voice):
        """Generate speech using Edge TTS"""
        try:
            audio_path = str(TEMP_DIR / f"{generate_id()}.mp3")
            communicate = edge_tts.Communicate(text, voice)
            await communicate.save(audio_path)
            self.tts_path = audio_path
            return audio_path
        except Exception as e:
            # Try an alternative voice if the specified one fails
            try:
                fallback_voice = "en-US-ChristopherNeural"
                communicate = edge_tts.Communicate(text, fallback_voice)
                audio_path = str(TEMP_DIR / f"{generate_id()}.mp3")
                await communicate.save(audio_path)
                self.tts_path = audio_path
                return audio_path
            except Exception as nested_e:
                raise ValueError(f"Edge TTS failed with both voices: {str(e)}, fallback: {str(nested_e)}")

    def generate_gtts(self, text, lang='en'):
        """Generate speech using Google TTS"""
        try:
            audio_path = str(TEMP_DIR / f"{generate_id()}.mp3")
            tts = gTTS(text=text, lang=lang, slow=False)
            tts.save(audio_path)
            self.tts_path = audio_path
            return audio_path
        except Exception as e:
            raise ValueError(f"Google TTS failed: {str(e)}")

    def generate_speech(self, text, engine="edge", voice="en-US-ChristopherNeural"):
        """Generate speech from text using selected engine"""
        # Clean text
        text = re.sub(r'[^\w\s.?!]', '', text)
        
        if engine == "edge":
            # Edge TTS is async, so we need to run it in an event loop
            return asyncio.run(self.generate_edge_tts(text, voice))
        elif engine == "gtts":
            return self.generate_gtts(text, lang=voice)
        else:
            raise ValueError(f"Unsupported TTS engine: {engine}")

    def generate_subtitles(self, audio_path, api_key):
        """Generate word-highlighted subtitles"""
        try:
            # Set API key
            aai.settings.api_key = api_key
            
            # Configure transcription
            config = aai.TranscriptionConfig(
                speaker_labels=False, 
                word_boost=[], 
                format_text=True
            )
            
            # Create transcriber and transcribe audio
            transcriber = aai.Transcriber(config=config)
            transcript = transcriber.transcribe(audio_path)
            
            # Process word-level information
            wordlevel_info = []
            for word in transcript.words:
                word_data = {
                    "word": word.text.strip(),
                    "start": word.start / 1000.0,
                    "end": word.end / 1000.0
                }
                wordlevel_info.append(word_data)
            
            # Split text into lines based on character count and duration
            MAX_CHARS = 30
            MAX_DURATION = 3.0
            MAX_GAP = 2.5
            
            subtitles = []
            line = []
            line_duration = 0
            
            for idx, word_data in enumerate(wordlevel_info):
                word = word_data["word"]
                start = word_data["start"]
                end = word_data["end"]
                
                line.append(word_data)
                line_duration += end - start
                temp = " ".join(item["word"] for item in line)
                new_line_chars = len(temp)
                duration_exceeded = line_duration > MAX_DURATION
                chars_exceeded = new_line_chars > MAX_CHARS
                
                if idx > 0:
                    gap = word_data['start'] - wordlevel_info[idx - 1]['end']
                    maxgap_exceeded = gap > MAX_GAP
                else:
                    maxgap_exceeded = False
                
                # Check if any condition is exceeded to finalize the current line
                if duration_exceeded or chars_exceeded or maxgap_exceeded:
                    if line:
                        subtitle_line = {
                            "text": " ".join(item["word"] for item in line),
                            "start": line[0]["start"],
                            "end": line[-1]["end"],
                            "words": line
                        }
                        subtitles.append(subtitle_line)
                        line = []
                        line_duration = 0
            
            # Add the remaining words as the last subtitle line if any
            if line:
                subtitle_line = {
                    "text": " ".join(item["word"] for item in line),
                    "start": line[0]["start"],
                    "end": line[-1]["end"],
                    "words": line
                }
                subtitles.append(subtitle_line)
            
            # Create subtitle clips
            all_subtitle_clips = []
            
            # Define formatting constants
            FONT = 'Helvetica-Bold'
            FONTSIZE = 80
            COLOR = 'white'
            BG_COLOR = 'blue'
            FRAME_SIZE = (1080, 1920)
            
            for subtitle in subtitles:
                full_duration = subtitle['end'] - subtitle['start']
                
                word_clips = []
                xy_textclips_positions = []
                
                # Dynamic vertical positioning (moved to bottom)
                frame_width, frame_height = FRAME_SIZE
                x_pos = 0
                y_pos = frame_height * 0.85  # Position at 85% of frame height
                x_buffer = frame_width * 1 / 10
                y_buffer = 10  # Small vertical buffer
                
                line_height = 0
                current_line_height = 0
                
                for index, wordJSON in enumerate(subtitle['words']):
                    duration = wordJSON['end'] - wordJSON['start']
                    word_clip = TextClip(wordJSON['word'], font=FONT, fontsize=FONTSIZE, color=COLOR).set_start(subtitle['start']).set_duration(full_duration)
                    word_width, word_height = word_clip.size
                    
                    # Track line height for multi-line support
                    line_height = max(line_height, word_height)
                    
                    # Check if the current word exceeds the frame width, move to the next line
                    if x_pos + word_width > frame_width - 2 * x_buffer:
                        x_pos = 0
                        y_pos += line_height + y_buffer
                        current_line_height += line_height + y_buffer
                    
                    # Store the position and other details for highlighting
                    xy_textclips_positions.append({
                        "x_pos": x_pos + x_buffer,
                        "y_pos": y_pos + y_buffer,
                        "width": word_width,
                        "height": word_height,
                        "word": wordJSON['word'],
                        "start": wordJSON['start'],
                        "end": wordJSON['end'],
                        "duration": duration
                    })
                    
                    # Set the position of the word clip
                    word_clip = word_clip.set_position((x_pos + x_buffer, y_pos + y_buffer))
                    word_clips.append(word_clip)
                    x_pos = x_pos + word_width + 10
                
                # Create highlighted word clips
                for highlight_word in xy_textclips_positions:
                    word_clip_highlight = TextClip(highlight_word['word'], font=FONT, fontsize=FONTSIZE, color=COLOR, bg_color=BG_COLOR).set_start(highlight_word['start']).set_duration(highlight_word['duration'])
                    word_clip_highlight = word_clip_highlight.set_position((highlight_word['x_pos'], highlight_word['y_pos']))
                    word_clips.append(word_clip_highlight)
                
                # Add all word clips to the list of subtitle clips
                all_subtitle_clips.extend(word_clips)
            
            return all_subtitle_clips
        except Exception as e:
            print(f"Subtitle generation error: {str(e)}")
            return []  # Return empty list if subtitles fail

    def combine_video(self, include_subtitles=True, subtitles_api_key=""):
        """Combine all elements into final video"""
        try:
            output_path = str(TEMP_DIR / f"{generate_id()}.mp4")
            
            # Load audio
            tts_clip = AudioFileClip(self.tts_path)
            max_duration = tts_clip.duration
            
            # Calculate duration per image
            req_dur = max_duration / len(self.images)
            
            # Create video clips from images
            clips = []
            tot_dur = 0
            
            while tot_dur < max_duration:
                for image_path in self.images:
                    clip = ImageClip(image_path)
                    clip.duration = req_dur
                    clip = clip.set_fps(30)
                    
                    # Intelligent cropping for different aspect ratios
                    aspect_ratio = 9/16  # Standard vertical video ratio
                    if clip.w / clip.h < aspect_ratio:
                        clip = crop(
                            clip, 
                            width=clip.w, 
                            height=round(clip.w / aspect_ratio), 
                            x_center=clip.w / 2, 
                            y_center=clip.h / 2
                        )
                    else:
                        clip = crop(
                            clip, 
                            width=round(aspect_ratio * clip.h), 
                            height=clip.h, 
                            x_center=clip.w / 2, 
                            y_center=clip.h / 2
                        )
                    
                    clip = clip.resize((1080, 1920))  # Hardcoded frame size for shorts
                    
                    clips.append(clip)
                    tot_dur += clip.duration
                    
                    # Break if we have enough duration
                    if tot_dur >= max_duration:
                        break
            
            # Concatenate all clips
            final_clip = concatenate_videoclips(clips)
            final_clip = final_clip.set_fps(30)
            
            # Add background music
            random_music = choose_random_music()
            random_music_clip = AudioFileClip(str(random_music))
            random_music_clip = random_music_clip.fx(volumex, 0.1)
            random_music_clip = random_music_clip.set_duration(max_duration)
            
            # Generate subtitles if requested
            word_highlighted_clips = []
            if include_subtitles and subtitles_api_key:
                word_highlighted_clips = self.generate_subtitles(self.tts_path, subtitles_api_key)
            
            # Combine audio
            comp_audio = CompositeAudioClip([
                tts_clip,
                random_music_clip
            ])
            
            # Set audio and duration
            final_clip = final_clip.set_audio(comp_audio)
            final_clip = final_clip.set_duration(tts_clip.duration)
            
            # Add subtitles if we have them
            if word_highlighted_clips:
                final_clip = CompositeVideoClip([final_clip] + word_highlighted_clips)
            
            # Write video file
            final_clip.write_videofile(output_path, threads=4)
            
            # Save to output directory with a more descriptive name
            safe_title = re.sub(r'[^\w\s-]', '', self.metadata["title"])
            safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-_')
            final_output = str(OUTPUT_DIR / f"{safe_title}_{int(time.time())}.mp4")
            shutil.copy2(output_path, final_output)
            
            self.video_path = final_output
            return final_output
        except Exception as e:
            raise ValueError(f"Video generation failed: {str(e)}")

def generate_full_pipeline(
    niche, 
    language, 
    img_provider, 
    img_model, 
    tts_engine, 
    tts_voice, 
    include_subtitles, 
    assemblyai_key,
    progress=gr.Progress()
):
    progress(0, desc="Initializing")
    generator = YouTubeGenerator()
    
    try:
        # Step 1: Generate topic
        progress(0.05, desc="Generating topic")
        topic = generator.generate_topic(niche)
        
        # Step 2: Generate script
        progress(0.1, desc="Generating script")
        script = generator.generate_script(topic, language)
        
        # Step 3: Generate metadata
        progress(0.15, desc="Generating metadata")
        metadata = generator.generate_metadata(topic)
        
        # Step 4: Generate image prompts
        progress(0.2, desc="Generating image prompts")
        image_prompts = generator.generate_prompts(topic, script)
        
        # Step 5: Generate images
        progress(0.3, desc="Generating images")
        images = []
        total_images = len(image_prompts)
        
        for i, prompt in enumerate(image_prompts):
            progress(0.3 + (0.3 * i/total_images), desc=f"Generating image {i+1}/{total_images}")
            img_path = generator.generate_image(prompt, provider=img_provider, model=img_model)
            images.append(img_path)
        
        # Step 6: Generate speech
        progress(0.6, desc="Generating speech")
        tts_path = generator.generate_speech(script, engine=tts_engine, voice=tts_voice)
        
        # Step 7: Combine into video
        progress(0.8, desc="Creating video")
        video_path = generator.combine_video(
            include_subtitles=include_subtitles,
            subtitles_api_key=assemblyai_key if include_subtitles else ""
        )
        
        progress(1.0, desc="Complete!")
        
        return {
            "topic": topic,
            "script": script,
            "title": metadata["title"],
            "description": metadata["description"],
            "image_prompts": "\n\n".join([f"{i+1}. {prompt}" for i, prompt in enumerate(image_prompts)]),
            "images": images,
            "audio": tts_path,
            "video": video_path,
            "video_html": f'
'
        }
    
    except Exception as e:
        generator.clean_temp_files()
        error_msg = str(e)
        return {
            "topic": f"ERROR: {error_msg}",
            "script": "",
            "title": "",
            "description": "",
            "image_prompts": "",
            "images": [],
            "audio": None,
            "video": None,
            "video_html": f'
Video generation failed: {error_msg}
'
        }

def ui_component():
    # Define UI components
    with gr.Blocks(theme=gr.themes.Soft()) as app:
        gr.Markdown("# YouTube Shorts Generator")
        gr.Markdown("Generate complete YouTube Shorts videos with AI")
        
        with gr.Tabs():
            with gr.TabItem("Generate Video"):
                with gr.Row():
                    with gr.Column():
                        # Input parameters
                        niche_input = gr.Textbox(label="Video Niche/Topic", placeholder="Historical Facts", value="Historical Facts")
                        language_input = gr.Dropdown(
                            label="Language", 
                            choices=["English", "Spanish", "French", "German", "Italian", "Portuguese", "Russian", "Japanese", "Chinese", "Korean", "Arabic"],
                            value="English"
                        )
                        
                        with gr.Accordion("Image Generation Settings", open=False):
                            img_provider = gr.Dropdown(
                                label="Image Provider", 
                                choices=["g4f", "prodia", "pollinations"],
                                value="g4f"
                            )
                            
                            img_model = gr.Dropdown(
                                label="Image Model",
                                choices=["sdxl-turbo", "sdxl", "stable-diffusion-3", "kandinsky-2.2", "midjourney"],
                                value="sdxl-turbo"
                            )
                            
                        with gr.Accordion("TTS Settings", open=False):
                            tts_engine = gr.Dropdown(
                                label="TTS Engine",
                                choices=["edge", "gtts"],
                                value="edge"
                            )
                            
                            tts_voice = gr.Dropdown(
                                label="TTS Voice",
                                choices=["en-US-ChristopherNeural", "en-US-GuyNeural", "en-US-JennyNeural", "en-US-AriaNeural", "en-GB-SoniaNeural", "en"],
                                value="en-US-ChristopherNeural"
                            )
                        
                        with gr.Accordion("Subtitle Settings", open=False):
                            include_subtitles = gr.Checkbox(label="Generate Word-Level Subtitles", value=False)
                            assemblyai_key = gr.Textbox(
                                label="AssemblyAI API Key (required for subtitles)", 
                                placeholder="Your AssemblyAI API Key",
                                type="password"
                            )
                        
                        generate_btn = gr.Button("Generate Video", variant="primary")
                    
                    with gr.Column():
                        # Output display
                        with gr.Accordion("Generated Content", open=True):
                            topic_output = gr.Textbox(label="Generated Topic")
                            script_output = gr.Textbox(label="Generated Script", lines=10)
                            title_output = gr.Textbox(label="Video Title")
                            description_output = gr.Textbox(label="Video Description", lines=5)
                        
                        with gr.Accordion("Generated Assets", open=True):
                            prompts_output = gr.Textbox(label="Image Prompts", lines=5)
                            gallery_output = gr.Gallery(label="Generated Images")
                            audio_output = gr.Audio(label="Generated Speech")
                            video_output = gr.Video(label="Final Video")
                            
                            video_html = gr.HTML(label="Video Player")
                
                # Connect button to function
                generate_btn.click(
                    generate_full_pipeline,
                    inputs=[
                        niche_input, 
                        language_input, 
                        img_provider, 
                        img_model, 
                        tts_engine, 
                        tts_voice, 
                        include_subtitles, 
                        assemblyai_key
                    ],
                    outputs={
                        "topic": topic_output,
                        "script": script_output,
                        "title": title_output,
                        "description": description_output,
                        "image_prompts": prompts_output,
                        "images": gallery_output,
                        "audio": audio_output,
                        "video": video_output,
                        "video_html": video_html
                    }
                )
            
            with gr.TabItem("Settings"):
                gr.Markdown("## Advanced Settings")
                
                with gr.Accordion("Storage Settings", open=True):
                    temp_dir = gr.Textbox(label="Temporary Directory", value=str(TEMP_DIR))
                    output_dir = gr.Textbox(label="Output Directory", value=str(OUTPUT_DIR))
                    music_dir = gr.Textbox(label="Music Directory", value=str(MUSIC_DIR))
                    
                    def update_dirs(temp, output, music):
                        global TEMP_DIR, OUTPUT_DIR, MUSIC_DIR
                        TEMP_DIR = Path(temp)
                        OUTPUT_DIR = Path(output)
                        MUSIC_DIR = Path(music)
                        
                        # Ensure directories exist
                        TEMP_DIR.mkdir(exist_ok=True)
                        OUTPUT_DIR.mkdir(exist_ok=True)
                        MUSIC_DIR.mkdir(exist_ok=True)
                        
                        return f"Directories updated: {temp}, {output}, {music}"
                    
                    update_dirs_btn = gr.Button("Update Directories")
                    dirs_status = gr.Textbox(label="Status")
                    
                    update_dirs_btn.click(
                        update_dirs,
                        inputs=[temp_dir, output_dir, music_dir],
                        outputs=dirs_status
                    )
                
                with gr.Accordion("Add Background Music", open=True):
                    music_file = gr.File(label="Upload Music File (MP3)")
                    
                    def add_music(file):
                        if file is None:
                            return "No file selected"
                        
                        try:
                            filename = os.path.basename(file.name)
                            dest_path = MUSIC_DIR / filename
                            shutil.copy2(file.name, dest_path)
                            return f"Music file added: {filename}"
                        except Exception as e:
                            return f"Error adding music: {str(e)}"
                    
                    add_music_btn = gr.Button("Add Music")
                    music_status = gr.Textbox(label="Status")
                    
                    add_music_btn.click(
                        add_music,
                        inputs=music_file,
                        outputs=music_status
                    )
                
                with gr.Accordion("Cleanup", open=True):
                    def clean_temp():
                        try:
                            for file in TEMP_DIR.glob("*"):
                                file.unlink()
                            return "Temporary files cleaned successfully"
                        except Exception as e:
                            return f"Error cleaning files: {str(e)}"
                    
                    clean_temp_btn = gr.Button("Clean Temporary Files")
                    clean_status = gr.Textbox(label="Status")
                    
                    clean_temp_btn.click(
                        clean_temp,
                        outputs=clean_status
                    )
            
            with gr.TabItem("Help"):
                gr.Markdown("""
                # Help & Troubleshooting
                
                ## Common Issues
                
                ### Image Generation
                
                - **G4F Issues**: If image generation with G4F fails, try switching to "prodia" or "pollinations" provider
                - **Model Compatibility**: Not all models work with all providers. If you get errors, try a different model/provider combination
                
                ### TTS Issues
                
                - **Edge TTS Voice Error**: If you get "No audio was received" error, try a different voice like "en-US-ChristopherNeural"
                - **Google TTS**: For simplicity, use Google TTS with language code "en" if Edge TTS isn't working
                
                ### Video Generation
                
                - **Video Creation Errors**: Make sure all images were successfully generated before creating the video
                - **Subtitle Issues**: Subtitles require an AssemblyAI API key. You can get a free one at [AssemblyAI](https://www.assemblyai.com/)
                
                ## Tips for Best Results
                
                1. **Topics**: Be specific with your niche/topic for better results
                2. **Images**: SDXL Turbo is fastest, but other models may give better quality
                3. **TTS**: Edge TTS generally gives the best quality voice with "en-US-ChristopherNeural"
                4. **Background Music**: Add your own music files for better video quality
                """)
        
    return app

if __name__ == "__main__":
    app = ui_component()
    app.launch()