JL i dZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z ddl m Zddl mZddlmZmZddlmZmZ ddlmZdd lmZmZdd lmZej@ejBd Z"gZ# ejHjKddjMejNZ(e#e(Dcgc]}|s| c}z Z#dejHvrHejFjSddk7r*e#jUejFjSdejVjYdre#ejFj[ej\dejFj[ej\ddejFj[ej\ddejFj[ejHjKddddddgz Z#nze#ejFj[ej\dejFj[ej\ddejFj[ej\ddddddgz Z# dYd Z/d!Z0d"Z1dZd#Z2Gd$d%e &Z3Gd'd(e3e4Z5ed)Gd*d+eZ6Gd,d-e5Z7Gd.d/e3Z8iZ9 d[d0Z:d\d1Z;d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdGdH Z=dIZ>d]dJZ?d^dKZ@dLZAdMZB d_dNZCd`dOZDdPZEdQZFGdRdSZGGdTdUejZIGdVdWZJgdXZKy#e$r dd lmZYwxYwcc}w)aa Functions to find and load NLTK resource files, such as corpora, grammars, and saved processing objects. Resource files are identified using URLs, such as ``nltk:corpora/abc/rural.txt`` or ``https://raw.githubusercontent.com/nltk/nltk/develop/nltk/test/toy.cfg``. The following URL protocols are supported: - ``file:path``: Specifies the file whose path is *path*. Both relative and absolute paths may be used. - ``https://host/path``: Specifies the file stored on the web server *host* at path *path*. - ``nltk:path``: Specifies the file stored in the NLTK data package at *path*. NLTK will search for these files in the directories specified by ``nltk.data.path``. If no protocol is specified, then the default protocol ``nltk:`` will be used. This module provides to functions that can be used to access a resource file, given its URL: ``load()`` loads a given resource, and adds it to a resource cache; and ``retrieve()`` copies a given resource to a local file. N)ABCMetaabstractmethod)WRITE)GzipFile)BytesIO TextIOWrapper) url2pathnameurlopen) Z_SYNC_FLUSH)Z_FINISH)grammarsem) deprecatedz )prefix NLTK_DATAAPPENGINE_RUNTIMEz~/z ~/nltk_datawin nltk_datasharelibAPPDATAzC:\z C:\nltk_dataz D:\nltk_dataz E:\nltk_dataz/usr/share/nltk_dataz/usr/local/share/nltk_dataz/usr/lib/nltk_dataz/usr/local/lib/nltk_datac>|t||||}t||||SN)rr)filenamemode compresslevelencodingfileobjerrorsnewlines O/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/data.pygzip_open_unicoder#is*8T='B (FG <<c|jdd\}}|dk(r ||fS|dk(r)|jdrd|jdz}||fStjdd|}||fS)a Splits a resource url into ":". >>> windows = sys.platform.startswith('win') >>> split_resource_url('nltk:home/nltk') ('nltk', 'home/nltk') >>> split_resource_url('nltk:/home/nltk') ('nltk', '/home/nltk') >>> split_resource_url('file:/home/nltk') ('file', '/home/nltk') >>> split_resource_url('file:///home/nltk') ('file', '/home/nltk') >>> split_resource_url('file:///C:/home/nltk') ('file', '/C:/home/nltk') :nltkfile/z^/{0,2}r)split startswithlstripresub resource_urlprotocolpath_s r"split_resource_urlr4ws #((a0OHe6 U? V    C %,,s++E U?z2u- U?r$c0 t|\}}|dk(r/tjj |rd}t |dd}n.|dk(rd}t |dd}n|dk(rd}t |d}n|dz }d j ||gS#t$rd}|}YwxYw) a Normalizes a resource url >>> windows = sys.platform.startswith('win') >>> os.path.normpath(split_resource_url(normalize_resource_url('file:grammar.fcfg'))[1]) == \ ... ('\\' if windows else '') + os.path.abspath(os.path.join(os.curdir, 'grammar.fcfg')) True >>> not windows or normalize_resource_url('file:C:/dir/file') == 'file:///C:/dir/file' True >>> not windows or normalize_resource_url('file:C:\\dir\\file') == 'file:///C:/dir/file' True >>> not windows or normalize_resource_url('file:C:\\dir/file') == 'file:///C:/dir/file' True >>> not windows or normalize_resource_url('file://C:/dir/file') == 'file:///C:/dir/file' True >>> not windows or normalize_resource_url('file:////C:/dir/file') == 'file:///C:/dir/file' True >>> not windows or normalize_resource_url('nltk:C:/dir/file') == 'file:///C:/dir/file' True >>> not windows or normalize_resource_url('nltk:C:\\dir\\file') == 'file:///C:/dir/file' True >>> windows or normalize_resource_url('file:/dir/file/toy.cfg') == 'file:///dir/file/toy.cfg' True >>> normalize_resource_url('nltk:home/nltk') 'nltk:home/nltk' >>> windows or normalize_resource_url('nltk:/home/nltk') == 'file:///home/nltk' True >>> normalize_resource_url('https://example.com/dir/file') 'https://example.com/dir/file' >>> normalize_resource_url('dir/file') 'nltk:dir/file' r(zfile://FNr)znltk:Tz://r)r4 ValueErrorospathisabsnormalize_resource_namejoin)r1r2names r"normalize_resource_urlr=sB+L9$ 6bggmmD1&tUD9 V &tUD9 V &tT2 E 77Hd# $$% sB BBc6ttjd|xs)|jtj j }tjjdr|jd}ntjdd|}|r tj j|}nO|tj}tj jtj j||}|j!ddj!tj j d}tjjdr$tj j#|rd|z}|r|jds|dz }|S)a( :type resource_name: str or unicode :param resource_name: The name of the resource to search for. Resource names are posix-style relative path names, such as ``corpora/brown``. Directory names will automatically be converted to a platform-appropriate path separator. Directory trailing slashes are preserved >>> windows = sys.platform.startswith('win') >>> normalize_resource_name('.', True) './' >>> normalize_resource_name('./', True) './' >>> windows or normalize_resource_name('dir/file', False, '/') == '/dir/file' True >>> not windows or normalize_resource_name('C:/file', False, '/') == '/C:/file' True >>> windows or normalize_resource_name('/dir/file', False, '/') == '/dir/file' True >>> windows or normalize_resource_name('../dir/file', False, '/') == '/dir/file' True >>> not windows or normalize_resource_name('/dir/file', True, '/') == 'dir/file' True >>> windows or normalize_resource_name('/dir/file', True, '/') == '/dir/file' True z[\\/.]$rr*z^/+\)boolr.searchendswithr7r8sepsysplatformr,r-r/normpathcurdirabspathr;replacer9) resource_nameallow_relative relative_pathis_dirs r"r:r:s%6"))J 6 7=;Q;Q  <F ||u%%,,S1 vsM: ((7  IIM ]M(RS !))$4<&ww~~e$9EAB B r$c|jS)z2The absolute path identified by this path pointer.rdrVs r"r8zFileSystemPathPointer.path=szzr$NcNt|jd}| t||}|SNrb)rSrdSeekableUnicodeStreamReaderrRrstreams r"rSzFileSystemPathPointer.openBs)djj$'  0BF r$cTtj|jjSr)r7statrdst_sizerVs r"rWzFileSystemPathPointer.file_sizeHswwtzz"***r$cltjj|j|}t |Sr)r7r8r;rdr`)rRrYrds r"r;zFileSystemPathPointer.joinKs% TZZ0$U++r$c d|jzS)NzFileSystemPathPointer(%r)rhrVs r"__repr__zFileSystemPathPointer.__repr__Os*TZZ77r$c|jSrrhrVs r"__str__zFileSystemPathPointer.__str__Rs zzr$r) rZr[r\r]rfpropertyr8rSrWr;rtrvrQr$r"r`r`(s9  +,8r$r`z3Use gzip.GzipFile instead as it also uses a buffer.c,eZdZdZ ddZfdZxZS)BufferedGzipFilezA ``GzipFile`` subclass for compatibility with older nltk releases. Use ``GzipFile`` directly as it also buffers in all supported Python versions. c 6tj|||||y)z#Return a buffered gzip file object.N)rrf)rRrrrrkwargss r"rfzBufferedGzipFile.__init__^s $$ wGr$c$t||yr)superwrite)rRdata __class__s r"r~zBufferedGzipFile.writeds  dr$)NN N)rZr[r\r]rfr~ __classcell__)rs@r"ryryVsBFH r$ryceZdZdZddZy)GzipFileSystemPathPointerz A subclass of ``FileSystemPathPointer`` that identifies a gzip-compressed file located at a given absolute path. ``GzipFileSystemPathPointer`` is appropriate for loading large gzip-compressed pickle objects efficiently. NcNt|jd}|r t||}|Srj)rrdrlrms r"rSzGzipFileSystemPathPointer.openqs&$**d+ 0BF r$r)rZr[r\r]rSrQr$r"rrjs  r$rcXeZdZdZd dZedZedZd dZdZ dZ d Z d Z y) ZipFilePathPointerz~ A path pointer that identifies a file contained within a zipfile, which can be accessed by reading that zipfile. ct|tr(ttjj |}|r/t |ddjd} |j|||_||_y#t$ro}|jdr8|jDcgc]}|j|s|ncc}wc}rntd|jd||Yd}~d}~wwxYw)z Create a new path pointer pointing at the specified entry in the given zipfile. :raise IOError: If the given zipfile does not exist, or if it does not contain the specified entry. Tr*zZipfile z does not contain N) isinstancestrOpenOnDemandZipFiler7r8rHr:r-getinfo ExceptionrBnamelistr,rcr_zipfile_entry)rRzipfileentryens r"rfzZipFilePathPointer.__init__~s gs #)"''//'*BCG +E4=DDSIE &     >>#&/w//1,Q\\%5HA,,""7#3#3"66H R s*A99 C1$C,&C=C&C,,C1c|jS)z The zipfile.ZipFile object used to access the zip file containing the entry identified by this path pointer. )rrVs r"rzZipFilePathPointer.zipfiles }}r$c|jS)z_ The name of the file within zipfile that this path pointer points to. )rrVs r"rzZipFilePathPointer.entrys {{r$Nc|jj|j}t|}|jj drt |j|}|S| t ||}|S)N.gz)r)rreadrrrBrrl)rRrrrns r"rSzZipFilePathPointer.opense}}!!$++. ;;   &dkk6:F  !0BF r$c`|jj|jjSr)rrrrWrVs r"rWzZipFilePathPointer.file_sizes!}}$$T[[1;;;r$cP|jd|}t|j|S)Nr*)rrr)rRrYrs r"r;zZipFilePathPointer.joins';;-q)!$--77r$cPd|jjd|jdS)NzZipFilePathPointer(z, ))rrrrVs r"rtzZipFilePathPointer.__repr__s&$T]]%;%;$>bqQQr$ctjjtjj|jj |j Sr)r7r8rFr;rrrrVs r"rvzZipFilePathPointer.__str__s4ww T]]-C-CT[[ QRRr$)rr) rZr[r\r]rfrwrrrSrWr;rtrvrQr$r"rrxsP !F<8RSr$rcjt|d}|t}tjd|}|j \}}|D]3}|r?t jj |r |jdr t||cS|r t jj|sg|tt jj|t|}t jj|s|jdr t|cSt|cSt jj|t|}t jj|s' t||cS|\|j!d}t#t%|D]4}dj|d|||dzgz||dz} t'| |cS|j!dd} | jdr| j+dd } t-d j/| } t1| } | d z } | d j/|z } | ddjd|Dzz } d} d| d| d| d} t)| #t$rYQwxYw#t$rYawxYw#t($rYwxYw)a Find the given resource by searching through the directories and zip files in paths, where a None or empty string specifies an absolute path. Returns a corresponding path name. If the given resource is not found, raise a ``LookupError``, whose message gives a pointer to the installation instructions for the NLTK downloader. Zip File Handling: - If ``resource_name`` contains a component with a ``.zip`` extension, then it is assumed to be a zipfile; and the remaining path components are used to look inside the zipfile. - If any element of ``nltk.data.path`` has a ``.zip`` extension, then it is assumed to be a zipfile. - If a given resource name that does not contain any zipfile component is not found initially, then ``find()`` will make a second attempt to find that resource, by replacing each component *p* in the path with *p.zip/p*. For example, this allows ``find()`` to map the resource name ``corpora/chat80/cities.pl`` to a zip file path pointer to ``corpora/chat80.zip/chat80/cities.pl``. - When using ``find()`` to locate a directory contained in a zipfile, the resource name must end with the forward slash character. Otherwise, ``find()`` will not locate the directory. :type resource_name: str or unicode :param resource_name: The name of the resource to search for. Resource names are posix-style relative path names, such as ``corpora/brown``. Directory names will be automatically converted to a platform-appropriate path separator. :rtype: str TNz(.*\.zip)/?(.*)$|z.ziprr*r'.rzResource {resource} not found. Please use the NLTK Downloader to obtain the resource: >>> import nltk >>> nltk.download('{resource}') )resourcez< For more information see: https://www.nltk.org/data.html z. Attempted to load {resource_name} )rJz Searched in:rc3&K|] }d|z yw)z - %rNrQ).0ds r" zfind..@s'HQ q(8'HszF********************************************************************** )r:r8r.matchgroupsr7isfilerBrrcisdirr;r rbrr`r+rangelenfind LookupError rpartitionrformattextwrap_indent)rJpathsmrzipentryr3ppiecesi modified_nameresource_zipnamemsgrCresource_not_founds r"rrsJ,M4@M } %}5A GX! bggnnU+v0F )%?? "''--.GGLL ](CD77>>!$zz%(8;;4Q77GGLL W(=>77>>!$!1!X>>-!<$$S)s6{# AHHVBQZ6!9v3E2F%FPQPR%STM M511 %**3/2  (+66s;A>    f&f' # C KKC B I I# J C 'H%'H H HHC CcU"SEC53 ( ))u  $#! !  s67 J( J J% JJ J"!J"% J21J2c:t|}|K|jdr#tjj |d}nt j dd|}tjj|r-tjj|}td|z|rtd|d|t|}t|d 5} |jd }|j||sn& ddd|jy#1swYxYw) a Copy the given resource to a local file. If no filename is specified, then use the URL's filename. If there is already a file named ``filename``, then raise a ``ValueError``. :type resource_url: str :param resource_url: A URL specifying where the resource should be loaded from. The default protocol is "nltk:", which searches for the file in the the NLTK data package. Nzfile:z (^\w+:)?.*/rzFile %r already exists!z Retrieving z , saving to wbi)r=r,r7r8r+r.r/rbrHr6print_openrSrr~close)r1rverboseinfileoutfiless r"retrieverFs*,7L  " "7 +ww}}\226Hvvnb,?H ww~~h77??8,2X=>> L+<|DE< F h  I&A MM!    LLNs (DDz;A serialized python object, stored using the pickle module.z9A serialized python object, stored using the json module.z9A serialized python object, stored using the yaml module.zA context free grammar.zA probabilistic CFG.zA feature CFG.zZA list of first order logic expressions, parsed with nltk.sem.logic.Expression.fromstring.zA list of first order logic expressions, parsed with nltk.sem.logic.LogicParser. Requires an additional logic_parser parameterz>A semantic valuation, parsed by nltk.sem.Valuation.fromstring.z)The raw (byte string) contents of a file.z-The raw (unicode string) contents of a file. ) picklejsonyamlcfgpcfgfcfgfollogicvalrawtextrrrrrrrrrr) rrrrrrrrrtxtrcLddlm}|t|jS)z6 Prevents any class or function from loading. r)RestrictedUnpickler)nltk.app.wordnet_apprrload)stringrs r"restricted_pickle_loadrs9 wv / 4 4 66r$cddlm}||S)z Return a pickle-free Punkt tokenizer instead of loading a pickle. >>> import nltk >>> tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') >>> print(tokenizer.tokenize("Hello! How are you?")) ['Hello!', 'How are you?'] r)PunktTokenizer) nltk.tokenizer)langtoks r" switch_punktrs4 t9r$cddlm}||S)a  Return a pickle-free Named Entity Chunker instead of loading a pickle. >>> import nltk >>> from nltk.corpus import treebank >>> from pprint import pprint >>> chunker = nltk.data.load('chunkers/maxent_ne_chunker/PY3/english_ace_multiclass.pickle') >>> pprint(chunker.parse(treebank.tagged_sents()[2][8:14])) # doctest: +NORMALIZE_WHITESPACE Tree('S', [('chairman', 'NN'), ('of', 'IN'), Tree('ORGANIZATION', [('Consolidated', 'NNP'), ('Gold', 'NNP'), ('Fields', 'NNP')]), ('PLC', 'NNP')]) r) ne_chunker) nltk.chunkr)fmtrs r"switch_chunkerrs& c?r$cddlm}|S)a Return a pickle-free Treebank Pos Tagger instead of loading a pickle. >>> import nltk >>> from nltk.tokenize import word_tokenize >>> tagger = nltk.data.load('taggers/maxent_treebank_pos_tagger/PY3/english.pickle') >>> print(tagger.tag(word_tokenize("Hello, how are you?"))) [('Hello', 'NNP'), (',', ','), ('how', 'WRB'), ('are', 'VBP'), ('you', 'PRP'), ('?', '.')] rmaxent_pos_tagger)nltk.classify.maxentrrs r"switch_t_taggerrs7  r$c2ddlm}|dk(rd}nd}||S)a Return a pickle-free Averaged Perceptron Tagger instead of loading a pickle. >>> import nltk >>> from nltk.tokenize import word_tokenize >>> tagger = nltk.data.load('taggers/averaged_perceptron_tagger/averaged_perceptron_tagger.pickle') >>> print(tagger.tag(word_tokenize("Hello, how are you?"))) [('Hello', 'NNP'), (',', ','), ('how', 'WRB'), ('are', 'VBP'), ('you', 'PRP'), ('?', '.')] r) _get_taggerrurusN)nltk.tagr)rrs r"switch_p_taggerrs#% t| t r$ct|}|dk(rE|jd}|d}|dk(r|d}tj|}|t d|z|t vrt d|d |r,t j||f} | |rtd |d | St|\} } | d dd k(r|rtd|d tjj| dd d} | jdr t| S| jdrt| jddS| jdr tS| jdrt| jddS|rtd|d t!|} |dk(r| j#} n|dk(rt%| j#} n|dk(rTddl}ddlm}|j-| } d}t/| dk7rt1| j3}||vr`t d|dk(rddl}|j7| } n9| j#}||j9|}n |j9d}|dk(r|} n|d k(r"t<j>jA||!} n|d"k(r"t<jBjA||!} n|d#k(r$t<jDjA||||$} n|d%k(r5tGjH|tFjJjM|&} nJ|d'k(rtGjH|||&} n,|d(k(rtGjN||!} ntQd)|d*| jS|r | t ||f<| S| S#t:$r|j9d}YBwxYw#tT$rY| SwxYw)+a Load a given resource from the NLTK data package. The following resource formats are currently supported: - ``pickle`` - ``json`` - ``yaml`` - ``cfg`` (context free grammars) - ``pcfg`` (probabilistic CFGs) - ``fcfg`` (feature-based CFGs) - ``fol`` (formulas of First Order Logic) - ``logic`` (Logical formulas to be parsed by the given logic_parser) - ``val`` (valuation of First Order Logic model) - ``text`` (the file contents as a unicode string) - ``raw`` (the raw file contents as a byte string) If no format is specified, ``load()`` will attempt to determine a format based on the resource name's file extension. If that fails, ``load()`` will raise a ``ValueError`` exception. For all text formats (everything except ``pickle``, ``json``, ``yaml`` and ``raw``), it tries to decode the raw contents using UTF-8, and if that doesn't work, it tries with ISO-8859-1 (Latin-1), unless the ``encoding`` is specified. :type resource_url: str :param resource_url: A URL specifying where the resource should be loaded from. The default protocol is "nltk:", which searches for the file in the the NLTK data package. :type cache: bool :param cache: If true, add this resource to a cache. If load() finds a resource in its cache, then it will return it from the cache rather than loading it. :type verbose: bool :param verbose: If true, print a message when loading a resource. Messages are not displayed when a resource is retrieved from the cache. :type logic_parser: LogicParser :param logic_parser: The parser that will be used to parse logical expressions. :type fstruct_reader: FeatStructReader :param fstruct_reader: The parser that will be used to parse the feature structure of an fcfg. :type encoding: str :param encoding: the encoding of the input; only used for text formats. autorrgzNzzCould not determine format for %s based on its file extension; use the "format" argument to specify the format explicitly.zUnknown format type: !z<>iz.picklez%<=?KL  W0:;; &**L&+AB  #/ ~R@A (6OHe RSzY  9,rJ KggmmE#2J'+   . /$ $   : ;!#))C."45 5   B C"$ $   B C"399S>"#56 6 <.+,L)O &++- 8 -o.B.B.DE 6 +yy1  |  !|((*+C i 01 1 6 ~~o6 &**,  %,,X6K <)009  V &L u_";;11+1QL v "<<22;2RL v "11<<)-! =L u_>> YY224!L w >>,Lu_--kHML 17:    6BO\62 3 <]& <)00;  N;:N;> O  O ct|}t|dd}|j}|D]6}|j|rt j d|r,t |8y)a} Write out a grammar file, ignoring escaped and empty lines. :type resource_url: str :param resource_url: A URL specifying where the resource should be loaded from. The default protocol is "nltk:", which searches for the file in the the NLTK data package. :type escape: str :param escape: Prepended string that signals lines to be ignored rF)rr z^$N)r=r splitlinesr,r.rr)r1escaperlinesls r"show_cfgrs`*,7L V5AL  # # %E  <<   88D!   a r$c,tjy)zF Remove all objects from the resource cache. :see: load() N)rclearrQr$r" clear_cachers r$ct|}t|\}}||jdk(r"t|tdgzj S|jdk(rt|dgj St |S)ao Helper function that returns an open file object for a resource, given its resource URL. If the given resource URL uses the "nltk:" protocol, or uses no protocol, then use ``nltk.data.find`` to find its path, and open it with the given mode; if the resource URL uses the 'file' protocol, then open the file with the given mode; otherwise, delegate to ``urllib2.urlopen``. :type resource_url: str :param resource_url: A URL specifying where the resource should be loaded from. The default protocol is "nltk:", which searches for the file in the the NLTK data package. r(rr))r=r4lowerrr8rSr r0s r"rrs~*,7L(6OHe8>>+v5E42$;',,..  V #EB4 %%''|$$r$c$eZdZdZdZdZdZy) LazyLoaderc||_yrrhres r"rfzLazyLoader.__init__s  r$crt|j}|j|_|j|_yr)rrd__dict__r)rRrs r"__loadzLazyLoader.__loads, #!)) !++r$c:|jt||Sr)_LazyLoader__loadgetattr)rRattrs r" __getattr__zLazyLoader.__getattr__s tT""r$c8|jt|Sr)r'reprrVs r"rtzLazyLoader.__repr__s Dzr$N)rZr[r\rfr'r*rtrQr$r"r!r!s,# r$r!c.eZdZdZdZdZdZdZdZy)ra A subclass of ``zipfile.ZipFile`` that closes its file pointer whenever it is not using it; and re-opens it when it needs to read data from the zipfile. This is useful for reducing the number of open file handles when many zip files are being accessed at once. ``OpenOnDemandZipFile`` must be constructed from a filename, not a file-like object (to allow re-opening). ``OpenOnDemandZipFile`` is read-only (i.e. ``write()`` and ``writestr()`` are disabled. ct|ts tdtjj |||j |k(sJ|jd|_y)Nz+ReopenableZipFile filename must be a stringr) rrr rZipFilerfrr _fileRefCnt)rRrs r"rfzOpenOnDemandZipFile.__init__sQ(C(IJ J  x0}}((( r$c|jJt|jd|_tjj ||}|xj dz c_|j|S)Nrkr')fprSrrr/rr0r)rRr<values r"rzOpenOnDemandZipFile.readsYwwt}}d+$$T40 A  r$ctdz<:raise NotImplementedError: OpenOnDemandZipfile is read-onlyz OpenOnDemandZipfile is read-onlyNotImplementedErrorrRargsr{s r"r~zOpenOnDemandZipFile.write !"DEEr$ctdr5r6r8s r"writestrzOpenOnDemandZipFile.writestrr:r$c2td|jzS)NzOpenOnDemandZipFile(%r))r,rrVs r"rtzOpenOnDemandZipFile.__repr__s- =>>r$N) rZr[r\r]rfrr~r<rtrQr$r"rrs"FF?r$rceZdZdZdZd dZd!dZdZd!dZd"dZ d Z d Z d Z d Z d ZdZdZedZedZedZdZd#dZdZd!dZdZd!dZdZej:dfgej<dfej>dfgej<dfgej>dfgej@dfejBdfgej@dfgejBdfgdZ"dZ#y)$rla A stream reader that automatically encodes the source byte stream into unicode (like ``codecs.StreamReader``); but still supports the ``seek()`` and ``tell()`` operations correctly. This is in contrast to ``codecs.StreamReader``, which provide *broken* ``seek()`` and ``tell()`` methods. This class was motivated by ``StreamBackedCorpusView``, which makes extensive use of ``seek()`` and ``tell()``, and needs to be able to handle unicode-encoded files. Note: this class requires stateless decoders. To my knowledge, this shouldn't cause a problem with any of python's builtin unicode encodings. Tc|jd||_ ||_ ||_ t j ||_ d|_ d|_ d|_ d|_ |j|_ y)Nrr$) seekrnrr codecs getdecoderr bytebuffer linebuffer_rewind_checkpoint_rewind_numchars _check_bom_bom)rRrnrr s r"rfz$SeekableUnicodeStreamReader.__init__1s A $   !  ''1   F ;#$ @ !% M OO%  =r$Nc|j|}|jr,dj|j|z}d|_d|_|S)a6 Read up to ``size`` bytes, decode them using this reader's encoding, and return the resulting unicode string. :param size: The maximum number of bytes to read. If not specified, then read as many bytes as possible. :type size: int :rtype: unicode rN)_readrDr;rF)rRsizecharss r"rz SeekableUnicodeStreamReader.readisF 4  ??GGDOO,u4E"DO$(D ! r$c|jrRt|jdkDr:|jjd}|xjt|z c_y|jj y)Nr'r)rDrpoprFrnreadlinerRlines r" discard_linez(SeekableUnicodeStreamReader.discard_line}sR ??s4??3a7??&&q)D  ! !SY . ! KK "r$c^|jrSt|jdkDr;|jjd}|xjt|z c_|S|xsd}d}|jr$||jjz }d|_ |jj t|j z }|j|}|r%|jdr||jdz }||z }|jd}t|dkDrA|d}|dd|_t|t|t|z z |_||_ |St|dk(r&|d}|djdd} || k7r|} |S|r||} |S|d kr|d z}) aj Read a line of text, decode it using this reader's encoding, and return the resulting unicode string. :param size: The maximum number of bytes to read. If no newline is encountered before ``size`` bytes have been read, then the returned value may not be a complete line of text. :type size: int r'rHrNT Fi@) rDrrNrFrntellrCrJrBrrE) rRrKrQreadsizerLstartpos new_charsr line0withendline0withoutends r"rOz$SeekableUnicodeStreamReader.readlines ??s4??3a7??&&q)D  ! !SY . !K:2 ?? T__((* *E"DO{{'')C,@@H 8,IY//5TZZ]* Y E$$T*E5zA~Qx"')(+I#e*s4y:P(Q%*2'  Uq$Qx "'("5"5e"|js|jyyr)closedrrVs r"__del__z#SeekableUnicodeStreamReader.__del__s{{ JJLr$c|SrrQrVs r" __enter__z%SeekableUnicodeStreamReader.__enter__s r$c$|jyr)r)rRtyper3 tracebacks r"__exit__z$SeekableUnicodeStreamReader.__exit__s  r$c|SrfrQrVs r" xreadlinesz&SeekableUnicodeStreamReader.xreadlinesrhr$c.|jjS)z(True if the underlying stream is closed.)rnrjrVs r"rjz"SeekableUnicodeStreamReader.closeds{{!!!r$c.|jjS)z"The name of the underlying stream.)rnr<rVs r"r<z SeekableUnicodeStreamReader.name{{r$c.|jjS)z"The mode of the underlying stream.)rnrrVs r"rz SeekableUnicodeStreamReader.modervr$c8|jjy)z. Close the underlying stream. N)rnrrVs r"rz!SeekableUnicodeStreamReader.closes r$c|dk(r td|jj||d|_d|_d|_|jj |_y)a Move the stream to a new file position. If the reader is maintaining any buffers, then they will be cleared. :param offset: A byte count offset. :param whence: If 0, then the offset is from the start of the file (offset should be positive), if 1, then the offset is from the current position (offset may be positive or negative); and if 2, then the offset is from the end of the file (offset should typically be negative). r'zmRelative seek is not supported for SeekableUnicodeStreamReader -- consider using char_seek_forward() instead.Nr$)r6rnr@rDrCrFrWrE)rRoffsetwhences r"r@z SeekableUnicodeStreamReader.seeks^ Q;5  ( $"&++"2"2"4r$c|dkr td|j|j|j|y)zI Move the read pointer forward by ``offset`` characters. rz"Negative offsets are not supportedN)r6r@rW_char_seek_forward)rRrzs r"char_seek_forwardz-SeekableUnicodeStreamReader.char_seek_forwards7 A:AB B $))+ 'r$c ||}d} |jj|t|z }||z }|j|\}}t||k(r*|jj t| |zdyt||kDrot||kDr7||t|z z }|j|d|\}}t||kDr7|jj t| |zdy||t|z z })a Move the file position forward by ``offset`` characters, ignoring all buffers. :param est_bytes: A hint, giving an estimate of the number of bytes that will be needed to move forward by ``offset`` chars. Defaults to ``offset``. Nr$r')rnrr _incr_decoder@)rRrz est_bytesbytesnewbytesrL bytes_decodeds r"r}z.SeekableUnicodeStreamReader._char_seek_forward)s  I{{'' CJ(>?H X E$(#4#4U#; E=5zV#   #e*}!.ds=Ts4y=s2rr)rDrnrWrrCrEsumintrFr@r}DEBUGrrr;r,)rR orig_filepos bytes_readbuf_sizerfileposcheck1check2s r"rWz SeekableUnicodeStreamReader.tellQsn ?? ";;##%DOO(<< < {{'') #S%99T=T=TT =T__== .. .$2G2G(2R S  001  5 5yA++""$ :: KK  W %&&t{{'7'7';A3E KK,,Q/  "'+'8'8'?$}  / r$c: |j|dS#t$r|}|jt|k(r.|j|d|j|j cYd}~S|j dk(r|j||j cYd}~Sd}~wwxYw)a Decode the given byte string into a unicode string, using this reader's encoding. If an exception is encountered that appears to be caused by a truncation error, then just decode the byte string without the bytes that cause the trunctaion error. Return a tuple ``(chars, num_consumed)``, where ``chars`` is the decoded unicode string, and ``num_consumed`` is the number of bytes that were consumed. strictN)rrendrstartr )rRrexcs r"rz(SeekableUnicodeStreamReader._incr_decodes ;{{5(33% ;77c%j(;;u[syy'94;;GG[[H,  ;;udkk:: ;s' BABB$+BBBzutf16-lezutf16-bezutf32-lezutf32-be)utf8utf16utf16leutf16beutf32utf32leutf32becjtjdd|jj}|jj |}|rg|j jd}|j jd|D],\}}|j|s|r||_t|cSy)Nz[ -]rr) r.r/rr _BOM_TABLErrnrr@r,r)rRencbom_inforbom new_encodings r"rGz&SeekableUnicodeStreamReader._check_bomsffVR!4!4!67??&&s+ KK$$R(E KK  Q &. $!\##C(#(4 s8O  $ r$)rrNT)r)$rZr[r\r]rrfrrRrOr`rrdrgrkrmrqrsrwrjr<rrr@r~r}rWrJrrABOM_UTF8 BOM_UTF16_LE BOM_UTF16_BE BOM_UTF32_LE BOM_UTF32_BErrGrQr$r"rlrlsK E2=p(#:x 0  ""    50 (&-P(\$L;>//4()&& 3f6I6I:5VW(($/0(($/0&& 3f6I6I:5VW(($/0(($/0Jr$rl)r8rOr`ryrrrrrrrrrr!rrrl)rkrrNNN)TNrr)english) multiclass)rTFNNN)z##)Lr]rA functoolsr7rr.rDtextwraprabcrrgziprGZ_WRITEriorrurllib.requestr r zlibr FLUSH ImportErrorr r(r rnltk.internalsrpartialindentrr8environrr+pathsep_paths_from_env expanduserappendrEr,r;rr#r4r=r:rOrr`ryrrrrrrrrrrrrrrrrr!r/rrl__all__)rs0r"rs]4 '"%0'*%#)##HOODA  9**..b177 CO)qq))bjj(RWW-?-?-E-MKK""=12<<5!  SZZ-  SZZ+6  SZZ 4  RZZ^^Iv6 D D   SZZ-  SZZ+6  SZZ 4$" D$      =65%p-j& G& R+K+\ ABxC&  5 MSMSl(p*f#TL G G $ "  , L 6 ; *            7 "  ,    qh,%>>(?'//(?`BBJ a-'&&'* *sL47M?M4 MM