
    =wgZ                        d Z ddlZddlZddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZ ddlmZ ddlmZmZmZmZ dd	lmZmZ dd
lmZ d Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z  G d de       Z! G d de       Z" G d de       Z# G d  d!e       Z$ G d" d#e       Z%y)$a  
This module contains "collector" objects. Collectors provide a way to gather
"raw" results from a :class:`whoosh.matching.Matcher` object, implement
sorting, filtering, collation, etc., and produce a
:class:`whoosh.searching.Results` object.

The basic collectors are:

TopCollector
    Returns the top N matching results sorted by score, using block-quality
    optimizations to skip blocks of documents that can't contribute to the top
    N. The :meth:`whoosh.searching.Searcher.search` method uses this type of
    collector by default or when you specify a ``limit``.

UnlimitedCollector
    Returns all matching results sorted by score. The
    :meth:`whoosh.searching.Searcher.search` method uses this type of collector
    when you specify ``limit=None`` or you specify a limit equal to or greater
    than the number of documents in the searcher.

SortingCollector
    Returns all matching results sorted by a :class:`whoosh.sorting.Facet`
    object. The :meth:`whoosh.searching.Searcher.search` method uses this type
    of collector when you use the ``sortedby`` parameter.

Here's an example of a simple collector that instead of remembering the matched
documents just counts up the number of matches::

    class CountingCollector(Collector):
        def prepare(self, top_searcher, q, context):
            # Always call super method in prepare
            Collector.prepare(self, top_searcher, q, context)

            self.count = 0

        def collect(self, sub_docnum):
            self.count += 1

    c = CountingCollector()
    mysearcher.search_with_collector(myquery, c)
    print(c.count)

There are also several wrapping collectors that extend or modify the
functionality of other collectors. The meth:`whoosh.searching.Searcher.search`
method uses many of these when you specify various parameters.

NOTE: collectors are not designed to be reentrant or thread-safe. It is
generally a good idea to create a new collector for each search.
    Narray)insort)defaultdict)heapifyheappushheapreplace)sorting)abstractmethod	iteritems
