o
    ;DiC                     @   s   d dl mZmZmZ d dlZd dlmZmZ d dlm	Z	 d dl
mZmZ dddZG dd	 d	eZd
d Z		dddZ		dddZ			dddZ			dddZG dd deZdd ZdS )    )absolute_importprint_functiondivisionN)string_typesizip)ArgumentError)Tabledictsc                 C   s   t | ||dS )a'  
    Extract all documents from a Whoosh index. E.g.::

        >>> import petl as etl
        >>> import os
        >>> # set up an index and load some documents via the Whoosh API
        ... from whoosh.index import create_in
        >>> from whoosh.fields import *
        >>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True),
        ...                 content=TEXT)
        >>> dirname = 'example.whoosh'
        >>> if not os.path.exists(dirname):
        ...     os.mkdir(dirname)
        ...
        >>> index = create_in(dirname, schema)
        >>> writer = index.writer()
        >>> writer.add_document(title=u"First document", path=u"/a",
        ...                     content=u"This is the first document we've added!")
        >>> writer.add_document(title=u"Second document", path=u"/b",
        ...                     content=u"The second one is even more interesting!")
        >>> writer.commit()
        >>> # extract documents as a table
        ... table = etl.fromtextindex(dirname)
        >>> table
        +------+-------------------+
        | path | title             |
        +======+===================+
        | '/a' | 'First document'  |
        +------+-------------------+
        | '/b' | 'Second document' |
        +------+-------------------+

    Keyword arguments:
    
    index_or_dirname
        Either an instance of `whoosh.index.Index` or a string containing the
        directory path where the index is stored.
    indexname
        String containing the name of the index, if multiple indexes are stored
        in the same directory.
    docnum_field
        If not None, an extra field will be added to the output table containing
        the internal document number stored in the index. The name of the field
        will be the value of this argument.

    )	indexnamedocnum_field)TextIndexViewindex_or_dirnamer
   r    r   G/var/www/Datamplify/venv/lib/python3.10/site-packages/petl/io/whoosh.pyfromtextindex   s   0r   c                   @   s   e Zd ZdddZdd ZdS )r   Nc                 C   s   || _ || _|| _d S Nr   )selfr   r
   r   r   r   r   __init__C   s   
zTextIndexView.__init__c                 C   s   t | j| j| jS r   )itertextindexr   r
   r   r   r   r   r   __iter__H   s   
zTextIndexView.__iter__NN__name__
__module____qualname__r   r   r   r   r   r   r   A   s    
r   c                 c   s(   dd l }t| tr| }|jj||dd}d}nt| |jjr$| }d}ntd|  zazQ|d u rSt|j	 }|V  t
j|j	  }|  D ]	\}	}
||
V  qHn(|ft|j	  }|V  t
j|j	  }|  D ]\}}
|f||
 V  qnW n    W |r|  d S d S |r|  w w )Nr   Tr
   readonlyF"expected string or index, found %r)whoosh.index
isinstancer   indexopen_dirIndexr   tupleschemastored_namesoperator
itemgetterreader	iter_docsclose)r   r
   r   whooshdirnamer"   needs_closinghdrastuple_stored_fields_dictdocnumr   r   r   r   M   sH   


