
    JTh                        S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK J	r	J
r
  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJrJrJrJrJrJr  S SKrS S	KJrJr  S S
KJ r J!r!  S SK"J#r#  SSK$J%r%  SSK&J'r'  SSK(J)r)J*r*  SSK+J,r,  SSK-J.r.  SSK/J0r0  SSK1J2r2J3r3  SSK4J5r5J6r6J7r7  / SQr8Sr9\S\:/S4   r; " S S\5      r< " S S\5      r=\ " S S5      5       r> " S S\?5      r@ " S  S!\?5      rA " S" S5      rBS#S$/rCS%rDS&\:S'\:4S( jrEg))    N)defaultdictOrderedDict)Sequence)	dataclass)Enum)SourceFileLoader)Path)AnyCallablecastIOOptionalUnion)location_tagnormalize_storage_type)FileLikeStorage)RemovableHandle   )DiGraph)_normalize_path)demangle
is_mangled)create_pickler)is_stdlib_module)find_files_source_depends_on)	GlobGroupGlobPattern)ImporterOrderedImportersys_importer)PackagingErrorReasonEmptyMatchErrorPackagingErrorPackageExporterTr%   c                   0    \ rS rSrSrSrSrSrSrSr	Sr
S	rg
)_ModuleProviderAction-   zRepresents one of the actions that :class:`PackageExporter` can take on a module.

See :meth:`PackageExporter.extern` and friends for a description of what the actions do.
r                   N)__name__
__module____qualname____firstlineno____doc__INTERNEXTERNMOCKDENYREPACKAGED_MOCK_MODULESKIP__static_attributes__r.       V/var/www/auris/envauris/lib/python3.13/site-packages/torch/package/package_exporter.pyr'   r'   -   s,    
 FFDD
  Dr;   r'   c                   :    \ rS rSrSrS rSrSrSrSr	Sr
S	rS
rSrg)r"   B   zListing of different reasons a dependency may fail to package.