itervaluesxrange)Results	TimeLimit)nowc                 "    d}| D ]  }|dz  }	 |S Nr       )iteratortotal_s      H/var/www/horilla/myenv/lib/python3.12/site-packages/whoosh/collectors.pyilenr   ]   s$    E 
L    c                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
ed	        Zed
        Zd Zd Zd Zd Zd Zed        Zy)	CollectorzBase class for collectors.
    c                 x    || _         || _        || _        t               | _        d| _        t               | _        y)a  This method is called before a search.

        Subclasses can override this to perform set-up work, but
        they should still call the superclass's method because it sets several
        necessary attributes on the collector object:

        self.top_searcher
            The top-level searcher.
        self.q
            The query object
        self.context
            ``context.needs_current`` controls whether a wrapping collector
            requires that this collector's matcher be in a valid state at every
            call to ``collect()``. If this is ``False``, the collector is free
            to use faster methods that don't necessarily keep the matcher
            updated, such as ``matcher.all_ids()``.

        :param top_searcher: the top-level :class:`whoosh.searching.Searcher`
            object.
        :param q: the :class:`whoosh.query.Query` object being searched for.
        :param context: a :class:`whoosh.searching.SearchContext` object
            containing information about the search.
        N)top_searcherqcontextr   	starttimeruntimesetdocsetselfr   r    r!   s       r   preparezCollector.preparej   s3    2 )er   c                     	 | j                   j                         D ]'  \  }}| j                  ||       | j                          ) 	 | j	                          y # | j	                          w xY wN)r   leaf_searchersset_subsearchercollect_matchesfinishr'   subsearcheroffsets      r   runzCollector.run   s[    	'+'8'8'G'G'I '#V$$[&9$$&' KKMDKKMs   AA A*c                 v    || _         || _        | j                  j                  || j                        | _        y)a`  This method is called each time the collector starts on a new
        sub-searcher.

        Subclasses can override this to perform set-up work, but
        they should still call the superclass's method because it sets several
        necessary attributes on the collector object:

        self.subsearcher
            The current sub-searcher. If the top-level searcher is atomic, this
            is the same as the top-level searcher.
        self.offset
            The document number offset of the current searcher. You must add
            this number to the document number passed to
            :meth:`Collector.collect` to get the top-level document number
            for use in results.
        self.matcher
            A :class:`whoosh.matching.Matcher` object representing the matches
            for the query in the current sub-searcher.
        N)r0   r1   r    matcherr!   r/   s      r   r,   zCollector.set_subsearcher   s-    * 'vv~~k4<<@r   c                      y)a  Returns True if the collector naturally computes the exact number of
        matching documents. Collectors that use block optimizations will return
        False since they might skip blocks containing matching documents.

        Note that if this method returns False you can still call :meth:`count`,
        but it means that method might have to do more work to calculate the
        number of matching documents.
        Tr   r'   s    r   computes_countzCollector.computes_count   s     r   c                     | j                   S )a	  Returns a sequence of docnums matched in this collector. (Only valid
        after the collector is run.)

        The default implementation is based on the docset. If a collector does
        not maintain the docset, it will need to override this method.
        r%   r6   s    r   all_idszCollector.all_ids   s     {{r   c                 ,    t        | j                        S )a  Returns the total number of documents matched in this collector.
        (Only valid after the collector is run.)

        The default implementation is based on the docset. If a collector does
        not maintain the docset, it will need to override this method.
        )lenr%   r6   s    r   countzCollector.count   s     4;;r   c                 V    | j                   }| j                         D ]
  } ||        y)a>  This method calls :meth:`Collector.matches` and then for each
        matched document calls :meth:`Collector.collect`. Sub-classes that
        want to intervene between finding matches and adding them to the
        collection (for example, to filter out certain documents) can override
        this method.
        N)collectmatches)r'   r?   
sub_docnums      r   r-   zCollector.collect_matches   s*     ,,,,. 	 JJ	 r   c                     t         )ae  This method is called for every matched document. It should do the
        work of adding a matched document to the results, and it should return
        an object to use as a "sorting key" for the given document (such as the
        document's score, a key generated by a facet, or just None). Subclasses
        must implement this method.

        If you want the score for the current document, use
        ``self.matcher.score()``.

        Overriding methods should add the current document offset
        (``self.offset``) to the ``sub_docnum`` to get the top-level document
        number for the matching document to add to results.

        :param sub_docnum: the document number of the current match within the
            current sub-searcher. You must add ``self.offset`` to this number
            to get the document's top-level document number.
        NotImplementedErrorr'   rA   s     r   r?   zCollector.collect   s
    ( "!r   c                     t         )a0  Returns a sorting key for the current match. This should return the
        same value returned by :meth:`Collector.collect`, but without the side
        effect of adding the current document to the results.

        If the collector has been prepared with ``context.needs_current=True``,
        this method can use ``self.matcher`` to get information, for example
        the score. Otherwise, it should only use the provided ``sub_docnum``,
        since the matcher may be in an inconsistent state.

        Subclasses must implement this method.
        rC   rE   s     r   sort_keyzCollector.sort_key   s
     "!r   c                     | j                   }t        t        |            D ]   }||   d   |k(  s|j                  |        y t	        |      )zRemoves a document from the collector. Not that this method uses the
        global document number as opposed to :meth:`Collector.collect` which
        takes a segment-relative docnum.
        r   N)itemsr   r<   popKeyError)r'   global_docnumrI   is       r   removezCollector.remove   sP     

E
# 	AQx{m+		!	 }%%r   c              #      K   | j                   }|j                         r4|j                          |j                          |j                         r3y y wr*   )r4   	is_activeidnext)r'   r4   s     r   _step_through_matcheszCollector._step_through_matches  s>     ,,!**,LLN !s   AAAc                     | j                   j                  r| j                         S | j                  j	                         S )zeYields a series of relative document numbers for matches
        in the current subsearcher.
        )r!   needs_currentrS   r4   r:   r6   s    r   r@   zCollector.matches  s3     <<%%--//<<''))r   c                 <    t               | j                  z
  | _        y)a>  This method is called after a search.

        Subclasses can override this to perform set-up work, but
        they should still call the superclass's method because it sets several
        necessary attributes on the collector object:

        self.runtime
            The time (in seconds) the search took.
        N)r   r"   r#   r6   s    r   r.   zCollector.finish  s     ut~~-r   c                 z    t        | j                  | j                  |fi |}| j                  |_        | |_        |S r*   )r   r   r    r#   	collector)r'   rI   kwargsrs       r   _resultszCollector._results+  s8     D%%tvvu??LL	r   c                     t         )zReturns a :class:`~whoosh.searching.Results` object containing the
        results of the search. Subclasses must implement this method
        rC   r6   s    r   resultszCollector.results3  s
     "!r   N)__name__
__module____qualname____doc__r(   r2   r,   r7   r:   r=   r-   r   r?   rG   rN   rS   r@   r.   r[   r]   r   r   r   r   r   f   s    BA2
 
  " "* " "&
*. " "r   r   c                   <    e Zd ZdZd
dZd Zd Zd Zd Zd Z	d Z
y	)ScoredCollectorzMBase class for collectors that sort the results based on document score.
    c                 <    t         j                  |        || _        y)z
        :param replace: Number of matches between attempts to replace the
            matcher with a more efficient version.
        N)r   __init__replace)r'   rf   s     r   re   zScoredCollector.__init__B  s     	4 r   c                     t         j                  | |||       |j                  j                  r|j                  j                  | _        nd | _        g | _        d| _        d| _        d| _	        y Nr   )
r   r(   	weighting	use_finalfinalfinal_fnrI   minscorereplaced_timesskipped_timesr&   s       r   r(   zScoredCollector.prepareK  sa    $a9!!++(2288DM DM 
 r   c                 <    d| j                   j                         z
  S rh   )r4   scorerE   s     r   rG   zScoredCollector.sort_key^  s    4<<%%'''r   c                     t         r*   rC   r'   rL   rq   s      r   _collectzScoredCollector._collecta  s
     "!r   c                      y)NFr   r6   s    r   _use_block_qualityz"ScoredCollector._use_block_qualityg  s     r   c                     | j                   |z   }| j                  j                         }| j                  r| j                  | j                  ||      }| j                  ||      S r*   )r1   r4   rq   rl   r   rt   )r'   rA   rL   rq   s       r   r?   zScoredCollector.collectm  sT    j0""$==MM$"3"3]EJE }}]E22r   c              #     K   | j                   }| j                  }| j                         }| j                  }d}d}|j	                         r|r|dk(  s| j                   |k7  r{|j                  |xs d      x| _        }| xj
                  dz  c_        |j	                         sy | j                         }| j                  }| j                   |k7  rd}| j                   }|dz  }|r9|r7|5| xj                  |j                  |      z  c_        |j	                         sy |j                          |j                         }|j	                         ry y w)Nr   Tr   )
rm   r4   rv   rf   rP   rn   ro   skip_to_qualityrQ   rR   )r'   rm   r4   
usequalityrf   replacecountercheckqualitys          r   r@   zScoredCollector.matchesx  s7    ==,,,,.
,, ! !Q&$--8*C-4__X]-KKDL7''1,'",,.!%!8!8!:J%)\\N}}0'+#'==!#
 lx/C""g&=&=h&GG" ((***,
 #<<>LC !!s   EEEN)
   )r^   r_   r`   ra   re   r(   rG   rt   rv   r?   r@   r   r   r   rc   rc   >  s*    &("	3,*r   rc   c                   B    e Zd ZdZddZd Zd Zd Zd Zd Z	d Z
d	 Zy
)TopCollectorz>A collector that only returns the top "N" scored results.
    c                 Z    t        j                  | fi | || _        || _        d| _        y)z
        :param limit: the maximum number of results to return.
        :param usequality: whether to use block-quality optimizations. This may
            be useful for debugging.
        r   N)rc   re   limitrz   r   )r'   r   rz   rY   s       r   re   zTopCollector.__init__  s,     	  00
