Lakpriya Seneviratna commited on
Commit
32007ab
·
1 Parent(s): 63fc4a1

chore: Add .gitignore and requirements.txt files

Browse files
Files changed (21) hide show
  1. .gitignore +6 -0
  2. Follow.png +0 -0
  3. G.png +0 -0
  4. __pycache__/tts.cpython-312.pyc +0 -0
  5. appsscript.json +19 -0
  6. background.jpg +0 -0
  7. client_secrets.json +9 -0
  8. fonts.py +35 -0
  9. giphy.gif +0 -0
  10. logo.png +0 -0
  11. main.py +402 -0
  12. main.py-oauth2.json +24 -0
  13. main_glitch.py +562 -0
  14. nature_background.jpg +0 -0
  15. requirements.txt +16 -0
  16. sub.png +0 -0
  17. sub.webp +0 -0
  18. test.py +180 -0
  19. tik.py +38 -0
  20. top_post.json +4 -0
  21. tts.py +15 -0
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .venv
2
+ audio
3
+ output
4
+ *.mp3
5
+ *.wav
6
+ *.mp4
Follow.png ADDED
G.png ADDED
__pycache__/tts.cpython-312.pyc ADDED
Binary file (731 Bytes). View file
 
appsscript.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timeZone": "America/New_York",
3
+ "dependencies": {
4
+ "enabledAdvancedServices": [
5
+ {
6
+ "userSymbol": "YouTube",
7
+ "version": "v3",
8
+ "serviceId": "youtube"
9
+ }
10
+ ]
11
+ },
12
+ "oauthScopes": [
13
+ "https://www.googleapis.com/auth/drive",
14
+ "https://www.googleapis.com/auth/script.external_request",
15
+ "https://www.googleapis.com/auth/youtube"
16
+ ],
17
+ "exceptionLogging": "STACKDRIVER",
18
+ "runtimeVersion": "V8"
19
+ }
background.jpg ADDED
client_secrets.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "web": {
3
+ "client_id": "672725064244-vqnm51a5ivbm6cnlbsl2mmk71k7243b5.apps.googleusercontent.com",
4
+ "client_secret": "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",
5
+ "redirect_uris": [],
6
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
7
+ "token_uri": "https://accounts.google.com/o/oauth2/token"
8
+ }
9
+ }
fonts.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+ # Create a black image
5
+ image = np.zeros((480, 640, 3), dtype="uint8")
6
+
7
+ # Text to be added
8
+ text = "OpenCV Fonts"
9
+
10
+ # Coordinates
11
+ org = (50, 230)
12
+
13
+ # Font color
14
+ color = (255, 255, 255) # White
15
+
16
+ # Using different fonts
17
+ fonts = [
18
+ cv2.FONT_HERSHEY_SIMPLEX,
19
+ cv2.FONT_HERSHEY_PLAIN,
20
+ cv2.FONT_HERSHEY_DUPLEX,
21
+ cv2.FONT_HERSHEY_COMPLEX,
22
+ cv2.FONT_HERSHEY_TRIPLEX,
23
+ cv2.FONT_HERSHEY_COMPLEX_SMALL,
24
+ cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
25
+ cv2.FONT_HERSHEY_SCRIPT_COMPLEX
26
+ ]
27
+
28
+ # Display text using different fonts
29
+ for i, font in enumerate(fonts):
30
+ cv2.putText(image, f"{text} {i+1}", (10, 30 + i*50), font, 1, color, 2)
31
+
32
+ # Show the image
33
+ cv2.imshow("OpenCV Fonts Example", image)
34
+ cv2.waitKey(0)
35
+ cv2.destroyAllWindows()
giphy.gif ADDED
logo.png ADDED
main.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import praw
3
+ import json
4
+ import cv2
5
+ import numpy as np
6
+ import textwrap
7
+ from gtts import gTTS
8
+ from pydub import AudioSegment
9
+ import subprocess
10
+ import re
11
+ import os
12
+ import random
13
+ import time
14
+ import sys
15
+ import uuid
16
+ from googleapiclient.discovery import build
17
+ from googleapiclient.errors import HttpError
18
+ from googleapiclient.http import MediaFileUpload
19
+ from oauth2client.client import flow_from_clientsecrets
20
+ from oauth2client.file import Storage
21
+ from oauth2client.tools import run_flow
22
+ from google.auth.transport.requests import Request
23
+
24
+ # Define the output folder path
25
+ output_folder = 'output'
26
+
27
+ # Constants
28
+ SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]
29
+ CLIENT_SECRETS_FILE = "client_secrets.json" # Update with your client_secrets.json file path
30
+ YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
31
+ DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"
32
+ YOUTUBE_API_SERVICE_NAME = "youtube"
33
+ YOUTUBE_API_VERSION = "v3"
34
+ MAX_RETRIES = 10
35
+ RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
36
+ ELEVENLABS_KEY = "55bfc10fb7eecae379f73e6740807101"
37
+
38
+ # Check if the folder exists, if not, create it
39
+ if not os.path.exists(output_folder):
40
+ os.makedirs(output_folder)
41
+
42
+ 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" ]
43
+
44
+ def contains_banned_word(text, banned_words):
45
+ for word in banned_words:
46
+ if word in text.lower():
47
+ return True
48
+ return False
49
+
50
+ def fetch_reddit_data(subreddit_name):
51
+ # Reddit API Credentials
52
+ client_id = 'TIacEazZS9FHWzDZ3T-3cA'
53
+ client_secret = '6Urwdiqo_cC8Gt040K_rBhnR3r8CLg'
54
+ user_agent = 'script by u/lakpriya1'
55
+
56
+ # Initialize PRAW with your credentials
57
+ reddit = praw.Reddit(client_id=client_id, client_secret=client_secret, user_agent=user_agent)
58
+
59
+ subreddit = reddit.subreddit(subreddit_name)
60
+
61
+ for _ in range(10): # Limit the number of attempts to 10
62
+ post = subreddit.random()
63
+ # Check if the title contains a pattern resembling a URL
64
+ if post and not re.search(r'\w+\.\w+', post.title) and not contains_banned_word(post.title, banned_words) and not len(post.title) < 50:
65
+ post_data = {'title': post.title}
66
+
67
+ with open('top_post.json', 'w') as outfile:
68
+ json.dump(post_data, outfile, indent=4)
69
+
70
+ print("Top post data saved to top_post.json")
71
+ return # Exit after finding a suitable post
72
+
73
+ print("No suitable post found without a URL-like string in the title.")
74
+
75
+ def read_json(filename):
76
+ print("Reading data from", filename)
77
+ with open(filename, 'r') as file:
78
+ data = json.load(file)
79
+ return data
80
+
81
+ def wrap_text(text, wrap_width):
82
+ return textwrap.wrap(text, width=wrap_width)
83
+
84
+ def resize_background_image(image_path, frame_width, frame_height):
85
+ print("Resizing background image")
86
+ image = cv2.imread(image_path)
87
+ h, w = image.shape[:2]
88
+ scale = max(frame_width / w, frame_height / h)
89
+ new_w, new_h = int(w * scale), int(h * scale)
90
+ resized_image = cv2.resize(image, (new_w, new_h))
91
+
92
+ # Cropping the resized image to fill the frame
93
+ startx = new_w // 2 - (frame_width // 2)
94
+ starty = new_h // 2 - (frame_height // 2)
95
+ cropped_image = resized_image[starty:starty+frame_height, startx:startx+frame_width]
96
+ return cropped_image
97
+
98
+ def put_text_with_stroke(frame, text, position, font_scale, line_height, wrap_width, font_color=(255, 255, 255), stroke_color=(0, 0, 0)):
99
+ font = cv2.FONT_HERSHEY_COMPLEX
100
+ lines = wrap_text(text, wrap_width)
101
+
102
+ # Calculate the total height of the text block
103
+ total_text_height = line_height * len(lines)
104
+
105
+ # Starting Y position to center text vertically
106
+ start_y = (frame.shape[0] - total_text_height) // 2
107
+
108
+ for line in lines:
109
+ text_size = cv2.getTextSize(line, font, font_scale, 1)[0]
110
+ # Calculate x coordinate for center alignment
111
+ text_x = (frame.shape[1] - text_size[0]) // 2
112
+ text_y = start_y + line_height
113
+
114
+ # Draw text stroke (increase thickness for a bolder stroke)
115
+ cv2.putText(frame, line, (text_x, text_y), font, font_scale, stroke_color, 8, cv2.LINE_AA)
116
+
117
+ # Draw original text on top
118
+ cv2.putText(frame, line, (text_x, text_y), font, font_scale, font_color, 2, cv2.LINE_AA)
119
+
120
+ start_y += line_height
121
+
122
+ def create_video_from_title(title, background_image, output_filename, audio_duration):
123
+ print("Creating video from title")
124
+ # Video properties
125
+ fps = 24
126
+ frame_width, frame_height = 720, 1280 # 9:16 aspect ratio
127
+ frame_count = audio_duration * fps
128
+
129
+ # Logo images
130
+ top_logo = load_logo('logo.png', frame_width, frame_height, 'top')
131
+ bottom_logo = load_logo('sub.png', frame_width, frame_height, 'bottom')
132
+
133
+ # OpenCV VideoWriter
134
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
135
+ out = cv2.VideoWriter(output_filename, fourcc, fps, (frame_width, frame_height))
136
+
137
+ # Resize the background image
138
+ background = resize_background_image(background_image, frame_width, frame_height)
139
+
140
+ for i in range(int(np.floor(frame_count))):
141
+ frame = background.copy() # Use the resized background image
142
+
143
+ # Overlay logos
144
+ frame = overlay_logo(frame, top_logo)
145
+ frame = overlay_logo(frame, bottom_logo)
146
+
147
+ # Add title to frame with text wrapping and highlight
148
+ 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
149
+
150
+ out.write(frame) # Write the frame to the video
151
+
152
+ out.release()
153
+
154
+ def fetch_random_nature_image(api_key):
155
+ print("Fetching random nature image from Unsplash")
156
+ url = f"https://api.unsplash.com/photos/random?query=nature&client_id={api_key}"
157
+ response = requests.get(url)
158
+ if response.status_code == 200:
159
+ img_url = response.json()['urls']['regular']
160
+ img_data = requests.get(img_url).content
161
+ with open('nature_background.jpg', 'wb') as handler:
162
+ handler.write(img_data)
163
+ return 'nature_background.jpg'
164
+ else:
165
+ print("Failed to fetch image from Unsplash")
166
+ return None
167
+
168
+ def text_to_speech(text, output_file):
169
+ print("Converting text to speech")
170
+ tts = gTTS(text=text, lang='en')
171
+ tts.save(output_file)
172
+ return output_file
173
+
174
+ def get_audio_duration(audio_file):
175
+ print("Getting audio duration")
176
+ audio = AudioSegment.from_mp3(audio_file)
177
+ return len(audio) / 1000.0 # Convert to seconds
178
+
179
+ def combine_audio_video(video_file, audio_file, output_file, audio_delay_seconds=0.3):
180
+ # Construct the full path for the output file
181
+ output_file = os.path.join(output_folder, output_file)
182
+
183
+ # Add a delay to the audio start
184
+ 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}"'
185
+ subprocess.call(cmd, shell=True)
186
+ print("Successfully made the video:", output_file)
187
+
188
+ def load_logo(logo_path, frame_width, frame_height, position='top'):
189
+ logo = cv2.imread(logo_path, cv2.IMREAD_UNCHANGED) # Load with alpha channel
190
+ logo_height, logo_width = logo.shape[:2]
191
+
192
+ # Scaling down the logo if it's too big
193
+ scale_factor = min(1, frame_width / 3 / logo_width, frame_height / 10 / logo_height)
194
+ new_size = (int(logo_width * scale_factor*1.3), int(logo_height * scale_factor*1.3))
195
+ logo = cv2.resize(logo, new_size, interpolation=cv2.INTER_AREA)
196
+
197
+ # Positioning
198
+ x_center = frame_width // 2 - logo.shape[1] // 2
199
+ if position == 'top':
200
+ y_pos = 100 # 10 pixels from the top
201
+ else: # 'bottom'
202
+ y_pos = frame_height - logo.shape[0] - 100 # 10 pixels from the bottom
203
+
204
+ return logo, (x_center, y_pos)
205
+
206
+ def overlay_logo(frame, logo_info):
207
+ logo, (x, y) = logo_info
208
+ y1, y2 = y, y + logo.shape[0]
209
+ x1, x2 = x, x + logo.shape[1]
210
+
211
+ if logo.shape[2] == 4: # If the logo has an alpha channel
212
+ alpha_logo = logo[:, :, 3] / 255.0
213
+ alpha_frame = 1.0 - alpha_logo
214
+ for c in range(0, 3):
215
+ frame[y1:y2, x1:x2, c] = (alpha_logo * logo[:, :, c] +
216
+ alpha_frame * frame[y1:y2, x1:x2, c])
217
+ else: # If the logo does not have an alpha channel
218
+ frame[y1:y2, x1:x2] = logo
219
+
220
+ return frame
221
+
222
+ def get_authenticated_service():
223
+ flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_UPLOAD_SCOPE)
224
+ storage = Storage(f"{sys.argv[0]}-oauth2.json")
225
+ credentials = storage.get()
226
+ if credentials is None or credentials.invalid:
227
+ credentials = run_flow(flow, storage)
228
+ return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, credentials=credentials)
229
+
230
+ def upload_video_to_drive(video_file, folder_id=None):
231
+ """Uploads a video to Google Drive."""
232
+ # Check if the credentials are stored
233
+ storage = Storage(f"{sys.argv[0]}-oauth2.json")
234
+ credentials = storage.get()
235
+
236
+ # If credentials are not available or are invalid, run the flow
237
+ if not credentials or credentials.invalid:
238
+ flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=[DRIVE_SCOPE])
239
+ credentials = run_flow(flow, storage)
240
+
241
+ service = build('drive', 'v3', credentials=credentials)
242
+
243
+ file_metadata = {
244
+ 'name': os.path.basename(video_file),
245
+ 'mimeType': 'video/mp4'
246
+ }
247
+ if folder_id:
248
+ file_metadata['parents'] = [folder_id]
249
+
250
+ media = MediaFileUpload(video_file, mimetype='video/mp4', resumable=True)
251
+ file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
252
+
253
+ print('File ID: %s' % file.get('id'))
254
+
255
+ def initialize_upload(youtube, options):
256
+ tags = None
257
+ if 'keywords' in options and options['keywords']:
258
+ tags = options['keywords'].split(",")
259
+
260
+ body = dict(
261
+ snippet=dict(
262
+ title=options['title'],
263
+ description=options['description'],
264
+ tags=tags,
265
+ categoryId=options['category']
266
+ ),
267
+ status=dict(
268
+ privacyStatus=options['privacyStatus']
269
+ )
270
+ )
271
+
272
+ # Call the API's videos.insert method to create and upload the video.
273
+ insert_request = youtube.videos().insert(
274
+ part=",".join(body.keys()),
275
+ body=body,
276
+ # The chunksize parameter specifies the size of each chunk of data, in
277
+ # bytes, that will be uploaded at a time. Set a higher value for
278
+ # reliable connections as fewer chunks lead to faster uploads. Set a lower
279
+ # value for better recovery on less reliable connections.
280
+ #
281
+ # Setting "chunksize" equal to -1 in the code below means that the entire
282
+ # file will be uploaded in a single HTTP request. (If the upload fails,
283
+ # it will still be retried where it left off.) This is usually a best
284
+ # practice, but if you're using Python older than 2.6 or if you're
285
+ # running on App Engine, you should set the chunksize to something like
286
+ # 1024 * 1024 (1 megabyte).
287
+ media_body=MediaFileUpload(options["file"], chunksize=-1, resumable=True)
288
+ )
289
+
290
+ resumable_upload(insert_request)
291
+
292
+ # This method implements an exponential backoff strategy to resume a
293
+ # failed upload.
294
+ def resumable_upload(insert_request):
295
+ response = None
296
+ error = None
297
+ retry = 0
298
+ while response is None:
299
+ try:
300
+ print("Uploading file...")
301
+ status, response = insert_request.next_chunk()
302
+ if response is not None:
303
+ if 'id' in response:
304
+ print("Video id '%s' was successfully uploaded." % response['id'])
305
+ else:
306
+ exit("The upload failed with an unexpected response: %s" % response)
307
+ except HttpError as e:
308
+ if e.resp.status in RETRIABLE_STATUS_CODES:
309
+ error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
310
+ e.content)
311
+ else:
312
+ raise
313
+ # except RETRIABLE_EXCEPTIONS as e:
314
+ # error = "A retriable error occurred: %s" % e
315
+
316
+ if error is not None:
317
+ print(error)
318
+ retry += 1
319
+ if retry > MAX_RETRIES:
320
+ exit("No longer attempting to retry.")
321
+
322
+ max_sleep = 2 ** retry
323
+ sleep_seconds = random.random() * max_sleep
324
+ print("Sleeping %f seconds and then retrying..." % sleep_seconds)
325
+ time.sleep(sleep_seconds)
326
+
327
+ def eleven_labs_text_to_speech(text, output_file):
328
+ voice_ids = {
329
+ "ndntWUKwYjgJGYkvF6at",
330
+ "SVLJSgUbrKWfY8HvF2Xd",
331
+ "sjdiTCylizqR74A3ssv4",
332
+ }
333
+ # randomly pick one of the voices
334
+ voice_id = random.choice(list(voice_ids))
335
+ url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
336
+
337
+ headers = {
338
+ "Accept": "audio/mpeg",
339
+ "Content-Type": "application/json",
340
+ "xi-api-key": ELEVENLABS_KEY
341
+ }
342
+
343
+ data = {
344
+ "text": text,
345
+ "model_id": "eleven_monolingual_v1",
346
+ "voice_settings": {
347
+ "stability": 0.5,
348
+ "similarity_boost": 0.5,
349
+ "speed": 0.3,
350
+ }
351
+ }
352
+
353
+ response = requests.post(url, json=data, headers=headers)
354
+ if response.status_code == 200:
355
+ with open(output_file, 'wb') as f:
356
+ for chunk in response.iter_content(chunk_size=1024):
357
+ f.write(chunk)
358
+ print(f"Audio content written to {output_file}")
359
+ else:
360
+ print(f"Failed to synthesize speech: {response.content}")
361
+
362
+ api_key = 'VhLwkCKi3iu5Pf37LXfz-Lp7hTW69EV8uw_hkLAPkiA' # Replace with your Unsplash API key
363
+ background_image = fetch_random_nature_image(api_key)
364
+
365
+ if background_image:
366
+ # Example usage
367
+ fetch_reddit_data('Glitch_in_the_Matrix')
368
+
369
+ # Read data from JSON
370
+ reddit_data = read_json('top_post.json') # Change filename if needed
371
+ title = reddit_data.get('title')
372
+
373
+ filename = "video_" + str(uuid.uuid4())
374
+
375
+ # Convert text to speech
376
+ # voiceover_file = text_to_speech(title, 'voiceover.mp3')
377
+ voiceover_file = eleven_labs_text_to_speech(title, 'voiceover.mp3')
378
+
379
+ # Get audio duration
380
+ audio_duration = get_audio_duration('voiceover.mp3')
381
+
382
+ # Create and save the video
383
+ create_video_from_title(title, background_image, "reddit_post_video_cv2.mp4", audio_duration)
384
+
385
+ # Combine audio and video
386
+ combine_audio_video('reddit_post_video_cv2.mp4', 'voiceover.mp3', filename + '.mp4')
387
+
388
+ options = {
389
+ 'file': 'output/'+ filename + '.mp4',
390
+ 'title': "Amazing Facts Revealed: Unveiling the World's Hidden Wonders #shorts",
391
+ '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",
392
+ 'category': "22",
393
+ 'keywords': "facts, shorts, funny",
394
+ 'privacyStatus': "private"
395
+ }
396
+
397
+ # try:
398
+ # youtube = get_authenticated_service()
399
+ # initialize_upload(youtube, options)
400
+ # upload_video_to_drive('output/'+ filename + '.mp4','1t2lcYNLgz6FTeabzccY_06rvcnTGdQiR')
401
+ # except HttpError as e:
402
+ # print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
main.py-oauth2.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "access_token": "ya29.a0AfB_byCOgc6o05Gy2sr--ly9q-fu1pasaHdO7sf99mc9QMZckk5gD_FIT7lJXjQ3Nl7Ak2YEwwlPqkQ1NjHw5qDEU96pCjOrz1cWgwLQowkP9Pu2VGDSdrrioKUVfGLezq7XhF-9YY08DR9iQhLZkh_EDAPLV5t4Pbz0aCgYKATcSARESFQHGX2MiIcRo1PRx2TYi8IC3A5vfJQ0171",
3
+ "client_id": "672725064244-vqnm51a5ivbm6cnlbsl2mmk71k7243b5.apps.googleusercontent.com",
4
+ "client_secret": "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",
5
+ "refresh_token": "1//0gpokRv3uQZF0CgYIARAAGBASNwF-L9IrwQ6moxZWlGx_tKdcbT2QMKp2LMQRoBMCRMKk5Gp3cLFasTMoYF9SI30il7hG3giukTY",
6
+ "token_expiry": "2024-01-28T20:19:41Z",
7
+ "token_uri": "https://accounts.google.com/o/oauth2/token",
8
+ "user_agent": null,
9
+ "revoke_uri": "https://oauth2.googleapis.com/revoke",
10
+ "id_token": null,
11
+ "id_token_jwt": null,
12
+ "token_response": {
13
+ "access_token": "ya29.a0AfB_byCOgc6o05Gy2sr--ly9q-fu1pasaHdO7sf99mc9QMZckk5gD_FIT7lJXjQ3Nl7Ak2YEwwlPqkQ1NjHw5qDEU96pCjOrz1cWgwLQowkP9Pu2VGDSdrrioKUVfGLezq7XhF-9YY08DR9iQhLZkh_EDAPLV5t4Pbz0aCgYKATcSARESFQHGX2MiIcRo1PRx2TYi8IC3A5vfJQ0171",
14
+ "expires_in": 3599,
15
+ "refresh_token": "1//0gpokRv3uQZF0CgYIARAAGBASNwF-L9IrwQ6moxZWlGx_tKdcbT2QMKp2LMQRoBMCRMKk5Gp3cLFasTMoYF9SI30il7hG3giukTY",
16
+ "scope": "https://www.googleapis.com/auth/youtube.upload",
17
+ "token_type": "Bearer"
18
+ },
19
+ "scopes": ["https://www.googleapis.com/auth/youtube.upload"],
20
+ "token_info_uri": "https://oauth2.googleapis.com/tokeninfo",
21
+ "invalid": false,
22
+ "_class": "OAuth2Credentials",
23
+ "_module": "oauth2client.client"
24
+ }
main_glitch.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import praw
3
+ import json
4
+ import cv2
5
+ import numpy as np
6
+ import textwrap
7
+ from gtts import gTTS
8
+ from pydub import AudioSegment
9
+ import subprocess
10
+ import re
11
+ import os
12
+ import random
13
+ import time
14
+ import sys
15
+ import uuid
16
+ from googleapiclient.discovery import build
17
+ from googleapiclient.errors import HttpError
18
+ from googleapiclient.http import MediaFileUpload
19
+ from oauth2client.client import flow_from_clientsecrets
20
+ from oauth2client.file import Storage
21
+ from oauth2client.tools import run_flow
22
+ from google.auth.transport.requests import Request
23
+ import nltk
24
+ from tts import synthesiser, speaker_embedding
25
+ import soundfile as sf
26
+
27
+ # from tortoise_tts import TextToSpeech
28
+
29
+ # nltk.download('punkt')
30
+
31
+ # Define the output folder path
32
+ output_folder = 'output'
33
+
34
+ # Constants
35
+ SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]
36
+ CLIENT_SECRETS_FILE = "client_secrets.json" # Update with your client_secrets.json file path
37
+ YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
38
+ DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"
39
+ YOUTUBE_API_SERVICE_NAME = "youtube"
40
+ YOUTUBE_API_VERSION = "v3"
41
+ MAX_RETRIES = 10
42
+ RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
43
+ ELEVENLABS_KEY = "153f3875b30f603644cc66a78f1345ea"
44
+
45
+ # Check if the folder exists, if not, create it
46
+ if not os.path.exists(output_folder):
47
+ os.makedirs(output_folder)
48
+
49
+ 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" ]
50
+
51
+ def contains_banned_word(text, banned_words):
52
+ for word in banned_words:
53
+ if word in text.lower():
54
+ return True
55
+ return False
56
+
57
+ def fetch_reddit_data(subreddit_name):
58
+ # Reddit API Credentials
59
+ client_id = 'TIacEazZS9FHWzDZ3T-3cA'
60
+ client_secret = '6Urwdiqo_cC8Gt040K_rBhnR3r8CLg'
61
+ user_agent = 'script by u/lakpriya1'
62
+
63
+ # Initialize PRAW with your credentials
64
+ reddit = praw.Reddit(client_id=client_id, client_secret=client_secret, user_agent=user_agent)
65
+
66
+ subreddit = reddit.subreddit(subreddit_name)
67
+
68
+ for _ in range(10): # Limit the number of attempts to 10
69
+ post = subreddit.random()
70
+ # Check if the title contains a pattern resembling a URL
71
+ 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:
72
+ post_data = {'title': post.title, 'selftext': post.selftext}
73
+
74
+ with open('top_post.json', 'w') as outfile:
75
+ json.dump(post_data, outfile, indent=4)
76
+
77
+ print("Top post data saved to top_post.json")
78
+ return # Exit after finding a suitable post
79
+
80
+ print("No suitable post found without a URL-like string in the title.")
81
+
82
+ def read_json(filename):
83
+ print("Reading data from", filename)
84
+ with open(filename, 'r') as file:
85
+ data = json.load(file)
86
+ return data
87
+
88
+ def wrap_text(text, wrap_width):
89
+ return textwrap.wrap(text, width=wrap_width)
90
+
91
+ def resize_background_image(image_path, frame_width, frame_height):
92
+ print("Resizing background image")
93
+ image = cv2.imread(image_path)
94
+ h, w = image.shape[:2]
95
+ scale = max(frame_width / w, frame_height / h)
96
+ new_w, new_h = int(w * scale), int(h * scale)
97
+ resized_image = cv2.resize(image, (new_w, new_h))
98
+
99
+ # Cropping the resized image to fill the frame
100
+ startx = new_w // 2 - (frame_width // 2)
101
+ starty = new_h // 2 - (frame_height // 2)
102
+ cropped_image = resized_image[starty:starty+frame_height, startx:startx+frame_width]
103
+ return cropped_image
104
+
105
+ 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):
106
+ default_font = cv2.FONT_HERSHEY_COMPLEX
107
+ if fonts is None:
108
+ fonts = [default_font] * len(texts) # Use default font if not specified
109
+
110
+ 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):
111
+ lines = wrap_text(text, wrap_width)
112
+
113
+ # Calculate the total height of the text block
114
+ total_text_height = line_height * len(lines)
115
+
116
+ # Starting Y position to center text vertically
117
+ if position[1] is None:
118
+ start_y = (frame.shape[0] - total_text_height) // 2 + 100
119
+ else:
120
+ start_y = position[1]
121
+
122
+ for line in lines:
123
+ text_size = cv2.getTextSize(line, font, font_scale, 1)[0]
124
+ text_x = position[0] - text_size[0] // 2
125
+ text_y = start_y + line_height
126
+
127
+ cv2.putText(frame, line, (text_x, text_y), font, font_scale, stroke_color, 8, cv2.LINE_AA)
128
+ cv2.putText(frame, line, (text_x, text_y), font, font_scale, font_color, 2, cv2.LINE_AA)
129
+
130
+ start_y += line_height
131
+
132
+ # def create_video_from_title(title, background_image, output_filename, audio_duration):
133
+ # print("Creating video from title")
134
+ # # Video properties
135
+ # fps = 24
136
+ # frame_width, frame_height = 720, 1280 # 9:16 aspect ratio
137
+ # frame_count = audio_duration * fps
138
+
139
+ # # Logo images
140
+ # top_logo = load_logo('logo.png', frame_width, frame_height, 'top')
141
+ # bottom_logo = load_logo('sub.png', frame_width, frame_height, 'bottom')
142
+
143
+ # # OpenCV VideoWriter
144
+ # fourcc = cv2.VideoWriter_fourcc(*'mp4v')
145
+ # out = cv2.VideoWriter(output_filename, fourcc, fps, (frame_width, frame_height))
146
+
147
+ # # Resize the background image
148
+ # background = resize_background_image(background_image, frame_width, frame_height)
149
+
150
+ # for i in range(int(np.floor(frame_count))):
151
+ # frame = background.copy() # Use the resized background image
152
+
153
+ # # Overlay logos
154
+ # frame = overlay_logo(frame, top_logo)
155
+ # frame = overlay_logo(frame, bottom_logo)
156
+
157
+ # # Add title to frame with text wrapping and highlight
158
+ # 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
159
+
160
+ # out.write(frame) # Write the frame to the video
161
+
162
+ # out.release()
163
+
164
+ def create_video_from_title(title, sentences, background_image, output_filename, audio_durations):
165
+ print("Creating video from title")
166
+ fps = 24
167
+ frame_width, frame_height = 720, 1280 # 9:16 aspect ratio
168
+
169
+ # OpenCV VideoWriter
170
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
171
+ out = cv2.VideoWriter(output_filename, fourcc, fps, (frame_width, frame_height))
172
+
173
+ # Logo images
174
+ top_logo = load_logo('G.png', frame_width, frame_height, 'top')
175
+ bottom_logo = load_logo('follow.png', frame_width, frame_height, 'bottom')
176
+
177
+ # Resize the background image
178
+ background = resize_background_image(background_image, frame_width, frame_height)
179
+
180
+ # Define font settings for title and sentence
181
+ title_font = cv2.FONT_HERSHEY_TRIPLEX
182
+ sentence_font = cv2.FONT_HERSHEY_TRIPLEX
183
+ title_font_scale = 1.5 # Larger font for the title
184
+ sentence_font_scale = 1.2 # Normal font for the sentence
185
+ title_line_height = 50
186
+ sentence_line_height = 50
187
+
188
+ # Font color as white
189
+ white_color = (255, 255, 255) # BGR color code for white
190
+ stroke_color = (0, 0, 0) # BGR color code for black
191
+
192
+ title = preprocess_text(title)
193
+
194
+ current_frame = 0
195
+ for sentence, duration in zip(sentences, audio_durations):
196
+ sentence_frames = int(duration * fps)
197
+ for i in range(sentence_frames):
198
+ frame = background.copy()
199
+
200
+ # Overlay logos
201
+ frame = overlay_logo(frame, top_logo)
202
+ frame = overlay_logo(frame, bottom_logo)
203
+
204
+ # Position for title and sentence
205
+ title_position = (frame_width // 2, frame_height // 4) # Title at the top
206
+ sentence_position = (frame_width // 2, None) # Sentence at the center
207
+
208
+ sentence = preprocess_text(sentence)
209
+
210
+ # Add title and sentence to frame with specific fonts, sizes, and colors
211
+ put_text_with_stroke(frame,
212
+ [title, sentence],
213
+ [title_position, sentence_position],
214
+ [title_font_scale, sentence_font_scale],
215
+ [title_line_height, sentence_line_height],
216
+ [25, 25],
217
+ font_colors=[white_color, white_color],
218
+ stroke_colors=[stroke_color, stroke_color],
219
+ fonts=[title_font, sentence_font])
220
+
221
+ out.write(frame)
222
+ current_frame += 1
223
+
224
+ out.release()
225
+
226
+
227
+ def tts_per_sentence(sentences, output_folder, silence_duration=1000):
228
+ audio_durations = []
229
+ audio_files = []
230
+
231
+ for index, sentence in enumerate(sentences):
232
+ output_file = f'{output_folder}/voiceover_{index}.wav'
233
+ text_to_speech_using_speecht5(sentence, output_file)
234
+ audio = AudioSegment.from_wav(output_file)
235
+ silence = AudioSegment.silent(duration=silence_duration)
236
+ audio_with_silence = audio + silence
237
+ audio_with_silence.export(output_file, format="wav")
238
+ audio_duration = len(audio_with_silence) / 1000.0
239
+ audio_durations.append(audio_duration)
240
+ audio_files.append(output_file)
241
+ return audio_files, audio_durations
242
+
243
+ # def eleven_labs_text_to_speech(text, output_file, voice_id):
244
+ # url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
245
+
246
+ # headers = {
247
+ # "Accept": "audio/mpeg",
248
+ # "Content-Type": "application/json",
249
+ # "xi-api-key": ELEVENLABS_KEY
250
+ # }
251
+
252
+ # data = {
253
+ # "text": text,
254
+ # "model_id": "eleven_monolingual_v1",
255
+ # "voice_settings": {
256
+ # "stability": 0.5,
257
+ # "similarity_boost": 0.5,
258
+ # "speed": 0.3,
259
+ # }
260
+ # }
261
+
262
+ # response = requests.post(url, json=data, headers=headers)
263
+ # if response.status_code == 200:
264
+ # with open(output_file, 'wb') as f:
265
+ # for chunk in response.iter_content(chunk_size=1024):
266
+ # f.write(chunk)
267
+ # print(f"Audio content written to {output_file}")
268
+ # else:
269
+ # print(f"Failed to synthesize speech: {response.content}")
270
+
271
+ def text_to_speech_using_speecht5(text, output_file):
272
+ # Use the synthesiser from tts.py
273
+ speech = synthesiser(text, forward_params={"speaker_embeddings": speaker_embedding})
274
+ sf.write(output_file, speech["audio"], samplerate=speech["sampling_rate"])
275
+ print(f"Audio content written to {output_file}")
276
+
277
+ def fetch_random_nature_image(api_key):
278
+ print("Fetching random nature image from Unsplash")
279
+ url = f"https://api.unsplash.com/photos/random?query=horror&client_id={api_key}"
280
+ response = requests.get(url)
281
+ if response.status_code == 200:
282
+ img_url = response.json()['urls']['regular']
283
+ img_data = requests.get(img_url).content
284
+ with open('nature_background.jpg', 'wb') as handler:
285
+ handler.write(img_data)
286
+ return 'nature_background.jpg'
287
+ else:
288
+ print("Failed to fetch image from Unsplash")
289
+ return None
290
+
291
+ def preprocess_text(text):
292
+ # Replace Unicode right single quotation mark with ASCII apostrophe
293
+ text = text.replace('\u2019', "'")
294
+ # If there are other specific characters causing issues, replace them similarly
295
+ return text
296
+
297
+ def text_to_speech(text, output_file):
298
+ print("Converting text to speech")
299
+ tts = gTTS(text=text, lang='en')
300
+ tts.save(output_file)
301
+ return output_file
302
+
303
+ def get_audio_duration(audio_file):
304
+ print("Getting audio duration")
305
+ audio = AudioSegment.from_mp3(audio_file)
306
+ return len(audio) / 1000.0 # Convert to seconds
307
+
308
+ def combine_audio_video(video_file, audio_file, output_file, audio_delay_seconds=0.3):
309
+ # Construct the full path for the output file
310
+ output_file = os.path.join(output_folder, output_file)
311
+
312
+ # Add a delay to the audio start
313
+ 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}"'
314
+ subprocess.call(cmd, shell=True)
315
+ print("Successfully made the video:", output_file)
316
+
317
+ def load_logo(logo_path, frame_width, frame_height, position='top'):
318
+ logo = cv2.imread(logo_path, cv2.IMREAD_UNCHANGED) # Load with alpha channel
319
+ logo_height, logo_width = logo.shape[:2]
320
+
321
+ # Scaling down the logo if it's too big
322
+ scale_factor = min(1, frame_width / 3 / logo_width, frame_height / 10 / logo_height)
323
+ new_size = (int(logo_width * scale_factor*1.3), int(logo_height * scale_factor*1.3))
324
+ logo = cv2.resize(logo, new_size, interpolation=cv2.INTER_AREA)
325
+
326
+ # Positioning
327
+ x_center = frame_width // 2 - logo.shape[1] // 2
328
+ if position == 'top':
329
+ y_pos = 100 # 10 pixels from the top
330
+ else: # 'bottom'
331
+ y_pos = frame_height - logo.shape[0] - 100 # 10 pixels from the bottom
332
+
333
+ return logo, (x_center, y_pos)
334
+
335
+ def overlay_logo(frame, logo_info):
336
+ logo, (x, y) = logo_info
337
+ y1, y2 = y, y + logo.shape[0]
338
+ x1, x2 = x, x + logo.shape[1]
339
+
340
+ if logo.shape[2] == 4: # If the logo has an alpha channel
341
+ alpha_logo = logo[:, :, 3] / 255.0
342
+ alpha_frame = 1.0 - alpha_logo
343
+ for c in range(0, 3):
344
+ frame[y1:y2, x1:x2, c] = (alpha_logo * logo[:, :, c] +
345
+ alpha_frame * frame[y1:y2, x1:x2, c])
346
+ else: # If the logo does not have an alpha channel
347
+ frame[y1:y2, x1:x2] = logo
348
+
349
+ return frame
350
+
351
+ def get_authenticated_service():
352
+ flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_UPLOAD_SCOPE)
353
+ storage = Storage(f"{sys.argv[0]}-oauth2.json")
354
+ credentials = storage.get()
355
+ if credentials is None or credentials.invalid:
356
+ credentials = run_flow(flow, storage)
357
+ return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, credentials=credentials)
358
+
359
+ def upload_video_to_drive(video_file, folder_id=None):
360
+ """Uploads a video to Google Drive."""
361
+ # Check if the credentials are stored
362
+ storage = Storage(f"{sys.argv[0]}-oauth2.json")
363
+ credentials = storage.get()
364
+
365
+ # If credentials are not available or are invalid, run the flow
366
+ if not credentials or credentials.invalid:
367
+ flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=[DRIVE_SCOPE])
368
+ credentials = run_flow(flow, storage)
369
+
370
+ service = build('drive', 'v3', credentials=credentials)
371
+
372
+ file_metadata = {
373
+ 'name': os.path.basename(video_file),
374
+ 'mimeType': 'video/mp4'
375
+ }
376
+ if folder_id:
377
+ file_metadata['parents'] = [folder_id]
378
+
379
+ media = MediaFileUpload(video_file, mimetype='video/mp4', resumable=True)
380
+ file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
381
+
382
+ print('File ID: %s' % file.get('id'))
383
+
384
+ def initialize_upload(youtube, options):
385
+ tags = None
386
+ if 'keywords' in options and options['keywords']:
387
+ tags = options['keywords'].split(",")
388
+
389
+ body = dict(
390
+ snippet=dict(
391
+ title=options['title'],
392
+ description=options['description'],
393
+ tags=tags,
394
+ categoryId=options['category']
395
+ ),
396
+ status=dict(
397
+ privacyStatus=options['privacyStatus']
398
+ )
399
+ )
400
+
401
+ # Call the API's videos.insert method to create and upload the video.
402
+ insert_request = youtube.videos().insert(
403
+ part=",".join(body.keys()),
404
+ body=body,
405
+ # The chunksize parameter specifies the size of each chunk of data, in
406
+ # bytes, that will be uploaded at a time. Set a higher value for
407
+ # reliable connections as fewer chunks lead to faster uploads. Set a lower
408
+ # value for better recovery on less reliable connections.
409
+ #
410
+ # Setting "chunksize" equal to -1 in the code below means that the entire
411
+ # file will be uploaded in a single HTTP request. (If the upload fails,
412
+ # it will still be retried where it left off.) This is usually a best
413
+ # practice, but if you're using Python older than 2.6 or if you're
414
+ # running on App Engine, you should set the chunksize to something like
415
+ # 1024 * 1024 (1 megabyte).
416
+ media_body=MediaFileUpload(options["file"], chunksize=-1, resumable=True)
417
+ )
418
+
419
+ resumable_upload(insert_request)
420
+
421
+ # This method implements an exponential backoff strategy to resume a
422
+ # failed upload.
423
+ def resumable_upload(insert_request):
424
+ response = None
425
+ error = None
426
+ retry = 0
427
+ while response is None:
428
+ try:
429
+ print("Uploading file...")
430
+ status, response = insert_request.next_chunk()
431
+ if response is not None:
432
+ if 'id' in response:
433
+ print("Video id '%s' was successfully uploaded." % response['id'])
434
+ else:
435
+ exit("The upload failed with an unexpected response: %s" % response)
436
+ except HttpError as e:
437
+ if e.resp.status in RETRIABLE_STATUS_CODES:
438
+ error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
439
+ e.content)
440
+ else:
441
+ raise
442
+ # except RETRIABLE_EXCEPTIONS as e:
443
+ # error = "A retriable error occurred: %s" % e
444
+
445
+ if error is not None:
446
+ print(error)
447
+ retry += 1
448
+ if retry > MAX_RETRIES:
449
+ exit("No longer attempting to retry.")
450
+
451
+ max_sleep = 2 ** retry
452
+ sleep_seconds = random.random() * max_sleep
453
+ print("Sleeping %f seconds and then retrying..." % sleep_seconds)
454
+ time.sleep(sleep_seconds)
455
+
456
+ # def eleven_labs_text_to_speech(text, output_file):
457
+ # voice_ids = {
458
+ # "ndntWUKwYjgJGYkvF6at",
459
+ # "SVLJSgUbrKWfY8HvF2Xd",
460
+ # "sjdiTCylizqR74A3ssv4",
461
+ # }
462
+ # # randomly pick one of the voices
463
+ # voice_id = random.choice(list(voice_ids))
464
+ # url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
465
+
466
+ # headers = {
467
+ # "Accept": "audio/mpeg",
468
+ # "Content-Type": "application/json",
469
+ # "xi-api-key": ELEVENLABS_KEY
470
+ # }
471
+
472
+ # data = {
473
+ # "text": text,
474
+ # "model_id": "eleven_monolingual_v1",
475
+ # "voice_settings": {
476
+ # "stability": 0.5,
477
+ # "similarity_boost": 0.5,
478
+ # "speed": 0.3,
479
+ # }
480
+ # }
481
+
482
+ # response = requests.post(url, json=data, headers=headers)
483
+ # if response.status_code == 200:
484
+ # with open(output_file, 'wb') as f:
485
+ # for chunk in response.iter_content(chunk_size=1024):
486
+ # f.write(chunk)
487
+ # print(f"Audio content written to {output_file}")
488
+ # else:
489
+ # print(f"Failed to synthesize speech: {response.content}")
490
+
491
+ def combine_audio_files(audio_files, output_file):
492
+ combined = AudioSegment.empty()
493
+ for file in audio_files:
494
+ audio = AudioSegment.from_mp3(file)
495
+ combined += audio
496
+ combined.export(output_file, format="mp3")
497
+ return output_file
498
+
499
+ api_key = 'VhLwkCKi3iu5Pf37LXfz-Lp7hTW69EV8uw_hkLAPkiA' # Replace with your Unsplash API key
500
+ background_image = fetch_random_nature_image(api_key)
501
+
502
+ if background_image:
503
+ fetch_reddit_data('Glitch_in_the_Matrix')
504
+ reddit_data = read_json('top_post.json')
505
+ title = reddit_data.get('title')
506
+ selftext = reddit_data.get('selftext')
507
+
508
+ # Split title into sentences
509
+ sentences = nltk.sent_tokenize(selftext)
510
+
511
+ # Generate audio for each sentence and get durations
512
+ audio_files, audio_durations = tts_per_sentence(sentences, 'audio')
513
+
514
+ # Create and save the video
515
+ create_video_from_title(title, sentences, background_image, "reddit_post_video_cv2.mp4", audio_durations)
516
+
517
+ # Combine all audio files into one (if needed)
518
+ combined_audio_file = combine_audio_files(audio_files, 'combined_voiceover.mp3') # Implement this function
519
+
520
+ filename = "video_" + str(uuid.uuid4())
521
+
522
+ # Combine the final video and audio
523
+ combine_audio_video('reddit_post_video_cv2.mp4', combined_audio_file, filename + '.mp4')
524
+
525
+ # if background_image:
526
+ # # Example usage
527
+ # fetch_reddit_data('Glitch_in_the_Matrix')
528
+
529
+ # # Read data from JSON
530
+ # reddit_data = read_json('top_post.json') # Change filename if needed
531
+ # title = reddit_data.get('title')
532
+
533
+ # filename = "video_" + str(uuid.uuid4())
534
+
535
+ # # Convert text to speech
536
+ # # voiceover_file = text_to_speech(title, 'voiceover.mp3')
537
+ # voiceover_file = eleven_labs_text_to_speech(title, 'voiceover.mp3')
538
+
539
+ # # Get audio duration
540
+ # audio_duration = get_audio_duration('voiceover.mp3')
541
+
542
+ # # Create and save the video
543
+ # create_video_from_title(title, background_image, "reddit_post_video_cv2.mp4", audio_duration)
544
+
545
+ # # Combine audio and video
546
+ # combine_audio_video('reddit_post_video_cv2.mp4', 'voiceover.mp3', filename + '.mp4')
547
+
548
+ # options = {
549
+ # 'file': 'output/'+ filename + '.mp4',
550
+ # 'title': "Amazing Facts Revealed: Unveiling the World's Hidden Wonders #shorts",
551
+ # '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",
552
+ # 'category': "22",
553
+ # 'keywords': "facts, shorts, funny",
554
+ # 'privacyStatus': "private"
555
+ # }
556
+
557
+ # try:
558
+ # youtube = get_authenticated_service()
559
+ # initialize_upload(youtube, options)
560
+ # upload_video_to_drive('output/'+ filename + '.mp4','1t2lcYNLgz6FTeabzccY_06rvcnTGdQiR')
561
+ # except HttpError as e:
562
+ # print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
nature_background.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ requests
2
+ praw
3
+ opencv-python
4
+ numpy
5
+ gtts
6
+ pydub
7
+ google-api-python-client
8
+ google-auth
9
+ google-auth-httplib2
10
+ google-auth-oauthlib
11
+ oauth2client
12
+ nltk
13
+ gradio
14
+ soundfile
15
+ transformers
16
+ datasets[audio]
sub.png ADDED
sub.webp ADDED
test.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+
3
+ import httplib2
4
+ import os
5
+ import random
6
+ import sys
7
+ import time
8
+
9
+ from apiclient.discovery import build
10
+ from apiclient.errors import HttpError
11
+ from apiclient.http import MediaFileUpload
12
+ from oauth2client.client import flow_from_clientsecrets
13
+ from oauth2client.file import Storage
14
+ from oauth2client.tools import argparser, run_flow
15
+
16
+
17
+ # Explicitly tell the underlying HTTP transport library not to retry, since
18
+ # we are handling retry logic ourselves.
19
+ httplib2.RETRIES = 1
20
+
21
+ # Maximum number of times to retry before giving up.
22
+ MAX_RETRIES = 10
23
+
24
+ # Always retry when these exceptions are raised.
25
+ # RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
26
+ # httplib.IncompleteRead, httplib.ImproperConnectionState,
27
+ # httplib.CannotSendRequest, httplib.CannotSendHeader,
28
+ # httplib.ResponseNotReady, httplib.BadStatusLine)
29
+
30
+ # Always retry when an apiclient.errors.HttpError with one of these status
31
+ # codes is raised.
32
+ RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
33
+
34
+ # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
35
+ # the OAuth 2.0 information for this application, including its client_id and
36
+ # client_secret. You can acquire an OAuth 2.0 client ID and client secret from
37
+ # the Google API Console at
38
+ # https://console.cloud.google.com/.
39
+ # Please ensure that you have enabled the YouTube Data API for your project.
40
+ # For more information about using OAuth2 to access the YouTube Data API, see:
41
+ # https://developers.google.com/youtube/v3/guides/authentication
42
+ # For more information about the client_secrets.json file format, see:
43
+ # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
44
+ CLIENT_SECRETS_FILE = "client_secrets.json"
45
+
46
+ # This OAuth 2.0 access scope allows an application to upload files to the
47
+ # authenticated user's YouTube channel, but doesn't allow other types of access.
48
+ YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
49
+ YOUTUBE_API_SERVICE_NAME = "youtube"
50
+ YOUTUBE_API_VERSION = "v3"
51
+
52
+ # This variable defines a message to display if the CLIENT_SECRETS_FILE is
53
+ # missing.
54
+ MISSING_CLIENT_SECRETS_MESSAGE = """
55
+ WARNING: Please configure OAuth 2.0
56
+
57
+ To make this sample run you will need to populate the client_secrets.json file
58
+ found at:
59
+
60
+ %s
61
+
62
+ with information from the API Console
63
+ https://console.cloud.google.com/
64
+
65
+ For more information about the client_secrets.json file format, please visit:
66
+ https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
67
+ """ % os.path.abspath(os.path.join(os.path.dirname(__file__),
68
+ CLIENT_SECRETS_FILE))
69
+
70
+ VALID_PRIVACY_STATUSES = ("public", "private", "unlisted")
71
+
72
+
73
+ def get_authenticated_service(args):
74
+ flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
75
+ scope=YOUTUBE_UPLOAD_SCOPE,
76
+ message=MISSING_CLIENT_SECRETS_MESSAGE)
77
+
78
+ storage = Storage("%s-oauth2.json" % sys.argv[0])
79
+ credentials = storage.get()
80
+
81
+ if credentials is None or credentials.invalid:
82
+ credentials = run_flow(flow, storage, args)
83
+
84
+ return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
85
+ http=credentials.authorize(httplib2.Http()))
86
+
87
+ def initialize_upload(youtube, options):
88
+ tags = None
89
+ if options.keywords:
90
+ tags = options.keywords.split(",")
91
+
92
+ body=dict(
93
+ snippet=dict(
94
+ title=options.title,
95
+ description=options.description,
96
+ tags=tags,
97
+ categoryId=options.category
98
+ ),
99
+ status=dict(
100
+ privacyStatus=options.privacyStatus
101
+ )
102
+ )
103
+
104
+ # Call the API's videos.insert method to create and upload the video.
105
+ insert_request = youtube.videos().insert(
106
+ part=",".join(body.keys()),
107
+ body=body,
108
+ # The chunksize parameter specifies the size of each chunk of data, in
109
+ # bytes, that will be uploaded at a time. Set a higher value for
110
+ # reliable connections as fewer chunks lead to faster uploads. Set a lower
111
+ # value for better recovery on less reliable connections.
112
+ #
113
+ # Setting "chunksize" equal to -1 in the code below means that the entire
114
+ # file will be uploaded in a single HTTP request. (If the upload fails,
115
+ # it will still be retried where it left off.) This is usually a best
116
+ # practice, but if you're using Python older than 2.6 or if you're
117
+ # running on App Engine, you should set the chunksize to something like
118
+ # 1024 * 1024 (1 megabyte).
119
+ media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
120
+ )
121
+
122
+ resumable_upload(insert_request)
123
+
124
+ # This method implements an exponential backoff strategy to resume a
125
+ # failed upload.
126
+ def resumable_upload(insert_request):
127
+ response = None
128
+ error = None
129
+ retry = 0
130
+ while response is None:
131
+ try:
132
+ print("Uploading file...")
133
+ status, response = insert_request.next_chunk()
134
+ if response is not None:
135
+ if 'id' in response:
136
+ print("Video id '%s' was successfully uploaded." % response['id'])
137
+ else:
138
+ exit("The upload failed with an unexpected response: %s" % response)
139
+ except HttpError as e:
140
+ if e.resp.status in RETRIABLE_STATUS_CODES:
141
+ error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
142
+ e.content)
143
+ else:
144
+ raise
145
+ # except RETRIABLE_EXCEPTIONS as e:
146
+ # error = "A retriable error occurred: %s" % e
147
+
148
+ if error is not None:
149
+ print(error)
150
+ retry += 1
151
+ if retry > MAX_RETRIES:
152
+ exit("No longer attempting to retry.")
153
+
154
+ max_sleep = 2 ** retry
155
+ sleep_seconds = random.random() * max_sleep
156
+ print("Sleeping %f seconds and then retrying..." % sleep_seconds)
157
+ time.sleep(sleep_seconds)
158
+
159
+ if __name__ == '__main__':
160
+ argparser.add_argument("--file", required=True, help="Video file to upload")
161
+ argparser.add_argument("--title", help="Video title", default="Test Title")
162
+ argparser.add_argument("--description", help="Video description",
163
+ default="Test Description")
164
+ argparser.add_argument("--category", default="22",
165
+ help="Numeric video category. " +
166
+ "See https://developers.google.com/youtube/v3/docs/videoCategories/list")
167
+ argparser.add_argument("--keywords", help="Video keywords, comma separated",
168
+ default="")
169
+ argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
170
+ default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
171
+ args = argparser.parse_args()
172
+
173
+ if not os.path.exists(args.file):
174
+ exit("Please specify a valid file using the --file= parameter.")
175
+
176
+ youtube = get_authenticated_service(args)
177
+ try:
178
+ initialize_upload(youtube, args)
179
+ except HttpError as e:
180
+ print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
tik.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, redirect
2
+ import requests
3
+ import random
4
+
5
+ app = Flask(__name__)
6
+
7
+ CLIENT_ID = 'awfh19twbfyt0de0'
8
+ CLIENT_SECRET = 'awfh19twbfyt0de0'
9
+ REDIRECT_URI = 'https://127.0.0.1:5000/callback/' # This must match the redirect URI registered in TikTok Developer Portal
10
+
11
+ @app.route('/')
12
+ def home():
13
+ csrfState = format(random.randint(0, 36**16), 'x')
14
+
15
+ # Redirect the user to TikTok's authorization page
16
+ tiktok_auth_url = f"https://open-api.tiktok.com/platform/oauth/connect/?client_key={CLIENT_ID}&scope=user.info.basic,video.list&response_type=code&redirect_uri={REDIRECT_URI}&state={csrfState}"
17
+ return redirect(tiktok_auth_url)
18
+
19
+ @app.route('/callback')
20
+ def callback():
21
+ # Get the code from the callback URL
22
+ code = request.args.get('code')
23
+
24
+ # Exchange the code for an access token
25
+ token_url = "https://open-api.tiktok.com/oauth/access_token/"
26
+ payload = {
27
+ 'client_key': CLIENT_ID,
28
+ 'client_secret': CLIENT_SECRET,
29
+ 'code': code,
30
+ 'grant_type': 'authorization_code',
31
+ }
32
+ response = requests.post(token_url, data=payload)
33
+ access_token = response.json().get('data', {}).get('access_token')
34
+
35
+ return f"Access Token: {access_token}"
36
+
37
+ if __name__ == '__main__':
38
+ app.run(debug=True)
top_post.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "title": "It wasn\u2019t my grandfather\u2019s body in the casket",
3
+ "selftext": "This happened last year. My grandfather\u2019s health had been declining from dementia for several months until one day he just dropped dead on the floor at home. Despite how sudden it was, he went peacefully.\n\nI hadn\u2019t seen him since Christmas almost a full year prior, and even though he didn\u2019t look so great, he was completely recognizable as him. Then the day of the funeral came and I hesitated to get close to his body. It was my first time as an adult having a family member die, and it just felt\u2026 more bleak than my other grandparents who died back when I was a kid or teen.\n\nEventually, I couldn\u2019t avoid it anymore, and my mom led me to the casket. When I saw his face, it wasn\u2019t his. It was mine.\n\nHis hair, his nose, his bone structure were all gone, replaced with my own features. I was staring at my own dead body lying in the casket, and no matter how many times I rubbed my eyes or looked away, it never changed.\n\nI don\u2019t look like my grandfather. For starters, I\u2019m a woman. My face is thinner, my jaw has a different shape, and my nose is pretty unique. Granted, I have short hair\u2014a bit like his\u2014but not the exact same. But it was undeniably me in the casket. Not someone who looked like me. It was me.\n\nI left the casket and began talking with family members. Every so often, I\u2019d go back to see if something had changed, though it was always the same. No one else mentioned it, and I was too scared to say anything myself. So I thought I must be the only one seeing myself in the casket\n\nIn all likelihood, it must have been a hallucination of some kind. Maybe it was some sort of stress response my brain created in the moment, but it\u2019s odd that nothing else was affected by the hallucination. Not a single thing seemed out of the ordinary aside from my body being in the casket.\n\nI don\u2019t know what it means, but it freaked me out."
4
+ }
tts.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ from datasets import load_dataset
3
+ import torch
4
+
5
+ print(torch.cuda.is_available()) # Should return True if a GPU is available
6
+
7
+ synthesiser = pipeline("text-to-speech", "microsoft/speecht5_tts")
8
+
9
+ embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
10
+ speaker_embedding = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
11
+ # You can replace this embedding with your own as well.
12
+
13
+ # speech = synthesiser("Hello, my dog is cooler than you!", forward_params={"speaker_embeddings": speaker_embedding})
14
+
15
+ # sf.write("speech.wav", speech["audio"], samplerate=speech["sampling_rate"])