-
Notifications
You must be signed in to change notification settings - Fork 2
/
tiktok-dl.py
244 lines (195 loc) · 8.59 KB
/
tiktok-dl.py
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
# -*- coding: utf-8 -*-
import argparse
import datetime
import subprocess
import os
import time
import random
import json
import requests
import pytz
from fake_useragent import UserAgent
from dotenv import load_dotenv
from rich import print
api = 'https://tiktok-video-no-watermark2.p.rapidapi.com' # RapidAPI
load_dotenv('.tiktok-dl.env')
def get_user_agent():
ua = UserAgent(
browsers=['firefox', 'chrome'],
os=['windows', 'macos'],
min_percentage=1.3).random
return ua
class TiktokDownloader:
def __init__(self, args):
self.args = args
def req(self, url):
url = url.strip()
data = {
'url': url,
'count': 12,
'cursor': 0,
'web': 1,
'hd': 1
}
headers = {
'User-Agent': get_user_agent(),
'X-RapidAPI-Key': os.getenv('TT_RAPIDAPI_KEY'),
'X-RapidAPI-Host': 'tiktok-video-no-watermark2.p.rapidapi.com',
}
# print(data)
r = requests.get(api, params=data, headers=headers)
if r.json()['code'] == -1:
print('---------------------------------------')
print(f'Retrying {url}...')
time.sleep(random.uniform(1, 30))
return False
else:
# print(r.json())
self.download(r.text)
return True
def req_retry(self, url):
while True:
if self.req(url):
break
def download(self, json_data):
json_data = json.loads(json_data)
post_id = json_data['data']['id']
caption = json_data['data']['title']
hdvid_url = json_data['data']['hdplay']
author = json_data['data']['author']['unique_id']
raw_date = json_data['data']['create_time']
video_url = f"https://www.tiktok.com/@{author}/video/{post_id}"
raw_date = datetime.datetime.fromtimestamp(raw_date)
post_date = raw_date.astimezone(pytz.timezone('Asia/Seoul')).strftime('%y%m%d')
date_time = raw_date.strftime('%Y-%m-%d %H:%M:%S')
dir = ''
if self.args.d:
dir = os.path.join(self.args.d, author)
if not os.path.exists(dir):
os.makedirs(dir)
else:
dir = os.path.join(os.getcwd(), author)
orig_filename = f'{post_id}.temp'
file_location = os.path.join(dir, orig_filename)
base_filename = f'{post_date} - {post_id}'
print('---------------------------------------')
print(f'[italic red]Video {post_id} by [blue]{author}[/blue] on {post_date}[/italic red]')
if not self.args.force:
if os.path.exists(os.path.join(dir, f'{author}.txt')):
with open(os.path.join(dir, f'{author}.txt'), 'r') as f:
if post_id in f.read():
print(f'{post_id} already downloaded!')
return
else:
with open(os.path.join(dir, f'{author}.txt'), 'w'):
pass
print(f'[blue]Caption: [/blue]{caption}')
print(f'[green]Downloading {orig_filename}...[/green]')
subprocess.run(['yt-dlp', '--quiet', '--ignore-config',
'-P', dir,
'-o', f'{orig_filename}',
hdvid_url])
print(f'[italic red]{orig_filename} downloaded![/italic red]')
"""Check codec of video and set output extension accordingly."""
codec_info = subprocess.check_output(['ffprobe',
'-v', 'error',
'-select_streams', 'v:0',
'-show_entries', 'stream=codec_name',
'-of', 'default=noprint_wrappers=1:nokey=1',
f'{file_location}']).decode('utf-8')
codec = codec_info.strip()
output_extension = 'mov' if codec == 'prores' else 'mp4'
filename = f"{base_filename}.{output_extension}"
finalname = os.path.join(dir, filename)
if 'images' in json_data['data']:
print(f"[green]IMAGE MODE: Downloading images...[/green]")
images = json_data['data']['images']
img_dir = os.path.join(dir, f'{base_filename}')
if not os.path.exists(img_dir):
os.makedirs(img_dir)
for i, img_url in enumerate(images):
img_filename = f"{post_id}_{i}.jpg"
subprocess.run(['yt-dlp', '--quiet', '--ignore-config',
'-P', img_dir,
'-o', f'{img_filename}',
'--embed-metadata',
img_url])
print(f'[italic red]{post_id}_{i}.jpg downloaded![/italic red]')
"""Do the conversion and cleanup."""
print(f'[italic yellow]Converting {orig_filename} to {filename}...[/italic yellow]')
if os.path.exists(os.path.join(dir, orig_filename)):
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error',
'-i', f'{file_location}',
'-c', 'copy',
'-movflags', 'use_metadata_tags',
'-metadata', f'url={video_url}',
'-metadata', f'title={caption}',
'-n',
f'{finalname}'])
os.remove(os.path.join(dir, orig_filename))
print(f'[italic white]{filename} created![/italic white]')
print(f'[italic cyan]Set modify date {filename}...[/italic cyan]')
subprocess.run(['exiftool', '-q', '-overwrite_original',
f'{finalname}',
f'-FileModifyDate="{date_time}"'])
with open(os.path.join(dir, f'{author}.txt'), 'a') as f:
f.write(f'{post_id}\n')
class Utility:
def __init__(self, args):
self.args = args
def page_parser(self, url):
tiktok_downloader = TiktokDownloader(self.args)
headers = {
'user-agent': get_user_agent(),
'X-RapidAPI-Key': os.getenv('TT_RAPIDAPI_KEY'),
'X-RapidAPI-Host': 'tiktok-video-no-watermark2.p.rapidapi.com',
}
posts_api = api + '/user/posts'
data = {
'url': url,
'count': self.args.n,
'cursor': 0,
'web': 1,
'hd': 1,
'unique_id': url
}
r = requests.get(posts_api, params=data, headers=headers)
for posts in r.json()['data']['videos']:
tiktok_downloader.req_retry(posts['video_id'])
def main():
parser = argparse.ArgumentParser(description='TikTok Video Downloader')
parser.add_argument('url', default=f"{os.getenv('DEFAULT_ACCOUNT')}", metavar='str', nargs='*', type=str, help='Accepting: Post URL, Account URL, Post ID, account handle with @. (ex. @ive.official)')
parser.add_argument('-d', default=fr"{os.getenv('DOWNLOAD_DIR')}", metavar='str', type=str, help='Download directory')
parser.add_argument('-n', default='33', type=str, help='Number of videos to download (default: latest 33 videos)')
parser.add_argument('-a', metavar='str', type=str, help='Text file containing TikTok URLs')
parser.add_argument('--force', action='store_true', help='Force download, ignore existing video (not recommended)')
args = parser.parse_args()
tiktok_downloader = TiktokDownloader(args)
utility = Utility(args)
try:
if args.a:
with open(args.a) as f:
for url in f.readlines():
tiktok_downloader.req_retry(url)
elif args.url:
if isinstance(args.url, list):
urls = args.url
elif isinstance(args.url, str):
urls = [args.url]
for url in urls:
if '/video/' in url or '/photo/' in url:
tiktok_downloader.req_retry(url)
elif '@' in url:
utility.page_parser(url)
else:
tiktok_downloader.req_retry(url)
else:
print('Please enter a TikTok URL (Account page, post url, or just the id')
print('You can also use -a to specify a text file containing TikTok URLs')
except KeyboardInterrupt:
print("\r", end="")
print("KeyboardInterrupt detected. Exiting gracefully.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == '__main__':
main()