$
r   c                     | j                   xr= | j                  j                  j                   xr | j                  j                         S r*   )rz   r   ri   rj   r4   supports_block_qualityr6   s    r   rv   zTopCollector._use_block_quality  s@     :))33===:LL779	;r   c                 $    | j                          S r*   )rv   r6   s    r   r7   zTopCollector.computes_count  s    **,,,r   c                 L    | j                   j                  | j                        S r*   )r   docs_for_queryr    r6   s    r   r:   zTopCollector.all_ids  s    
   //77r   c                 l    | j                         r| j                  S t        | j                               S r*   )r7   r   r   r:   r6   s    r   r=   zTopCollector.count  s)     ::''r   c                     | j                   }| xj                  dz  c_        t        |      | j                  k  rt	        ||d|z
  f       d|z
  S ||d   d   kD  r#t        ||d|z
  f       |d   d   | _        d|z
  S y)Nr   r   )rI   r   r<   r   r   r	   rm   )r'   rL   rq   rI   s       r   rt   zTopCollector._collect  s    



a
 u:

"UUA$567u9U1Xa[  q='89:!!HQKDMu9r   c                     d|z
  }| j                   }t        t        |            D ]C  }||   d   |k(  s|j                  |       t	        |       |r|d   d   | _         y d| _         y  y r   )rI   r   r<   rJ   r   rm   )r'   rL   negatedrI   rM   s        r   rN   zTopCollector.remove  sq    m#

 E
# 	AQx{g%		!/4a ;<	r   c                     | j                   }|j                  d       |D cg c]  \  }}|d|z
  f }}}| j                  |      S c c}}w )NTreverser   )rI   sortr[   )r'   rI   rq   docnums       r   r]   zTopCollector.results  sP    
 



