
    #ZjD                        d Z ddlZddlZddlZddlZddlmZmZmZm	Z	 ddl
Z
ddlZddlZddlZddlZddlmZmZ ddlmZ ddlmZ g dZeee
j        f         Zeeeee         f         Zej        eeeee         f         f         Zd	ed
efdZ G d d          Z G d d          Z  G d de           Z! G d de           Z" G d de"          Z#	 	 	 d%dedee$         dee$         d	ee         d
ef
dZ%e%Z&dede	e'ee         gedee         f         f         fdZ(dedee         fd Z)ded!e	e*ge$f         d
e'fd"Z+ G d# d$          Z,dS )&a  Support for reading delimiter-separated value files.

This module contains unicode aware replacements for :func:`csv.reader`
and :func:`csv.writer`. It was stolen/extracted from the ``csvkit``
project to allow re-use when the whole ``csvkit`` package isn't
required.

The original implementations were largely copied from
`examples in the csv module documentation <http://docs.python.org/library/csv.html#examples>`_.

.. seealso:: http://en.wikipedia.org/wiki/Delimiter-separated_values
    N)OptionalUnionIOCallable)Iterable	Generator   )utils)Dialect)	UnicodeWriterUnicodeReaderUnicodeReaderWithLineNumberUnicodeDictReaderNamedTupleReaderiterrowsrewriteadd_rowsfilter_rows_as_dictencodingreturnc                 4    t          j        |           j        S )z#Normalize the name of the encoding.)codecslookupname)r   s    T/Users/jameslopez/projects/MentorCore/.venv/lib/python3.11/site-packages/csvw/dsv.pynormalize_encodingr   *   s    =""''    c                       e Zd ZdZ	 	 ddee         deeeef                  fdZ	d Z
dee         fdZd	 Zd
eeedf                  fdZdeeeeef                  fdZdS )r   u  
    Write Unicode data to a csv file.

    :param f: The target to which to write the data; a local path specified as `str` or     `pathlib.Path` or `None`, in which case the data, formatted as DSV can be retrieved     via :meth:`~UnicodeWriter.read`
    :param dialect: Either a dialect name as recognized by `csv.writer` or a     :class:`~Dialect` instance for dialect customization beyond what can be done with     `csv.writer`.
    :param kw: Keyword arguments passed through to `csv.writer`.

    .. code-block:: python

        >>> from csvw import UnicodeWriter
        >>> with UnicodeWriter('data.tsv', delimiter='	') as writer:
        ...     writer.writerow(['ä', 'ö', 'ü'])
    Nfdialectc                 Z   || _         |                    dd          | _        t          |t                    r@|j        | _        |                                | _        | j                            |           n|| _        |r
|| j        d<   t          | j                  | _        | j        
                    d          | _        | j        rB| j        
                    d          t          j        k    rt          | j        d| j        z  fd}nd }|| _        d	| _        d
