File size: 29,638 Bytes
32007ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c563a2
32007ab
 
8f5bdbe
4cd041c
d279001
 
32007ab
 
 
 
 
 
 
90bc8ef
 
 
 
 
 
 
32007ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a7a68
32007ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d6668a
32007ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a7a68
 
 
 
 
 
 
 
32007ab
 
92a7a68
32007ab
 
 
92a7a68
32007ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f5bdbe
 
4cd041c
 
 
 
 
 
 
 
95062f0
 
 
 
7f04aa2
95062f0
 
 
d279001
95062f0
 
 
 
4e36dd3
 
95062f0
d279001
95062f0
 
 
 
 
 
 
 
 
d279001
95062f0
 
d279001
95062f0
 
 
 
 
 
 
 
 
 
d279001
95062f0
 
 
 
 
d279001
95062f0
 
d279001
95062f0
d279001
 
95062f0
 
d279001
95062f0
d279001
95062f0
 
 
4cd041c
 
 
adc97bd
 
cbd5fd3
adc97bd
50a0143
adc97bd
d279001
 
 
 
 
 
 
 
c6db5df
d279001
 
 
 
 
 
816ed38
 
 
 
 
 
 
 
 
1dc6da8
58f3513
 
 
 
816ed38
 
 
 
 
 
 
1dc6da8
816ed38
58f3513
 
 
1dc6da8
 
 
d279001
58f3513
816ed38
58f3513
 
 
 
d279001
58f3513
 
 
d279001
58f3513
816ed38
58f3513
816ed38
58f3513
816ed38
 
fbd693e
4cd041c
fbd693e
 
8f5bdbe
 
 
 
 
 
 
 
 
 
 
 
 
 
2d6668a
8f5bdbe
 
 
 
 
 
 
 
 
 
 
 
 
fbd693e
 
4e36dd3
fbd693e
8f5bdbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32007ab
8f5bdbe
 
32007ab
8f5bdbe
 
32007ab
8f5bdbe
 
32007ab
8f5bdbe
 
32007ab
8f5bdbe
32007ab
8f5bdbe
 
32007ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import praw
import json
import cv2
import numpy as np
import textwrap
from gtts import gTTS
from pydub import AudioSegment
import subprocess
import re
import os
import random
import time
import sys
import uuid
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from google.auth.transport.requests import Request
import nltk
nltk.download('punkt_tab')
from tts import synthesiser, speaker_embedding 
import soundfile as sf
import uuid
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, RedirectResponse
from fastapi import FastAPI, Request, Response, HTTPException

# from tortoise_tts import TextToSpeech

# nltk.download('punkt')

# Define the output folder path
output_folder = 'output'
audio_output_folder = 'audio'

if not os.path.exists(audio_output_folder):
    os.makedirs(audio_output_folder)

if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# Constants
SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]
CLIENT_SECRETS_FILE = "client_secrets.json" # Update with your client_secrets.json file path
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
MAX_RETRIES = 10
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
ELEVENLABS_KEY = "153f3875b30f603644cc66a78f1345ea"

banned_words = ["fuck", "pussy", "ass", "porn", "gay", "dick", "cock", "kill", "fucking", "shit", "bitch", "bullshit", "asshole","douchebag", "bitch", "motherfucker", "nigga","cunt", "whore", "piss", "shoot", "bomb", "palestine", "israel" ]

def contains_banned_word(text, banned_words):
    for word in banned_words:
        if word in text.lower():
            return True
    return False

def fetch_reddit_data(subreddit_name):
    # Reddit API Credentials
    client_id = 'TIacEazZS9FHWzDZ3T-3cA'
    client_secret = '6Urwdiqo_cC8Gt040K_rBhnR3r8CLg'
    user_agent = 'script by u/lakpriya1'

    # Initialize PRAW with your credentials
    reddit = praw.Reddit(client_id=client_id, client_secret=client_secret, user_agent=user_agent)

    subreddit = reddit.subreddit(subreddit_name)

    for _ in range(10):  # Limit the number of attempts to 10
        post = subreddit.random()
        # Check if the title contains a pattern resembling a URL
        if post and not re.search(r'\w+\.\w+', post.selftext) and not contains_banned_word(post.selftext, banned_words) and not len(post.selftext) < 50:
            post_data = {'title': post.title, 'selftext': post.selftext}

            with open('top_post.json', 'w') as outfile:
                json.dump(post_data, outfile, indent=4)

            print("Top post data saved to top_post.json")
            return  # Exit after finding a suitable post

    print("No suitable post found without a URL-like string in the title.")