4
 :?@%V$@@}}U## As   A	N)r}   T)r^   r_   r`   ra   re   rv   r7   r:   r=   rt   rN   r]   r   r   r   r   r     s/    
;
-8(.	$r   r   c                   $    e Zd ZdZddZd Zd Zy)UnlimitedCollectorz5A collector that returns **all** scored results.
    c                 <    t         j                  |        || _        y r*   )rc   re   r   )r'   r   s     r   re   zUnlimitedCollector.__init__  s      &r   c                 |    | j                   j                  ||f       | j                  j                  |       d|z
  S rh   )rI   appendr%   addrs   s      r   rt   zUnlimitedCollector._collect  s3    

5-01&5yr   c                     | j                   j                  d | j                         | j                  | j                   | j                        S )Nc                     d| d   z
  | d   fS r   r   )xs    r   <lambda>z,UnlimitedCollector.results.<locals>.<lambda>  s    q1Q4x1&6 r   )keyr   r9   )rI   r   r   r[   r%   r6   s    r   r]   zUnlimitedCollector.results  s8     	

6M}}TZZ}<<r   N)F)r^   r_   r`   ra   re   rt   r]   r   r   r   r   r     s    
=r   r   c                   6    e Zd ZdZd	dZd Zd Zd Zd Zd Z	y)
SortingCollectorzA collector that returns results sorted by a given
    :class:`whoosh.sorting.Facet` object. See :doc:`/facets` for more
    information.
    c                     t         j                  |        t        j                  j	                  |      | _        || _        || _        y)z
        :param sortedby: see :doc:`/facets`.
        :param reverse: If True, reverse the overall results. Note that you
            can reverse individual facets in a multi-facet sort key as well.
        N)r   re   r
   
MultiFacetfrom_sortedby	sortfacetr   r   )r'   sortedbyr   r   s       r   re   zSortingCollector.__init__  s8     	4  ++99(C
r   c                     | j                   j                  |      | _        |j                  xs | j                  j                  }t        j	                  | |||j                  |             g | _        y NrU   )r   categorizerrU   r   r(   r$   rI   )r'   r   r    r!   rms        r   r(   zSortingCollector.prepare)  s_    >>55lC ""Dd&6&6&D&D$a21NO 
r   c                 j    t         j                  | ||       | j                  j                  ||       y r*   )r   r,   r   set_searcherr/   s      r   r,   z SortingCollector.set_subsearcher3  s*    !!$V<%%k6:r   c                 N    | j                   j                  | j                  |      S r*   )r   key_forr4   rE   s     r   rG   zSortingCollector.sort_key7  s    ''jAAr   c                     | j                   |z   }| j                  |      }| j                  j                  ||f       | j                  j                  |       |S r*   )r1   rG   rI   r   r%   r   )r'   rA   rL   sortkeys       r   r?   zSortingCollector.collect:  sJ    j0--
+

7M23&r   c                     | j                   }|j                  | j                         | j                  r|d | j                   }| j	                  || j
                        S )Nr   r9   )rI   r   r   r   r[   r%   r'   rI   s     r   r]   zSortingCollector.resultsA  sK    



4<<
(::+4::&E}}U4;;}77r   N)r}   F)
r^   r_   r`   ra   re   r(   r,   rG   r?   r]   r   r   r   r   r     s&    

;B8r   r   c                       e Zd Zd Zd Zd Zy)UnsortedCollectorc                 b    t         j                  | |||j                  d              g | _        y )N)ri   )r   r(   r$   rI   r&   s       r   r(   zUnsortedCollector.prepareJ  s(    $at1LM
r   c                     | j                   |z   }| j                  j                  d |f       | j                  j	                  |       y r*   )r1   rI   r   r%   r   )r'   rA   rL   s      r   r?   zUnsortedCollector.collectN  s7    j0

