-
Notifications
You must be signed in to change notification settings - Fork 1
/
opensubs-metadata-dump-json.py
executable file
·356 lines (309 loc) · 9.1 KB
/
opensubs-metadata-dump-json.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
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
#!/usr/bin/env python3
import sys
import os
import re
import time
import sqlite3
import json
import subprocess
import shlex
import shutil
#import csv
# generated by subtitles_all.txt.gz-parse.py
db_path = "opensubs-metadata.db"
output_dir = "opensubtitles-scraper-sub-dates"
filename_base = "sub-dates.jsonl"
output_path_base = f"{output_dir}/{filename_base}"
#part_size = 50000 # 1 part = 1 MByte, 120 parts
part_size = 100000 # 1 part = 2 MByte, 60 parts
part_name = "100k"
#part_size = 250000 # 1 part = 5 MByte, 24 parts
# verbose
debug_print = print
# quiet
#debug_print = lambda _: None
# subtitles_all.txt.gz-parse.py
column_names = [
# zcat subtitles_all.txt.gz | head -n1 | tr '\t' '\n' | grep -n . | sed -E 's/^([0-9]+):(.*)$/"\2", # \1/'
"IDSubtitle",
"MovieName", # redundant with IMDB titles
"MovieYear", # redundant with IMDB titles
#"MovieNameIfNoImdbId", # 10% smaller
#"MovieYearIfNoImdbId",
#"LanguageName", # 4 # redundant with ISO639 # 5% smaller
"ISO639",
#"SubAddDate",
"SubAddDateUnix", # 5% smaller
"ImdbID",
#"SubFormat",
#"SubSumCD",
#"MovieReleaseName", # redundant with IMDB titles/aliases # 30% smaller
#"MovieFPS", # not needed? FPS is specified in *.sub files
"SeriesSeason",
"SeriesEpisode",
"SeriesIMDBParent",
#"MovieKind",
"MovieKindIsMovie", # derived from MovieKind # 2% smaller
#"URL", # redundant with IDSubtitle
]
column_names = [
"IDSubtitle",
"SubAddDateUnix",
]
assert column_names[0] == "IDSubtitle" # num = row[0]
column_sql = {
"MovieNameIfNoImdbId": "CASE WHEN ImdbID = 0 THEN MovieName ELSE '' END",
"MovieYearIfNoImdbId": "CASE WHEN ImdbID = 0 THEN MovieYear ELSE 0 END",
"SubAddDateUnix": "unixepoch(SubAddDate)",
"MovieKindIsMovie": "CASE WHEN MovieKind = 'movie' THEN 1 ELSE 0 END",
}
column_types = {
"IDSubtitle": int,
"MovieName": str,
"MovieNameIfNoImdbId": str,
"MovieYear": int,
"MovieYearIfNoImdbId": int,
"LanguageName": str,
"ISO639": str,
"SubAddDate": str,
"SubAddDateUnix": int,
"ImdbID": int,
"SubFormat": str,
"SubSumCD": int,
"MovieReleaseName": str,
"MovieFPS": float,
"SeriesSeason": int,
"SeriesEpisode": int,
"SeriesIMDBParent": int,
"MovieKind": str,
"MovieKindIsMovie": int,
"URL": str,
}
# TODO better?
type_name = {
int: "int",
float: "float",
str: "str",
}
if output_path_base.endswith(".jsonl"):
# store schema in separate file -> column names and types
output_columns_path = ".".join(output_path_base.split(".")[0:-1]) + ".columns.json"
#assert os.path.exists(output_columns_path) == False, f"error: output file exists: {output_columns_path}"
print(f"writing {output_columns_path} ...")
output_columns = []
for name in column_names:
column = {
"name": name,
"type": str(type_name[column_types[name]]),
}
if name in column_sql:
column["sql"] = column_sql[name]
output_columns.append(column)
with open(output_columns_path, "w") as dst:
json.dump(output_columns, dst, indent=2)
#assert os.path.exists(output_path_base) == False, f"error: output file exists: {output_path_base}"
con = sqlite3.connect(db_path)
"""
# get column names
cur = con.cursor()
cur.row_factory = sqlite3.Row
sql_query = "SELECT * FROM subz_metadata LIMIT 1"
row = cur.execute(sql_query).fetchone()
column_names = list(row.keys())
"""
cur = con.cursor()
column_names_sql = []
for name in column_names:
if name in column_sql:
column_names_sql.append(f"{column_sql[name]} AS {name}")
else:
column_names_sql.append(name)
sql_query = f"SELECT {', '.join(column_names_sql)} FROM subz_metadata"
print(f"sql_query: {sql_query}")
# hole in dataset between 242445 and 3080254 = 2.5M missing nums
allow_empty_before = 3080254
# loop intervals
part_idx = -1
while True:
part_idx += 1
part_first = part_size * part_idx
part_last = part_first + part_size - 1
sql_query_part = sql_query + f" WHERE IDSubtitle BETWEEN {part_first} AND {part_last}"
# "ORDER BY" must come after "WHERE"
sql_query_part += " ORDER BY IDSubtitle ASC"
path_parts = output_path_base.split(".")
#output_path_part = ".".join(path_parts[0:-1]) + f".count.{part_size}.from.{part_first}.{path_parts[-1]}"
#output_path_part = ".".join(path_parts[0:-1]) + f".count.{part_size}.part.{part_idx}.{path_parts[-1]}"
output_path_part = ".".join(path_parts[0:-1]) + f".{part_name}.{part_idx}.{path_parts[-1]}"
if os.path.exists(output_path_part):
print(f"exists {output_path_part}")
else:
# json is typed: str, int, float, bool, NoneType
if output_path_part.endswith(".jsonl"):
with open(output_path_part, "w") as dst:
for row in cur.execute(sql_query_part):
line = json.dumps(
row,
indent=None,
separators=(',', ':'),
#separators=(', ', ': '),
)
dst.write(line + "\n")
if os.path.getsize(output_path_part) > 0:
print(f"done {output_path_part}")
else:
print(f"empty {output_path_part}")
os.unlink(output_path_part)
if allow_empty_before < part_first:
print("done all")
break
# no. csv is untyped, every value is a string
elif False and output_path_base.endswith(".csv"):
with open(output_path_base, "w") as dst:
writer = csv.writer(dst)
for row in cur.execute(sql_query):
num = row[0]
if num % 100000 == 0:
print(f"done {part_idx}")
writer.writerow(row)
else:
print(f"error: unknown file extension in output file: {output_path_base}")
if os.path.exists(output_path_part) == False:
# output file was empty
continue
# add to git
filename = os.path.basename(output_path_part)
print(f"git add {filename}")
worktree_path = f"{output_dir}/parts/{part_idx}"
if os.path.exists(worktree_path):
# remove old worktree
args = [
"git",
"-C", output_dir,
"worktree",
"remove",
#"--force",
f"parts/{part_idx}", # worktree path
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
args = [
"git",
"-C", output_dir,
"worktree",
"add",
"--quiet",
"--detach",
"--no-checkout",
f"parts/{part_idx}", # worktree path
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
args = [
"git",
"-C", worktree_path,
"checkout",
"--quiet",
"--orphan",
f"parts/{part_idx}", # branch name
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
args = [
"git",
"-C", worktree_path,
"reset",
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
args = [
"git",
"-C", worktree_path,
"clean",
"-fdq",
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
# copy file to worktree
shutil.copyfile(
f"{output_dir}/{filename}",
f"{output_dir}/parts/{part_idx}/{filename}",
)
args = [
"git",
"-C", worktree_path,
"add",
filename
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
if False:
# disable compression for zip files
gitattributes_path = f"{output_dir}/parts/{part_idx}/.gitattributes"
# https://stackoverflow.com/questions/7102053/git-pull-without-remotely-compressing-objects
with open(gitattributes_path, "w") as f:
f.write("*.zip -delta\n")
args = [
"git",
"-C", worktree_path,
"add",
os.path.basename(gitattributes_path),
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
args = [
"git",
"-C", worktree_path,
"commit",
"--quiet",
"-m", f"add {part_idx}",
#"-m", f"add part {part_idx}",
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
args = [
"git",
"-C", output_dir,
"worktree",
"remove",
f"parts/{part_idx}", # worktree path
]
debug_print(shlex.join(args))
proc = subprocess.run(
args,
check=True,
timeout=10,
)
os.unlink(f"{output_dir}/{filename}")