This repository was archived by the owner on Mar 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlib.py
More file actions
1885 lines (1704 loc) · 81.2 KB
/
lib.py
File metadata and controls
1885 lines (1704 loc) · 81.2 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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Automatically organizes folders with potentially huge amounts of unorganized
ebooks.
This is done by renaming the files with proper names and moving them to other
folders.
This is a Python port of `organize-ebooks.sh` from `ebook-tools` written in
shell by `na--`.
Ref.: https://github.com/na--/ebook-tools
"""
import ast
import logging
import mimetypes
import os
import re
import shlex
import shutil
import string
import subprocess
import tempfile
import time
from argparse import Namespace
from copy import copy
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
from unicodedata import normalize
from organize_ebooks import __version__
logger = logging.getLogger('organize_lib')
logger.setLevel(logging.CRITICAL + 1)
def get_re_year():
# In bash: (19[0-9]|20[0-$(date '+%Y' | cut -b 3)])[0-9]"
# output: (19[0-9]|20[0-1])[0-9]
regex = '(19[0-9]|20[0-{}])[0-9]'.format(str(datetime.now())[2])
return regex
# TODO: test it
def get_without_isbn_ignore():
re_year = get_re_year()
regex = ''
# Periodicals with filenames that contain something like 2010-11, 199010, 2015_7, 20110203:
regex += '(^|[^0-9]){}[ _\.-]*(0?[1-9]|10|11|12)([0-9][0-9])?($|[^0-9])'.format(re_year)
# Periodicals with month numbers before the year
regex += '|(^|[^0-9])([0-9][0-9])?(0?[1-9]|10|11|12)[ _\.-]*{}($|[^0-9])'.format(re_year)
# Periodicals with months or issues
regex += '|((^|[^a-z])(jan(uary)?|feb(ruary)?|mar(ch)?|apr(il)?|may|june?|july?|aug(ust)?|sep(tember)?|' \
'oct(ober)?|nov(ember)?|dec(ember)?|mag(azine)?|issue|#[ _\.-]*[0-9]+)+($|[^a-z]))'
# Periodicals with seasons and years
regex += '|((spr(ing)?|sum(mer)?|aut(umn)?|win(ter)?|fall)[ _\.-]*{})'.format(re_year)
regex += '|({}[ _\.-]*(spr(ing)?|sum(mer)?|aut(umn)?|win(ter)?|fall))'.format(re_year)
# Remove newlines
# TODO: is it necessary?
regex = regex.replace('\n', '')
return regex
# =====================
# Default config values
# =====================
# Misc options
# ============
DRY_RUN = False
SYMLINK_ONLY = False
KEEP_METADATA = False
REVERSE = False
# Convert-to-txt options
# ======================
DJVU_CONVERT_METHOD = 'djvutxt'
EPUB_CONVERT_METHOD = 'epubtxt'
MSWORD_CONVERT_METHOD = 'textutil'
PDF_CONVERT_METHOD = 'pdftotext'
# Options related to extracting ISBNs from files and finding metadata by ISBN
# ===========================================================================
MAX_ISBNS = 5
# Horizontal whitespace and dash-like ASCII and Unicode characters that are
# used for better matching of ISBNs in (badly) OCR-ed books. Gathered from:
# - https://en.wikipedia.org/wiki/Whitespace_character
# - https://en.wikipedia.org/wiki/Dash#Similar_Unicode_characters
# - https://en.wikipedia.org/wiki/Dash#Common_dashes
# From: https://github.com/na--/ebook-tools/blob/master/lib.sh#L31
# NOTE: I need to escape the most important dash '-' because Python re doesn't recognize it if I don't
WSD = "[\u0009|\u0020|\u00A0|\u1680|\u2000|\u2001|\u2002|\u2003|\u2004|\u2005|\u2006|\u2007|\u2008" \
"|\u2009|\u200A|\u202F|\u205F|\u3000|\u180E|\u200B|\u200C|\u200D|\u2060|\uFEFF|\-|\u005F|\u007E|\u00AD|\u00AF" \
"|\u02C9|\u02CD|\u02D7|\u02DC|\u2010|\u2011|\u2012|\u203E|\u2043|\u207B|\u208B|\u2212|\u223C|\u23AF|\u23E4" \
"|\u2500|\u2796|\u2E3A|\u2E3B|\u10191|\u2012|\u2013|\u2014|\u2015|\u2053" \
"|\u058A|\u05BE|\u1428|\u1B78|\u3161|\u30FC|\uFE63|\uFF0D|\u10110|\u1104B|\u11052|\u110BE|\u1D360]?"
# ISBN_REGEX = '(?<![0-9])(-?9-?7[789]-?)?((-?[0-9]-?){9}[0-9xX])(?![0-9])'
# NOTE: if I use '?+' like they do in their code, I get `error: multiple repeat at position 592`
# Also, double accolades for 9 or they get removed by f-string
ISBN_REGEX = f"(?<![0-9])({WSD}9{WSD}7{WSD}[789]{WSD})?(({WSD}[0-9]{WSD}){{9}}[0-9xX])(?![0-9])"
ISBN_BLACKLIST_REGEX = '^(0123456789|([0-9xX])\\2{9})$'
ISBN_DIRECT_FILES = '^text/(plain|xml|html)$'
ISBN_IGNORED_FILES = '^(image/(gif|svg.+)|application/(x-shockwave-flash|CDFV2|vnd.ms-opentype|x-font-ttf|x-dosexec|' \
'vnd.ms-excel|x-java-applet)|audio/.+|video/.+)$'
# False to disable the functionality or (first_lines,last_lines) to enable it
ISBN_REORDER_FILES = [400, 50]
ISBN_RET_SEPARATOR = ' - '
# NOTE: If you use Calibre versions that are older than 2.84, it's required to
# manually set the following option to an empty string
ISBN_METADATA_FETCH_ORDER = ['Goodreads', 'Google', 'Amazon.com', 'ISBNDB', 'WorldCat xISBN', 'OZON.ru']
# Logging options
# ===============
LOGGING_FORMATTER = 'only_msg'
LOGGING_LEVEL = 'info'
# OCR options
# ===========
OCR_ENABLED = 'false'
OCR_COMMAND = 'tesseract_wrapper'
OCR_ONLY_FIRST_LAST_PAGES = (7, 3)
# Organize options
# ================
SKIP_ARCHIVES = False
CORRUPTION_CHECK = 'true'
ORGANIZE_WITHOUT_ISBN = False
ORGANIZE_WITHOUT_ISBN_SOURCES = ['Goodreads', 'Google', 'Amazon.com']
PAMPHLET_EXCLUDED_FILES = '\.(chm|epub|cbr|cbz|mobi|lit|pdb)$'
PAMPHLET_INCLUDED_FILES = '\.(png|jpg|jpeg|gif|bmp|svg|csv|pptx?)$'
PAMPHLET_MAX_FILESIZE_KIB = 250
PAMPHLET_MAX_PDF_PAGES = 50
TESTED_ARCHIVE_EXTENSIONS = '^(7z|bz2|chm|arj|cab|gz|tgz|gzip|zip|rar|xz|tar|epub|docx|odt|ods|cbr|cbz|maff|iso)$'
WITHOUT_ISBN_IGNORE = get_without_isbn_ignore()
OUTPUT_FILENAME_TEMPLATE = "${d[AUTHORS]// & /, } - ${d[SERIES]:+[${d[SERIES]}] " \
"- }${d[TITLE]/:/ -}${d[PUBLISHED]:+ (${d[PUBLISHED]%%-*})}" \
"${d[ISBN]:+ [${d[ISBN]}]}.${d[EXT]}"
OUTPUT_FOLDER_CORRUPT = None
OUTPUT_FOLDER_PAMPHLETS = None
OUTPUT_FOLDER_UNCERTAIN = None
# If `keep_metadata` is enabled, this is the extension of the additional
# metadata file that is saved next to each newly renamed file
OUTPUT_METADATA_EXTENSION = 'meta'
class Result:
def __init__(self, stdout='', stderr='', returncode=None, args=None):
self.stdout = stdout
self.stderr = stderr
self.returncode = returncode
self.args = args
def __repr__(self):
return self.__str__()
def __str__(self):
return f'stdout={str(self.stdout).strip()}, ' \
f'stderr={str(self.stderr).strip()}, ' \
f'returncode={self.returncode}, args={self.args}'
# ------
# Colors
# ------
COLORS = {
'GREEN': '\033[0;36m', # 32
'RED': '\033[0;31m',
'YELLOW': '\033[0;33m', # 32
'BLUE': '\033[0;34m', #
'VIOLET': '\033[0;35m', #
'BOLD': '\033[1m',
'NC': '\033[0m',
}
_COLOR_TO_CODE = {
'g': COLORS['GREEN'],
'r': COLORS['RED'],
'y': COLORS['YELLOW'],
'b': COLORS['BLUE'],
'v': COLORS['VIOLET'],
'bold': COLORS['BOLD']
}
def color(msg, msg_color='y', bold_msg=False):
msg_color = msg_color.lower()
colors = list(_COLOR_TO_CODE.keys())
assert msg_color in colors, f'Wrong color: {msg_color}. Only these ' \
f'colors are supported: {msg_color}'
msg = bold(msg) if bold_msg else msg
msg = msg.replace(COLORS['NC'], COLORS['NC']+_COLOR_TO_CODE[msg_color])
return f"{_COLOR_TO_CODE[msg_color]}{msg}{COLORS['NC']}"
def blue(msg):
return color(msg, 'b')
def bold(msg):
return color(msg, 'bold')
def green(msg):
return color(msg, 'g')
def red(msg):
return color(msg, 'r')
def violet(msg):
return color(msg, 'v')
def yellow(msg):
return color(msg)
def catdoc(input_file, output_file):
cmd = f'catdoc "{input_file}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Everything on the stdout must be copied to the output file
if result.returncode == 0:
with open(output_file, 'w') as f:
f.write(result.stdout)
return convert_result_from_shell_cmd(result)
# Checks the supplied file for different kinds of corruption:
# - If it's zero-sized or contains only \0
# - If it has a pdf extension but different mime type
# - If it's a pdf and `pdfinfo` returns an error
# - If it has an archive extension but `7z t` returns an error
# ref.: https://bit.ly/2JLpqgf
def check_file_for_corruption(
file_path, tested_archive_extensions=TESTED_ARCHIVE_EXTENSIONS):
file_err = ''
logger.debug(f"Testing '{Path(file_path).name}' for corruption...")
logger.debug(f"Full path: {file_path}")
# TODO: test that it is the same as
# if [[ "$(tr -d '\0' < "$file_path" | head -c 1)" == "" ]]; then
# Ref.: https://bit.ly/2jpX0xf
if is_file_empty(file_path):
file_err = 'The file is empty or contains only zeros!'
logger.debug(file_err)
return file_err
ext = Path(file_path).suffix[1:] # Remove the dot from extension
mime_type = get_mime_type(file_path)
if mime_type == 'application/octet-stream' and \
re.match('^(pdf|djv|djvu)$', mime_type):
file_err = f"The file has a {ext} extension but '{mime_type}' MIME type!"
logger.debug(file_err)
return file_err
elif mime_type == 'application/pdf':
logger.debug('Checking pdf file for integrity...')
if not command_exists('pdfinfo'):
file_err = 'pdfinfo does not exist, could not check if pdf is OK'
logger.debug(file_err)
return file_err
else:
pdfinfo_output = pdfinfo(file_path)
if pdfinfo_output.stderr:
logger.debug('pdfinfo returned an error!')
logger.debug(f'Error:\n{pdfinfo_output.stderr}')
file_err = 'Has pdf MIME type or extension, but pdfinfo ' \
'returned an error!'
logger.debug(file_err)
return file_err
else:
logger.debug('pdfinfo returned successfully')
logger.debug(f'Output of pdfinfo:\n{pdfinfo_output.stdout}')
if re.search('^Page size:\s*0 x 0 pts$', pdfinfo_output.stdout):
logger.debug('pdf is corrupt anyway, page size property is '
'empty!')
file_err = 'pdf can be parsed, but page size is 0 x 0 pts!'
logger.debug(file_err)
return file_err
if re.match(tested_archive_extensions, ext):
logger.debug(f"The file has a '{ext}' extension, testing with 7z...")
log = test_archive(file_path)
if log.stderr:
logger.debug('Test failed!')
logger.debug(log.stderr)
file_err = 'Looks like an archive, but testing it with 7z failed!'
return file_err
else:
logger.debug('Test succeeded!')
logger.debug(log.stdout)
if file_err == '':
logger.debug('Corruption not detected!')
else:
logger.debug(f'We are at the end of the function and '
f'file_err="{file_err}"; it should be empty!')
return file_err
# Ref.: https://stackoverflow.com/a/28909933
def command_exists(cmd):
return shutil.which(cmd) is not None
def convert_bytes_binary(num, unit):
"""
this function will convert bytes to MiB.... GiB... etc
Ref.: https://stackoverflow.com/a/39988702
"""
unit = unit.lower()
units = ['bytes', 'kib', 'mib', 'gib', 'tib']
if unit not in units:
"""
logger.error(f"'{unit}' is not a valid unit\n"
f'Aborting {convert_bytes_binary.__name__}()')
"""
return None
for x in units:
if num < 1024.0 or x == unit:
# return "%3.1f %s" % (num, x)
x = x.capitalize()
if x != 'Bytes':
x = x[:-1] + x[-1].upper()
return num, "%3.1f %s" % (num, x)
num /= 1024.0
def convert_bytes_decimal(num, unit):
"""
this function will convert bytes to MB.... GB... etc
Ref.: https://stackoverflow.com/a/39988702
"""
unit = unit.lower()
units = ['bytes', 'kb', 'mb', 'gb', 'tb']
if unit not in units:
"""
logger.error(f"'{unit}' is not a valid unit\n"
f'Aborting {convert_bytes_decimal.__name__}()')
"""
return None
for x in units:
if num < 1000.0 or x == unit:
# return "%3.1f %s" % (num, x)
return num, "%3.1f %s" % (num, x)
num /= 1000.0
def convert_result_from_shell_cmd(old_result):
new_result = Result()
for attr_name, new_val in new_result.__dict__.items():
old_val = getattr(old_result, attr_name)
if old_val is None:
shell_args = getattr(old_result, 'args', None)
# logger.debug(f'result.{attr_name} is None. Shell args: {shell_args}')
else:
if isinstance(new_val, str):
try:
new_val = old_val.decode('UTF-8')
except (AttributeError, UnicodeDecodeError) as e:
if type(e) == UnicodeDecodeError:
# old_val = b'...'
new_val = old_val.decode('unicode_escape')
else:
# `old_val` already a string
# logger.debug('Error decoding old value: {}'.format(old_val))
# logger.debug(e.__repr__())
# logger.debug('Value already a string. No decoding necessary')
new_val = old_val
try:
new_val = ast.literal_eval(new_val)
except (SyntaxError, ValueError) as e:
# NOTE: ValueError might happen if value consists of [A-Za-z]
# logger.debug('Error evaluating the value: {}'.format(old_val))
# logger.debug(e.__repr__())
# logger.debug('Aborting evaluation of string. Will consider
# the string as it is')
pass
else:
new_val = old_val
setattr(new_result, attr_name, new_val)
return new_result
# Tries to convert the supplied ebook file into .txt. It uses calibre's
# ebook-convert tool. For optimization, if present, it will use pdftotext
# for pdfs, catdoc for word files and djvutxt for djvu files.
# Ref.: https://bit.ly/2HXdf2I
def convert_to_txt(input_file, output_file, mime_type,
djvu_convert_method=DJVU_CONVERT_METHOD,
epub_convert_method=EPUB_CONVERT_METHOD,
msword_convert_method=MSWORD_CONVERT_METHOD,
pdf_convert_method=PDF_CONVERT_METHOD, **kwargs):
if mime_type.startswith('image/vnd.djvu') \
and djvu_convert_method == 'djvutxt' and command_exists('djvutxt'):
logger.debug('The file looks like a djvu, using djvutxt to extract the text')
result = djvutxt(input_file, output_file)
elif mime_type.startswith('application/epub+zip') \
and epub_convert_method == 'epubtxt' and command_exists('unzip'):
logger.debug('The file looks like an epub, using epubtxt to extract the text')
result = epubtxt(input_file, output_file)
elif mime_type == 'application/msword' \
and msword_convert_method in ['catdoc', 'textutil'] \
and (command_exists('catdoc') or command_exists('textutil')):
msg = 'The file looks like a doc, using {} to extract the text'
# TODO: select convert method as specified by user
# e.g. if convert_method = 'textutil' and 'catdoc' exists,
# 'catdoc' will be used
if command_exists('catdoc'):
logger.debug(msg.format('catdoc'))
result = catdoc(input_file, output_file)
else:
logger.debug(msg.format('textutil'))
result = textutil(input_file, output_file)
elif mime_type == 'application/pdf' and pdf_convert_method == 'pdftotext' \
and command_exists('pdftotext'):
logger.debug('The file looks like a pdf, using pdftotext to extract the text')
result = pdftotext(input_file, output_file)
elif (not mime_type.startswith('image/vnd.djvu')) \
and mime_type.startswith('image/'):
msg = f'The file looks like a normal image ({mime_type}), skipping ' \
f'ebook-convert usage: {input_file}'
# logger.debug(msg)
return convert_result_from_shell_cmd(Result(stderr=msg, returncode=1))
else:
logger.debug(f"Trying to use calibre's ebook-convert to convert the {mime_type} file to .txt")
result = ebook_convert(input_file, output_file)
return result
def djvutxt(input_file, output_file, pages=None):
pages = f'--page={pages}' if pages else ''
cmd = f'djvutxt "{input_file}" "{output_file}" {pages}'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return convert_result_from_shell_cmd(result)
def ebook_convert(input_file, output_file):
cmd = f'ebook-convert "{input_file}" "{output_file}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return convert_result_from_shell_cmd(result)
def epubtxt(input_file, output_file):
cmd = f'unzip -c "{input_file}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if not result.stderr:
text = str(result.stdout)
with open(output_file, 'w') as f:
f.write(text)
result.stdout = text
return convert_result_from_shell_cmd(result)
def extract_archive(input_file, output_file):
cmd = f'7z x -o"{output_file}" "{input_file}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return convert_result_from_shell_cmd(result)
def fail_file(old_path, reason, new_path=None):
# More info about printing in terminal with color:
# https://stackoverflow.com/a/21786287
old_path = get_parts_from_path(old_path)
logger.error(red(f'ERR:\t{old_path[:150]}'))
second_line = red(f'REASON:\t{reason}')
if new_path:
new_path = get_parts_from_path(new_path)
logger.error(second_line)
new_fp = normalize("NFKC", str(new_path))
logger.error(red(f'TO:\t{new_fp[:150]}\n'))
else:
logger.error(second_line + '\n')
# Uses Calibre's `fetch-ebook-metadata` CLI tool to download metadata from
# online sources. The first parameter is the comma-separated list of allowed
# plugins (e.g. 'Goodreads,Amazon.com,Google') and the second parameter is the
# remaining of the `fetch-ebook-metadata`'s options, e.g.
# options='--verbose --opf isbn=1234567890'
# Returns the ebook metadata as a string; if no metadata found, an empty string
# is returned
# Ref.: https://bit.ly/2HS0iXQ
def fetch_metadata(isbn_sources, options=''):
args = f'fetch-ebook-metadata {options}'
if isinstance(isbn_sources, str):
isbn_sources = isbn_sources.split(',')
for isbn_source in isbn_sources:
args += f' --allowed-plugin={isbn_source} '
# Remove trailing whitespace
args = args.strip()
logger.debug(f'Calling `{args}`')
args = shlex.split(args)
# NOTE: `stderr` contains the whole log from running the fetch-data query
# from the specified online sources. Thus, `stderr` is a superset of
# `stdout` which only contains the ebook metadata for those fields that
# have the pattern '[a-zA-Z()]+ +: .*'
# TODO: make sure that you are getting only the fields that match the pattern
# '[a-zA-Z()]+ +: .*' since you are not using a regex on the result
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return convert_result_from_shell_cmd(result)
# Searches the input string for ISBN-like sequences and removes duplicates and
# finally validates them using is_isbn_valid() and returns them separated by
# `isbn_ret_separator`
# Ref.: https://bit.ly/2HyLoSQ
def find_isbns(input_str, isbn_blacklist_regex=ISBN_BLACKLIST_REGEX,
isbn_regex=ISBN_REGEX, isbn_ret_separator=ISBN_RET_SEPARATOR,
**kwargs):
isbns = []
invalid_isbns = []
duplicate_isbns = []
check_more = True
input_str_copy = copy(input_str)
while True:
# TODO: they are using grep -oP
# Ref.: https://bit.ly/2HUbnIs
# Remove spaces
# input_str = input_str.replace(' ', '')
matches = re.finditer(isbn_regex, input_str_copy)
for i, match in enumerate(matches):
match = match.group()
# Remove everything except numbers [0-9], 'x', and 'X'
# NOTE: equivalent to UNIX command `tr -c -d '0-9xX'`
# TODO 1: they don't remove \n in their code
# TODO 2: put the following in a function
del_tab = string.printable[10:].replace('x', '').replace('X', '')
tran_tab = str.maketrans('', '', del_tab)
match = match.translate(tran_tab)
# Only keep unique ISBNs
if match not in isbns:
# Validate ISBN
if is_isbn_valid(match):
if re.match(isbn_blacklist_regex, match):
logger.debug(f'Wrong ISBN (blacklisted): {match}')
else:
logger.debug(f'Valid ISBN found: {match}')
isbns.append(match)
else:
if match not in invalid_isbns:
logger.debug(f'Invalid ISBN found: {match}')
invalid_isbns.append(match)
else:
if match not in duplicate_isbns:
logger.debug(f'Non-unique ISBN found: {match}')
duplicate_isbns.append(match)
if isbns or not check_more:
break
# NOTE: remove it since we are using a longer regex that covers many cases of dashes
input_str_copy = input_str_copy.replace('–', '').replace('—', '').replace('-', '').replace('·', ''). \
replace('.', '').replace(' ', '')
input_str_no_newlines = input_str_copy.replace('\n', '')[:100]
logger.debug('Trying to find ISBNs with modified input string (showing only first 100 characters): '
f'{input_str_no_newlines}')
check_more = False
if not isbns:
input_str_no_newlines = input_str.replace('\n', '')[:100]
# msg (next line) not used anymore
# msg = f'"{input_str_no_newlines}"' if len(input_str_no_newlines) < 100 else ''
logger.debug(f'No ISBN found in the input string (showing only first 100 characters): {input_str_no_newlines}')
# NOTE: if isbns = [], it returns ''
# ' - '.join([]) => ''
return isbn_ret_separator.join(isbns)
def get_all_isbns_from_archive(
file_path, isbn_blacklist_regex=ISBN_BLACKLIST_REGEX,
isbn_direct_files=ISBN_DIRECT_FILES,
isbn_reorder_files=ISBN_DIRECT_FILES,
isbn_ignored_files=ISBN_IGNORED_FILES, isbn_regex=ISBN_REGEX,
isbn_ret_separator=ISBN_RET_SEPARATOR, ocr_command=OCR_COMMAND,
ocr_enabled=OCR_ENABLED,
ocr_only_first_last_pages=OCR_ONLY_FIRST_LAST_PAGES, **kwargs):
func_params = locals().copy()
func_params.pop('file_path')
all_isbns = []
tmpdir = tempfile.mkdtemp()
logger.debug(f"Trying to decompress '{os.path.basename(file_path)}' and "
"recursively scan the contents")
logger.debug(f"Decompressing '{file_path}' into tmp folder '{tmpdir}'")
result = extract_archive(file_path, tmpdir)
if result.stderr:
logger.debug('Error extracting the file (probably not an archive)! '
'Removing tmp dir...')
logger.debug(result.stderr)
remove_tree(tmpdir)
return ''
logger.debug(f"Archive extracted successfully in '{tmpdir}', scanning "
f"contents recursively...")
# TODO: Ref.: https://stackoverflow.com/a/2759553
# TODO: ignore .DS_Store
for path, dirs, files in os.walk(tmpdir, topdown=False):
# TODO: they use flag options for sorting the directory contents
# see https://github.com/na--/ebook-tools#miscellaneous-options [FILE_SORT_FLAGS]
for file_to_check in files:
# TODO: add debug_prefixer
file_to_check = os.path.join(path, file_to_check)
isbns = search_file_for_isbns(file_to_check, **func_params)
if isbns:
logger.debug(f"Found ISBNs\n{isbns}")
# TODO: two prints, one for stderror and the other for stdout
logger.debug(isbns.replace(isbn_ret_separator, '\n'))
for isbn in isbns.split(isbn_ret_separator):
if isbn not in all_isbns:
all_isbns.append(isbn)
logger.debug(f'Removing {file_to_check}...')
remove_file(file_to_check)
if len(os.listdir(path)) == 0 and path != tmpdir:
os.rmdir(path)
elif path == tmpdir:
if len(os.listdir(tmpdir)) == 1 and '.DS_Store' in tmpdir:
remove_file(os.path.join(tmpdir, '.DS_Store'))
logger.debug(f"Removing temporary folder '{tmpdir}' (should be empty)...")
if is_dir_empty(tmpdir):
remove_tree(tmpdir)
return isbn_ret_separator.join(all_isbns)
def get_ebook_metadata(file_path):
# TODO: add `ebook-meta` in PATH
cmd = f'ebook-meta "{file_path}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return convert_result_from_shell_cmd(result)
# NOTE: the original function was returning the file size in MB... GB... but it
# was actually returning the file in MiB... GiB... etc (dividing by 1024, not 1000)
# see the comment @ https://bit.ly/2HL5RnI
# TODO: call this function when computing file size here in lib.py
# TODO: unit can be given with binary prefix as {'bytes', 'KiB', 'MiB', 'GiB', TiB'}
# or decimal prefix as {'bytes', 'KB', 'MB', 'GB', TB'}
def get_file_size(file_path, unit):
"""
This function will return the file size
Ref.: https://stackoverflow.com/a/39988702
"""
if os.path.isfile(file_path):
file_info = os.stat(file_path)
if unit[1] == 'i':
return convert_bytes_binary(file_info.st_size, unit=unit)
else:
return convert_bytes_decimal(file_info.st_size, unit=unit)
else:
logger.error(f"'{file_path}' is not a file\nAborting get_file_size()")
return None
# Using Python built-in module mimetypes
def get_mime_type(file_path):
try:
# NOTE: on Ubuntu (docker, python 3.6.9) file_path is PosixPath and they expect str
# On python 3.7, they don't care that file_path is PosixPath
file_path = str(file_path)
mime_type = mimetypes.guess_type(file_path)[0]
except TypeError as e:
logger.error(red(f"Couldn't get the mime type: {file_path}"))
logger.exception(e)
return ''
return mime_type if mime_type else ''
# Return number of pages in a djvu document
def get_pages_in_djvu(file_path):
cmd = f'djvused -e "n" "{file_path}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return convert_result_from_shell_cmd(result)
# Return number of pages in a pdf document
def get_pages_in_pdf(file_path, cmd='mdls'):
assert cmd in ['mdls', 'pdfinfo']
if command_exists(cmd) and cmd == 'mdls':
cmd = f'mdls -raw -name kMDItemNumberOfPages "{file_path}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if '(null)' in str(result.stdout):
return get_pages_in_pdf(file_path, cmd='pdfinfo')
else:
cmd = f'pdfinfo "{file_path}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if result.returncode == 0:
result = convert_result_from_shell_cmd(result)
result.stdout = int(re.findall('^Pages:\s+([0-9]+)',
result.stdout,
flags=re.MULTILINE)[0])
return result
return convert_result_from_shell_cmd(result)
def get_parts_from_path(path):
path = Path(path)
anchor = path.anchor
if not anchor:
anchor = '/'
return f'{anchor}'.join(path.parts[-2:])
# Checks if directory is empty
# Ref.: https://stackoverflow.com/a/47363995
def is_dir_empty(path):
return next(os.scandir(path), None) is None
# Ref.: https://stackoverflow.com/a/15924160
def is_file_empty(file_path):
# TODO: test when file doesn't exist
# TODO: see if the proposed solution @ https://stackoverflow.com/a/15924160
# is equivalent to using try and catch the `OSError`
try:
return not os.path.getsize(file_path) > 0
except OSError as e:
logger.error(f'Error: {e.filename} - {e.strerror}.')
return False
# Validates ISBN-10 and ISBN-13 numbers
# Ref.: https://bit.ly/2HO2lMD
def is_isbn_valid(isbn):
# TODO: there is also a Python package for validating ISBNs (but dependency)
# Remove whitespaces (space, tab, newline, and so on), '-', and capitalize all
# characters (ISBNs can consist of numbers [0-9] and the letters [xX])
isbn = ''.join(isbn.split())
isbn = isbn.replace('-', '')
isbn = isbn.upper()
sum = 0
# Case 1: ISBN-10
if len(isbn) == 10:
for i in range(len(isbn)):
if i == 9 and isbn[i] == 'X':
number = 10
else:
number = int(isbn[i])
sum += (number * (10 - i))
if sum % 11 == 0:
return True
# Case 2: ISBN-13
elif len(isbn) == 13:
if isbn[0:3] in ['978', '979']:
for i in range(0, len(isbn), 2):
sum += int(isbn[i])
for i in range(1, len(isbn), 2):
sum += (int(isbn[i])*3)
if sum % 10 == 0:
return True
return False
def move(src, dst, clobber=True):
# TODO: necessary?
# Since path can be relative to the cwd
# src = os.path.abspath(src)
# filename = os.path.basename(src)
src = Path(src)
dst = Path(dst)
if dst.exists():
logger.debug(f'{dst.name}: file already exists')
logger.debug(f"Destination folder path: {dst.parent}")
if clobber:
logger.debug(f'{dst.name}: overwriting the file')
shutil.move(src, dst)
logger.debug("File moved!")
else:
logger.debug(f'{dst.name}: cannot overwrite existing file')
logger.debug(f"Skipping it!")
else:
logger.debug(f"Moving '{src.name}'...")
logger.debug(f"Destination folder path: {dst.parent}")
shutil.move(src, dst)
logger.debug("File moved!")
# Ref.: https://bit.ly/2HxYEaw
def move_or_link_ebook_file_and_metadata(
new_folder, current_ebook_path, current_metadata_path, dry_run=DRY_RUN,
keep_metadata=KEEP_METADATA,
output_filename_template=OUTPUT_FILENAME_TEMPLATE,
output_metadata_extension=OUTPUT_METADATA_EXTENSION,
symlink_only=SYMLINK_ONLY, **kwargs):
# Get ebook's file extension
ext = Path(current_ebook_path).suffix
ext = ext[1:] if ext[0] == '.' else ext
d = {'EXT': ext}
# Extract fields from metadata file
with open(current_metadata_path, 'r') as f:
for line in f:
# Get field name and value separately, e.g.
# 'Title : A nice ebook' ---> field_name = 'Title ' and field_value = ' A nice ebook'
# Find the first colon and split on its position
pos = line.find(':')
field_name, field_value = line[:pos], line[pos+1:]
# TODO: try to use subprocess.run instead of subprocess.Popen and
# creating two processes
# OR try to do it without subprocess, only with Python regex
# Process field name
# TODO: converting characters to upper case with `-e 's/\(.*\)/\\U\1/'`
# doesn't work on mac, \\U is not supported
result = substitute_with_sed(regex='[ \t]*$', replacement='',
text=field_name, use_global=False)
result = substitute_with_sed(regex=' ', replacement='_', text=result)
field_name = substitute_with_sed(regex='[^a-zA-Z0-9_]', replacement='', text=result).upper()
# Process field value
# Get only the first 100 characters
d[field_name] = substitute_with_sed(
regex='[\\/\*\?<>\|\x01-\x1F\x7F\x22\x24\x60]', replacement='_',
text=field_value)[:100]
logger.debug('Variables that will be used for the new filename construction:')
for k, v in d.items():
# TODO: important, encode('utf-8')? like in rename?
logger.debug(f'{k}: {v}')
new_name = substitute_params(d, output_filename_template)
logger.debug(f"The new file name of the book file/link '{current_ebook_path}' "
f'will be: {new_name}')
new_path = unique_filename(new_folder, new_name)
logger.debug(f'Full path: {new_path}')
move_or_link_file(current_ebook_path, new_path, dry_run, symlink_only)
if keep_metadata:
new_metadata_path = f'{new_path}.{output_metadata_extension}'
logger.debug(f"Moving metadata file '{current_metadata_path}' to "
f"'{new_metadata_path}'....")
if dry_run:
logger.debug('Removing current metadata file: '
f'{current_metadata_path}')
remove_file(current_metadata_path)
else:
if Path(new_metadata_path).is_file():
logger.debug(f'File already exists: {new_metadata_path}')
else:
shutil.move(current_metadata_path, new_metadata_path)
else:
logger.debug(f'Removing metadata file {current_metadata_path}...')
remove_file(current_metadata_path)
return new_path
def move_or_link_file(current_path, new_path, dry_run=DRY_RUN,
symlink_only=SYMLINK_ONLY):
new_folder = Path(new_path).parent
if dry_run:
logger.debug('DRY RUN! No file rename/move/symlink/etc. operations '
'will actually be executed')
# Create folder
if not new_folder.exists():
logger.debug(f'Creating folder {new_folder}')
if not dry_run:
new_folder.mkdir()
# Symlink or move file
if symlink_only:
logger.debug(f"Symlinking file '{current_path}' to '{new_path}'...")
if not dry_run:
Path(new_path).symlink_to(current_path)
else:
logger.debug(f"Moving file '{current_path}' to '{new_path}'...")
if not dry_run:
move(current_path, new_path, clobber=False)
def namespace_to_dict(ns):
namspace_classes = [Namespace, SimpleNamespace]
# TODO: check why not working anymore
# if isinstance(ns, SimpleNamespace):
if type(ns) in namspace_classes:
adict = vars(ns)
else:
adict = ns
for k, v in adict.items():
# if isinstance(v, SimpleNamespace):
if type(v) in namspace_classes:
v = vars(v)
adict[k] = v
if isinstance(v, dict):
namespace_to_dict(v)
return adict
# OCR on a pdf, djvu document or image
# NOTE: If pdf or djvu document, then first needs to be converted to image and then OCR
def ocr_file(file_path, output_file, mime_type,
ocr_command=OCR_COMMAND,
ocr_only_first_last_pages=OCR_ONLY_FIRST_LAST_PAGES, **kwargs):
# Convert pdf to png image
def convert_pdf_page(page, input_file, output_file):
cmd = f'gs -dSAFER -q -r300 -dFirstPage={page} -dLastPage={page} ' \
'-dNOPAUSE -dINTERPOLATE -sDEVICE=png16m ' \
f'-sOutputFile="{output_file}" "{input_file}" -c quit'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return convert_result_from_shell_cmd(result)
# Convert djvu to tif image
def convert_djvu_page(page, input_file, output_file):
cmd = f'ddjvu -page={page} -format=tif "{input_file}" "{output_file}"'
args = shlex.split(cmd)
result = subprocess.run(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return convert_result_from_shell_cmd(result)
if mime_type.startswith('application/pdf'):
result = get_pages_in_pdf(file_path)
num_pages = result.stdout
logger.debug(f"Result of '{get_pages_in_pdf.__name__}()' on '{file_path}':\n{result}")
page_convert_cmd = convert_pdf_page
elif mime_type.startswith('image/vnd.djvu'):
result = get_pages_in_djvu(file_path)
num_pages = result.stdout
logger.debug(f"Result of '{get_pages_in_djvu.__name__}()' on '{file_path}':\n{result}")
page_convert_cmd = convert_djvu_page
elif mime_type.startswith('image/'):
logger.debug(f"Running OCR on file '{file_path}' and with mime type '{mime_type}'...")
if ocr_command in globals():
result = eval(f'{ocr_command}("{file_path}", "{output_file}")')
logger.debug(f"Result of '{ocr_command}':\n{result}")
return 0
else:
msg = red("Function '{ocr_command}' doesn't exit.")
logger.error(f'{msg}')
return 1
else:
logger.error(f"{red('Unsupported mime type')} '{mime_type}'!")
return 1
if result.returncode == 1:
err_msg = result.stdout if result.stdout else result.stderr
msg = "Couldn't get number of pages:"
logger.error(f"{red(msg)} '{str(err_msg).strip()}'")
return 1
if ocr_command not in globals():
msg = red("Function '{ocr_command}' doesn't exit.")
logger.error(f'{msg}')
return 1
logger.debug(f"The file '{file_path}' has {num_pages} page{'s' if num_pages > 1 else ''}")
logger.debug(f'mime type: {mime_type}')
# Pre-compute the list of pages to process based on ocr_only_first_last_pages
if ocr_only_first_last_pages:
ocr_first_pages = int(ocr_only_first_last_pages[0])
ocr_last_pages = int(ocr_only_first_last_pages[1])
pages_to_process = [i for i in range(1, ocr_first_pages + 1)]
pages_to_process.extend([i for i in range(num_pages + 1 - ocr_last_pages, num_pages + 1)])
else:
# ocr_only_first_last_pages is False
logger.debug('ocr_only_first_last_pages is False')
logger.warning(f"{yellow('OCR will be applied to all ({pages}) pages of the document')}")
pages_to_process = [i for i in range(1, num_pages+1)]
logger.debug(f'Pages to process: {pages_to_process}')
text = ''
for i, page in enumerate(pages_to_process, start=1):
logger.debug(f'Processing page {i} of {len(pages_to_process)}')
# Make temporary files
tmp_file = tempfile.mkstemp()[1]
tmp_file_txt = tempfile.mkstemp(suffix='.txt')[1]
logger.debug(f'Running OCR of page {page}...')
logger.debug(f'Using tmp files {tmp_file} and {tmp_file_txt}')
# doc(pdf, djvu) --> image(png, tiff)
result = page_convert_cmd(page, file_path, tmp_file)
if result.returncode == 0:
logger.debug(f"Result of {page_convert_cmd.__name__}():\n{result}")
# image --> text
logger.debug(f"Running the '{ocr_command}'...")
result = eval(f'{ocr_command}("{tmp_file}", "{tmp_file_txt}")')
if result.returncode == 0:
logger.debug(f"Result of '{ocr_command}':\n{result}")
with open(tmp_file_txt, 'r') as f:
data = f.read()
# logger.debug(f"Text content of page {page}:\n{data}")
text += data
else:
msg = red(f"Image couldn't be converted to text: {result}")
logger.error(f'{msg}')
logger.error(f'Skipping current page ({page})')
else:
msg = red(f"Document couldn't be converted to image: {result}")
logger.error(f'{msg}')
logger.error(f'Skipping current page ({page})')
# Remove temporary files