4/0&r   c                 T    | j                   }| j                  || j                        S )Nr9   )rI   r[   r%   r   s     r   r]   zUnsortedCollector.resultsS  s"    

}}U4;;}77r   N)r^   r_   r`   r(   r?   r]   r   r   r   r   r   I  s    '
8r   r   c                   x    e Zd ZdZd Zed        Zed        Zd Zd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Zd Zy)WrappingCollectorz:Base class for collectors that wrap other collectors.
    c                     || _         y r*   )childr'   r   s     r   re   zWrappingCollector.__init__^  s	    
r   c                 .    | j                   j                  S r*   )r   r   r6   s    r   r   zWrappingCollector.top_searchera  s    zz&&&r   c                 .    | j                   j                  S r*   )r   r!   r6   s    r   r!   zWrappingCollector.contexte  s    zz!!!r   c                 >    | j                   j                  |||       y r*   )r   r(   r&   s       r   r(   zWrappingCollector.preparei  s    

<G4r   c                     | j                   j                  ||       || _        | j                   j                  | _        | j                   j                  | _        y r*   )r   r,   r0   r4   r1   r/   s      r   r,   z!WrappingCollector.set_subsearcherl  s@    

"";7&zz))jj''r   c                 6    | j                   j                         S r*   )r   r:   r6   s    r   r:   zWrappingCollector.all_idsr      zz!!##r   c                 6    | j                   j                         S r*   )r   r=   r6   s    r   r=   zWrappingCollector.countu  s    zz!!r   c                 P    | j                         D ]  }| j                  |        y r*   )r@   r?   rE   s     r   r-   z!WrappingCollector.collect_matchesx  s#    ,,. 	%JLL$	%r   c                 8    | j                   j                  |      S r*   )r   rG   rE   s     r   rG   zWrappingCollector.sort_key|  s    zz"":..r   c                 8    | j                   j                  |      S r*   )r   r?   rE   s     r   r?   zWrappingCollector.collect  s    zz!!*--r   c                 8    | j                   j                  |      S r*   )r   rN   )r'   rL   s     r   rN   zWrappingCollector.remove  s    zz  //r   c                 6    | j                   j                         S r*   )r   r@   r6   s    r   r@   zWrappingCollector.matches  r   r   c                 8    | j                   j                          y r*   )r   r.   r6   s    r   r.   zWrappingCollector.finish  s    

r   c                 6    | j                   j                         S r*   )r   r]   r6   s    r   r]   zWrappingCollector.results  r   r   N)r^   r_   r`   ra   re   propertyr   r!   r(   r,   r:   r=   r-   rG   r?   rN   r@   r.   r]   r   r   r   r   r   Z  sk     ' ' " "5($"%/.0$$r   r   c                   6    e Zd ZdZd	dZd Zd Zd Zd Zd Z	y)
FilterCollectora^  A collector that lets you allow and/or restrict certain document numbers
    in the results::

        uc = collectors.UnlimitedCollector()

        ins = query.Term("chapter", "rendering")
        outs = query.Term("status", "restricted")
        fc = FilterCollector(uc, allow=ins, restrict=outs)

        mysearcher.search_with_collector(myquery, fc)
        print(fc.results())

    This collector discards a document if:

    * The allowed set is not None and a document number is not in the set, or
    * The restrict set is not None and a document number is in the set.

    (So, if the same document number is in both sets, that document will be
    discarded.)

    If you have a reference to the collector, you can use
    ``FilterCollector.filtered_count`` to get the number of matching documents
    filtered out of the results by the collector.
    Nc                 .    || _         || _        || _        y)a  
        :param child: the collector to wrap.
        :param allow: a query, Results object, or set-like object containing
            docnument numbers that are allowed in the results, or None (meaning
            everything is allowed).
        :param restrict: a query, Results object, or set-like object containing
            document numbers to disallow from the results, or None (meaning
            nothing is disallowed).
        N)r   allowrestrict)r'   r   r   r   s       r   re   zFilterCollector.__init__  s     

 r   c                     | j                   j                  |||       | j                  }| j                  }|j                  }|r ||      nd | _        |r ||      nd | _        d| _        y rh   )r   r(   r   r   _filter_to_comb_allow	_restrictfiltered_count)r'   r   r    r!   r   r   ftcs          r   r(   zFilterCollector.prepare  s[    

<G4

==**$)c%jt*2Xr   c              #      K   | j                   }| j                  }| j                  }|j                         D ]  }|r||vs|r||v r|  y wr*   )r   r   r   r:   )r'   r   r   r   rL   s        r   r:   zFilterCollector.all_ids  sS     

NN	"]]_ 	 MM7}	9	 s   AAc                     | j                   }|j                         r|j                         S t        | j	                               S r*   )r   r7   r=   r   r:   r   s     r   r=   zFilterCollector.count  s4    

!;;= ''r   c                 *   | j                   }| j                  }| j                  }||[| j                  }|j	                         D ]4  }| j
                  |z   }|||vs|
||v r|dz  }$|j                  |       6 || _        y |j                          y Nr   )r   r   r   r   r@   r1   r?   r-   )r'   r   r   r   r   rA   rL   s          r   r-   zFilterCollector.collect_matches  s    

NN	!6!00N#mmo *
 $j 8'M,G!--92L"a'Nj)* #1D !!#r   c                     | j                   j                         }| |_        | j                  |_        | j                  |_        | j                  |_        |S r*   )r   r]   rX   r   r   allowedr   
