# -*- coding: utf-8 -*-
# *******************************************************
#   ____                     _               _
#  / ___|___  _ __ ___   ___| |_   _ __ ___ | |
# | |   / _ \| '_ ` _ \ / _ \ __| | '_ ` _ \| |
# | |__| (_) | | | | | |  __/ |_ _| | | | | | |
#  \____\___/|_| |_| |_|\___|\__(_)_| |_| |_|_|
#
#  Sign up for free at http://www.comet.ml
#  Copyright (C) 2015-2021 Comet ML INC
#  This file can not be copied and/or distributed without the express
#  permission of Comet ML Inc.
# *******************************************************
import copy
import logging

from ..monkey_patching import check_module

LOGGER = logging.getLogger(__name__)


def pre_process_params(params):
    try:
        if "random_state" in params:
            our_params = copy.copy(params)
            if our_params["random_state"].__class__.__name__ == "RandomState":
                del our_params["random_state"]
                return our_params

    except Exception as e:
        LOGGER.info(
            "failed to remove RandomState from sklearn object with error %s",
            e,
            exc_info=True,
        )

    return params


def _log_estimator_params(experiment, estimator):
    if experiment.auto_param_logging:
        try:
            params = estimator.get_params()
            processed_params = pre_process_params(params)
            experiment._log_parameters(processed_params, framework="sklearn")
        except Exception:
            LOGGER.error("Failed to extract parameters from estimator", exc_info=True)


def fit_logger_before(experiment, original, *args, **kwargs):
    _log_estimator_params(experiment, args[0])


def fit_logger_after(experiment, original, ret_val, *args, **kwargs):
    _log_estimator_params(experiment, ret_val)


def _log_pipeline_params(experiment, pipeline):
    if experiment.auto_param_logging:
        try:
            params = pipeline.get_params()
            if params is not None and "steps" in params:
                for step in params["steps"]:
                    step_name, step_mdl = step
                    params = step_mdl.get_params()
                    processed_params = pre_process_params(params)
                    experiment._log_parameters(
                        processed_params, prefix=step_name, framework="sklearn"
                    )
        except Exception:
            LOGGER.error("Failed to extract parameters from Pipeline", exc_info=True)


def pipeline_fit_logger_before(experiment, original, *args, **kwargs):
    _log_pipeline_params(experiment, args[0])


def pipeline_fit_logger_after(experiment, original, ret_val, *args, **kwargs):
    _log_pipeline_params(experiment, ret_val)


