
    $HJjD                     4   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
j0                  f   Zeeeee   f   Zej6                  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,y)$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                 @    t        j                  |       j                  S )z#Normalize the name of the encoding.)codecslookupname)r   s    R/Users/ahmed/devFolder/claude-voice/.venv/lib/python3.12/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y)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                 |   || _         |j                  dd      | _        t        |t              rB|j
                  | _        |j                         | _        | j                  j                  |       n|| _        |r|| j                  d<   t        | j                        | _        | j                  j                  d      | _        | j                  rO| j                  j                  d      t        j                  k7  r#t        | j                  d| j                  z  fd}nd }|| _        d	| _        d
| _        d | _        y )Nr   utf-8r    
escapecharquoting   c                 h    | D cg c]"  }t        ||      r|j                  ||      n|$ c}S c c}w N)
isinstancereplace)row_type_old_newss        r   _escapedoubledz.UnicodeWriter.__init__.<locals>._escapedoubledV   s:     WZZVYQRAu1E		$-1LVYZZZs   '/c                     | S r'    )r*   s    r   r/   z.UnicodeWriter.__init__.<locals>._escapedoubled\   s    
r   Fr   )r   popr   r(   r   python_encodingas_python_formatting_parameterskwupdater   getr#   csv
QUOTE_NONEstrr/   _close_rows_writtenwriter)selfr   r    r5   r/   s        r   __init__zUnicodeWriter.__init__B   s    
 z73gw'#33DM==?DGGGNN2DG%,	"*4==9''++l3??tww{{95G &)$(OO$%$7[,r   c                    t        | j                  t        t        j                  f      rxt        | 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)rC   )r(   r   r:   pathlibPathioopenr   r;   StringIOr8   r=   r5   r>   s    r   	__enter__zUnicodeWriter.__enter__c   s    dffsGLL12$&&',,/TVVWWTVVTDMM2NDFDKVV^[[,DFjj34773r   r   c                     t        | j                  d      r| j                  j                  d       t        | j                  d      r)| j                  j                         j	                  d      S y)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   rL   rM   encoderI   s    r   rM   zUnicodeWriter.readp   sM    
 4666"FFKKN4666"66;;=''00r   c                 R    | j                   r| j                  j                          y y r'   r;   r   close)r>   type_value	tracebacks       r   __exit__zUnicodeWriter.__exit__{       ;;FFLLN r   r*   c                     | j                   j                  | j                  |             | xj                  dz  c_        y)zWrite multiple rows.r	   N)r=   writerowr/   r<   )r>   r*   s     r   rY   zUnicodeWriter.writerow   s0    T0056ar   rowsc                     t        |      D ]f  \  }}t        |t              r@|dk(  r+| j                  s| j	                  |j                                |j                         }| j	                  |       h y)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<   rY   keysvalues)r>   rZ   ir*   s       r   	writerowszUnicodeWriter.writerows   sX      oFAs#t$6$"4"4MM#((*-jjlMM# &r   )NN)__name__
__module____qualname____doc__r   PathTyper   r   r:   r?   rJ   bytesrM   rV   r   rY   tuplelistr]   ra   r1   r   r   r   r   /   s    ( %)59! eGSL12B	huo 	 HU39%56  
huUD$->'?@ r   r   c                   R    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y)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        |j                  dd            | _        |j                  dd       | _        t        |t              r|nd | _        d | _        d | _	        | j                  rL| j                  j                  | _        |j                         | _        | j                  j                  |       n|| _        |r|| j                  d<   d| _        g | _        | j                  dk(  rd| _        | j                  | _        y )Nr   z	utf-8-siglineterminatorr    Fr"   )r   r   r2   r   rC   r(   r   r    linenoreaderr3   r4   r5   r6   r;   comments_reader_encoding)r>   r   r    r5   s       r   r?   zUnicodeReader.__init__   s    
 *266*k+JKvv.5",Wg">wD<< LL88DM==?DGGGNN2DG%,	" ==G#'DM
 !%r   c                    t        | j                  t        t        j                  f      rt        | j                  t        j                        rt        | j                        | _        t        j                  | j                  d| j                  | j                  xs d      | _        d| _	        nlt        | j                  d      sVg }| j                  D ]>  }|j                  t        |t              r|j                  | j                        n|       @ || _        t        j                  | j                  fi | j                   | _        d| _        | S )NrtrB   )moder   rC   TrM   )r(   r   r:   rD   rE   rF   rG   r   rC   r;   rN   appendrg   decoder8   rn   r5   rm   )r>   lineslines      r   rJ   zUnicodeReader.__enter__   s    dffsGLL12$&&',,/TVVWWTVV$PTP\P\Pb`bcDFDK(E:dE;RT[[7X\] DFjj34773r   c                    | xj                   dz  c_         t        | j                        D cg c]/  }t        |t              r|n|j                  | j                        1 }}| xj                   t        d |D              z  c_         |S c c}w )Nr	   c              3   P   K   | ]  }t        |      j                  d          yw)