restrictedr'   rZ   s     r   r]   zFilterCollector.results  sD    JJ ..JJ	}}r   )NN)
r^   r_   r`   ra   re   r(   r:   r=   r-   r]   r   r   r   r   r     s%    2!	  ($(r   r   c                   0    e Zd ZdZddZd Zd Zd Zd Zy)	FacetCollectora  A collector that creates groups of documents based on
    :class:`whoosh.sorting.Facet` objects. See :doc:`/facets` for more
    information.

    This collector is used if you specify a ``groupedby`` parameter in the
    :meth:`whoosh.searching.Searcher.search` method. You can use the
    :meth:`whoosh.searching.Results.groups` method to access the facet groups.

    If you have a reference to the collector can also use
    ``FacetedCollector.facetmaps`` to access the groups directly::

        uc = collectors.UnlimitedCollector()
        fc = FacetedCollector(uc, sorting.FieldFacet("category"))
        mysearcher.search_with_collector(myquery, fc)
        print(fc.facetmaps)
    Nc                 h    || _         t        j                  j                  |      | _        || _        y)z
        :param groupedby: see :doc:`/facets`.
        :param maptype: a :class:`whoosh.sorting.FacetMap` type to use for any
            facets that don't specify their own.
        N)r   r
   Facetsfrom_groupedbyfacetsmaptype)r'   r   	groupedbyr   s       r   re   zFacetCollector.__init__  s(     
nn33I>r   c                    | j                   }i | _        i | _        |j                  }|j	                         D ]]  \  }}|j                  | j                        | j                  |<   |j                  |      }|| j                  |<   |xs |j                  }_ |j                  |      }| j                  j                  |||       y r   )r   	facetmapscategorizersrU   rI   mapr   r   r$   r   r(   )	r'   r   r    r!   r   rU   	facetnamefacetctrs	            r   r(   zFacetCollector.prepare  s    
   -- & 	?Iu(-		$,,(?DNN9%##L1C+.Di()>S->->M	? ++M+:

<G4r   c                     t         j                  | ||       t        | j                        D ]<  }|j	                  | j
                  j                  | j
                  j                         > y r*   )r   r,   r   r   r   r   r0   r1   )r'   r0   r1   r   s       r   r,   zFacetCollector.set_subsearcher,  sV    ))$VD &d&7&78 	PK$$TZZ%;%;TZZ=N=NO	Pr   c                    | j                   j                  }|| j                   j                  z   }| j                   j                  |      }t	        | j
                        D ]  \  }}| j                  |   j                  }|j                  r1|j                  ||      D ]  } ||j                  |      ||        \|j                  ||      }|j                  |      } ||||        |S r*   )r   r4   r1   r?   r   r   r   r   allow_overlapkeys_forkey_to_namer   )	r'   rA   r4   rL   r   namer   r   r   s	            r   r?   zFacetCollector.collect3  s    **$$"TZZ%6%66 **$$Z0 "+4+<+<!= 
	1D+..&**C ((&//D NC//4mWMN "))':>!--c2C0
	1 r   c                 \    | j                   j                         }| j                  |_        |S r*   )r   r]   r   
_facetmapsr   s     r   r]   zFacetCollector.resultsJ  s$    JJ ~~r   r*   )	r^   r_   r`   ra   re   r(   r,   r?   r]   r   r   r   r   r     s!    "	5,P.r   r   c                   <    e Zd ZdZd
dZd Zd Zd Zd Zd Z	d	 Z
y)CollapseCollectora  A collector that collapses results based on a facet. That is, it
    eliminates all but the top N results that share the same facet key.
    Documents with an empty key for the facet are never eliminated.

    The "top" results within each group is determined by the result ordering
    (e.g. highest score in a scored search) or an optional second "ordering"
    facet.

    If you have a reference to the collector you can use
    ``CollapseCollector.collapsed_counts`` to access the number of documents
    eliminated based on each key::

        tc = TopCollector(limit=20)
        cc = CollapseCollector(tc, "group", limit=3)
        mysearcher.search_with_collector(myquery, cc)
        print(cc.collapsed_counts)

    See :ref:`collapsing` for more information.
    Nc                     || _         t        j                  j                  |      | _        || _        |r%t        j                  j                  |      | _        yd| _        y)aJ  
        :param child: the collector to wrap.
        :param keyfacet: a :class:`whoosh.sorting.Facet` to use for collapsing.
            All but the top N documents that share a key will be eliminated
            from the results.
        :param limit: the maximum number of documents to keep for each key.
        :param order: an optional :class:`whoosh.sorting.Facet` to use
            to determine the "top" document(s) to keep when collapsing. The
            default (``orderfaceet=None``) uses the results order (e.g. the
            highest score in a scored search).
        N)r   r
   r   r   keyfacetr   
