
    0PhLQ                        d Z ddlZddl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	 ddl
mZm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 dd	lmZmZmZ dd
lmZ ddlm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z'  ej(        e)          Z* e#ddd          Z+dZ,dZ-dZ.d Z/d Z0 ej1        d          Z2d Z3d Z4 ee5ej6        dg eh d          gddgdgdge7gdgdg eeddd          g eed dd!          gd"
d#$          dd%dd#d&d'd#d(d)d*d"
d+            Z8 e eh d          ge7ge5ej6        dgdgdgdgdg eeddd          g eed dd!          gd,	d#$          d%d'dd#d(d#d(d)d*d,	d-            Z9dS ).a  Caching loader for the 20 newsgroups text classification dataset.


The description of the dataset is available on the official website at:

    http://people.csail.mit.edu/jrennie/20Newsgroups/

Quoting the introduction:

    The 20 Newsgroups data set is a collection of approximately 20,000
    newsgroup documents, partitioned (nearly) evenly across 20 different
    newsgroups. To the best of my knowledge, it was originally collected
    by Ken Lang, probably for his Newsweeder: Learning to filter netnews
    paper, though he does not explicitly mention this collection. The 20
    newsgroups collection has become a popular data set for experiments
    in text applications of machine learning techniques, such as text
    classification and text clustering.

This dataset loader will download the recommended "by date" variant of the
dataset and which features a point in time split between the train and
test sets. The compressed dataset size is around 14 Mb compressed. Once
uncompressed the train set is 52 MB and the test set is 34 MB.
    N)suppress)IntegralReal   )preprocessing)CountVectorizer)Bunchcheck_random_state)Interval
StrOptionsvalidate_params)tarfile_extractall   )get_data_home
load_files)RemoteFileMetadata_convert_data_dataframe_fetch_remote_pkl_filepath
load_descrz20news-bydate.tar.gzz.https://ndownloader.figshare.com/files/5975967@8f1b2514ca22a5ade8fbb9cfa5727df95fa587f4c87b786e15c759fa66d95610)filenameurlchecksumz20news-bydate.pkzz20news-bydate-trainz20news-bydate-testc                    t           j                            | t                    }t           j                            | t                    }t          j        | d           t                              dt          j	                   t          t          | ||          }t                              d|           t          j        |d          5 }t          ||            ddd           n# 1 swxY w Y   t          t                     5  t          j        |           ddd           n# 1 swxY w Y   t%          t'          |d	
          t'          |d	
                    }t)          j        t-          j        |          d          }	t          |d          5 }
|
                    |	           ddd           n# 1 swxY w Y   t3          j        |            |S )zADownload the 20 newsgroups data and stored it as a zipped pickle.T)exist_okz#Downloading dataset from %s (14 MB))dirname	n_retriesdelayzDecompressing %szr:gz)pathNlatin1)encodingtraintest
zlib_codecwb)osr    joinTRAIN_FOLDERTEST_FOLDERmakedirsloggerinfoARCHIVEr   r   debugtarfileopenr   r   FileNotFoundErrorremovedictr   codecsencodepickledumpswriteshutilrmtree)
target_dir
cache_pathr   r   
train_path	test_patharchive_pathfpcachecompressed_contentfs              c/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/datasets/_twenty_newsgroups.py_download_20newsgroupsrG   G   sY   j,77JZ55IK
T****
KK5w{CCC y  L LL#\222	lF	+	+ 0r2J////0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
#	$	$    
	,                              h777	H555  E  v|E':':LII	j$		 $1	"###$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ M*Ls6   C,,C03C0D,,D03D0F??GGc                 8    |                      d          \  }}}|S )z
    Given text in "news" format, strip the headers, by removing everything
    before the first blank line.

    Parameters
    ----------
    text : str
        The text from which to remove the signature block.
    z

)	partition)text_before
_blanklineafters       rF   strip_newsgroup_headerrN   g   s!     "&!7!7GZL    zF(writes in|writes:|wrote:|says:|said:|^In article|^Quoted from|^\||^>)c                 j    d |                      d          D             }d                    |          S )a:  
    Given text in "news" format, strip lines beginning with the quote
    characters > or |, plus lines that often introduce a quoted section
    (for example, because they contain the string 'writes:'.)

    Parameters
    ----------
    text : str
        The text from which to remove the signature block.
    c                 F    g | ]}t                               |          |S  )	_QUOTE_REsearch).0lines     rF   
