Repository navigation
Expand file tree
/
Copy pathgenerate_data.py
More file actions
445 lines (347 loc) · 16.3 KB
/
Copy pathgenerate_data.py
File metadata and controls
445 lines (347 loc) · 16.3 KB
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# -*- coding: utf-8 -*-
import json
import os
import sys
from bisect import bisect_left
from dataclasses import dataclass
from datetime import datetime, timedelta
from hashlib import sha512
from io import BytesIO
from pathlib import PurePath
from string import Template
import geopy.distance
import numpy as np
import pandas as pd
from pyadps.helpers import calculate_hashsum
from pyadps.mail import CoordsData, FileAttachment, Mail
# [PyADPS]$ time python -m pyadps.scripts.generate_data /path/to/adps_repo
SEED = 12345
@dataclass
class City:
name: str
country_code: str
coords: CoordsData
# https://stackoverflow.com/questions/18622781/why-is-numpy-random-choice-so-slow
class FastRandomGenerator:
def __init__(self, np_rng):
self._rng = np_rng
def integers(self, *args, **kwargs):
return self._rng.integers(*args, **kwargs)
def bytes(self, *args, **kwargs):
return self._rng.bytes(*args, **kwargs)
def random(self, *args, **kwargs):
return self._rng.random(*args, **kwargs)
def choice(self, collection: list, *args):
if len(collection) < 100:
return self._rng.choice(collection, *args)
count = 1
if args:
count = args[0]
indexes = set()
for _ in range(count):
attempts = 100
found_number = False
for attempt in range(attempts):
idx = self.integers(0, len(collection))
if idx not in indexes:
indexes.add(idx)
found_number = True
break
if not found_number:
raise Exception('Could not build unique set')
if count == 1:
return collection[indexes.pop()]
else:
return [collection[idx_] for idx_ in indexes]
def get_cumulative_list(dataframe):
population_list = dataframe['population'].tolist()
cumulative_list = []
s = 0
for population_entry in population_list:
population_value = population_entry if not pd.isna(population_entry) else 0
cumulative_list.append(population_value + s)
s += population_value
return cumulative_list
def choose_city_by_random_value(
value: float,
target_dataframe,
population,
cumulative_population_list
) -> City:
"""value is float from 0 to 1"""
people_num = value * population
city_idx = bisect_left(cumulative_population_list, people_num)
city_row = target_dataframe[city_idx:city_idx + 1]
return City(
name=city_row['city_ascii'].tolist()[0],
country_code=city_row['iso2'].tolist()[0],
coords=CoordsData(city_row['lat'].tolist()[0], city_row['lng'].tolist()[0]))
def get_file_sizes_bytes(number_of_files: int, sum_bytes: int, rng: FastRandomGenerator) -> list:
sizes_rnd = [rng.random() for _ in range(number_of_files)]
sizes_cum_sum = np.cumsum(sizes_rnd)
rate_coef = sum_bytes / sizes_cum_sum[-1]
boundaries_byte_numbers = [round(rate_coef * el) for el in sizes_cum_sum]
return boundaries_byte_numbers
def choose_attachments_for_mail(big_attachments: list, short_attachments: list, rng: FastRandomGenerator) -> list:
random_value = rng.random()
if 0 <= random_value < 0.05:
return []
elif 0.05 <= random_value < 0.10:
return [rng.choice(big_attachments)]
elif 0.10 <= random_value < 0.12:
return list(rng.choice(big_attachments, 2))
elif 0.12 <= random_value < 0.14:
return [*list(rng.choice(big_attachments, 2)), rng.choice(short_attachments)]
elif 0.14 <= random_value < 0.15:
return [*list(rng.choice(big_attachments, 2)), *list(rng.choice(short_attachments, 2))]
elif 0.15 <= random_value < 0.20:
return [rng.choice(big_attachments), rng.choice(short_attachments)]
elif 0.20 <= random_value < 0.90:
return [rng.choice(short_attachments)]
elif 0.90 <= random_value < 0.95:
return list(rng.choice(short_attachments, 2))
elif 0.95 <= random_value < 0.97:
return list(rng.choice(short_attachments, 3))
elif 0.97 <= random_value < 0.99:
return list(rng.choice(short_attachments, 4))
else:
return list(rng.choice(short_attachments, 5))
def generate_name(names_dataframe: list, rng: FastRandomGenerator) -> str:
random_value = rng.random()
if 0 <= random_value < 0.6:
return f'{rng.choice(names_dataframe).lower()}@{rng.choice(names_dataframe).lower()}.com'
elif 0.6 <= random_value < 0.95:
return '+' + ''.join([str(rng.integers(0, 10)) for _ in range(10)])
else:
return rng.choice(names_dataframe) + ' ' + rng.choice(names_dataframe)
def generate_additional_notes(names_dataframe: list, rng: FastRandomGenerator):
random_value = rng.random()
if 0 <= random_value < 0.8:
return rng.choice(names_dataframe) + ' ' + rng.choice(names_dataframe)
else:
return None
def generate_inline_message(names_dataframe: list, rng: FastRandomGenerator):
random_value = rng.random()
if 0 <= random_value < 0.8:
return ' '.join(rng.choice(names_dataframe).lower() for _ in range(rng.integers(1, 40)))
else:
return None
def add_error_to_coords(lat: float, lon: float, rng: FastRandomGenerator,
min_error_meters=100, max_error_meters=20_000) -> tuple:
bearing = rng.random() * 360
distance = rng.random() * (max_error_meters - min_error_meters) + min_error_meters
geodesic = geopy.distance.geodesic()
lat_, lon_, _ = geodesic.destination((lat, lon), bearing, distance / 1000)
return lat_, lon_
def get_list_of_coords(
cities,
top_100_cities_dataframe,
top_100_cities_population,
top_100_cities_population_cumulative_list,
rng: FastRandomGenerator
):
result = []
for city in cities:
random_value = rng.random()
if 0 <= random_value < 0.9:
additional_cities = 0
elif 0.9 <= random_value < 0.95:
additional_cities = 1
elif 0.95 <= random_value < 0.98:
additional_cities = 2
else:
additional_cities = 3
filtered_cities = [city]
for _ in range(additional_cities):
filtered_cities.append(choose_city_by_random_value(
rng.random(),
top_100_cities_dataframe,
top_100_cities_population,
top_100_cities_population_cumulative_list,
))
coords_list = []
for filtered_city in filtered_cities:
noised_coords = add_error_to_coords(filtered_city.coords.lat, filtered_city.coords.lon, rng)
coords_list.append(noised_coords)
result.append(coords_list)
return result
def create_attachment(adps_attachments_path: PurePath, size_bytes: int, rng: FastRandomGenerator) -> FileAttachment:
tmp_file_path = adps_attachments_path / 'tmp.bin'
with open(tmp_file_path, 'wb') as file_:
file_.write(rng.bytes(size_bytes))
with open(tmp_file_path, 'rb') as file_:
hashsum_result = calculate_hashsum(file_)
target_filename = hashsum_result.hex_digest[:10] + '.bin'
target_file_path = adps_attachments_path / target_filename
os.rename(tmp_file_path, target_file_path)
return FileAttachment(target_filename, hashsum_result.size_bytes, hashsum_result.hex_digest)
def generate_random_datetime(start, end, rng: FastRandomGenerator):
"""Generate a random datetime between `start` and `end`"""
return start + timedelta(
# Get a random amount of seconds between `start` and `end`
seconds=int(rng.integers(0, int((end - start).total_seconds()))),
)
# https://stackoverflow.com/a/60703924
def find_partial_collision_by_templates(
template1: str,
template2: str,
collision_length: int = 10,
ntries: int = 10_000_000
):
tpl1 = Template(template1)
tpl2 = Template(template2)
def get_text_1(n_): return tpl1.substitute(templateVal=n_)
def get_text_2(n_): return tpl2.substitute(templateVal=n_)
seen = {}
for n in range(ntries):
h = sha512(get_text_1(n).encode('ascii')).hexdigest()[:collision_length]
seen[h] = n
for n in range(ntries):
h = sha512(get_text_2(n).encode('ascii')).hexdigest()[:collision_length]
if h in seen:
str_1 = get_text_1(seen[h])
str_2 = get_text_2(n)
return str_1, str_2
def find_collisions():
template1 = 'Frank is one of the best students topicId$templateVal '
template2 = 'Frank is one of the top students topicId$templateVal '
str1, str2 = find_partial_collision_by_templates(template1, template2)
mail_1 = Mail(
date_created=datetime(2022, 2, 2),
recipient_coords=[CoordsData(1.0, 2.0)],
name='Johnny',
additional_notes=None,
inline_message=template1,
attachments=[FileAttachment('123.txt', len(str1), sha512(str1.encode()).hexdigest())]
)
mail_1_serialized = Mail.Schema().dump(mail_1)
mail_1_json_template_str = json.dumps(mail_1_serialized, indent=4, sort_keys=True)
mail_2 = Mail(
date_created=datetime(2022, 2, 2),
recipient_coords=[CoordsData(1.0, 2.0)],
name='Johnny',
additional_notes=None,
inline_message=template2,
attachments=[FileAttachment('333.txt', len(str2), sha512(str2.encode()).hexdigest())]
)
mail_2_serialized = Mail.Schema().dump(mail_2)
mail_2_json_template_str = json.dumps(mail_2_serialized, indent=4, sort_keys=True)
mail_1_json_str, mail_2_json_str = find_partial_collision_by_templates(
mail_1_json_template_str, mail_2_json_template_str)
return [s.encode() for s in (str1, str2, mail_1_json_str, mail_2_json_str)]
def main():
worldcities_path = PurePath(__file__).parents[1] / 'static_files/worldcities/worldcities.csv'
first_names_path = PurePath(__file__).parents[1] / 'static_files/name_databases/all.txt'
output_dir = sys.argv[1]
target_country_code_iso2 = 'RU'
target_country_part = 0.8
rest_part = 1 - target_country_part
mail_number = 50000
attachment_number = 100000
target_country_mail_number = round(target_country_part * mail_number)
other_countries_mail_number = round(rest_part * mail_number)
datetime_from = datetime(2022, 1, 1)
datetime_to = datetime(2023, 1, 1)
dataframe = pd.read_csv(worldcities_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
adps_messages_path = PurePath(output_dir) / 'adps_messages'
adps_attachments_path = PurePath(output_dir) / 'adps_attachments'
os.mkdir(adps_messages_path)
os.mkdir(adps_attachments_path)
rng = FastRandomGenerator(np.random.default_rng(SEED))
target_country_dataframe = dataframe.loc[dataframe['iso2'] == target_country_code_iso2]
target_country_population = target_country_dataframe['population'].sum()
target_country_cumulative_population_list = get_cumulative_list(target_country_dataframe)
other_countries_dataframe = dataframe.loc[dataframe['iso2'] != target_country_code_iso2]
other_countries_population = other_countries_dataframe['population'].sum()
other_countries_cumulative_population_list = get_cumulative_list(other_countries_dataframe)
print('Filtering target country cities...')
target_country_cities = [
choose_city_by_random_value(rng.random(), target_country_dataframe, target_country_population,
target_country_cumulative_population_list)
for _ in range(target_country_mail_number)
]
print('Filtering other countries cities...')
other_countries_cities = [
choose_city_by_random_value(rng.random(), other_countries_dataframe, other_countries_population,
other_countries_cumulative_population_list)
for _ in range(other_countries_mail_number)
]
print('Filtering top 100 cities...')
top_100_cities_dataframe = dataframe.sort_values(by=['population'], ascending=False).head(100)
top_100_cities_population = top_100_cities_dataframe['population'].sum()
top_100_cities_cumulative_population_list = get_cumulative_list(top_100_cities_dataframe)
big_files_sizes = [1024 ** 3, *([512 * 1024 ** 2] * 2), *([256 * 1024 ** 2] * 4), *([128 * 1024 ** 2] * 8)]
short_files_sizes = list(np.diff([0, *get_file_sizes_bytes(attachment_number - len(big_files_sizes),
1 * 1024 * 1024 * 1024,
rng=rng)]))
print('Reading names database...')
names_df = pd.read_csv(first_names_path, header=None)
all_names = list(names_df[0])
print('Creating big attachments...')
big_attachments = [create_attachment(adps_attachments_path, file_size_bytes, rng)
for file_size_bytes in big_files_sizes]
print('Creating small attachments...')
small_attachments = [create_attachment(adps_attachments_path, file_size_bytes, rng)
for file_size_bytes in short_files_sizes]
print('Generating names...')
list_of_names = [generate_name(all_names, rng) for _ in range(mail_number)]
print('Generating additional notes...')
list_of_additional_notes = [generate_additional_notes(all_names, rng) for _ in range(mail_number)]
print('Generating inline messages...')
list_of_inline_messages = [generate_inline_message(all_names, rng) for _ in range(mail_number)]
print('Generating dates...')
list_of_date_created = [generate_random_datetime(datetime_from, datetime_to, rng) for _ in range(mail_number)]
print('Generating attachments sets...')
list_of_attachments = [choose_attachments_for_mail(big_attachments, small_attachments, rng)
for _ in range(mail_number)]
print('Generating coordinates...')
list_of_coords = get_list_of_coords([*target_country_cities, *other_countries_cities],
top_100_cities_dataframe,
top_100_cities_population,
top_100_cities_cumulative_population_list,
rng)
five_percent_indexes = {i * mail_number // 20 for i in range(1, 20)}
progress = 0.00
for idx, (created_date, coords_list, name, additional_notes, inline_message, attachment_infos) in enumerate(zip(
list_of_date_created,
list_of_coords,
list_of_names,
list_of_additional_notes,
list_of_inline_messages,
list_of_attachments
)):
if idx in five_percent_indexes:
progress += 0.05
print(f'Generating mail json files...{int(progress * 100)}%...')
mail = Mail(
date_created=created_date,
recipient_coords=[CoordsData(*one_coords) for one_coords in coords_list],
name=name,
additional_notes=additional_notes,
inline_message=inline_message,
attachments=attachment_infos
)
mail_serialized = Mail.Schema().dump(mail)
mail_json_bytes = json.dumps(mail_serialized, indent=4, sort_keys=True).encode()
hashsum = calculate_hashsum(BytesIO(mail_json_bytes))
mail_path = adps_messages_path / (hashsum.hex_digest[:10] + '.json')
with open(mail_path, 'wb') as output_json_file:
output_json_file.write(mail_json_bytes)
print('Generating partial collisions...')
attachment_1_content, attachment_2_content, msg_json_1, msg_json_2 = find_collisions()
attachment_1_hashsum = sha512(attachment_1_content).hexdigest()
attachment_2_hashsum = sha512(attachment_2_content).hexdigest()
msg_json_1_hashsum = sha512(msg_json_1).hexdigest()
msg_json_2_hashsum = sha512(msg_json_2).hexdigest()
with open(adps_messages_path / (msg_json_1_hashsum[:10] + '.json'), 'wb') as output_json_file:
output_json_file.write(msg_json_1)
with open(adps_messages_path / (msg_json_2_hashsum[:10] + '_0' + '.json'), 'wb') as output_json_file:
output_json_file.write(msg_json_2)
with open(adps_attachments_path / (attachment_1_hashsum[:10] + '.bin'), 'wb') as output_attachment_file:
output_attachment_file.write(attachment_1_content)
with open(adps_attachments_path / (attachment_2_hashsum[:10] + '_0' + '.bin'), 'wb') as output_attachment_file:
output_attachment_file.write(attachment_2_content)
if __name__ == '__main__':
main()