| _        d | _        d S )Nr   utf-8r    
escapecharquoting   c                 (    fd| D             S )Nc                 `    g | ]*}t          |          r|                              n|+S  )
isinstancereplace).0s_new_old_types     r   
<listcomp>zBUnicodeWriter.__init__.<locals>._escapedoubled.<locals>.<listcomp>Z   s<    ZZZQRAu1E1EL		$---1ZZZr   r(   )rowr/   r.   r-   s    ```r   _escapedoubledz.UnicodeWriter.__init__.<locals>._escapedoubledV   s)     [ZZZZZVYZZZZr   c                     | S Nr(   )r1   s    r   r2   z.UnicodeWriter.__init__.<locals>._escapedoubled\   s    
r   Fr   )r   popr   r)   r   python_encodingas_python_formatting_parameterskwupdater   getr#   csv
QUOTE_NONEstrr2   _close_rows_writtenwriter)selfr   r    r8   r2   s        r   __init__zUnicodeWriter.__init__B   s.   
 z733gw'' 	-#3DM==??DGGNN2DG -%,	"*4=99'++l33? 
	tw{{955GG &)$(O$%$7[ [ [ [ [  ,r   c                    t          | j        t          t          j        f          rgt          | j        t          j                  rt          | j                  | _        t          j        | j        d| j        d          | _        d| _        n!| j        t          j	        d          | _        t          j        | j        fi | j        | _        | S )Nwt )r   newlineT)rF   )r)   r   r=   pathlibPathioopenr   r>   StringIOr;   r@   r8   rA   s    r   	__enter__zUnicodeWriter.__enter__c   s    dfsGL122 	-$&',// %TVWTVTDM2NNNDFDKKV^[,,,DFj334733r   r   c                     t          | j        d          r| j                            d           t          | j        d          r,| j                                                            d          S dS )z
        If the writer has been initialized passing `None` as target, the CSV data as `bytes` can be
        retrieved calling this method.
        seekr   readr"   N)hasattrr   rO   rP   encoderL   s    r   rP   zUnicodeWriter.readp   s`    
 466"" 	FKKNNN466"" 	16;;==''000tr   c                 J    | j         r| j                                         d S d S r4   r>   r   close)rA   type_value	tracebacks       r   __exit__zUnicodeWriter.__exit__{   )    ; 	FLLNNNNN	 	r   r1   c                     | j                             |                     |                     | xj        dz  c_        dS )zWrite multiple rows.r	   N)r@   writerowr2   r?   rA   r1   s     r   r\   zUnicodeWriter.writerow   s@    T0055666ar   rowsc                    t          |          D ]w\  }}t          |t                    rH|dk    r.| j        s'|                     |                                           |                                }|                     |           xdS )aL  
        Writes each row in `rows` formatted as CSV row. This behaves as
        [`csvwriter.writerows`](https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows)
        except when an iterable of `dict` objects is passed. In that case, it is assumed that all
        items in `rows` are `dict`s and all have the same keys in the same order (as what would
        be read by `UnicodeDictReader`). Then, the keys of the first item are written as header row
        and the values of each row are written as subsequent rows.

        :param rows: The data to be written.
        r   N)	enumerater)   dictr?   r\   keysvalues)rA   r^   ir1   s       r   	writerowszUnicodeWriter.writerows   s      oo 	 	FAs#t$$ #66$"46MM#((**---jjllMM#	 	r   )NN)__name__
__module____qualname____doc__r   PathTyper   r   r=   rB   rM   bytesrP   rY   r   r\   tuplelistra   re   r(   r   r   r   r   /   s         ( %)59 ! eGSL12   B  	huo 	 	 	 	   HU39%56        
huUD$->'?@      r   r   c                   `    e Zd ZdZ	 ddedeeeef                  fdZ	d Z
d Zd Zd	 Zd
 ZdS )r   a  
    Read Unicode data from a csv file.

    :param f: The source from which to read the data; a local path specified as `str` or     `pathlib.Path`, a file-like object or a `list` of lines.
    :param dialect: Either a dialect name as recognized by `csv.reader` or a     :class:`~Dialect` instance for dialect customization beyond what can be done with     `csv.writer`.
    :param kw: Keyword arguments passed through to `csv.reader`.

    .. code-block:: python

        >>> with UnicodeReader('tests/fixtures/frictionless-data.csv', delimiter='|') as reader:
        ...     for row in reader:
        ...         print(row)
        ...         break
        ...
        ['FK', 'Year', 'Location name', 'Value', 'binary', 'anyURI', 'email', 'boolean', 'array',
        'geojson']
    Nr   r    c                    || _         t          |                    dd                    | _        |                    dd           | _        t          |t                    r|nd | _        d | _        d | _	        | j        rE| j        j
        | _        |                                | _        | j                            |           n|| _        |r
|| j        d<   d| _        g | _        | j        dk    rd| _        | j        | _        d S )Nr   z	utf-8-siglineterminatorr    Fr"   )r   r   r5   r   rF   r)   r   r    linenoreaderr6   r7   r8   r9   r>   comments_reader_encoding)rA   r   r    r8   s       r   rB   zUnicodeReader.__init__   s    
 *266*k+J+JKKvv.55",Wg">">HwwD< 	- L8DM==??DGGNN2DG -%,	" =G##'DM
 !%r   c                 V   t          | j        t          t          j        f          rnt          | j        t          j                  rt          | j                  | _        t          j        | j        d| j        | j        pd          | _        d| _	        nlt          | j        d          sWg }| j        D ]F}|                    t          |t                    r|                    | j                  n|           G|| _        t          j        | j        fi | j        | _        d| _        | S )NrtrE   )moder   rF   TrP   )r)   r   r=   rG   rH   rI   rJ   r   rF   r>   rQ   appendrk   decoder;   rr   r8   rq   )rA   lineslines      r   rM   zUnicodeReader.__enter__   s   dfsGL122 
	$&',// %TVWTV$PTP\Pb`bcccDFDKK(( 	E ^ ^:dE;R;R\T[[777X\]]]]DFj334733r   c                       xj         dz  c_          fdt           j                  D             } xj         t          d |D                       z  c_         |S )Nr	   c                 r    g | ]3}t          |t                    r|n|                    j                  4S r(   )r)   r=   rz   rt   r+   r,   rA   s     r   r0   z+UnicodeReader._next_row.<locals>.<listcomp>   sK     ( ( ( As##HAA$2G)H)H( ( (r   c              3   Z   K   | ]&}t          |                              d           V  'dS )