<listcomp>z+strip_newsgroup_quoting.<locals>.<listcomp>   s+    RRR49;K;KD;Q;QR$RRRrO   
)splitr)   )rJ   
good_liness     rF   strip_newsgroup_quotingr[   z   s6     SR4::d#3#3RRRJ99Z   rO   c                 L   |                                                      d          }t          t          |          dz
  dd          D ]7}||         }|                                                      d          dk    r n8|dk    rd                    |d|                   S | S )a  
    Given text in "news" format, attempt to remove a signature block.

    As a rough heuristic, we assume that signatures are set apart by either
    a blank line or a line made of hyphens, and that it is the last such line
    in the file (disregarding blank lines at the end).

    Parameters
    ----------
    text : str
        The text from which to remove the signature block.
    rX   r   - r   N)striprY   rangelenr)   )rJ   linesline_numrV   s       rF   strip_newsgroup_footerre      s     JJLLt$$E#e**q."b11  X::<<c""b((E ) !||yyyy)***rO   >   allr%   r$   z
array-likebooleanrandom_stateleft)closedg        neither)
	data_homesubset
categoriesshufflerh   r4   download_if_missing
return_X_yr   r   T)prefer_skip_nested_validationr$   *   rR   F   g      ?c        
         v   t          |           } t          | t                    }
t          j                            | d          }d}t          j                            |
          r	 t          |
d          5 }|                                }ddd           n# 1 swxY w Y   t          j
        |d          }t          j        |          }nS# t          $ rF}t          d           t          d           t          d           t          |           Y d}~nd}~ww xY w|?|r.t                              d           t#          ||