def read_json(filename):
    print("Reading data from", filename)
    with open(filename, 'r') as file:
        data = json.load(file)
    return data

def wrap_text(text, wrap_width):
    return textwrap.wrap(text, width=wrap_width)

def resize_background_image(image_path, frame_width, frame_height):
    print("Resizing background image")
    image = cv2.imread(image_path)
    h, w = image.shape[:2]
    scale = max(frame_width / w, frame_height / h)
    new_w, new_h = int(w * scale), int(h * scale)
    resized_image = cv2.resize(image, (new_w, new_h))

    # Cropping the resized image to fill the frame
    startx = new_w // 2 - (frame_width // 2)
    starty = new_h // 2 - (frame_height // 2)
    cropped_image = resized_image[starty:starty+frame_height, startx:startx+frame_width]
    return cropped_image

def put_text_with_stroke(frame, texts, positions, font_scales, line_heights, wrap_widths, font_colors=(255, 255, 255), stroke_colors=(0, 0, 0), fonts=None):
    default_font = cv2.FONT_HERSHEY_COMPLEX
    if fonts is None:
        fonts = [default_font] * len(texts)  # Use default font if not specified

    for text, position, font_scale, line_height, wrap_width, font_color, stroke_color, font in zip(texts, positions, font_scales, line_heights, wrap_widths, font_colors, stroke_colors, fonts):
        lines = wrap_text(text, wrap_width)

        # Calculate the total height of the text block
        total_text_height = line_height * len(lines)

        # Starting Y position to center text vertically
        if position[1] is None:
            start_y = (frame.shape[0] - total_text_height) // 2 + 100
        else:
            start_y = position[1]

        for line in lines:
            text_size = cv2.getTextSize(line, font, font_scale, 1)[0]
            text_x = position[0] - text_size[0] // 2
            text_y = start_y + line_height

            cv2.putText(frame, line, (text_x, text_y), font, font_scale, stroke_color, 8, cv2.LINE_AA)
            cv2.putText(frame, line, (text_x, text_y), font, font_scale, font_color, 2, cv2.LINE_AA)

            start_y += line_height

# def create_video_from_title(title, background_image, output_filename, audio_duration):
#     print("Creating video from title")
#     # Video properties
#     fps = 24
#     frame_width, frame_height = 720, 1280  # 9:16 aspect ratio
#     frame_count = audio_duration * fps

#     # Logo images
#     top_logo = load_logo('logo.png', frame_width, frame_height, 'top')
#     bottom_logo = load_logo('sub.png', frame_width, frame_height, 'bottom')

#     # OpenCV VideoWriter
#     fourcc = cv2.VideoWriter_fourcc(*'mp4v')
#     out = cv2.VideoWriter(output_filename, fourcc, fps, (frame_width, frame_height))

#     # Resize the background image
#     background = resize_background_image(background_image, frame_width, frame_height)

#     for i in range(int(np.floor(frame_count))):
#         frame = background.copy()  # Use the resized background image

#         # Overlay logos
#         frame = overlay_logo(frame, top_logo)
#         frame = overlay_logo(frame, bottom_logo)

#         # Add title to frame with text wrapping and highlight
#         put_text_with_stroke(frame, title, (50, 500), 1, 50, 25, font_color=(255, 255, 255), stroke_color=(0, 0, 0))  # Adjust wrap_width and line_height as needed

#         out.write(frame)  # Write the frame to the video

#     out.release()