N)ri   count).0r.   s     r   	<genexpr>z*UnicodeReader._next_row.<locals>.<genexpr>   s     <147==.s   $&)rm   nextrn   r(   r:   rv   rp   sum)r>   r.   r*   s      r   	_next_rowzUnicodeReader._next_row   s}    q $++&(& As#A$2G2G)HH& 	 ( 	s<<<<
	(s   4B
c                    | j                         }| j                  rK|r>| j                  j                  r(|d   j                  | j                  j                        sK|rt	        |      dhk(  r| j                  j
                  s$| j                  | j                  j                  k  r|r>| j                  j                  r(|d   j                  | j                  j                        s%|r| j                  | j                  j                  k  r{| j                  j                  | j                  | j                  j                  j                  |      j                  | j                  j                        j                         f       | j                         }|r@| j                  j                  r*|d   j                  | j                  j                        r2|rt	        |      dhk(  r| j                  j
                  r[| j                  | j                  j                  k  r|D cg c]  }| j                  j                  |       c}| j                  j                  d  }|S c c}w )Nr   rB   )r   r    commentPrefix
startswithsetskipBlankRowsrm   skipRowsro   ru   	delimiterjoinlstripstriptrimmerskipColumns)r>   r*   r.   s      r   __next__zUnicodeReader.__next__   s   nn<<4<<55q6$$T\\%?%?@SbT!1t||7Q7Q[[4<<#8#88DLL66A))$,,*D*DEt||/D/D!DMM((..33C8??@Z@Z[aac*  nn& 4<<55q6$$T\\%?%?@SbT!1t||7Q7Q[[4<<#8#88 588Cq4<<''*C89Q9Q9RSC
 9s   -"I+c                 R    | j                   r| j                  j                          y y r'   rQ   )r>   exc_typeexc_valexc_tbs       r   rV   zUnicodeReader.__exit__   rW   r   c                     | S r'   r1   rI   s    r   __iter__zUnicodeReader.__iter__   s    r   r'   )rb   rc   rd   re   LinesOrPathr   r   r   r:   r?   rJ   r   r   rV   r   r1   r   r   r   r      sK    . 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                 B    t         |          }| j                  dz   |fS )zI
        :return: a pair (1-based line number in the input, row)
        r	   )superr   rm   r>   r*   	__class__s     r   r   z$UnicodeReaderWithLineNumber.__next__  s%    
 g {{Q##r   )rb   rc   rd   re   r   __classcell__r   s   @r   r   r     s    $ $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')])

    
fieldnamesrestkeyrestvalc                 ^    || _         || _        || _        d| _        t	        |   |fi | y Nr   )_fieldnamesr   r   line_numr   r?   )r>   r   r   r   r   r5   r   s         r   r?   zUnicodeDictReader.__init__&  s4     &!b!r   r   c                 Z   | j                   	 t        | 	         | _         | j                  j
                  | _        | j                   rIt        t        | j                               t        | j                         k7  rt        j                  d       | j                   S # t        $ r Y w xY w)z:Get the fieldnames, i.e. the dictionary keys for the rows.zDuplicate column names!)
r   r   r   StopIterationrn   r   lenr   warningswarn)r>   r   s    r   r   zUnicodeDictReader.fieldnames3  s     ##(7#3#5  ,,3t''()S1A1A-BB78 ! s   B 	B*)B*c                     | j                   dk(  r| j                   t        |          }| j                  j                   | _         |g k(  rt        |          }|g k(  r| j                  |      S r   )r   r   r   r   rn   itemr   s     r   r   zUnicodeDictReader.__next__A  sa    ==AOOg ,,
 Ri'"$C Riyy~r   c                 (   t        j                  d t        | j                  |      D              }t	        | j                        }t	        |      }||k  r||d || j
                  <   |S ||kD  r#| j                  |d D ]  }| j                  ||<    |S )zTurn a row into a dict.c              3   *   K   | ]  \  }}||f  y wr'   r1   )r}   kvs      r   r~   z)UnicodeDictReader.item.<locals>.<genexpr>Q  s     #Q7Ptq!QF7Ps   N)collectionsOrderedDictzipr   r   r   r   )r>   r*   dlflrkeys         r   r   zUnicodeDictReader.itemO  s    ###Qs4??C7P#QQ!X7!"#hAdllO  "Wrs+# ,r   )NNN)rb   rc   rd   re   r   ri   r:   r?   propertyr   DictRowTyper   r   r   r   s   @r   r   r     s    2 /3%)%)" !c+" c]	"
 c]"  HT#Y/    + 
