
    LMh6              	          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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m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 d d	lmZmZm Z  d d
l!m"Z" d dl#m$Z$m%Z%  ej&        e'          Z(dZ)dZ*dZ+dZ,dZ-dZ.dZ/dZ0dddde1dee2         de2defdZ3deddfdZ4de1dej5        fdZ6dede7e1         fd Z8deddfd!Z9 G d" d#          Z:d$ed%e j;        ddfd&Z<dS )'    N)
ModuleType)AnyCallableOptional)registry)get_username)get_cached_path)is_in_colab_notebookis_in_kaggle_notebook)UserCancelledError)PackageHandleResourceHandleparse_package_handle)EXTRA_CONSOLE_BLOCK)VersionedDatasources	read_filez0.1.0__package_version__packageassetsz/kaggle/package_assets__dependency_manager_notebook__zinstall_requirements.shzkagglehub_requirements.yamlF)force_downloadbypass_confirmationhandler   r   returnc          
      d   t          |           }t                              d|                                 di t                     t          j        |d|          \  }}|                                s|r|                    |          }t          j
        |          t          z  dz  }|                                sd|dt           d	}t          |          t          j        d
dd|j         d|j         d|           t$          j        v r|st$          j                 S |st)          |           t$          j        v r^t                              d di t                     t$          j        = fdt$          j        D             }|D ]}	t$          j        |	= t*          j                            |          }
|
|
j        d| d d}t3          |          t*          j                            |
          }|t$          j        <   |
j                            |           |S )ay  Download a Kaggle Package and import it.

    A Kaggle Package is a Kaggle Notebook which has exported code to a python package format.

    Args:
        handle: (string) the notebook handle under https://kaggle.com/code.
        force_download: (bool) Optional flag to force download motebook output, even if it's cached.
    Returns:
        The imported python module.
    z)Downloading Notebook Output for Package:  ...extraN)pathr   z__init__.pyz
Notebook 'z' is not a Package, missing 'z/__init__.py' file.z[^a-zA-Z0-9_]_kagglehub_package_z%Uninstalling existing package module z before re-importing.c                 D    g | ]}|                      d           |S ).)
startswith).0namemodule_names     R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/kagglehub/packages.py
<listcomp>z"package_import.<locals>.<listcomp>[   s3    ^^^D4??kK\K\K\;];]^4^^^    zCould not load module from z as r#   )r   loggerinfoto_urlr   r   notebook_output_resolveris_versionedwith_versionpathlibPathPACKAGE_NOTEBOOK_DIRexists
ValueErrorresubownernotebooksysmodules_confirm_import	importlibutilspec_from_file_locationloaderImportErrormodule_from_specexec_module)r   r   r   hnotebook_pathversioninit_file_pathmsgsubmodule_namesr&   specmoduler'   s               @r(   package_importrL   1   sS    	V$$A
KKLAHHJJLLLTkWjTkKlll%>qt\jkkkM7>> $ $NN7##\-003GG-WN  "" f1ff=Qfffoo &)30eQW0e0eqz0e0e\c0e0effK ck!!.!{;''   ck!!VKVVV^uat^u 	 	
 	
 	
 K$^^^^CK^^^# 	" 	"DD!!>11+~NND|t{*NNNNNNN#^,,T22F%CKKF###Mr*   rD   c                    t                      s>t                      s0t                      | j        k    st                                          dS d|                                  dt          |            d}t          t          j
        |           d          }|                                dvrt                      dS )ac  Gets user's manual confirmation before importing a package which would execute arbitrary code.

    This is skipped for known safe cases:
    1. Within a Kaggle or Colab environment (already containerized, not user-owned system)
    2. Package owned by the logged-in user (assumed trusted)
    3. Nested Package (assume confirmation already provided)
    Nz
      WARNING: You are about to execute untrusted code.
      This code could modify your python environment or operating system.

      Review this code at z$
      or in your download cache at z

      It is strongly recommended that you run this code within a container
      such as Docker to provide a secure, isolated execution environment.
      See https://www.kaggle.com/docs/packages for more information.
      z%
Do you want to proceed? (y)es/[no]: )yyes)r   r
   r   r8   PackageScopegetr-   r	   inputtextwrapdedentlowerr   )rD   rH   confirmations      r(   r<   r<   k   s     	!! >>QW$$)

 88::	

 


 %4A$6$6

 

 