# List generated by utils/generate_sklearn_entrypoints.py for Scikit-versions:
# * 0.20.4
# * 0.21.3
# * 0.22.2
# * 0.23.2
# * 0.24.0rc1
FIT_MODULES = [
    ("sklearn.calibration", "CalibratedClassifierCV.fit"),
    ("sklearn.calibration", "_SigmoidCalibration.fit"),
    ("sklearn.cluster._affinity_propagation", "AffinityPropagation.fit"),
    ("sklearn.cluster._agglomerative", "FeatureAgglomeration.fit"),
    ("sklearn.cluster._bicluster", "SpectralBiclustering.fit"),
    ("sklearn.cluster._bicluster", "SpectralCoclustering.fit"),
    ("sklearn.cluster._birch", "Birch.fit"),
    ("sklearn.cluster._dbscan", "DBSCAN.fit"),
    ("sklearn.cluster._kmeans", "MiniBatchKMeans.fit"),
    ("sklearn.cluster._mean_shift", "MeanShift.fit"),
    ("sklearn.cluster._optics", "OPTICS.fit"),
    ("sklearn.cluster._spectral", "SpectralClustering.fit"),
    ("sklearn.cluster.affinity_propagation_", "AffinityPropagation.fit"),
    ("sklearn.cluster.bicluster", "SpectralBiclustering.fit"),
    ("sklearn.cluster.bicluster", "SpectralCoclustering.fit"),
    ("sklearn.cluster.birch", "Birch.fit"),
    ("sklearn.cluster.dbscan_", "DBSCAN.fit"),
    ("sklearn.cluster.hierarchical", "FeatureAgglomeration.fit"),
    ("sklearn.cluster.k_means_", "MiniBatchKMeans.fit"),
    ("sklearn.cluster.mean_shift_", "MeanShift.fit"),
    ("sklearn.cluster.optics_", "OPTICS.fit"),
    ("sklearn.cluster.spectral", "SpectralClustering.fit"),
    ("sklearn.compose._column_transformer", "ColumnTransformer.fit"),
    ("sklearn.compose._target", "TransformedTargetRegressor.fit"),
    ("sklearn.covariance._elliptic_envelope", "EllipticEnvelope.fit"),
    ("sklearn.covariance._graph_lasso", "GraphicalLassoCV.fit"),
    ("sklearn.covariance._shrunk_covariance", "LedoitWolf.fit"),
    ("sklearn.covariance._shrunk_covariance", "OAS.fit"),
    ("sklearn.covariance._shrunk_covariance", "ShrunkCovariance.fit"),
    ("sklearn.covariance.elliptic_envelope", "EllipticEnvelope.fit"),
    ("sklearn.covariance.graph_lasso_", "GraphLasso.fit"),
    ("sklearn.covariance.graph_lasso_", "GraphLassoCV.fit"),
    ("sklearn.covariance.shrunk_covariance_", "LedoitWolf.fit"),
    ("sklearn.covariance.shrunk_covariance_", "OAS.fit"),
    ("sklearn.covariance.shrunk_covariance_", "ShrunkCovariance.fit"),
    ("sklearn.cross_decomposition._cca", "CCA.fit"),
    ("sklearn.cross_decomposition._pls", "CCA.fit"),
    ("sklearn.cross_decomposition._pls", "PLSCanonical.fit"),
    ("sklearn.cross_decomposition._pls", "PLSRegression.fit"),
    ("sklearn.cross_decomposition._pls", "PLSSVD.fit"),
    ("sklearn.cross_decomposition.cca_", "CCA.fit"),
    ("sklearn.cross_decomposition.pls_", "PLSCanonical.fit"),
    ("sklearn.cross_decomposition.pls_", "PLSRegression.fit"),
    ("sklearn.cross_decomposition.pls_", "PLSSVD.fit"),
    ("sklearn.decomposition._dict_learning", "DictionaryLearning.fit"),
    ("sklearn.decomposition._dict_learning", "MiniBatchDictionaryLearning.fit"),
    ("sklearn.decomposition._dict_learning", "SparseCoder.fit"),
    ("sklearn.decomposition._factor_analysis", "FactorAnalysis.fit"),
    ("sklearn.decomposition._fastica", "FastICA.fit"),
    ("sklearn.decomposition._incremental_pca", "IncrementalPCA.fit"),
    ("sklearn.decomposition._kernel_pca", "KernelPCA.fit"),
    ("sklearn.decomposition._lda", "LatentDirichletAllocation.fit"),
    ("sklearn.decomposition._nmf", "NMF.fit"),
    ("sklearn.decomposition._pca", "PCA.fit"),
    ("sklearn.decomposition._sparse_pca", "MiniBatchSparsePCA.fit"),
    ("sklearn.decomposition._truncated_svd", "TruncatedSVD.fit"),
    ("sklearn.decomposition.dict_learning", "DictionaryLearning.fit"),
    ("sklearn.decomposition.dict_learning", "MiniBatchDictionaryLearning.fit"),
    ("sklearn.decomposition.dict_learning", "SparseCoder.fit"),
    ("sklearn.decomposition.factor_analysis", "FactorAnalysis.fit"),
    ("sklearn.decomposition.fastica_", "FastICA.fit"),
    ("sklearn.decomposition.incremental_pca", "IncrementalPCA.fit"),
    ("sklearn.decomposition.kernel_pca", "KernelPCA.fit"),
    ("sklearn.decomposition.nmf", "NMF.fit"),
    ("sklearn.decomposition.online_lda", "LatentDirichletAllocation.fit"),
    ("sklearn.decomposition.pca", "PCA.fit"),
    ("sklearn.decomposition.sparse_pca", "MiniBatchSparsePCA.fit"),
    ("sklearn.decomposition.truncated_svd", "TruncatedSVD.fit"),
    ("sklearn.discriminant_analysis", "LinearDiscriminantAnalysis.fit"),
    ("sklearn.discriminant_analysis", "QuadraticDiscriminantAnalysis.fit"),
    ("sklearn.dummy", "DummyClassifier.fit"),
    ("sklearn.dummy", "DummyRegressor.fit"),
    ("sklearn.ensemble._bagging", "BaggingClassifier.fit"),
    ("sklearn.ensemble._bagging", "BaggingRegressor.fit"),
    ("sklearn.ensemble._forest", "ExtraTreesClassifier.fit"),
    ("sklearn.ensemble._forest", "ExtraTreesRegressor.fit"),
    ("sklearn.ensemble._forest", "RandomForestClassifier.fit"),
    ("sklearn.ensemble._forest", "RandomForestRegressor.fit"),
    ("sklearn.ensemble._forest", "RandomTreesEmbedding.fit"),
    ("sklearn.ensemble._gb", "GradientBoostingClassifier.fit"),
    ("sklearn.ensemble._gb", "GradientBoostingRegressor.fit"),
    ("sklearn.ensemble._hist_gradient_boosting.binning", "_BinMapper.fit"),
    (
        "sklearn.ensemble._hist_gradient_boosting.gradient_boosting",
        "HistGradientBoostingClassifier.fit",
    ),
    (
        "sklearn.ensemble._hist_gradient_boosting.gradient_boosting",
        "HistGradientBoostingRegressor.fit",
    ),
    ("sklearn.ensemble._iforest", "IsolationForest.fit"),
    ("sklearn.ensemble._stacking", "StackingClassifier.fit"),
    ("sklearn.ensemble._stacking", "StackingRegressor.fit"),
    ("sklearn.ensemble._voting", "VotingClassifier.fit"),
    ("sklearn.ensemble._voting", "VotingRegressor.fit"),
    ("sklearn.ensemble._weight_boosting", "AdaBoostClassifier.fit"),
    ("sklearn.ensemble._weight_boosting", "AdaBoostRegressor.fit"),
    ("sklearn.ensemble.bagging", "BaggingClassifier.fit"),
    ("sklearn.ensemble.bagging", "BaggingRegressor.fit"),
    ("sklearn.ensemble.forest", "ExtraTreesClassifier.fit"),
    ("sklearn.ensemble.forest", "ExtraTreesRegressor.fit"),
    ("sklearn.ensemble.forest", "RandomForestClassifier.fit"),
    ("sklearn.ensemble.forest", "RandomForestRegressor.fit"),
    ("sklearn.ensemble.forest", "RandomTreesEmbedding.fit"),
    ("sklearn.ensemble.gradient_boosting", "GradientBoostingClassifier.fit"),
    ("sklearn.ensemble.gradient_boosting", "GradientBoostingRegressor.fit"),
    ("sklearn.ensemble.iforest", "IsolationForest.fit"),
    ("sklearn.ensemble.voting", "VotingClassifier.fit"),
    ("sklearn.ensemble.voting", "VotingRegressor.fit"),
    ("sklearn.ensemble.voting_classifier", "VotingClassifier.fit"),
    ("sklearn.ensemble.weight_boosting", "AdaBoostClassifier.fit"),
    ("sklearn.ensemble.weight_boosting", "AdaBoostRegressor.fit"),
    ("sklearn.feature_extraction._dict_vectorizer", "DictVectorizer.fit"),
    ("sklearn.feature_extraction._hash", "FeatureHasher.fit"),
    ("sklearn.feature_extraction.dict_vectorizer", "DictVectorizer.fit"),
    ("sklearn.feature_extraction.hashing", "FeatureHasher.fit"),
    ("sklearn.feature_extraction.image", "PatchExtractor.fit"),
    ("sklearn.feature_extraction.text", "HashingVectorizer.fit"),
    ("sklearn.feature_extraction.text", "TfidfTransformer.fit"),
    ("sklearn.feature_extraction.text", "TfidfVectorizer.fit"),
    ("sklearn.feature_selection._from_model", "SelectFromModel.fit"),
    ("sklearn.feature_selection._rfe", "RFECV.fit"),
    ("sklearn.feature_selection._sequential", "SequentialFeatureSelector.fit"),
    ("sklearn.feature_selection._univariate_selection", "GenericUnivariateSelect.fit"),
    ("sklearn.feature_selection._univariate_selection", "SelectFdr.fit"),
    ("sklearn.feature_selection._univariate_selection", "SelectFpr.fit"),
    ("sklearn.feature_selection._univariate_selection", "SelectFwe.fit"),
    ("sklearn.feature_selection._univariate_selection", "SelectKBest.fit"),
    ("sklearn.feature_selection._univariate_selection", "SelectPercentile.fit"),
    ("sklearn.feature_selection._variance_threshold", "VarianceThreshold.fit"),
    ("sklearn.feature_selection.from_model", "SelectFromModel.fit"),
    ("sklearn.feature_selection.rfe", "RFECV.fit"),
    ("sklearn.feature_selection.univariate_selection", "GenericUnivariateSelect.fit"),
    ("sklearn.feature_selection.univariate_selection", "SelectFdr.fit"),
    ("sklearn.feature_selection.univariate_selection", "SelectFpr.fit"),
    ("sklearn.feature_selection.univariate_selection", "SelectFwe.fit"),
    ("sklearn.feature_selection.univariate_selection", "SelectKBest.fit"),
    ("sklearn.feature_selection.univariate_selection", "SelectPercentile.fit"),
    ("sklearn.feature_selection.variance_threshold", "VarianceThreshold.fit"),
    ("sklearn.gaussian_process._gpc", "GaussianProcessClassifier.fit"),
    ("sklearn.gaussian_process._gpc", "_BinaryGaussianProcessClassifierLaplace.fit"),
    ("sklearn.gaussian_process._gpr", "GaussianProcessRegressor.fit"),
    ("sklearn.gaussian_process.gpc", "GaussianProcessClassifier.fit"),
    ("sklearn.gaussian_process.gpc", "_BinaryGaussianProcessClassifierLaplace.fit"),
    ("sklearn.gaussian_process.gpr", "GaussianProcessRegressor.fit"),
    ("sklearn.impute", "MissingIndicator.fit"),
    ("sklearn.impute", "SimpleImputer.fit"),
    ("sklearn.impute._base", "MissingIndicator.fit"),
    ("sklearn.impute._base", "SimpleImputer.fit"),
    ("sklearn.impute._knn", "KNNImputer.fit"),
    ("sklearn.isotonic", "IsotonicRegression.fit"),
    ("sklearn.kernel_approximation", "AdditiveChi2Sampler.fit"),
    ("sklearn.kernel_approximation", "Nystroem.fit"),
    ("sklearn.kernel_approximation", "PolynomialCountSketch.fit"),
    ("sklearn.kernel_approximation", "RBFSampler.fit"),
    ("sklearn.kernel_approximation", "SkewedChi2Sampler.fit"),
    ("sklearn.kernel_ridge", "KernelRidge.fit"),
    ("sklearn.linear_model._base", "LinearRegression.fit"),
    ("sklearn.linear_model._bayes", "ARDRegression.fit"),
    ("sklearn.linear_model._bayes", "BayesianRidge.fit"),
    ("sklearn.linear_model._coordinate_descent", "ElasticNetCV.fit"),
    ("sklearn.linear_model._coordinate_descent", "LassoCV.fit"),
    ("sklearn.linear_model._coordinate_descent", "MultiTaskElasticNetCV.fit"),
    ("sklearn.linear_model._coordinate_descent", "MultiTaskLasso.fit"),
    ("sklearn.linear_model._coordinate_descent", "MultiTaskLassoCV.fit"),
    ("sklearn.linear_model._glm.glm", "GammaRegressor.fit"),
    ("sklearn.linear_model._glm.glm", "PoissonRegressor.fit"),
    ("sklearn.linear_model._glm.glm", "TweedieRegressor.fit"),
    ("sklearn.linear_model._huber", "HuberRegressor.fit"),
    ("sklearn.linear_model._least_angle", "LassoLarsCV.fit"),
    ("sklearn.linear_model._least_angle", "LassoLarsIC.fit"),
    ("sklearn.linear_model._logistic", "LogisticRegressionCV.fit"),
    ("sklearn.linear_model._omp", "OrthogonalMatchingPursuit.fit"),
    ("sklearn.linear_model._omp", "OrthogonalMatchingPursuitCV.fit"),
    ("sklearn.linear_model._passive_aggressive", "PassiveAggressiveClassifier.fit"),
    ("sklearn.linear_model._passive_aggressive", "PassiveAggressiveRegressor.fit"),
    ("sklearn.linear_model._perceptron", "Perceptron.fit"),
    ("sklearn.linear_model._ransac", "RANSACRegressor.fit"),
    ("sklearn.linear_model._ridge", "Ridge.fit"),
    ("sklearn.linear_model._ridge", "RidgeCV.fit"),
    ("sklearn.linear_model._ridge", "RidgeClassifier.fit"),
    ("sklearn.linear_model._ridge", "RidgeClassifierCV.fit"),
    ("sklearn.linear_model._ridge", "_RidgeGCV.fit"),
    ("sklearn.linear_model._stochastic_gradient", "SGDClassifier.fit"),
    ("sklearn.linear_model._stochastic_gradient", "SGDRegressor.fit"),
    ("sklearn.linear_model._theil_sen", "TheilSenRegressor.fit"),
    ("sklearn.linear_model.base", "LinearRegression.fit"),
    ("sklearn.linear_model.bayes", "ARDRegression.fit"),
    ("sklearn.linear_model.bayes", "BayesianRidge.fit"),
    ("sklearn.linear_model.coordinate_descent", "ElasticNetCV.fit"),
    ("sklearn.linear_model.coordinate_descent", "LassoCV.fit"),
    ("sklearn.linear_model.coordinate_descent", "MultiTaskElasticNetCV.fit"),
    ("sklearn.linear_model.coordinate_descent", "MultiTaskLasso.fit"),
    ("sklearn.linear_model.coordinate_descent", "MultiTaskLassoCV.fit"),
    ("sklearn.linear_model.huber", "HuberRegressor.fit"),
    ("sklearn.linear_model.least_angle", "LassoLarsCV.fit"),
    ("sklearn.linear_model.least_angle", "LassoLarsIC.fit"),
    ("sklearn.linear_model.logistic", "LogisticRegressionCV.fit"),
    ("sklearn.linear_model.omp", "OrthogonalMatchingPursuit.fit"),
    ("sklearn.linear_model.omp", "OrthogonalMatchingPursuitCV.fit"),
    ("sklearn.linear_model.passive_aggressive", "PassiveAggressiveClassifier.fit"),
    ("sklearn.linear_model.passive_aggressive", "PassiveAggressiveRegressor.fit"),
    ("sklearn.linear_model.perceptron", "Perceptron.fit"),
    ("sklearn.linear_model.randomized_l1", "RandomizedLasso.fit"),
    ("sklearn.linear_model.randomized_l1", "RandomizedLogisticRegression.fit"),
    ("sklearn.linear_model.ransac", "RANSACRegressor.fit"),
    ("sklearn.linear_model.ridge", "Ridge.fit"),
    ("sklearn.linear_model.ridge", "RidgeCV.fit"),
    ("sklearn.linear_model.ridge", "RidgeClassifier.fit"),
    ("sklearn.linear_model.ridge", "RidgeClassifierCV.fit"),
    ("sklearn.linear_model.ridge", "_RidgeGCV.fit"),
    ("sklearn.linear_model.stochastic_gradient", "SGDClassifier.fit"),
    ("sklearn.linear_model.stochastic_gradient", "SGDRegressor.fit"),
    ("sklearn.linear_model.theil_sen", "TheilSenRegressor.fit"),
    ("sklearn.manifold._isomap", "Isomap.fit"),
    ("sklearn.manifold._locally_linear", "LocallyLinearEmbedding.fit"),
    ("sklearn.manifold._mds", "MDS.fit"),
    ("sklearn.manifold._spectral_embedding", "SpectralEmbedding.fit"),
    ("sklearn.manifold._t_sne", "TSNE.fit"),
    ("sklearn.manifold.isomap", "Isomap.fit"),
    ("sklearn.manifold.locally_linear", "LocallyLinearEmbedding.fit"),
    ("sklearn.manifold.mds", "MDS.fit"),
    ("sklearn.manifold.spectral_embedding_", "SpectralEmbedding.fit"),
    ("sklearn.manifold.t_sne", "TSNE.fit"),
    ("sklearn.mixture._bayesian_mixture", "BayesianGaussianMixture.fit"),
    ("sklearn.mixture._gaussian_mixture", "GaussianMixture.fit"),
    ("sklearn.mixture.bayesian_mixture", "BayesianGaussianMixture.fit"),
    ("sklearn.mixture.gaussian_mixture", "GaussianMixture.fit"),
    ("sklearn.model_selection._search", "GridSearchCV.fit"),
    ("sklearn.model_selection._search", "RandomizedSearchCV.fit"),
    ("sklearn.multiclass", "OneVsOneClassifier.fit"),
    ("sklearn.multiclass", "OneVsRestClassifier.fit"),
    ("sklearn.multiclass", "OutputCodeClassifier.fit"),
    ("sklearn.multiclass", "_ConstantPredictor.fit"),
    ("sklearn.multioutput", "ClassifierChain.fit"),
    ("sklearn.multioutput", "MultiOutputClassifier.fit"),
    ("sklearn.multioutput", "MultiOutputEstimator.fit"),
    ("sklearn.multioutput", "MultiOutputRegressor.fit"),
    ("sklearn.multioutput", "RegressorChain.fit"),
    ("sklearn.naive_bayes", "BaseDiscreteNB.fit"),
    ("sklearn.naive_bayes", "BernoulliNB.fit"),
    ("sklearn.naive_bayes", "CategoricalNB.fit"),
    ("sklearn.naive_bayes", "ComplementNB.fit"),
    ("sklearn.naive_bayes", "GaussianNB.fit"),
    ("sklearn.naive_bayes", "MultinomialNB.fit"),
    ("sklearn.neighbors._classification", "KNeighborsClassifier.fit"),
    ("sklearn.neighbors._classification", "RadiusNeighborsClassifier.fit"),
    ("sklearn.neighbors._graph", "KNeighborsTransformer.fit"),
    ("sklearn.neighbors._graph", "RadiusNeighborsTransformer.fit"),
    ("sklearn.neighbors._kde", "KernelDensity.fit"),
    ("sklearn.neighbors._lof", "LocalOutlierFactor.fit"),
    ("sklearn.neighbors._nca", "NeighborhoodComponentsAnalysis.fit"),
    ("sklearn.neighbors._nearest_centroid", "NearestCentroid.fit"),
    ("sklearn.neighbors._regression", "KNeighborsRegressor.fit"),
    ("sklearn.neighbors._regression", "RadiusNeighborsRegressor.fit"),
    ("sklearn.neighbors._unsupervised", "NearestNeighbors.fit"),
    ("sklearn.neighbors.approximate", "GaussianRandomProjectionHash.fit"),
    ("sklearn.neighbors.approximate", "LSHForest.fit"),
    ("sklearn.neighbors.classification", "KNeighborsClassifier.fit"),
    ("sklearn.neighbors.classification", "RadiusNeighborsClassifier.fit"),
    ("sklearn.neighbors.kde", "KernelDensity.fit"),
    ("sklearn.neighbors.lof", "LocalOutlierFactor.fit"),
    ("sklearn.neighbors.nca", "NeighborhoodComponentsAnalysis.fit"),
    ("sklearn.neighbors.nearest_centroid", "NearestCentroid.fit"),
    ("sklearn.neighbors.regression", "KNeighborsRegressor.fit"),
    ("sklearn.neighbors.regression", "RadiusNeighborsRegressor.fit"),
    ("sklearn.neighbors.unsupervised", "NearestNeighbors.fit"),
    ("sklearn.neural_network._multilayer_perceptron", "MLPClassifier.fit"),
    ("sklearn.neural_network._multilayer_perceptron", "MLPRegressor.fit"),
    ("sklearn.neural_network._rbm", "BernoulliRBM.fit"),
    ("sklearn.neural_network.multilayer_perceptron", "MLPClassifier.fit"),
    ("sklearn.neural_network.multilayer_perceptron", "MLPRegressor.fit"),
    ("sklearn.neural_network.rbm", "BernoulliRBM.fit"),
    ("sklearn.pipeline", "FeatureUnion.fit"),
    ("sklearn.pipeline", "Pipeline.fit"),
    ("sklearn.preprocessing._data", "Binarizer.fit"),
    ("sklearn.preprocessing._data", "KernelCenterer.fit"),
    ("sklearn.preprocessing._data", "MaxAbsScaler.fit"),
    ("sklearn.preprocessing._data", "MinMaxScaler.fit"),
    ("sklearn.preprocessing._data", "Normalizer.fit"),
    ("sklearn.preprocessing._data", "PolynomialFeatures.fit"),
    ("sklearn.preprocessing._data", "PowerTransformer.fit"),
    ("sklearn.preprocessing._data", "QuantileTransformer.fit"),
    ("sklearn.preprocessing._data", "RobustScaler.fit"),
    ("sklearn.preprocessing._data", "StandardScaler.fit"),
    ("sklearn.preprocessing._discretization", "KBinsDiscretizer.fit"),
    ("sklearn.preprocessing._encoders", "OneHotEncoder.fit"),
    ("sklearn.preprocessing._encoders", "OrdinalEncoder.fit"),
    ("sklearn.preprocessing._function_transformer", "FunctionTransformer.fit"),
    ("sklearn.preprocessing._label", "LabelBinarizer.fit"),
    ("sklearn.preprocessing._label", "LabelEncoder.fit"),
    ("sklearn.preprocessing._label", "MultiLabelBinarizer.fit"),
    ("sklearn.preprocessing.data", "Binarizer.fit"),
    ("sklearn.preprocessing.data", "KernelCenterer.fit"),
    ("sklearn.preprocessing.data", "MaxAbsScaler.fit"),
    ("sklearn.preprocessing.data", "MinMaxScaler.fit"),
    ("sklearn.preprocessing.data", "Normalizer.fit"),
    ("sklearn.preprocessing.data", "PolynomialFeatures.fit"),
    ("sklearn.preprocessing.data", "PowerTransformer.fit"),
    ("sklearn.preprocessing.data", "QuantileTransformer.fit"),
    ("sklearn.preprocessing.data", "RobustScaler.fit"),
    ("sklearn.preprocessing.data", "StandardScaler.fit"),
    ("sklearn.preprocessing.imputation", "Imputer.fit"),
    ("sklearn.preprocessing.label", "LabelBinarizer.fit"),
    ("sklearn.preprocessing.label", "LabelEncoder.fit"),
    ("sklearn.preprocessing.label", "MultiLabelBinarizer.fit"),
    ("sklearn.random_projection", "GaussianRandomProjection.fit"),
    ("sklearn.random_projection", "SparseRandomProjection.fit"),
    ("sklearn.semi_supervised._label_propagation", "LabelPropagation.fit"),
    ("sklearn.semi_supervised._label_propagation", "LabelSpreading.fit"),
    ("sklearn.semi_supervised._self_training", "SelfTrainingClassifier.fit"),
    ("sklearn.semi_supervised.label_propagation", "LabelPropagation.fit"),
    ("sklearn.semi_supervised.label_propagation", "LabelSpreading.fit"),
    ("sklearn.svm._classes", "LinearSVC.fit"),
    ("sklearn.svm._classes", "LinearSVR.fit"),
    ("sklearn.svm._classes", "NuSVC.fit"),
    ("sklearn.svm._classes", "NuSVR.fit"),
    ("sklearn.svm._classes", "OneClassSVM.fit"),
    ("sklearn.svm._classes", "SVC.fit"),
    ("sklearn.svm._classes", "SVR.fit"),
    ("sklearn.svm.classes", "LinearSVC.fit"),
    ("sklearn.svm.classes", "LinearSVR.fit"),
    ("sklearn.svm.classes", "NuSVC.fit"),
    ("sklearn.svm.classes", "NuSVR.fit"),
    ("sklearn.svm.classes", "OneClassSVM.fit"),
    ("sklearn.svm.classes", "SVC.fit"),
    ("sklearn.svm.classes", "SVR.fit"),
    ("sklearn.tree._classes", "ExtraTreeClassifier.fit"),
    ("sklearn.tree._classes", "ExtraTreeRegressor.fit"),
    ("sklearn.tree.tree", "ExtraTreeClassifier.fit"),
    ("sklearn.tree.tree", "ExtraTreeRegressor.fit"),
]


PIPELINE_FIT_MODULES = [("sklearn.pipeline", "Pipeline.fit")]


def patch(module_finder):
    check_module("sklearn")

    # Register the pipeline fit methods
    for module, object_name in PIPELINE_FIT_MODULES:
        module_finder.register_before(module, object_name, pipeline_fit_logger_before)
        module_finder.register_after(module, object_name, pipeline_fit_logger_after)

    # Register the fit methods
    for module, object_name in FIT_MODULES:
        module_finder.register_before(module, object_name, fit_logger_before)
        module_finder.register_after(module, object_name, fit_logger_after)


check_module("sklearn")
