-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
219 lines (195 loc) · 6.42 KB
/
main.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
from pathlib import Path
from shutil import copyfile
from threading import Thread, Semaphore
import argparse
import logging
import logging.config
from typing import Any, Tuple
from uuid import uuid4
from datetime import datetime
from time import sleep
from multiprocessing import cpu_count
from factorize_sync import (
factorize_mul,
factorize_sync,
)
from factorize_async_pipe import factorize_mul_pipe
from factorize_async_queue import factorize_mul_queue
from factorize_async_joinqueue import factorize_mul_jqueue
from factorize_async_pool import factorize_mul_pool
from factorize_sync_thread import factorize_mul_thread
from factorize_async_concurrent import factorize_mul_concurrent
# logging.config.fileConfig('logging.conf')
logging.basicConfig(
level=logging.INFO, format="%(asctime)s PID: %(process)d [ %(threadName)s ] %(message)s"
)
logger = logging.getLogger(__name__)
def get_params():
args_cli = argparse.ArgumentParser(description="File sorter")
args_cli.add_argument(
"-s", "--source", required=False, default="pictures", help="default: pictures"
)
args_cli.add_argument("-o", "--output", default="sort_result")
args_cli.add_argument(
"-t", "--threads", default=10, type=int, help="Max threads, default: 10"
)
args_cli.add_argument("-v", "--verbose", action="store_true")
args_cli.add_argument("-f", "--factorize", action="store_true")
return vars(args_cli.parse_args())
def sort_folder(
folder: Path, output: Path, condition: Semaphore, verbose: bool = False
) -> None:
with condition:
if verbose:
logging.info(f"`Thread running for sort in {folder}")
# pre sorting files to dict
result = {}
for el in folder.iterdir():
if el.is_file():
ext = el.suffix.lower()
if not ext:
continue
ext_items = result.get(ext, [])
ext_items.append(el)
result[ext] = ext_items
# physical copy founded files
for ext, ext_items in result.items():
destination_path = output.joinpath(ext[1:])
destination_path.mkdir(exist_ok=True, parents=True)
for el in ext_items:
destination_file = destination_path.joinpath(el.name)
if destination_file.exists():
destination_file = destination_path.joinpath(
f"{el.stem}_{uuid4()}{el.suffix}"
)
try:
if verbose:
logging.info(f"`Thread copy {el} to {destination_file}")
copyfile(el, destination_file)
except OSError as e:
logging.error(e)
def get_folders(source_path: Path) -> list[Path]:
folders = []
for el in source_path.glob("*/**"):
if el.is_dir():
folders.append(el)
return folders
def main(args_cli: dict = None):
source = args_cli.get("source")
output = args_cli.get("output", "sort_result")
threads_maximum: int = args_cli.get("threads", 10)
verbose = args_cli.get("verbose", False)
assert source is not None, "Source must be defined"
if verbose:
logging.info("Start search")
folders = get_folders(Path(source))
output_path = Path(output)
threads = []
pool = Semaphore(threads_maximum)
for num, folder in enumerate(folders):
th = Thread(
name=f"Th-{num}",
target=sort_folder,
args=(folder, output_path, pool, verbose),
)
th.start()
threads.append(th)
if verbose:
logging.info(f"Wait all {len(threads)} threads")
[th.join() for th in threads]
if verbose:
logging.info("Finish")
# print(folders)
def test_factorize(method: int = 0):
source = (128, 255, 99999, 10651060)
if method == 0:
a, b, c, d = factorize_sync(*source)
elif method == 1:
a, b, c, d = factorize_mul(*source)
elif method == 2:
a, b, c, d = factorize_mul_pool(*source)
elif method == 3:
threads_maximum = 10
logging.info(f"Threads max: {threads_maximum}")
a, b, c, d = factorize_mul_thread(*source, threads_maximum=threads_maximum)
elif method == 4:
a, b, c, d = factorize_mul_pipe(*source)
elif method == 5:
a, b, c, d = factorize_mul_queue(*source)
elif method == 6:
a, b, c, d = factorize_mul_jqueue(*source)
elif method == 7:
a, b, c, d = factorize_mul_concurrent(*source)
assert a == [1, 2, 4, 8, 16, 32, 64, 128]
assert b == [1, 3, 5, 15, 17, 51, 85, 255]
assert c == [1, 3, 9, 41, 123, 271, 369, 813, 2439, 11111, 33333, 99999]
assert c == [1, 3, 9, 41, 123, 271, 369, 813, 2439, 11111, 33333, 99999]
assert d == [
1,
2,
4,
5,
7,
10,
14,
20,
28,
35,
70,
140,
76079,
152158,
304316,
380395,
532553,
760790,
1065106,
1521580,
2130212,
2662765,
5325530,
10651060,
]
def test_fact():
METHOD_DESC: tuple = (
"SYNC ONE FUNC",
"SYNC SPLIT FUNC",
"ASYNC MP POOL",
"ASYNC THREAD",
"ASYNC MP PROC PIPE",
"ASYNC MP PROC QUEUE",
"ASYNC MP PROC JOIN QUEUE",
"ASYNC MP FUTURE CONCURENT",
)
durations = []
cpu_total_m = cpu_count()
logging.info(
f"On this system is total cpu: {cpu_total_m}"
)
for method in range(0, len(METHOD_DESC)):
start_time_m = datetime.now()
test_factorize(method)
duration_m = datetime.now() - start_time_m
durations.append(duration_m)
logging.info(
f"Method [{METHOD_DESC[method]}]. Duration: {duration_m}"
)
sleep(1)
if __name__ == "__main__":
# logging.basicConfig(
# level=logging.DEBUG, format="%(asctime)s [ %(threadName)s ] %(message)s"
# )
logger = logging.getLogger(__name__)
args = get_params()
threads_max = args.get("threads", 10)
factorize = args.get("factorize", False)
if factorize:
test_fact()
else:
cpu_total = cpu_count()
start_time = datetime.now()
main(args_cli=args)
duration = datetime.now() - start_time
logger.info(
f"Duration : {duration} with max threads: {threads_max}, on this system is total cpu: {cpu_total}"
)