N)rm   count)r+   r,   s     r   	<genexpr>z*UnicodeReader._next_row.<locals>.<genexpr>   s4      <<1477==..<<<<<<r   )rq   nextrr   sumr]   s   ` r   	_next_rowzUnicodeReader._next_row   ss    q( ( ( ($+&&( ( ( 	s<<<<<<<<
r   c                                                       } j        r|r1 j        j        r%|d                              j        j                  s8|rt	          |          dhk    r j        j        s j         j        j        k     r7|r1 j        j        r%|d                              j        j                  s|r j         j        j        k     rm j        	                     j         j        j
                            |                               j        j                                                  f                                             }|r1 j        j        r%|d                              j        j                  |rt	          |          dhk    r j        j        ! j         j        j        k     7 fd|D              j        j        d          }|S )Nr   rE   c                 D    g | ]}j                             |          S r(   )r    trimmerr   s     r   r0   z*UnicodeReader.__next__.<locals>.<listcomp>   s)    888q4<''**888r   )r   r    commentPrefix
startswithsetskipBlankRowsrq   skipRowsrs   ry   	delimiterjoinlstripstripskipColumnsr]   s   ` r   __next__zUnicodeReader.__next__   s   nn< 	T '4<5 'q6$$T\%?@@''!$SbT!1!1t|7Q!1[4<#888 DL6 A))$,*DEE!%t|/D!D!DM((.33C88??@Z[[aacc*    nn&&  '4<5 'q6$$T\%?@@''!$SbT!1!1t|7Q!1[4<#888 9888C8889Q9R9RSC
r   c                 J    | j         r| j                                         d S d S r4   rT   )rA   exc_typeexc_valexc_tbs       r   rY   zUnicodeReader.__exit__   rZ   r   c                     | S r4   r(   rL   s    r   __iter__zUnicodeReader.__iter__   s    r   r4   )rf   rg   rh   ri   LinesOrPathr   r   r   r=   rB   rM   r   r   rY   r   r(   r   r   r   r      s         . 6: .  . . eGSL12 .  .  .  .D       $      r   r   c                   "     e Zd ZdZ fdZ xZS )r   z
    A `UnicodeReader` yielding (lineno, row) pairs, where "lineno" is the 1-based number of the
    the **text line** where the (possibly multi-line) row data starts in the DSV file.
    c                 \    t                                                      }| j        dz   |fS )zI
        :return: a pair (1-based line number in the input, row)
        r	   )superr   rq   rA   r1   	__class__s     r   r   z$UnicodeReaderWithLineNumber.__next__  s+    
 gg  {Q##r   )rf   rg   rh   ri   r   __classcell__r   s   @r   r   r     sB         $ $ $ $ $ $ $ $ $r   r   c                        e Zd ZdZ	 	 	 ddeee                  dee         dee         f fdZedeee                  f fd            Z	de
f fd	Zde
fd
Z xZS )r   a  
    A `UnicodeReader` yielding one `dict` per row.

    :param f: As for :class:`UnicodeReader`
    :param fieldnames:

    .. code-block:: python

        >>> with UnicodeDictReader(
        ...         'tests/fixtures/frictionless-data.csv',
        ...         dialect=Dialect(delimiter='|', header=False),
        ...         fieldnames=[str(i) for i in range(1, 11)]) as reader:
        ...     for row in reader:
        ...         print(row)
        ...         break
        ...
        OrderedDict([('1', 'FK'), ('2', 'Year'), ('3', 'Location name'), ('4', 'Value'),
        ('5', 'binary'), ('6', 'anyURI'), ('7', 'email'), ('8', 'boolean'), ('9', 'array'),
        ('10', 'geojson')])

    N
