
    #h6P                     D   d dl mZ d dlZd dlZd dlmZ d dlmZmZ d dlm	Z	 ddl
mZmZmZmZmZmZ ddlmZmZmZ d dlZd	ad
adadadad Zd Z ed      fdZedd       Zedd       Zed        Z ddZ!edd       Z"d dZ# G d de$      Z%ed        Z&d Z'd Z(y)!    )unicode_literalsN)BeautifulSoup)datetime	timedelta)Decimal   )	PageErrorDisambiguationErrorRedirectErrorHTTPTimeoutErrorWikipediaExceptionODD_ERROR_MESSAGE)cachestdout_encodedebugz!http://en.wikipedia.org/w/api.phpFz3wikipedia (https://github.com/goldsmith/Wikipedia/)c                 |    d| j                         z   dz   at        t        t        fD ]  }|j                           y)a~  
  Change the language of the API being requested.
  Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_.

  After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared.

  .. note:: Make sure you search for page titles in the language that you have set.
  zhttp://z.wikipedia.org/w/api.phpN)lowerAPI_URLsearchsuggestsummaryclear_cache)prefixcached_funcs     P/var/www/html/sandstorm/venv/lib/python3.12/site-packages/wikipedia/wikipedia.pyset_langr      s<     &)CC'gw/ k    c                     | a y)z
  Set the User-Agent string to be used for all requests.

  Arguments:

  * user_agent_string - (string) a string specifying the User-Agent header
  N)
USER_AGENT)user_agent_strings    r   set_user_agentr!   &   s	     !*r   2   )millisecondsc                     | a | sdaday|aday)a  
  Enable or disable rate limiting on requests to the Mediawiki servers.
  If rate limiting is not enabled, under some circumstances (depending on
  load on Wikipedia, the number of requests you and other `wikipedia` users
  are making, and other factors), Wikipedia may return an HTTP timeout error.

  Enabling rate limiting generally prevents that issue, but please note that
  HTTPTimeoutError still might be raised.

  Arguments:

  * rate_limit - (Boolean) whether to enable rate limiting or not

  Keyword arguments:

  * min_wait - if rate limiting is enabled, `min_wait` is a timedelta describing the minimum time to wait before requests.
         Defaults to timedelta(milliseconds=50)
  N)
RATE_LIMITRATE_LIMIT_MIN_WAITRATE_LIMIT_LAST_CALL)
rate_limitmin_waits     r   set_rate_limitingr*   2   s(    . *	  #r   c                 0   dd||| d}|rd|d<   t        |      }d|v r&|d   d   dv rt        |       t        |d   d         d	 |d
   d   D        }|r7|d
   j                  d      rt	        |      |d
   d   d   fS t	        |      dfS t	        |      S )z
  Do a Wikipedia search for `query`.

  Keyword arguments:

  * results - the maxmimum number of results returned
  * suggestion - if True, return results and suggestion (if any) in a tuple
  r    )listsrpropsrlimitlimitsrsearch
suggestionsrinfoerrorinfozHTTP request timed out.zPool queue is fullc              3   &   K   | ]	  }|d      ywtitleN .0ds     r   	<genexpr>zsearch.<locals>.<genexpr>o   s     G1AgJG   query
searchinfoN)_wiki_requestr   r   getr-   )r@   resultsr2   search_paramsraw_resultssearch_resultss         r   r   r   R   s     - *M(m,+7F#'XXU##{73F;<<GG(<X(FG.7-.!;w#7#El#SSS.!4''	n	r   c                 n   d|dj                  | |      |d}|r||d<   t        |      }d|v r6|d   d   dv rt        dj                  | |            t        |d   d         |d   j	                  d	d
      }|r"d |j                         D        }t        |      S d |d   d   D        }t        |      S )a  
  Do a wikipedia geo search for `latitude` and `longitude`
  using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData

  Arguments:

  * latitude (float or decimal.Decimal)
  * longitude (float or decimal.Decimal)

  Keyword arguments:

  * title - The title of an article to search for
  * results - the maximum number of results returned
  * radius - Search radius in meters. The value must be between 10 and 10000
  	geosearchz{0}|{1})r-   gsradiusgscoordgslimittitlesr4   r5   r6   r@   pagesNc              3   8   K   | ]  \  }}|d k7  s|d     yw)z-1r9   Nr:   )r<   kvs      r   r>   zgeosearch.<locals>.<genexpr>   s     OTQQ$YajOs   
