-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordFinder.py
232 lines (155 loc) · 5.36 KB
/
wordFinder.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
from youtube_transcript_api import YouTubeTranscriptApi
from youtubesearchpython import *
import random
import webbrowser
import time
import math
import multiprocessing as mp
import numpy
import json
from sys import argv, exit
#Own modules
import cache
import logger
pietsmiet_id = "UCqwGaUvq_l0RKszeHhZ5leA"
my_id = "UCSEo8hOjRRkbh549h4qfjGg"
yt_id_en = "3MOgiF_TIEI"
yt_id_de = "F7xygLAk2X0"
lg = logger.Logger()
lg.enabled = True
def get_video_ids(channel_id, depth):
#Check if needed ids are already cached?
if cache.id_cache_available(channel_id, depth) > 0:
return cache.load_ids(channel_id, depth)
counter = 0
playlist = Playlist(playlist_from_channel_id(channel_id))
lg.print_log(f'Videos Retrieved: {len(playlist.videos)}')
while playlist.hasMoreVideos and counter <= depth:
lg.print_log('Getting more videos...')
playlist.getNextVideos()
lg.print_log(f'Videos Retrieved: {len(playlist.videos)}')
counter += 1
lg.print_log('Found all the videos.')
#Get list with ids
ids = []
for video in playlist.videos:
ids.append(video["id"])
#Cache ids
cache.save_ids(ids, channel_id, depth)
return ids
# ----
#Subtitles
# ----
def is_language_available(video_id):
try:
transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
is_de = False
for t in transcript_list:
if t.language_code == "de":
is_de = True
return is_de
except:
return False
def get_subtitle(video_id):
if cache.subtitle_cache_available(video_id):
lg.print_log("Is cached!")
return cache.load_subtitle(video_id)
if not is_language_available(video_id):
return
subtitle = YouTubeTranscriptApi.get_transcript(video_id, languages=['de'])
#Cache subtitle
cache.save_subtitle(subtitle, video_id)
return subtitle
def download_subtitles(channel_id, amount):
lg.print_log("[Downloading subtitles]")
ids = get_video_ids(channel_id, math.ceil(amount / 100))
for i in range(amount):
get_subtitle(ids[i])
lg.print_log("Downloaded: " + str(i) + " / " + str(amount))
# ----
# Search
# ----
def search_words_video(words, video_id, exact = False):
start_whole = time.time()
start_sub = time.time()
subtitle = get_subtitle(video_id)
end_sub = time.time()
occ = []
if subtitle == None:
return []
if len(words.split()) > 1:
exact = False
start_search = time.time()
for part in subtitle:
if exact:
if words in part["text"].split():
occ.append(part)
else:
if words in part["text"]:
occ.append(part)
end_search = time.time()
end_whole = time.time()
lg.print_log("Getting subs took: " + str(end_sub - start_sub) + "s")
lg.print_log("Searching took: " + str(end_search - start_search) + "s")
lg.print_log(" ---> Everything took: " + str(end_whole - start_whole) + "s")
return occ
def _search_words_videos(parameter_data):
found_words = []
cache.LOADED_SUBTITLES = parameter_data[2]
for counter, video_id in enumerate(parameter_data[1]):
lg.set_box(True)
lg.print_log(" [" + str(counter) + "] ")
found = {"video_id": video_id, "keys": search_words_video(parameter_data[0], video_id, True)}
if len(found["keys"]) != 0:
found_words.append(found)
lg.print_log(found)
lg.set_box(False)
return found_words
# ----
# Multiprocessing
# ----
def run_search_async(words, channel_id, depth, save = True):
ids = get_video_ids(channel_id, depth)
print("--------------")
id_chunks = numpy.array_split(ids, mp.cpu_count())
parameter_data = []
for i in id_chunks:
parameter_data.append([words, list(i), cache.LOADED_SUBTITLES])
pool = mp.Pool(mp.cpu_count())
result = pool.map(_search_words_videos, parameter_data)
#Cleanup
findings = []
for item in result:
if len(item) > 0:
findings.append(item[0])
#Save
if save:
with open("./results/search_" + channel_id + "_" + words + "_" + str(depth) + ".txt", "w") as f:
json.dump(findings, f)
return findings
# ----
# Misc
# ----
def get_random_video_id(channel_id, depth):
ids = get_video_ids(channel_id, 32)
return ids[random.randint(0, len(ids) - 1)]
def open_yt_clips(video_id, keys):
if keys == None:
return
for key in keys:
webbrowser.open("https://www.youtube.com/watch?v=" + video_id + "&t=" + str(int(key["start"])) + "s")
def main():
if len(argv) != 4:
print('Usage: python3 wordFinder.py "<WORD|PHRASE>" <YT-CHANNEL-ID> <DEPTH>')
exit(1)
try:
startT = time.time()
r = run_search_async(argv[1], argv[2], int(argv[3]))
print(r)
endT = time.time()
print("Took: " + str(endT-startT) + "s")
except Exception as e:
print('Usage: python3 wordFinder.py "<WORD|PHRASE>" <YT-CHANNEL-ID> <DEPTH>')
exit(1)
if __name__ == "__main__":
main()