r   Fc                 C   s   ddl }ddl}t|tr|}|jj|||d}d}	nt||jjr'|}d}	ntd| | }
z/zt	| D ]
}|
j
di | q7|
j|||jjd W n   |
   W |	r_|  dS dS |	rh|  w w )	a  
    Load all rows from `table` into a Whoosh index. N.B., this will clear any
    existing data in the index before loading. E.g.::

        >>> import petl as etl
        >>> import datetime
        >>> import os
        >>> # here is the table we want to load into an index
        ... table = (('f0', 'f1', 'f2', 'f3', 'f4'),
        ...          ('AAA', 12, 4.3, True, datetime.datetime.now()),
        ...          ('BBB', 6, 3.4, False, datetime.datetime(1900, 1, 31)),
        ...          ('CCC', 42, 7.8, True, datetime.datetime(2100, 12, 25)))
        >>> # define a schema for the index
        ... from whoosh.fields import *
        >>> schema = Schema(f0=TEXT(stored=True),
        ...                 f1=NUMERIC(int, stored=True),
        ...                 f2=NUMERIC(float, stored=True),
        ...                 f3=BOOLEAN(stored=True),
        ...                 f4=DATETIME(stored=True))
        >>> # load index
        ... dirname = 'example.whoosh'
        >>> if not os.path.exists(dirname):
        ...     os.mkdir(dirname)
        ...
        >>> etl.totextindex(table, dirname, schema=schema)

    Keyword arguments:

    table
        A table container with the data to be loaded.
    index_or_dirname
        Either an instance of `whoosh.index.Index` or a string containing the
        directory path where the index is to be stored.
    schema
        Index schema to use if creating the index.
    indexname
        String containing the name of the index, if multiple indexes are stored
        in the same directory.
    merge
        Merge small segments during commit?
    optimize
        Merge all segments together?

    r   N)r
   TFr   )mergeoptimize	mergetyper   )r    whoosh.writingr!   r   r"   	create_inr$   r   writerr	   add_documentcommitwritingCLEARcancelr,   )tabler   r&   r
   r5   r6   r-   r.   r"   r/   r:   dr   r   r   totextindex}   s<   .



rB   Tc                 C   s   ddl }t|tr|}|jj||dd}d}nt||jjr#|}d}ntd| | }	z0zt| D ]
}
|	j	di |
 q3|	j
||d W n tyR   |	   w W |r\|  dS dS |re|  w w )	aF  
    Load all rows from `table` into a Whoosh index, adding them to any existing
    data in the index.

    Keyword arguments:

    table
        A table container with the data to be loaded.
    index_or_dirname
        Either an instance of `whoosh.index.Index` or a string containing the
        directory path where the index is to be stored.
    indexname
        String containing the name of the index, if multiple indexes are stored
        in the same directory.
    merge
        Merge small segments during commit?
    optimize
        Merge all segments together?

    r   NFr   Tr   )r5   r6   r   )r    r!   r   r"   r#   r$   r   r:   r	   r;   r<   	Exceptionr?   r,   )r@   r   r
   r5   r6   r-   r.   r"   r/   r:   rA   r   r   r   appendtextindex   s8   