||		          }nt%          d
          |dv r	||         n|dk    rt'                      }t'                      }t'                      }dD ]X}||         |                    j                   |                    j                   |                    j                   Y|_        t1          j        |          _        t1          j        |          _        t5          d          }|_        d|v rd j        D             _        d|v rd j        D             _        d|v rd j        D             _        |fd|D             }|                                 t;          | \  }}t1          j        j        |          }j        |         _        j        |         _        t1          j        |j                  _        t'          |          _         t1          j        j        tB                    }||         }|"                                _        |rtG          |          }t1          j$        j        j%        d                   }|&                    |           j        |         _        j        |         _        t1          j        j        tB                    }||         }|"                                _        |rj        j        fS S )a  Load the filenames and data from the 20 newsgroups dataset (classification).

    Download it if necessary.

    =================   ==========
    Classes                     20
    Samples total            18846
    Dimensionality               1
    Features                  text
    =================   ==========

    Read more in the :ref:`User Guide <20newsgroups_dataset>`.

    Parameters
    ----------
    data_home : str or path-like, default=None
        Specify a download and cache folder for the datasets. If None,
        all scikit-learn data is stored in '~/scikit_learn_data' subfolders.

    subset : {'train', 'test', 'all'}, default='train'
        Select the dataset to load: 'train' for the training set, 'test'
        for the test set, 'all' for both, with shuffled ordering.

    categories : array-like, dtype=str, default=None
        If None (default), load all the categories.
        If not None, list of category names to load (other categories
        ignored).

    shuffle : bool, default=True
        Whether or not to shuffle the data: might be important for models that
        make the assumption that the samples are independent and identically
        distributed (i.i.d.), such as stochastic gradient descent.

    random_state : int, RandomState instance or None, default=42
        Determines random number generation for dataset shuffling. Pass an int
        for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    remove : tuple, default=()
        May contain any subset of ('headers', 'footers', 'quotes'). Each of
        these are kinds of text that will be detected and removed from the
        newsgroup posts, preventing classifiers from overfitting on
        metadata.

        'headers' removes newsgroup headers, 'footers' removes blocks at the
        ends of posts that look like signatures, and 'quotes' removes lines
        that appear to be quoting another post.

        'headers' follows an exact standard; the other filters are not always
        correct.

    download_if_missing : bool, default=True
        If False, raise an OSError if the data is not locally available
        instead of trying to download the data from the source site.

    return_X_y : bool, default=False
        If True, returns `(data.data, data.target)` instead of a Bunch
        object.

        .. versionadded:: 0.22

    n_retries : int, default=3
        Number of retries when HTTP errors are encountered.

        .. versionadded:: 1.5

    delay : float, default=1.0
        Number of seconds between retries.

        .. versionadded:: 1.5

    Returns
    -------
    bunch : :class:`~sklearn.utils.Bunch`
        Dictionary-like object, with the following attributes.

        data : list of shape (n_samples,)
            The data list to learn.
        target: ndarray of shape (n_samples,)
            The target labels.
        filenames: list of shape (n_samples,)
            The path to the location of the data.
        DESCR: str
            The full description of the dataset.
        target_names: list of shape (n_classes,)
            The names of target classes.

    (data, target) : tuple if `return_X_y=True`
        A tuple of two ndarrays. The first contains a 2D array of shape
        (n_samples, n_classes) with each row representing one sample and each
        column representing the features. The second array of shape
        (n_samples,) contains the target samples.

        .. versionadded:: 0.22

    Examples
    --------
    >>> from sklearn.datasets import fetch_20newsgroups
    >>> cats = ['alt.atheism', 'sci.space']
    >>> newsgroups_train = fetch_20newsgroups(subset='train', categories=cats)
    >>> list(newsgroups_train.target_names)
    ['alt.atheism', 'sci.space']
    >>> newsgroups_train.filenames.shape
    (1073,)
    >>> newsgroups_train.target.shape
    (1073,)
    >>> newsgroups_train.target[:10]
    array([0, 1, 1, 1, 0, 1, 1, 0, 0, 0])
    rl   20news_homeNrbr&   P________________________________________________________________________________zCache loading failedz8Downloading 20news dataset. This may take a few minutes.)r=   r>   r   r   z20Newsgroups dataset not foundr#   rf   twenty_newsgroups.rstheadersc                 ,    g | ]}t          |          S rR   )rN   rU   rJ   s     rF   rW   z&fetch_20newsgroups.<locals>.<listcomp>^  !    HHHd+D11HHHrO   footersc                 ,    g | ]}t          |          S rR   )re   r}   s     rF   rW   z&fetch_20newsgroups.<locals>.<listcomp>`  r~   rO   quotesc                 ,    g | ]}t          |          S rR   )r[   r}   s     rF   rW   z&fetch_20newsgroups.<locals>.<listcomp>b  s!    IIIt,T22IIIrO   c                 H    g | ]}j                             |          |fS rR   )target_namesindex)rU   catdatas     rF   rW   z&fetch_20newsgroups.<locals>.<listcomp>e  s/    LLL#4$**3//5LLLrO   dtyper   )'r   r   