def create_video_from_title(title, sentences, background_image, output_filename, audio_durations):
    print("Creating video from title")
    fps = 24
    frame_width, frame_height = 720, 1280  # 9:16 aspect ratio

    # OpenCV VideoWriter
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_filename, fourcc, fps, (frame_width, frame_height))

     # Logo images
    top_logo = load_logo('G.png', frame_width, frame_height, 'top')
    bottom_logo = load_logo('Follow.png', frame_width, frame_height, 'bottom')
    # Resize the background image
    background = resize_background_image(background_image, frame_width, frame_height)

    # Define font settings for title and sentence
    title_font = cv2.FONT_HERSHEY_TRIPLEX
    sentence_font = cv2.FONT_HERSHEY_TRIPLEX
    title_font_scale = 1.5  # Larger font for the title
    sentence_font_scale = 1.2  # Normal font for the sentence
    title_line_height = 50
    sentence_line_height = 50

    # Font color as white
    white_color = (255, 255, 255)  # BGR color code for white
    stroke_color = (0, 0, 0)  # BGR color code for black

    title = preprocess_text(title)

    current_frame = 0
    for sentence, duration in zip(sentences, audio_durations):
        sentence_frames = int(duration * fps)
        for i in range(sentence_frames):
            frame = background.copy()

                 # Overlay logos
            frame = overlay_logo(frame, top_logo)
            frame = overlay_logo(frame, bottom_logo)

            # Position for title and sentence
            title_position = (frame_width // 2, frame_height // 4)  # Title at the top
            sentence_position = (frame_width // 2, None)  # Sentence at the center

            sentence = preprocess_text(sentence)

            # Add title and sentence to frame with specific fonts, sizes, and colors
            put_text_with_stroke(frame, 
                                 [title, sentence], 
                                 [title_position, sentence_position], 
                                 [title_font_scale, sentence_font_scale], 
                                 [title_line_height, sentence_line_height], 
                                 [25, 25], 
                                 font_colors=[white_color, white_color], 
                                 stroke_colors=[stroke_color, stroke_color], 
                                 fonts=[title_font, sentence_font])

            out.write(frame)
            current_frame += 1

    out.release()


def tts_per_sentence(sentences, output_folder, silence_duration=1000):
    audio_durations = []
    audio_files = []

    for index, sentence in enumerate(sentences):
        output_file = f'{output_folder}/voiceover_{index}.wav'
        text_to_speech_using_speecht5(sentence, output_file)
        audio = AudioSegment.from_wav(output_file)
        silence = AudioSegment.silent(duration=silence_duration)
        audio_with_silence = audio + silence
        audio_with_silence.export(output_file, format="wav")
        audio_duration = len(audio_with_silence) / 1000.0  
        audio_durations.append(audio_duration)
        audio_files.append(output_file)
    return audio_files, audio_durations

# def eleven_labs_text_to_speech(text, output_file, voice_id):
#     url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
    
#     headers = {
#         "Accept": "audio/mpeg",
#         "Content-Type": "application/json",
#         "xi-api-key": ELEVENLABS_KEY
#     }

#     data = {
#         "text": text,
#         "model_id": "eleven_monolingual_v1",
#         "voice_settings": {
#             "stability": 0.5,
#             "similarity_boost": 0.5,
#             "speed": 0.3,
#         }
#     }

#     response = requests.post(url, json=data, headers=headers)
#     if response.status_code == 200:
#         with open(output_file, 'wb') as f:
#             for chunk in response.iter_content(chunk_size=1024):
#                 f.write(chunk)
#         print(f"Audio content written to {output_file}")
#     else:
#         print(f"Failed to synthesize speech: {response.content}")

def text_to_speech_using_speecht5(text, output_file): 
    # Use the synthesiser from tts.py
    speech = synthesiser(text, forward_params={"speaker_embeddings": speaker_embedding})
    sf.write(output_file, speech["audio"], samplerate=speech["sampling_rate"])
    print(f"Audio content written to {output_file}")

def fetch_random_nature_image(api_key):
    print("Fetching random nature image from Unsplash")
    url = f"https://api.unsplash.com/photos/random?query=horror&client_id={api_key}"
    response = requests.get(url)
    if response.status_code == 200:
        img_url = response.json()['urls']['regular']
        img_data = requests.get(img_url).content
        with open('nature_background.jpg', 'wb') as handler:
            handler.write(img_data)
        return 'nature_background.jpg'
    else:
        print("Failed to fetch image from Unsplash")
        return None
    
def preprocess_text(text):
    # Replace Unicode right single quotation mark with ASCII apostrophe
    text = text.replace('\u2019', "'")
    # If there are other specific characters causing issues, replace them similarly
    return text
    
def text_to_speech(text, output_file):
    print("Converting text to speech")
    tts = gTTS(text=text, lang='en')
    tts.save(output_file)
    return output_file

def get_audio_duration(audio_file):
    print("Getting audio duration")
    audio = AudioSegment.from_mp3(audio_file)
    return len(audio) / 1000.0  # Convert to seconds

def combine_audio_video(video_file, audio_file, output_file, audio_delay_seconds=0.3):
    # Construct the full path for the output file
    output_file = os.path.join(output_folder, output_file)

    # Add a delay to the audio start
    cmd = f'ffmpeg -i "{video_file}" -itsoffset {audio_delay_seconds} -i "{audio_file}" -c:v copy -c:a aac -strict experimental -map 0:v:0 -map 1:a:0 "{output_file}"'
    subprocess.call(cmd, shell=True)
    print("Successfully made the video:", output_file)

def load_logo(logo_path, frame_width, frame_height, position='top'):
    if not os.path.exists(logo_path):
        raise FileNotFoundError(f"Logo file not found: {logo_path}")
    
    logo = cv2.imread(logo_path, cv2.IMREAD_UNCHANGED)
    
    if logo is None:
        raise ValueError(f"Failed to load image at path: {logo_path}")
    
    logo_height, logo_width = logo.shape[:2]
    scale_factor = min(1, frame_width / 3 / logo_width, frame_height / 10 / logo_height)
    new_size = (int(logo_width * scale_factor * 1.3), int(logo_height * scale_factor * 1.3))
    logo = cv2.resize(logo, new_size, interpolation=cv2.INTER_AREA)

    x_center = frame_width // 2 - logo.shape[1] // 2
    y_pos = 100 if position == 'top' else frame_height - logo.shape[0] - 100

    return logo, (x_center, y_pos)

def overlay_logo(frame, logo_info):
    logo, (x, y) = logo_info
    y1, y2 = y, y + logo.shape[0]
    x1, x2 = x, x + logo.shape[1]

    if logo.shape[2] == 4:  # If the logo has an alpha channel
        alpha_logo = logo[:, :, 3] / 255.0
        alpha_frame = 1.0 - alpha_logo
        for c in range(0, 3):
            frame[y1:y2, x1:x2, c] = (alpha_logo * logo[:, :, c] +
                                      alpha_frame * frame[y1:y2, x1:x2, c])
    else:  # If the logo does not have an alpha channel
        frame[y1:y2, x1:x2] = logo

    return frame

def get_authenticated_service():
    flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_UPLOAD_SCOPE)
    storage = Storage(f"{sys.argv[0]}-oauth2.json")
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage)
    return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, credentials=credentials)