c              3   &   K   | ]	  }|d      ywr8   r:   r;   s     r   r>   zgeosearch.<locals>.<genexpr>   s     LQajLr?   )formatrB   r   r   rC   itemsr-   )	latitude	longituder9   rD   radiusrE   rF   search_pagesrG   s	            r   rI   rI   z   s    & )4	- #M(m,+7F#'XXY--h	BCC{73F;<<W%))'48,O\-?-?-AON 
n	 M+g*>{*KLN	n	r   c                 n    dddd}| |d<   t        |      }|d   j                  d      r|d   d   d   S y)	zk
  Get a Wikipedia search suggestion for `query`.
  Returns a string or None if no suggestion was found.
  r   r2   r,   )r-   r3   r.   r1   r@   rA   N)rB   rC   )r@   rE   
raw_results      r   r   r      sU     -
 $-
]+*\*g|,\::	r   c                     dd| d}t        |      }|d   d   D cg c]  }|d   	 }}t        |      dk(  r|d   S |S c c}w )z
  Get a list of random Wikipedia article titles.

  .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.

  Keyword arguments:

  * pages - the number of random pages returned (max of 10)
  randomr   )r-   rnnamespacernlimitr@   r9   r   )rB   len)rN   query_paramsrequestpagerM   s        r   r\   r\      sb     , ,''&-g&6x&@AdDMA&A[A!9	- Bs   ?c                     t        | ||      }|j                  } |j                  }dd| d}|r||d<   n|r||d<   nd|d<   t        |      }|d   d	   |   d
   }	|	S )a  
  Plain text summary of the page.

  .. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default

  Keyword arguments:

  * sentences - if set, return the first `sentences` sentences (can be no greater than 10).
  * chars - if set, return only the first `chars` characters (actual text returned may be slightly longer).
  * auto_suggest - let Wikipedia find a valid page title for the query
  * redirect - allow redirection without raising RedirectError
  )auto_suggestredirectextractsr,   )propexplaintextrM   exsentencesexcharsexintror@   rN   extract)rb   r9   pageidrB   )
