/
utils.py
2103 lines (1684 loc) · 65.1 KB
/
utils.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""Various general utility functions."""
from __future__ import with_statement
from contextlib import contextmanager
import collections.abc
import logging
import warnings
import numbers
from html.entities import name2codepoint as n2cp
import pickle as _pickle
import re
import unicodedata
import os
import random
import itertools
import tempfile
from functools import wraps
import multiprocessing
import shutil
import sys
import subprocess
import inspect
import heapq
from copy import deepcopy
from datetime import datetime
import platform
import types
import numpy as np
import scipy.sparse
from smart_open import open
from gensim import __version__ as gensim_version
logger = logging.getLogger(__name__)
# When pickling objects for persistence, use this protocol by default.
# Note that users won't be able to load models saved with high protocols on older environments that do
# not support that protocol (e.g. Python 2).
# In the rare cases where this matters, users can explicitly pass `model.save(pickle_protocol=2)`.
# See also https://github.com/RaRe-Technologies/gensim/pull/3065
PICKLE_PROTOCOL = 4
PAT_ALPHABETIC = re.compile(r'(((?![\d])\w)+)', re.UNICODE)
RE_HTML_ENTITY = re.compile(r'&(#?)([xX]?)(\w{1,8});', re.UNICODE)
NO_CYTHON = RuntimeError(
"Compiled extensions are unavailable. "
"If you've installed from a package, ask the package maintainer to include compiled extensions. "
"If you're building Gensim from source yourself, install Cython and a C compiler, and then "
"run `python setup.py build_ext --inplace` to retry. "
)
"""An exception that gensim code raises when Cython extensions are unavailable."""
#: A default, shared numpy-Generator-based PRNG for any/all uses that don't require seeding
default_prng = np.random.default_rng()
def get_random_state(seed):
"""Generate :class:`numpy.random.RandomState` based on input seed.
Parameters
----------
seed : {None, int, array_like}
Seed for random state.
Returns
-------
:class:`numpy.random.RandomState`
Random state.
Raises
------
AttributeError
If seed is not {None, int, array_like}.
Notes
-----
Method originally from `maciejkula/glove-python <https://github.com/maciejkula/glove-python>`_
and written by `@joshloyal <https://github.com/joshloyal>`_.
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, (numbers.Integral, np.integer)):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a np.random.RandomState instance' % seed)
def synchronous(tlockname):
"""A decorator to place an instance-based lock around a method.
Notes
-----
Adapted from http://code.activestate.com/recipes/577105-synchronization-decorator-for-class-methods/.
"""
def _synched(func):
@wraps(func)
def _synchronizer(self, *args, **kwargs):
tlock = getattr(self, tlockname)
logger.debug("acquiring lock %r for %s", tlockname, func.__name__)
with tlock: # use lock as a context manager to perform safe acquire/release pairs
logger.debug("acquired lock %r for %s", tlockname, func.__name__)
result = func(self, *args, **kwargs)
logger.debug("releasing lock %r for %s", tlockname, func.__name__)
return result
return _synchronizer
return _synched
def file_or_filename(input):
"""Open a filename for reading with `smart_open`, or seek to the beginning if `input` is an already open file.
Parameters
----------
input : str or file-like
Filename or file-like object.
Returns
-------
file-like object
An open file, positioned at the beginning.
"""
if isinstance(input, str):
# input was a filename: open as file
return open(input, 'rb')
else:
# input already a file-like object; just reset to the beginning
input.seek(0)
return input
@contextmanager
def open_file(input):
"""Provide "with-like" behaviour without closing the file object.
Parameters
----------
input : str or file-like
Filename or file-like object.
Yields
-------
file
File-like object based on input (or input if this already file-like).
"""
mgr = file_or_filename(input)
exc = False
try:
yield mgr
except Exception:
# Handling any unhandled exceptions from the code nested in 'with' statement.
exc = True
if not isinstance(input, str) or not mgr.__exit__(*sys.exc_info()):
raise
# Try to introspect and silence errors.
finally:
if not exc and isinstance(input, str):
mgr.__exit__(None, None, None)
def deaccent(text):
"""Remove letter accents from the given string.
Parameters
----------
text : str
Input string.
Returns
-------
str
Unicode string without accents.
Examples
--------
.. sourcecode:: pycon
>>> from gensim.utils import deaccent
>>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek")
u'Sef chomutovskych komunistu dostal postou bily prasek'
"""
if not isinstance(text, str):
# assume utf8 for byte strings, use default (strict) error handling
text = text.decode('utf8')
norm = unicodedata.normalize("NFD", text)
result = ''.join(ch for ch in norm if unicodedata.category(ch) != 'Mn')
return unicodedata.normalize("NFC", result)
def copytree_hardlink(source, dest):
"""Recursively copy a directory ala shutils.copytree, but hardlink files instead of copying.
Parameters
----------
source : str
Path to source directory
dest : str
Path to destination directory
Warnings
--------
Available on UNIX systems only.
"""
copy2 = shutil.copy2
try:
shutil.copy2 = os.link
shutil.copytree(source, dest)
finally:
shutil.copy2 = copy2
def tokenize(text, lowercase=False, deacc=False, encoding='utf8', errors="strict", to_lower=False, lower=False):
"""Iteratively yield tokens as unicode strings, optionally removing accent marks and lowercasing it.
Parameters
----------
text : str or bytes
Input string.
deacc : bool, optional
Remove accentuation using :func:`~gensim.utils.deaccent`?
encoding : str, optional
Encoding of input string, used as parameter for :func:`~gensim.utils.to_unicode`.
errors : str, optional
Error handling behaviour, used as parameter for :func:`~gensim.utils.to_unicode`.
lowercase : bool, optional
Lowercase the input string?
to_lower : bool, optional
Same as `lowercase`. Convenience alias.
lower : bool, optional
Same as `lowercase`. Convenience alias.
Yields
------
str
Contiguous sequences of alphabetic characters (no digits!), using :func:`~gensim.utils.simple_tokenize`
Examples
--------
.. sourcecode:: pycon
>>> from gensim.utils import tokenize
>>> list(tokenize('Nic nemůže letět rychlostí vyšší, než 300 tisíc kilometrů za sekundu!', deacc=True))
[u'Nic', u'nemuze', u'letet', u'rychlosti', u'vyssi', u'nez', u'tisic', u'kilometru', u'za', u'sekundu']
"""
lowercase = lowercase or to_lower or lower
text = to_unicode(text, encoding, errors=errors)
if lowercase:
text = text.lower()
if deacc:
text = deaccent(text)
return simple_tokenize(text)
def simple_tokenize(text):
"""Tokenize input test using :const:`gensim.utils.PAT_ALPHABETIC`.
Parameters
----------
text : str
Input text.
Yields
------
str
Tokens from `text`.
"""
for match in PAT_ALPHABETIC.finditer(text):
yield match.group()
def simple_preprocess(doc, deacc=False, min_len=2, max_len=15):
"""Convert a document into a list of lowercase tokens, ignoring tokens that are too short or too long.
Uses :func:`~gensim.utils.tokenize` internally.
Parameters
----------
doc : str
Input document.
deacc : bool, optional
Remove accent marks from tokens using :func:`~gensim.utils.deaccent`?
min_len : int, optional
Minimum length of token (inclusive). Shorter tokens are discarded.
max_len : int, optional
Maximum length of token in result (inclusive). Longer tokens are discarded.
Returns
-------
list of str
Tokens extracted from `doc`.
"""
tokens = [
token for token in tokenize(doc, lower=True, deacc=deacc, errors='ignore')
if min_len <= len(token) <= max_len and not token.startswith('_')
]
return tokens
def any2utf8(text, errors='strict', encoding='utf8'):
"""Convert a unicode or bytes string in the given encoding into a utf8 bytestring.
Parameters
----------
text : str
Input text.
errors : str, optional
Error handling behaviour if `text` is a bytestring.
encoding : str, optional
Encoding of `text` if it is a bytestring.
Returns
-------
str
Bytestring in utf8.
"""
if isinstance(text, str):
return text.encode('utf8')
# do bytestring -> unicode -> utf8 full circle, to ensure valid utf8
return str(text, encoding, errors=errors).encode('utf8')
to_utf8 = any2utf8
def any2unicode(text, encoding='utf8', errors='strict'):
"""Convert `text` (bytestring in given encoding or unicode) to unicode.
Parameters
----------
text : str
Input text.
errors : str, optional
Error handling behaviour if `text` is a bytestring.
encoding : str, optional
Encoding of `text` if it is a bytestring.
Returns
-------
str
Unicode version of `text`.
"""
if isinstance(text, str):
return text
return str(text, encoding, errors=errors)
to_unicode = any2unicode
def call_on_class_only(*args, **kwargs):
"""Helper to raise `AttributeError` if a class method is called on an instance. Used internally.
Parameters
----------
*args
Variable length argument list.
**kwargs
Arbitrary keyword arguments.
Raises
------
AttributeError
If a class method is called on an instance.
"""
raise AttributeError('This method should be called on a class object.')
class SaveLoad:
"""Serialize/deserialize objects from disk, by equipping them with the `save()` / `load()` methods.
Warnings
--------
This uses pickle internally (among other techniques), so objects must not contain unpicklable attributes
such as lambda functions etc.
"""
def add_lifecycle_event(self, event_name, log_level=logging.INFO, **event):
"""
Append an event into the `lifecycle_events` attribute of this object, and also
optionally log the event at `log_level`.
Events are important moments during the object's life, such as "model created",
"model saved", "model loaded", etc.
The `lifecycle_events` attribute is persisted across object's :meth:`~gensim.utils.SaveLoad.save`
and :meth:`~gensim.utils.SaveLoad.load` operations. It has no impact on the use of the model,
but is useful during debugging and support.
Set `self.lifecycle_events = None` to disable this behaviour. Calls to `add_lifecycle_event()`
will not record events into `self.lifecycle_events` then.
Parameters
----------
event_name : str
Name of the event. Can be any label, e.g. "created", "stored" etc.
event : dict
Key-value mapping to append to `self.lifecycle_events`. Should be JSON-serializable, so keep it simple.
Can be empty.
This method will automatically add the following key-values to `event`, so you don't have to specify them:
- `datetime`: the current date & time
- `gensim`: the current Gensim version
- `python`: the current Python version
- `platform`: the current platform
- `event`: the name of this event
log_level : int
Also log the complete event dict, at the specified log level. Set to False to not log at all.
"""
# See also https://github.com/RaRe-Technologies/gensim/issues/2863
event_dict = deepcopy(event)
event_dict['datetime'] = datetime.now().isoformat()
event_dict['gensim'] = gensim_version
event_dict['python'] = sys.version
event_dict['platform'] = platform.platform()
event_dict['event'] = event_name
if not hasattr(self, 'lifecycle_events'):
# Avoid calling str(self), the object may not be fully initialized yet at this point.
logger.debug("starting a new internal lifecycle event log for %s", self.__class__.__name__)
self.lifecycle_events = []
if log_level:
logger.log(log_level, "%s lifecycle event %s", self.__class__.__name__, event_dict)
if self.lifecycle_events is not None:
self.lifecycle_events.append(event_dict)
@classmethod
def load(cls, fname, mmap=None):
"""Load an object previously saved using :meth:`~gensim.utils.SaveLoad.save` from a file.
Parameters
----------
fname : str
Path to file that contains needed object.
mmap : str, optional
Memory-map option. If the object was saved with large arrays stored separately, you can load these arrays
via mmap (shared memory) using `mmap='r'.
If the file being loaded is compressed (either '.gz' or '.bz2'), then `mmap=None` **must be** set.
See Also
--------
:meth:`~gensim.utils.SaveLoad.save`
Save object to file.
Returns
-------
object
Object loaded from `fname`.
Raises
------
AttributeError
When called on an object instance instead of class (this is a class method).
"""
logger.info("loading %s object from %s", cls.__name__, fname)
compress, subname = SaveLoad._adapt_by_suffix(fname)
obj = unpickle(fname)
obj._load_specials(fname, mmap, compress, subname)
obj.add_lifecycle_event("loaded", fname=fname)
return obj
def _load_specials(self, fname, mmap, compress, subname):
"""Load attributes that were stored separately, and give them the same opportunity
to recursively load using the :class:`~gensim.utils.SaveLoad` interface.
Parameters
----------
fname : str
Input file path.
mmap : {None, ‘r+’, ‘r’, ‘w+’, ‘c’}
Memory-map options. See `numpy.load(mmap_mode)
<https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.load.html>`_.
compress : bool
Is the input file compressed?
subname : str
Attribute name. Set automatically during recursive processing.
"""
def mmap_error(obj, filename):
return IOError(
'Cannot mmap compressed object %s in file %s. ' % (obj, filename)
+ 'Use `load(fname, mmap=None)` or uncompress files manually.'
)
for attrib in getattr(self, '__recursive_saveloads', []):
cfname = '.'.join((fname, attrib))
logger.info("loading %s recursively from %s.* with mmap=%s", attrib, cfname, mmap)
with ignore_deprecation_warning():
getattr(self, attrib)._load_specials(cfname, mmap, compress, subname)
for attrib in getattr(self, '__numpys', []):
logger.info("loading %s from %s with mmap=%s", attrib, subname(fname, attrib), mmap)
if compress:
if mmap:
raise mmap_error(attrib, subname(fname, attrib))
val = np.load(subname(fname, attrib))['val']
else:
val = np.load(subname(fname, attrib), mmap_mode=mmap)
with ignore_deprecation_warning():
setattr(self, attrib, val)
for attrib in getattr(self, '__scipys', []):
logger.info("loading %s from %s with mmap=%s", attrib, subname(fname, attrib), mmap)
sparse = unpickle(subname(fname, attrib))
if compress:
if mmap:
raise mmap_error(attrib, subname(fname, attrib))
with np.load(subname(fname, attrib, 'sparse')) as f:
sparse.data = f['data']
sparse.indptr = f['indptr']
sparse.indices = f['indices']
else:
sparse.data = np.load(subname(fname, attrib, 'data'), mmap_mode=mmap)
sparse.indptr = np.load(subname(fname, attrib, 'indptr'), mmap_mode=mmap)
sparse.indices = np.load(subname(fname, attrib, 'indices'), mmap_mode=mmap)
with ignore_deprecation_warning():
setattr(self, attrib, sparse)
for attrib in getattr(self, '__ignoreds', []):
logger.info("setting ignored attribute %s to None", attrib)
with ignore_deprecation_warning():
setattr(self, attrib, None)
@staticmethod
def _adapt_by_suffix(fname):
"""Get compress setting and filename for numpy file compression.
Parameters
----------
fname : str
Input filename.
Returns
-------
(bool, function)
First argument will be True if `fname` compressed.
"""
compress, suffix = (True, 'npz') if fname.endswith('.gz') or fname.endswith('.bz2') else (False, 'npy')
return compress, lambda *args: '.'.join(args + (suffix,))
def _smart_save(
self, fname,
separately=None, sep_limit=10 * 1024**2, ignore=frozenset(), pickle_protocol=PICKLE_PROTOCOL,
):
"""Save the object to a file. Used internally by :meth:`gensim.utils.SaveLoad.save()`.
Parameters
----------
fname : str
Path to file.
separately : list, optional
Iterable of attributes than need to store distinctly.
sep_limit : int, optional
Limit for separation.
ignore : frozenset, optional
Attributes that shouldn't be store.
pickle_protocol : int, optional
Protocol number for pickle.
Notes
-----
If `separately` is None, automatically detect large numpy/scipy.sparse arrays in the object being stored,
and store them into separate files. This avoids pickle memory errors and allows mmap'ing large arrays back
on load efficiently.
You can also set `separately` manually, in which case it must be a list of attribute names to be stored
in separate files. The automatic check is not performed in this case.
"""
compress, subname = SaveLoad._adapt_by_suffix(fname)
restores = self._save_specials(
fname, separately, sep_limit, ignore, pickle_protocol, compress, subname,
)
try:
pickle(self, fname, protocol=pickle_protocol)
finally:
# restore attribs handled specially
for obj, asides in restores:
for attrib, val in asides.items():
with ignore_deprecation_warning():
setattr(obj, attrib, val)
logger.info("saved %s", fname)
def _save_specials(self, fname, separately, sep_limit, ignore, pickle_protocol, compress, subname):
"""Save aside any attributes that need to be handled separately, including
by recursion any attributes that are themselves :class:`~gensim.utils.SaveLoad` instances.
Parameters
----------
fname : str
Output filename.
separately : list or None
List of attributes to store separately.
sep_limit : int
Don't store arrays smaller than this separately. In bytes.
ignore : iterable of str
Attributes that shouldn't be stored at all.
pickle_protocol : int
Protocol number for pickle.
compress : bool
If True - compress output with :func:`numpy.savez_compressed`.
subname : function
Produced by :meth:`~gensim.utils.SaveLoad._adapt_by_suffix`
Returns
-------
list of (obj, {attrib: value, ...})
Settings that the caller should use to restore each object's attributes that were set aside
during the default :func:`~gensim.utils.pickle`.
"""
asides = {}
sparse_matrices = (scipy.sparse.csr_matrix, scipy.sparse.csc_matrix)
if separately is None:
separately = []
for attrib, val in self.__dict__.items():
if isinstance(val, np.ndarray) and val.size >= sep_limit:
separately.append(attrib)
elif isinstance(val, sparse_matrices) and val.nnz >= sep_limit:
separately.append(attrib)
with ignore_deprecation_warning():
# whatever's in `separately` or `ignore` at this point won't get pickled
for attrib in separately + list(ignore):
if hasattr(self, attrib):
asides[attrib] = getattr(self, attrib)
delattr(self, attrib)
recursive_saveloads = []
restores = []
for attrib, val in self.__dict__.items():
if hasattr(val, '_save_specials'): # better than 'isinstance(val, SaveLoad)' if IPython reloading
recursive_saveloads.append(attrib)
cfname = '.'.join((fname, attrib))
restores.extend(val._save_specials(cfname, None, sep_limit, ignore, pickle_protocol, compress, subname))
try:
numpys, scipys, ignoreds = [], [], []
for attrib, val in asides.items():
if isinstance(val, np.ndarray) and attrib not in ignore:
numpys.append(attrib)
logger.info("storing np array '%s' to %s", attrib, subname(fname, attrib))
if compress:
np.savez_compressed(subname(fname, attrib), val=np.ascontiguousarray(val))
else:
np.save(subname(fname, attrib), np.ascontiguousarray(val))
elif isinstance(val, (scipy.sparse.csr_matrix, scipy.sparse.csc_matrix)) and attrib not in ignore:
scipys.append(attrib)
logger.info("storing scipy.sparse array '%s' under %s", attrib, subname(fname, attrib))
if compress:
np.savez_compressed(
subname(fname, attrib, 'sparse'),
data=val.data,
indptr=val.indptr,
indices=val.indices
)
else:
np.save(subname(fname, attrib, 'data'), val.data)
np.save(subname(fname, attrib, 'indptr'), val.indptr)
np.save(subname(fname, attrib, 'indices'), val.indices)
data, indptr, indices = val.data, val.indptr, val.indices
val.data, val.indptr, val.indices = None, None, None
try:
# store array-less object
pickle(val, subname(fname, attrib), protocol=pickle_protocol)
finally:
val.data, val.indptr, val.indices = data, indptr, indices
else:
logger.info("not storing attribute %s", attrib)
ignoreds.append(attrib)
self.__dict__['__numpys'] = numpys
self.__dict__['__scipys'] = scipys
self.__dict__['__ignoreds'] = ignoreds
self.__dict__['__recursive_saveloads'] = recursive_saveloads
except Exception:
# restore the attributes if exception-interrupted
for attrib, val in asides.items():
setattr(self, attrib, val)
raise
return restores + [(self, asides)]
def save(
self, fname_or_handle,
separately=None, sep_limit=10 * 1024**2, ignore=frozenset(), pickle_protocol=PICKLE_PROTOCOL,
):
"""Save the object to a file.
Parameters
----------
fname_or_handle : str or file-like
Path to output file or already opened file-like object. If the object is a file handle,
no special array handling will be performed, all attributes will be saved to the same file.
separately : list of str or None, optional
If None, automatically detect large numpy/scipy.sparse arrays in the object being stored, and store
them into separate files. This prevent memory errors for large objects, and also allows
`memory-mapping <https://en.wikipedia.org/wiki/Mmap>`_ the large arrays for efficient
loading and sharing the large arrays in RAM between multiple processes.
If list of str: store these attributes into separate files. The automated size check
is not performed in this case.
sep_limit : int, optional
Don't store arrays smaller than this separately. In bytes.
ignore : frozenset of str, optional
Attributes that shouldn't be stored at all.
pickle_protocol : int, optional
Protocol number for pickle.
See Also
--------
:meth:`~gensim.utils.SaveLoad.load`
Load object from file.
"""
self.add_lifecycle_event(
"saving",
fname_or_handle=str(fname_or_handle),
separately=str(separately),
sep_limit=sep_limit,
ignore=ignore,
)
try:
_pickle.dump(self, fname_or_handle, protocol=pickle_protocol)
logger.info("saved %s object", self.__class__.__name__)
except TypeError: # `fname_or_handle` does not have write attribute
self._smart_save(fname_or_handle, separately, sep_limit, ignore, pickle_protocol=pickle_protocol)
def identity(p):
"""Identity fnc, for flows that don't accept lambda (pickling etc).
Parameters
----------
p : object
Input parameter.
Returns
-------
object
Same as `p`.
"""
return p
def get_max_id(corpus):
"""Get the highest feature id that appears in the corpus.
Parameters
----------
corpus : iterable of iterable of (int, numeric)
Collection of texts in BoW format.
Returns
------
int
Highest feature id.
Notes
-----
For empty `corpus` return -1.
"""
maxid = -1
for document in corpus:
if document:
maxid = max(maxid, max(fieldid for fieldid, _ in document))
return maxid
class FakeDict:
"""Objects of this class act as dictionaries that map integer->str(integer), for a specified
range of integers <0, num_terms).
This is meant to avoid allocating real dictionaries when `num_terms` is huge, which is a waste of memory.
"""
def __init__(self, num_terms):
"""
Parameters
----------
num_terms : int
Number of terms.
"""
self.num_terms = num_terms
def __str__(self):
return "%s<num_terms=%s>" % (self.__class__.__name__, self.num_terms)
def __getitem__(self, val):
if 0 <= val < self.num_terms:
return str(val)
raise ValueError("internal id out of bounds (%s, expected <0..%s))" % (val, self.num_terms))
def __contains__(self, val):
return 0 <= val < self.num_terms
def iteritems(self):
"""Iterate over all keys and values.
Yields
------
(int, str)
Pair of (id, token).
"""
for i in range(self.num_terms):
yield i, str(i)
def keys(self):
"""Override the `dict.keys()`, which is used to determine the maximum internal id of a corpus,
i.e. the vocabulary dimensionality.
Returns
-------
list of int
Highest id, packed in list.
Notes
-----
To avoid materializing the whole `range(0, self.num_terms)`,
this returns the highest id = `[self.num_terms - 1]` only.
"""
return [self.num_terms - 1]
def __len__(self):
return self.num_terms
def get(self, val, default=None):
if 0 <= val < self.num_terms:
return str(val)
return default
def dict_from_corpus(corpus):
"""Scan corpus for all word ids that appear in it, then construct a mapping
which maps each `word_id` -> `str(word_id)`.
Parameters
----------
corpus : iterable of iterable of (int, numeric)
Collection of texts in BoW format.
Returns
------
id2word : :class:`~gensim.utils.FakeDict`
"Fake" mapping which maps each `word_id` -> `str(word_id)`.
Warnings
--------
This function is used whenever *words* need to be displayed (as opposed to just their ids)
but no `word_id` -> `word` mapping was provided. The resulting mapping only covers words actually
used in the corpus, up to the highest `word_id` found.
"""
num_terms = 1 + get_max_id(corpus)
id2word = FakeDict(num_terms)
return id2word
def is_corpus(obj):
"""Check whether `obj` is a corpus, by peeking at its first element. Works even on streamed generators.
The peeked element is put back into a object returned by this function, so always use
that returned object instead of the original `obj`.
Parameters
----------
obj : object
An `iterable of iterable` that contains (int, numeric).
Returns
-------
(bool, object)
Pair of (is `obj` a corpus, `obj` with peeked element restored)
Examples
--------
.. sourcecode:: pycon
>>> from gensim.utils import is_corpus
>>> corpus = [[(1, 1.0)], [(2, -0.3), (3, 0.12)]]
>>> corpus_or_not, corpus = is_corpus(corpus)
Warnings
--------
An "empty" corpus (empty input sequence) is ambiguous, so in this case
the result is forcefully defined as (False, `obj`).
"""
try:
if 'Corpus' in obj.__class__.__name__: # the most common case, quick hack
return True, obj
except Exception:
pass
try:
if hasattr(obj, 'next') or hasattr(obj, '__next__'):
# the input is an iterator object, meaning once we call next()
# that element could be gone forever. we must be careful to put
# whatever we retrieve back again
doc1 = next(obj)
obj = itertools.chain([doc1], obj)
else:
doc1 = next(iter(obj)) # empty corpus is resolved to False here
if len(doc1) == 0: # sparse documents must have a __len__ function (list, tuple...)
return True, obj # the first document is empty=>assume this is a corpus
# if obj is a 1D numpy array(scalars) instead of 2-tuples, it resolves to False here
id1, val1 = next(iter(doc1))
id1, val1 = int(id1), float(val1) # must be a 2-tuple (integer, float)
except Exception:
return False, obj
return True, obj
def get_my_ip():
"""Try to obtain our external ip (from the Pyro4 nameserver's point of view)
Returns
-------
str
IP address.
Warnings
--------
This tries to sidestep the issue of bogus `/etc/hosts` entries and other local misconfiguration,
which often mess up hostname resolution.
If all else fails, fall back to simple `socket.gethostbyname()` lookup.
"""
import socket
try:
from Pyro4.naming import locateNS
# we know the nameserver must exist, so use it as our anchor point
ns = locateNS()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ns._pyroUri.host, ns._pyroUri.port))
result, port = s.getsockname()
except Exception:
try:
# see what ifconfig says about our default interface
import commands
result = commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]
if len(result.split('.')) != 4:
raise Exception()
except Exception:
# give up, leave the resolution to gethostbyname
result = socket.gethostbyname(socket.gethostname())
return result
class RepeatCorpus(SaveLoad):
"""Wrap a `corpus` as another corpus of length `reps`. This is achieved by repeating documents from `corpus`
over and over again, until the requested length `len(result) == reps` is reached.
Repetition is done on-the-fly=efficiently, via `itertools`.
Examples