def upload_video_to_drive(video_file, folder_id=None):
    """Uploads a video to Google Drive."""
    # Check if the credentials are stored
    storage = Storage(f"{sys.argv[0]}-oauth2.json")
    credentials = storage.get()

    # If credentials are not available or are invalid, run the flow
    if not credentials or credentials.invalid:
        flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=[DRIVE_SCOPE])
        credentials = run_flow(flow, storage)

    service = build('drive', 'v3', credentials=credentials)

    file_metadata = {
        'name': os.path.basename(video_file),
        'mimeType': 'video/mp4'
    }
    if folder_id:
        file_metadata['parents'] = [folder_id]

    media = MediaFileUpload(video_file, mimetype='video/mp4', resumable=True)
    file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    
    print('File ID: %s' % file.get('id'))

def initialize_upload(youtube, options):
    tags = None
    if 'keywords' in options and options['keywords']:
        tags = options['keywords'].split(",")

    body = dict(
        snippet=dict(
            title=options['title'],
            description=options['description'],
            tags=tags,
            categoryId=options['category']
        ),
        status=dict(
            privacyStatus=options['privacyStatus']
        )
    )

    # Call the API's videos.insert method to create and upload the video.
    insert_request = youtube.videos().insert(
    part=",".join(body.keys()),
    body=body,
    # The chunksize parameter specifies the size of each chunk of data, in
    # bytes, that will be uploaded at a time. Set a higher value for
    # reliable connections as fewer chunks lead to faster uploads. Set a lower
    # value for better recovery on less reliable connections.
    #
    # Setting "chunksize" equal to -1 in the code below means that the entire
    # file will be uploaded in a single HTTP request. (If the upload fails,
    # it will still be retried where it left off.) This is usually a best
    # practice, but if you're using Python older than 2.6 or if you're
    # running on App Engine, you should set the chunksize to something like
    # 1024 * 1024 (1 megabyte).
    media_body=MediaFileUpload(options["file"], chunksize=-1, resumable=True)
    )

    resumable_upload(insert_request)