CACHE_NAMEr(   r    r)   existsr2   readr6   decoder8   loads	Exceptionprintr-   r.   rG   OSErrorlistextendr   target	filenamesnparrayr   DESCRsortzipisinsearchsortedr   objecttolistr
   arangeshapero   )rl   rm   rn   ro   rh   r4   rp   rq   r   r   r>   twenty_homerC   rE   rD   uncompressed_contentedata_lstr   r   fdescrlabelsmaskindicesr   s                           @rF   fetch_20newsgroupsr      s>   V 	222Iy*55J',,y-88KE	w~~j!! 
		j$'' .1%&VVXX". . . . . . . . . . . . . . .#)=1C\#R#R L!566EE 	 	 	(OOO()))(OOO!HHHHHHHH		 } 		<KKRSSS*&%#	  EE :;;;"""V}	566FF	' 	- 	-F=DOODI&&&MM$+&&&T^,,,,	hv&&),,/00FDJFHHdiHHH	FHHdiHHH	6IItyIII	LLLLLLL &\
wt{F++-k$'ofdk:: ,,8DIV444D>OO%%	 	&),77)DK-a011W%%%0k'*8DIV444G$OO%%	 &y$+%%Ks<   )C 9BC BC !B",C 
D<DD)	rm   r4   rl   rp   rq   	normalizeas_framer   r   c        	         @   t          |          }d}	|r|	dd                    |          z   z  }	t          ||	dz             }
t          |dddd	||||
	  	        }t          |dddd	||||
	  	        }t          j                            |
          rC	 t          j        |
          \  }}}n# t          $ r}t          d|
 d|
 d          |d}~ww xY wt          t          j                  }|                    |j                                                  }|                    |j                                                  }|                                }t          j        |||f|