orderfacet)r'   r   r   r   orders        r   re   zCollapseCollector.__init__g  sL     
**88B
%00>>uEDO"DOr   c                    | j                   j                  |      | _        d | _        | j                  r | j                  j                  |      | _        t        t              | _        t        t              | _	        d| _
        |j                  xs< | j                  j                  xs$ | j                  xr | j                  j                  }| j                  j                  |||j                  |             y )Nr   r   )r   r   keyerordererr   r   listlistsintcollapsed_countscollapsed_totalrU   r   r(   r$   )r'   r   r    r!   rU   s        r   r(   zCollapseCollector.prepare}  s    ]]..|<
????66|DDL !&
 !,C 0  !.. F

00FD$,,*D*D 	 	

<";;];C	Er   c                     t         j                  | ||       | j                  j                  ||       | j                  r| j                  j                  ||       y y r*   )r   r,   r   r   r   r/   s      r   r,   z!CollapseCollector.set_subsearcher  sJ    ))$VD 	

V4<<LL%%k6: r   c              #   r  K   | j                   }| j                  }t        t              }|j	                         D ]y  \  }}| j                  ||       |j                  }| j                  }|j                         D ]7  }|j                  ||      }	|	|	|v r	||	   |k\  r$||	xx   dz  cc<   ||z    9 { y wr   )
r   r   r   r   subsearchersr,   r4   r   r@   r   )
r'   r   r   countersr0   r1   r4   r   rA   ckeys
             r   r:   zCollapseCollector.all_ids  s     



s##(#5#5#7 	*K  f5mmGJJE#mmo *
}}Wj9#x'HTNe,C  !+z))*		*s   B5B7c                     | j                   j                         r'| j                   j                         | j                  z
  S t	        | j                               S r*   )r   r7   r=   r   r   r:   r6   s    r   r=   zCollapseCollector.count  sA    ::$$&::##%(<(<<<''r   c                    | j                   }| j                  }| j                  }| j                  }| j                  }| j
                  }|j                  }|j                  }|j                         D ]  }	|j                  |j                  ||	            }
|
s|j                  |	       8||	z   }|r|j                  |j                  |	      }n|j                  |	      }||
   }d}t        |      |k  rd}n/||d   d   k  r$|j                  |j                         d          d}|r t!        |||f       |j                  |	       ||
xx   dz  cc<   | xj"                  dz  c_         y )NFTr   r   )r   r   r   r   r   r   r4   r1   r@   r   r   r?   rG   r<   rN   rJ   r   r   )r'   r   r   r   r   r   r   r4   r1   rA   r  rL   r   bestr   s                  r   r-   z!CollapseCollector.collect_matches  sM   





,,00

----/ $	.J$$U]]7J%GHDj) & 3%ooemmZHG $nnZ8G T{t9u$CtBx{*
 LLA/C4'=!9:MM*- %T*a/*((A-(I$	.r   c                 \    | j                   j                         }| j                  |_        |S r*   )r   r]   r   r   s     r   r]   zCollapseCollector.results  s'    JJ !22r   )r   N)r^   r_   r`   ra   re   r(   r,   r:   r=   r-   r]   r   r   r   r   r   R  s,    (#,E2;*$(..`r   r   c                   6    e Zd ZdZd	dZd Zd Zd Zd Zd Z	y)
TimeLimitCollectoraI  A collector that raises a :class:`TimeLimit` exception if the search
    does not complete within a certain number of seconds::

        uc = collectors.UnlimitedCollector()
        tlc = TimeLimitedCollector(uc, timelimit=5.8)
        try:
            mysearcher.search_with_collector(myquery, tlc)
        except collectors.TimeLimit:
            print("The search ran out of time!")

        # We can still get partial results from the collector
        print(tlc.results())

    IMPORTANT: On Unix systems (systems where signal.SIGALRM is defined), the
    code uses signals to stop searching immediately when the time limit is
    reached. On Windows, the OS does not support this functionality, so the
    search only checks the time between each found document, so if a matcher
    is slow the search could exceed the time limit.
    c                     || _         || _        || _        |rddl}|xr t	        |d      | _        nd| _        d| _        d| _        y)a  
        :param child: the collector to wrap.
        :param timelimit: the maximum amount of time (in seconds) to
            allow for searching. If the search takes longer than this, it will
            raise a ``TimeLimit`` exception.
        :param greedy: if ``True``, the collector will finish adding the most
            recent hit before raising the ``TimeLimit`` exception.
        :param use_alarm: if ``True`` (the default), the collector will try to
            use signal.SIGALRM (on UNIX).
        r   NSIGALRMF)r   	timelimitgreedysignalhasattr	use_alarmtimertimedout)r'   r   r  r  r  r  s         r   re   zTimeLimitCollector.__init__  sG     