r9   	sentencescharsrd   re   	page_inform   r`   ra   r   s
             r   r   r      s    " 5|hG)
//%& , "+L#L L,''GW%f-i8'	.r   c                     | +|rt        | dd      \  }}	 |xs |d   } t        | ||      S |t        ||      S t	        d      # t        $ r t        |       w xY w)a  
  Get a WikipediaPage object for the page with title `title` or the pageid
  `pageid` (mutually exclusive).

  Keyword arguments:

  * title - the title of the page to load
  * pageid - the numeric pageid of the page to load
  * auto_suggest - let Wikipedia find a valid page title for the query
  * redirect - allow redirection without raising RedirectError
  * preload - load content, summary, images, references, and links during initialization
  r   T)rD   r2   r   re   preload)rm   rs   ,Either a title or a pageid must be specified)r   
IndexErrorr	   WikipediaPage
ValueError)r9   rm   rd   re   rs   rD   r2   s          r   rb   rb      s     "5!Egz(gaj 7CC88
C
DD  s   	A Ac                       e Zd ZdZddZd Zd ZddZd Ze	d        Z
d	 Ze	d
        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Ze	d        Zd Zy)rv   zd
  Contains data from a Wikipedia page.
  Uses property methods to filter data from the raw HTML.
  Nc                     ||| _         |xs || _        n||| _        nt        d      | j	                  ||       |rdD ]  }t        | |        y y )Nrt   rr   )contentr   images
referenceslinkssections)r9   original_titlerm   rw   _WikipediaPage__loadgetattr)selfr9   rm   re   rs   r   rg   s          r   __init__zWikipediaPage.__init__"  sf    dj*3ed		dkEFFKK7K3U $d r   c                 J    t        dj                  | j                              S )Nz<WikipediaPage '{}'>)r   rS   r9   r   s    r   __repr__zWikipediaPage.__repr__1  s    299$**EFFr   c                     	 | j                   |j                   k(  xr4 | j                  |j                  k(  xr | j                  |j                  k(  S #  Y yxY w)NF)rm   r9   url)r   others     r   __eq__zWikipediaPage.__eq__4  sP    u||# 	"JJ%++%	"HH		!
s   AA Ac           
         ddddd}t        | dd      s| j                  |d<   n| j                  |d	<   t        |      }|d
   }t	        |d   j                               d   }|d   |   }d|v r7t        | d      rt        | j                        t        | j                        d|v r|rn|d   d   }d|v r+|d   d   }	|	d   | j                  k(  sJ t               |	d   }
n| j                  }
|d   |
k(  sJ t               | j                  |d   ||       yt        t        | d|d               d|v rddddd}t        | d      r| j                  |d	<   n| j                  |d<   t        |      }|d
   d   |   d   d   d   }t        |      j                  d      }|D cg c](  }ddj                  |j                  dg             vs'|* }}|D cg c])  }|j                  s|j                  j!                         + }}t#        t        | d|d         |      || _        |d   | _        |d   | _        yc c}w c c}w )z
    Load basic information from Wikipedia.
    Confirm that page exists and is not a disambiguation/redirect.

    Does not need to be called manually, should be called automatically during __init__.
    zinfo|pagepropsr   disambiguationr,   )rg   inpropppprop	redirectsrm   NrM   pageidsr@   rN   r   missingr9   )rm   r   
normalizedfromtorr   	pageprops	revisionsrz   r   )rg   rvproprvparservlimit*li
tocsectionclassfullurl)r   r9   rm   rB   r-   keyshasattrr	   r   r   r   r   find_alljoinrC   aget_textr
   r   )r   re   rs   r`   ra   r@   rm   rb   r   r   
from_titlehtmllisr   filtered_lismay_refer_tos                   r   __loadzWikipediaPage.__load>  s|     	L 44(#zzl8 $l9L)GGE%.%%'(+F>&!D D	w	

##t{{++ 
		+&q)	5 \*1-*F#tzz1
D3D
D1!$'* zz* J.A0AA. 	io'J GD'4=ABB
 
		l 
x	 "&++Y!%Xl+gWg&v.{;A>sCd$((.c#&[RlbggbffWVXFY>Z.Zb[l[0<E"bddmmoElEgtG} E|TT dk=djidh \Es   &(H?H?I+Ic              #   d  K   |j                  | j                         i }|j                  dd      }	 |j                         }|j                  |       t	        |      }d|vry|d   d   }d|v r|j                         D ]  }|  n|| j                     |   D ]  }|  d|vry|d   }}w)zN
    Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries
    rg   Nr@   rN   	generatorcontinue)update!_WikipediaPage__title_query_paramrC   copyrB   valuesrm   )r   r`   last_continuerg   paramsra   rN   datums           r   __continued_queryzWikipediaPage.__continued_query  s      001MFD)D
  "fmmM"f%g		gw'e		$\\^ 	E+	 4;;'- 	E+	 
7	"j)m) s   B.B0c                 T    t        | dd       d| j                  iS d| j                  iS )Nr9   rM   r   )r   r9   rm   r   s    r   __title_query_paramz!WikipediaPage.__title_query_param  s/    tWd#/

##%%r   c                     t        | dd      s@dddd| j                  d}t        |      }|d   d	   | j                     d   d
   d   | _        | j                  S )zW
    Get full page HTML.

    .. warning:: This can get pretty slow on long pages.
    _htmlFr   rz   r   r,   )rg   r   r   r   rM   r@   rN   r   r   )r   r9   rB   rm   r   r   r`   ra   s      r   r   zWikipediaPage.html  si     4%(**l l+g7#G,T[[9+FqI#Ndj::r   c                 t   t        | dd      sdddd}t        | dd      | j                  |d	<   n| j                  |d
<   t        |      }|d   d   | j                     d   | _        |d   d   | j                     d   d   d   | _        |d   d   | j                     d   d   d   | _        | j                  S )zS
    Plain text content of the page, excluding images, tables, and other data.
    _contentFzextracts|revisionsr,   ids)rg   rh   r   r9   NrM   r   r@   rN   rl   r   r   revidparentid)r   r9   rm   rB   r   _revision_id