This enum is used to provide good error messages when
:class:`PackagingError` is raised.
c                 P    SU R                   R                   SU R                   S3$ )N<.>)	__class__r/   nameselfs    r<   __repr__PackagingErrorReason.__repr__I   s&    4>>**+1TYYKq99r;   zKModule is a C extension module. torch.package supports Python modules only.zModule had no __file__ defined.zCModule had a __file__, but we could not find it in your filesystem.zDependency resolution failed.zLModule did not match against any action pattern. Extern, mock, or intern it.zModule was denied by a pattern.zModule was mocked out, but is still being used in the package. Please intern or extern the mocked modules if objects are supposed to be in the package.r.   N)r/   r0   r1   r2   r3   rG   IS_EXTENSION_MODULENO_DUNDER_FILESOURCE_FILE_NOT_FOUNDDEPENDENCY_RESOLUTION_FAILED	NO_ACTIONDENIEDMOCKED_BUT_STILL_USEDr:   r.   r;   r<   r"   r"   B   sH    : 	V  7NM  $C V  /F	 r;   r"   c                   >    \ rS rSr% Sr\\S'   \\S'   \\S'   S rSr	g)	_PatternInfo_   zQHolds :class:`PackageExporter`-specific info about how to execute matches againstactionallow_emptywas_matchedc                 *    Xl         X l        SU l        g )NFrS   rT   rU   )rF   rS   rT   s      r<   __init___PatternInfo.__init__j   s    & r;   rW   N)
r/   r0   r1   r2   r3   r'   __annotations__boolrX   r:   r.   r;   r<   rQ   rQ   _   s    [ "!!r;   rQ   c                       \ rS rSrSrSrg)r#   p   zThis is an exception that is thrown when a mock or extern is marked as
``allow_empty=False``, and is not matched with any module during packaging.
r.   N)r/   r0   r1   r2   r3   r:   r.   r;   r<   r#   r#   p   s    r;   r#   c                   8   ^  \ rS rSrSrSS\4U 4S jjjrSrU =r$ )r$   v   zThis exception is raised when there is an issue with exporting a package.
``PackageExporter`` will attempt to gather up all the errors and present
them to you at once.
dependency_graphc                   > [        [        5      nUR                  R                  5        HJ  u  pEUR	                  S5      nUc  M  U[
        R                  :X  a  SU;  d   eX6   R                  U5        ML     [        R                  " 5       nUR                  S5        UR                  5        H  u  pUR                  SUR                   S35        U	 H  nUR                  SU S35        UR                  U   R	                  S5      n
U
b  UR                  SU
 S35        U[        ;   a  UR                  SU S	U S
U S35        U(       d  M|  UR                  U5      nUR                  SU SSR                  U5       S35        M     M     U(       d"  UR                  S5        UR                  S5        Xl        [         TU ]E  UR%                  5       5        g )NerrorrS   
z* z    error_contextz      Context: ze      Note: While we usually use modules in the python standard library from the local environment, `zj` has a lot of system level access and therefore can pose a security risk. We heavily recommend removing `z{` from your packaged code. However, if that is not possible, add it to the extern list by calling PackageExporter.extern("`z`")
z      A path to z: z -> zjSet debug=True when invoking PackageExporter for a visualization of where broken modules are coming from!
)r   listnodesitemsgetr"   rM   appendioStringIOwritevalue_DISALLOWED_MODULES
first_pathjoinr`   superrX   getvalue)rF   r`   debugbrokenmodule_nameattrsrb   messagereasonmodule_namesrd   module_pathrC   s               r<   rX   PackagingError.__init__|   s   8CD8I"2"8"8">">"@KIIg&E},666u,,,M  - #A ++-d$*LLN FMMBv||nB/0+[M45 !1 6 6{ C G G X ,MMOM?""EF"55MM88C} E//:m <44?=G 5"2"="=k"JKMM*;-r&++k:R9SSUV%  , %3. MM$MM4
 !1))+,r;   )r`   F)	r/   r0   r1   r2   r3   r   rX   r:   __classcell__)rC   s   @r<   r$   r$   v   s    
-- -- --r;   r$   c                   J   \ rS rSr% Sr \\S'   \S4S\S\	\\
\   4   S\SS4S	 jjr SKS\S\4S jjrS\4S jrS\S\S\S\\   4S jr  SLS\S\S\S\4S jjr SMS\S\S\4S jjrS\4S jrS\S\4S jrS\R.                  S\\   4S jrSKS\4S jjrSKS\4S jjrS\S\4S jr  SNS\S\S\S\S\4
S  jjrS\S\S!\4S" jr S#\!4S$ jr"S%\#S\$4S& jr%S%\#S\$4S' jr&S%\#S\$4S( jr'S)S
S*.S+S,S-S,S.\4S/ jjr(S)S
S*.S+S,S-S,S.\4S0 jjr)S)S
S*.S+S,S-S,S.\4S1 jjr*S)S2.SOS3 jjr+S4 r,S5 r-S6 r.S7 r/S8 r0S9 r1S: r2S; r3S< r4S= r5S> r6S\4S? jr7S\4S@ jr8SA\\9   S\\   4SB jr:S\\   4SC jr;S\\   4SD jr<S\\   4SE jr=S\\   4SF jr>S\S\\   4SG jr?S\SH\S\4SI jr@SJrAg)Pr%      a  Exporters allow you to write packages of code, pickled Python data, and
arbitrary binary and text resources into a self-contained package.

Imports can load this code in a hermetic way, such that code is loaded
from the package rather than the normal Python import system. This allows
for the packaging of PyTorch model code and data so that it can be run
on a server or used in the future for transfer learning.

The code contained in packages is copied file-by-file from the original
source when it is created, and the file format is a specially organized
zip file. Future users of the package can unzip the package, and edit the code
in order to perform custom modifications to it.

The importer for packages ensures that code in the module can only be loaded from
within the package, except for modules explicitly listed as external using :meth:`extern`.
The file ``extern_modules`` in the zip archive lists all the modules that a package externally depends on.
This prevents "implicit" dependencies where the package runs locally because it is importing
a locally-installed package, but then fails when the package is copied to another machine.

When source code is added to the package, the exporter can optionally scan it
for further code dependencies (``dependencies=True``). It looks for import statements,
resolves relative references to qualified module names, and performs an action specified by the user
(See: :meth:`extern`, :meth:`mock`, and :meth:`intern`).
importerFfrs   returnNc                    [         R                  R                  S5        X0l        [	        U[
        [        R                  45      (       a  [        R                  " U5      nSU l	        OXl	        [         R                  R                  U5      U l        U R                  R                  S5        [        5       U l        0 U l        [!        5       U l        [         R                  R%                  U R                  5      U l        U R&                  R)                  5       U l        [+        5       U l        [+        5       U l        [+        5       U l        [	        U[2        5      (       a  X l        ON[	        U[6        R8                  R:                  5      (       d  [=        S[?        U5       S35      e[A        U6 U l        0 U l!        SU l"        g)a  
Create an exporter.

Args:
    f: The location to export to. Can be a  ``string``/``Path`` object containing a filename
        or a binary I/O object.
    importer: If a single Importer is passed, use that to search for modules.
        If a sequence of importers are passed, an ``OrderedImporter`` will be constructed out of them.
    debug: If set to True, add path of broken modules to PackagingErrors.
ztorch.package.PackageExporterNr-   zCimporter arg should be an Importer or a sequence of Importers, got z	 instead.r   )#torch_C_log_api_usage_oncers   
isinstancestrosPathLikefspathbufferPyTorchFileWriterzip_fileset_min_versionset_written_filesserialized_reducesr   r`   ScriptModuleSerializerscript_module_serializerstorage_contextr   _extern_hooks_mock_hooks_intern_hooksr   r   collectionsabcr   	TypeErrortyper    patterns
_unique_id)rF   r   r   rs   s       r<   rX   PackageExporter.__init__   sK     	$$%DE
a#r{{+,,		!A/3DKK2215%%a((+24 !(	(-(G(G(V%#<<LLN
 +6-(3*5-h))$Mh(@(@AA>*)5  ,X6DM79r;   Tru   file_or_directoryc           	      l   [        U5      nUR                  5       (       a  / nUR                  SS5      nUR                  S5       H  nUR	                  U5      R                  5       nUS-   U-   n	Sn
UR                  S:X  a"  U	S[        S5      *  R                  SS5      n
SnO!U	S[        S5      *  R                  SS5      n
S	nUR                  U
[        [        U5      5      UU45        M     U H  nU R                  " U6   M     gUR                  S:H  nU R                  U[        U5      UU5        g)
aF  Adds the local file system ``file_or_directory`` to the source package to provide the code
for ``module_name``.

Args:
    module_name (str): e.g. ``"my_package.my_subpackage"``, code will be saved to provide code for this package.
    file_or_directory (str): the path to a file or directory of code. When a directory, all python files in the directory
        are recursively copied using :meth:`save_source_file`. If a file is named ``"/__init__.py"`` the code is treated
        as a package.
    dependencies (bool, optional): If ``True``, we scan the source for dependencies.
rA   /z**/*.pyNz__init__.py/__init__.pyT.pyF)r	   is_dirreplaceglobrelative_toas_posixrD   lenri   
_read_filer   save_source_string)rF   ru   r   dependenciespathto_saverz   filenamerelative_patharchivenamesubmodule_name
is_packageitems                r<   save_source_file PackageExporter.save_source_file  s?    %&;;==G%--c37K IIi0 ( 4 4T : C C E)C/-?!%==M1%01GC4G3G%H%P%PS&N "&J%0CJ;%?%G%GS%QN!&J &"3x=1"$	# 14  ''.   m3J##,-	r;   c                 Z    [        U R                  5      nU =R                  S-  sl        U$ )zMGet an id. This id is guaranteed to only be handed out once for this package.r   )r   r   )rF   rets     r<   get_unique_idPackageExporter.get_unique_id<  s#    $//"1
r;   srcr   c                    U(       a  UOUR                  SSS9S   n [        X5      n0 nU HG  u  pU	b#  U SU	 3n
U R                  U
5      (       a  SXz'   M+  U R                  U5      (       d  MC  SXx'   MI     [        UR                  5       5      $ ! [         a>  nU R                  R	                  U[
        R                  [        U5      S9  / s SnA$ SnAff = f)a  Return all modules that this source code depends on.

Dependencies are found by scanning the source code for import-like statements.

Arguments:
    src: The Python source code to analyze for dependencies.
    module_name: The name of the module that ``src`` corresponds to.
    is_package: Whether this module should be treated as a package.
        See :py:meth:`save_source_string` for more info.

Returns:
    A list containing modules detected as direct dependencies in
    ``src``.  The items in the list are guaranteed to be unique.
rA   r   )maxsplitr   )rb   rd   NT)rsplitr   	Exceptionr`   add_noder"   rL   r   _module_existsre   keys)rF   r   ru   r   package_name	dep_pairser   dep_module_namedep_module_objpossible_submodules              r<   _get_dependencies!PackageExporter._get_dependenciesB  s    $ &K;+=+=cA+=+Nq+Q 		4SGI /8+O )(7'8.9I%J"&&'9::7;L4""?3304- 09 L%%'((3  	!!***GG!!f + 
 I	s   B 
C3CCCr   c                     U R                   R                  UUUS[        R                  S9  U(       aH  U R	                  X!U5      nU H/  nU R                   R                  X5        U R                  U5        M1     gg)aP  Adds ``src`` as the source code for ``module_name`` in the exported package.

Args:
    module_name (str): e.g. ``my_package.my_subpackage``, code will be saved to provide code for this package.
    src (str): The Python source code to save for this package.
    is_package (bool, optional): If ``True``, this module is treated as a package. Packages are allowed to have submodules
        (e.g. ``my_package.my_subpackage.my_subsubpackage``), and resources can be saved inside them. Defaults to ``False``.
    dependencies (bool, optional): If ``True``, we scan the source for dependencies.
T)sourcer   providedrS   N)r`   r   r'   r4   r   add_edgeadd_dependency)rF   ru   r   r   r   depsdeps          r<   r   "PackageExporter.save_source_strings  sz      	&&!(// 	' 	
 ))#JGD%%..{@##C(  r;   c                 f    U(       a  SOSnUR                  SS5      U-   nU R                  XR5        g)zWrite ``src`` as the source code for ``module_name`` in the zip archive.

Arguments are otherwise the same as for :meth:`save_source_string`.
r   r   rA   r   N)r   _write)rF   ru   r   r   	extensionr   s         r<   _write_source_string$PackageExporter._write_source_string  s0     '1Ne	&&sC09<H"r;   c                      U R                   R                  U5      $ ! [         a$    [        U5      (       d  e SU S3n[        U5      S ef = f)NzModule not found: 'zW'. Make sure the PackageImporter that created this module is present in `self.importer`)r   import_moduleModuleNotFoundErrorr   )rF   ru   msgs      r<   _import_modulePackageExporter._import_module  s`    		5==..{;;" 	5k**%k] 3D D  &c*4	5s	    .Ac                 H     U R                  U5        g! [         a     gf = f)NTF)r   r   rF   ru   s     r<   r   PackageExporter._module_exists  s*    	, 		s    
!!modulec                    S n[        USS 5      nUbA  [        USS 5      nUb1  [        U[        5      (       a   UR                  UR                  5      nUc  [        USS 5      n[        U[        5      (       aE  UR                  S5      (       a/  SR                  [        R                  " X!R                  5      5      $ g ! [
         a     Nwf = f)N__spec__loader__file__r    )getattrr   r   get_filenamer/   ImportErrorr   endswithrp   	linecachegetlines__dict__)rF   r   r   specr   s        r<   _get_source_of_module%PackageExporter._get_source_of_module  s    vz40T8T2F!j9I&J&J%226??CH vz48Hh$$):):5)A)A779--hHII # s   B? ?
CCc                    XR                   ;   a,  U R                   R                  U   R                  S5      SL a  gUS:X  a*  U R                   R                  U[        R
                  SS9  gUS:X  a*  U R                   R                  U[        R                  SS9  gU R                  U5      (       a*  U R                   R                  U[        R                  SS9  gU R                  R                  5        H  u  p4UR                  U5      (       d  M  SUl        U R                   R                  XR                  SS9  UR                  [        R                  :X  a(  U R                   R                  U[        R                   S9  UR                  [        R"                  :X  a  U R%                  X5          g   U R                   R                  U[        R&                  S9  g)z\Given a module, add it to the dependency graph according to patterns
specified by the user.
r   TNtorch_package_importer)rS   r   _mock)rb   )r`   rf   rh   r   r'   r9   r8   _can_implicitly_externr5   r   rg   matchesrU   rS   r7   r"   rN   r4   _intern_modulerM   )rF   ru   r   patternpattern_infos        r<   r   PackageExporter.add_dependency  s   
 000%%++K8<<ZHDP
 22!!**,11 + 
 '!!!**,CC + 
 &&{33!!**$9$@$@4 +  %)]]%8%8%:!G{+++/(%%..(;(;d /   &&*?*D*DD))22#+?+F+F 3   &&*?*F*FF''B# &;( 	&&3== 	' 	
r;   c                 f    [        U[        5      (       d  [        S5      eU R                  X5        g)a  Save the code for ``module`` into the package. Code for the module is resolved using the ``importers`` path to find the
module object, and then using its ``__file__`` attribute to find the source code.

Args:
    module_name (str): e.g. ``my_package.my_subpackage``, code will be saved to provide code
        for this package.
    dependencies (bool, optional): If ``True``, we scan the source for dependencies.
zNsave_module() expects a string input, did you perhaps mean to pass `__name__`?N)r   r   r   r   )rF   ru   r   s      r<   save_modulePackageExporter.save_module  s1     +s++`  	K6r;   c           	         U R                  U5      n[        U5      n[        US5      nU R                  U5      nUc  [	        USS5      nSnUc  [
        R                  nO]UR                  [        [        R                  R                  5      5      (       a  [
        R                  nO[
        R                  nSU 3nU R                  R                  U[         R"                  UUUSS9  gU R                  R                  U[         R"                  UUSS9  U(       aH  U R%                  XQU5      n	U	 H/  n
U R                  R'                  X5        U R)                  U
5        M1     gg)zAdds the module to the dependency graph as an interned module,
along with any metadata needed to write it out to the zipfile at serialization time.
__path__Nr   z
filename: T)rS   r   rb   rd   r   )rS   r   r   r   )r   r   hasattrr   r   r"   rJ   r   tuple	importlib	machineryEXTENSION_SUFFIXESrI   rK   r`   r   r'   r4   r   r   r   )rF   ru   r   
module_objr   r   r   rd   packaging_errorr   r   s              r<   r   PackageExporter._intern_module  sY    ((5
 {+ Z4
++J7> z:t<H M"6"E"E""5)<)<)O)O#PQQ"6"J"J"6"L"L",XJ 7!!**,33%%+ +  &&(//! 	' 	
 ))&zJD%%..{@##C(  r;   packageresourceobjpickle_protocolc                   ^ ^ US:X  d  US:X  d   S5       eT R                  X5      n[        R                  " 5       n[        UT R                  US9nT R
                  Ul        UR                  U5        UR                  5       n	[        [        5      mSU SU S3n
T R                  R                  U
[        R                  SSS	9  S
[        [            S[        [            4UU 4S jjnU(       GaX  / nSnSn[        S5      nSn["        R$                  " U	5       GH  u  nnnUS:X  Ga  UR&                  S:X  d   UR&                  S:X  d  UR&                  S:X  a"  [)        U[         5      (       d   eUnUnUUU'   Ma  UR&                  S:X  d   UR&                  S:X  d  UR&                  S:X  a-  [)        U[*        5      (       d   eUnUR-                  US5      nM  UR&                  S:X  a  US-  nM  UR&                  S:X  a=  Uc  M  [)        U[         5      (       d   eX;  a  UR/                  U5        U" X5        GM"  GM%  US:X  d  GM.  UR&                  S:X  d  GMA  [)        U[         5      (       d   eUR1                  S5      u  pX;  a  UR/                  U5        U" X5        GM     U H  nT R                  R3                  U
U5         UT;   ad  [)        U[         5      (       d   eTU   nT R                  R                  U[        R4                  [6        R8                  SU SU SU SU S3	SS9  M  T R;                  U5        M     T R=                  Xi5        g) a  Save a python object to the archive using pickle. Equivalent to :func:`torch.save` but saving into
the archive rather than a stand-alone file. Standard pickle does not save the code, only the objects.
If ``dependencies`` is true, this method will also scan the pickled objects for which modules are required
to reconstruct them and save the relevant code.

To be able to save an object where ``type(obj).__name__`` is ``my_module.MyObject``,
``my_module.MyObject`` must resolve to the class of the object according to the ``importer`` order. When saving objects that
have previously been packaged, the importer's ``import_module`` method will need to be present in the ``importer`` list
for this to work.

Args:
    package (str): The name of module package this resource should go in (e.g. ``"my_package.my_subpackage"``).
    resource (str): A unique name for the resource, used to identify it to load.
    obj (Any): The object to save, must be picklable.
    dependencies (bool, optional): If ``True``, we scan the source for dependencies.
r+   r*   z4torch.package only supports pickle protocols 3 and 4)protocolr@   rA   rB   T)rS   r   	is_pickler   fieldc                 j  > [        U [        5      (       d   e[        U[        5      (       d   eTR                  U 5      (       a  gTR                  R	                  5        HO  u  p#UR                  U 5      (       d  M  UR                  [        R                  :X  a  TU    R                  U5          g   g)a*  
checks if an object (field) comes from a mocked module and then adds
the pair to mocked_modules which contains mocked modules paired with their
list of mocked objects present in the pickle.

We also hold the invariant that the first user defined rule that applies
to the module is the one we use.
N)
r   r   r   r   rg   r   rS   r'   r6   ri   )r   r  r   r   mocked_modulesrF   s       r<   _check_mocked_error8PackageExporter.save_pickle.<locals>._check_mocked_errort  s     fc****eS))))**622)-)<)<)>%??6**#**.C.H.HH&v.55e<	 *?r;   Nr   SHORT_BINUNICODE
BINUNICODEBINUNICODE8LONG_BINGETBINGETGETMEMOIZEr   STACK_GLOBALGLOBAL zObject(s) 'z' from module `zC` was mocked out during packaging but is being used in resource - `z` in package `z`. )rS   rb   rd   r   )	_filenamerj   BytesIOr   r   _persistent_idpersistent_iddumprr   r   re   r`   r   r'   r4   r   r   pickletoolsgenopsrD   r   intrh   ri   splitr   r6   r"   rO   r   r   )rF   r  r	  r
  r   r  r   data_bufpickler
data_valuename_in_dependency_graphr  all_dependenciesr   r  memo
memo_countopcodearg_posru   fieldsr  s   `                     @r<   save_picklePackageExporter.save_pickleG  sB   2  1$q 	BA	B 
 >>'4::< 4==?S $ 3 3S&&(
$T*%&wiq
!#< &&$(//	 	' 	
	 	hsm 	 	( !FE*5d*;DJ%0%7%7
%C!T"a''99!;;,6!;;-7)#s3333!& #+.Z(}4!;;(2!;;%/)#s3333!& $d 3	1"a
6!>$)&#6666!9,33F;+F: 7 $q(V[[H-D%c3////$'IIcNMF5(//7'6I &DJ  0%%../GU .0%k37777+K8F))22#4992HH(3F8?;- X<<D:^T[S\\_'a!% 3  ''4%  0( 	H)r;   textc                 D    U R                  XUR                  S5      5      $ )a  Save text data to the package.

Args:
    package (str): The name of module package this resource should go it (e.g. ``"my_package.my_subpackage"``).
    resource (str): A unique name for the resource, used to identify it to load.
    text (str): The contents to save.
utf-8)save_binaryencode)rF   r  r	  r4  s       r<   	save_textPackageExporter.save_text  s      4;;w3GHHr;   binaryc                 H    U R                  X5      nU R                  XC5        g)a  Save raw bytes to the package.

Args:
    package (str): The name of module package this resource should go it (e.g. ``"my_package.my_subpackage"``).
    resource (str): A unique name for the resource, used to identify it to load.
    binary (str): The data to save.
N)r  r   )rF   r  r	  r;  r   s        r<   r7  PackageExporter.save_binary  s     >>'4H%r;   hookc                 `    [        U R                  5      nXR                  UR                  '   U$ )a  Registers an extern hook on the exporter.

The hook will be called each time a module matches against an :meth:`extern` pattern.
It should have the following signature::

    hook(exporter: PackageExporter, module_name: str) -> None

Hooks will be called in order of registration.

Returns:
    :class:`torch.utils.hooks.RemovableHandle`:
        A handle that can be used to remove the added hook by calling
        ``handle.remove()``.
)r   r   idrF   r>  handles      r<   register_extern_hook$PackageExporter.register_extern_hook  +     !!3!34(,699%r;   c                 `    [        U R                  5      nXR                  UR                  '   U$ )a  Registers a mock hook on the exporter.

The hook will be called each time a module matches against a :meth:`mock` pattern.
It should have the following signature::

    hook(exporter: PackageExporter, module_name: str) -> None

Hooks will be called in order of registration.

Returns:
    :class:`torch.utils.hooks.RemovableHandle`:
        A handle that can be used to remove the added hook by calling
        ``handle.remove()``.
)r   r   r@  rA  s      r<   register_mock_hook"PackageExporter.register_mock_hook  s+     !!1!12&*#r;   c                 `    [        U R                  5      nXR                  UR                  '   U$ )a  Registers an intern hook on the exporter.

The hook will be called each time a module matches against an :meth:`intern` pattern.
It should have the following signature::

    hook(exporter: PackageExporter, module_name: str) -> None

Hooks will be called in order of registration.

Returns:
    :class:`torch.utils.hooks.RemovableHandle`:
        A handle that can be used to remove the added hook by calling
        ``handle.remove()``.
)r   r   r@  rA  s      r<   register_intern_hook$PackageExporter.register_intern_hook  rE  r;   r.   )excluderT   includer   rL  rT   c                `    [        [        R                  U5      U R                  [	        XS9'   g)a  Specify modules that should be packaged. A module must match some ``intern`` pattern in order to be
included in the package and have its dependencies processed recursively.

Args:
    include (Union[List[str], str]): A string e.g. "my_package.my_subpackage", or list of strings
        for the names of the modules to be externed. This can also be a glob-style pattern, as described in :meth:`mock`.

    exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.

    allow_empty (bool): An optional flag that specifies whether the intern modules specified by this call
        to the ``intern`` method must be matched to some module during packaging. If an ``intern`` module glob
        pattern is added with ``allow_empty=False``, and :meth:`close` is called (either explicitly or via ``__exit__``)
        before any modules match that pattern, an exception is thrown. If ``allow_empty=True``, no such exception is thrown.

rL  N)rQ   r'   r4   r   r   rF   rM  rL  rT   s       r<   internPackageExporter.intern  s(    , >J!((+>
i9:r;   c                `    [        [        R                  U5      U R                  [	        XS9'   g)a#  Replace some required modules with a mock implementation.  Mocked modules will return a fake
object for any attribute accessed from it. Because we copy file-by-file, the dependency resolution will sometimes
find files that are imported by model files but whose functionality is never used
(e.g. custom serialization code or training helpers).
Use this function to mock this functionality out without having to modify the original code.

Args:
    include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
        for the names of the modules to be mocked out. Strings can also be a glob-style pattern
        string that may match multiple modules. Any required dependencies that match this pattern
        string will be mocked out automatically.

        Examples :
            ``'torch.**'`` -- matches ``torch`` and all submodules of torch, e.g. ``'torch.nn'``
            and ``'torch.nn.functional'``

            ``'torch.*'`` -- matches ``'torch.nn'`` or ``'torch.functional'``, but not
            ``'torch.nn.functional'``

    exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.
        e.g. ``include='torch.**', exclude='torch.foo'`` will mock all torch packages except ``'torch.foo'``,
        Default: is ``[]``.

    allow_empty (bool): An optional flag that specifies whether the mock implementation(s) specified by this call
        to the :meth:`mock` method must be matched to some module during packaging. If a mock is added with
        ``allow_empty=False``, and :meth:`close` is called (either explicitly or via ``__exit__``) and the mock has
        not been matched to a module used by the package being exported, an exception is thrown.
        If ``allow_empty=True``, no such exception is thrown.

rO  N)rQ   r'   r6   r   r   rP  s       r<   mockPackageExporter.mock2  s)    J >J!&&>
i9:r;   c                `    [        [        R                  U5      U R                  [	        XS9'   g)ar  Include ``module`` in the list of external modules the package can import.
This will prevent dependency discovery from saving
it in the package. The importer will load an external module directly from the standard import system.
Code for extern modules must also exist in the process loading the package.

Args:
    include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
        for the names of the modules to be externed. This can also be a glob-style pattern, as
        described in :meth:`mock`.

    exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the
        include string.

    allow_empty (bool): An optional flag that specifies whether the extern modules specified by this call
        to the ``extern`` method must be matched to some module during packaging. If an extern module glob
        pattern is added with ``allow_empty=False``, and :meth:`close` is called (either explicitly or via
        ``__exit__``) before any modules match that pattern, an exception is thrown. If ``allow_empty=True``,
        no such exception is thrown.

rO  N)rQ   r'   r5   r   r   rP  s       r<   externPackageExporter.extern[  s(    6 >J!((+>
i9:r;   rO  c                \    [        [        R                  SS9U R                  [	        XS9'   g)a  Blocklist modules who names match the given glob patterns from the list of modules the package can import.
If a dependency on any matching packages is found, a :class:`PackagingError` is raised.

Args:
    include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
        for the names of the modules to be externed. This can also be a glob-style pattern, as described in :meth:`mock`.

    exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.
T)rT   rO  N)rQ   r'   r7   r   r   )rF   rM  rL  s      r<   denyPackageExporter.denyz  s(     >J!&&D>
i9:r;   c                 &   [         R                  " U5      (       d*  [        U[         R                  R                  5      (       Ga  [        U[         R                  R                  5      (       aM  UR
                  nUR                  5       n[        [         U5      n[        [        U5      nUR                  5       nOm[        U[         R                  5      (       a7  Un[        [        U5      n[        [        U5      5      nUR                  5       nO[        S[        U5       35      e[!        U5      nU R"                  R%                  U5      nU R"                  R'                  U5      n	U(       dZ  UR(                  R                  S:w  a  UR+                  5       nUR                  5       n
U R,                  R/                  SU	 S3XZ5        SXIXv4$ [1        US5      (       a  [2        (       a4  [        U[         R4                  R6                  5      (       a  [9        S5      eU R:                  R=                  [?        U5      5      c5  S[?        U5      /URA                  U 5      Q7U R:                  [?        U5      '   U R:                  [?        U5         $ g )	Nzstorage type not recognized: cpuz.data/z.storagestorage__reduce_package__zSerializing ScriptModules directly into a package is a beta feature. To use, set global `torch.package.package_exporter._gate_torchscript_serialization` to `False`.reduce_package)!r   
is_storager   r^  TypedStorage_untyped_storagepickle_storage_typer   r   r   sizeUntypedStorager   r   nbytesRuntimeErrorr   r   has_storageget_or_add_storagedevicer]  r   write_recordr   _gate_torchscript_serializationjitRecursiveScriptModuler   r   rh   r@  r_  )rF   r
  untyped_storagestorage_type_strstorage_typer^  storage_numellocationstorage_present
storage_id	num_bytess              r<   r   PackageExporter._persistent_id  s   C  JsEMM4N4N$O$O#u}}99:: #&"6"6#&#:#:#< &u.>?w8 #
C!5!566"%w85d7mD ' 0"%B49+#NOO#G,H #22>>wGO--@@IJ">>&&%/%kkmG#NN,	**ZL17 |QQ3,--..:UYY444 4  c 
 &&**2c73;$sG4 ++D14''30 **2c733r;   c                     U $ Nr.   rE   s    r<   	__enter__PackageExporter.__enter__  s    r;   c                 L    Ub  U R                  5         g U R                  5         g rz  )_finalize_zipclose)rF   exc_type	exc_value	tracebacks       r<   __exit__PackageExporter.__exit__  s"      

r;   c                 J   XR                   ;   a  [        SU S35      eU R                   R                  U5        [        U5      (       a  [        SU S35      e[	        U[
        5      (       a  UR                  S5      nU R                  R                  X[        U5      5        g )NzTried to write file 'z<', but it already exists in this archive. Please file a bug.z+Tried to save a torch.package'd module as 'z:'. Directly saving torch.package'd modules is not allowed.r6  )
r   AssertionErroraddr   r   r   r8  r   rl  r   )rF   r   str_or_bytess      r<   r   PackageExporter._write  s    *** 'z 2% %  	)h =hZ HJ J  lC(('..w7L""83|;LMr;   c                 N   U R                   R                  R                  5        H'  nSU;   d  M  [        U R                   U R                  S9e   U R
                  R                  5        H8  u  p#UR                  (       a  M  UR                  (       a  M+  [        SU S35      e   g )Nrb   )rs   z&Exporter did not match any modules to z', which was marked as allow_empty=False)
r`   rf   valuesr$   rs   r   rg   rT   rU   r#   )rF   rv   r   r   s       r<   _validate_dependency_graph*PackageExporter._validate_dependency_graph  s    **00779E%$T%:%:$**MM :
 &*]]%8%8%:!G+++L4L4L4L%<WIElm  &;r;   c                     SU R                   ;  a@  [        [        [        5      R                  S-  5      nU R                  S[        U5      SS9  g g )Nz_mock.pyr   F)r   )r   r   r	   r   parentr   r   )rF   	mock_files     r<   _write_mock_file PackageExporter._write_mock_file  sI    T000DN11J>?I%%gz)/DQV%W 1r;   c                 &   U R                  5         / nU R                  R                  R                  5        GH  u  p#US   nU[        R
                  :X  a<  U R                  R                  5        H  nU" X5        M     UR                  U5        M[  U[        R                  :X  am  U R                  R                  5        H  nU" X5        M     U R                  5         [        U R                  U5      S5      nU R                  U[        U5        M  U[        R                   :X  as  U R"                  R                  5        H  nU" X5        M     SU;  a  [%        SU 35      eUR'                  S5      SL a  GMD  US   nUS   nU R                  X'U5        GMc  U[        R(                  :X  a  U R                  5         GM  U[        R*                  :X  a  GM  [%        S	U S
U S35      e   SR-                  U5      S-   nU R/                  SU5        g)zvTakes a finalized dependency graph describing how to package all
modules and executes it, writing to the ZIP archive.
rS   r   r   z-Module was marked `intern` but not provided: r  Tr   r   zInvalid action: z, z!. Please report a bug to PyTorch.rc   z.data/extern_modulesN)r  r`   rf   rg   r'   r5   r   r  ri   r6   r   r  r   r   r   
_MOCK_IMPLr4   r   r  rh   r8   r9   rp   r   )	rF   extern_modulesru   rv   rS   r>  r   r   extern_file_contentss	            r<   _execute_dependency_graph)PackageExporter._execute_dependency_graph  s    	'')"&"7"7"="="C"C"EK8_F.555 ..557D+ 8 %%k20555 ,,335D+ 6 %%'$T%8%8%EzR
))+z:N0777 ..557D+ 8
 U*(G}U  99[)T1"<0
x))+zJ0GGG%%'0555$&{m2fX=^_ U #F\  $yy84?*,@Ar;   c                 N    U R                  S[        R                  " 5       5        g)zSWrites the python version that the package was created with to .data/python_versionz.data/python_versionN)r   platformpython_versionrE   s    r<   _write_python_version%PackageExporter._write_python_version'  s    *H,C,C,EFr;   c                     U R                  5         U R                  5         U R                  R                  5         U R	                  5         g)zWrite the package to the filesystem. Any calls after :meth:`close` are now invalid.
It is preferable to use resource guard syntax instead::

    with PackageExporter("file.zip") as e:
        ...
N)r  r  r   write_filesr~  rE   s    r<   r  PackageExporter.close+  s:     	&&(""$%%113r;   c                 `    U ? U R                  (       a  U R                  R                  5         gg)zUCalled at the very end of packaging to leave the zipfile in a closed but valid state.N)r   r   flushrE   s    r<   r~  PackageExporter._finalize_zip8  s#    M;;KK r;   c                 J    UR                  SS5      n[        U5      nU SU 3$ )NrA   r   )r   r   )rF   r  r	  package_paths       r<   r  PackageExporter._filename>  s-    sC0"8,q
++r;   c                 x    UR                  S5      S   nUS:H  =(       d    U[        ;  =(       a    [        U5      $ )NrA   r   r   )	partitionrn   r   )rF   ru   top_level_package_names      r<   r   &PackageExporter._can_implicitly_externC  sA    !,!6!6s!;A!>%0 
"*== 9 !78	
r;   c                 6    U R                   R                  5       $ )zReturns digraph string representation of dependencies in package.

Returns:
    A string representation of dependencies in package.
)r`   to_dotrE   s    r<   dependency_graph_string'PackageExporter.dependency_graph_stringJ  s     $$++--r;   rS   c                     / nU R                   R                  R                  5        H7  u  p4UR                  SS 5      nXQ:X  d  M  SU;  d  M&  UR	                  U5        M9     UR                  5         U$ )NrS   r  )r`   rf   rg   rh   ri   sort)rF   rS   resultrD   	node_dictnode_actions         r<   _nodes_with_action_type'PackageExporter._nodes_with_action_typeR  sd     #44::@@BOD#--$7K$I)Ed#  C 	r;   c                 @    U R                  [        R                  5      $ )zReturn all modules that are currently externed.

Returns:
    A list containing the names of modules which will be
    externed in this package.
)r  r'   r5   rE   s    r<   externed_modules PackageExporter.externed_modules]       ++,A,H,HIIr;   c                 @    U R                  [        R                  5      $ )zReturn all modules that are currently interned.

Returns:
    A list containing the names of modules which will be
    interned in this package.
)r  r'   r4   rE   s    r<   interned_modules PackageExporter.interned_modulesf  r  r;   c                 @    U R                  [        R                  5      $ )zReturn all modules that are currently mocked.

Returns:
    A list containing the names of modules which will be
    mocked in this package.
)r  r'   r6   rE   s    r<   r  PackageExporter.mocked_moduleso       ++,A,F,FGGr;   c                 @    U R                  [        R                  5      $ )zReturn all modules that are currently denied.

Returns:
    A list containing the names of modules which will be
    denied in this package.
)r  r'   r7   rE   s    r<   denied_modulesPackageExporter.denied_modulesx  r  r;   c                     XR                   R                  R                  5       ;   a0  [        U R                   R                  U   R                  5       5      $ / $ )zReturn a list of all modules which depend on the module ``module_name``.

Returns:
    A list containing the names of modules which depend on ``module_name``.
)r`   _predr   re   r   s     r<   	get_rdepsPackageExporter.get_rdeps  sI     //55::<<--33K@EEGHHIr;   dstc                 8    U R                   R                  X5      $ )zReturn a dot representation of the subgraph
   that has all paths from src to dst.

Returns:
    A dot representation containing all paths from src to dst.
    (https://graphviz.org/doc/info/lang.html)
)r`   	all_paths)rF   r   r  s      r<   r  PackageExporter.all_paths  s     $$..s88r;   )r   r   r   r   r   r   rs   r`   r   r   r   r   r   r   )T)FTr|   )Tr*   )rM  r   rL  r   )Br/   r0   r1   r2   r3   r   rZ   r!   r   r   r   r[   rX   r   r   r   re   r   r   r   r   r   types
ModuleTyper   r   r   r   r   r
   r%  r2  r9  bytesr7  
ActionHookr   rC  rG  rJ  rQ  rT  rW  rZ  r   r{  r  r   r  r  r  r  r  r~  r  r   r  r'   r  r  r  r  r  r  r  r:   r.   r;   r<   r%   r%      s   2 
 9E	99 (8"4459 	9
 
9x FJ44364ls /)/)%(/)6:/)	c/)j !!)) ) 	)
 )F !	## # 	#
5# 
5# $ E,<,< #  9
# 9
v7s 7 6)6) 6)z " A*A* A* 	A*
 A* A*FI I I3 I	&U 	&  &z o &  . "$ 

 	

 
< "$ '
'
 	'

 '
Z "$ 

 	

 
> HJ 
4l	N"X
6BpG ,

# 
. .	45		c	J$s) JJ$s) JHS	 HHS	 H	S 	T#Y 	9S 9s 9s 9r;   sysrj   z~from _mock import MockedObject
def __getattr__(attr: str):
    return MockedObject(__name__ + '.' + attr, _suppress_err=True)
r   r   c                     [        U S5       nUR                  5       nUR                  S5      sS S S 5        $ ! , (       d  f       g = f)Nrbr6  )openreaddecode)r   r   bs      r<   r   r     s1    	h	FFHxx  
		s	   !8
A)Fr   importlib.machineryr  rj   r   r   r#  r  r  r   r   collections.abcr   dataclassesr   enumr   r   pathlibr	   typingr
   r   r   r   r   r   r   torch.serializationr   r   torch.typesr   r   torch.utils.hooksr   _digraphr   
_importlibr   	_manglingr   r   _package_picklerr   _stdlibr   find_file_dependenciesr   
glob_groupr   r   r   r   r    r!   __all__rm  r   r  r'   r"   rQ   r   r#   r$   r%   rn   r  r   r.   r;   r<   <module>r     s      	  	    0 $ !  0  ; ;  D ) -  ' + , % @ . = = #' (#.45
D *4 : ! ! ! i 3-Y 3-lh9 h9Z dm 
! ! !r;   