# This method implements an exponential backoff strategy to resume a
# failed upload.
def resumable_upload(insert_request):
  response = None
  error = None
  retry = 0
  while response is None:
    try:
      print("Uploading file...")
      status, response = insert_request.next_chunk()
      if response is not None:
        if 'id' in response:
          print("Video id '%s' was successfully uploaded." % response['id'])
        else:
          exit("The upload failed with an unexpected response: %s" % response)
    except HttpError as e:
      if e.resp.status in RETRIABLE_STATUS_CODES:
        error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
                                                             e.content)
      else:
        raise
    # except RETRIABLE_EXCEPTIONS as e:
    #   error = "A retriable error occurred: %s" % e

    if error is not None:
      print(error)
      retry += 1
      if retry > MAX_RETRIES:
        exit("No longer attempting to retry.")

      max_sleep = 2 ** retry
      sleep_seconds = random.random() * max_sleep
      print("Sleeping %f seconds and then retrying..." % sleep_seconds)
      time.sleep(sleep_seconds)

# def eleven_labs_text_to_speech(text, output_file):
#     voice_ids = {
#         "ndntWUKwYjgJGYkvF6at",
#         "SVLJSgUbrKWfY8HvF2Xd",
#         "sjdiTCylizqR74A3ssv4",
#     }
#     # randomly pick one of the voices
#     voice_id = random.choice(list(voice_ids))
#     url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
    
#     headers = {
#         "Accept": "audio/mpeg",
#         "Content-Type": "application/json",
#         "xi-api-key": ELEVENLABS_KEY
#     }

#     data = {
#         "text": text,
#         "model_id": "eleven_monolingual_v1",
#         "voice_settings": {
#             "stability": 0.5,
#             "similarity_boost": 0.5,
#             "speed": 0.3,
#         }
#     }

#     response = requests.post(url, json=data, headers=headers)
#     if response.status_code == 200:
#         with open(output_file, 'wb') as f:
#             for chunk in response.iter_content(chunk_size=1024):
#                 f.write(chunk)
#         print(f"Audio content written to {output_file}")
#     else:
#         print(f"Failed to synthesize speech: {response.content}")

def combine_audio_files(audio_files, output_file):
    combined = AudioSegment.empty()
    for file in audio_files:
        audio = AudioSegment.from_mp3(file)
        combined += audio
    combined.export(output_file, format="mp3")
    return output_file