_parent_idr   s      r   rz   zWikipediaPage.content  s     4U+$l
 T7D)1"&**h	#';;i	 l+g!'*73DKK@Kdm!'*73DKK@MaPQXYd!'*73DKK@MaPQ[\do==r   c                 L    t        | dd      s| j                   | j                  S )a4  
    Revision ID of the page.

    The revision ID is a number that uniquely identifies the current
    version of the page. It can be used to create the permalink or for
    other direct API calls. See `Help:Page history
    <http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more
    information.
    _revidF)r   rz   r   r   s    r   revision_idzWikipediaPage.revision_id  s#     45)
llr   c                 L    t        | dd      s| j                   | j                  S )z
    Revision ID of the parent version of the current revision of this
    page. See ``revision_id`` for more information.
    	_parentidF)r   rz   r   r   s    r   	parent_idzWikipediaPage.parent_id  s!     4e,
ll??r   c                     t        | dd      sZdddd}t        | dd      | j                  |d<   n| j                  |d	<   t        |      }|d
   d   | j                     d   | _        | j                  S )z)
    Plain text summary of the page.
    _summaryFrf   r,   )rg   rh   rk   r9   NrM   r   r@   rN   rl   )r   r9   rm   rB   r   r   s      r   r   zWikipediaPage.summary  s     4U+l
 T7D)1"&**h	#';;i	 l+gg&w/<YGdm==r   c                     t        | dd      s6| j                  ddddd      D cg c]  }d|v r|d   d   d    c}| _        | j                  S c c}w )	z-
    List of URLs of images on the page.
    _imagesFr{   max	imageinfor   )r   gimlimitrg   iipropr   )r   _WikipediaPage__continued_queryr   )r   rb   s     r   r{   zWikipediaPage.images  sr     4E* **	,
 	 $ 	[!U#	dl <<	s   Ac                    t        | dd      sqdd| j                  d}t        |      }d|v rK|d   d   | j                     d   }t	        |d   d	         t	        |d   d
         f| _        | j
                  S d| _        | j
                  S )z=
    Tuple of Decimals in the form of (lat, lon) or None
    _coordinatesFcoordinatesr   )rg   colimitrM   r@   rN   r   latlonN)r   r9   rB   rm   r   r   )r   r`   ra   r   s       r   r   zWikipediaPage.coordinates+  s    
 4/**l l+g	G	g&w/<]K$[^E%:;W[QR^TYEZ=[\  !r   c                     t        | dd      s3d }| j                  ddd      D cg c]  } ||d          c}| _        | j                  S c c}w )z
    List of URLs of external links on a page.
    May include external links within page that aren't technically cited anywhere.
    _referencesFc                 2    | j                  d      r| S d| z   S )Nhttpzhttp:)
startswith)r   s    r   add_protocolz.WikipediaPage.references.<locals>.add_protocolI  s    nnV,s?'C-?r   extlinksr   )rg   ellimitr   )r   r   r   )r   r   links      r   r|   zWikipediaPage.referencesA  se     4.@
 **,
  	T#Yd s   Ac                     t        | dd      s+| j                  dddd      D cg c]  }|d   	 c}| _        | j                  S c c}w )z
    List of titles of Wikipedia page links on a page.

    .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
    _linksFr}   r   r   )rg   plnamespacepllimitr9   )r   r   r   )r   r   s     r   r}   zWikipediaPage.linksV  sZ     45) **,
  	Wdk ;;s   Ac                     t        | dd      sM| j                  ddd      D cg c]  }|d   	 c}D cg c]  }t        j                  dd|       c}| _        | j                  S c c}w c c}w )	z'
    List of categories of a page.
    _categoriesF
categoriesr   )rg   cllimitr9   z
^Category:r,   )r   r   resubr   )r   r   xs      r   r   zWikipediaPage.categoriesj  s{     4. **,
 	 
g 		1"&&A6 	d 		s
   A'A,c                     t        | dd      sIddd}|j                  | j                         t        |      }|d   d   D cg c]  }|d   	 c}| _        | j                  S c c}w )zH
    List of section titles from the table of contents on the page.
    	_sectionsFparser~   )actionrg   line)r   r   r   rB   r   )r   r`   ra   sections       r   r~   zWikipediaPage.sections{  sm     4e,l $223l+g7>w7G
7STGTdn>> Us   A#c                 l   dj                  |      }	 | j                  j                  |      t        |      z   }	 | j                  j                  d|      }| j                  || j                  d      j                         S # t        $ r Y yw xY w# t        $ r t        | j                        }Y [w xY w)a  
    Get the plain text content of a section from `self.sections`.
    Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string.

    This is a convenience method that wraps self.content.

    .. warning:: Calling `section` on a section that has subheadings will NOT return
           the full text of all of the subsections. It only gets the text between
           `section_title` and the next subheading, which is often empty.
    z== {} ==Nz===)rS   rz   indexr_   rw   lstripstrip)r   section_titler   r   
next_indexs        r   r   zWikipediaPage.section  s       /Gll  )CL8e%<<%%dE2j <<j)005;;==  
  %t||$j%s"   'B B 	BBB32B3)NNTFr,   )TF)__name__
__module____qualname____doc__r   r   r   r   r   propertyr   r   rz   r   r   r   r{   r   r|   r}   r   r~   r   r:   r   r   rv   rv     s	   
GP!d*> & &*  ,  " 
 
  *  &  *  (  &     ">r   rv   c                  f    t        ddd      } | d   d   }|D ci c]  }|d   |d    c}S c c}w )a5  
  List all the currently supported language prefixes (usually ISO language code).

  Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests
  results from.

  Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes,
  use `wikipedia.languages().keys()`.
  siteinfo	languages)metasipropr@   coder   )rB   )responser   langs      r   r   r     sY      (
 w,) 
 	L$s)
  
s   .c                  2    ddl } | j                  dd       y)zA
  Open up the Wikimedia donate page in your favorite browser.
  r   NzLhttps://donate.wikimedia.org/w/index.php?title=Special:FundraiserLandingPage   )new)
webbrowseropen)r  s    r   donater
    s     //`fg/hr   c                    d| d<   d| vrd| d<   dt         i}t        rvt        rpt        t        z   t	        j
                         kD  rNt        t        z   t	        j
                         z
  }t        j                  t        |j                                      t        j                  t        | |      }t        rt	        j
                         a|j                         S )zz
  Make a request to the Wikipedia API using the given search parameters.
  Returns a parsed dict of the JSON response.
  jsonrS   r   r@   z
User-Agent)r   headers)r   r%   r'   r&   r   nowtimesleepinttotal_secondsrequestsrC   r   r  )r   r  	wait_timers       r   rB   rB     s     &	V	F8 *' (..?
 &(;;x||~MIJJs9**,-.ll767;!#<<>	
/r   )
   F)Nr  i  )r   )r   r   TT)NNTTF))
__future__r   r  r  bs4r   r   r   decimalr   
exceptionsr	   r
   r   r   r   r   utilr   r   r   r   r   r%   r&   r'   r   r   r!   r*   r   rI   r   r\   r   rb   objectrv   r   r
  rB   r:   r   r   <module>r     s    '    ( ) ) . - 	
-
  B
 	! ,5"+E @ $ $N ( (V  *4 $ $NE<H>F H>V  .ir   