fieldnamesrestkeyrestvalc                 t    || _         || _        || _        d| _         t	                      j        |fi | d S Nr   )_fieldnamesr   r   line_numr   rB   )rA   r   r   r   r   r8   r   s         r   rB   zUnicodeDictReader.__init__&  sG     &!!b!!!!!r   r   c                 T   | j         7	 t                                                      | _         n# t          $ r Y nw xY w| j        j        | _        | j         rKt          t          | j                             t          | j                   k    rt          j	        d           | j         S )z:Get the fieldnames, i.e. the dictionary keys for the rows.NzDuplicate column names!)
r   r   r   StopIterationrr   r   lenr   warningswarn)rA   r   s    r   r   zUnicodeDictReader.fieldnames3  s     ##(77#3#3#5#5      , 	93t'(())S1A-B-BBB7888s   %0 
==c                    | j         dk    r| j         t                                                      }| j        j         | _         |g k    r&t                                                      }|g k    &|                     |          S r   )r   r   r   r   rr   itemr   s     r   r   zUnicodeDictReader.__next__A  ss    =AOOgg  ,
 Rii''""$$C Riiyy~~r   c                 $   t          j        d t          | j        |          D                       }t	          | j                  }t	          |          }||k     r||d         || j        <   n"||k    r| j        |d         D ]}| j        ||<   |S )zTurn a row into a dict.c              3   $   K   | ]\  }}||fV  d S r4   r(   )r+   kvs      r   r   z)UnicodeDictReader.item.<locals>.<genexpr>Q  s*      #Q#Qtq!QF#Q#Q#Q#Q#Q#Qr   N)collectionsOrderedDictzipr   r   r   r   )rA   r1   dlflrkeys         r   r   zUnicodeDictReader.itemO  s    ##Q#Qs4?C7P7P#Q#Q#QQQ!!XX77!"##hAdlOO"WWrss+ & &#r   )NNN)rf   rg   rh   ri   r   rm   r=   rB   propertyr   DictRowTyper   r   r   r   s   @r   r   r     s         2 /3%)%)" " !c+" c]	"
 c]" " " " " "  HT#Y/           X +      
; 
 
 
 
 
 
 
 
r   r   c                   X    e Zd ZdZ eej                  Zej	        d             Z
d ZdS )r   a  
    A `UnicodeReader` yielding one `namedtuple` per row.

    .. note::

        This reader has some limitations, notably that fieldnames must be normalized to be
        admissible Python names, but also bad performance (compared with `UnicodeDictReader`).
    c                 z    t          t          | j        | j                            }t	          j        d|          S )zY
        Creates a namedtuple class suitable for the columns of the CSV content.
        Row)rm   map_normalize_fieldnamer   r   
namedtuple)rA   r   s     r   clszNamedTupleReader.clsh  s3    
 #d7IIJJ
%eZ888r   c                      t                                |          } j        D ]}|                    |d             j        di  fd|                                D             S )zCreate a namedtuple from a row.Nc                 T    i | ]$\  }}|j         v                     |          |%S r(   )r   r   )r+   r   r   rA   s      r   
<dictcomp>z)NamedTupleReader.item.<locals>.<dictcomp>v  s9    ]]]41aT_H\H\t((++QH\H\H\r   r(   )r   r   r   
setdefaultr   items)rA   r1   r   r   s   `   r   r   zNamedTupleReader.itemp  s    ""4--O 	% 	%DLLt$$$$tx _ _]]]]17799]]]_ _ 	_r   N)rf   rg   rh   ri   staticmethodr
   normalize_namer   	functoolscached_propertyr   r   r(   r   r   r   r   \  sd          (<(<==9 9 9_ _ _ _ _r   r   Fr"   lines_or_filenamedtuplesdictsc              +      K   |r|rt          d          |rt          }n|rt          }nt          } || fd|i|5 }|E d{V  ddd           dS # 1 swxY w Y   dS )a  Convenience factory function for csv reader.

    :param lines_or_file: Content to be read. Either a file handle, a file path or a list    of strings.
    :param namedtuples: Yield namedtuples.
    :param dicts: Yield dicts.
    :param encoding: Encoding of the content.
    :param kw: Keyword parameters are passed through to csv.reader.
    :return: A generator over the rows.
    z:either namedtuples or dicts can be chosen as output formatr   N)
ValueErrorr   r   r   )r   r   r   r   r8   _readerrs          r   r   r   y  s        Wu WUVVV  "	  #		8	8	8R	8	8 A                 s   	AAAfnamevisitorc                    t          j        |           } |                                 sJ t          j        d          5 }t          j        |j                  }ddd           n# 1 swxY w Y   t          | fi |5 }t          |fi |5 }t          |          D ](\  }} |||          }||	                    |           )	 ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   t          j        ||            dS )aD  Utility function to rewrite rows in dsv files.

    :param fname: Path of the dsv file to operate on.
    :param visitor: A callable that takes a line-number and a row as input and returns a     (modified) row or None to filter out the row.
    :param kw: Keyword parameters are passed through to csv.reader/csv.writer.
    FdeleteN)rG   rH   is_filetempfileNamedTemporaryFiler   r   r   r`   r\   shutilmove)	r   r   r8   fptmpreader_r@   rd   r1   s	            r   r   r     s    LE==???		$E	2	2	2 $bl27##$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 
