/
search-ebooks
executable file
·412 lines (385 loc) · 17.5 KB
/
search-ebooks
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
#!/usr/bin/env python
import argparse
import os
from pathlib import Path
from diskcache import Cache
import searchebooks
from pyebooktools.edit_config import edit_file, reset_file
from pyebooktools.lib import (
BLUE, GREEN, NC, RED, YELLOW, color_msg as c, get_hash)
from pyebooktools.scripts.ebooktools import (
LOG_CFG, MAIN_CFG, add_general_options, add_ocr_options,
process_returned_values, required_length)
from pyebooktools.utils.genutils import (
get_config_dict, namespace_to_dict, override_config_with_args, setup_log)
from pyebooktools.utils.logutils import init_log
from searchebooks.configs import default_config as default_cfg, __path__
from searchebooks.searchebooks import searcher
logger = init_log(__name__, __file__)
# =====================
# Default config values
# =====================
DEFAULT_EBOOK_FORMATS = ['djvu', 'epub', 'html', 'pdf', 'txt']
EBOOK_FORMATS = default_cfg.ebook_formats
CACHE_FOLDER = default_cfg.cache_folder
CACHE_SIZE_LIMIT = default_cfg.cache_size_limit
DJVU_SEARCH_METHOD = default_cfg.djvu_search_method
DJVU_SEARCH_METHODS = ['djvutxt', 'calibre']
EPUB_SEARCH_METHOD = default_cfg.epub_search_method
EPUB_SEARCH_METHODS = ['epubtxt', 'calibre']
EVICTION_POLICY = default_cfg.eviction_policy
MSWORD_SEARCH_METHOD = default_cfg.msword_search_method
MSWORD_SEARCH_METHODS = ['catdoc', 'textutil', 'calibre']
OCR_ENABLED = default_cfg.ocr_enabled
PDF_SEARCH_METHOD = default_cfg.pdf_search_method
PDF_SEARCH_METHODS = ['pdftotext', 'calibre']
USE_CACHE = default_cfg.use_cache
class ArgumentParser(argparse.ArgumentParser):
def error(self, message):
# self.print_help(sys.stderr)
# self.print_usage(sys.stderr)
print(self.format_usage().splitlines()[0])
self.exit(2, c(f'\nerror: {message}\n', 'r'))
# Ref.: https://stackoverflow.com/a/32891625/14664104
class MyFormatter(argparse.HelpFormatter):
"""
Corrected _max_action_length for the indenting of subactions
"""
def add_argument(self, action):
if action.help is not argparse.SUPPRESS:
# find all invocations
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
current_indent = self._current_indent
for subaction in self._iter_indented_subactions(action):
# compensate for the indent that will be added
indent_chg = self._current_indent - current_indent
added_indent = 'x' * indent_chg
invocations.append(added_indent + get_invocation(subaction))
# print('inv', invocations)
# update the maximum item length
invocation_length = max([len(s) for s in invocations])
action_length = invocation_length + self._current_indent
self._action_max_length = max(self._action_max_length,
action_length)
# add the item to the list
self._add_item(self._format_action, [action])
# Ref.: https://stackoverflow.com/a/23941599/14664104
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
# if the Optional doesn't take a value, format is:
# -s, --long
if action.nargs == 0:
parts.extend(action.option_strings)
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
# change to
# -s, --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
for option_string in action.option_strings:
# parts.append('%s %s' % (option_string, args_string))
parts.append('%s' % option_string)
parts[-1] += ' %s'%args_string
return ', '.join(parts)
def check_formats():
class CheckFromats(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
for i, v in enumerate(values):
if v.startswith('.'):
v = v[1:]
values[i] = v
if v not in DEFAULT_EBOOK_FORMATS:
msg = f'argument "{self.dest}" doesn\'t support {v}. Only ' \
'the following ebook formats are supported: ' \
f'{DEFAULT_EBOOK_FORMATS}'
raise argparse.ArgumentTypeError(msg)
setattr(args, self.dest, values)
return CheckFromats
def get_configs_dirpath():
from searchebooks.configs import __path__
return __path__[0]
def get_default_message(default_value):
return f' ({GREEN}default: {default_value}{NC})'
def setup_argparser():
width = os.get_terminal_size().columns - 5
# Setup the parser
name_input = 'input_data'
msg = 'Search through content and metadata of ebooks.'
parser = ArgumentParser(
description=f'{RED}IMPORTANT{NC}: if an argument has spaces, '
'enclose it in quotation marks, e.g. "Book title with '
'spaces"',
usage=f'{BLUE}%(prog)s [OPTIONS] {{{name_input}}}{NC}\n\n{msg}',
add_help=False,
# ArgumentDefaultsHelpFormatter
# HelpFormatter
# RawDescriptionHelpFormatter
formatter_class=lambda prog: MyFormatter(
prog, max_help_position=50, width=width))
general_group = add_general_options(
parser,
remove_opts=['dry-run', 'keep-metadata', 'reverse', 'symlink-only'],
program_version=searchebooks.__version__,
title=f'{YELLOW}General options{NC}')
general_group.add_argument(
'--regex', dest='regex',
action='store_true',
help='Use regex when searching ebook content and metadata.')
general_group.add_argument(
'-i', '-ignore-case', dest='ignore_case',
action='store_true',
help='Perform case insensitive matching when searching ebook '
'content and metadata. By default, content and metadata search is '
'case sensitive.')
general_group.add_argument(
"--ocr", "--ocr-enabled", dest='ocr_enabled',
choices=['always', 'true', 'false'], default=OCR_ENABLED,
help='Whether to enable OCR for .pdf, .djvu and image files. It is '
'disabled by default.' + get_default_message(OCR_ENABLED))
# ================
# Edit/reset files
# ================
edit_group = parser.add_argument_group(
f'{YELLOW}Edit/reset a configuration file{NC}')
parser_edit_mutual_group = edit_group.add_mutually_exclusive_group()
parser_edit_mutual_group.add_argument(
"-e", "--edit", action='store_true',
help='Edit a configuration file, either the main configuration file '
f'(`{MAIN_CFG}`) or the logging configuration file (`{LOG_CFG}`).')
edit_group.add_argument(
"-a", "--app", dest="app", default=None,
help='''Name of the application to use for editing the file. If no
name is given, then the default application for opening this type of
file will be used.''')
parser_edit_mutual_group.add_argument(
'-r', '--reset', action='store_true',
help=f'Reset a configuration file (`{MAIN_CFG}` or `{LOG_CFG}`) '
'with factory default values.')
edit_group.add_argument(
'--cfg', choices=[LOG_CFG, MAIN_CFG],
help='Configuration file to edit or reset: '
f'`{MAIN_CFG}` or `{LOG_CFG}`' + get_default_message(MAIN_CFG))
# =====
# Cache
# =====
cache_group = parser.add_argument_group(title=f'{YELLOW}Cache options{NC}')
cache_group.add_argument(
'--uc', '--use-cache', dest='use_cache', action='store_true',
help='Use cache.')
cache_group.add_argument(
'--cf', '--cache-folder', metavar='PATH', default=CACHE_FOLDER,
help='Cache folder.' + get_default_message(CACHE_FOLDER))
cache_group.add_argument(
'--ep', '--eviction-policy', dest='eviction_policy', metavar='POLICY',
choices=['least-recently-stored', 'least-recently-used',
'least-frequently-used', 'none'], default=EVICTION_POLICY,
help='Eviction policy which can either be: `least-recently-stored`, '
'`least-recently-used`, `least-frequently-used` or '
'`none` (never evict keys).' + get_default_message(EVICTION_POLICY))
cache_group.add_argument(
'--csl', '--cache-size-limit', metavar='SIZE', dest='cache_size_limit',
default=CACHE_SIZE_LIMIT, type=int,
help='Size limit in gigabytes (GB).'
+ get_default_message(CACHE_SIZE_LIMIT))
mutual_cache_group = cache_group.add_mutually_exclusive_group()
mutual_cache_group.add_argument(
'-c', '--clear-cache', dest='clear_cache', action='store_true',
help='Clear cache.')
mutual_cache_group.add_argument(
'--rk', '--remove-keys', metavar='KEY', dest='remove_keys',
nargs='+', default=[],
help='Keys to be removed from the cache which can either be the paths '
'to the ebook files or their MD5 hash.')
mutual_cache_group.add_argument(
'-n', '--number-items', dest='number_items', action='store_true',
help='Shows number of items stored in cache.')
# ===========
# Search text
# ===========
search_text_group = parser.add_argument_group(
title=f'{YELLOW}Fulltext search options{NC}')
search_text_group.add_argument(
'--query', metavar='QUERY',
help='Search query to look through an ebook text content. It can also '
'be considered a regex by using the `--text-regex` flag.')
search_text_group.add_argument(
'-f', '--ebook-formats', metavar='FORMAT', nargs='+',
default=EBOOK_FORMATS, action=check_formats(),
choices=DEFAULT_EBOOK_FORMATS,
help=f'Choice one or more from: {DEFAULT_EBOOK_FORMATS}.'
+ get_default_message(EBOOK_FORMATS))
search_text_group.add_argument(
'--dsm', '--djvu-search-method', metavar='METHOD',
dest='djvu_search_method', choices=DJVU_SEARCH_METHODS,
default=DJVU_SEARCH_METHOD,
help='Search method for djvu files. Choose one from: '
f'{DJVU_SEARCH_METHODS}.' + get_default_message(DJVU_SEARCH_METHOD))
search_text_group.add_argument(
'--msm', '--msword-search-method', metavar='METHOD',
dest='msword_search_method', choices=MSWORD_SEARCH_METHODS,
default=MSWORD_SEARCH_METHOD,
help='Search method for doc files. Choose one from '
f'{MSWORD_SEARCH_METHODS}.'
+ get_default_message(MSWORD_SEARCH_METHOD))
search_text_group.add_argument(
'--esm', '--epub-search-method', metavar='METHOD',
dest='epub_search_method', choices=EPUB_SEARCH_METHODS,
default=EPUB_SEARCH_METHOD,
help='Search method for epub files. Choose one from: '
f'{EPUB_SEARCH_METHODS}.' + get_default_message(EPUB_SEARCH_METHOD))
search_text_group.add_argument(
'--psm', '--pdf-search-method', metavar='METHOD',
dest='pdf_search_method', choices=PDF_SEARCH_METHODS,
default=PDF_SEARCH_METHOD,
help='Search method for pdf files. Choose one from: '
f'{PDF_SEARCH_METHOD}.' + get_default_message(PDF_SEARCH_METHOD))
search_text_group.add_argument(
"--tr", "--text-regex", dest='text_regex',
action='store_true',
help='Use regex when searching ebook text content.')
search_text_group.add_argument(
'--ti', '--text-ignore-case', dest='text_ignore_case',
action='store_true',
help='Perform case insensitive matching when searching ebook '
'text content. By default, content search is case sensitive.')
# ===============
# Search metadata
# ===============
search_metadata_group = parser.add_argument_group(
title=f'{YELLOW}Metadata search options{NC}',
description=f'{RED}IMPORTANT:{NC} the metadata fields and the fulltext '
'search query are linked with ANDs between each other')
# TODO: add pages field
search_metadata_group.add_argument(
'--authors', help='Authors')
search_metadata_group.add_argument(
'-k', '--book-producer', help='Book producer')
search_metadata_group.add_argument(
'--category', help='Category')
search_metadata_group.add_argument(
'--comments', help='Comments')
# TODO: important, date or published?
"""
search_metadata_group.add_argument(
'-d', '--date', help='Published date')
"""
search_metadata_group.add_argument(
'--filename', help='Filename')
search_metadata_group.add_argument(
'--identifiers', help='Identifiers')
search_metadata_group.add_argument(
'--isbn', help='ISBN')
search_metadata_group.add_argument(
'-l', '--language', help='Language')
search_metadata_group.add_argument(
'--published', help='Published date')
search_metadata_group.add_argument(
'-p', '--publisher', help='Publisher')
search_metadata_group.add_argument(
'--rating', help='Rating')
search_metadata_group.add_argument(
'-s', '--series', help='Series')
search_metadata_group.add_argument(
'--tags', help='Tags')
search_metadata_group.add_argument(
'-t', '--title', help='Title')
search_metadata_group.add_argument(
"--mr", "--metadata-regex", dest='metadata_regex',
action='store_true',
help='Use regex when searching ebook metadata.')
search_metadata_group.add_argument(
'--mi', '--metadata-ignore-case', dest='metadata_ignore_case',
action='store_true',
help='Perform case insensitive matching when searching ebook '
'metadata. By default, metadata earch is case sensitive.')
# ==============
# Input argument
# ==============
input_group = parser.add_argument_group(title=f'{YELLOW}Input argument{NC}')
input_group.add_argument(
name_input, default=None, nargs='*', action=required_length(0, 1),
help='Can either be the path to an ebook or a folder containing ebooks.')
return parser
def main():
try:
exit_code = 0
parser = setup_argparser()
args = parser.parse_args()
# TODO: find if you can do it in setup_argparser()
if args.app and not args.edit:
print(f'\n{RED}error: argument -e/--edit: required with argument '
f'-a/--app{NC}')
return 1
args.cache_size_limit *= 10 ** 9
# Get main cfg dict
# TODO: important, check if an option is defined more than once
configs_dirpath = __path__[0]
main_cfg = argparse.Namespace(**get_config_dict('main', configs_dirpath))
# Override main configuration from file with command-line arguments
returned_values = override_config_with_args(
main_cfg, args, default_cfg.__dict__, use_config=args.use_config)
if main_cfg.regex:
main_cfg.text_regex = True
main_cfg.metadata_regex = True
if main_cfg.ignore_case:
main_cfg.text_ignore_case = True
main_cfg.metadata_ignore_case = True
setup_log(package='searchebooks', configs_dirpath=configs_dirpath,
quiet=main_cfg.quiet,
verbose=main_cfg.verbose,
logging_level=main_cfg.logging_level,
logging_formatter=main_cfg.logging_formatter)
process_returned_values(returned_values)
# Setup cache
cache = Cache(directory=main_cfg.cache_folder,
eviction_policy=main_cfg.eviction_policy,
size_limit=main_cfg.cache_size_limit)
# TODO: important, exit script after remove keys ...?
if args.number_items:
n_items = len([k for k in cache.iterkeys()])
ending = 's' if n_items > 1 else ''
logger.info(f'There are {n_items} item{ending} in cache')
elif args.clear_cache:
result = cache.clear()
if result:
logger.info('Cache cleared!')
else:
logger.info('Cache was already empty!')
elif args.remove_keys:
for key in args.remove_keys:
if Path(key).is_file():
file_path = Path(key)
key = get_hash(file_path)
msg1 = f"File '{file_path.name}' with hash={key} " \
'removed from cache'
msg2 = f"File '{file_path.name}'"
else:
msg1 = f'Key={key} removed from cache!'
msg2 = f'Key={key}'
result = cache.delete(key)
if result:
logger.info(msg1)
else:
logger.info(msg2)
if main_cfg.edit:
exit_code = edit_file(main_cfg.cfg, main_cfg.app, get_configs_dirpath())
elif main_cfg.reset:
exit_code = reset_file(main_cfg.cfg, get_configs_dirpath())
elif main_cfg.input_data:
if isinstance(main_cfg.input_data, list):
main_cfg.input_data = main_cfg.input_data[0]
exit_code = searcher.search(cache=cache, **namespace_to_dict(main_cfg))
except AssertionError as e:
# TODO (IMPORTANT): use same logic as in Darth-Vader-RPi
# TODO: add KeyboardInterruptError
logger.error(e)
exit_code = 1
return exit_code
if __name__ == '__main__':
retcode = main()