"&E769+EDN"DN
r   c                 J   | j                   j                  |||       d| _        | j                  r*dd l}|j	                  |j
                  | j                         t        j                  | j                  | j                        | _        | j                  j                          y )NFr   )r   r(   r  r  r  r  _was_signaled	threadingTimerr  	_timestopr  start)r'   r   r    r!   r  s        r   r(   zTimeLimitCollector.prepare  sm    

<G4>>MM&..$*<*<= __T^^T^^D


r   c                     d | _         d| _        | j                  r7dd l}t	        j
                  t	        j                         |j                         y y )NTr   )r  r  r  r  oskillgetpidr  )r'   r  s     r   r  zTimeLimitCollector._timestop(  s7    
>>GGBIIK0 r   c                     t         r*   )r   )r'   signumframes      r   r  z TimeLimitCollector._was_signaled2  s    r   c                     | j                   }| j                  }|j                         D ]9  }| j                  r|st        |j                  |       | j                  s5t         y r*   )r   r  r@   r  r   r?   )r'   r   r  rA   s       r   r-   z"TimeLimitCollector.collect_matches5  sS    

--/ 	 J }}VMM*% }}	 r   c                     | j                   r| j                   j                          d | _         | j                  j                          y r*   )r  cancelr   r.   r6   s    r   r.   zTimeLimitCollector.finishF  s0    ::JJ


r   N)FT)
r^   r_   r`   ra   re   r(   r  r  r-   r.   r   r   r   r  r    s%    (01 "r   r  c                   2    e Zd ZdZefdZd Zd Zd Zd Z	y)TermsCollectora  A collector that remembers which terms appeared in which terms appeared
    in each matched document.

    This collector is used if you specify ``terms=True`` in the
    :meth:`whoosh.searching.Searcher.search` method.

    If you have a reference to the collector can also use
    ``TermsCollector.termslist`` to access the term lists directly::

        uc = collectors.UnlimitedCollector()
        tc = TermsCollector(uc)
        mysearcher.search_with_collector(myquery, tc)
        # tc.termdocs is a dictionary mapping (fieldname, text) tuples to
        # sets of document numbers
        print(tc.termdocs)
        # tc.docterms is a dictionary mapping docnums to lists of
        # (fieldname, text) tuples
        print(tc.docterms)
    c                      || _         || _        y r*   )r   settype)r'   r   r(  s      r   re   zTermsCollector.__init__d  s    
r   c                     | j                   j                  |||j                  d             t        d       | _        t        t
              | _        y )NTr   c                      t        d      S )NIr   r   r   r   r   z(TermsCollector.prepare.<locals>.<lambda>m  s
    E#J r   )r   r(   r$   r   termdocsr   doctermsr&   s       r   r(   zTermsCollector.prepareh  s>    

<GKKdK,KL $$67#D)r   c                     t         j                  | ||       t        | j                  j                  j                               | _        y r*   )r   r,   r   r   r4   term_matcherstermmatchersr/   s      r   r,   zTermsCollector.set_subsearcherq  s6    ))$VD !!3!3!A!A!CDr   c                 h   | j                   }| j                  }| j                  }|j                  |       |j                  |z   }| j
                  D ]_  }|j                         s|j                         |k(  s(|j                         }||   j                  |       ||   j                  |       a y r*   )
r   r,  r-  r?   r1   r0  rP   rQ   termr   )r'   rA   r   r,  r-  rL   tmr2  s           r   r?   zTermsCollector.collectw  s    

====j!z1 ## 	5B||~"%%'Z"7wwy%%m4'..t4	5r   c                     | j                   j                         }t        | j                        |_        t        | j                        |_        |S r*   )r   r]   dictr,  r-  r   s     r   r]   zTermsCollector.results  s9    JJ $--(
$--(
r   N)
r^   r_   r`   ra   r$   re   r(   r,   r?   r]   r   r   r   r&  r&  O  s&    ( '* *E5$r   r&  )&ra   r  r  r   bisectr   collectionsr   heapqr   r   r	   whooshr
   whoosh.compatr   r   r   r   whoosh.searchingr   r   whoosh.utilr   r   objectr   rc   r   r   r   r   r   r   r   r   r  r&  r   r   r   <module>r>     s   80d 
    # 0 0  G G / 
S" S"pf*i f*RT$? T$n= =2/8y /8d8	 8"2$	 2$nc' cPT& TrW) Wx\* \B>& >r   