u	#	#	#	# )w3%%"%% 	)#G,, ) )3gaoo?OOC((()	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)) ) ) ) ) ) ) ) ) ) ) ) ) ) ) KUsH    A&&A*-A*>C)9CC)C	C)C	C))C-0C-r^   c                    t          j        d          5 }t          j        |j                  }ddd           n# 1 swxY w Y   t          j        |           } t          |          5 }|                                 rBt          |           5 }|D ]}|                    |           	 ddd           n# 1 swxY w Y   |	                    |           ddd           n# 1 swxY w Y   t          j        ||            dS )z!
    Add rows to a CSV file.
    Fr   N)r   r   rG   rH   r   r   existsr   r\   re   r   r   )r   r^   r   r   r@   r   r1   s          r   r   r     s    
	$E	2	2	2 $bl27##$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ LE	s		 v<<>> 	)u%% )" ) )COOC(((()) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 	               KUsE   <A A *$C"B6*C"6B:	:C"=B:	>C""C&)C&filter_c                 J    t          |          }t          | |fi | |j        S )a  Rewrite a dsv file, filtering the rows.

    :param fname: Path to dsv file
    :param filter_: callable which accepts a `dict` with a row's data as single argument    returning a `Boolean` indicating whether to keep the row (`True`) or to discard it     `False`.
    :param kw: Keyword arguments to be passed `UnicodeReader` and `UnicodeWriter`.
    :return: The number of rows that have been removed.
    )
DictFilterr   removed)r   r   r8   s      r   r   r     s1     !!GE7!!b!!!?r   c                   x    e Zd ZdZdeeeef         gef         fdZde	de
e         dee
e                  fdZdS )	r   zMUtility to apply a filter to a row as dict, while iterating over rows a list.r   c                 0    d | _         || _        d| _        d S r   )headerfilterr   )rA   r   s     r   rB   zDictFilter.__init__  s    +/r   rd   r1   r   c                     |dk    r	|| _         |S |rIt          t          | j         |                    }|                     |          r|S | xj        dz  c_        d S )Nr   r	   )r   ra   r   r   r   )rA   rd   r1   r   s       r   __call__zDictFilter.__call__  sf    66DKJ 	DK--..D{{4   
LLALLtr   N)rf   rg   rh   ri   r   ra   r=   boolrB   intrm   r   r   r(   r   r   r   r     s        WW$sCx.)94)? @    
	# 	DI 	(492E 	 	 	 	 	 	r   r   )FFr"   )-ri   rI   r;   r   r   typingr   r   r   r   rG   r   r   r   r   collections.abcr   r   rE   r
   dsv_dialectsr   __all__r=   rH   rj   r   r   rm   r   r   r   r   r   r   r   r   r   rr   r   r   r   ra   r   r   r(   r   r   <module>r      sf    
			 



   0 0 0 0 0 0 0 0 0 0 0 0            / / / / / / / /       ! ! ! ! ! !   gl"#Hb(3-/0%c5d3i+@&@A( ( ( ( ( (
f f f f f f f fRf f f f f f f fR$ $ $ $ $- $ $ $J J J J J J J JZ_ _ _ _ _( _ _ _< ,1%*'. K "4.TN  }  	   8 
8 hT#Y/?tTRUYAW/W&X    ,H T#Y    "x (D64<2H SV             r   