api_key = 'VhLwkCKi3iu5Pf37LXfz-Lp7hTW69EV8uw_hkLAPkiA'  # Replace with your Unsplash API key
background_image = fetch_random_nature_image(api_key)

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def upload_video_to_tiktok(access_token: str, video_file_path: str):
    try:
        video_size = os.path.getsize(video_file_path)
        init_response = requests.post(
            'https://open.tiktokapis.com/v2/post/publish/inbox/video/init/',
            headers={
                'Authorization': f'Bearer {access_token}',
                'Content-Type': 'application/json; charset=UTF-8'
            },
            json={
                "source_info": {
                    "source": "FILE_UPLOAD",
                    "video_size": video_size,
                    "chunk_size": video_size,
                    "total_chunk_count": 1
                }
            }
        )

        if init_response.status_code != 200:
            raise Exception(f"Failed to initialize video upload: {init_response.status_code} {init_response.text}")

        init_data = init_response.json()

        if 'error' in init_data and init_data['error']['code'] != 'ok':
            raise Exception(f"Initialization error: {init_data['error']['message']}")

        publish_id = init_data['data']['publish_id']
        upload_url = init_data['data']['upload_url']

        with open(video_file_path, 'rb') as video_file:
            video_data = video_file.read()
            upload_response = requests.put(
                upload_url,
                headers={
                    'Content-Type': 'video/mp4',
                    'Content-Range': f'bytes 0-{len(video_data) - 1}/{len(video_data)}'
                },
                data=video_data
            )

        if upload_response.status_code != 200:
            raise Exception(f"Failed to upload video: {upload_response.status_code} {upload_response.text}")

        status_response = requests.post(
            'https://open.tiktokapis.com/v2/post/publish/status/fetch/',
            headers={
                'Authorization': f'Bearer {access_token}',
                'Content-Type': 'application/json; charset=UTF-8'
            },
            json={'publish_id': publish_id}
        )

        if status_response.status_code != 200:
            raise Exception(f"Failed to fetch post status: {status_response.status_code} {status_response.text}")

        return status_response.json()

    except Exception as e:
        print(f"Exception occurred: {str(e)}")
        return {"status": "error", "message": str(e)}

@app.get("/", tags=["home"])
def api_home():
    return {'detail': 'Welcome to VideoGen!'}

@app.get("/tiktok04mGYqnihbw3hRUasbHWxXu03zEGxXH9.txt")
def api_tick():
    return FileResponse(f"tiktok04mGYqnihbw3hRUasbHWxXu03zEGxXH9.txt")

CLIENT_KEY = 'sbawybfvayitbc5i5u'
CLIENT_SECRET = '1WBu9szNwKPiAw374VWty4EoVK8wtTWo'
REDIRECT_URI = 'https://lakpriya-videogen-api.hf.space/tiktok_callback'

@app.get("/tiktok_login")
async def tiktok_login():
    csrf_state = uuid.uuid4().hex
    response = RedirectResponse(
        url=f"https://www.tiktok.com/v2/auth/authorize/?client_key={CLIENT_KEY}&response_type=code&scope=user.info.basic,video.publish,video.upload&redirect_uri={REDIRECT_URI}&state={csrf_state}"
    )
    response.set_cookie(key="csrf_state", value=csrf_state, max_age=600)
    return response