rD   
   c              
   C   s   t | |||||||dS )a
  
    Search a Whoosh index using a query. E.g.::

        >>> import petl as etl
        >>> import os
        >>> # set up an index and load some documents via the Whoosh API
        ... from whoosh.index import create_in
        >>> from whoosh.fields import *
        >>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True),
        ...                            content=TEXT)
        >>> dirname = 'example.whoosh'
        >>> if not os.path.exists(dirname):
        ...     os.mkdir(dirname)
        ...
        >>> index = create_in('example.whoosh', schema)
        >>> writer = index.writer()
        >>> writer.add_document(title=u"Oranges", path=u"/a",
        ...                     content=u"This is the first document we've added!")
        >>> writer.add_document(title=u"Apples", path=u"/b",
        ...                     content=u"The second document is even more "
        ...                             u"interesting!")
        >>> writer.commit()
        >>> # demonstrate the use of searchtextindex()
        ... table1 = etl.searchtextindex('example.whoosh', 'oranges')
        >>> table1
        +------+-----------+
        | path | title     |
        +======+===========+
        | '/a' | 'Oranges' |
        +------+-----------+

        >>> table2 = etl.searchtextindex('example.whoosh', 'doc*')
        >>> table2
        +------+-----------+
        | path | title     |
        +======+===========+
        | '/a' | 'Oranges' |
        +------+-----------+
        | '/b' | 'Apples'  |
        +------+-----------+

    Keyword arguments:

    index_or_dirname
        Either an instance of `whoosh.index.Index` or a string containing the
        directory path where the index is to be stored.
    query
        Either a string or an instance of `whoosh.query.Query`. If a string,
        it will be parsed as a multi-field query, i.e., any terms not bound
        to a specific field will match **any** field.
    limit
        Return at most `limit` results.
    indexname
        String containing the name of the index, if multiple indexes are stored
        in the same directory.
    docnum_field
        If not None, an extra field will be added to the output table containing
        the internal document number stored in the index. The name of the field
        will be the value of this argument.
    score_field
        If not None, an extra field will be added to the output table containing
        the score of the result. The name of the field will be the value of this
        argument.
    fieldboosts
        An optional dictionary mapping field names to boosts.
    search_kwargs
        Any extra keyword arguments to be passed through to the Whoosh
        `search()` method.

    )limitr
   r   score_fieldfieldboostssearch_kwargsSearchTextIndexView)r   queryrF   r
   r   rG   rH   rI   r   r   r   searchtextindex  s
   JrM   c	           	      C   s   t | ||||||||d	S )a)  
    Search an index using a query, returning a result page.

    Keyword arguments:

    index_or_dirname
        Either an instance of `whoosh.index.Index` or a string containing the
        directory path where the index is to be stored.
    query
        Either a string or an instance of `whoosh.query.Query`. If a string,
        it will be parsed as a multi-field query, i.e., any terms not bound
        to a specific field will match **any** field.
    pagenum
        Number of the page to return (e.g., 1 = first page).
    pagelen
        Number of results per page.
    indexname
        String containing the name of the index, if multiple indexes are stored
        in the same directory.
    docnum_field
        If not None, an extra field will be added to the output table containing
        the internal document number stored in the index. The name of the field
        will be the value of this argument.
    score_field
        If not None, an extra field will be added to the output table containing
        the score of the result. The name of the field will be the value of this
        argument.
    fieldboosts
        An optional dictionary mapping field names to boosts.
    search_kwargs
        Any extra keyword arguments to be passed through to the Whoosh
        `search()` method.

    )pagenumpagelenr
   r   rG   rH   rI   rJ   )	r   rL   rN   rO   r
   r   rG   rH   rI   r   r   r   searchtextindexpageQ  s   &rP   c                   @   s$   e Zd Z			dddZdd ZdS )rK   Nc                 C   s@   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	d S r   )
_index_or_dirname_query_limit_pagenum_pagelen
_indexname_docnum_field_score_field_fieldboosts_search_kwargs)r   r   rL   rF   rN   rO   r
   r   rG   rH   rI   r   r   r   r     s   
zSearchTextIndexView.__init__c                 C   s.   t | j| j| j| j| j| j| j| j| j	| j

S r   )itersearchindexrQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r   r   r   r   r     s   
zSearchTextIndexView.__iter__)NNNNNNNNr   r   r   r   r   rK   ~  s    
rK   c
                 c   s(   dd l }
dd l}
dd l}
|	st }	t| tr%| }|
jj||dd}d}nt| |
jjr1| }d}nt	d|  zzt
 }|d urE||f7 }|d urN||f7 }t
|j }||7 }|V  t|trt|
jj|j |j|d}||}nt||
jjr|nt	d| tj|j  }| c}|d ur|j|fd|i|	}n|j||fd	|i|	}|d u r|d u r|D ]}||V  qn,t| |D ]$\\}}}t
 }|d ur||f7 }|d ur||f7 }|||7 }|V  qW d    n1 sw   Y  W n    W |r	|  d S d S |r|  w w )
Nr   Tr   Fr   )rH   z/expected string or whoosh.query.Query, found %rrF   rO   )r    whoosh.querywhoosh.qparserdictr!   r   r"   r#   r$   r   r%   r&   r'   qparserMultifieldParsernamesparserL   Queryr(   r)   searchersearchsearch_pager   itemsr,   )r   rL   rF   rN   rO   r
   r   rG   rH   rI   r-   r.   r"   r/   r0   r'   parserr1   rd   resultsdocr4   scorerowr   r   r   r[     s   








r[   r   )NNFF)NTF)rE   NNNNN)
__future__r   r   r   r(   petl.compatr   r   petl.errorsr   petl.util.baser   r	   r   r   r   rB   rD   rM   rP   rK   r[   r   r   r   r   <module>   s0   
40
O
5
P
-