
    MhX                       d Z ddlmZ ddl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 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 i Z e            Zg dZd Zd Z d5dZ!d6dZ"d7dZ#d Z$dZ%dZ&d Z' G d de          Z(d Z)	 	 d6dddd8d'Z*d9d*Z+d+ Z,ddddddeefd:d0Z-d;d2Z.d<d3Z/	 	 	 	 	 	 	 d=d4Z0dS )>zNotebook format validators.    )annotationsN)deepcopy)Path)dedent)AnyOptional   )import_item)generate_corpus_id)ValidationError_validator_for_nameget_current_validator)get_version)DuplicateCellIdMissingIDFieldWarning)r   get_validatorisvalidNotebookValidationErrorbetter_validation_error	normalizevalidateiter_validatec                   t          | t                    r7|                                 D ]!\  }}|dk    rdnt          |          }|| |<   "n<t          | t                    r't          |           D ]\  }}t          |          | |<   | S )z relax any `additionalProperties`additionalPropertiesT)
isinstancedictitems_relax_additional_propertieslist	enumerate)objkeyvalueis       R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/nbformat/validator.pyr   r   %   s    #t 9))++ 	 	JC555;WX];^;^  CHH		
 
C		 9!# 	9 	9HAu1%88CFFJ    c                    | d         d         d                              ddi           | d         d         d                              ddi           | S )NdefinitionscelloneOf$refz#/definitions/unrecognized_celloutputz!#/definitions/unrecognized_output)append)schemas    r%   _allow_undefinedr/   3   sY    
=&!'*116;\2]^^^
=(#G,33V=`4abbbMr&   Fc                ,   | ddl m} |} t          d| z            }t          |dd          }||}|rt	          |          nt                      }|j        | |f}|t          vr\	 t          || |          }	n# t          $ r Y dS w xY w||k     rt          |	          }	t          |	          }	 ||	          t          |<   |rG	 t          || |          }	n# t          $ r Y dS w xY wt          |	          }	 ||	          t          |<   t          |         S )z%Load the JSON schema into a ValidatorNr	   )current_nbformatznbformat.v%snbformat_minorr   versionversion_minor) r1   r
   getattrr   r   name
validators_get_schema_jsonAttributeErrorr   r/   )
r4   r5   relax_add_propsr8   r1   vcurrent_minorcurrent_validatorversion_tupleschema_jsons
             r%   r   r   9   su   &&&&&&"NW,--AA/33M%59V+D111?T?V?V&+WmDMJ&&	*1g][[[KK 	 	 	44	 =((6{CCK*;77K$5$5k$B$B