C HOC00XXXYYL<// """ 0/r*   r   c                    t                                           }|r|j        t          z  | z  S t	                      sd}t          |          t          j        t                    | z  }|j	        
                    dd           |S )a  Returns a path referring to an asset file for use in Kaggle Packages.

    If within a PackageScope context, returns the path relative to it. This should be true
    any time a Package has been imported, whether via `package_import()` or directly.
    Otherwise, assumes we're in an interactive Kaggle Notebook and creating a Package,
    where package data should be written to a staging directory which will later get copied
    into the exported package when the Notebook is saved.

    Args:
        path: (str) The relative path of the desired asset file.
    Returns:
        The absolute path (as pathlib.Path) of the desired asset file.
    zAsset paths should only be retrieved within the execution of an existing Kaggle Package, or during the creation of a new Kaggle Package within a Kaggle Notebook.T)parentsexist_ok)rP   rQ   r   EXPORTED_PACKAGE_ASSETS_DIRr   r5   r1   r2   #KAGGLE_NOTEBOOK_ASSETS_STAGING_PATHparentmkdir)r   package_scoperH   
asset_paths       r(   get_package_asset_pathr`      s     !$$&&M G!$??$FF "" ` 	 ooABBTIJD4888r*   package_modulec                 L   t          | t          d          }|t          k    rd| }t          |          t	          |           5 }t          |            t                      }t          |j        	                    d                    D ]s}t          j        d|j         | j                  }t          ||           |j        D ]6}t!          | |t          ||                     |                    |           7tt          |          cddd           S # 1 swxY w Y   dS )aM  Complete the import of a Kaggle Package's python module.

    Only intended for use by auto-generated Package __init__.py files.

    Installs the package's Python Dependencies if applicable, and imports all (public) sibling .py
    files as submodules, exposes their public members onto the parent module, and decorates
    them with our PackageScope (see that class for more details).

    Args:
        package_module: (ModuleType) The python module of the Kaggle Package.
    Returns:
        The names of all public members which we scoped onto the module (similar to `__all__`).
    Nz$Unsupported Kaggle Package version: z[!_]*.pyr#   )r   )getattrPACKAGE_VERSION_NAMEPACKAGE_VERSIONr5   rP   _install_dependenciessetsortedr   globr=   import_modulestem__name__ _apply_context_manager_to_module__all__setattradd)ra   package_versionrH   r^   	all_namesfilepath	submoduler&   s           r(   _finalize_package_importru      sx    n.BDIIO/))F_FFoo 
n	%	% !n--- "ee	}166zBBCC 
	$ 
	$H!/0CHM0C0C^MdeeeI -YFFF ") $ $gi.F.FGGGd####$ i  %! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !s   CDD Dc                 b   t          | t          d          }|sdS | j        }t          |          }|j        dk    rd| d|d}t          |          t                              d|                                 di t                     t          j        |          \  }}t          j        |          t          z  }|                                sd| d	|d
}t          |          t!          j        dddd          5 }t                              d| d|j         d
           |                    d| d|d           |                                 t+          j        dt/          |          gdd||           |                                 ddd           dS # 1 swxY w Y   dS )z}Download and install a Package's dependencies, if applicable.

    Uses the Dependency Manager feature from Kaggle Notebooks.Npackagemanagerz	Package 'z' has Dependency Manager 'z%' not owned by 'packagemanager' user.z)Downloading Dependency Manager Notebook: r   r   z:' has dependencies configured but installer not found at 'z'.z'kagglehub-package-dependencies-install-z.txtFzw+)prefixsuffixdeletemodez,Installing python dependencies for Package 'z', logging progress to 'z' using install script at 'z'.