; 
r   r   c                   ^    e Zd ZdZ eej                        Zej                  d        Z
d Zy)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                     t        t        | j                  | j                              }t	        j
                  d|      S )zY
        Creates a namedtuple class suitable for the columns of the CSV content.
        Row)ri   map_normalize_fieldnamer   r   
namedtuple)r>   r   s     r   clszNamedTupleReader.clsh  s2    
 #d77IJ
%%eZ88r   c                 $   t         j                  | |      }| j                  D ]  }|j                  |d         | j                  di |j                         D ci c]&  \  }}|| j                  v s| j                  |      |( c}}S c c}}w )zCreate a namedtuple from a row.Nr1   )r   r   r   
setdefaultr   itemsr   )r>   r*   r   r   r   r   s         r   r   zNamedTupleReader.itemp  s    ""4-OODLLt$ $txx _;<779]941aT__H\t((+Q.9]_ 	_]s   B2BN)rb   rc   rd   re   staticmethodr
   normalize_namer   	functoolscached_propertyr   r   r1   r   r   r   r   \  s8     ((<(<=9 9_r   r   lines_or_filenamedtuplesdictsc              +      K   |r|rt        d      |rt        }n|rt        }nt        } || fd|i|5 }|E d{    ddd       y7 # 1 sw Y   yxY ww)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   r5   _readerrs          r   r   r   y  s]      uUVV"	#		8	8R	8A 
9	8 
9	8s,   3AAA	A 	A	AAAfnamevisitorc                    t        j                  |       } | j                         sJ t        j                  d      5 }t        j                  |j
                        }ddd       t        | fi |5 }t        fi |5 }t        |      D ]"  \  }} |||      }||j                  |       $ 	 ddd       ddd       t        j                  |        y# 1 sw Y   {xY w# 1 sw Y   4xY w# 1 sw Y   8xY w)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)rD   rE   is_filetempfileNamedTemporaryFiler   r   r   r\   rY   shutilmove)	r   r   r5   fptmpreader_r=   r`   r*   s	            r   r   r     s     LLE==??		$	$E	2bll277# 
3 
u	#	#w3%"%#G,3ao?OOC( - & 
$ KKU 
3	2 &% 
$	#s5    C2C0?C$C$1C0C!$C-	)C00C9rZ   c                    t        j                  d      5 }t        j                  |j                        }ddd       t        j                  |       } t              5 }| j                         r-t        |       5 }|D ]  }|j                  |        	 ddd       |j                  |       ddd       t        j                  ||        y# 1 sw Y   xY w# 1 sw Y   ExY w# 1 sw Y   8xY w)z!
    Add rows to a CSV file.
    Fr   N)r   r   rD   rE   r   r   existsr   rY   ra   r   r   )r   rZ   r   r   r=   r   r*   s          r   r   r     s     
	$	$E	2bll277# 
3 LLE	s	v<<>u%"COOC( # & 	 
 KKU 
3	2 &% 
	s/    CC%;CC%C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   r5   s      r   r   r     s'     !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y)	r   zMUtility to apply a filter to a row as dict, while iterating over rows a list.r   c                 .    d | _         || _        d| _        y r   )headerfilterr   )r>   r   s     r   r?   zDictFilter.__init__  s    +/r   r`   r*   r   c                     |dk(  r	|| _         |S |rGt        t        | j                   |            }| j                  |      r|S | xj                  dz  c_        y )Nr   r	   )r   r]   r   r   r   )r>   r`   r*   r   s       r   __call__zDictFilter.__call__  sO    6DKJDKK-.D{{4 
LLALr   N)rb   rc   rd   re   r   r]   r:   boolr?   intri   r   r   r1   r   r   r   r     sM    W$sCx.)94)? @ 
	# 	DI 	(492E 	r   r   )FFr"   )-re   rF   r8   r   r   typingr   r   r   r   rD   r   r   r   r   collections.abcr   r   rB   r
   dsv_dialectsr   __all__r:   rE   rf   r   r   ri   r   r   r   r   r   r   r   r   r   rn   r   r   r   r]   r   r   r1   r   r   <module>r      s   
 
   0 0      /  ! gll"#Hb(3-/0%%c5d3i+@&@A( ( (
f fRf fR$- $J JZ_( _< ,1%*'.K "4.TN  }  	8 
8 hT#Y/?tTRUYAW/W&X ,H T#Y "x (D64<2H SV  r   