=! 	C	*1g][[[KK 	 	 	44	
 3;??$5$5k$B$B
=!m$$s$   %A8 8
BBC 
C$#C$c                   ||f| j         v r7t          t          | j                  j        | j         ||f         z            }nQ|| j        k    r5t          t          | j                  j        | j         d         z            }nd}t          |          t          |                              d          5 }t          j	        |          }ddd           n# 1 swxY w Y   |S )zR
    Gets the json schema from a given imported library and nbformat version.
    NNz-Cannot find appropriate nbformat schema file.utf8)encodingN)
nbformat_schemastrr   __file__parentr2   r;   openjsonload)r=   r4   r5   schema_pathmsgfrA   s          r%   r:   r:   e   s    	1#444$qz**1A4EwP]F^4__``	)	)	)$qz**1A4El4SSTT=S!!!	k						0	0 #Aill# # # # # # # # # # # # # # #s   7CCCc                   t          |           }	 t          j                    5  t          j        dt                     t          j        dt
                     t          | |||d           ddd           n# 1 swxY w Y   	 | |k    rt          dS # t          $ r Y | |k    rt          dS w xY w# | |k    rt          w xY w)a  Checks whether the given notebook JSON conforms to the current
    notebook format schema. Returns True if the JSON is valid, and
    False otherwise.

    To see the individual errors that were encountered, please use the
    `validate` function instead.
    ignore)categoryF)repair_duplicate_cell_idsNT)	r   warningscatch_warningsfilterwarningsDeprecationWarningr   r   AssertionErrorr   )nbjsonrefr4   r5   origs        r%   r   r   v   sD    FD!$&& 	[ 	[#H7IJJJJ#H7LMMMMVS'=TYZZZZ	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ T>>   >     T>>   >
 T>>      sG   B AA;/B ;A??B A?B 
B1 B4 0B11B4 4Cc                N    | sdS dd                     d | D                       z  S )z
    (from jsonschema._utils.format_as_index, copied to avoid relying on private API)

    Construct a single string containing indexing operations for the indices.

    For example, [1, 2, "foo"] -> [1][2]["foo"]
    r6   z[%s]z][c              3  4   K   | ]}t          |          V  d S N)repr).0indexs     r%   	<genexpr>z#_format_as_index.<locals>.<genexpr>   s(      ??ed5kk??????r&   )join)indicess    r%   _format_as_indexre      s7      rDII??w???????r&      @   c                   t          | t                    rd t          |                                           dt                   D             }t          |                    d          t                    rdt          | d                   z  g|d<   t          |                    d          t                    rdt          | d                   z  g|d<   t          |           t          k    rdt          |           t          z
  z  |d<   |S t          | t                    r`d	 | dt                   D             }t          |           t          k    r-|                    d
t          |           t          z
  z             |S t          | t                    r.| dt                   }t          |           t          k    r|dz  }|S | S )zTruncate objects for use in validation tracebacks

    Cell and output lists are squashed, as are long strings, lists, and dicts.
    c                4    i | ]\  }}|t          |          S  _truncate_obj)r`   kr=   s      r%   
