-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild.py
executable file
·313 lines (269 loc) · 10.4 KB
/
build.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
#!/usr/bin/env python
import argparse
import csv
import json
import os
import random
import sys
import textwrap
from PIL import Image, ImageDraw, ImageFont
import cv2
DEFAULT_QUOTE = {
"ru": [
{
"quote_first": "Счастливые часов не наблюдают.",
"quote_time_case": "",
"quote_last": "",
"title": "Горе от ума",
"author": "А. Грибоедов",
"sfw": "yes"
},
{
"quote_first": "Санчасть была в самом глухом, дальнем углу зоны, и звуки сюда не достигали никакие. Ни ходики не стучали — заключённым часов не положено, время за них знает начальство.",
"quote_time_case": "",
"quote_last": "",
"title": "Один день Ивана Денисовича",
"author": "А. Солженицын",
"sfw": "yes"
},
{
"quote_first": "Пожалуй, я не буду больше пить. Который час? Впрочем, не надо, я знаю который час. Пришел час! Теперь самое время.",
"quote_time_case": "",
"quote_last": "",
"title": "Идиот",
"author": "Федор Михайлович Достоевский",
"sfw": "yes"
},
{
"quote_first": "К тому моменту, пока добрались до дома, смотреть на часы было уже стыдно.",
"quote_time_case": "",
"quote_last": "",
"title": "Наследие 2",
"author": "Сергей Тармашев",
"sfw": "yes"
},
{
"quote_first": "— Время идет быстро, а между тем здесь такая скука! — сказала она, не глядя на него.",
"quote_time_case": "",
"quote_last": "",
"title": "Дама с собачкой",
"author": "Антон Чехов",
"sfw": "yes"
},
{
"quote_first": "Выяснилось, что у каждого из них на часах было разное время.",
"quote_time_case": "",
"quote_last": "",
"title": "Будет по-моему. Убеждай и побеждай",
"author": "Павел Астахов",
"sfw": "yes"
},
{
"quote_first": "– Да нет, дайте мне рассказать, – повторил он. – После всей этой увеселительности мы еще устроили легкий полночный завтрак, и когда мы отчалили, то уж было времени хренадцатый час того утра что после ночи.",
"quote_time_case": "",
"quote_last": "",
"title": "Улисс",
"author": "Джеймс Джойс",
"sfw": "yes"
}
],
"en": [
{
"quote_first": "Who knows, in happiness, how time is flying?",
"quote_time_case": "",
"quote_last": "",
"title": "Woe From Wit",
"author": "Alexander Griboyedov",
"sfw": "yes"
}
]
}
def complement_number(num):
if num < 10:
return f"0{num}"
return str(num)
def iter_daytime():
for hours in range(24):
for minutes in range(60):
yield (complement_number(hours),
complement_number(minutes))
def split_string(quote, quote_time_case):
quote_lc = quote.lower()
quote_time_case_lc = quote_time_case.lower()
start_pos = quote_lc.find(quote_time_case_lc)
if start_pos == -1:
print(f"substr '{quote_time_case}' is not found")
sys.exit(1)
end_pos = start_pos + len(quote_time_case)
quote_first = quote[0:start_pos]
quote_last = quote[end_pos:len(quote)]
return quote_first, quote_last
def build_record(row):
record = {}
record["time"] = row["time"]
record["quote_time_case"] = row["quote_time_case"]
record["quote_first"], record["quote_last"] = \
split_string(row["quote"], row["quote_time_case"])
record["title"] = row["title"]
record["author"] = row["author"]
record["sfw"] = "no"
if row["sfw"] != "nsfw":
record["sfw"] = "yes"
return record
def generate_image(txt_quote, txt_title, txt_author, image_name):
bg_color = 'black'
text_color = 'white'
width = 1024
height = 512
font_size = 30
font_path = "/usr/share/fonts/truetype/liberation2/LiberationMono-Regular.ttf"
font = ImageFont.truetype(
font_path, size=font_size, index=0, encoding='unic')
img = Image.new('RGB', (width, height), color=bg_color)
imgDraw = ImageDraw.Draw(img)
start_w = 50
start_h = 100
interligne = 40
for line in textwrap.wrap(txt_quote, width=50):
imgDraw.text((start_w, start_h), line, font=font, fill=text_color)
start_h = start_h + interligne
txt = f"— '{txt_title}', {txt_author}"
imgDraw.text((start_w, start_h + 10), txt, font=font, fill=text_color)
img.save(image_name)
def random_default_quote(lang):
quotes_list = DEFAULT_QUOTE.get(lang)
return random.choice(quotes_list)
def complement_placeholders(times, lang):
times_with_placeholders = times.copy()
for hours, minutes in iter_daytime():
time_str = f"{hours}:{minutes}"
quotes_list = times_with_placeholders.get(time_str)
if not quotes_list:
default_quote = random_default_quote(lang)
placeholder = default_quote.copy()
placeholder["time"] = time_str
quote_first = placeholder["quote_first"]
placeholder["quote_first"] = f"{time_str}: {quote_first}"
times_with_placeholders[time_str] = [placeholder]
return times_with_placeholders
def write_files(quotes_dict, path, image=False):
for time_str, quotes_list in quotes_dict.items():
json_obj = json.dumps(quotes_list, indent=4)
time_wo_colon = time_str.replace(":", "_", 1)
if not image:
file_name = os.path.join(path, f"{time_wo_colon}.json")
json_obj = json.dumps(quotes_list, indent=4)
with open(file_name, "w") as outfile:
outfile.write(json_obj)
else:
file_name = os.path.join(path, f"{time_wo_colon}.png")
quote = random.choice(quotes_list)
quote_str = quote["quote_first"] + \
quote["quote_time_case"] + \
quote["quote_last"]
generate_image(quote_str, quote["title"],
quote["author"], file_name)
"""
The dictionary format is the following:
[
"00:09": [
...
],
"00:10": [
{
"time": "00:10",
"quote_first": "",
"quote_time_case": "",
"quote_last": "",
"title": "",
"author": "",
"sfw": ""
},
{
"time": "00:10",
"quote_first": "",
"quote_time_case": "",
"quote_last": "",
"title": "",
"author": "",
"sfw": ""
}]
"00:11": [
...
],
]
"""
def build_dict(quote_filename, verbose=False):
times = {}
csv_fields = ["time", "quote_time_case", "quote", "title", "author", "sfw"]
with open(quote_filename) as csv_file:
csv_reader = csv.DictReader(csv_file, fieldnames=csv_fields,
delimiter="|", quoting=csv.QUOTE_NONE)
for row in list(csv_reader):
# Build a dictionary.
time = row["time"]
if times.get(time) is None:
times[time] = []
record = build_record(row)
if verbose:
print(record)
times[time].append(record)
return times
def parse_args():
parser = argparse.ArgumentParser(prog="build_data")
parser.add_argument("--filename",
type=str)
parser.add_argument("-l", "--language",
choices=["ru", "en"],
required=True,
type=str)
parser.add_argument("-p", "--path",
type=str)
parser.add_argument("-d", "--dry-run",
action="store_true")
parser.add_argument("-v", "--verbose",
action="store_true")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--create-video', action="store_true")
group.add_argument('--create-json', action="store_true")
args = parser.parse_args()
return args
def build_video(image_dir, video_name):
fps = 1 / 60 # 1 minute
images = [img for img in sorted(
os.listdir(image_dir)) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_dir, images[0]))
height, width, layers = frame.shape
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
result_file = os.path.join(image_dir, video_name)
video = cv2.VideoWriter(filename=result_file, fourcc=fourcc,
fps=fps, frameSize=(width, height))
for image in images:
video.write(cv2.imread(os.path.join(image_dir, image)))
cv2.destroyAllWindows()
video.release()
print(f"File {result_file}")
def main():
inputs = parse_args()
filename = inputs.filename
if not filename and inputs.language:
filename = f"quotes/quotes_{inputs.language}.csv"
if not os.path.isfile(filename):
print(f"File {filename} is not found")
sys.exit(1)
if not inputs.dry_run and not os.path.isdir(inputs.path):
os.makedirs(inputs.path)
times = build_dict(filename, inputs.verbose)
times_with_placeholders = complement_placeholders(times, inputs.language)
# Write JSON files.
if not inputs.dry_run and inputs.create_json:
write_files(times_with_placeholders, inputs.path)
# Write a video file.
if not inputs.dry_run and inputs.create_video:
write_files(times_with_placeholders, inputs.path, image=True)
build_video(inputs.path, "litclock.avi")
perc_covered = round(len(times)/(60 * 24) * 100)
print(f"File with quotes: {filename}")
print(f"Number of quotes with unique time: {len(times)} ({perc_covered}%)")
if __name__ == '__main__':
main()