#!/usr/bin/env python# -*- coding: utf-8; -*-# Copyright (c) 2022 Oracle and/or its affiliates.# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/importconfigparserimportosfromtypingimportListimporturllib.parseimportfsspecfromads.common.decorator.runtime_dependencyimport(runtime_dependency,OptionalDependency,)
[docs]classOperatorNotFound(Exception):# pragma: no coverpass
[docs]classCondaPackInfoNotProvided(Exception):# pragma: no coverpass
[docs]classNotSupportedError(Exception):# pragma: no coverpass
[docs]defread_from_ini(path:str)->configparser.ConfigParser:ifnotos.path.exists(path):raiseFileNotFoundError(f"File {path} is not found.")parser=configparser.ConfigParser(default_section=None)parser.optionxform=str# preserve caseparser.read(path)returnparser
[docs]@runtime_dependency(module="nbformat",install_from=OptionalDependency.OPCTL)@runtime_dependency(module="nbconvert",install_from=OptionalDependency.OPCTL)defconvert_notebook(input_path,auth,exclude_tags:List=None,output_path:str=None,overwrite:bool=False,)->str:withfsspec.open(input_path,**auth)asf:nb=nbformat.reads(f.read(),nbformat.NO_CONVERT)fromnbconvert.preprocessorsimportTagRemovePreprocessorfromnbconvert.exportersimportPythonExporterexporter=PythonExporter()ifexclude_tags:exporter.register_preprocessor(TagRemovePreprocessor(remove_cell_tags=exclude_tags),enabled=True)output,_=exporter.from_notebook_node(nb)output=output.strip("\n")output_path=output_pathoros.path.splitext(input_path)[0]+".py"file_system_clz=fsspec.get_filesystem_class(urllib.parse.urlparse(output_path).schemeor"file")file_system=file_system_clz(**auth)ifnotoverwriteandfile_system.exists(output_path):raiseFileExistsError(f"{output_path} exists. Please rename your notebook or use overwrite option.")withfsspec.open(output_path,mode="wb",**auth)asf:f.write(output.encode("utf-8"))returnoutput_path