<dictcomp>z!_truncate_obj.<locals>.<dictcomp>   s&    ZZZ$!Q!]1--ZZZr&   Ncellsz...%i cells...outputsz...%i outputs...z%i keys truncatedz...c                ,    g | ]}t          |          S rj   rk   )r`   items     r%   
<listcomp>z!_truncate_obj.<locals>.<listcomp>   s     LLL$---LLLr&   z...%i items truncated...)
r   r   r   r   _ITEM_LIMITgetlenr-   rG   
_STR_LIMIT)r!   truncated_dicttruncated_listtruncated_strs       r%   rl   rl      s   
 #t 	ZZ$syy{{:K:KL[L:YZZZn((11488 	M'7#c'l:K:K'K&LN7#n((33T:: 	S);c#i.>Q>Q)Q(RN9%s88k!!$73s88k;Q$RN5!#t LL#l{l:KLLLs88k!!!!"<C;@V"WXXX#s KZK(s88j  U"MJr&   c                  *    e Zd ZdZddZd Zd ZeZdS )r   zcSchema ValidationError with truncated representation

    to avoid massive verbose tracebacks.
    Nc                l    || _         t          | j         d|          | _        | j         j        | _        dS )zInitialize the error class.rZ   N)originalr7   rZ   message)selfr}   rZ   s      r%   __init__z NotebookValidationError.__init__   s.     4=%55},r&   c                ,    t          | j        |          S )z Get an attribute from the error.)r7   r}   )r   r"   s     r%   __getattr__z#NotebookValidationError.__getattr__   s    t}c***r&   c                Z   | j         }t          |j                  }d                    |j        dd                    |j        | j        pdt          t          |j
                  dd                             ddt          |j                  z  t          j        |d	          g          S )
zbCustom str for validation errors

        avoids dumping full schema and notebook to logs
        
r6   zFailed validating {!r} in {}{}:notebookNzOn instance%s:N   )width)r}   rl   instancerc   r~   format	validatorrZ   re   r   relative_schema_pathrelative_pathpprintpformat)r   errorr   s      r%   __unicode__z#NotebookValidationError.__unicode__   s    
  00yy188OH*
$T%*D%E%Ecrc%JKK 
  #3E4G#H#HHxr222
 
 	
r&   r^   )__name__
__module____qualname____doc__r   r   r   __str__rj   r&   r%   r   r      sQ         
- - - -+ + +
 
 
. GGGr&   r   c                >   t          | j                  s| S | j        d         }d}|                    d          rt          | j        t
                    r0d| j        v r| j        d         dz   }nd| j        v r| j        d         }|r	 t          | j        |||           nn# t          $ rV}| j        	                    |j                   | j        |_        t          |||          }|j        ||_        |cY d}~S d}~wt          $ r Y nw xY wt          | |          S )zGet better ValidationError on oneOf failures

    oneOf errors aren't informative.
    if it's a cell type or output_type error,
    try validating directly based on the type for a better error message
    r   NOf	cell_type_celloutput_typer3   )rv   rM   endswithr   r   r   r   r   r   extendr   rZ   	Exceptionr   )r   r4   r5   r"   rZ   	sub_errorbetters          r%   r   r      sf    u !! 

B
C
C
||D end++ 	4en,,n[1G;%.00n]3 	N#"/	     #   #**9+BCCC*/*=	'0G]SS:%!$FJ     #5#...s%   B! !
D+AC<6D<DDr<   strip_invalid_metadatanbdictr   r4   Optional[int]r5   r<   boolr   returntuple[int, Any]c               ~    t          |           } t          |           \  }}||}||}t          | ||d||          S )a  
    Normalise a notebook prior to validation.

    This tries to implement a couple of normalisation steps to standardise
    notebooks and make validation easier.

    You should in general not rely on this function and make sure the notebooks
    that reach nbformat are already in a normal form. If not you likely have a bug,
    and may have security issues.

    Parameters
    ----------
    nbdict : dict
        notebook document
    version : int
    version_minor : int
    relax_add_props : bool
        Whether to allow extra property in the Json schema validating the
        notebook.
    strip_invalid_metadata : bool
        Whether to strip metadata that does not exist in the Json schema when
        validating the notebook.

    Returns
    -------
    changes : int
        number of changes in the notebooks
    notebook : dict
        deep-copy of the original object with relevant changes.

    NTr   )r   r   
_normalize)r   r4   r5   r<   r   nbdict_versionnbdict_version_minors          r%   r   r     sc    N fF+6v+>+>(N( ,'5   r&   intrS   c                   d}||fdk    r| d         D ]:}d|vr4t          j        dt          d           |rt                      |d<   |dz  };t	                      }| d         D ]{}d|vr|d         }	|	|v rS|r<t                      }
|
|d<   |dz  }t          j        d	|	d
|
dt
          d           nd|	 d}t          |          |                    |	           ||r|t          | |||          z  }|| fS )a  
    Private normalisation routine.

    This function attempts to normalize the `nbdict` passed to it.

    As `_normalize()` is currently used both in `validate()` (for
    historical reasons), and in the `normalize()` public function,
    `_normalize()` does currently mutate `nbdict`.
    Ideally, once `validate()` stops calling `_normalize()`, `_normalize()`
    may stop mutating `nbdict`.

    r   )      ro   ida)  Cell is missing an id field, this will become a hard error in future nbformat versions. You may want to use `normalize()` on your notebooks before validations (available since nbformat 5.1.4). Previous versions of nbformat are fixing this issue transparently, and will stop doing so in the future.   
stacklevelr	   zNon-unique cell id z detected. Corrected to .zNon-unique cell id 'z' detected.r<   )	rT   warnr   r   setr   r   add_strip_invalida_metadata)r   r4   r5   rS   r<   r   changesr)   seen_idscell_idnew_idrN   s               r%   r   r   E  s   ( G6))7O 	! 	!D4& * 	 	 	 	 - !!3!5!5DJqLG 557O 	" 	"D44jG("", //11F!'DJqLGM\g\\QW\\\'#$     FEEEC)#...LL!!!! 
+G]O
 
 
 	
 F?r&   c                `    t          j        t          d|  d          t          d           d S )N`a7  ` kwargs of validate has been deprecated for security
        reasons, and will be removed soon.

        Please explicitly use the `n_changes, new_notebook = nbformat.validator.normalize(old_notebook, ...)` if you wish to
        normalise your notebook. `normalize` is available since nbformat 5.5.0

        r   r   )rT   r   r   rW   )fields    r%   	_dep_warnr     sP    M%   	
 	
 	     r&   rZ   Optional[str]rY   Nonec                   t          |t                    s|J |t          u rd}nt          d           |t          u rd}nt          d           | n||} nd}t	          |          |t          |           \  }	}