z	/bin/bashT)checktextstdoutstderr)rc   DEPENDENCY_MANAGER_HANDLE_NAMErl   r   r8   r5   r+   r,   r-   r   r   r.   r1   r2   #DEPENDENCY_MANAGER_INSTALL_FILEPATHis_filetempfileNamedTemporaryFiler&   writeflush
subprocessrunstr)	ra   dependency_manager_handle_strpackage_namer   rH   r   r    install_pathlog_files	            r(   rf   rf      s<    %,N<Z\`$a$a!( !*L!"?@@F|'''q,qq&qqqoo
KKQFMMOOQQQYp\oYpKqqq/77GD!<%%(KKL!! t,ttbntttoo 
	$8PU\`
 
 
 	r<rraianrrr	
 	
 	
 	x<xxdpxxx	
 	
 	
 	#l++,DtH]e	
 	
 	
 	
 	                 s   BF$$F(+F(c                       e Zd ZdZ ej        ed                   dd          ZdefdZ	d Z
d Zed	ed          fd
            Zeded	ee         fd            ZdS )rP   a  Captures data about a Kaggle Package. Use as Context Manager to apply the scope.

    When scope is applied, certain `kagglehub` calls will utilize the Package info.
    Specifically, downloading a datasource without a version specified will check
    the PackageScope and use the Package's version if it finds a matching entry.
    `kagglehub.get_package_asset_path` also relies on the current scope to pull
    assets related to a package.
    kagglehub_package_scopeN)defaultra   c                    t          |d          r|j        sd|j         d}t          |          || _        t          j        |j                  j        | _        t          | j        t          z            | _        g | _        d S )N__file__zPackage module 'z' missing '__file__'.)hasattrr   rl   r5   ra   r1   r2   r\   r   r   KAGGLEHUB_REQUIREMENTS_FILENAMEdatasources_token_stack)selfra   rH   s      r(   __init__zPackageScope.__init__	  s    ~z22 	".:Q 	"S^%<SSSCS//!*8"),~/F"G"G"N	1:49Gf;f1g1g57r*   c                 x    t           j                            |           }| j                            |           | S N)rP   _ctxrg   r   append)r   tokens     r(   	__enter__zPackageScope.__enter__  s4    !%%d++  '''r*   c                 v    | j                                         }t          j                            |           d S r   )r   poprP   r   reset)r   exc_type	exc_value	tracebackr   s        r(   __exit__zPackageScope.__exit__  s3    !%%''&&&&&r*   r   c                  >    t           j                                        S )zAGets the currently applied PackageScope, or None if none applied.)rP   r   rQ    r*   r(   rQ   zPackageScope.get  s      $$&&&r*   rD   c                 p    t                                           }|r|j                            |           ndS )zGets version number for given resource within current PackageScope (if any).

        Returns None if no PackageScope is applied, or if it didn't contain the resource.N)rP   rQ   r   )rD   r^   s     r(   get_versionzPackageScope.get_version"  s6    
 %((**3@J}(,,Q///dJr*   )rl   
__module____qualname____doc__contextvars
ContextVarr   r   r   r   r   r   staticmethodrQ   r   intr   r   r*   r(   rP   rP      s          <;!(>":;<U_cdddD	8z 	8 	8 	8 	8  
' ' ' '.) ' ' ' \' K~ K(3- K K K \K K Kr*   rP   rK   context_managerc                    dt           dt           ffd}| g}|r|                                }t          j        |          D ]\  }}t	          |dd          | j        k    r t          j        |          r|dvr|                    |           Nt          j        |          st          j	        |          rt          || ||                     |dS dS )zzDecorates all functions/methods in the module to apply the Context Manager.

    Also includes methods defined on classes.funcr   c                 J     t          j                    fd            }|S )Nc                  L    5   | i |cd d d            S # 1 swxY w Y   d S r   r   )argskwargsr   r   s     r(   wrapperzC_apply_context_manager_to_module.<locals>.decorate.<locals>.wrapper3  s      - -tT,V,,- - - - - - - - - - - - - - - - - -s   )	functoolswraps)r   r   r   s   ` r(   decoratez2_apply_context_manager_to_module.<locals>.decorate2  s>    				- 	- 	- 	- 	- 
		- r*   r   N)__base__	__class__)r   r   inspect
getmembersrc   rl   isclassr   
isfunctionismethodro   )rK   r   r   stackobjr&   members    `     r(   rm   rm   ,  s   x H       xE
 5iikk#.s33 		5 		5LD&v|T22foEE (( 5T9R-R-RV$$$$#F++ 5w/?/G/G 5T88F#3#3444  5 5 5 5 5r*   )=
contextlibr   r   r=   r   loggingr1   r6   r   r:   r   rS   typesr   typingr   r   r   	kagglehubr   kagglehub.authr   kagglehub.cacher	   kagglehub.envr
   r   kagglehub.exceptionsr   kagglehub.handler   r   r   kagglehub.loggerr   kagglehub.trackerr   r   	getLoggerrl   r+   re   rd   r3   rZ   r[   r   r   r   r   boolrL   r<   r2   r`   listru   rf   rP   AbstractContextManagerrm   r   r*   r(   <module>r      s                      				     



         * * * * * * * * * *       ' ' ' ' ' ' + + + + + + E E E E E E E E 3 3 3 3 3 3 P P P P P P P P P P 0 0 0 0 0 0 = = = = = = = =		8	$	$ ,  !  ' &> # "C &? # #@  6;X]7 7 77$,TN7QU77 7 7 7t#} # # # # #D     <&!Z &!DI &! &! &! &!R%* % % % % %P-K -K -K -K -K -K -K -K`5Z 5*Jk 5pt 5 5 5 5 5 5r*   