@app.get("/tiktok_callback")
async def tiktok_callback(request: Request):
    try:
        code = request.query_params.get('code')
        state = request.query_params.get('state')
        csrf_state = request.cookies.get('csrf_state')

        if state != csrf_state:
            raise HTTPException(status_code=400, detail="Invalid state parameter")

        # Exchange code for access token
        response = requests.post(
            'https://open.tiktokapis.com/v2/oauth/token/',
            headers={
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data={
                'client_key': CLIENT_KEY,
                'client_secret': CLIENT_SECRET,
                'code': code,
                'grant_type': 'authorization_code',
                'redirect_uri': REDIRECT_URI
            }
        )

        # Check for successful response
        if response.status_code != 200:
            raise HTTPException(status_code=response.status_code, detail="Failed to exchange code for token")

        # Try parsing the JSON response
        token_response = response.json()

        # Check if there is an error in the response
        if "error" in token_response:
            raise HTTPException(status_code=400, detail=token_response.get("error_description", "Unknown error"))

        access_token = token_response.get('access_token')
        open_id = token_response.get('open_id')

        # Log the access token and open_id for debugging purposes
        print(f"Access token: {access_token}")
        print(f"Open ID: {open_id}")

        # Return a success message with the token details
        return {"message": "Authorization successful", "access_token": access_token, "open_id": open_id}

    except Exception as e:
        # Log the exception for debugging purposes
        print(f"Exception occurred: {str(e)}")
        raise HTTPException(status_code=500, detail="Internal Server Error")
    
@app.get("/generate_video")
def generate_video(request: Request):
    access_token = request.query_params.get('access_token')
    try:
        api_key = 'VhLwkCKi3iu5Pf37LXfz-Lp7hTW69EV8uw_hkLAPkiA'  # Replace with your Unsplash API key
        background_image = fetch_random_nature_image(api_key)

        if background_image:
            fetch_reddit_data('Glitch_in_the_Matrix')
            reddit_data = read_json('top_post.json')
            title = reddit_data.get('title')
            selftext = reddit_data.get('selftext')

            # Split title into sentences
            sentences = nltk.sent_tokenize(selftext)
            
            # Generate audio for each sentence and get durations
            audio_files, audio_durations = tts_per_sentence(sentences, audio_output_folder)

            # Create and save the video
            video_filename = "reddit_post_video_cv2.mp4"
            create_video_from_title(title, sentences, background_image, video_filename, audio_durations)

            # Combine all audio files into one (if needed)
            combined_audio_file = combine_audio_files(audio_files, 'combined_voiceover.mp3')  # Implement this function

            final_filename = "video_" + str(uuid.uuid4())

            # Combine the final video and audio
            combine_audio_video(video_filename, combined_audio_file, final_filename + '.mp4')

            video_path = os.path.join(output_folder, final_filename + '.mp4')

            upload_video_to_tiktok(access_token, video_path)

            return {"status": "success", "filename": final_filename + '.mp4'}
        else:
            return {"status": "failed", "message": "Failed to fetch background image"}
    except Exception as e:
        return {"status": "error", "message": str(e)}

# Run the application using Uvicorn
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

# if background_image:
#     fetch_reddit_data('Glitch_in_the_Matrix')
#     reddit_data = read_json('top_post.json')
#     title = reddit_data.get('title')
#     selftext = reddit_data.get('selftext')

#     # Split title into sentences
#     sentences = nltk.sent_tokenize(selftext)
    
#     # Generate audio for each sentence and get durations
#     audio_files, audio_durations = tts_per_sentence(sentences, 'audio')

#     # Create and save the video
#     create_video_from_title(title, sentences, background_image, "reddit_post_video_cv2.mp4", audio_durations)

#     # Combine all audio files into one (if needed)
#     combined_audio_file = combine_audio_files(audio_files, 'combined_voiceover.mp3')  # Implement this function

#     filename = "video_" + str(uuid.uuid4())

#     # Combine the final video and audio
#     combine_audio_video('reddit_post_video_cv2.mp4', combined_audio_file, filename + '.mp4')

# if background_image:
#     # Example usage
#     fetch_reddit_data('Glitch_in_the_Matrix')

#     # Read data from JSON
#     reddit_data = read_json('top_post.json')  # Change filename if needed
#     title = reddit_data.get('title')

#     filename = "video_" + str(uuid.uuid4())

#     # Convert text to speech
#     # voiceover_file = text_to_speech(title, 'voiceover.mp3')
#     voiceover_file = eleven_labs_text_to_speech(title, 'voiceover.mp3')

#     # Get audio duration
#     audio_duration = get_audio_duration('voiceover.mp3')

#     # Create and save the video
#     create_video_from_title(title, background_image, "reddit_post_video_cv2.mp4", audio_duration)

#     # Combine audio and video
#     combine_audio_video('reddit_post_video_cv2.mp4', 'voiceover.mp3', filename + '.mp4')

#     options = {
#         'file': 'output/'+ filename + '.mp4',
#         'title': "Amazing Facts Revealed: Unveiling the World's Hidden Wonders #shorts",
#         'description':  "Welcome to our latest YouTube video, 'Amazing Facts Revealed: Unveiling the World's Hidden Wonders'! In this enthralling episode, we dive deep into the most astonishing and lesser-known facts about our world. From the mysteries of the deep sea to the enigmas of outer space, we cover it all. Get ready to be amazed by incredible scientific discoveries, historical secrets, and mind-blowing natural phenomena. Each fact is meticulously researched and presented with stunning visuals and engaging narration. Don't forget to like, share, and subscribe for more fascinating content. Stay curious and let's explore the wonders of our world together #shorts",
#         'category': "22",
#         'keywords': "facts, shorts, funny",
#         'privacyStatus': "private"
#     }

    # try:
        # youtube = get_authenticated_service()
        # initialize_upload(youtube, options)
    #     upload_video_to_drive('output/'+ filename + '.mp4','1t2lcYNLgz6FTeabzccY_06rvcnTGdQiR')
    # except HttpError as e:
    #     print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))