d           |rj|                    t          j                  }|                    t          j                  }t+          j        |d           t+          j        |d           |j        }| dk    r
|}|j        }n^| dk    r
|}|j        }nN| dk    rHt3          j        ||f                                          }t          j        |j        |j        f          }t9          d          }d}dg}|rt;          d||||d          \  }}}|r||fS t=          ||||||          S )a  Load and vectorize the 20 newsgroups dataset (classification).

    Download it if necessary.

    This is a convenience function; the transformation is done using the
    default settings for
    :class:`~sklearn.feature_extraction.text.CountVectorizer`. For more
    advanced usage (stopword filtering, n-gram extraction, etc.), combine
    fetch_20newsgroups with a custom
    :class:`~sklearn.feature_extraction.text.CountVectorizer`,
    :class:`~sklearn.feature_extraction.text.HashingVectorizer`,
    :class:`~sklearn.feature_extraction.text.TfidfTransformer` or
    :class:`~sklearn.feature_extraction.text.TfidfVectorizer`.

    The resulting counts are normalized using
    :func:`sklearn.preprocessing.normalize` unless normalize is set to False.

    =================   ==========
    Classes                     20
    Samples total            18846
    Dimensionality          130107
    Features                  real
    =================   ==========

    Read more in the :ref:`User Guide <20newsgroups_dataset>`.

    Parameters
    ----------
    subset : {'train', 'test', 'all'}, default='train'
        Select the dataset to load: 'train' for the training set, 'test'
        for the test set, 'all' for both, with shuffled ordering.

    remove : tuple, default=()
        May contain any subset of ('headers', 'footers', 'quotes'). Each of
        these are kinds of text that will be detected and removed from the
        newsgroup posts, preventing classifiers from overfitting on
        metadata.

        'headers' removes newsgroup headers, 'footers' removes blocks at the
        ends of posts that look like signatures, and 'quotes' removes lines
        that appear to be quoting another post.

    data_home : str or path-like, default=None
        Specify an download and cache folder for the datasets. If None,
        all scikit-learn data is stored in '~/scikit_learn_data' subfolders.

    download_if_missing : bool, default=True
        If False, raise an OSError if the data is not locally available
        instead of trying to download the data from the source site.

    return_X_y : bool, default=False
        If True, returns ``(data.data, data.target)`` instead of a Bunch
        object.

        .. versionadded:: 0.20

    normalize : bool, default=True
        If True, normalizes each document's feature vector to unit norm using
        :func:`sklearn.preprocessing.normalize`.

        .. versionadded:: 0.22

    as_frame : bool, default=False
        If True, the data is a pandas DataFrame including columns with
        appropriate dtypes (numeric, string, or categorical). The target is
        a pandas DataFrame or Series depending on the number of
        `target_columns`.

        .. versionadded:: 0.24

    n_retries : int, default=3
        Number of retries when HTTP errors are encountered.

        .. versionadded:: 1.5

    delay : float, default=1.0
        Number of seconds between retries.

        .. versionadded:: 1.5

    Returns
    -------
    bunch : :class:`~sklearn.utils.Bunch`
        Dictionary-like object, with the following attributes.

        data: {sparse matrix, dataframe} of shape (n_samples, n_features)
            The input data matrix. If ``as_frame`` is `True`, ``data`` is
            a pandas DataFrame with sparse columns.
        target: {ndarray, series} of shape (n_samples,)
            The target labels. If ``as_frame`` is `True`, ``target`` is a
            pandas Series.
        target_names: list of shape (n_classes,)
            The names of target classes.
        DESCR: str
            The full description of the dataset.
        frame: dataframe of shape (n_samples, n_features + 1)
            Only present when `as_frame=True`. Pandas DataFrame with ``data``
            and ``target``.

            .. versionadded:: 0.24

    (data, target) : tuple if ``return_X_y`` is True
        `data` and `target` would be of the format defined in the `Bunch`
        description above.

        .. versionadded:: 0.20

    Examples
    --------
    >>> from sklearn.datasets import fetch_20newsgroups_vectorized
    >>> newsgroups_vectorized = fetch_20newsgroups_vectorized(subset='test')
    >>> newsgroups_vectorized.data.shape
    (7532, 130107)
    >>> newsgroups_vectorized.target.shape
    (7532,)
    rv   20newsgroup_vectorizedzremove-r^   z.pklr$   NT   )	rl   rm   rn   ro   rh   r4   rp   r   r   r%   zThe cached dataset located in z was fetched with an older scikit-learn version and it is not compatible with the scikit-learn version imported. You need to manually delete the file: .r   	   )compressF)copyrf   rz   category_classfetch_20newsgroups_vectorized)r   sparse_data)r   r   framer   feature_namesr   )r   r)   r   r   r(   r    r   joblibload
ValueErrorr   r   int16fit_transformr   tocsr	transformget_feature_names_outdumpastypefloat64r   r   r   r   spvstackconcatenater   r   r	   )rm   r4   rl   rp   rq   r   r   r   r   filebasetarget_file
data_train	data_testX_trainX_testr   r   
vectorizerr   r   r   r   r   target_names                           rF   r   r     s1   \ 	222I'H 1I 0 000	8f+<==K $/
 
 
J #/
 
 
I 
w~~k"" O	-3[-E-E*GV]] 	 	 	< < < .9< < < 
 	 %28444
**:?;;AACC%%in55;;=="88::Wfm4kANNNN  4..,,rz**e4444U3333*L"	6		!	5y'6*++1133!2I4D EFF/00FE#$K 
5+$
 
 
tV  V|!#   s   B, ,
C6CC):__doc__r6   loggingr(   r8   rer;   r1   
contextlibr   numbersr   r   r   numpyr   scipy.sparsesparser   r_   r   feature_extraction.textr   utilsr	   r
   utils._param_validationr   r   r   utils.fixesr   r   r   _baser   r   r   r   r   	getLogger__name__r-   r/   r   r*   r+   rG   rN   compilerS   r[   re   strPathLiketupler   r   rR   rO   rF   <module>r      s   6   				  				         " " " " " " " "                  5 5 5 5 5 5 - - - - - - - - K K K K K K K K K K , , , , , , ' ' ' ' ' ' ' '              
	8	$	$ 
#8O   !
$"  @   BJQ 	
! ! !  2 2;-:666778#T*;'(' ){ khxD@@@A(4d9===>  #'  " 
Q Q Q Q Qh :666778'2;- ){ k[KhxD@@@A(4d9===>
 
 #'    
^ ^ ^ ^ ^ ^ ^rO   