||	}||
}n|d\  }}|Ct          |t                    sJ t          |t                    sJ t          | |||||           t          | |||||	          D ]}|dS )
a  Checks whether the given notebook dict-like object
    conforms to the relevant notebook format schema.

    Parameters
    ----------
    nbdict : dict
        notebook document
    ref : optional, str
        reference to the subset of the schema we want to validate against.
        for example ``"markdown_cell"``, `"code_cell"` ....
    version : int
    version_minor : int
    relax_add_props : bool
        Whether to allow extra properties in the JSON schema validating the notebook.
        When True, all known fields are validated, but unknown fields are ignored.
    nbjson
    repair_duplicate_cell_ids : bool
        Deprecated since 5.5.0 - will be removed in the future.
    strip_invalid_metadata : bool
        Deprecated since 5.5.0 - will be removed in the future.

    Returns
    -------
    None

    Raises
    ------
    ValidationError if not valid.

    Notes
    -----
    Prior to Nbformat 5.5.0 the `validate` and `isvalid` method would silently
    try to fix invalid notebook and mutate arguments. This behavior is deprecated
    and will be removed in a near future.

    Please explicitly call `normalize` if you need to normalize notebooks.
    NFr   TrS   z0validate() missing 1 required argument: 'nbdict')r	   r   r   )rZ   r4   r5   r<   r   )	r   rG   _deprecatedr   	TypeErrorr   r   r   r   )r   rZ   r4   r5   r<   rY   rS   r   rN   r   r   r   s               r%   r   r     sf   ^ c3.3;;;,,!&*+++ K//$(!!-... 		@nn
{/:6/B/B,,?$G 0M	!%
{'3'''''------%+#9	
 	
 	
 	
 #'5      r&   argsc                (   t          |||          }|sd| d| d}t          |           |j        | g|R  }t          |          }t	          |          r,|j        dk    r!t          |||d          } |j        | g|R  S t          |          S )Nr   zNo schema for validating vr   
 notebooks
jsonschemar4   r5   r<   r8   )r   r   iter_errorsr   rv   r8   iter)	r   r4   r5   r<   r   r   rN   r   errorss	            r%   _get_errorsr      s     g}oVVVI #N7NN]NNNc"""')'6666K+F
6{{ 4y~55!'+	
 
 
	 %y$V3d3333<<r&   c                    t          | |||          }d}t          t          |                    dk    rt          |||d          }|sd| d| d}t	          |          |                    |           }|                    |          }d|v r,|d         D ]#}	| d                             |	d           |d	z  }$d
|v r<t          |                     d
d                    }
t          |
          D ]}d|d
         |         j
        v r| d
         |         d         }d |d
         |         j
        d         j        d         D             }d| d}||v r|                    |          }|d
         |         j
        d         j        D ]p}|j        }|j        d         |k    }t          |          dk    o|d         dk    }|r5|r3| d
         |         d                             |d	         d           |d	z  }q
|S )a  
    This function tries to extract metadata errors from the validator and fix
    them if necessary. This mostly mean stripping unknown keys from metadata
    fields, or removing metadata fields altogether.

    Parameters
    ----------
    nbdict : dict
        notebook document
    version : int
    version_minor : int
    relax_add_props : bool
        Whether to allow extra property in the Json schema validating the
        notebook.

    Returns
    -------
    int
        number of modifications

    r   r   r   zNo jsonschema for validating vr   r   metadataNr	   ro   r*   r   c                    g | ]
}|d          S )r+   rj   )r`   rZ   s     r%   rs   z,_strip_invalida_metadata.<locals>.<listcomp>J  s,     ( ( ( F( ( (r&   z#/definitions/r      )r   rv   r   r   r   r   
error_treepopru   ranger   r.   ra   contextr   rM   )r   r4   r5   r<   r   r   r   rN   r   r"   number_of_cellscell_idxintended_cell_typeschemas_by_indexcell_type_definition_nameschema_indexr   rel_patherror_for_intended_schemais_top_level_metadata_keys                       r%   r   r     sw   0 -IIFG
4<<1!'+	
 
 
	  	'V7VV]VVVC!#&&&&&v..))&11
##!*-  z"&&sD1111j  !&**Wa"8"899O!/22 - -
 j1(;BBB)/)B;)O&( (#-g#6x#@#G#P#WX_#`( ( ($ 1[AS0Z0Z0Z-04DDD'7'='=>W'X'X%/%8%B%I'%R%Z - -E',':H8=8I!8LP\8\5 #H 2 Px{j7P 6  9 -=V - &w 9* E I I(ST+W[ \ \ \ '1Nr&   c           	   #    K   | n||} nd}t          |          |t          |           \  }}|r6	 t          | |||dd|z  i          }n`# t          $ r}	|	V  Y d}	~	dS d}	~	ww xY w|rt	          | |||           	 t          | |||          }n# t          $ r}	|	V  Y d}	~	dS d}	~	ww xY w|D ]}
t          |
||          V  dS )at  Checks whether the given notebook dict-like object conforms to the
    relevant notebook format schema.

    Returns a generator of all ValidationErrors if not valid.

    Notes
    -----
    To fix: For security reasons, this function should *never* mutate its `nbdict` argument, and
    should *never* try to validate a mutated or modified version of its notebook.

    Nz5iter_validate() missing 1 required argument: 'nbdict'r+   z#/definitions/%s)r   r   r   r   r   r   )r   rZ   r4   r5   r<   rY   r   rN   r   er   s              r%   r   r   ^  s]     * 		Enn!,V!4!4
 
	 +c12 FF  	 	 	GGGFFFFF	
 " 	V$VWm_UUU	 -QQFF 	 	 	GGGFFFFF	  E E%eWmDDDDDDE Es/   A 
A%A  A%=B 
B)B$$B))NNFNrC   )NNN)r   r   r4   r   r5   r   r<   r   r   r   r   r   )r   r   r4   r   r5   r   rS   r   r<   r   r   r   r   r   )r   r   rZ   r   r4   r   r5   r   r<   r   rY   r   rS   r   r   r   r   r   )r   r   r4   r   r5   r   r<   r   r   r   r   r   )
r   r   r4   r   r5   r   r<   r   r   r   )NNNNFNF)1r   
__future__r   rK   r   rT   copyr   pathlibr   textwrapr   typingr   r   _importsr
   corpus.wordsr   json_compatr   r   r   readerr   r   r   r9   objectr   __all__r   r/   r   r:   r   re   rt   rw   rl   r   r   r   r   r   r   r   r   r   rj   r&   r%   <module>r      s   ! ! # " " " " "                                      ! ! ! ! ! ! , , , , , , T T T T T T T T T T       < < < < < < < <
fhh	 	 	    )% )% )% )%X   "! ! ! !.@ @ @ 
  8' ' ' ' 'o ' ' 'T&/ &/ &/V "#'4
 "#(4 4 4 4 4 4nB B B BJ  " !#'!&1#.c c c c cL   *F F F FT  <E <E <E <E <E <Er&   