-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathlibzim.pyx
More file actions
1769 lines (1361 loc) · 55 KB
/
libzim.pyx
File metadata and controls
1769 lines (1361 loc) · 55 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
# This file is part of python-libzim
# (see https://github.com/libzim/python-libzim)
#
# Copyright (c) 2020 Juan Diego Caballero <jdc@monadical.com>
# Copyright (c) 2020 Matthieu Gautier <mgautier@kymeria.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Make our libzim module a package by setting a __path__
# There is no real path here, but it will be passed to our module finder.
"""openZIM's file format library binding
- libzim.writer to create ZIM file with Creator
- libzim.reader to open ZIM file as Archive
- libzim.search to search on an Archive
- libzim.suggestion to retrieve suggestions on an Archive
https://openzim.org"""
__path__ = []
cimport zim
import datetime
import enum
import importlib
import importlib.abc
import os
import pathlib
import sys
import traceback
import warnings
from collections import OrderedDict
from types import ModuleType
from typing import Dict, Generator, Iterator, List, Optional, Set, TextIO, Tuple, Union
from uuid import UUID
from cpython.buffer cimport PyBUF_WRITABLE
from cpython.ref cimport PyObject
from cython.operator import preincrement
from libc.stdint cimport uint32_t, uint64_t
from libcpp cimport bool
from libcpp.map cimport map
from libcpp.memory cimport shared_ptr
from libcpp.string cimport string
from libcpp.utility cimport move
pybool = type(True)
pyint = type(1)
def create_module(name, doc, members):
"""Create/define a module for name and docstring, populated by members"""
module = ModuleType(name, doc)
_all = []
for obj in members:
if isinstance(obj, tuple):
name = obj[0]
obj = obj[1]
else:
name = obj.__name__
setattr(module, name, obj)
_all.append(name)
module.__all__ = _all
sys.modules[name] = module
return module
###############################################################################
# Public API to be called from C++ side #
###############################################################################
# This calls a python method and returns a python object.
cdef object call_method(object obj, string method):
func = getattr(obj, method.decode('UTF-8'))
return func()
# Define methods calling a python method and converting the resulting python
# object to the correct cpp type.
# Will be used by cpp side to call python method.
cdef public api:
# this tells whether a method/property is none or not
bool method_is_none(object obj, string method) with gil:
func = getattr(obj, method.decode('UTF-8'))
return func is None
bool obj_has_attribute(object obj, string attribute) with gil:
"""Check if a object has a given attribute"""
return hasattr(obj, attribute.decode('UTF-8'))
string string_cy_call_fct(object obj, string method, string *error) with gil:
"""Lookup and execute a pure virtual method on object returning a string"""
try:
ret_str = call_method(obj, method)
return ret_str.encode('UTF-8')
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return b""
zim.Blob blob_cy_call_fct(object obj, string method, string *error) with gil:
"""Lookup and execute a pure virtual method on object returning a Blob"""
cdef WritingBlob blob
try:
blob = call_method(obj, method)
if blob is None:
raise RuntimeError("Blob is none")
return move(blob.c_blob)
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return move(zim.Blob())
zim.ContentProvider* contentprovider_cy_call_fct(object obj, string method, string *error) with gil:
"""Lookup and execute a pure virtual method on object returning a ContentProvider"""
try:
contentProvider = call_method(obj, method)
if not contentProvider:
raise RuntimeError("ContentProvider is None")
return new zim.ContentProviderWrapper(<PyObject*>contentProvider)
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return NULL
zim.IndexData* indexdata_cy_call_fct(object obj, string method, string *error) with gil:
"""Lookup and execute a pure virtual method on object returning a IndexData"""
try:
indexData = call_method(obj, method)
if not indexData:
# indexData is none
return NULL;
return new zim.IndexDataWrapper(<PyObject*>indexData)
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return NULL
bool bool_cy_call_fct(object obj, string method, string *error) with gil:
"""Lookup and execute a pure virtual method on object returning a bool"""
try:
return call_method(obj, method)
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return False
uint64_t uint64_cy_call_fct(object obj, string method, string *error) with gil:
"""Lookup and execute a pure virtual method on object returning an uint64_t"""
try:
return <uint64_t> call_method(obj, method)
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return 0
uint32_t uint32_cy_call_fct(object obj, string method, string *error) with gil:
"""Lookup and execute a pure virtual method on object returning an uint_32"""
try:
return <uint32_t> call_method(obj, method)
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return 0
zim.GeoPosition geoposition_cy_call_fct(object obj, string method, string *error) with gil:
"""Lookup and execute a pure virtual method on object returning a GeoPosition"""
try:
geoPosition = call_method(obj, method)
if geoPosition:
return zim.GeoPosition(True, geoPosition[0], geoPosition[1]);
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return zim.GeoPosition(False, 0, 0)
map[zim.HintKeys, uint64_t] convertToCppHints(dict hintsDict):
"""C++ Hints from Python dict"""
cdef map[zim.HintKeys, uint64_t] ret;
for key, value in hintsDict.items():
ret[key.value] = <uint64_t>value
return ret
map[zim.HintKeys, uint64_t] hints_cy_call_fct(object obj, string method, string* error) with gil:
"""Lookup and execute a pure virtual method on object returning Hints"""
cdef map[zim.HintKeys, uint64_t] ret;
try:
func = getattr(obj, method.decode('UTF-8'))
hintsDict = {k: pybool(v) for k, v in func().items() if isinstance(k, Hint)}
return convertToCppHints(hintsDict)
except Exception as e:
error[0] = traceback.format_exc().encode('UTF-8')
return ret
###############################################################################
# Creator module #
###############################################################################
writer_module_name = f"{__name__}.writer"
cdef class WritingBlob:
"""A writable blob of data.
Attributes:
c_blob (zim.Blob): A pointer to a C++ Blob object.
ref_content (bytes): A reference to the content stored in the blob.
"""
__module__ = writer_module_name
cdef zim.Blob c_blob
cdef bytes ref_content
def __cinit__(self, content: Union[str, bytes]):
if isinstance(content, str):
self.ref_content = content.encode('UTF-8')
else:
self.ref_content = content
self.c_blob = move(zim.Blob(<char *> self.ref_content, len(self.ref_content)))
def size(self) -> pyint:
"""The size (in bytes) of the blob's content.
Returns:
The size of the blob (in bytes).
"""
return self.c_blob.size()
class Compression(enum.Enum):
"""Compression algorithms available to create ZIM files."""
__module__ = writer_module_name
# We don't care of the exact value. The function comp_from_int will do the right
# conversion to zim::Compression
none = 0
zstd = 1
class Hint(enum.Enum):
"""Generic way to pass information to the creator on how to handle item/redirection."""
__module__ = writer_module_name
COMPRESS = zim.HintKeys.COMPRESS
FRONT_ARTICLE = zim.HintKeys.FRONT_ARTICLE
class ContentProvider:
"""ABC in charge of providing the content to add in the archive to the Creator."""
__module__ = writer_module_name
def __init__(self):
self.generator = None
def get_size(self) -> pyint:
"""Size of `get_data`'s result in bytes.
Returns:
int: The size of the data in bytes.
"""
raise NotImplementedError("get_size must be implemented.")
def feed(self) -> WritingBlob:
"""Blob(s) containing the complete content of the article.
Must return an empty blob to tell writer no more content has to be written.
Sum(size(blobs)) must be equals to `self.get_size()`
Returns:
WritingBlob: The content blob(s) of the article.
"""
if self.generator is None:
self.generator = self.gen_blob()
try:
# We have to keep a ref to _blob to be sure gc do not del it while cpp is
# using it
self._blob = next(self.generator)
except StopIteration:
self._blob = WritingBlob("")
return self._blob
def gen_blob(self) -> Generator[WritingBlob, None, None]:
"""Generator yielding blobs for the content of the article.
Yields:
WritingBlob: A blob containing part of the article content.
"""
raise NotImplementedError("gen_blob (ro feed) must be implemented")
class BaseWritingItem:
"""
Data to be added to the archive.
This is a stub to override. Pass a subclass of it to `Creator.add_item()`
"""
__module__ = writer_module_name
def __init__(self):
self._blob = None
get_indexdata = None
def get_path(self) -> str:
"""Full path of item.
The path must be absolute and unique.
Returns:
Path of the item.
"""
raise NotImplementedError("get_path must be implemented.")
def get_title(self) -> str:
"""Item title. Might be indexed and used in suggestions.
Returns:
Title of the item.
"""
raise NotImplementedError("get_title must be implemented.")
def get_mimetype(self) -> str:
"""MIME-type of the item's content.
Returns:
Mimetype of the item.
"""
raise NotImplementedError("get_mimetype must be implemented.")
def get_contentprovider(self) -> ContentProvider:
"""ContentProvider containing the complete content of the item.
Returns:
The content provider of the item.
"""
raise NotImplementedError("get_contentprovider must be implemented.")
def get_hints(self) -> Dict[Hint, pyint]:
"""Get the Hints that help the Creator decide how to handle this item.
Hints affects compression, presence in suggestion, random and search.
Returns:
Hints to help the Creator decide how to handle this item.
"""
raise NotImplementedError("get_hints must be implemented.")
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}(path={self.get_path()}, "
f"title={self.get_title()})"
)
cdef class _Creator:
"""ZIM Creator.
Args:
filename: Full path to a zim file.
Attributes:
*c_creator (zim.ZimCreator): a pointer to the C++ Creator object
_filename (pathlib.Path): path to create the ZIM file at.
_started (bool): flag if the creator has started.
"""
__module__ = writer_module_name
cdef zim.ZimCreator c_creator
cdef object _filename
cdef object _started
def __cinit__(self, object filename: pathlib.Path, *args, **kwargs):
self._filename = pathlib.Path(filename)
self._started = False
# fail early if destination is not writable
parent = self._filename.expanduser().resolve().parent
if not os.access(parent, mode=os.W_OK, effective_ids=(os.access in os.supports_effective_ids)):
raise IOError(f"Unable to write ZIM file at {self._filename}")
def __init__(self, filename: pathlib.Path):
pass
def config_verbose(self, bool verbose: bool) -> _Creator:
"""Set creator verbosity inside libzim (default: off).
Args:
verbose (bool): Whether to enable verbosity.
Returns:
The Creator instance with updated verbosity settings.
"""
if self._started:
raise RuntimeError("Creator started")
self.c_creator.configVerbose(verbose)
return self
def config_compression(self, compression: Compression) -> _Creator:
"""Set compression algorithm to use.
Check libzim for default setting. (Fall 2021 default: zstd).
Args:
compression: The compression algorithm to set.
Returns:
The Creator instance with updated compression settings.
"""
if self._started:
raise RuntimeError("Creator started")
self.c_creator.configCompression(zim.comp_from_int(compression.value))
return self
def config_clustersize(self, int size: pyint) -> _Creator:
"""Set size of created clusters.
Check libzim for default setting. (Fall 2021 default: 2Mib).
libzim will store at most this value per cluster before creating
another one.
Args:
size (int): The maximum size (in bytes) for each cluster.
Returns:
The Creator instance with updated cluster size settings.
"""
if self._started:
raise RuntimeError("Creator started")
self.c_creator.configClusterSize(size)
return self
def config_indexing(self, bool indexing: bool, str language: str) -> _Creator:
"""Configures the full-text indexing feature.
Args:
indexing (bool): whether to create a full-text index of the content
language (str): language (ISO-639-3 code) to assume content in during indexation.
Returns:
The Creator instance with updated indexing settings.
"""
if self._started:
raise RuntimeError("Creator started")
self.c_creator.configIndexing(indexing, language.encode('UTF-8'))
return self
def config_nbworkers(self, int nbWorkers: pyint) -> _Creator:
"""Configures the number of threads to use for internal workers (default: 4).
Args:
nbWorkers (int): The number of threads to allocate.
Returns:
The Creator instance with updated worker thread settings.
"""
if self._started:
raise RuntimeError("Creator started")
self.c_creator.configNbWorkers(nbWorkers)
return self
def set_mainpath(self, str mainPath: str) -> _Creator:
"""Set path of the main entry.
Args:
mainPath (str): The path of the main entry.
Returns:
The Creator instance with the updated main entry path.
"""
self.c_creator.setMainPath(mainPath.encode('UTF-8'))
return self
def add_illustration(self, int size: pyint, content: bytes):
"""Add a PNG illustration to Archive.
Refer to https://wiki.openzim.org/wiki/Metadata for more details.
Args:
size (int): The width of the square PNG illustration in pixels.
content (bytes): The binary content of the PNG illustration.
Raises:
RuntimeError: If an illustration with the same width already exists.
"""
cdef string _content = content
self.c_creator.addIllustration(size, _content)
# def set_uuid(self, uuid) -> _Creator:
# self.c_creator.setUuid(uuid)
def add_item(self, writer_item not None: BaseWritingItem):
"""Add an item to the Creator object.
Args:
item (WriterItem): The item to add to the archive.
Raises:
RuntimeError: If an item with the same path already exists.
RuntimeError: If the ZimCreator has already been finalized.
"""
if not self._started:
raise RuntimeError("Creator not started")
# Make a shared pointer to ZimArticleWrapper from the ZimArticle object
cdef shared_ptr[zim.WriterItem] item = shared_ptr[zim.WriterItem](
new zim.WriterItemWrapper(<PyObject*>writer_item));
with nogil:
self.c_creator.addItem(item)
def add_metadata(self, str name: str, bytes content: bytes, str mimetype: str):
"""Adds a metadata entry to the archive.
Refer to https://wiki.openzim.org/wiki/Metadata for more details.
Args:
name (str): The name of the metadata entry.
content (bytes): The binary content of the metadata entry.
mimetype (str): The MIME type of the metadata entry.
Raises:
RuntimeError: If a metadata entry with the same name already exists.
"""
if not self._started:
raise RuntimeError("Creator not started")
cdef string _name = name.encode('UTF-8')
cdef string _content = content
cdef string _mimetype = mimetype.encode('UTF-8')
with nogil:
self.c_creator.addMetadata(_name, _content, _mimetype)
def add_redirection(self, str path: str, str title: str, str targetPath: str, dict hints: Dict[Hint, pyint]):
"""Add redirection entry to the archive.
Refer to https://wiki.openzim.org/wiki/ZIM_file_format#Redirect_Entry for more details.
Args:
path (str): The path of the redirection entry.
title (str): The title associated with the redirection.
targetPath (str): The target path for the redirection.
hints (dict[Hint, int]): A dictionary of hints for the redirection.
Raises:
RuntimeError: If a redirection entry exists with the same path.
"""
if not self._started:
raise RuntimeError("Creator not started")
cdef string _path = path.encode('UTF-8')
cdef string _title = title.encode('UTF-8')
cdef string _targetPath = targetPath.encode('UTF-8')
cdef map[zim.HintKeys, uint64_t] _hints = convertToCppHints(hints)
with nogil:
self.c_creator.addRedirection(_path, _title, _targetPath, _hints)
def add_alias(self, str path: str, str title: str, str targetPath: str, dict hints: Dict[Hint, pyint]):
"""Alias the (existing) entry `targetPath` as a new entry `path`.
Args:
path (str): The path for the new alias.
title (str): The title associated with the alias.
targetPath (str): The existing entry to be aliased.
hints (dict[Hint, int]): A dictionary of hints for the alias.
Raises:
RuntimeError: If the `targetPath` entry doesn't exist.
"""
if not self._started:
raise RuntimeError("Creator not started")
cdef string _path = path.encode('UTF-8')
cdef string _title = title.encode('UTF-8')
cdef string _targetPath = targetPath.encode('UTF-8')
cdef map[zim.HintKeys, uint64_t] _hints = convertToCppHints(hints)
with nogil:
self.c_creator.addAlias(_path, _title, _targetPath, _hints)
def __enter__(self):
cdef string _path = str(self._filename).encode('UTF-8')
with nogil:
self.c_creator.startZimCreation(_path)
self._started = True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if True or exc_type is None:
with nogil:
self.c_creator.finishZimCreation()
self._started = False
@property
def filename(self) -> pathlib.Path:
"""Path of the ZIM Archive on the filesystem.
Returns:
(pathlib.Path): Path of the ZIM Archive on the filesystem.
"""
return self._filename
class StringProvider(ContentProvider):
"""ContentProvider for a single encoded-or-not UTF-8 string."""
__module__ = writer_module_name
def __init__(self, content: Union[str, bytes]):
super().__init__()
self.content = content.encode("UTF-8") if isinstance(content, str) else content
def get_size(self) -> pyint:
return len(self.content)
def gen_blob(self) -> Generator[WritingBlob, None, None]:
yield WritingBlob(self.content)
class FileProvider(ContentProvider):
"""ContentProvider for a file using its local path."""
__module__ = writer_module_name
def __init__(self, filepath: Union[pathlib.Path, str]):
super().__init__()
self.filepath = filepath
self.size = os.path.getsize(self.filepath)
def get_size(self) -> pyint:
return self.size
def gen_blob(self) -> Generator[WritingBlob, None, None]:
bsize = 1048576 # 1MiB chunk
with open(self.filepath, "rb") as fh:
res = fh.read(bsize)
while res:
yield WritingBlob(res)
res = fh.read(bsize)
class IndexData:
"""IndexData stub to override.
A subclass of it should be returned in `Item.get_indexdata()`.
"""
__module__ = writer_module_name
def has_indexdata(self) -> bool:
"""Whether the IndexData contains any data.
Returns:
True if the IndexData contains data, otherwise False.
"""
return False
def get_title(self) -> str:
"""Get the title to use when indexing an Item.
Might be the same as Item's title or not.
Returns:
str: The title to use.
"""
raise NotImplementedError("get_title must be implemented.")
def get_content(self) -> str:
"""Get the content to use when indexing an Item.
Might be the same as Item's content or not.
Returns:
str: The content to use.
"""
raise NotImplementedError("get_content must be implemented.")
def get_keywords(self) -> str:
"""Get the keywords used to index the item.
Returns:
Space-separated string containing keywords to index for.
"""
raise NotImplementedError("get_keywords must be implemented.")
def get_wordcount(self) -> int:
"""Get the number of word in content.
Returns:
Number of words in the item's content.
"""
raise NotImplementedError("get_wordcount must be implemented.")
def get_geoposition(self) -> Optional[Tuple[float, float]]:
"""GeoPosition used to index the item.
Returns:
A (latitude, longitude) tuple or None.
"""
return None
class Creator(_Creator):
"""Creator to create ZIM files."""
__module__ = writer_module_name
def config_compression(self, compression: Union[Compression, str]):
if not isinstance(compression, Compression):
compression = getattr(Compression, compression.lower())
return super().config_compression(compression)
def add_metadata(
self, name: str, content: Union[str, bytes, datetime.date, datetime.datetime],
mimetype: str = "text/plain;charset=UTF-8"
):
if name == "Date" and isinstance(content, (datetime.date, datetime.datetime)):
content = content.strftime("%Y-%m-%d").encode("UTF-8")
if isinstance(content, str):
content = content.encode("UTF-8")
super().add_metadata(name=name, content=content, mimetype=mimetype)
def __repr__(self) -> str:
return f"Creator(filename={self.filename})"
writer_module_doc = """libzim writer module
- Creator to create ZIM files
- Item to store ZIM articles metadata
- ContentProvider to store an Item's content
- Blob to store actual content
- StringProvider to store an Item's content from a string
- FileProvider to store an Item's content from a file path
- Compression to select the algorithm to compress ZIM archive with
Usage:
```python
with Creator(pathlib.Path("myfile.zim")) as creator:
creator.config_verbose(False)
creator.add_metadata("Name", b"my name")
# example
creator.add_item(MyItemSubclass(path, title, mimetype, content)
creator.set_mainpath(path)
```"""
writer_public_objects = [
Creator,
Compression,
('Blob', WritingBlob),
Hint,
('Item', BaseWritingItem),
ContentProvider,
FileProvider,
StringProvider,
IndexData
]
writer = create_module(writer_module_name, writer_module_doc, writer_public_objects)
###############################################################################
# Reader module #
###############################################################################
reader_module_name = f"{__name__}.reader"
cdef Py_ssize_t itemsize = 1
cdef class ReadingBlob:
__module__ = reader_module_name
cdef zim.Blob c_blob
cdef Py_ssize_t size
cdef int view_count
# Factory functions - Currently Cython can't use classmethods
@staticmethod
cdef from_blob(zim.Blob blob):
"""Creates a python Blob from a C++ Blob (zim::) -> Blob
Parameters
----------
blob : Blob
A C++ Entry
Returns
------
Blob
Casted blob"""
cdef ReadingBlob rblob = ReadingBlob()
rblob.c_blob = move(blob)
rblob.size = rblob.c_blob.size()
rblob.view_count = 0
return rblob
def __dealloc__(self):
if self.view_count:
raise RuntimeError("Blob has views")
def __getbuffer__(self, Py_buffer *buffer, int flags):
if flags&PyBUF_WRITABLE:
raise BufferError("Cannot create writable memoryview on readonly data")
buffer.obj = self
buffer.buf = <void*>self.c_blob.data()
buffer.len = self.size
buffer.readonly = 1
buffer.format = 'c'
buffer.internal = NULL # see References
buffer.itemsize = itemsize
buffer.ndim = 1
buffer.shape = &self.size
buffer.strides = &itemsize
buffer.suboffsets = NULL # for pointer arrays only
self.view_count += 1
def __releasebuffer__(self, Py_buffer *buffer):
self.view_count -= 1
cdef class Entry:
"""Entry in a ZIM archive.
Attributes:
*c_entry (zim.Entry): a pointer to the C++ entry object.
"""
__module__ = reader_module_name
cdef zim.Entry c_entry
# Factory functions - Currently Cython can't use classmethods
@staticmethod
cdef from_entry(zim.Entry ent):
"""Creates a python Entry from a C++ Entry (zim::).
Args:
ent (Entry): A C++ Entry
Returns:
Entry: Casted entry
"""
cdef Entry entry = Entry()
entry.c_entry = move(ent)
return entry
@property
def title(self) -> str:
"""The UTF-8 decoded title of the entry.
Returns:
(str): The UTF-8 decoded title of the entry.
"""
return self.c_entry.getTitle().decode('UTF-8')
@property
def path(self) -> str:
"""The UTF-8 decoded path of the entry.
Returns:
(str): The UTF-8 decoded path of the entry.
"""
return self.c_entry.getPath().decode("UTF-8", "strict")
@property
def _index(self) -> pyint:
"""Internal index in Archive.
Returns:
(int): Internal index in Archive.
"""
return self.c_entry.getIndex()
@property
def is_redirect(self) -> pybool:
"""Whether entry is a redirect.
Returns:
(bool): Whether entry is a redirect.
"""
return self.c_entry.isRedirect()
def get_redirect_entry(self) -> Entry:
"""Get the target entry if this entry is a redirect.
Returns:
The target entry of the redirect.
"""
cdef zim.Entry entry = move(self.c_entry.getRedirectEntry())
return Entry.from_entry(move(entry))
def get_item(self) -> Item:
"""Get the `Item` associated with this entry.
Returns:
The item associated with this entry.
"""
cdef zim.Item item = move(self.c_entry.getItem(True))
return Item.from_item(move(item))
def __repr__(self) -> str:
return f"{self.__class__.__name__}(url={self.path}, title={self.title})"
cdef class Item:
"""Item in a ZIM archive
Attributes:
*c_item (zim.Item): a pointer to the C++ Item object.
"""
__module__ = reader_module_name
cdef zim.Item c_item
cdef ReadingBlob _blob
cdef bool _haveBlob
# Factory functions - Currently Cython can't use classmethods
@staticmethod
cdef from_item(zim.Item _item):
"""Creates a python ReadArticle from a C++ Article (zim::) -> ReadArticle.
Args:
_item (zim.Item): A C++ Item
Returns:
(Item): Casted item"""
cdef Item item = Item()
item.c_item = move(_item)
return item
@property
def title(self) -> str:
"""The UTF-8 decoded title of the item.
Returns:
(str): The UTF-8 decoded title of the item.
"""
return self.c_item.getTitle().decode('UTF-8')
@property
def path(self) -> str:
"""The UTF-8 decoded path of the item.
Returns:
(str): The UTF-8 decoded path of the item.
"""
return self.c_item.getPath().decode("UTF-8", "strict")
@property
def content(self) -> memoryview:
"""The data associated to the item.
Returns:
(memoryview): The data associated to the item.
"""
if not self._haveBlob:
self._blob = ReadingBlob.from_blob(move(self.c_item.getData(<int> 0)))
self._haveBlob = True
return memoryview(self._blob)
@property
def mimetype(self) -> str:
"""The mimetype of the item.
Returns:
(str): The mimetype of the item.
"""
return self.c_item.getMimetype().decode('UTF-8')
@property
def _index(self) -> pyint:
"""Internal index in Archive.
Returns:
(int): Internal index in Archive.
"""
return self.c_item.getIndex()
@property
def size(self) -> pyint:
"""The size (in bytes) of the item.
Returns:
(int): The size (in bytes) of the item.
"""
return self.c_item.getSize()
def __repr__(self) -> str:
return f"{self.__class__.__name__}(url={self.path}, title={self.title})"
cdef class Archive:
"""ZIM Archive Reader
Args:
filename (pathlib.Path): Full path to a zim file.
"""
__module__ = reader_module_name
cdef zim.Archive c_archive
cdef object _filename