sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
scikit-learn/scikit-learn:examples/release_highlights/plot_release_highlights_1_8_0.py
# ruff: noqa: CPY001 """ ======================================= Release Highlights for scikit-learn 1.8 ======================================= .. currentmodule:: sklearn We are pleased to announce the release of scikit-learn 1.8! Many bug fixes and improvements were added, as well as some key new features. Below we detail the highlights of this release. **For an exhaustive list of all the changes**, please refer to the :ref:`release notes <release_notes_1_8>`. To install the latest version (with pip):: pip install --upgrade scikit-learn or with conda:: conda install -c conda-forge scikit-learn """ # %% # Array API support (enables GPU computations) # -------------------------------------------- # The progressive adoption of the Python array API standard in # scikit-learn means that PyTorch and CuPy input arrays # are used directly. This means that in scikit-learn estimators # and functions non-CPU devices, such as GPUs, can be used # to perform the computation. As a result performance is improved # and integration with these libraries is easier. # # In scikit-learn 1.8, several estimators and functions have been updated to # support array API compatible inputs, for example PyTorch tensors and CuPy # arrays. # # Array API support was added to the following estimators: # :class:`preprocessing.StandardScaler`, # :class:`preprocessing.PolynomialFeatures`, :class:`linear_model.RidgeCV`, # :class:`linear_model.RidgeClassifierCV`, :class:`mixture.GaussianMixture` and # :class:`calibration.CalibratedClassifierCV`. # # Array API support was also added to several metrics in :mod:`sklearn.metrics` # module, see :ref:`array_api_supported` for more details. # # Please refer to the :ref:`array API support<array_api>` page for instructions # to use scikit-learn with array API compatible libraries such as PyTorch or CuPy. # Note: Array API support is experimental and must be explicitly enabled both # in SciPy and scikit-learn. # # Here is an excerpt of using a feature engineering preprocessor on the CPU, # followed by :class:`calibration.CalibratedClassifierCV` # and :class:`linear_model.RidgeCV` together on a GPU with the help of PyTorch: # # .. code-block:: python # # ridge_pipeline_gpu = make_pipeline( # # Ensure that all features (including categorical features) are preprocessed # # on the CPU and mapped to a numerical representation. # feature_preprocessor, # # Move the results to the GPU and perform computations there # FunctionTransformer( # lambda x: torch.tensor(x.to_numpy().astype(np.float32), device="cuda")) # , # CalibratedClassifierCV( # RidgeClassifierCV(alphas=alphas), method="temperature" # ), # ) # with sklearn.config_context(array_api_dispatch=True): # cv_results = cross_validate(ridge_pipeline_gpu, features, target) # # # See the `full notebook on Google Colab # <https://colab.research.google.com/drive/1ztH8gUPv31hSjEeR_8pw20qShTwViGRx?usp=sharing>`_ # for more details. On this particular example, using the Colab GPU vs using a # single CPU core leads to a 10x speedup which is quite typical for such workloads. # %% # Free-threaded CPython 3.14 support # ---------------------------------- # # scikit-learn has support for free-threaded CPython, in particular # free-threaded wheels are available for all of our supported platforms on Python # 3.14. # # We would be very interested by user feedback. Here are a few things you can # try: # # - install free-threaded CPython 3.14, run your favourite # scikit-learn script and check that nothing breaks unexpectedly. # Note that CPython 3.14 (rather than 3.13) is strongly advised because a # number of free-threaded bugs have been fixed since CPython 3.13. # - if you use some estimators with a `n_jobs` parameter, try changing the # default backend to threading with `joblib.parallel_config` as in the # snippet below. This could potentially speed-up your code because the # default joblib backend is process-based and incurs more overhead than # threads. # # .. code-block:: python # # grid_search = GridSearchCV(clf, param_grid=param_grid, n_jobs=4) # with joblib.parallel_config(backend="threading"): # grid_search.fit(X, y) # # - don't hesitate to report any issue or unexpected performance behaviour by # opening a `GitHub issue <https://github.com/scikit-learn/scikit-learn/issues/new/choose>`_! # # Free-threaded (also known as nogil) CPython is a version of CPython that aims # to enable efficient multi-threaded use cases by removing the Global # Interpreter Lock (GIL). # # For more details about free-threaded CPython see `py-free-threading doc # <https://py-free-threading.github.io>`_, in particular `how to install a # free-threaded CPython <https://py-free-threading.github.io/installing-cpython/>`_ # and `Ecosystem compatibility tracking <https://py-free-threading.github.io/tracking/>`_. # # In scikit-learn, one hope with free-threaded Python is to more efficiently # leverage multi-core CPUs by using thread workers instead of subprocess # workers for parallel computation when passing `n_jobs>1` in functions or # estimators. Efficiency gains are expected by removing the need for # inter-process communication. Be aware that switching the default joblib # backend and testing that everything works well with free-threaded Python is an # ongoing long-term effort. # %% # Temperature scaling in `CalibratedClassifierCV` # ----------------------------------------------- # Probability calibration of classifiers with temperature scaling is available in # :class:`calibration.CalibratedClassifierCV` by setting `method="temperature"`. # This method is particularly well suited for multiclass problems because it provides # (better) calibrated probabilities with a single free parameter. This is in # contrast to all the other available calibrations methods # which use a "One-vs-Rest" scheme that adds more parameters for each class. from sklearn.calibration import CalibratedClassifierCV from sklearn.datasets import make_classification from sklearn.naive_bayes import GaussianNB X, y = make_classification(n_classes=3, n_informative=8, random_state=42) clf = GaussianNB().fit(X, y) sig = CalibratedClassifierCV(clf, method="sigmoid", ensemble=False).fit(X, y) ts = CalibratedClassifierCV(clf, method="temperature", ensemble=False).fit(X, y) # %% # The following example shows that temperature scaling can produce better calibrated # probabilities than sigmoid calibration in multi-class classification problem # with 3 classes. import matplotlib.pyplot as plt from sklearn.calibration import CalibrationDisplay fig, axes = plt.subplots( figsize=(8, 4.5), ncols=3, sharey=True, ) for i, c in enumerate(ts.classes_): CalibrationDisplay.from_predictions( y == c, clf.predict_proba(X)[:, i], name="Uncalibrated", ax=axes[i], marker="s" ) CalibrationDisplay.from_predictions( y == c, ts.predict_proba(X)[:, i], name="Temperature scaling", ax=axes[i], marker="o", ) CalibrationDisplay.from_predictions( y == c, sig.predict_proba(X)[:, i], name="Sigmoid", ax=axes[i], marker="v" ) axes[i].set_title(f"Class {c}") axes[i].set_xlabel(None) axes[i].set_ylabel(None) axes[i].get_legend().remove() fig.suptitle("Reliability Diagrams per Class") fig.supxlabel("Mean Predicted Probability") fig.supylabel("Fraction of Class") fig.legend(*axes[0].get_legend_handles_labels(), loc=(0.72, 0.5)) plt.subplots_adjust(right=0.7) _ = fig.show() # %% # Efficiency improvements in linear models # ---------------------------------------- # The fit time has been massively reduced for squared error based estimators # with L1 penalty: `ElasticNet`, `Lasso`, `MultiTaskElasticNet`, # `MultiTaskLasso` and their CV variants. The fit time improvement is mainly # achieved by **gap safe screening rules**. They enable the coordinate descent # solver to set feature coefficients to zero early on and not look at them # again. The stronger the L1 penalty the earlier features can be excluded from # further updates. from time import time from sklearn.datasets import make_regression from sklearn.linear_model import ElasticNetCV X, y = make_regression(n_features=10_000, random_state=0) model = ElasticNetCV() tic = time() model.fit(X, y) toc = time() print(f"Fitting ElasticNetCV took {toc - tic:.3} seconds.") # %% # HTML representation of estimators # --------------------------------- # Hyperparameters in the dropdown table of the HTML representation now include # links to the online documentation. Docstring descriptions are also shown as # tooltips on hover. from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler clf = make_pipeline(StandardScaler(), LogisticRegression(random_state=0, C=10)) # %% # Expand the estimator diagram below by clicking on "LogisticRegression" and then on # "Parameters". clf # %% # DecisionTreeRegressor with `criterion="absolute_error"` # ------------------------------------------------------- # :class:`tree.DecisionTreeRegressor` with `criterion="absolute_error"` # now runs much faster. It has now `O(n * log(n))` complexity compared to # `O(n**2)` previously, which allows to scale to millions of data points. # # As an illustration, on a dataset with 100_000 samples and 1 feature, doing a # single split takes of the order of 100 ms, compared to ~20 seconds before. import time from sklearn.datasets import make_regression from sklearn.tree import DecisionTreeRegressor X, y = make_regression(n_samples=100_000, n_features=1) tree = DecisionTreeRegressor(criterion="absolute_error", max_depth=1) tic = time.time() tree.fit(X, y) elapsed = time.time() - tic print(f"Fit took {elapsed:.2f} seconds") # %% # ClassicalMDS # ------------ # Classical MDS, also known as "Principal Coordinates Analysis" (PCoA) # or "Torgerson's scaling" is now available within the `sklearn.manifold` # module. Classical MDS is close to PCA and instead of approximating # distances, it approximates pairwise scalar products, which has an exact # analytic solution in terms of eigendecomposition. # # Let's illustrate this new addition by using it on an S-curve dataset to # get a low-dimensional representation of the data. import matplotlib.pyplot as plt from matplotlib import ticker from sklearn import datasets, manifold n_samples = 1500 S_points, S_color = datasets.make_s_curve(n_samples, random_state=0) md_classical = manifold.ClassicalMDS(n_components=2) S_scaling = md_classical.fit_transform(S_points) fig = plt.figure(figsize=(8, 4)) ax1 = fig.add_subplot(1, 2, 1, projection="3d") x, y, z = S_points.T ax1.scatter(x, y, z, c=S_color, s=50, alpha=0.8) ax1.set_title("Original S-curve samples", size=16) ax1.view_init(azim=-60, elev=9) for axis in (ax1.xaxis, ax1.yaxis, ax1.zaxis): axis.set_major_locator(ticker.MultipleLocator(1)) ax2 = fig.add_subplot(1, 2, 2) x2, y2 = S_scaling.T ax2.scatter(x2, y2, c=S_color, s=50, alpha=0.8) ax2.set_title("Classical MDS", size=16) for axis in (ax2.xaxis, ax2.yaxis): axis.set_major_formatter(ticker.NullFormatter()) plt.show()
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "examples/release_highlights/plot_release_highlights_1_8_0.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 250, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
scikit-learn/scikit-learn:sklearn/utils/tests/test_dataframe.py
"""Tests for dataframe detection functions.""" import numpy as np import pytest from sklearn._min_dependencies import dependent_packages from sklearn.utils._dataframe import is_df_or_series, is_pandas_df, is_polars_df from sklearn.utils._testing import _convert_container @pytest.mark.parametrize("constructor_name", ["pyarrow", "dataframe", "polars"]) def test_is_df_or_series(constructor_name): df = _convert_container([[1, 4, 2], [3, 3, 6]], constructor_name) assert is_df_or_series(df) assert not is_df_or_series(np.asarray([1, 2, 3])) @pytest.mark.parametrize("constructor_name", ["pyarrow", "dataframe", "polars"]) def test_is_pandas_df_other_libraries(constructor_name): df = _convert_container([[1, 4, 2], [3, 3, 6]], constructor_name) if constructor_name in ("pyarrow", "polars"): assert not is_pandas_df(df) else: assert is_pandas_df(df) def test_is_pandas_df(): """Check behavior of is_pandas_df when pandas is installed.""" pd = pytest.importorskip("pandas") df = pd.DataFrame([[1, 2, 3]]) assert is_pandas_df(df) assert not is_pandas_df(np.asarray([1, 2, 3])) assert not is_pandas_df(1) def test_is_pandas_df_pandas_not_installed(hide_available_pandas): """Check is_pandas_df when pandas is not installed.""" assert not is_pandas_df(np.asarray([1, 2, 3])) assert not is_pandas_df(1) @pytest.mark.parametrize( "constructor_name, minversion", [ ("pyarrow", dependent_packages["pyarrow"][0]), ("dataframe", dependent_packages["pandas"][0]), ("polars", dependent_packages["polars"][0]), ], ) def test_is_polars_df_other_libraries(constructor_name, minversion): df = _convert_container( [[1, 4, 2], [3, 3, 6]], constructor_name, minversion=minversion, ) if constructor_name in ("pyarrow", "dataframe"): assert not is_polars_df(df) else: assert is_polars_df(df) def test_is_polars_df_for_duck_typed_polars_dataframe(): """Check is_polars_df for object that looks like a polars dataframe""" class NotAPolarsDataFrame: def __init__(self): self.columns = [1, 2, 3] self.schema = "my_schema" not_a_polars_df = NotAPolarsDataFrame() assert not is_polars_df(not_a_polars_df) def test_is_polars_df(): """Check that is_polars_df return False for non-dataframe objects.""" class LooksLikePolars: def __init__(self): self.columns = ["a", "b"] self.schema = ["a", "b"] assert not is_polars_df(LooksLikePolars())
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/utils/tests/test_dataframe.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scikit-learn/scikit-learn:build_tools/github/autoclose_prs.py
"""Close PRs labeled with 'autoclose' more than 14 days ago. Called from .github/workflows/autoclose-schedule.yml.""" import os from datetime import datetime, timedelta, timezone from pprint import pprint from github import Auth, Github def get_labeled_last_time(pr, label): labeled_time = datetime.max for event in pr.get_events(): if event.event == "labeled" and event.label.name == label: labeled_time = event.created_at return labeled_time dry_run = False cutoff_days = 14 gh_repo = "scikit-learn/scikit-learn" github_token = os.getenv("GITHUB_TOKEN") auth = Auth.Token(github_token) gh = Github(auth=auth) repo = gh.get_repo(gh_repo) now = datetime.now(timezone.utc) label = "autoclose" prs = [ each for each in repo.get_issues(labels=[label]) if each.pull_request is not None ] prs_info = [f"{pr.title}: {pr.html_url}" for pr in prs] print(f"Found {len(prs)} opened PRs with label {label}") pprint(prs_info) prs = [ pr for pr in prs if (now - get_labeled_last_time(pr, label)) > timedelta(days=cutoff_days) ] prs_info = [f"{pr.title} {pr.html_url}" for pr in prs] print(f"Found {len(prs)} PRs to autoclose") pprint(prs_info) message = ( "Thank you for your interest in contributing to scikit-learn, but we cannot " "accept your contribution as this pull request does not meet our development " "standards.\n\n" "Following our autoclose policy, we are closing this PR after allowing two " "weeks time for improvements.\n\n" "Thank you for your understanding. If you think your PR has been closed " "by mistake, please comment below." ) for pr in prs: print(f"Closing PR #{pr.number} with comment") if not dry_run: pr.create_comment(message) pr.edit(state="closed")
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "build_tools/github/autoclose_prs.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
scikit-learn/scikit-learn:sklearn/tree/tests/test_fenwick.py
import numpy as np from sklearn.tree._utils import PytestWeightedFenwickTree def test_cython_weighted_fenwick_tree(global_random_seed): """ Test Cython's weighted Fenwick tree implementation """ rng = np.random.default_rng(global_random_seed) n = 100 indices = rng.permutation(n) y = rng.normal(size=n) w = rng.integers(0, 4, size=n) y_included_so_far = np.zeros_like(y) w_included_so_far = np.zeros_like(w) tree = PytestWeightedFenwickTree(n) tree.py_reset(n) for i in range(n): idx = indices[i] tree.py_add(idx, y[idx], w[idx]) y_included_so_far[idx] = y[idx] w_included_so_far[idx] = w[idx] target = rng.uniform(0, w_included_so_far.sum()) t_idx_low, t_idx, cw, cwy = tree.py_search(target) # check the aggregates are consistent with the returned idx assert np.isclose(cw, np.sum(w_included_so_far[:t_idx])) assert np.isclose( cwy, np.sum(w_included_so_far[:t_idx] * y_included_so_far[:t_idx]) ) # check if the cumulative weight is less than or equal to the target # depending on t_idx_low and t_idx if t_idx_low == t_idx: assert cw < target else: assert cw == target # check that if we add the next non-null weight, we are above the target: next_weights = w_included_so_far[t_idx:][w_included_so_far[t_idx:] > 0] if next_weights.size > 0: assert cw + next_weights[0] > target # and not below the target for `t_idx_low`: next_weights = w_included_so_far[t_idx_low:][w_included_so_far[t_idx_low:] > 0] if next_weights.size > 0: assert cw + next_weights[0] >= target
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/tree/tests/test_fenwick.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scikit-learn/scikit-learn:sklearn/utils/_repr_html/tests/test_js.py
import socket import threading from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path import pytest @pytest.fixture(scope="session", autouse=True) def check_playwright(): """Skip tests if playwright is not installed. This fixture is used by the next fixture (which is autouse) to skip all tests if playwright is not installed.""" return pytest.importorskip("playwright") @pytest.fixture def local_server(request): """Start a simple HTTP server that serves custom HTML per test. Usage : ```python def test_something(page, local_server): url, set_html_response = local_server set_html_response("<html>...</html>") page.goto(url) ... ``` """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("127.0.0.1", 0)) PORT = s.getsockname()[1] html_content = "<html><body>Default</body></html>" def set_html_response(content): nonlocal html_content html_content = content class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(html_content.encode("utf-8")) # suppress logging def log_message(self, format, *args): return httpd = HTTPServer(("127.0.0.1", PORT), Handler) thread = threading.Thread(target=httpd.serve_forever, daemon=True) thread.start() yield f"http://127.0.0.1:{PORT}", set_html_response httpd.shutdown() def _make_page(body): """Helper to create an HTML page that includes `estimator.js` and the given body.""" js_path = Path(__file__).parent.parent / "estimator.js" with open(js_path, "r", encoding="utf-8") as f: script = f.read() return f""" <html> <head> <script>{script}</script> </head> <body> {body} </body> </html> """ def test_copy_paste(page, local_server): """Test that copyToClipboard copies the right text to the clipboard. Test requires clipboard permissions, which are granted through page's context. Assertion is done by reading back the clipboard content from the browser. This is easier than writing a cross platform clipboard reader. """ url, set_html_response = local_server copy_paste_html = _make_page( '<div class="sk-toggleable__content" data-param-prefix="prefix"/>' ) set_html_response(copy_paste_html) page.context.grant_permissions(["clipboard-read", "clipboard-write"]) page.goto(url) page.evaluate( "copyToClipboard('test', document.querySelector('.sk-toggleable__content'))" ) clipboard_content = page.evaluate("navigator.clipboard.readText()") # `copyToClipboard` function concatenates the `data-param-prefix` attribute # with the first argument. Hence we expect "prefixtest" and not just test. assert clipboard_content == "prefixtest" @pytest.mark.parametrize( "color,expected_theme", [ ( "black", "light", ), ( "white", "dark", ), ( "#828282", "light", ), ], ) def test_force_theme(page, local_server, color, expected_theme): """Test that forceTheme applies the right theme class to the element. A light color must lead to a dark theme and vice-versa. """ url, set_html_response = local_server html = _make_page('<div style="color: ${color};"><div id="test"></div></div>') set_html_response(html.replace("${color}", color)) page.goto(url) page.evaluate("forceTheme('test')") assert page.locator("#test").evaluate( f"el => el.classList.contains('{expected_theme}')" )
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/utils/_repr_html/tests/test_js.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scikit-learn/scikit-learn:sklearn/manifold/_classical_mds.py
""" Classical multi-dimensional scaling (classical MDS). """ # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause from numbers import Integral import numpy as np from scipy import linalg from sklearn.base import BaseEstimator, _fit_context from sklearn.metrics import pairwise_distances from sklearn.utils import check_symmetric from sklearn.utils._param_validation import Interval from sklearn.utils.extmath import svd_flip from sklearn.utils.validation import validate_data class ClassicalMDS(BaseEstimator): """Classical multidimensional scaling (MDS). This is also known as principal coordinates analysis (PCoA) or Torgerson's scaling. It is a version of MDS that has exact solution in terms of eigendecomposition. If the input dissimilarity matrix consists of the pairwise Euclidean distances between some vectors, then classical MDS is equivalent to PCA applied to this set of vectors. Read more in the :ref:`User Guide <multidimensional_scaling>`. Parameters ---------- n_components : int, default=2 Number of embedding dimensions. metric : str or callable, default='euclidean' Metric to use for dissimilarity computation. Default is "euclidean". If metric is a string, it must be one of the options allowed by `scipy.spatial.distance.pdist` for its metric parameter, or a metric listed in :func:`sklearn.metrics.pairwise.distance_metrics` If metric is "precomputed", X is assumed to be a distance matrix and must be square during fit. If metric is a callable function, it takes two arrays representing 1D vectors as inputs and must return one value indicating the distance between those vectors. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. metric_params : dict, default=None Additional keyword arguments for the dissimilarity computation. Attributes ---------- embedding_ : ndarray of shape (n_samples, n_components) Stores the position of the dataset in the embedding space. dissimilarity_matrix_ : ndarray of shape (n_samples, n_samples) Pairwise dissimilarities between the points. eigenvalues_ : ndarray of shape (n_components,) Eigenvalues of the double-centered dissimilarity matrix, corresponding to each of the selected components. They are equal to the squared 2-norms of the `n_components` variables in the embedding space. n_features_in_ : int Number of features seen during :term:`fit`. feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. See Also -------- sklearn.decomposition.PCA : Principal component analysis. MDS : Metric and non-metric MDS. References ---------- .. [1] "Modern Multidimensional Scaling - Theory and Applications" Borg, I.; Groenen P. Springer Series in Statistics (1997) Examples -------- >>> from sklearn.datasets import load_digits >>> from sklearn.manifold import ClassicalMDS >>> X, _ = load_digits(return_X_y=True) >>> X.shape (1797, 64) >>> cmds = ClassicalMDS(n_components=2) >>> X_emb = cmds.fit_transform(X[:100]) >>> X_emb.shape (100, 2) """ _parameter_constraints: dict = { "n_components": [Interval(Integral, 1, None, closed="left")], "metric": [str, callable], "metric_params": [dict, None], } def __init__( self, n_components=2, *, metric="euclidean", metric_params=None, ): self.n_components = n_components self.metric = metric self.metric_params = metric_params def __sklearn_tags__(self): tags = super().__sklearn_tags__() tags.input_tags.pairwise = self.metric == "precomputed" return tags def fit(self, X, y=None): """ Compute the embedding positions. Parameters ---------- X : array-like of shape (n_samples, n_features) or \ (n_samples, n_samples) Input data. If ``metric=='precomputed'``, the input should be the dissimilarity matrix. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Fitted estimator. """ self.fit_transform(X) return self @_fit_context(prefer_skip_nested_validation=True) def fit_transform(self, X, y=None): """ Compute and return the embedding positions. Parameters ---------- X : array-like of shape (n_samples, n_features) or \ (n_samples, n_samples) Input data. If ``metric=='precomputed'``, the input should be the dissimilarity matrix. y : Ignored Not used, present for API consistency by convention. Returns ------- X_new : ndarray of shape (n_samples, n_components) The embedding coordinates. """ X = validate_data(self, X) if self.metric == "precomputed": self.dissimilarity_matrix_ = X self.dissimilarity_matrix_ = check_symmetric( self.dissimilarity_matrix_, raise_exception=True ) else: self.dissimilarity_matrix_ = pairwise_distances( X, metric=self.metric, **(self.metric_params if self.metric_params is not None else {}), ) # Double centering B = self.dissimilarity_matrix_**2 B = B.astype(np.float64) B -= np.mean(B, axis=0) B -= np.mean(B, axis=1, keepdims=True) B *= -0.5 # Eigendecomposition w, U = linalg.eigh(B) # Reversing the order of the eigenvalues/eigenvectors to put # the eigenvalues in decreasing order w = w[::-1][: self.n_components] U = U[:, ::-1][:, : self.n_components] # Set the signs of eigenvectors to enforce deterministic output U, _ = svd_flip(U, None) self.embedding_ = np.sqrt(w) * U self.eigenvalues_ = w return self.embedding_
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/manifold/_classical_mds.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 157, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
scikit-learn/scikit-learn:sklearn/manifold/tests/test_classical_mds.py
import numpy as np import pytest from numpy.testing import assert_allclose from sklearn.datasets import load_iris from sklearn.decomposition import PCA from sklearn.manifold import ClassicalMDS from sklearn.metrics import euclidean_distances def test_classical_mds_equivalent_to_pca(): X, _ = load_iris(return_X_y=True) cmds = ClassicalMDS(n_components=2, metric="euclidean") pca = PCA(n_components=2) Z1 = cmds.fit_transform(X) Z2 = pca.fit_transform(X) # Swap the signs if necessary for comp in range(2): if Z1[0, comp] < 0 and Z2[0, comp] > 0: Z2[:, comp] *= -1 assert_allclose(Z1, Z2) assert_allclose(np.sqrt(cmds.eigenvalues_), pca.singular_values_) def test_classical_mds_equivalent_on_data_and_distances(): X, _ = load_iris(return_X_y=True) cmds = ClassicalMDS(n_components=2, metric="euclidean") Z1 = cmds.fit_transform(X) cmds = ClassicalMDS(n_components=2, metric="precomputed") Z2 = cmds.fit_transform(euclidean_distances(X)) assert_allclose(Z1, Z2) def test_classical_mds_wrong_inputs(): # Non-symmetric input dissim = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) with pytest.raises(ValueError, match="Array must be symmetric"): ClassicalMDS(metric="precomputed").fit(dissim) # Non-square input dissim = np.array([[0, 1, 2], [3, 4, 5]]) with pytest.raises(ValueError, match="array must be 2-dimensional and square"): ClassicalMDS(metric="precomputed").fit(dissim) def test_classical_mds_metric_params(): X, _ = load_iris(return_X_y=True) cmds = ClassicalMDS(n_components=2, metric="euclidean") Z1 = cmds.fit_transform(X) cmds = ClassicalMDS(n_components=2, metric="minkowski", metric_params={"p": 2}) Z2 = cmds.fit_transform(X) assert_allclose(Z1, Z2) cmds = ClassicalMDS(n_components=2, metric="minkowski", metric_params={"p": 1}) Z3 = cmds.fit_transform(X) assert not np.allclose(Z1, Z3)
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/manifold/tests/test_classical_mds.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scikit-learn/scikit-learn:sklearn/externals/_numpydoc/docscrape.py
"""Extract reference documentation from the NumPy source tree.""" import copy import inspect import pydoc import re import sys import textwrap from collections import namedtuple from collections.abc import Callable, Mapping from functools import cached_property from warnings import warn def strip_blank_lines(l): "Remove leading and trailing blank lines from a list of lines" while l and not l[0].strip(): del l[0] while l and not l[-1].strip(): del l[-1] return l class Reader: """A line-based string reader.""" def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\\n'. """ if isinstance(data, list): self._str = data else: self._str = data.split("\n") # store string as list of lines self.reset() def __getitem__(self, n): return self._str[n] def reset(self): self._l = 0 # current line nr def read(self): if not self.eof(): out = self[self._l] self._l += 1 return out else: return "" def seek_next_non_empty_line(self): for l in self[self._l :]: if l.strip(): break else: self._l += 1 def eof(self): return self._l >= len(self._str) def read_to_condition(self, condition_func): start = self._l for line in self[start:]: if condition_func(line): return self[start : self._l] self._l += 1 if self.eof(): return self[start : self._l + 1] return [] def read_to_next_empty_line(self): self.seek_next_non_empty_line() def is_empty(line): return not line.strip() return self.read_to_condition(is_empty) def read_to_next_unindented_line(self): def is_unindented(line): return line.strip() and (len(line.lstrip()) == len(line)) return self.read_to_condition(is_unindented) def peek(self, n=0): if self._l + n < len(self._str): return self[self._l + n] else: return "" def is_empty(self): return not "".join(self._str).strip() class ParseError(Exception): def __str__(self): message = self.args[0] if hasattr(self, "docstring"): message = f"{message} in {self.docstring!r}" return message Parameter = namedtuple("Parameter", ["name", "type", "desc"]) class NumpyDocString(Mapping): """Parses a numpydoc string to an abstract representation Instances define a mapping from section title to structured data. """ sections = { "Signature": "", "Summary": [""], "Extended Summary": [], "Parameters": [], "Attributes": [], "Methods": [], "Returns": [], "Yields": [], "Receives": [], "Other Parameters": [], "Raises": [], "Warns": [], "Warnings": [], "See Also": [], "Notes": [], "References": "", "Examples": "", "index": {}, } def __init__(self, docstring, config=None): orig_docstring = docstring docstring = textwrap.dedent(docstring).split("\n") self._doc = Reader(docstring) self._parsed_data = copy.deepcopy(self.sections) try: self._parse() except ParseError as e: e.docstring = orig_docstring raise def __getitem__(self, key): return self._parsed_data[key] def __setitem__(self, key, val): if key not in self._parsed_data: self._error_location(f"Unknown section {key}", error=False) else: self._parsed_data[key] = val def __iter__(self): return iter(self._parsed_data) def __len__(self): return len(self._parsed_data) def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith(".. index::"): return True l2 = self._doc.peek(1).strip() # ---------- or ========== if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1): snip = "\n".join(self._doc._str[:2]) + "..." self._error_location( f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}", error=False, ) return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1)) def _strip(self, doc): i = 0 j = 0 for i, line in enumerate(doc): if line.strip(): break for j, line in enumerate(doc[::-1]): if line.strip(): break return doc[i : len(doc) - j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [""] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith(".."): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self, content, single_element_is_type=False): content = dedent_lines(content) r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if " : " in header: arg_name, arg_type = header.split(" : ", maxsplit=1) else: # NOTE: param line with single element should never have a # a " :" before the description line, so this should probably # warn. header = header.removesuffix(" :") if single_element_is_type: arg_name, arg_type = "", header else: arg_name, arg_type = header, "" desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) desc = strip_blank_lines(desc) params.append(Parameter(arg_name, arg_type, desc)) return params # See also supports the following formats. # # <FUNCNAME> # <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE* # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)+ (COMMA | PERIOD)? SPACE* # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE* # <FUNCNAME> is one of # <PLAIN_FUNCNAME> # COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK # where # <PLAIN_FUNCNAME> is a legal function name, and # <ROLE> is any nonempty sequence of word characters. # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` # <DESC> is a string describing the function. _role = r":(?P<role>(py:)?\w+):" _funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`" _funcplain = r"(?P<name2>[a-zA-Z0-9_\.-]+)" _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" _funcnamenext = _funcname.replace("role", "rolenext") _funcnamenext = _funcnamenext.replace("name", "namenext") _description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$" _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") _line_rgx = re.compile( r"^\s*" + r"(?P<allfuncs>" + _funcname # group for all function names + r"(?P<morefuncs>([,]\s+" + _funcnamenext + r")*)" + r")" + r"(?P<trailing>[,\.])?" # end of "allfuncs" + _description # Some function lists have a trailing comma (or period) '\s*' ) # Empty <DESC> elements are replaced with '..' empty_description = ".." def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ content = dedent_lines(content) items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'.""" m = self._func_rgx.match(text) if not m: self._error_location(f"Error parsing See Also entry {line!r}") role = m.group("role") name = m.group("name") if role else m.group("name2") return name, role, m.end() rest = [] for line in content: if not line.strip(): continue line_match = self._line_rgx.match(line) description = None if line_match: description = line_match.group("desc") if line_match.group("trailing") and description: self._error_location( "Unexpected comma or period after function list at index %d of " 'line "%s"' % (line_match.end("trailing"), line), error=False, ) if not description and line.startswith(" "): rest.append(line.strip()) elif line_match: funcs = [] text = line_match.group("allfuncs") while True: if not text.strip(): break name, role, match_end = parse_item_name(text) funcs.append((name, role)) text = text[match_end:].strip() if text and text[0] == ",": text = text[1:].strip() rest = list(filter(None, [description])) items.append((funcs, rest)) else: self._error_location(f"Error parsing See Also entry {line!r}") return items def _parse_index(self, section, content): """ .. index:: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split("::") if len(section) > 1: out["default"] = strip_each_in(section[1].split(","))[0] for line in content: line = line.split(":") if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(",")) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$") if compiled.match(summary_str): self["Signature"] = summary_str if not self._is_at_section(): continue break if summary is not None: self["Summary"] = summary if not self._is_at_section(): self["Extended Summary"] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() sections = list(self._read_sections()) section_names = {section for section, content in sections} has_yields = "Yields" in section_names # We could do more tests, but we are not. Arbitrarily. if not has_yields and "Receives" in section_names: msg = "Docstring contains a Receives section but not Yields." raise ValueError(msg) for section, content in sections: if not section.startswith(".."): section = (s.capitalize() for s in section.split(" ")) section = " ".join(section) if self.get(section): self._error_location( "The section %s appears twice in %s" % (section, "\n".join(self._doc._str)) ) if section in ("Parameters", "Other Parameters", "Attributes", "Methods"): self[section] = self._parse_param_list(content) elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"): self[section] = self._parse_param_list( content, single_element_is_type=True ) elif section.startswith(".. index::"): self["index"] = self._parse_index(section, content) elif section == "See Also": self["See Also"] = self._parse_see_also(content) else: self[section] = content @property def _obj(self): if hasattr(self, "_cls"): return self._cls elif hasattr(self, "_f"): return self._f return None def _error_location(self, msg, error=True): if self._obj is not None: # we know where the docs came from: try: filename = inspect.getsourcefile(self._obj) except TypeError: filename = None # Make UserWarning more descriptive via object introspection. # Skip if introspection fails name = getattr(self._obj, "__name__", None) if name is None: name = getattr(getattr(self._obj, "__class__", None), "__name__", None) if name is not None: msg += f" in the docstring of {name}" msg += f" in {filename}." if filename else "" if error: raise ValueError(msg) else: warn(msg, stacklevel=3) # string conversion routines def _str_header(self, name, symbol="-"): return [name, len(name) * symbol] def _str_indent(self, doc, indent=4): return [" " * indent + line for line in doc] def _str_signature(self): if self["Signature"]: return [self["Signature"].replace("*", r"\*")] + [""] return [""] def _str_summary(self): if self["Summary"]: return self["Summary"] + [""] return [] def _str_extended_summary(self): if self["Extended Summary"]: return self["Extended Summary"] + [""] return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param in self[name]: parts = [] if param.name: parts.append(param.name) if param.type: parts.append(param.type) out += [" : ".join(parts)] if param.desc and "".join(param.desc).strip(): out += self._str_indent(param.desc) out += [""] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [""] return out def _str_see_also(self, func_role): if not self["See Also"]: return [] out = [] out += self._str_header("See Also") out += [""] last_had_desc = True for funcs, desc in self["See Also"]: assert isinstance(funcs, list) links = [] for func, role in funcs: if role: link = f":{role}:`{func}`" elif func_role: link = f":{func_role}:`{func}`" else: link = f"`{func}`_" links.append(link) link = ", ".join(links) out += [link] if desc: out += self._str_indent([" ".join(desc)]) last_had_desc = True else: last_had_desc = False out += self._str_indent([self.empty_description]) if last_had_desc: out += [""] out += [""] return out def _str_index(self): idx = self["index"] out = [] output_index = False default_index = idx.get("default", "") if default_index: output_index = True out += [f".. index:: {default_index}"] for section, references in idx.items(): if section == "default": continue output_index = True out += [f" :{section}: {', '.join(references)}"] if output_index: return out return "" def __str__(self, func_role=""): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() out += self._str_param_list("Parameters") for param_list in ("Attributes", "Methods"): out += self._str_param_list(param_list) for param_list in ( "Returns", "Yields", "Receives", "Other Parameters", "Raises", "Warns", ): out += self._str_param_list(param_list) out += self._str_section("Warnings") out += self._str_see_also(func_role) for s in ("Notes", "References", "Examples"): out += self._str_section(s) out += self._str_index() return "\n".join(out) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n") class FunctionDoc(NumpyDocString): def __init__(self, func, role="func", doc=None, config=None): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or "" if config is None: config = {} NumpyDocString.__init__(self, doc, config) def get_func(self): func_name = getattr(self._f, "__name__", self.__class__.__name__) if inspect.isclass(self._f): func = getattr(self._f, "__call__", self._f.__init__) else: func = self._f return func, func_name def __str__(self): out = "" func, func_name = self.get_func() roles = {"func": "function", "meth": "method"} if self._role: if self._role not in roles: print(f"Warning: invalid role {self._role}") out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n" out += super().__str__(func_role=self._role) return out class ObjDoc(NumpyDocString): def __init__(self, obj, doc=None, config=None): self._f = obj if config is None: config = {} NumpyDocString.__init__(self, doc, config=config) class ClassDoc(NumpyDocString): extra_public_methods = ["__call__"] def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None): if not inspect.isclass(cls) and cls is not None: raise ValueError(f"Expected a class or None, but got {cls!r}") self._cls = cls if "sphinx" in sys.modules: from sphinx.ext.autodoc import ALL else: ALL = object() if config is None: config = {} self.show_inherited_members = config.get("show_inherited_class_members", True) if modulename and not modulename.endswith("."): modulename += "." self._mod = modulename if doc is None: if cls is None: raise ValueError("No class or documentation string given") doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) _members = config.get("members", []) if _members is ALL: _members = None _exclude = config.get("exclude-members", []) if config.get("show_class_members", True) and _exclude is not ALL: def splitlines_x(s): if not s: return [] else: return s.splitlines() for field, items in [ ("Methods", self.methods), ("Attributes", self.properties), ]: if not self[field]: doc_list = [] for name in sorted(items): if name in _exclude or (_members and name not in _members): continue try: doc_item = pydoc.getdoc(getattr(self._cls, name)) doc_list.append(Parameter(name, "", splitlines_x(doc_item))) except AttributeError: pass # method doesn't exist self[field] = doc_list @property def methods(self): if self._cls is None: return [] return [ name for name, func in inspect.getmembers(self._cls) if ( (not name.startswith("_") or name in self.extra_public_methods) and isinstance(func, Callable) and self._is_show_member(name) ) ] @property def properties(self): if self._cls is None: return [] return [ name for name, func in inspect.getmembers(self._cls) if ( not name.startswith("_") and not self._should_skip_member(name, self._cls) and ( func is None or isinstance(func, (property, cached_property)) or inspect.isdatadescriptor(func) ) and self._is_show_member(name) ) ] @staticmethod def _should_skip_member(name, klass): return ( # Namedtuples should skip everything in their ._fields as the # docstrings for each of the members is: "Alias for field number X" issubclass(klass, tuple) and hasattr(klass, "_asdict") and hasattr(klass, "_fields") and name in klass._fields ) def _is_show_member(self, name): return ( # show all class members self.show_inherited_members # or class member is not inherited or name in self._cls.__dict__ ) def get_doc_object( obj, what=None, doc=None, config=None, class_doc=ClassDoc, func_doc=FunctionDoc, obj_doc=ObjDoc, ): if what is None: if inspect.isclass(obj): what = "class" elif inspect.ismodule(obj): what = "module" elif isinstance(obj, Callable): what = "function" else: what = "object" if config is None: config = {} if what == "class": return class_doc(obj, func_doc=func_doc, doc=doc, config=config) elif what in ("function", "method"): return func_doc(obj, doc=doc, config=config) else: if doc is None: doc = pydoc.getdoc(obj) return obj_doc(obj, doc, config=config)
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/externals/_numpydoc/docscrape.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 634, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
scikit-learn/scikit-learn:examples/release_highlights/plot_release_highlights_1_7_0.py
# ruff: noqa: CPY001 """ ======================================= Release Highlights for scikit-learn 1.7 ======================================= .. currentmodule:: sklearn We are pleased to announce the release of scikit-learn 1.7! Many bug fixes and improvements were added, as well as some key new features. Below we detail the highlights of this release. **For an exhaustive list of all the changes**, please refer to the :ref:`release notes <release_notes_1_7>`. To install the latest version (with pip):: pip install --upgrade scikit-learn or with conda:: conda install -c conda-forge scikit-learn """ # %% # Improved estimator's HTML representation # ---------------------------------------- # The HTML representation of estimators now includes a section containing the list of # parameters and their values. Non-default parameters are highlighted in orange. A copy # button is also available to copy the "fully-qualified" parameter name without the # need to call the `get_params` method. It is particularly useful when defining a # parameter grid for a grid-search or a randomized-search with a complex pipeline. # # See the example below and click on the different estimator's blocks to see the # improved HTML representation. from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler model = make_pipeline(StandardScaler(with_std=False), LogisticRegression(C=2.0)) model # %% # Custom validation set for histogram-based Gradient Boosting estimators # ---------------------------------------------------------------------- # The :class:`ensemble.HistGradientBoostingClassifier` and # :class:`ensemble.HistGradientBoostingRegressor` now support directly passing a custom # validation set for early stopping to the `fit` method, using the `X_val`, `y_val`, and # `sample_weight_val` parameters. # In a :class:`pipeline.Pipeline`, the validation set `X_val` can be transformed along # with `X` using the `transform_input` parameter. import sklearn from sklearn.datasets import make_classification from sklearn.ensemble import HistGradientBoostingClassifier from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler sklearn.set_config(enable_metadata_routing=True) X, y = make_classification(random_state=0) X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=0) clf = HistGradientBoostingClassifier() clf.set_fit_request(X_val=True, y_val=True) model = Pipeline([("sc", StandardScaler()), ("clf", clf)], transform_input=["X_val"]) model.fit(X, y, X_val=X_val, y_val=y_val) # %% # Plotting ROC curves from cross-validation results # ------------------------------------------------- # The class :class:`metrics.RocCurveDisplay` has a new class method `from_cv_results` # that allows to easily plot multiple ROC curves from the results of # :func:`model_selection.cross_validate`. from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression from sklearn.metrics import RocCurveDisplay from sklearn.model_selection import cross_validate X, y = make_classification(n_samples=150, random_state=0) clf = LogisticRegression(random_state=0) cv_results = cross_validate(clf, X, y, cv=5, return_estimator=True, return_indices=True) _ = RocCurveDisplay.from_cv_results(cv_results, X, y) # %% # Array API support # ----------------- # Several functions have been updated to support array API compatible inputs since # version 1.6, especially metrics from the :mod:`sklearn.metrics` module. # # In addition, it is no longer required to install the `array-api-compat` package to use # the experimental array API support in scikit-learn. # # Please refer to the :ref:`array API support<array_api>` page for instructions to use # scikit-learn with array API compatible libraries such as PyTorch or CuPy. # %% # Improved API consistency of Multi-layer Perceptron # -------------------------------------------------- # The :class:`neural_network.MLPRegressor` has a new parameter `loss` and now supports # the "poisson" loss in addition to the default "squared_error" loss. # Moreover, the :class:`neural_network.MLPClassifier` and # :class:`neural_network.MLPRegressor` estimators now support sample weights. # These improvements have been made to improve the consistency of these estimators # with regard to the other estimators in scikit-learn. # %% # Migration toward sparse arrays # ------------------------------ # In order to prepare `SciPy migration from sparse matrices to sparse arrays <https://docs.scipy.org/doc/scipy/reference/sparse.migration_to_sparray.html>`_, # all scikit-learn estimators that accept sparse matrices as input now also accept # sparse arrays.
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "examples/release_highlights/plot_release_highlights_1_7_0.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 93, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
scikit-learn/scikit-learn:sklearn/utils/_repr_html/base.py
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import itertools from sklearn import __version__ from sklearn._config import get_config from sklearn.utils.fixes import parse_version class _HTMLDocumentationLinkMixin: """Mixin class allowing to generate a link to the API documentation. This mixin relies on three attributes: - `_doc_link_module`: it corresponds to the root module (e.g. `sklearn`). Using this mixin, the default value is `sklearn`. - `_doc_link_template`: it corresponds to the template used to generate the link to the API documentation. Using this mixin, the default value is `"https://scikit-learn.org/{version_url}/modules/generated/ {estimator_module}.{estimator_name}.html"`. - `_doc_link_url_param_generator`: it corresponds to a function that generates the parameters to be used in the template when the estimator module and name are not sufficient. The method :meth:`_get_doc_link` generates the link to the API documentation for a given estimator. This mixin provides all the necessary states for :func:`sklearn.utils.estimator_html_repr` to generate a link to the API documentation for the estimator HTML diagram. Examples -------- If the default values for `_doc_link_module`, `_doc_link_template` are not suitable, then you can override them and provide a method to generate the URL parameters: >>> from sklearn.base import BaseEstimator >>> doc_link_template = "https://address.local/{single_param}.html" >>> def url_param_generator(estimator): ... return {"single_param": estimator.__class__.__name__} >>> class MyEstimator(BaseEstimator): ... # use "builtins" since it is the associated module when declaring ... # the class in a docstring ... _doc_link_module = "builtins" ... _doc_link_template = doc_link_template ... _doc_link_url_param_generator = url_param_generator >>> estimator = MyEstimator() >>> estimator._get_doc_link() 'https://address.local/MyEstimator.html' If instead of overriding the attributes inside the class definition, you want to override a class instance, you can use `types.MethodType` to bind the method to the instance: >>> import types >>> estimator = BaseEstimator() >>> estimator._doc_link_template = doc_link_template >>> estimator._doc_link_url_param_generator = types.MethodType( ... url_param_generator, estimator) >>> estimator._get_doc_link() 'https://address.local/BaseEstimator.html' """ _doc_link_module = "sklearn" _doc_link_url_param_generator = None @property def _doc_link_template(self): sklearn_version = parse_version(__version__) if sklearn_version.dev is None: version_url = f"{sklearn_version.major}.{sklearn_version.minor}" else: version_url = "dev" return getattr( self, "__doc_link_template", ( f"https://scikit-learn.org/{version_url}/modules/generated/" "{estimator_module}.{estimator_name}.html" ), ) @_doc_link_template.setter def _doc_link_template(self, value): setattr(self, "__doc_link_template", value) def _get_doc_link(self): """Generates a link to the API documentation for a given estimator. This method generates the link to the estimator's documentation page by using the template defined by the attribute `_doc_link_template`. Returns ------- url : str The URL to the API documentation for this estimator. If the estimator does not belong to module `_doc_link_module`, the empty string (i.e. `""`) is returned. """ if self.__class__.__module__.split(".")[0] != self._doc_link_module: return "" if self._doc_link_url_param_generator is None: estimator_name = self.__class__.__name__ # Construct the estimator's module name, up to the first private submodule. # This works because in scikit-learn all public estimators are exposed at # that level, even if they actually live in a private sub-module. estimator_module = ".".join( itertools.takewhile( lambda part: not part.startswith("_"), self.__class__.__module__.split("."), ) ) return self._doc_link_template.format( estimator_module=estimator_module, estimator_name=estimator_name ) return self._doc_link_template.format(**self._doc_link_url_param_generator()) class ReprHTMLMixin: """Mixin to handle consistently the HTML representation. When inheriting from this class, you need to define an attribute `_html_repr` which is a callable that returns the HTML representation to be shown. """ @property def _repr_html_(self): """HTML representation of estimator. This is redundant with the logic of `_repr_mimebundle_`. The latter should be favored in the long term, `_repr_html_` is only implemented for consumers who do not interpret `_repr_mimbundle_`. """ if get_config()["display"] != "diagram": raise AttributeError( "_repr_html_ is only defined when the " "'display' configuration option is set to " "'diagram'" ) return self._repr_html_inner def _repr_html_inner(self): """This function is returned by the @property `_repr_html_` to make `hasattr(estimator, "_repr_html_") return `True` or `False` depending on `get_config()["display"]`. """ return self._html_repr() def _repr_mimebundle_(self, **kwargs): """Mime bundle used by jupyter kernels to display estimator""" output = {"text/plain": repr(self)} if get_config()["display"] == "diagram": output["text/html"] = self._html_repr() return output
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/utils/_repr_html/base.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 130, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
scikit-learn/scikit-learn:sklearn/utils/_repr_html/params.py
# Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import html import reprlib from collections import UserDict from sklearn.utils._repr_html.base import ReprHTMLMixin from sklearn.utils._repr_html.common import ( generate_link_to_param_doc, get_docstring, ) def _read_params(name, value, non_default_params): """Categorizes parameters as 'default' or 'user-set' and formats their values. Escapes or truncates parameter values for display safety and readability. """ name = html.escape(name) r = reprlib.Repr() r.maxlist = 2 # Show only first 2 items of lists r.maxtuple = 1 # Show only first item of tuples r.maxstring = 50 # Limit string length cleaned_value = html.escape(r.repr(value)) param_type = "user-set" if name in non_default_params else "default" return {"param_type": param_type, "param_name": name, "param_value": cleaned_value} def _params_html_repr(params): """Generate HTML representation of estimator parameters. Creates an HTML table with parameter names and values, wrapped in a collapsible details element. Parameters are styled differently based on whether they are default or user-set values. """ PARAMS_TABLE_TEMPLATE = """ <div class="estimator-table"> <details> <summary>Parameters</summary> <table class="parameters-table"> <tbody> {rows} </tbody> </table> </details> </div> """ PARAM_ROW_TEMPLATE = """ <tr class="{param_type}"> <td><i class="copy-paste-icon" onclick="copyToClipboard('{param_name}', this.parentElement.nextElementSibling)" ></i></td> <td class="param">{param_display}</td> <td class="value">{param_value}</td> </tr> """ PARAM_AVAILABLE_DOC_LINK_TEMPLATE = """ <a class="param-doc-link" style="anchor-name: --doc-link-{param_name};" rel="noreferrer" target="_blank" href="{link}"> {param_name} <span class="param-doc-description" style="position-anchor: --doc-link-{param_name};"> {param_description}</span> </a> """ rows = [] for row in params: param = _read_params(row, params[row], params.non_default) link = generate_link_to_param_doc(params.estimator_class, row, params.doc_link) param_description = get_docstring(params.estimator_class, "Parameters", row) if params.doc_link and link and param_description: # Create clickable parameter name with documentation link param_display = PARAM_AVAILABLE_DOC_LINK_TEMPLATE.format( link=link, param_name=param["param_name"], param_description=param_description, ) else: # Just show the parameter name without link param_display = param["param_name"] rows.append(PARAM_ROW_TEMPLATE.format(**param, param_display=param_display)) return PARAMS_TABLE_TEMPLATE.format(rows="\n".join(rows)) class ParamsDict(ReprHTMLMixin, UserDict): """Dictionary-like class to store and provide an HTML representation. It builds an HTML structure to be used with Jupyter notebooks or similar environments. It allows storing metadata to track non-default parameters. Parameters ---------- params : dict, default=None The original dictionary of parameters and their values. non_default : tuple, default=(,) The list of non-default parameters. estimator_class : type, default=None The class of the estimator. It allows to find the online documentation link for each parameter. doc_link : str, default="" The base URL to the online documentation for the estimator class. Used to generate parameter-specific documentation links in the HTML representation. If empty, documentation links will not be generated. """ _html_repr = _params_html_repr def __init__( self, *, params=None, non_default=tuple(), estimator_class=None, doc_link="" ): super().__init__(params or {}) self.non_default = non_default self.estimator_class = estimator_class self.doc_link = doc_link
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/utils/_repr_html/params.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 103, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
scikit-learn/scikit-learn:sklearn/utils/_repr_html/tests/test_params.py
import re import pytest from sklearn import config_context from sklearn.utils._repr_html.common import generate_link_to_param_doc from sklearn.utils._repr_html.params import ParamsDict, _params_html_repr, _read_params def test_params_dict_content(): """Check the behavior of the ParamsDict class.""" params = ParamsDict(params={"a": 1, "b": 2}) assert params["a"] == 1 assert params["b"] == 2 assert params.non_default == () params = ParamsDict(params={"a": 1, "b": 2}, non_default=("a",)) assert params["a"] == 1 assert params["b"] == 2 assert params.non_default == ("a",) def test_params_dict_repr_html_(): params = ParamsDict(params={"a": 1, "b": 2}, non_default=("a",), estimator_class="") out = params._repr_html_() assert "<summary>Parameters</summary>" in out with config_context(display="text"): msg = "_repr_html_ is only defined when" with pytest.raises(AttributeError, match=msg): params._repr_html_() def test_params_dict_repr_mimebundle(): params = ParamsDict(params={"a": 1, "b": 2}, non_default=("a",), estimator_class="") out = params._repr_mimebundle_() assert "text/plain" in out assert "text/html" in out assert "<summary>Parameters</summary>" in out["text/html"] assert out["text/plain"] == "{'a': 1, 'b': 2}" with config_context(display="text"): out = params._repr_mimebundle_() assert "text/plain" in out assert "text/html" not in out def test_read_params(): """Check the behavior of the `_read_params` function.""" out = _read_params("a", 1, tuple()) assert out["param_type"] == "default" assert out["param_name"] == "a" assert out["param_value"] == "1" # check non-default parameters out = _read_params("a", 1, ("a",)) assert out["param_type"] == "user-set" assert out["param_name"] == "a" assert out["param_value"] == "1" # check that we escape html tags tag_injection = "<script>alert('xss')</script>" out = _read_params("a", tag_injection, tuple()) assert ( out["param_value"] == "&quot;&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&quot;" ) assert out["param_name"] == "a" assert out["param_type"] == "default" def test_params_html_repr(): """Check returned HTML template""" params = ParamsDict(params={"a": 1, "b": 2}, estimator_class="") assert "parameters-table" in _params_html_repr(params) assert "estimator-table" in _params_html_repr(params) def test_params_html_repr_with_doc_links(): """Test `_params_html_repr` with valid and invalid doc links.""" class MockEstimator: """A fake estimator class with a docstring used for testing. Parameters ---------- a : int Description of a which can include `<formatted text https://example.com>`_ that should not be confused with HTML tags. b : str """ __module__ = "sklearn.mock_module" __qualname__ = "MockEstimator" params = ParamsDict( params={"a": 1, "b": "value"}, non_default=("a",), estimator_class=MockEstimator, doc_link="mock_module.MockEstimator.html", ) html_output = _params_html_repr(params) html_param_a = ( r'<td class="param">' r'\s*<a class="param-doc-link"' r'\s*style="anchor-name: --doc-link-a;"' r'\s*rel="noreferrer" target="_blank"' r'\shref="mock_module\.MockEstimator\.html#:~:text=a,-int">' r"\s*a" r'\s*<span class="param-doc-description"' r'\s*style="position-anchor: --doc-link-a;">\s*a:' r"\sint<br><br>" r"Description of a which can include `&lt;formatted text<br>" r"https://example.com&gt;`_ that should not be confused with HTML tags.</span>" r"\s*</a>" r"\s*</td>" ) assert re.search(html_param_a, html_output, flags=re.DOTALL) html_param_b = ( r'<td class="param">' r'.*<a class="param-doc-link"' r'\s*style="anchor-name: --doc-link-b;"' r'\s*rel="noreferrer" target="_blank"' r'\shref="mock_module\.MockEstimator\.html#:~:text=b,-str">' r"\s*b" r'\s*<span class="param-doc-description"' r'\s*style="position-anchor: --doc-link-b;">\s*b:' r"\sstr<br><br></span>" r"\s*</a>" r"\s*</td>" ) assert re.search(html_param_b, html_output, flags=re.DOTALL) def test_params_html_repr_without_doc_links(): """Test `_params_html_repr` when `link_to_param_doc` returns None.""" class MockEstimatorWithoutDoc: __module__ = "sklearn.mock_module" __qualname__ = "MockEstimatorWithoutDoc" # No docstring defined on this test class. params = ParamsDict( params={"a": 1, "b": "value"}, non_default=("a",), estimator_class=MockEstimatorWithoutDoc, ) html_output = _params_html_repr(params) # Check that no doc links are generated assert "?" not in html_output assert "Click to access" not in html_output html_param_a = ( r'<td class="param">a</td>' r'\s*<td class="value">1</td>' ) assert re.search(html_param_a, html_output, flags=re.DOTALL) html_param_b = ( r'<td class="param">b</td>' r'\s*<td class="value">&#x27;value&#x27;</td>' ) assert re.search(html_param_b, html_output, flags=re.DOTALL) def test_generate_link_to_param_doc_basic(): """Return anchor URLs for documented parameters in the estimator.""" class MockEstimator: """Mock class. Parameters ---------- alpha : float Regularization strength. beta : int Some integer parameter. """ doc_link = "mock_module.MockEstimator.html" url = generate_link_to_param_doc(MockEstimator, "alpha", doc_link) assert url == "mock_module.MockEstimator.html#:~:text=alpha,-float" url = generate_link_to_param_doc(MockEstimator, "beta", doc_link) assert url == "mock_module.MockEstimator.html#:~:text=beta,-int" def test_generate_link_to_param_doc_param_not_found(): """Ensure None is returned when the parameter is not documented.""" class MockEstimator: """Mock class Parameters ---------- alpha : float Regularization strength. """ doc_link = "mock_module.MockEstimator.html" url = generate_link_to_param_doc(MockEstimator, "gamma", doc_link) assert url is None def test_generate_link_to_param_doc_empty_docstring(): """Ensure None is returned when the estimator has no docstring.""" class MockEstimator: pass doc_link = "mock_module.MockEstimator.html" url = generate_link_to_param_doc(MockEstimator, "alpha", doc_link) assert url is None
{ "repo_id": "scikit-learn/scikit-learn", "file_path": "sklearn/utils/_repr_html/tests/test_params.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 169, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_downloader_handler_httpx.py
"""Tests for scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler.""" from __future__ import annotations from typing import TYPE_CHECKING, Any import pytest from scrapy import Request from tests.test_downloader_handlers_http_base import ( TestHttp11Base, TestHttpProxyBase, TestHttps11Base, TestHttpsCustomCiphersBase, TestHttpsInvalidDNSIdBase, TestHttpsInvalidDNSPatternBase, TestHttpsWrongHostnameBase, TestHttpWithCrawlerBase, TestSimpleHttpsBase, ) from tests.utils.decorators import coroutine_test if TYPE_CHECKING: from scrapy.core.downloader.handlers import DownloadHandlerProtocol from tests.mockserver.http import MockServer pytest.importorskip("httpx") class HttpxDownloadHandlerMixin: @property def download_handler_cls(self) -> type[DownloadHandlerProtocol]: # the import will fail if httpx is not installed from scrapy.core.downloader.handlers._httpx import ( # noqa: PLC0415 HttpxDownloadHandler, ) return HttpxDownloadHandler class TestHttp11(HttpxDownloadHandlerMixin, TestHttp11Base): @coroutine_test async def test_unsupported_bindaddress( self, caplog: pytest.LogCaptureFixture, mockserver: MockServer ) -> None: meta = {"bindaddress": "127.0.0.2"} request = Request(mockserver.url("/text"), meta=meta) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == b"Works" assert ( "The 'bindaddress' request meta key is not supported by HttpxDownloadHandler" in caplog.text ) @coroutine_test async def test_unsupported_proxy( self, caplog: pytest.LogCaptureFixture, mockserver: MockServer ) -> None: meta = {"proxy": "127.0.0.2"} request = Request(mockserver.url("/text"), meta=meta) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == b"Works" assert ( "The 'proxy' request meta key is not supported by HttpxDownloadHandler" in caplog.text ) class TestHttps11(HttpxDownloadHandlerMixin, TestHttps11Base): tls_log_message = "SSL connection to 127.0.0.1 using protocol TLSv1.3, cipher" class TestSimpleHttps(HttpxDownloadHandlerMixin, TestSimpleHttpsBase): pass class Https11WrongHostnameTestCase( HttpxDownloadHandlerMixin, TestHttpsWrongHostnameBase ): pass class Https11InvalidDNSId(HttpxDownloadHandlerMixin, TestHttpsInvalidDNSIdBase): pass class Https11InvalidDNSPattern( HttpxDownloadHandlerMixin, TestHttpsInvalidDNSPatternBase ): pass class Https11CustomCiphers(HttpxDownloadHandlerMixin, TestHttpsCustomCiphersBase): pass class TestHttp11WithCrawler(TestHttpWithCrawlerBase): @property def settings_dict(self) -> dict[str, Any] | None: return { "DOWNLOAD_HANDLERS": { "http": "scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler", "https": "scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler", } } class TestHttps11WithCrawler(TestHttp11WithCrawler): is_secure = True @pytest.mark.skip(reason="response.certificate is not implemented") @coroutine_test async def test_response_ssl_certificate(self, mockserver: MockServer) -> None: pass @pytest.mark.skip(reason="Proxy support is not implemented yet") class TestHttp11Proxy(HttpxDownloadHandlerMixin, TestHttpProxyBase): pass @pytest.mark.skip(reason="Proxy support is not implemented yet") class TestHttps11Proxy(HttpxDownloadHandlerMixin, TestHttpProxyBase): is_secure = True
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_downloader_handler_httpx.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 93, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/utils/decorators.py
from __future__ import annotations from functools import wraps from typing import TYPE_CHECKING, Any, ParamSpec import pytest from twisted.internet.defer import Deferred, inlineCallbacks from scrapy.utils.defer import deferred_from_coro, deferred_to_future from scrapy.utils.reactor import is_reactor_installed if TYPE_CHECKING: from collections.abc import Awaitable, Callable, Generator _P = ParamSpec("_P") def inline_callbacks_test( f: Callable[_P, Generator[Deferred[Any], Any, None]], ) -> Callable[_P, Awaitable[None]]: """Mark a test function written in a :func:`twisted.internet.defer.inlineCallbacks` style. This calls :func:`twisted.internet.defer.inlineCallbacks` and then: * with ``pytest-twisted`` this returns the resulting Deferred * with ``pytest-asyncio`` this converts the resulting Deferred into a coroutine """ if not is_reactor_installed(): @pytest.mark.asyncio @wraps(f) async def wrapper_coro(*args: _P.args, **kwargs: _P.kwargs) -> None: await deferred_to_future(inlineCallbacks(f)(*args, **kwargs)) return wrapper_coro @wraps(f) @inlineCallbacks def wrapper_dfd( *args: _P.args, **kwargs: _P.kwargs ) -> Generator[Deferred[Any], Any, None]: return f(*args, **kwargs) return wrapper_dfd def coroutine_test( coro_f: Callable[_P, Awaitable[None]], ) -> Callable[_P, Awaitable[None]]: """Mark a test function that returns a coroutine. * with ``pytest-twisted`` this converts a coroutine into a :class:`twisted.internet.defer.Deferred` * with ``pytest-asyncio`` this is a no-op """ if not is_reactor_installed(): return pytest.mark.asyncio(coro_f) @wraps(coro_f) def f(*coro_args: _P.args, **coro_kwargs: _P.kwargs) -> Deferred[None]: return deferred_from_coro(coro_f(*coro_args, **coro_kwargs)) return f
{ "repo_id": "scrapy/scrapy", "file_path": "tests/utils/decorators.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:scrapy/utils/reactorless.py
from __future__ import annotations import sys from importlib.abc import MetaPathFinder from typing import TYPE_CHECKING from scrapy.utils.asyncio import is_asyncio_available from scrapy.utils.reactor import is_reactor_installed if TYPE_CHECKING: from collections.abc import Sequence from importlib.machinery import ModuleSpec from types import ModuleType def is_reactorless() -> bool: """Check if we are running in the reactorless mode, i.e. with :setting:`TWISTED_ENABLED` set to ``False``. As this checks the runtime state and not the setting itself, it can be wrong when executed very early, before the reactor and/or the asyncio event loop are initialized. .. note:: As this function uses :func:`scrapy.utils.asyncio.is_asyncio_available()`, it has the same limitations for detecting a running asyncio event loop as that one. .. versionadded:: VERSION """ return is_asyncio_available() and not is_reactor_installed() class ReactorImportHook(MetaPathFinder): """Hook that prevents importing :mod:`twisted.internet.reactor`.""" def find_spec( self, fullname: str, path: Sequence[str] | None, target: ModuleType | None = None, ) -> ModuleSpec | None: if fullname == "twisted.internet.reactor": raise ImportError( f"Import of {fullname} is forbidden when running without a Twisted reactor," f" as importing it installs the reactor, which can lead to unexpected behavior." ) return None def install_reactor_import_hook() -> None: """Prevent importing :mod:`twisted.internet.reactor`.""" sys.meta_path.insert(0, ReactorImportHook())
{ "repo_id": "scrapy/scrapy", "file_path": "scrapy/utils/reactorless.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
scrapy/scrapy:tests/AsyncCrawlerProcess/reactorless_datauri.py
from scrapy import Request, Spider from scrapy.crawler import AsyncCrawlerProcess class DataSpider(Spider): name = "data" async def start(self): yield Request("data:,foo") def parse(self, response): return {"data": response.text} process = AsyncCrawlerProcess( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } ) process.crawl(DataSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/reactorless_datauri.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/reactorless_import_hook.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): import twisted.internet.reactor # noqa: F401 return yield process = AsyncCrawlerProcess( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/reactorless_import_hook.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/reactorless_reactor.py
from scrapy.crawler import AsyncCrawlerProcess from scrapy.utils.reactor import install_reactor install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") AsyncCrawlerProcess( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } )
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/reactorless_reactor.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/reactorless_simple.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess from scrapy.utils.reactorless import is_reactorless class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): self.logger.info(f"is_reactorless(): {is_reactorless()}") return yield process = AsyncCrawlerProcess( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/reactorless_simple.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/reactorless_telnetconsole_default.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/reactorless_telnetconsole_default.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/reactorless_telnetconsole_disabled.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, "TELNETCONSOLE_ENABLED": False, } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/reactorless_telnetconsole_disabled.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/reactorless_telnetconsole_enabled.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, "TELNETCONSOLE_ENABLED": True, } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/reactorless_telnetconsole_enabled.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/reactorless_datauri.py
import asyncio from scrapy import Request, Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.log import configure_logging class DataSpider(Spider): name = "data" async def start(self): yield Request("data:,foo") def parse(self, response): return {"data": response.text} async def main(): configure_logging() runner = AsyncCrawlerRunner( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } ) await runner.crawl(DataSpider) asyncio.run(main())
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/reactorless_datauri.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/reactorless_reactor.py
import asyncio from scrapy import Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" async def start(self): return yield async def main(): configure_logging() runner = AsyncCrawlerRunner( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } ) await runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") asyncio.run(main())
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/reactorless_reactor.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/reactorless_simple.py
import asyncio from scrapy import Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.reactorless import is_reactorless class NoRequestsSpider(Spider): name = "no_request" async def start(self): self.logger.info(f"is_reactorless(): {is_reactorless()}") return yield async def main(): configure_logging() runner = AsyncCrawlerRunner( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } ) await runner.crawl(NoRequestsSpider) asyncio.run(main())
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/reactorless_simple.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/CrawlerProcess/reactorless.py
from scrapy.crawler import CrawlerProcess CrawlerProcess( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } )
{ "repo_id": "scrapy/scrapy", "file_path": "tests/CrawlerProcess/reactorless.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/CrawlerRunner/reactorless.py
from scrapy.crawler import CrawlerRunner CrawlerRunner( settings={ "TWISTED_ENABLED": False, "DOWNLOAD_HANDLERS": { "http": None, "https": None, "ftp": None, }, } )
{ "repo_id": "scrapy/scrapy", "file_path": "tests/CrawlerRunner/reactorless.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:scrapy/utils/_download_handlers.py
"""Utils for built-in HTTP download handlers.""" from __future__ import annotations from abc import ABC from contextlib import contextmanager from typing import TYPE_CHECKING, Any from twisted.internet.defer import CancelledError from twisted.internet.error import ConnectionRefusedError as TxConnectionRefusedError from twisted.internet.error import DNSLookupError from twisted.internet.error import TimeoutError as TxTimeoutError from twisted.python.failure import Failure from twisted.web.client import ResponseFailed from twisted.web.error import SchemeNotSupported from scrapy import responsetypes from scrapy.core.downloader.handlers.base import BaseDownloadHandler from scrapy.exceptions import ( CannotResolveHostError, DownloadCancelledError, DownloadConnectionRefusedError, DownloadFailedError, DownloadTimeoutError, StopDownload, UnsupportedURLSchemeError, ) from scrapy.utils.log import logger if TYPE_CHECKING: from collections.abc import Iterator from ipaddress import IPv4Address, IPv6Address from twisted.internet.ssl import Certificate from scrapy import Request from scrapy.crawler import Crawler from scrapy.http import Headers, Response class BaseHttpDownloadHandler(BaseDownloadHandler, ABC): """Base class for built-in HTTP download handlers.""" def __init__(self, crawler: Crawler): super().__init__(crawler) self._default_maxsize: int = crawler.settings.getint("DOWNLOAD_MAXSIZE") self._default_warnsize: int = crawler.settings.getint("DOWNLOAD_WARNSIZE") self._fail_on_dataloss: bool = crawler.settings.getbool( "DOWNLOAD_FAIL_ON_DATALOSS" ) self._fail_on_dataloss_warned: bool = False @contextmanager def wrap_twisted_exceptions() -> Iterator[None]: """Context manager that wraps Twisted exceptions into Scrapy exceptions.""" try: yield except SchemeNotSupported as e: raise UnsupportedURLSchemeError(str(e)) from e except CancelledError as e: raise DownloadCancelledError(str(e)) from e except TxConnectionRefusedError as e: raise DownloadConnectionRefusedError(str(e)) from e except DNSLookupError as e: raise CannotResolveHostError(str(e)) from e except ResponseFailed as e: raise DownloadFailedError(str(e)) from e except TxTimeoutError as e: raise DownloadTimeoutError(str(e)) from e def check_stop_download( signal: object, crawler: Crawler, request: Request, **kwargs: Any ) -> StopDownload | None: """Send the given signal and check if any of its handlers raised :exc:`~scrapy.exceptions.StopDownload`. Return the raised exception or ``None``. """ signal_result = crawler.signals.send_catch_log( signal=signal, request=request, spider=crawler.spider, **kwargs, ) for handler, result in signal_result: if isinstance(result, Failure) and isinstance(result.value, StopDownload): logger.debug( f"Download stopped for {request} from signal handler {handler.__qualname__}" ) return result.value return None def make_response( url: str, status: int, headers: Headers, body: bytes = b"", flags: list[str] | None = None, certificate: Certificate | None = None, ip_address: IPv4Address | IPv6Address | None = None, protocol: str | None = None, stop_download: StopDownload | None = None, ) -> Response: respcls = responsetypes.responsetypes.from_args(headers=headers, url=url, body=body) response = respcls( url=url, status=status, headers=headers, body=body, flags=flags, certificate=certificate, ip_address=ip_address, protocol=protocol, ) if stop_download: response.flags.append("download_stopped") if stop_download.fail: stop_download.response = response raise stop_download return response def get_maxsize_msg(size: int, limit: int, request: Request, *, expected: bool) -> str: prefix = "Expected to receive" if expected else "Received" return ( f"{prefix} {size} bytes which is larger than download " f"max size ({limit}) in request {request}." ) def get_warnsize_msg(size: int, limit: int, request: Request, *, expected: bool) -> str: prefix = "Expected to receive" if expected else "Received" return ( f"{prefix} {size} bytes which is larger than download " f"warn size ({limit}) in request {request}." ) def get_dataloss_msg(url: str) -> str: return ( f"Got data loss in {url}. If you want to process broken " f"responses set the setting DOWNLOAD_FAIL_ON_DATALOSS = False" f" -- This message won't be shown in further requests" )
{ "repo_id": "scrapy/scrapy", "file_path": "scrapy/utils/_download_handlers.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
scrapy/scrapy:scrapy/core/downloader/handlers/base.py
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: # typing.Self requires Python 3.11 from typing_extensions import Self from scrapy import Request from scrapy.crawler import Crawler from scrapy.http import Response class BaseDownloadHandler(ABC): """Optional base class for download handlers.""" lazy: bool = False def __init__(self, crawler: Crawler): self.crawler = crawler @classmethod def from_crawler(cls, crawler: Crawler) -> Self: return cls(crawler) @abstractmethod async def download_request(self, request: Request) -> Response: raise NotImplementedError async def close(self) -> None: # noqa: B027 pass
{ "repo_id": "scrapy/scrapy", "file_path": "scrapy/core/downloader/handlers/base.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
scrapy/scrapy:scrapy/extensions/logcount.py
from __future__ import annotations import logging from typing import TYPE_CHECKING from scrapy import Spider, signals from scrapy.utils.log import LogCounterHandler if TYPE_CHECKING: # typing.Self requires Python 3.11 from typing_extensions import Self from scrapy.crawler import Crawler logger = logging.getLogger(__name__) class LogCount: """Install a log handler that counts log messages by level. The handler installed is :class:`scrapy.utils.log.LogCounterHandler`. The counts are stored in stats as ``log_count/<level>``. .. versionadded:: 2.14 """ def __init__(self, crawler: Crawler): self.crawler: Crawler = crawler self.handler: LogCounterHandler | None = None @classmethod def from_crawler(cls, crawler: Crawler) -> Self: o = cls(crawler) crawler.signals.connect(o.spider_opened, signal=signals.spider_opened) crawler.signals.connect(o.spider_closed, signal=signals.spider_closed) return o def spider_opened(self, spider: Spider) -> None: self.handler = LogCounterHandler( self.crawler, level=self.crawler.settings.get("LOG_LEVEL") ) logging.root.addHandler(self.handler) def spider_closed(self, spider: Spider, reason: str) -> None: if self.handler: logging.root.removeHandler(self.handler) self.handler = None
{ "repo_id": "scrapy/scrapy", "file_path": "scrapy/extensions/logcount.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
scrapy/scrapy:tests/test_zz_resources.py
"""Test that certain resources are not leaked during earlier tests.""" from __future__ import annotations import asyncio import logging import pytest from scrapy.utils.log import LogCounterHandler from scrapy.utils.reactor import is_asyncio_reactor_installed, is_reactor_installed def test_counter_handler() -> None: """Test that ``LogCounterHandler`` is always properly removed. It's added in ``Crawler.crawl{,_async}()`` and removed on engine_stopped. """ c = sum(1 for h in logging.root.handlers if isinstance(h, LogCounterHandler)) assert c == 0 def test_stderr_log_handler() -> None: """Test that the Scrapy root handler is always properly removed. It's added in ``configure_logging()``, called by ``{Async,}CrawlerProcess`` (without ``install_root_handler=False``). It can be removed with ``_uninstall_scrapy_root_handler()`` if installing it was really neeeded. """ c = sum(1 for h in logging.root.handlers if type(h) is logging.StreamHandler) # pylint: disable=unidiomatic-typecheck assert c == 0 @pytest.mark.requires_reactor # needs a running event loop for asyncio.all_tasks() @pytest.mark.only_asyncio def test_pending_asyncio_tasks() -> None: """Test that there are no pending asyncio tasks.""" assert not asyncio.all_tasks() def test_installed_reactor(reactor_pytest: str) -> None: """Test that the correct reactor is installed.""" match reactor_pytest: case "asyncio": assert is_asyncio_reactor_installed() case "default": assert not is_asyncio_reactor_installed() case "none": assert not is_reactor_installed()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_zz_resources.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_extension_statsmailer.py
from unittest.mock import MagicMock import pytest from scrapy import signals from scrapy.exceptions import NotConfigured from scrapy.extensions import statsmailer from scrapy.mail import MailSender from scrapy.signalmanager import SignalManager from scrapy.statscollectors import StatsCollector from scrapy.utils.spider import DefaultSpider @pytest.fixture def dummy_stats(): class DummyStats(StatsCollector): def __init__(self): # pylint: disable=super-init-not-called self._stats = {"global_item_scraped_count": 42} def get_stats(self): return {"item_scraped_count": 10, **self._stats} return DummyStats() def test_from_crawler_without_recipients_raises_notconfigured(): crawler = MagicMock() crawler.settings.getlist.return_value = [] crawler.stats = MagicMock() with pytest.raises(NotConfigured): statsmailer.StatsMailer.from_crawler(crawler) def test_from_crawler_with_recipients_initializes_extension(dummy_stats, monkeypatch): crawler = MagicMock() crawler.settings.getlist.return_value = ["test@example.com"] crawler.stats = dummy_stats crawler.signals = SignalManager(crawler) mailer = MagicMock(spec=MailSender) monkeypatch.setattr(statsmailer.MailSender, "from_crawler", lambda _: mailer) ext = statsmailer.StatsMailer.from_crawler(crawler) assert isinstance(ext, statsmailer.StatsMailer) assert ext.recipients == ["test@example.com"] assert ext.mail is mailer def test_from_crawler_connects_spider_closed_signal(dummy_stats, monkeypatch): crawler = MagicMock() crawler.settings.getlist.return_value = ["test@example.com"] crawler.stats = dummy_stats crawler.signals = SignalManager(crawler) mailer = MagicMock(spec=MailSender) monkeypatch.setattr(statsmailer.MailSender, "from_crawler", lambda _: mailer) statsmailer.StatsMailer.from_crawler(crawler) connected = crawler.signals.send_catch_log( signals.spider_closed, spider=DefaultSpider(name="dummy") ) assert connected is not None def test_spider_closed_sends_email(dummy_stats): recipients = ["test@example.com"] mail = MagicMock(spec=MailSender) ext = statsmailer.StatsMailer(dummy_stats, recipients, mail) spider = DefaultSpider(name="dummy") ext.spider_closed(spider) args, _ = mail.send.call_args to, subject, body = args assert to == recipients assert "Scrapy stats for: dummy" in subject assert "global_item_scraped_count" in body assert "item_scraped_count" in body
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_extension_statsmailer.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_core_scraper.py
from __future__ import annotations from typing import TYPE_CHECKING from scrapy.utils.test import get_crawler from tests.spiders import SimpleSpider from tests.utils.decorators import coroutine_test if TYPE_CHECKING: import pytest from tests.mockserver.http import MockServer @coroutine_test async def test_scraper_exception( mockserver: MockServer, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, ) -> None: crawler = get_crawler(SimpleSpider) monkeypatch.setattr( "scrapy.core.engine.Scraper.handle_spider_output_async", lambda *args, **kwargs: 1 / 0, ) await crawler.crawl_async(url=mockserver.url("/")) assert "Scraper bug processing" in caplog.text
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_core_scraper.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_downloader_handler_twisted_ftp.py
from __future__ import annotations import os import sys from abc import ABC, abstractmethod from pathlib import Path from tempfile import mkstemp from typing import TYPE_CHECKING, Any import pytest from pytest_twisted import async_yield_fixture from twisted.cred import checkers, credentials, portal from scrapy.core.downloader.handlers.ftp import FTPDownloadHandler from scrapy.http import HtmlResponse, Request, Response from scrapy.http.response.text import TextResponse from scrapy.utils.defer import deferred_f_from_coro_f from scrapy.utils.misc import build_from_crawler from scrapy.utils.python import to_bytes from scrapy.utils.test import get_crawler if TYPE_CHECKING: from collections.abc import AsyncGenerator, Generator from twisted.protocols.ftp import FTPFactory pytestmark = pytest.mark.requires_reactor class TestFTPBase(ABC): username = "scrapy" password = "passwd" req_meta: dict[str, Any] = {"ftp_user": username, "ftp_password": password} test_files = ( ("file.txt", b"I have the power!"), ("file with spaces.txt", b"Moooooooooo power!"), ("html-file-without-extension", b"<!DOCTYPE html>\n<title>.</title>"), ) @abstractmethod def _create_files(self, root: Path) -> None: raise NotImplementedError @abstractmethod def _get_factory(self, tmp_path: Path) -> FTPFactory: raise NotImplementedError @async_yield_fixture # type: ignore[untyped-decorator] async def server_url(self, tmp_path: Path) -> AsyncGenerator[str]: from twisted.internet import reactor self._create_files(tmp_path) factory = self._get_factory(tmp_path) port = reactor.listenTCP(0, factory, interface="127.0.0.1") portno = port.getHost().port yield f"https://127.0.0.1:{portno}/" await port.stopListening() @staticmethod @pytest.fixture def dh() -> Generator[FTPDownloadHandler]: crawler = get_crawler() dh = build_from_crawler(FTPDownloadHandler, crawler) yield dh # if the test was skipped, there will be no client attribute if hasattr(dh, "client"): assert dh.client.transport dh.client.transport.loseConnection() @deferred_f_from_coro_f async def test_ftp_download_success( self, server_url: str, dh: FTPDownloadHandler ) -> None: request = Request(url=server_url + "file.txt", meta=self.req_meta) r = await dh.download_request(request) assert r.status == 200 assert r.body == b"I have the power!" assert r.headers == {b"Local Filename": [b""], b"Size": [b"17"]} assert r.protocol is None @deferred_f_from_coro_f async def test_ftp_download_path_with_spaces( self, server_url: str, dh: FTPDownloadHandler ) -> None: request = Request( url=server_url + "file with spaces.txt", meta=self.req_meta, ) r = await dh.download_request(request) assert r.status == 200 assert r.body == b"Moooooooooo power!" assert r.headers == {b"Local Filename": [b""], b"Size": [b"18"]} @deferred_f_from_coro_f async def test_ftp_download_nonexistent( self, server_url: str, dh: FTPDownloadHandler ) -> None: request = Request(url=server_url + "nonexistent.txt", meta=self.req_meta) r = await dh.download_request(request) assert r.status == 404 assert r.body == b"['550 nonexistent.txt: No such file or directory.']" @deferred_f_from_coro_f async def test_ftp_local_filename( self, server_url: str, dh: FTPDownloadHandler ) -> None: f, local_fname = mkstemp() fname_bytes = to_bytes(local_fname) local_path = Path(local_fname) os.close(f) meta = {"ftp_local_filename": fname_bytes} meta.update(self.req_meta) request = Request(url=server_url + "file.txt", meta=meta) r = await dh.download_request(request) assert r.body == fname_bytes assert r.headers == {b"Local Filename": [fname_bytes], b"Size": [b"17"]} assert local_path.exists() assert local_path.read_bytes() == b"I have the power!" local_path.unlink() @pytest.mark.parametrize( ("filename", "response_class"), [ ("file.txt", TextResponse), ("html-file-without-extension", HtmlResponse), ], ) @deferred_f_from_coro_f async def test_response_class( self, filename: str, response_class: type[Response], server_url: str, dh: FTPDownloadHandler, ) -> None: f, local_fname = mkstemp() local_fname_path = Path(local_fname) os.close(f) meta = {} meta.update(self.req_meta) request = Request(url=server_url + filename, meta=meta) r = await dh.download_request(request) assert type(r) is response_class # pylint: disable=unidiomatic-typecheck local_fname_path.unlink() class TestFTP(TestFTPBase): def _create_files(self, root: Path) -> None: userdir = root / self.username userdir.mkdir() for filename, content in self.test_files: (userdir / filename).write_bytes(content) def _get_factory(self, root): from twisted.protocols.ftp import FTPFactory, FTPRealm realm = FTPRealm(anonymousRoot=str(root), userHome=str(root)) p = portal.Portal(realm) users_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() users_checker.addUser(self.username, self.password) p.registerChecker(users_checker, credentials.IUsernamePassword) return FTPFactory(portal=p) @deferred_f_from_coro_f async def test_invalid_credentials( self, server_url: str, dh: FTPDownloadHandler, reactor_pytest: str ) -> None: if reactor_pytest == "asyncio" and sys.platform == "win32": pytest.skip( "This test produces DirtyReactorAggregateError on Windows with asyncio" ) from twisted.protocols.ftp import ConnectionLost meta = dict(self.req_meta) meta.update({"ftp_password": "invalid"}) request = Request(url=server_url + "file.txt", meta=meta) with pytest.raises(ConnectionLost): await dh.download_request(request) class TestAnonymousFTP(TestFTPBase): username = "anonymous" req_meta = {} def _create_files(self, root: Path) -> None: for filename, content in self.test_files: (root / filename).write_bytes(content) def _get_factory(self, tmp_path): from twisted.protocols.ftp import FTPFactory, FTPRealm realm = FTPRealm(anonymousRoot=str(tmp_path)) p = portal.Portal(realm) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) return FTPFactory(portal=p, userAnonymous=self.username)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_downloader_handler_twisted_ftp.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/mockserver/dns.py
from __future__ import annotations import sys from subprocess import PIPE, Popen from twisted.internet import defer from twisted.names import dns, error from twisted.names.server import DNSServerFactory from tests.utils import get_script_run_env class MockDNSResolver: """ Implements twisted.internet.interfaces.IResolver partially """ def _resolve(self, name): record = dns.Record_A(address=b"127.0.0.1") answer = dns.RRHeader(name=name, payload=record) return [answer], [], [] def query(self, query, timeout=None): if query.type == dns.A: return defer.succeed(self._resolve(query.name.name)) return defer.fail(error.DomainError()) def lookupAllRecords(self, name, timeout=None): return defer.succeed(self._resolve(name)) class MockDNSServer: def __enter__(self): self.proc = Popen( [sys.executable, "-u", "-m", "tests.mockserver.dns"], stdout=PIPE, env=get_script_run_env(), ) self.host = "127.0.0.1" self.port = int( self.proc.stdout.readline().strip().decode("ascii").split(":")[1] ) return self def __exit__(self, exc_type, exc_value, traceback): self.proc.kill() self.proc.communicate() def main() -> None: from twisted.internet import reactor clients = [MockDNSResolver()] factory = DNSServerFactory(clients=clients) protocol = dns.DNSDatagramProtocol(controller=factory) listener = reactor.listenUDP(0, protocol) def print_listening(): host = listener.getHost() print(f"{host.host}:{host.port}") reactor.callWhenRunning(print_listening) reactor.run() if __name__ == "__main__": main()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/mockserver/dns.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/mockserver/ftp.py
from __future__ import annotations import sys from argparse import ArgumentParser from pathlib import Path from shutil import rmtree from subprocess import PIPE, Popen from tempfile import mkdtemp from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer from tests.utils import get_script_run_env class MockFTPServer: """Creates an FTP server on port 2121 with a default passwordless user (anonymous) and a temporary root path that you can read from the :attr:`path` attribute.""" def __enter__(self): self.path = Path(mkdtemp()) self.proc = Popen( [sys.executable, "-u", "-m", "tests.mockserver.ftp", "-d", str(self.path)], stderr=PIPE, env=get_script_run_env(), ) for line in self.proc.stderr: if b"starting FTP server" in line: break return self def __exit__(self, exc_type, exc_value, traceback): rmtree(str(self.path)) self.proc.kill() self.proc.communicate() def url(self, path): return "ftp://127.0.0.1:2121/" + path def main() -> None: parser = ArgumentParser() parser.add_argument("-d", "--directory") args = parser.parse_args() authorizer = DummyAuthorizer() full_permissions = "elradfmwMT" authorizer.add_anonymous(args.directory, perm=full_permissions) handler = FTPHandler handler.authorizer = authorizer address = ("127.0.0.1", 2121) server = FTPServer(address, handler) server.serve_forever() if __name__ == "__main__": main()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/mockserver/ftp.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/mockserver/http.py
from __future__ import annotations from pathlib import Path from twisted.web import resource from twisted.web.static import Data, File from twisted.web.util import Redirect from tests import tests_datadir from .http_base import BaseMockServer, main_factory from .http_resources import ( ArbitraryLengthPayloadResource, BrokenChunkedResource, BrokenDownloadResource, ChunkedResource, Compress, ContentLengthHeaderResource, Delay, Drop, DuplicateHeaderResource, Echo, EmptyContentTypeHeaderResource, Follow, ForeverTakingResource, HostHeaderResource, LargeChunkedFileResource, NoMetaRefreshRedirect, Partial, PayloadResource, Raw, RedirectTo, ResponseHeadersResource, SetCookie, Status, ) class Root(resource.Resource): def __init__(self): super().__init__() self.putChild(b"status", Status()) self.putChild(b"follow", Follow()) self.putChild(b"delay", Delay()) self.putChild(b"partial", Partial()) self.putChild(b"drop", Drop()) self.putChild(b"raw", Raw()) self.putChild(b"echo", Echo()) self.putChild(b"payload", PayloadResource()) self.putChild(b"alpayload", ArbitraryLengthPayloadResource()) self.putChild(b"static", File(str(Path(tests_datadir, "test_site/")))) self.putChild(b"redirect-to", RedirectTo()) self.putChild(b"text", Data(b"Works", "text/plain")) self.putChild( b"html", Data( b"<body><p class='one'>Works</p><p class='two'>World</p></body>", "text/html", ), ) self.putChild( b"enc-gb18030", Data(b"<p>gb18030 encoding</p>", "text/html; charset=gb18030"), ) self.putChild(b"redirect", Redirect(b"/redirected")) self.putChild( b"redirect-no-meta-refresh", NoMetaRefreshRedirect(b"/redirected") ) self.putChild(b"redirected", Data(b"Redirected here", "text/plain")) numbers = [str(x).encode("utf8") for x in range(2**18)] self.putChild(b"numbers", Data(b"".join(numbers), "text/plain")) self.putChild(b"wait", ForeverTakingResource()) self.putChild(b"hang-after-headers", ForeverTakingResource(write=True)) self.putChild(b"host", HostHeaderResource()) self.putChild(b"broken", BrokenDownloadResource()) self.putChild(b"chunked", ChunkedResource()) self.putChild(b"broken-chunked", BrokenChunkedResource()) self.putChild(b"contentlength", ContentLengthHeaderResource()) self.putChild(b"nocontenttype", EmptyContentTypeHeaderResource()) self.putChild(b"largechunkedfile", LargeChunkedFileResource()) self.putChild(b"compress", Compress()) self.putChild(b"duplicate-header", DuplicateHeaderResource()) self.putChild(b"response-headers", ResponseHeadersResource()) self.putChild(b"set-cookie", SetCookie()) def getChild(self, name, request): return self def render(self, request): return b"Scrapy mock HTTP server\n" class MockServer(BaseMockServer): module_name = "tests.mockserver.http" main = main_factory(Root) if __name__ == "__main__": main()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/mockserver/http.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/mockserver/http_base.py
"""Base classes and functions for HTTP mockservers.""" from __future__ import annotations import argparse import sys from abc import ABC, abstractmethod from subprocess import PIPE, Popen from typing import TYPE_CHECKING from urllib.parse import urlparse from twisted.web.server import Site from tests.utils import get_script_run_env from .utils import ssl_context_factory if TYPE_CHECKING: from collections.abc import Callable from twisted.web import resource class BaseMockServer(ABC): listen_http: bool = True listen_https: bool = True @property @abstractmethod def module_name(self) -> str: raise NotImplementedError def __init__(self) -> None: if not self.listen_http and not self.listen_https: raise ValueError("At least one of listen_http and listen_https must be set") self.proc: Popen | None = None self.host: str = "127.0.0.1" self.http_port: int | None = None self.https_port: int | None = None def __enter__(self): self.proc = Popen( [sys.executable, "-u", "-m", self.module_name, *self.get_additional_args()], stdout=PIPE, env=get_script_run_env(), ) if self.listen_http: http_address = self.proc.stdout.readline().strip().decode("ascii") http_parsed = urlparse(http_address) self.http_port = http_parsed.port if self.listen_https: https_address = self.proc.stdout.readline().strip().decode("ascii") https_parsed = urlparse(https_address) self.https_port = https_parsed.port return self def __exit__(self, exc_type, exc_value, traceback): if self.proc: self.proc.kill() self.proc.communicate() def get_additional_args(self) -> list[str]: return [] def port(self, is_secure: bool = False) -> int: if not is_secure and not self.listen_http: raise ValueError("This server doesn't provide HTTP") if is_secure and not self.listen_https: raise ValueError("This server doesn't provide HTTPS") port = self.https_port if is_secure else self.http_port assert port is not None return port def url(self, path: str, is_secure: bool = False) -> str: port = self.port(is_secure) scheme = "https" if is_secure else "http" return f"{scheme}://{self.host}:{port}{path}" def main_factory( resource_class: type[resource.Resource], *, listen_http: bool = True, listen_https: bool = True, ) -> Callable[[], None]: if not listen_http and not listen_https: raise ValueError("At least one of listen_http and listen_https must be set") def main() -> None: from twisted.internet import reactor root = resource_class() factory = Site(root) if listen_http: http_port = reactor.listenTCP(0, factory) if listen_https: parser = argparse.ArgumentParser() parser.add_argument("--keyfile", help="SSL key file") parser.add_argument("--certfile", help="SSL certificate file") parser.add_argument( "--cipher-string", default=None, help="SSL cipher string (optional)", ) args = parser.parse_args() context_factory_kw = {} if args.keyfile: context_factory_kw["keyfile"] = args.keyfile if args.certfile: context_factory_kw["certfile"] = args.certfile if args.cipher_string: context_factory_kw["cipher_string"] = args.cipher_string context_factory = ssl_context_factory(**context_factory_kw) https_port = reactor.listenSSL(0, factory, context_factory) def print_listening(): if listen_http: http_host = http_port.getHost() http_address = f"http://{http_host.host}:{http_host.port}" print(http_address) if listen_https: https_host = https_port.getHost() https_address = f"https://{https_host.host}:{https_host.port}" print(https_address) reactor.callWhenRunning(print_listening) reactor.run() return main
{ "repo_id": "scrapy/scrapy", "file_path": "tests/mockserver/http_base.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 106, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/mockserver/http_resources.py
from __future__ import annotations import gzip import json import random from urllib.parse import urlencode from twisted.internet.task import deferLater from twisted.web import resource, server from twisted.web.server import NOT_DONE_YET from twisted.web.util import Redirect, redirectTo from scrapy.utils.python import to_bytes, to_unicode def getarg(request, name, default=None, type_=None): if name in request.args: value = request.args[name][0] if type_ is not None: value = type_(value) return value return default def close_connection(request): # We have to force a disconnection for HTTP/1.1 clients. Otherwise # client keeps the connection open waiting for more data. request.channel.loseConnection() request.finish() # most of the following resources are copied from twisted.web.test.test_webclient class ForeverTakingResource(resource.Resource): """ L{ForeverTakingResource} is a resource which never finishes responding to requests. """ def __init__(self, write=False): resource.Resource.__init__(self) self._write = write def render(self, request): if self._write: request.write(b"some bytes") return server.NOT_DONE_YET class HostHeaderResource(resource.Resource): """ A testing resource which renders itself as the value of the host header from the request. """ def render(self, request): return request.requestHeaders.getRawHeaders(b"host")[0] class PayloadResource(resource.Resource): """ A testing resource which renders itself as the contents of the request body as long as the request body is 100 bytes long, otherwise which renders itself as C{"ERROR"}. """ def render(self, request): data = request.content.read() contentLength = request.requestHeaders.getRawHeaders(b"content-length")[0] if len(data) != 100 or int(contentLength) != 100: return b"ERROR" return data class LeafResource(resource.Resource): isLeaf = True def deferRequest(self, request, delay, f, *a, **kw): from twisted.internet import reactor def _cancelrequest(_): # silence CancelledError d.addErrback(lambda _: None) d.cancel() d = deferLater(reactor, delay, f, *a, **kw) request.notifyFinish().addErrback(_cancelrequest) return d class Follow(LeafResource): def render(self, request): total = getarg(request, b"total", 100, type_=int) show = getarg(request, b"show", 1, type_=int) order = getarg(request, b"order", b"desc") maxlatency = getarg(request, b"maxlatency", 0, type_=float) n = getarg(request, b"n", total, type_=int) if order == b"rand": nlist = [random.randint(1, total) for _ in range(show)] else: # order == "desc" nlist = range(n, max(n - show, 0), -1) lag = random.random() * maxlatency self.deferRequest(request, lag, self.renderRequest, request, nlist) return NOT_DONE_YET def renderRequest(self, request, nlist): s = """<html> <head></head> <body>""" args = request.args.copy() for nl in nlist: args[b"n"] = [to_bytes(str(nl))] argstr = urlencode(args, doseq=True) s += f"<a href='/follow?{argstr}'>follow {nl}</a><br>" s += """</body>""" request.write(to_bytes(s)) request.finish() class Delay(LeafResource): def render_GET(self, request): n = getarg(request, b"n", 1, type_=float) b = getarg(request, b"b", 1, type_=int) if b: # send headers now and delay body request.write("") self.deferRequest(request, n, self._delayedRender, request, n) return NOT_DONE_YET def _delayedRender(self, request, n): request.write(to_bytes(f"Response delayed for {n:.3f} seconds\n")) request.finish() class Status(LeafResource): def render_GET(self, request): n = getarg(request, b"n", 200, type_=int) request.setResponseCode(n) return b"" class Raw(LeafResource): def render_GET(self, request): request.startedWriting = 1 self.deferRequest(request, 0, self._delayedRender, request) return NOT_DONE_YET render_POST = render_GET def _delayedRender(self, request): raw = getarg(request, b"raw", b"HTTP 1.1 200 OK\n") request.startedWriting = 1 request.write(raw) request.channel.transport.loseConnection() request.finish() class Echo(LeafResource): def render_GET(self, request): output = { "headers": { to_unicode(k): [to_unicode(v) for v in vs] for k, vs in request.requestHeaders.getAllRawHeaders() }, "body": to_unicode(request.content.read()), } return to_bytes(json.dumps(output)) render_POST = render_GET class RedirectTo(LeafResource): def render(self, request): goto = getarg(request, b"goto", b"/") # we force the body content, otherwise Twisted redirectTo() # returns HTML with <meta http-equiv="refresh" redirectTo(goto, request) return b"redirecting..." class Partial(LeafResource): def render_GET(self, request): request.setHeader(b"Content-Length", b"1024") self.deferRequest(request, 0, self._delayedRender, request) return NOT_DONE_YET def _delayedRender(self, request): request.write(b"partial content\n") request.finish() class Drop(Partial): def _delayedRender(self, request): abort = getarg(request, b"abort", 0, type_=int) request.write(b"this connection will be dropped\n") tr = request.channel.transport try: if tr: if abort and hasattr(tr, "abortConnection"): tr.abortConnection() else: tr.loseConnection() finally: request.finish() class ArbitraryLengthPayloadResource(LeafResource): def render(self, request): return request.content.read() class NoMetaRefreshRedirect(Redirect): def render(self, request: server.Request) -> bytes: content = Redirect.render(self, request) return content.replace( b'http-equiv="refresh"', b'http-no-equiv="do-not-refresh-me"' ) class ContentLengthHeaderResource(resource.Resource): """ A testing resource which renders itself as the value of the Content-Length header from the request. """ def render(self, request): return request.requestHeaders.getRawHeaders(b"content-length")[0] class ChunkedResource(resource.Resource): def render(self, request): from twisted.internet import reactor def response(): request.write(b"chunked ") request.write(b"content\n") request.finish() reactor.callLater(0, response) return server.NOT_DONE_YET class BrokenChunkedResource(resource.Resource): def render(self, request): from twisted.internet import reactor def response(): request.write(b"chunked ") request.write(b"content\n") # Disable terminating chunk on finish. request.chunked = False close_connection(request) reactor.callLater(0, response) return server.NOT_DONE_YET class BrokenDownloadResource(resource.Resource): def render(self, request): from twisted.internet import reactor def response(): request.setHeader(b"Content-Length", b"20") request.write(b"partial") close_connection(request) reactor.callLater(0, response) return server.NOT_DONE_YET class EmptyContentTypeHeaderResource(resource.Resource): """ A testing resource which renders itself as the value of request body without content-type header in response. """ def render(self, request): request.setHeader("content-type", "") return request.content.read() class LargeChunkedFileResource(resource.Resource): def render(self, request): from twisted.internet import reactor def response(): for _ in range(1024): request.write(b"x" * 1024) request.finish() reactor.callLater(0, response) return server.NOT_DONE_YET class DuplicateHeaderResource(resource.Resource): def render(self, request): request.responseHeaders.setRawHeaders(b"Set-Cookie", [b"a=b", b"c=d"]) return b"" class UriResource(resource.Resource): """Return the full uri that was requested""" def getChild(self, path, request): return self def render(self, request): # Note: this is an ugly hack for CONNECT request timeout test. # Returning some data here fail SSL/TLS handshake # ToDo: implement proper HTTPS proxy tests, not faking them. if request.method != b"CONNECT": return request.uri request.transport.write(b"HTTP/1.1 200 Connection established\r\n\r\n") return NOT_DONE_YET class ResponseHeadersResource(resource.Resource): """Return a response with headers set from the JSON request body""" def render(self, request): body = json.loads(request.content.read().decode()) for header_name, header_value in body.items(): request.responseHeaders.addRawHeader(header_name, header_value) return json.dumps(body).encode("utf-8") class Compress(resource.Resource): """Compress the data sent in the request url params and set Content-Encoding header""" def render(self, request): data = request.args.get(b"data")[0] accept_encoding_header = request.getHeader(b"accept-encoding") # include common encoding schemes here if accept_encoding_header == b"gzip": request.setHeader(b"Content-Encoding", b"gzip") return gzip.compress(data) # just set this to trigger a test failure if no valid accept-encoding header was set request.setResponseCode(500) return b"Did not receive a valid accept-encoding header" class SetCookie(resource.Resource): """Return a response with a Set-Cookie header for each request url parameter""" def render(self, request): for cookie_name, cookie_values in request.args.items(): for cookie_value in cookie_values: cookie = (cookie_name.decode() + "=" + cookie_value.decode()).encode() request.setHeader(b"Set-Cookie", cookie) return b""
{ "repo_id": "scrapy/scrapy", "file_path": "tests/mockserver/http_resources.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 262, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/mockserver/proxy_echo.py
# This is only used by tests.test_downloader_handlers_http_base.TestHttpProxyBase from __future__ import annotations from .http_base import BaseMockServer, main_factory from .http_resources import UriResource class ProxyEchoMockServer(BaseMockServer): module_name = "tests.mockserver.proxy_echo" main = main_factory(UriResource) if __name__ == "__main__": main()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/mockserver/proxy_echo.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/mockserver/simple_https.py
# This is only used by tests.test_downloader_handlers_http_base.TestSimpleHttpsBase from __future__ import annotations from twisted.web import resource from twisted.web.static import Data from .http_base import BaseMockServer, main_factory class Root(resource.Resource): def __init__(self): resource.Resource.__init__(self) self.putChild(b"file", Data(b"0123456789", "text/plain")) def getChild(self, name, request): return self class SimpleMockServer(BaseMockServer): listen_http = False module_name = "tests.mockserver.simple_https" def __init__(self, keyfile: str, certfile: str, cipher_string: str | None): super().__init__() self.keyfile = keyfile self.certfile = certfile self.cipher_string = cipher_string or "" def get_additional_args(self) -> list[str]: args = [ "--keyfile", self.keyfile, "--certfile", self.certfile, ] if self.cipher_string is not None: args.extend(["--cipher-string", self.cipher_string]) return args main = main_factory(Root, listen_http=False) if __name__ == "__main__": main()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/mockserver/simple_https.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/mockserver/utils.py
from __future__ import annotations from pathlib import Path from OpenSSL import SSL from twisted.internet import ssl from scrapy.utils.python import to_bytes def ssl_context_factory( keyfile="keys/localhost.key", certfile="keys/localhost.crt", cipher_string=None ): factory = ssl.DefaultOpenSSLContextFactory( str(Path(__file__).parent.parent / keyfile), str(Path(__file__).parent.parent / certfile), ) if cipher_string: ctx = factory.getContext() # disabling TLS1.3 because it unconditionally enables some strong ciphers ctx.set_options(SSL.OP_CIPHER_SERVER_PREFERENCE | SSL.OP_NO_TLSv1_3) ctx.set_cipher_list(to_bytes(cipher_string)) return factory
{ "repo_id": "scrapy/scrapy", "file_path": "tests/mockserver/utils.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_command_crawl.py
from __future__ import annotations from typing import TYPE_CHECKING from tests.test_commands import TestProjectBase from tests.utils.cmdline import proc if TYPE_CHECKING: from collections.abc import Iterable from pathlib import Path class TestCrawlCommand(TestProjectBase): def crawl( self, code: str, proj_path: Path, args: Iterable[str] = () ) -> tuple[int, str, str]: (proj_path / self.project_name / "spiders" / "myspider.py").write_text( code, encoding="utf-8" ) return proc("crawl", "myspider", *args, cwd=proj_path) def get_log(self, code: str, proj_path: Path, args: Iterable[str] = ()) -> str: _, _, stderr = self.crawl(code, proj_path, args=args) return stderr def test_no_output(self, proj_path: Path) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): self.logger.debug('It works!') return yield """ log = self.get_log(spider_code, proj_path) assert "[myspider] DEBUG: It works!" in log assert ( "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" in log ) assert "Spider closed (finished)" in log def test_output(self, proj_path: Path) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): self.logger.debug('FEEDS: {}'.format(self.settings.getdict('FEEDS'))) return yield """ args = ["-o", "example.json"] log = self.get_log(spider_code, proj_path, args=args) assert "[myspider] DEBUG: FEEDS: {'example.json': {'format': 'json'}}" in log def test_overwrite_output(self, proj_path: Path) -> None: spider_code = """ import json import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): self.logger.debug( 'FEEDS: {}'.format( json.dumps(self.settings.getdict('FEEDS'), sort_keys=True) ) ) return yield """ j = proj_path / "example.json" j.write_text("not empty", encoding="utf-8") args = ["-O", "example.json"] log = self.get_log(spider_code, proj_path, args=args) assert ( '[myspider] DEBUG: FEEDS: {"example.json": {"format": "json", "overwrite": true}}' in log ) with j.open(encoding="utf-8") as f2: first_line = f2.readline() assert first_line != "not empty" def test_output_and_overwrite_output(self, proj_path: Path) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): return yield """ args = ["-o", "example1.json", "-O", "example2.json"] log = self.get_log(spider_code, proj_path, args=args) assert ( "error: Please use only one of -o/--output and -O/--overwrite-output" in log ) def test_default_reactor(self, proj_path: Path) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): self.logger.debug('It works!') return yield """ log = self.get_log(spider_code, proj_path, args=("-s", "TWISTED_REACTOR=")) assert "[myspider] DEBUG: It works!" in log assert ( "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" not in log ) assert "Spider closed (finished)" in log
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_command_crawl.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 105, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_command_genspider.py
from __future__ import annotations import re from pathlib import Path import pytest from tests.test_commands import TestProjectBase from tests.utils.cmdline import call, proc def find_in_file(filename: Path, regex: str) -> re.Match | None: """Find first pattern occurrence in file""" pattern = re.compile(regex) with filename.open("r", encoding="utf-8") as f: for line in f: match = pattern.search(line) if match is not None: return match return None class TestGenspiderCommand(TestProjectBase): def test_arguments(self, proj_path: Path) -> None: spider = proj_path / self.project_name / "spiders" / "test_name.py" # only pass one argument. spider script shouldn't be created assert call("genspider", "test_name", cwd=proj_path) == 2 assert not spider.exists() # pass two arguments <name> <domain>. spider script should be created assert call("genspider", "test_name", "test.com", cwd=proj_path) == 0 assert spider.exists() @pytest.mark.parametrize( "tplname", [ "basic", "crawl", "xmlfeed", "csvfeed", ], ) def test_template(self, tplname: str, proj_path: Path) -> None: args = [f"--template={tplname}"] if tplname else [] spname = "test_spider" spmodule = f"{self.project_name}.spiders.{spname}" spfile = proj_path / self.project_name / "spiders" / f"{spname}.py" _, out, _ = proc("genspider", spname, "test.com", *args, cwd=proj_path) assert ( f"Created spider {spname!r} using template {tplname!r} in module:\n {spmodule}" in out ) assert spfile.exists() modify_time_before = spfile.stat().st_mtime _, out, _ = proc("genspider", spname, "test.com", *args, cwd=proj_path) assert f"Spider {spname!r} already exists in module" in out modify_time_after = spfile.stat().st_mtime assert modify_time_after == modify_time_before def test_list(self, proj_path: Path) -> None: assert call("genspider", "--list", cwd=proj_path) == 0 def test_dump(self, proj_path: Path) -> None: assert call("genspider", "--dump=basic", cwd=proj_path) == 0 assert call("genspider", "-d", "basic", cwd=proj_path) == 0 def test_same_name_as_project(self, proj_path: Path) -> None: assert call("genspider", self.project_name, cwd=proj_path) == 2 assert not ( proj_path / self.project_name / "spiders" / f"{self.project_name}.py" ).exists() @pytest.mark.parametrize("force", [True, False]) def test_same_filename_as_existing_spider( self, force: bool, proj_path: Path ) -> None: file_name = "example" file_path = proj_path / self.project_name / "spiders" / f"{file_name}.py" assert call("genspider", file_name, "example.com", cwd=proj_path) == 0 assert file_path.exists() # change name of spider but not its file name with file_path.open("r+", encoding="utf-8") as spider_file: file_data = spider_file.read() file_data = file_data.replace('name = "example"', 'name = "renamed"') spider_file.seek(0) spider_file.write(file_data) spider_file.truncate() modify_time_before = file_path.stat().st_mtime file_contents_before = file_data if force: _, out, _ = proc( "genspider", "--force", file_name, "example.com", cwd=proj_path ) assert ( f"Created spider {file_name!r} using template 'basic' in module" in out ) modify_time_after = file_path.stat().st_mtime assert modify_time_after != modify_time_before file_contents_after = file_path.read_text(encoding="utf-8") assert file_contents_after != file_contents_before else: _, out, _ = proc("genspider", file_name, "example.com", cwd=proj_path) assert f"{file_path.resolve()} already exists" in out modify_time_after = file_path.stat().st_mtime assert modify_time_after == modify_time_before file_contents_after = file_path.read_text(encoding="utf-8") assert file_contents_after == file_contents_before @pytest.mark.parametrize( ("url", "domain"), [ ("test.com", "test.com"), ("https://test.com", "test.com"), ], ) def test_url(self, url: str, domain: str, proj_path: Path) -> None: assert call("genspider", "--force", "test_name", url, cwd=proj_path) == 0 spider = proj_path / self.project_name / "spiders" / "test_name.py" m = find_in_file(spider, r"allowed_domains\s*=\s*\[['\"](.+)['\"]\]") assert m is not None assert m.group(1) == domain m = find_in_file(spider, r"start_urls\s*=\s*\[['\"](.+)['\"]\]") assert m is not None assert m.group(1) == f"https://{domain}" @pytest.mark.parametrize( ("url", "expected", "template"), [ # basic ("https://test.com", "https://test.com", "basic"), ("http://test.com", "http://test.com", "basic"), ("http://test.com/other/path", "http://test.com/other/path", "basic"), ("test.com/other/path", "https://test.com/other/path", "basic"), # crawl ("https://test.com", "https://test.com", "crawl"), ("http://test.com", "http://test.com", "crawl"), ("http://test.com/other/path", "http://test.com/other/path", "crawl"), ("test.com/other/path", "https://test.com/other/path", "crawl"), ("test.com", "https://test.com", "crawl"), # xmlfeed ("https://test.com/feed.xml", "https://test.com/feed.xml", "xmlfeed"), ("http://test.com/feed.xml", "http://test.com/feed.xml", "xmlfeed"), ("test.com/feed.xml", "https://test.com/feed.xml", "xmlfeed"), # csvfeed ("https://test.com/feed.csv", "https://test.com/feed.csv", "csvfeed"), ("http://test.com/feed.xml", "http://test.com/feed.xml", "csvfeed"), ("test.com/feed.csv", "https://test.com/feed.csv", "csvfeed"), ], ) def test_template_start_urls( self, url: str, expected: str, template: str, proj_path: Path ) -> None: assert ( call( "genspider", "-t", template, "--force", "test_name", url, cwd=proj_path ) == 0 ) spider = proj_path / self.project_name / "spiders" / "test_name.py" m = find_in_file(spider, r"start_urls\s*=\s*\[['\"](.+)['\"]\]") assert m is not None assert m.group(1) == expected class TestGenspiderStandaloneCommand: def test_generate_standalone_spider(self, tmp_path: Path) -> None: call("genspider", "example", "example.com", cwd=tmp_path) assert Path(tmp_path, "example.py").exists() @pytest.mark.parametrize("force", [True, False]) def test_same_name_as_existing_file(self, force: bool, tmp_path: Path) -> None: file_name = "example" file_path = Path(tmp_path, file_name + ".py") _, out, _ = proc("genspider", file_name, "example.com", cwd=tmp_path) assert f"Created spider {file_name!r} using template 'basic' " in out assert file_path.exists() modify_time_before = file_path.stat().st_mtime file_contents_before = file_path.read_text(encoding="utf-8") if force: # use different template to ensure contents were changed _, out, _ = proc( "genspider", "--force", "-t", "crawl", file_name, "example.com", cwd=tmp_path, ) assert f"Created spider {file_name!r} using template 'crawl' " in out modify_time_after = file_path.stat().st_mtime assert modify_time_after != modify_time_before file_contents_after = file_path.read_text(encoding="utf-8") assert file_contents_after != file_contents_before else: _, out, _ = proc("genspider", file_name, "example.com", cwd=tmp_path) assert ( f"{Path(tmp_path, file_name + '.py').resolve()} already exists" in out ) modify_time_after = file_path.stat().st_mtime assert modify_time_after == modify_time_before file_contents_after = file_path.read_text(encoding="utf-8") assert file_contents_after == file_contents_before
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_command_genspider.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 185, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_command_runspider.py
from __future__ import annotations import asyncio import inspect import platform import sys from typing import TYPE_CHECKING import pytest from tests.test_crawler import ExceptionSpider, NoRequestsSpider from tests.utils.cmdline import proc if TYPE_CHECKING: from collections.abc import Iterable from pathlib import Path class TestRunSpiderCommand: spider_filename = "myspider.py" debug_log_spider = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): self.logger.debug("It Works!") return yield """ badspider = """ import scrapy class BadSpider(scrapy.Spider): name = "bad" async def start(self): raise Exception("oops!") yield """ def runspider( self, cwd: Path, code: str, name: str | None = None, args: Iterable[str] = () ) -> tuple[int, str, str]: fname = cwd / (name or self.spider_filename) fname.write_text(code, encoding="utf-8") return proc("runspider", str(fname), *args, cwd=cwd) def get_log( self, cwd: Path, code: str, name: str | None = None, args: Iterable[str] = () ) -> str: _, _, stderr = self.runspider(cwd, code, name, args=args) return stderr def test_runspider(self, tmp_path: Path) -> None: log = self.get_log(tmp_path, self.debug_log_spider) assert "DEBUG: It Works!" in log assert ( "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" in log ) assert "INFO: Spider closed (finished)" in log def test_run_fail_spider(self, tmp_path: Path) -> None: ret, _, _ = self.runspider( tmp_path, "import scrapy\n" + inspect.getsource(ExceptionSpider) ) assert ret != 0 def test_run_good_spider(self, tmp_path: Path) -> None: ret, _, _ = self.runspider( tmp_path, "import scrapy\n" + inspect.getsource(NoRequestsSpider) ) assert ret == 0 def test_runspider_log_level(self, tmp_path: Path) -> None: log = self.get_log( tmp_path, self.debug_log_spider, args=("-s", "LOG_LEVEL=INFO") ) assert "DEBUG: It Works!" not in log assert "INFO: Spider opened" in log def test_runspider_default_reactor(self, tmp_path: Path) -> None: log = self.get_log( tmp_path, self.debug_log_spider, args=("-s", "TWISTED_REACTOR=") ) assert "DEBUG: It Works!" in log assert ( "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" not in log ) assert "INFO: Spider opened" in log assert "INFO: Closing spider (finished)" in log assert "INFO: Spider closed (finished)" in log def test_runspider_dnscache_disabled(self, tmp_path: Path) -> None: # see https://github.com/scrapy/scrapy/issues/2811 # The spider below should not be able to connect to localhost:12345, # which is intended, # but this should not be because of DNS lookup error # assumption: localhost will resolve in all cases (true?) dnscache_spider = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' start_urls = ['http://localhost:12345'] custom_settings = { "ROBOTSTXT_OBEY": False, "RETRY_ENABLED": False, } def parse(self, response): return {'test': 'value'} """ log = self.get_log( tmp_path, dnscache_spider, args=("-s", "DNSCACHE_ENABLED=False") ) assert "CannotResolveHostError" not in log assert "INFO: Spider opened" in log @pytest.mark.parametrize("value", [False, True]) def test_runspider_log_short_names(self, tmp_path: Path, value: bool) -> None: log1 = self.get_log( tmp_path, self.debug_log_spider, args=("-s", f"LOG_SHORT_NAMES={value}") ) assert "[myspider] DEBUG: It Works!" in log1 assert ("[scrapy]" in log1) is value assert ("[scrapy.core.engine]" in log1) is not value def test_runspider_no_spider_found(self, tmp_path: Path) -> None: log = self.get_log(tmp_path, "from scrapy.spiders import Spider\n") assert "No spider found in file" in log def test_runspider_file_not_found(self) -> None: _, _, log = proc("runspider", "some_non_existent_file") assert "File not found: some_non_existent_file" in log def test_runspider_unable_to_load(self, tmp_path: Path) -> None: log = self.get_log(tmp_path, "", name="myspider.txt") assert "Unable to load" in log def test_start_errors(self, tmp_path: Path) -> None: log = self.get_log(tmp_path, self.badspider, name="badspider.py") assert "start" in log assert "badspider.py" in log, log def test_asyncio_enabled_true(self, tmp_path: Path) -> None: log = self.get_log( tmp_path, self.debug_log_spider, args=[ "-s", "TWISTED_REACTOR=twisted.internet.asyncioreactor.AsyncioSelectorReactor", ], ) assert ( "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" in log ) def test_asyncio_enabled_default(self, tmp_path: Path) -> None: log = self.get_log(tmp_path, self.debug_log_spider) assert ( "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" in log ) def test_asyncio_enabled_false(self, tmp_path: Path) -> None: log = self.get_log( tmp_path, self.debug_log_spider, args=["-s", "TWISTED_REACTOR=twisted.internet.selectreactor.SelectReactor"], ) assert "Using reactor: twisted.internet.selectreactor.SelectReactor" in log assert ( "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" not in log ) @pytest.mark.requires_uvloop def test_custom_asyncio_loop_enabled_true(self, tmp_path: Path) -> None: log = self.get_log( tmp_path, self.debug_log_spider, args=[ "-s", "TWISTED_REACTOR=twisted.internet.asyncioreactor.AsyncioSelectorReactor", "-s", "ASYNCIO_EVENT_LOOP=uvloop.Loop", ], ) assert "Using asyncio event loop: uvloop.Loop" in log def test_custom_asyncio_loop_enabled_false(self, tmp_path: Path) -> None: log = self.get_log( tmp_path, self.debug_log_spider, args=[ "-s", "TWISTED_REACTOR=twisted.internet.asyncioreactor.AsyncioSelectorReactor", ], ) if sys.platform != "win32": loop = asyncio.new_event_loop() else: loop = asyncio.SelectorEventLoop() assert ( f"Using asyncio event loop: {loop.__module__}.{loop.__class__.__name__}" in log ) def test_output(self, tmp_path: Path) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): self.logger.debug('FEEDS: {}'.format(self.settings.getdict('FEEDS'))) return yield """ args = ["-o", "example.json"] log = self.get_log(tmp_path, spider_code, args=args) assert "[myspider] DEBUG: FEEDS: {'example.json': {'format': 'json'}}" in log def test_overwrite_output(self, tmp_path: Path) -> None: spider_code = """ import json import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): self.logger.debug( 'FEEDS: {}'.format( json.dumps(self.settings.getdict('FEEDS'), sort_keys=True) ) ) return yield """ (tmp_path / "example.json").write_text("not empty", encoding="utf-8") args = ["-O", "example.json"] log = self.get_log(tmp_path, spider_code, args=args) assert ( '[myspider] DEBUG: FEEDS: {"example.json": {"format": "json", "overwrite": true}}' in log ) with (tmp_path / "example.json").open(encoding="utf-8") as f2: first_line = f2.readline() assert first_line != "not empty" def test_output_and_overwrite_output(self, tmp_path: Path) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): return yield """ args = ["-o", "example1.json", "-O", "example2.json"] log = self.get_log(tmp_path, spider_code, args=args) assert ( "error: Please use only one of -o/--output and -O/--overwrite-output" in log ) def test_output_stdout(self, tmp_path: Path) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' async def start(self): self.logger.debug('FEEDS: {}'.format(self.settings.getdict('FEEDS'))) return yield """ args = ["-o", "-:json"] log = self.get_log(tmp_path, spider_code, args=args) assert "[myspider] DEBUG: FEEDS: {'stdout:': {'format': 'json'}}" in log @pytest.mark.parametrize("arg", ["output.json:json", "output.json"]) def test_absolute_path(self, tmp_path: Path, arg: str) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' start_urls = ["data:,"] def parse(self, response): yield {"hello": "world"} """ args = ["-o", str(tmp_path / arg)] log = self.get_log(tmp_path, spider_code, args=args) assert ( f"[scrapy.extensions.feedexport] INFO: Stored json feed (1 items) in: {tmp_path / 'output.json'}" in log ) def test_args_change_settings(self, tmp_path: Path) -> None: spider_code = """ import scrapy class MySpider(scrapy.Spider): name = 'myspider' @classmethod def from_crawler(cls, crawler, *args, **kwargs): spider = super().from_crawler(crawler, *args, **kwargs) spider.settings.set("FOO", kwargs.get("foo")) return spider async def start(self): self.logger.info(f"The value of FOO is {self.settings.getint('FOO')}") return yield """ args = ["-a", "foo=42"] log = self.get_log(tmp_path, spider_code, args=args) assert "Spider closed (finished)" in log assert "The value of FOO is 42" in log @pytest.mark.skipif( platform.system() != "Windows", reason="Windows required for .pyw files" ) class TestWindowsRunSpiderCommand(TestRunSpiderCommand): spider_filename = "myspider.pyw" def test_start_errors(self, tmp_path: Path) -> None: log = self.get_log(tmp_path, self.badspider, name="badspider.pyw") assert "start" in log assert "badspider.pyw" in log def test_runspider_unable_to_load(self, tmp_path: Path) -> None: pytest.skip("Already Tested in 'RunSpiderCommandTest'")
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_command_runspider.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 293, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_command_startproject.py
from __future__ import annotations import os import subprocess import sys from contextlib import contextmanager from itertools import chain from pathlib import Path from shutil import copytree from stat import S_IWRITE as ANYONE_WRITE_PERMISSION import scrapy from scrapy.commands.startproject import IGNORE from scrapy.utils.test import get_testenv from tests.utils.cmdline import call, proc class TestStartprojectCommand: project_name = "testproject" @staticmethod def _assert_files_exist(project_dir: Path, project_name: str) -> None: assert (project_dir / "scrapy.cfg").exists() assert (project_dir / project_name).exists() assert (project_dir / project_name / "__init__.py").exists() assert (project_dir / project_name / "items.py").exists() assert (project_dir / project_name / "pipelines.py").exists() assert (project_dir / project_name / "settings.py").exists() assert (project_dir / project_name / "spiders" / "__init__.py").exists() def test_startproject(self, tmp_path: Path) -> None: # with no dir argument creates the project in the "self.project_name" subdir of cwd assert call("startproject", self.project_name, cwd=tmp_path) == 0 self._assert_files_exist(tmp_path / self.project_name, self.project_name) assert call("startproject", self.project_name, cwd=tmp_path) == 1 assert call("startproject", "wrong---project---name") == 1 assert call("startproject", "sys") == 1 def test_startproject_with_project_dir(self, tmp_path: Path) -> None: # with a dir arg creates the project in the specified dir project_dir = tmp_path / "project" assert ( call("startproject", self.project_name, str(project_dir), cwd=tmp_path) == 0 ) self._assert_files_exist(project_dir, self.project_name) assert ( call( "startproject", self.project_name, str(project_dir) + "2", cwd=tmp_path ) == 0 ) assert ( call("startproject", self.project_name, str(project_dir), cwd=tmp_path) == 1 ) assert ( call( "startproject", self.project_name + "2", str(project_dir), cwd=tmp_path ) == 1 ) assert call("startproject", "wrong---project---name") == 1 assert call("startproject", "sys") == 1 assert call("startproject") == 2 assert ( call("startproject", self.project_name, str(project_dir), "another_params") == 2 ) def test_existing_project_dir(self, tmp_path: Path) -> None: project_name = self.project_name + "_existing" project_path = tmp_path / project_name project_path.mkdir() assert call("startproject", project_name, cwd=tmp_path) == 0 self._assert_files_exist(project_path, project_name) def get_permissions_dict( path: str | os.PathLike, renamings=None, ignore=None ) -> dict[str, str]: def get_permissions(path: Path) -> str: return oct(path.stat().st_mode) path_obj = Path(path) renamings = renamings or () permissions_dict = { ".": get_permissions(path_obj), } for root, dirs, files in os.walk(path_obj): nodes = list(chain(dirs, files)) if ignore: ignored_names = ignore(root, nodes) nodes = [node for node in nodes if node not in ignored_names] for node in nodes: absolute_path = Path(root, node) relative_path = str(absolute_path.relative_to(path)) for search_string, replacement in renamings: relative_path = relative_path.replace(search_string, replacement) permissions = get_permissions(absolute_path) permissions_dict[relative_path] = permissions return permissions_dict class TestStartprojectTemplates: def test_startproject_template_override(self, tmp_path: Path) -> None: tmpl = tmp_path / "templates" tmpl_proj = tmpl / "project" project_name = "testproject" copytree(Path(scrapy.__path__[0], "templates"), tmpl) (tmpl_proj / "root_template").write_bytes(b"") args = ["--set", f"TEMPLATES_DIR={tmpl}"] _, out, _ = proc("startproject", project_name, *args, cwd=tmp_path) assert f"New Scrapy project '{project_name}', using template directory" in out assert str(tmpl_proj) in out assert (tmp_path / project_name / "root_template").exists() def test_startproject_permissions_from_writable(self, tmp_path: Path) -> None: """Check that generated files have the right permissions when the template folder has the same permissions as in the project, i.e. everything is writable.""" scrapy_path = scrapy.__path__[0] project_template = Path(scrapy_path, "templates", "project") project_name = "startproject1" renamings = ( ("module", project_name), (".tmpl", ""), ) expected_permissions = get_permissions_dict( project_template, renamings, IGNORE, ) destination = tmp_path / "proj" destination.mkdir() process = subprocess.Popen( ( sys.executable, "-m", "scrapy.cmdline", "startproject", project_name, ), cwd=destination, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=get_testenv(), ) process.wait() project_dir = destination / project_name actual_permissions = get_permissions_dict(project_dir) assert actual_permissions == expected_permissions def test_startproject_permissions_from_read_only(self, tmp_path: Path) -> None: """Check that generated files have the right permissions when the template folder has been made read-only, which is something that some systems do. See https://github.com/scrapy/scrapy/pull/4604 """ scrapy_path = scrapy.__path__[0] templates_dir = Path(scrapy_path, "templates") project_template = Path(templates_dir, "project") project_name = "startproject2" renamings = ( ("module", project_name), (".tmpl", ""), ) expected_permissions = get_permissions_dict( project_template, renamings, IGNORE, ) def _make_read_only(path: Path): current_permissions = path.stat().st_mode path.chmod(current_permissions & ~ANYONE_WRITE_PERMISSION) read_only_templates_dir = tmp_path / "templates" copytree(templates_dir, read_only_templates_dir) for root, dirs, files in os.walk(read_only_templates_dir): for node in chain(dirs, files): _make_read_only(Path(root, node)) destination = tmp_path / "proj" destination.mkdir() assert ( call( "startproject", project_name, "--set", f"TEMPLATES_DIR={read_only_templates_dir}", cwd=destination, ) == 0 ) project_dir = destination / project_name actual_permissions = get_permissions_dict(project_dir) assert actual_permissions == expected_permissions def test_startproject_permissions_unchanged_in_destination( self, tmp_path: Path ) -> None: """Check that preexisting folders and files in the destination folder do not see their permissions modified.""" scrapy_path = scrapy.__path__[0] project_template = Path(scrapy_path, "templates", "project") project_name = "startproject3" renamings = ( ("module", project_name), (".tmpl", ""), ) expected_permissions = get_permissions_dict( project_template, renamings, IGNORE, ) destination = tmp_path / "proj" project_dir = destination / project_name project_dir.mkdir(parents=True) existing_nodes = { f"{permissions:o}{extension}": permissions for extension in ("", ".d") for permissions in ( 0o444, 0o555, 0o644, 0o666, 0o755, 0o777, ) } for node, permissions in existing_nodes.items(): path = project_dir / node if node.endswith(".d"): path.mkdir(mode=permissions) else: path.touch(mode=permissions) expected_permissions[node] = oct(path.stat().st_mode) assert call("startproject", project_name, ".", cwd=project_dir) == 0 actual_permissions = get_permissions_dict(project_dir) assert actual_permissions == expected_permissions def test_startproject_permissions_umask_022(self, tmp_path: Path) -> None: """Check that generated files have the right permissions when the system uses a umask value that causes new files to have different permissions than those from the template folder.""" @contextmanager def umask(new_mask): cur_mask = os.umask(new_mask) yield os.umask(cur_mask) scrapy_path = scrapy.__path__[0] project_template = Path(scrapy_path, "templates", "project") project_name = "umaskproject" renamings = ( ("module", project_name), (".tmpl", ""), ) expected_permissions = get_permissions_dict( project_template, renamings, IGNORE, ) with umask(0o002): destination = tmp_path / "proj" destination.mkdir() assert call("startproject", project_name, cwd=destination) == 0 project_dir = destination / project_name actual_permissions = get_permissions_dict(project_dir) assert actual_permissions == expected_permissions
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_command_startproject.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 248, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/args_settings.py
from typing import Any import scrapy from scrapy.crawler import AsyncCrawlerProcess, Crawler class NoRequestsSpider(scrapy.Spider): name = "no_request" @classmethod def from_crawler(cls, crawler: Crawler, *args: Any, **kwargs: Any): spider = super().from_crawler(crawler, *args, **kwargs) spider.settings.set("FOO", kwargs.get("foo")) return spider async def start(self): self.logger.info(f"The value of FOO is {self.settings.getint('FOO')}") return yield process = AsyncCrawlerProcess(settings={}) process.crawl(NoRequestsSpider, foo=42) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/args_settings.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/asyncio_custom_loop.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/asyncio_custom_loop.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/asyncio_custom_loop_custom_settings_different.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" custom_settings = { "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": None, } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/asyncio_custom_loop_custom_settings_different.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/asyncio_custom_loop_custom_settings_same.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" custom_settings = { "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/asyncio_custom_loop_custom_settings_same.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/asyncio_deferred_signal.py
from __future__ import annotations import asyncio import sys from scrapy import Spider from scrapy.crawler import AsyncCrawlerProcess from scrapy.utils.defer import deferred_from_coro class UppercasePipeline: async def _open_spider(self, spider): spider.logger.info("async pipeline opened!") await asyncio.sleep(0.1) def open_spider(self, spider): return deferred_from_coro(self._open_spider(spider)) def process_item(self, item): return {"url": item["url"].upper()} class UrlSpider(Spider): name = "url_spider" start_urls = ["data:,"] custom_settings = { "ITEM_PIPELINES": {UppercasePipeline: 100}, } def parse(self, response): yield {"url": response.url} if __name__ == "__main__": ASYNCIO_EVENT_LOOP: str | None try: ASYNCIO_EVENT_LOOP = sys.argv[1] except IndexError: ASYNCIO_EVENT_LOOP = None process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": ASYNCIO_EVENT_LOOP, } ) process.crawl(UrlSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/asyncio_deferred_signal.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/asyncio_enabled_no_reactor.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess from scrapy.utils.reactor import is_asyncio_reactor_installed class ReactorCheckExtension: def __init__(self): if not is_asyncio_reactor_installed(): raise RuntimeError("ReactorCheckExtension requires the asyncio reactor.") class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "EXTENSIONS": {ReactorCheckExtension: 0}, } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/asyncio_enabled_no_reactor.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/asyncio_enabled_reactor.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess from scrapy.utils.reactor import ( install_reactor, is_asyncio_reactor_installed, is_reactor_installed, ) if is_reactor_installed(): raise RuntimeError( "Reactor already installed before is_asyncio_reactor_installed()." ) try: is_asyncio_reactor_installed() except RuntimeError: pass else: raise RuntimeError("is_asyncio_reactor_installed() did not raise RuntimeError.") if is_reactor_installed(): raise RuntimeError( "Reactor already installed after is_asyncio_reactor_installed()." ) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") if not is_asyncio_reactor_installed(): raise RuntimeError("Wrong reactor installed after install_reactor().") class ReactorCheckExtension: def __init__(self): if not is_asyncio_reactor_installed(): raise RuntimeError("ReactorCheckExtension requires the asyncio reactor.") class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "EXTENSIONS": {ReactorCheckExtension: 0}, } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/asyncio_enabled_reactor.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/asyncio_enabled_reactor_different_loop.py
import asyncio import sys from twisted.internet import asyncioreactor import scrapy from scrapy.crawler import AsyncCrawlerProcess if sys.platform == "win32": asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) asyncioreactor.install(asyncio.get_event_loop()) class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/asyncio_enabled_reactor_different_loop.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/asyncio_enabled_reactor_same_loop.py
import asyncio import sys from twisted.internet import asyncioreactor from uvloop import Loop import scrapy from scrapy.crawler import AsyncCrawlerProcess if sys.platform == "win32": asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) asyncio.set_event_loop(Loop()) asyncioreactor.install(asyncio.get_event_loop()) class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } ) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/asyncio_enabled_reactor_same_loop.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/caching_hostname_resolver.py
import sys import scrapy from scrapy.crawler import AsyncCrawlerProcess class CachingHostnameResolverSpider(scrapy.Spider): """ Finishes in a finite amount of time (does not hang indefinitely in the DNS resolution) """ name = "caching_hostname_resolver_spider" async def start(self): yield scrapy.Request(self.url) def parse(self, response): for _ in range(10): yield scrapy.Request( response.url, dont_filter=True, callback=self.ignore_response ) def ignore_response(self, response): self.logger.info(repr(response.ip_address)) if __name__ == "__main__": process = AsyncCrawlerProcess( settings={ "RETRY_ENABLED": False, "DNS_RESOLVER": "scrapy.resolver.CachingHostnameResolver", } ) process.crawl(CachingHostnameResolverSpider, url=sys.argv[1]) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/caching_hostname_resolver.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/caching_hostname_resolver_ipv6.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class CachingHostnameResolverSpider(scrapy.Spider): """ Finishes without a scrapy.exceptions.CannotResolveHostError exception """ name = "caching_hostname_resolver_spider" start_urls = ["http://[::1]"] if __name__ == "__main__": process = AsyncCrawlerProcess( settings={ "RETRY_ENABLED": False, "DNS_RESOLVER": "scrapy.resolver.CachingHostnameResolver", } ) process.crawl(CachingHostnameResolverSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/caching_hostname_resolver_ipv6.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/default_name_resolver.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class IPv6Spider(scrapy.Spider): """ Raises a scrapy.exceptions.CannotResolveHostError: the default name resolver does not handle IPv6 addresses. """ name = "ipv6_spider" start_urls = ["http://[::1]"] if __name__ == "__main__": process = AsyncCrawlerProcess(settings={"RETRY_ENABLED": False}) process.crawl(IPv6Spider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/default_name_resolver.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/multi.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess(settings={}) process.crawl(NoRequestsSpider) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/multi.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/reactor_default.py
from twisted.internet import reactor # noqa: F401,TID253 import scrapy from scrapy.crawler import AsyncCrawlerProcess class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess(settings={}) d = process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/reactor_default.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/simple.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess from scrapy.utils.reactorless import is_reactorless class NoRequestsSpider(scrapy.Spider): name = "no_request" async def start(self): self.logger.info(f"is_reactorless(): {is_reactorless()}") return yield process = AsyncCrawlerProcess(settings={}) process.crawl(NoRequestsSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/simple.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/sleeping.py
import asyncio import sys import scrapy from scrapy.crawler import AsyncCrawlerProcess class SleepingSpider(scrapy.Spider): name = "sleeping" start_urls = ["data:,;"] async def parse(self, response): await asyncio.sleep(int(sys.argv[1])) process = AsyncCrawlerProcess(settings={}) process.crawl(SleepingSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/sleeping.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/twisted_reactor_asyncio.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class AsyncioReactorSpider(scrapy.Spider): name = "asyncio_reactor" process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", } ) process.crawl(AsyncioReactorSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/twisted_reactor_asyncio.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/twisted_reactor_custom_settings.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class AsyncioReactorSpider(scrapy.Spider): name = "asyncio_reactor" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", } process = AsyncCrawlerProcess() process.crawl(AsyncioReactorSpider) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/twisted_reactor_custom_settings.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/twisted_reactor_custom_settings_same.py
import scrapy from scrapy.crawler import AsyncCrawlerProcess class AsyncioReactorSpider1(scrapy.Spider): name = "asyncio_reactor1" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", } class AsyncioReactorSpider2(scrapy.Spider): name = "asyncio_reactor2" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", } process = AsyncCrawlerProcess() process.crawl(AsyncioReactorSpider1) process.crawl(AsyncioReactorSpider2) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/twisted_reactor_custom_settings_same.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerProcess/twisted_reactor_custom_settings_select.py
from __future__ import annotations import logging from typing import TYPE_CHECKING import scrapy from scrapy.crawler import AsyncCrawlerProcess if TYPE_CHECKING: from asyncio import Task class AsyncioReactorSpider(scrapy.Spider): name = "asyncio_reactor" custom_settings = { "TWISTED_REACTOR": "twisted.internet.selectreactor.SelectReactor", } def log_task_exception(task: Task) -> None: try: task.result() except Exception: logging.exception("Crawl task failed") # noqa: LOG015 process = AsyncCrawlerProcess() task = process.crawl(AsyncioReactorSpider) task.add_done_callback(log_task_exception) process.start()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerProcess/twisted_reactor_custom_settings_select.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/custom_loop_different.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.defer import deferred_f_from_coro_f from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } async def start(self): return yield @deferred_f_from_coro_f async def main(reactor): configure_logging() runner = AsyncCrawlerRunner() await runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/custom_loop_different.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/custom_loop_same.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.defer import deferred_f_from_coro_f from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } async def start(self): return yield @deferred_f_from_coro_f async def main(reactor): configure_logging() runner = AsyncCrawlerRunner() await runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor", "uvloop.Loop") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/custom_loop_same.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/CrawlerRunner/custom_loop_different.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } async def start(self): return yield def main(reactor): configure_logging() runner = CrawlerRunner() return runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/CrawlerRunner/custom_loop_different.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/CrawlerRunner/custom_loop_same.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } async def start(self): return yield def main(reactor): configure_logging() runner = CrawlerRunner() return runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor", "uvloop.Loop") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/CrawlerRunner/custom_loop_same.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_utils_reactor.py
import asyncio import warnings import pytest from scrapy.utils.reactor import ( _asyncio_reactor_path, install_reactor, is_asyncio_reactor_installed, set_asyncio_event_loop, ) from tests.utils.decorators import coroutine_test class TestAsyncio: @pytest.mark.requires_reactor def test_is_asyncio_reactor_installed(self, reactor_pytest: str) -> None: # the result should depend only on the pytest --reactor argument assert is_asyncio_reactor_installed() == (reactor_pytest == "asyncio") @pytest.mark.requires_reactor def test_install_asyncio_reactor(self): from twisted.internet import reactor as original_reactor with warnings.catch_warnings(record=True) as w: install_reactor(_asyncio_reactor_path) assert len(w) == 0, [str(warning) for warning in w] from twisted.internet import reactor # pylint: disable=reimported assert original_reactor == reactor @pytest.mark.requires_reactor @pytest.mark.only_asyncio @coroutine_test async def test_set_asyncio_event_loop(self): install_reactor(_asyncio_reactor_path) assert set_asyncio_event_loop(None) is asyncio.get_running_loop()
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_utils_reactor.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_downloader_handler_twisted_http10.py
"""Tests for scrapy.core.downloader.handlers.http10.HTTP10DownloadHandler.""" from __future__ import annotations from typing import TYPE_CHECKING import pytest from scrapy.core.downloader.handlers.http10 import HTTP10DownloadHandler from scrapy.http import Request from scrapy.utils.defer import deferred_f_from_coro_f from tests.test_downloader_handlers_http_base import TestHttpBase, TestHttpProxyBase if TYPE_CHECKING: from scrapy.core.downloader.handlers import DownloadHandlerProtocol from tests.mockserver.http import MockServer pytestmark = pytest.mark.requires_reactor class HTTP10DownloadHandlerMixin: @property def download_handler_cls(self) -> type[DownloadHandlerProtocol]: return HTTP10DownloadHandler @pytest.mark.filterwarnings("ignore::scrapy.exceptions.ScrapyDeprecationWarning") class TestHttp10(HTTP10DownloadHandlerMixin, TestHttpBase): """HTTP 1.0 test case""" def test_unsupported_scheme(self) -> None: # type: ignore[override] pytest.skip("Check not implemented") @deferred_f_from_coro_f async def test_protocol(self, mockserver: MockServer) -> None: request = Request( mockserver.url("/host", is_secure=self.is_secure), method="GET" ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.protocol == "HTTP/1.0" class TestHttps10(TestHttp10): is_secure = True @pytest.mark.filterwarnings("ignore::scrapy.exceptions.ScrapyDeprecationWarning") class TestHttp10Proxy(HTTP10DownloadHandlerMixin, TestHttpProxyBase): @deferred_f_from_coro_f async def test_download_with_proxy_https_timeout(self): pytest.skip("Not implemented") @deferred_f_from_coro_f async def test_download_with_proxy_without_http_scheme(self): pytest.skip("Not implemented")
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_downloader_handler_twisted_http10.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_downloader_handler_twisted_http11.py
"""Tests for scrapy.core.downloader.handlers.http11.HTTP11DownloadHandler.""" from __future__ import annotations from typing import TYPE_CHECKING, Any import pytest from scrapy.core.downloader.handlers.http11 import HTTP11DownloadHandler from tests.test_downloader_handlers_http_base import ( TestHttp11Base, TestHttpProxyBase, TestHttps11Base, TestHttpsCustomCiphersBase, TestHttpsInvalidDNSIdBase, TestHttpsInvalidDNSPatternBase, TestHttpsWrongHostnameBase, TestHttpWithCrawlerBase, TestSimpleHttpsBase, ) if TYPE_CHECKING: from scrapy.core.downloader.handlers import DownloadHandlerProtocol pytestmark = pytest.mark.requires_reactor class HTTP11DownloadHandlerMixin: @property def download_handler_cls(self) -> type[DownloadHandlerProtocol]: return HTTP11DownloadHandler class TestHttp11(HTTP11DownloadHandlerMixin, TestHttp11Base): pass class TestHttps11(HTTP11DownloadHandlerMixin, TestHttps11Base): pass class TestSimpleHttps(HTTP11DownloadHandlerMixin, TestSimpleHttpsBase): pass class TestHttps11WrongHostname(HTTP11DownloadHandlerMixin, TestHttpsWrongHostnameBase): pass class TestHttps11InvalidDNSId(HTTP11DownloadHandlerMixin, TestHttpsInvalidDNSIdBase): pass class TestHttps11InvalidDNSPattern( HTTP11DownloadHandlerMixin, TestHttpsInvalidDNSPatternBase ): pass class TestHttps11CustomCiphers(HTTP11DownloadHandlerMixin, TestHttpsCustomCiphersBase): pass class TestHttp11WithCrawler(TestHttpWithCrawlerBase): @property def settings_dict(self) -> dict[str, Any] | None: return { "DOWNLOAD_HANDLERS": { "http": "scrapy.core.downloader.handlers.http11.HTTP11DownloadHandler", "https": "scrapy.core.downloader.handlers.http11.HTTP11DownloadHandler", } } class TestHttps11WithCrawler(TestHttp11WithCrawler): is_secure = True class TestHttp11Proxy(HTTP11DownloadHandlerMixin, TestHttpProxyBase): pass
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_downloader_handler_twisted_http11.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_downloader_handlers_http_base.py
"""Base classes for HTTP download handler tests.""" from __future__ import annotations import gzip import json import re import sys from abc import ABC, abstractmethod from contextlib import asynccontextmanager from http import HTTPStatus from ipaddress import IPv4Address from socket import gethostbyname from typing import TYPE_CHECKING, Any from urllib.parse import urlparse import pytest from twisted.internet.ssl import Certificate from twisted.python.failure import Failure from scrapy.exceptions import ( CannotResolveHostError, DownloadCancelledError, DownloadConnectionRefusedError, DownloadFailedError, DownloadTimeoutError, ResponseDataLossError, StopDownload, UnsupportedURLSchemeError, ) from scrapy.http import Headers, HtmlResponse, Request, Response, TextResponse from scrapy.utils.defer import deferred_from_coro, maybe_deferred_to_future from scrapy.utils.misc import build_from_crawler from scrapy.utils.spider import DefaultSpider from scrapy.utils.test import get_crawler from tests import NON_EXISTING_RESOLVABLE from tests.mockserver.proxy_echo import ProxyEchoMockServer from tests.mockserver.simple_https import SimpleMockServer from tests.spiders import ( BytesReceivedCallbackSpider, BytesReceivedErrbackSpider, HeadersReceivedCallbackSpider, HeadersReceivedErrbackSpider, SingleRequestSpider, ) from tests.utils.decorators import coroutine_test if TYPE_CHECKING: from collections.abc import AsyncGenerator, Generator from scrapy.core.downloader.handlers import DownloadHandlerProtocol from tests.mockserver.http import MockServer class TestHttpBase(ABC): is_secure = False @property @abstractmethod def download_handler_cls(self) -> type[DownloadHandlerProtocol]: raise NotImplementedError @asynccontextmanager async def get_dh( self, settings_dict: dict[str, Any] | None = None ) -> AsyncGenerator[DownloadHandlerProtocol]: crawler = get_crawler(DefaultSpider, settings_dict) crawler.spider = crawler._create_spider() dh = build_from_crawler(self.download_handler_cls, crawler) try: yield dh finally: await dh.close() @coroutine_test async def test_unsupported_scheme(self) -> None: request = Request("ftp://unsupported.scheme") async with self.get_dh() as download_handler: with pytest.raises(UnsupportedURLSchemeError): await download_handler.download_request(request) @coroutine_test async def test_download(self, mockserver: MockServer) -> None: request = Request(mockserver.url("/text", is_secure=self.is_secure)) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == b"Works" @coroutine_test async def test_download_head(self, mockserver: MockServer) -> None: request = Request( mockserver.url("/text", is_secure=self.is_secure), method="HEAD" ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == b"" @pytest.mark.parametrize( "http_status", [ pytest.param(http_status, id=f"status={http_status.value}") for http_status in HTTPStatus if http_status.value == 200 or http_status.value // 100 in (4, 5) ], ) @coroutine_test async def test_download_has_correct_http_status_code( self, mockserver: MockServer, http_status: HTTPStatus ) -> None: request = Request( mockserver.url(f"/status?n={http_status.value}", is_secure=self.is_secure) ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == http_status.value @coroutine_test async def test_server_receives_correct_request_headers( self, mockserver: MockServer ) -> None: request_headers = { # common request headers "Accept": "text/html", "Accept-Charset": "utf-8", "Accept-Datetime": "Thu, 31 May 2007 20:35:00 GMT", "Accept-Encoding": "gzip, deflate", # custom headers "X-Custom-Header": "Custom Value", } request = Request( mockserver.url("/echo", is_secure=self.is_secure), headers=request_headers, ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == HTTPStatus.OK body = json.loads(response.body.decode("utf-8")) assert "headers" in body for header_name, header_value in request_headers.items(): assert header_name in body["headers"] assert body["headers"][header_name] == [header_value] @coroutine_test async def test_request_header_none(self, mockserver: MockServer) -> None: """Adding a header with None as the value should not send that header.""" request_headers = { "Cookie": None, "X-Custom-Header": None, } request = Request( mockserver.url("/echo", is_secure=self.is_secure), headers=request_headers, ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == HTTPStatus.OK body = json.loads(response.body.decode("utf-8")) assert "headers" in body for header_name in request_headers: assert header_name not in body["headers"] @pytest.mark.parametrize( "request_headers", [ {"X-Custom-Header": ["foo", "bar"]}, [("X-Custom-Header", "foo"), ("X-Custom-Header", "bar")], ], ) @coroutine_test async def test_request_header_duplicate( self, mockserver: MockServer, request_headers: Any ) -> None: """All values for a header should be sent.""" request = Request( mockserver.url("/echo", is_secure=self.is_secure), headers=request_headers, ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == HTTPStatus.OK body = json.loads(response.body.decode("utf-8")) assert "headers" in body assert body["headers"]["X-Custom-Header"] == ["foo", "bar"] @coroutine_test async def test_server_receives_correct_request_body( self, mockserver: MockServer ) -> None: request_body = { "message": "It works!", } request = Request( mockserver.url("/echo", is_secure=self.is_secure), body=json.dumps(request_body), ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == HTTPStatus.OK body = json.loads(response.body.decode("utf-8")) assert json.loads(body["body"]) == request_body @coroutine_test async def test_download_has_correct_response_headers( self, mockserver: MockServer ) -> None: # these headers will be set on the response in the resource and returned response_headers = { # common response headers "Access-Control-Allow-Origin": "*", "Allow": "Get, Head", "Age": "12", "Cache-Control": "max-age=3600", "Content-Encoding": "gzip", "Content-MD5": "Q2hlY2sgSW50ZWdyaXR5IQ==", "Content-Type": "text/html; charset=utf-8", "Date": "Tue, 15 Nov 1994 08:12:31 GMT", "Pragma": "no-cache", "Retry-After": "120", "Set-Cookie": "CookieName=CookieValue; Max-Age=3600; Version=1", "WWW-Authenticate": "Basic", # custom headers "X-Custom-Header": "Custom Header Value", } request = Request( mockserver.url("/response-headers", is_secure=self.is_secure), headers={"content-type": "application/json"}, body=json.dumps(response_headers), ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == 200 for header_name, header_value in response_headers.items(): assert header_name in response.headers, ( f"Response was missing expected header {header_name}" ) assert response.headers[header_name] == bytes( header_value, encoding="utf-8" ) @coroutine_test async def test_redirect_status(self, mockserver: MockServer) -> None: request = Request(mockserver.url("/redirect", is_secure=self.is_secure)) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == 302 @coroutine_test async def test_redirect_status_head(self, mockserver: MockServer) -> None: request = Request( mockserver.url("/redirect", is_secure=self.is_secure), method="HEAD" ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == 302 @coroutine_test async def test_timeout_download_from_spider_nodata_rcvd( self, mockserver: MockServer, reactor_pytest: str ) -> None: if reactor_pytest == "asyncio" and sys.platform == "win32": # https://twistedmatrix.com/trac/ticket/10279 pytest.skip( "This test produces DirtyReactorAggregateError on Windows with asyncio" ) # client connects but no data is received meta = {"download_timeout": 0.5} request = Request(mockserver.url("/wait", is_secure=self.is_secure), meta=meta) async with self.get_dh() as download_handler: d = deferred_from_coro(download_handler.download_request(request)) with pytest.raises(DownloadTimeoutError): await maybe_deferred_to_future(d) @coroutine_test async def test_timeout_download_from_spider_server_hangs( self, mockserver: MockServer, reactor_pytest: str, ) -> None: if reactor_pytest == "asyncio" and sys.platform == "win32": # https://twistedmatrix.com/trac/ticket/10279 pytest.skip( "This test produces DirtyReactorAggregateError on Windows with asyncio" ) # client connects, server send headers and some body bytes but hangs meta = {"download_timeout": 0.5} request = Request( mockserver.url("/hang-after-headers", is_secure=self.is_secure), meta=meta ) async with self.get_dh() as download_handler: d = deferred_from_coro(download_handler.download_request(request)) with pytest.raises(DownloadTimeoutError): await maybe_deferred_to_future(d) @pytest.mark.parametrize("send_header", [True, False]) @coroutine_test async def test_host_header(self, send_header: bool, mockserver: MockServer) -> None: host_port = f"{mockserver.host}:{mockserver.port(is_secure=self.is_secure)}" request = Request( mockserver.url("/host", is_secure=self.is_secure), headers={"Host": host_port} if send_header else {}, ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == host_port.encode() if send_header: assert request.headers.get("Host") == host_port.encode() else: assert not request.headers @coroutine_test async def test_content_length_zero_bodyless_post_request_headers( self, mockserver: MockServer ) -> None: """Tests if "Content-Length: 0" is sent for bodyless POST requests. This is not strictly required by HTTP RFCs but can cause trouble for some web servers. See: https://github.com/scrapy/scrapy/issues/823 https://issues.apache.org/jira/browse/TS-2902 https://github.com/kennethreitz/requests/issues/405 https://bugs.python.org/issue14721 """ request = Request( mockserver.url("/contentlength", is_secure=self.is_secure), method="POST" ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == b"0" @coroutine_test async def test_content_length_zero_bodyless_post_only_one( self, mockserver: MockServer ) -> None: request = Request( mockserver.url("/echo", is_secure=self.is_secure), method="POST" ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) headers = Headers(json.loads(response.text)["headers"]) contentlengths = headers.getlist("Content-Length") assert len(contentlengths) == 1 assert contentlengths == [b"0"] @coroutine_test async def test_payload(self, mockserver: MockServer) -> None: body = b"1" * 100 # PayloadResource requires body length to be 100 request = Request( mockserver.url("/payload", is_secure=self.is_secure), method="POST", body=body, ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == body @coroutine_test async def test_response_header_content_length(self, mockserver: MockServer) -> None: request = Request( mockserver.url("/text", is_secure=self.is_secure), method="GET" ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.headers[b"content-length"] == b"5" @pytest.mark.parametrize( ("filename", "body", "response_class"), [ ("foo.html", b"", HtmlResponse), ("foo", b"<!DOCTYPE html>\n<title>.</title>", HtmlResponse), ], ) @coroutine_test async def test_response_class( self, filename: str, body: bytes, response_class: type[Response], mockserver: MockServer, ) -> None: request = Request( mockserver.url(f"/{filename}", is_secure=self.is_secure), body=body ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert type(response) is response_class # pylint: disable=unidiomatic-typecheck @coroutine_test async def test_get_duplicate_header(self, mockserver: MockServer) -> None: request = Request(mockserver.url("/duplicate-header", is_secure=self.is_secure)) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.headers.getlist(b"Set-Cookie") == [b"a=b", b"c=d"] @coroutine_test async def test_download_is_not_automatically_gzip_decoded( self, mockserver: MockServer ) -> None: """Test download handler does not automatically decode content using the scheme provided in Content-Encoding header""" data = "compress-me" # send a request to mock resource that gzip encodes the "data" url parameter request = Request( mockserver.url(f"/compress?data={data}", is_secure=self.is_secure), headers={ "accept-encoding": "gzip", }, ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == 200 # check that the Content-Encoding header is gzip content_encoding = response.headers[b"Content-Encoding"] assert content_encoding == b"gzip" # check that the response is still encoded # by checking for the magic number that is always included at the start of a gzip encoding # see https://datatracker.ietf.org/doc/html/rfc1952#page-5 section 2.3.1 GZIP_MAGIC = b"\x1f\x8b" assert response.body[:2] == GZIP_MAGIC, "Response body was not in gzip format" # check that a gzip decoding matches the data sent in the request expected_decoding = bytes(data, encoding="utf-8") assert gzip.decompress(response.body) == expected_decoding @coroutine_test async def test_no_cookie_processing_or_persistence( self, mockserver: MockServer ) -> None: cookie_name = "foo" cookie_value = "bar" # check that cookies are not modified request = Request( mockserver.url( f"/set-cookie?{cookie_name}={cookie_value}", is_secure=self.is_secure ) ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == 200 set_cookie = response.headers.get(b"Set-Cookie") assert set_cookie == f"{cookie_name}={cookie_value}".encode() # check that cookies are not sent in the next request request = Request(mockserver.url("/echo", is_secure=self.is_secure)) response = await download_handler.download_request(request) assert response.status == 200 headers = Headers(json.loads(response.text)["headers"]) assert "Cookie" not in headers assert "cookie" not in headers class TestHttp11Base(TestHttpBase): """HTTP 1.1 test case""" @coroutine_test async def test_download_without_maxsize_limit(self, mockserver: MockServer) -> None: request = Request(mockserver.url("/text", is_secure=self.is_secure)) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == b"Works" @coroutine_test async def test_response_class_choosing_request( self, mockserver: MockServer ) -> None: """Tests choosing of correct response type in case of Content-Type is empty but body contains text. """ body = b"Some plain text\ndata with tabs\t and null bytes\0" request = Request( mockserver.url("/nocontenttype", is_secure=self.is_secure), body=body ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert type(response) is TextResponse # pylint: disable=unidiomatic-typecheck @coroutine_test async def test_download_with_maxsize( self, caplog: pytest.LogCaptureFixture, mockserver: MockServer ) -> None: request = Request(mockserver.url("/text", is_secure=self.is_secure)) # 10 is minimal size for this request and the limit is only counted on # response body. (regardless of headers) async with self.get_dh({"DOWNLOAD_MAXSIZE": 5}) as download_handler: response = await download_handler.download_request(request) assert response.body == b"Works" caplog.clear() msg = "Expected to receive 5 bytes which is larger than download max size (4)" async with self.get_dh({"DOWNLOAD_MAXSIZE": 4}) as download_handler: with pytest.raises(DownloadCancelledError, match=re.escape(msg)): await download_handler.download_request(request) assert msg in caplog.text @coroutine_test async def test_download_with_maxsize_very_large_file( self, mockserver: MockServer, caplog: pytest.LogCaptureFixture ) -> None: request = Request(mockserver.url("/largechunkedfile", is_secure=self.is_secure)) async with self.get_dh({"DOWNLOAD_MAXSIZE": 1_500}) as download_handler: with pytest.raises(DownloadCancelledError): await download_handler.download_request(request) assert ( "Received 2048 bytes which is larger than download max size (1500)" in caplog.text ) @coroutine_test async def test_download_with_maxsize_per_req(self, mockserver: MockServer) -> None: meta = {"download_maxsize": 2} request = Request(mockserver.url("/text", is_secure=self.is_secure), meta=meta) async with self.get_dh() as download_handler: with pytest.raises(DownloadCancelledError): await download_handler.download_request(request) @coroutine_test async def test_download_with_small_maxsize_via_setting( self, mockserver: MockServer ) -> None: request = Request(mockserver.url("/text", is_secure=self.is_secure)) async with self.get_dh({"DOWNLOAD_MAXSIZE": 2}) as download_handler: with pytest.raises(DownloadCancelledError): await download_handler.download_request(request) @coroutine_test async def test_download_with_large_maxsize_via_setting( self, mockserver: MockServer ) -> None: request = Request(mockserver.url("/text", is_secure=self.is_secure)) async with self.get_dh({"DOWNLOAD_MAXSIZE": 100}) as download_handler: response = await download_handler.download_request(request) assert response.body == b"Works" @coroutine_test async def test_download_with_warnsize( self, caplog: pytest.LogCaptureFixture, mockserver: MockServer ) -> None: request = Request(mockserver.url("/text", is_secure=self.is_secure)) async with self.get_dh({"DOWNLOAD_WARNSIZE": 4}) as download_handler: response = await download_handler.download_request(request) assert response.body == b"Works" assert ( "Expected to receive 5 bytes which is larger than download warn size (4)" in caplog.text ) @coroutine_test async def test_download_with_warnsize_no_content_length( self, caplog: pytest.LogCaptureFixture, mockserver: MockServer ) -> None: request = Request( mockserver.url("/delay?n=0.1", is_secure=self.is_secure), ) async with self.get_dh({"DOWNLOAD_WARNSIZE": 10}) as download_handler: response = await download_handler.download_request(request) assert response.body == b"Response delayed for 0.100 seconds\n" assert ( "Received 35 bytes which is larger than download warn size (10)" in caplog.text ) @coroutine_test async def test_download_chunked_content(self, mockserver: MockServer) -> None: request = Request(mockserver.url("/chunked", is_secure=self.is_secure)) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == b"chunked content\n" @pytest.mark.parametrize("url", ["broken", "broken-chunked"]) @coroutine_test async def test_download_cause_data_loss( self, url: str, mockserver: MockServer ) -> None: request = Request(mockserver.url(f"/{url}", is_secure=self.is_secure)) async with self.get_dh() as download_handler: with pytest.raises(ResponseDataLossError): await download_handler.download_request(request) @coroutine_test async def test_download_cause_data_loss_double_warning( self, caplog: pytest.LogCaptureFixture, mockserver: MockServer ) -> None: request = Request(mockserver.url("/broken", is_secure=self.is_secure)) async with self.get_dh() as download_handler: with pytest.raises(ResponseDataLossError): await download_handler.download_request(request) assert "Got data loss" in caplog.text caplog.clear() with pytest.raises(ResponseDataLossError): await download_handler.download_request(request) # no repeated warning assert "Got data loss" not in caplog.text @pytest.mark.parametrize("url", ["broken", "broken-chunked"]) @coroutine_test async def test_download_allow_data_loss( self, url: str, mockserver: MockServer ) -> None: request = Request( mockserver.url(f"/{url}", is_secure=self.is_secure), meta={"download_fail_on_dataloss": False}, ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.flags == ["dataloss"] @pytest.mark.parametrize("url", ["broken", "broken-chunked"]) @coroutine_test async def test_download_allow_data_loss_via_setting( self, url: str, mockserver: MockServer ) -> None: request = Request(mockserver.url(f"/{url}", is_secure=self.is_secure)) async with self.get_dh( {"DOWNLOAD_FAIL_ON_DATALOSS": False} ) as download_handler: response = await download_handler.download_request(request) assert response.flags == ["dataloss"] @coroutine_test async def test_download_conn_failed(self) -> None: # copy of TestCrawl.test_retry_conn_failed() scheme = "https" if self.is_secure else "http" request = Request(f"{scheme}://localhost:65432/") async with self.get_dh() as download_handler: with pytest.raises(DownloadConnectionRefusedError): await download_handler.download_request(request) @coroutine_test async def test_download_conn_lost(self, mockserver: MockServer) -> None: # copy of TestCrawl.test_retry_conn_lost() request = Request(mockserver.url("/drop?abort=0", is_secure=self.is_secure)) async with self.get_dh() as download_handler: with pytest.raises(ResponseDataLossError): await download_handler.download_request(request) @coroutine_test async def test_download_conn_aborted(self, mockserver: MockServer) -> None: # copy of TestCrawl.test_retry_conn_aborted() request = Request(mockserver.url("/drop?abort=1", is_secure=self.is_secure)) async with self.get_dh() as download_handler: with pytest.raises(DownloadFailedError): await download_handler.download_request(request) @pytest.mark.skipif( NON_EXISTING_RESOLVABLE, reason="Non-existing hosts are resolvable" ) @coroutine_test async def test_download_dns_error(self) -> None: # copy of TestCrawl.test_retry_dns_error() scheme = "https" if self.is_secure else "http" request = Request(f"{scheme}://dns.resolution.invalid./") async with self.get_dh() as download_handler: with pytest.raises(CannotResolveHostError): await download_handler.download_request(request) @coroutine_test async def test_protocol(self, mockserver: MockServer) -> None: request = Request( mockserver.url("/host", is_secure=self.is_secure), method="GET" ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.protocol == "HTTP/1.1" class TestHttps11Base(TestHttp11Base): is_secure = True tls_log_message = ( 'SSL connection certificate: issuer "/C=IE/O=Scrapy/CN=localhost", ' 'subject "/C=IE/O=Scrapy/CN=localhost"' ) def test_download_conn_lost(self) -> None: # type: ignore[override] # For some reason (maybe related to TLS shutdown flow, and maybe the # mockserver resource can be fixed so that this works) HTTPS clients # (not just Scrapy) hang on /drop?abort=0. pytest.skip("Unable to test on HTTPS") @coroutine_test async def test_tls_logging( self, mockserver: MockServer, caplog: pytest.LogCaptureFixture ) -> None: request = Request(mockserver.url("/text", is_secure=self.is_secure)) async with self.get_dh( {"DOWNLOADER_CLIENT_TLS_VERBOSE_LOGGING": True} ) as download_handler: with caplog.at_level("DEBUG"): response = await download_handler.download_request(request) assert response.body == b"Works" assert self.tls_log_message in caplog.text class TestSimpleHttpsBase(ABC): """Base class for special cases tested with just one simple request""" keyfile = "keys/localhost.key" certfile = "keys/localhost.crt" host = "localhost" cipher_string: str | None = None @pytest.fixture(scope="class") def simple_mockserver(self) -> Generator[SimpleMockServer]: with SimpleMockServer( self.keyfile, self.certfile, self.cipher_string ) as simple_mockserver: yield simple_mockserver @pytest.fixture(scope="class") def url(self, simple_mockserver: SimpleMockServer) -> str: # need to use self.host instead of what mockserver returns return f"https://{self.host}:{simple_mockserver.port(is_secure=True)}/file" @property @abstractmethod def download_handler_cls(self) -> type[DownloadHandlerProtocol]: raise NotImplementedError @asynccontextmanager async def get_dh(self) -> AsyncGenerator[DownloadHandlerProtocol]: if self.cipher_string is not None: settings_dict = {"DOWNLOADER_CLIENT_TLS_CIPHERS": self.cipher_string} else: settings_dict = None crawler = get_crawler(DefaultSpider, settings_dict=settings_dict) crawler.spider = crawler._create_spider() dh = build_from_crawler(self.download_handler_cls, crawler) try: yield dh finally: await dh.close() @coroutine_test async def test_download(self, url: str) -> None: request = Request(url) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.body == b"0123456789" class TestHttpsWrongHostnameBase(TestSimpleHttpsBase): # above tests use a server certificate for "localhost", # client connection to "localhost" too. # here we test that even if the server certificate is for another domain, # "www.example.com" in this case, # the tests still pass keyfile = "keys/example-com.key.pem" certfile = "keys/example-com.cert.pem" class TestHttpsInvalidDNSIdBase(TestSimpleHttpsBase): """Connect to HTTPS hosts with IP while certificate uses domain names IDs.""" host = "127.0.0.1" class TestHttpsInvalidDNSPatternBase(TestSimpleHttpsBase): """Connect to HTTPS hosts where the certificate are issued to an ip instead of a domain.""" keyfile = "keys/localhost.ip.key" certfile = "keys/localhost.ip.crt" class TestHttpsCustomCiphersBase(TestSimpleHttpsBase): cipher_string = "CAMELLIA256-SHA" class TestHttpWithCrawlerBase(ABC): @property @abstractmethod def settings_dict(self) -> dict[str, Any] | None: raise NotImplementedError is_secure = False @coroutine_test async def test_download_with_content_length(self, mockserver: MockServer) -> None: crawler = get_crawler(SingleRequestSpider, self.settings_dict) # http://localhost:8998/partial set Content-Length to 1024, use download_maxsize= 1000 to avoid # download it await maybe_deferred_to_future( crawler.crawl( seed=Request( url=mockserver.url("/partial", is_secure=self.is_secure), meta={"download_maxsize": 1000}, ) ) ) assert crawler.spider failure = crawler.spider.meta["failure"] # type: ignore[attr-defined] assert isinstance(failure.value, DownloadCancelledError) @coroutine_test async def test_download(self, mockserver: MockServer) -> None: crawler = get_crawler(SingleRequestSpider, self.settings_dict) await maybe_deferred_to_future( crawler.crawl( seed=Request(url=mockserver.url("", is_secure=self.is_secure)) ) ) assert crawler.spider failure = crawler.spider.meta.get("failure") # type: ignore[attr-defined] assert failure is None reason = crawler.spider.meta["close_reason"] # type: ignore[attr-defined] assert reason == "finished" @coroutine_test async def test_response_ssl_certificate(self, mockserver: MockServer) -> None: if not self.is_secure: pytest.skip("Only applies to HTTPS") # copy of TestCrawl.test_response_ssl_certificate() # the current test implementation can only work for Twisted-based download handlers crawler = get_crawler(SingleRequestSpider, self.settings_dict) url = mockserver.url("/echo?body=test", is_secure=self.is_secure) await crawler.crawl_async(seed=url, mockserver=mockserver) assert isinstance(crawler.spider, SingleRequestSpider) cert = crawler.spider.meta["responses"][0].certificate assert isinstance(cert, Certificate) assert cert.getSubject().commonName == b"localhost" assert cert.getIssuer().commonName == b"localhost" @coroutine_test async def test_response_ip_address(self, mockserver: MockServer) -> None: # copy of TestCrawl.test_response_ip_address() crawler = get_crawler(SingleRequestSpider, self.settings_dict) url = mockserver.url("/echo?body=test", is_secure=self.is_secure) expected_netloc, _ = urlparse(url).netloc.split(":") await crawler.crawl_async(seed=url, mockserver=mockserver) assert isinstance(crawler.spider, SingleRequestSpider) ip_address = crawler.spider.meta["responses"][0].ip_address assert isinstance(ip_address, IPv4Address) assert str(ip_address) == gethostbyname(expected_netloc) @coroutine_test async def test_bytes_received_stop_download_callback( self, mockserver: MockServer ) -> None: # copy of TestCrawl.test_bytes_received_stop_download_callback() crawler = get_crawler(BytesReceivedCallbackSpider, self.settings_dict) await crawler.crawl_async(mockserver=mockserver, is_secure=self.is_secure) assert isinstance(crawler.spider, BytesReceivedCallbackSpider) assert crawler.spider.meta.get("failure") is None assert isinstance(crawler.spider.meta["response"], Response) assert crawler.spider.meta["response"].body == crawler.spider.meta.get( "bytes_received" ) assert ( len(crawler.spider.meta["response"].body) < crawler.spider.full_response_length ) @coroutine_test async def test_bytes_received_stop_download_errback( self, mockserver: MockServer ) -> None: # copy of TestCrawl.test_bytes_received_stop_download_errback() crawler = get_crawler(BytesReceivedErrbackSpider, self.settings_dict) await crawler.crawl_async(mockserver=mockserver, is_secure=self.is_secure) assert isinstance(crawler.spider, BytesReceivedErrbackSpider) assert crawler.spider.meta.get("response") is None assert isinstance(crawler.spider.meta["failure"], Failure) assert isinstance(crawler.spider.meta["failure"].value, StopDownload) assert isinstance(crawler.spider.meta["failure"].value.response, Response) assert crawler.spider.meta[ "failure" ].value.response.body == crawler.spider.meta.get("bytes_received") assert ( len(crawler.spider.meta["failure"].value.response.body) < crawler.spider.full_response_length ) @coroutine_test async def test_headers_received_stop_download_callback( self, mockserver: MockServer ) -> None: # copy of TestCrawl.test_headers_received_stop_download_callback() crawler = get_crawler(HeadersReceivedCallbackSpider, self.settings_dict) await crawler.crawl_async(mockserver=mockserver, is_secure=self.is_secure) assert isinstance(crawler.spider, HeadersReceivedCallbackSpider) assert crawler.spider.meta.get("failure") is None assert isinstance(crawler.spider.meta["response"], Response) assert crawler.spider.meta["response"].headers == crawler.spider.meta.get( "headers_received" ) @coroutine_test async def test_headers_received_stop_download_errback( self, mockserver: MockServer ) -> None: # copy of TestCrawl.test_headers_received_stop_download_errback() crawler = get_crawler(HeadersReceivedErrbackSpider, self.settings_dict) await crawler.crawl_async(mockserver=mockserver, is_secure=self.is_secure) assert isinstance(crawler.spider, HeadersReceivedErrbackSpider) assert crawler.spider.meta.get("response") is None assert isinstance(crawler.spider.meta["failure"], Failure) assert isinstance(crawler.spider.meta["failure"].value, StopDownload) assert isinstance(crawler.spider.meta["failure"].value.response, Response) assert crawler.spider.meta[ "failure" ].value.response.headers == crawler.spider.meta.get("headers_received") class TestHttpProxyBase(ABC): is_secure = False expected_http_proxy_request_body = b"http://example.com" @property @abstractmethod def download_handler_cls(self) -> type[DownloadHandlerProtocol]: raise NotImplementedError @pytest.fixture(scope="session") def proxy_mockserver(self) -> Generator[ProxyEchoMockServer]: with ProxyEchoMockServer() as proxy: yield proxy @asynccontextmanager async def get_dh(self) -> AsyncGenerator[DownloadHandlerProtocol]: crawler = get_crawler(DefaultSpider) crawler.spider = crawler._create_spider() dh = build_from_crawler(self.download_handler_cls, crawler) try: yield dh finally: await dh.close() @coroutine_test async def test_download_with_proxy( self, proxy_mockserver: ProxyEchoMockServer ) -> None: http_proxy = proxy_mockserver.url("", is_secure=self.is_secure) request = Request("http://example.com", meta={"proxy": http_proxy}) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == 200 assert response.url == request.url assert response.body == self.expected_http_proxy_request_body @coroutine_test async def test_download_without_proxy( self, proxy_mockserver: ProxyEchoMockServer ) -> None: request = Request( proxy_mockserver.url("/path/to/resource", is_secure=self.is_secure) ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == 200 assert response.url == request.url assert response.body == b"/path/to/resource" @coroutine_test async def test_download_with_proxy_https_timeout( self, proxy_mockserver: ProxyEchoMockServer ) -> None: if NON_EXISTING_RESOLVABLE: pytest.skip("Non-existing hosts are resolvable") http_proxy = proxy_mockserver.url("", is_secure=self.is_secure) domain = "https://no-such-domain.nosuch" request = Request(domain, meta={"proxy": http_proxy, "download_timeout": 0.2}) async with self.get_dh() as download_handler: with pytest.raises(DownloadTimeoutError) as exc_info: await download_handler.download_request(request) assert domain in str(exc_info.value) @coroutine_test async def test_download_with_proxy_without_http_scheme( self, proxy_mockserver: ProxyEchoMockServer ) -> None: http_proxy = f"{proxy_mockserver.host}:{proxy_mockserver.port()}" request = Request("http://example.com", meta={"proxy": http_proxy}) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.status == 200 assert response.url == request.url assert response.body == self.expected_http_proxy_request_body
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_downloader_handlers_http_base.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 875, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/multi_parallel.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.defer import deferred_f_from_coro_f from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" async def start(self): return yield @deferred_f_from_coro_f async def main(reactor): configure_logging() runner = AsyncCrawlerRunner() runner.crawl(NoRequestsSpider) runner.crawl(NoRequestsSpider) await runner.join() install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/multi_parallel.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/multi_seq.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.defer import deferred_f_from_coro_f from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" async def start(self): return yield @deferred_f_from_coro_f async def main(reactor): configure_logging() runner = AsyncCrawlerRunner() await runner.crawl(NoRequestsSpider) await runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/multi_seq.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/simple.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.defer import deferred_f_from_coro_f from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor from scrapy.utils.reactorless import is_reactorless class NoRequestsSpider(Spider): name = "no_request" async def start(self): self.logger.info(f"is_reactorless(): {is_reactorless()}") return yield @deferred_f_from_coro_f async def main(reactor): configure_logging() runner = AsyncCrawlerRunner() await runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/simple.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/AsyncCrawlerRunner/simple_default_reactor.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import AsyncCrawlerRunner from scrapy.utils.defer import deferred_f_from_coro_f from scrapy.utils.log import configure_logging class NoRequestsSpider(Spider): name = "no_request" async def start(self): return yield @deferred_f_from_coro_f async def main(reactor): configure_logging() runner = AsyncCrawlerRunner() await runner.crawl(NoRequestsSpider) react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/AsyncCrawlerRunner/simple_default_reactor.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/CrawlerRunner/explicit_default_reactor.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging class NoRequestsSpider(Spider): name = "no_request" custom_settings = { "TWISTED_REACTOR": None, } async def start(self): return yield def main(reactor): configure_logging( {"LOG_FORMAT": "%(levelname)s: %(message)s", "LOG_LEVEL": "DEBUG"} ) runner = CrawlerRunner() return runner.crawl(NoRequestsSpider) react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/CrawlerRunner/explicit_default_reactor.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/CrawlerRunner/multi_parallel.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" async def start(self): return yield def main(reactor): configure_logging() runner = CrawlerRunner() runner.crawl(NoRequestsSpider) runner.crawl(NoRequestsSpider) return runner.join() install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/CrawlerRunner/multi_parallel.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/CrawlerRunner/multi_seq.py
from twisted.internet.defer import inlineCallbacks from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor class NoRequestsSpider(Spider): name = "no_request" async def start(self): return yield @inlineCallbacks def main(reactor): configure_logging() runner = CrawlerRunner() yield runner.crawl(NoRequestsSpider) yield runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/CrawlerRunner/multi_seq.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/CrawlerRunner/simple.py
from twisted.internet.task import react from scrapy import Spider from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from scrapy.utils.reactor import install_reactor from scrapy.utils.reactorless import is_reactorless class NoRequestsSpider(Spider): name = "no_request" async def start(self): self.logger.info(f"is_reactorless(): {is_reactorless()}") return yield def main(reactor): configure_logging() runner = CrawlerRunner() return runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/CrawlerRunner/simple.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:scrapy/spidermiddlewares/start.py
from __future__ import annotations from typing import TYPE_CHECKING from .base import BaseSpiderMiddleware if TYPE_CHECKING: from scrapy.http import Request from scrapy.http.response import Response class StartSpiderMiddleware(BaseSpiderMiddleware): """Set :reqmeta:`is_start_request`. .. reqmeta:: is_start_request is_start_request ---------------- :attr:`~scrapy.Request.meta` key that is set to ``True`` in :ref:`start requests <start-requests>`, allowing you to tell start requests apart from other requests, e.g. in :ref:`downloader middlewares <topics-downloader-middleware>`. """ def get_processed_request( self, request: Request, response: Response | None ) -> Request | None: if response is None: request.meta.setdefault("is_start_request", True) return request
{ "repo_id": "scrapy/scrapy", "file_path": "scrapy/spidermiddlewares/start.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
scrapy/scrapy:tests/test_engine_loop.py
from __future__ import annotations from collections import deque from logging import ERROR from typing import TYPE_CHECKING import pytest from twisted.internet.defer import Deferred from scrapy import Request, Spider, signals from scrapy.utils.defer import maybe_deferred_to_future from scrapy.utils.test import get_crawler from tests.mockserver.http import MockServer from tests.test_scheduler import MemoryScheduler from tests.utils.decorators import coroutine_test if TYPE_CHECKING: from scrapy.http import Response async def sleep(seconds: float = 0.001) -> None: from twisted.internet import reactor deferred: Deferred[None] = Deferred() reactor.callLater(seconds, deferred.callback, None) await maybe_deferred_to_future(deferred) class TestMain: @pytest.mark.requires_reactor # TODO @coroutine_test async def test_sleep(self): """Neither asynchronous sleeps on Spider.start() nor the equivalent on the scheduler (returning no requests while also returning True from the has_pending_requests() method) should cause the spider to miss the processing of any later requests.""" seconds = 2 class TestSpider(Spider): name = "test" async def start(self): from twisted.internet import reactor yield Request("data:,a") await sleep(seconds) self.crawler.engine._slot.scheduler.pause() self.crawler.engine._slot.scheduler.enqueue_request(Request("data:,b")) # During this time, the scheduler reports having requests but # returns None. await sleep(seconds) self.crawler.engine._slot.scheduler.unpause() # The scheduler request is processed. await sleep(seconds) yield Request("data:,c") await sleep(seconds) self.crawler.engine._slot.scheduler.pause() self.crawler.engine._slot.scheduler.enqueue_request(Request("data:,d")) # The last start request is processed during the time until the # delayed call below, proving that the start iteration can # finish before a scheduler “sleep” without causing the # scheduler to finish. reactor.callLater(seconds, self.crawler.engine._slot.scheduler.unpause) def parse(self, response): pass actual_urls = [] def track_url(request, spider): actual_urls.append(request.url) settings = {"SCHEDULER": MemoryScheduler} crawler = get_crawler(TestSpider, settings_dict=settings) crawler.signals.connect(track_url, signals.request_reached_downloader) await crawler.crawl_async() assert crawler.stats.get_value("finish_reason") == "finished" expected_urls = ["data:,a", "data:,b", "data:,c", "data:,d"] assert actual_urls == expected_urls, f"{actual_urls=} != {expected_urls=}" @coroutine_test async def test_close_during_start_iteration( self, caplog: pytest.LogCaptureFixture ) -> None: class TestSpider(Spider): name = "test" async def start(self): assert self.crawler.engine is not None await self.crawler.engine.close_async() yield Request("data:,a") def parse(self, response): pass actual_urls = [] def track_url(request, spider): actual_urls.append(request.url) settings = {"SCHEDULER": MemoryScheduler} crawler = get_crawler(TestSpider, settings_dict=settings) crawler.signals.connect(track_url, signals.request_reached_downloader) caplog.clear() with caplog.at_level(ERROR): await crawler.crawl_async() assert not caplog.records assert crawler.stats assert crawler.stats.get_value("finish_reason") == "shutdown" assert not actual_urls class TestRequestSendOrder: seconds = 0.1 # increase if flaky @classmethod def setup_class(cls): cls.mockserver = MockServer() cls.mockserver.__enter__() @classmethod def teardown_class(cls): cls.mockserver.__exit__(None, None, None) # increase if flaky def request(self, num, response_seconds, download_slots, priority=0): url = self.mockserver.url(f"/delay?n={response_seconds}&{num}") meta = {"download_slot": str(num % download_slots)} return Request(url, meta=meta, priority=priority) def get_num(self, request_or_response: Request | Response): return int(request_or_response.url.rsplit("&", maxsplit=1)[1]) async def _test_request_order( self, start_nums, cb_nums=None, settings=None, response_seconds=None, download_slots=1, start_fn=None, parse_fn=None, ): cb_nums = cb_nums or [] settings = settings or {} response_seconds = response_seconds or self.seconds cb_requests = deque( [self.request(num, response_seconds, download_slots) for num in cb_nums] ) if start_fn is None: async def start_fn(spider): for num in start_nums: yield self.request(num, response_seconds, download_slots) if parse_fn is None: def parse_fn(spider, response): while cb_requests: yield cb_requests.popleft() class TestSpider(Spider): name = "test" start = start_fn parse = parse_fn actual_nums = [] def track_num(request, spider): actual_nums.append(self.get_num(request)) crawler = get_crawler(TestSpider, settings_dict=settings) crawler.signals.connect(track_num, signals.request_reached_downloader) await crawler.crawl_async() assert crawler.stats.get_value("finish_reason") == "finished" expected_nums = sorted(start_nums + cb_nums) assert actual_nums == expected_nums, f"{actual_nums=} != {expected_nums=}" @coroutine_test async def test_default(self): """By default, callback requests take priority over start requests and are sent in order. Priority matters, but given the same priority, a callback request takes precedence.""" nums = [1, 2, 3, 4, 5, 6] response_seconds = 0 download_slots = 1 def _request(num, priority=0): return self.request( num, response_seconds, download_slots, priority=priority ) async def start(spider): # The first CONCURRENT_REQUESTS start requests are sent # immediately. yield _request(1) for request in ( _request(2, priority=1), _request(5), ): spider.crawler.engine._slot.scheduler.enqueue_request(request) yield _request(6) yield _request(3, priority=1) yield _request(4, priority=1) def parse(spider, response): return yield await self._test_request_order( start_nums=nums, settings={"CONCURRENT_REQUESTS": 1}, response_seconds=response_seconds, start_fn=start, parse_fn=parse, ) @coroutine_test async def test_lifo_start(self): """Changing the queues of start requests to LIFO, matching the queues of non-start requests, does not cause all requests to be stored in the same queue objects, it only affects the order of start requests.""" nums = [1, 2, 3, 4, 5, 6] response_seconds = 0 download_slots = 1 def _request(num, priority=0): return self.request( num, response_seconds, download_slots, priority=priority ) async def start(spider): # The first CONCURRENT_REQUESTS start requests are sent # immediately. yield _request(1) for request in ( _request(2, priority=1), _request(5), ): spider.crawler.engine._slot.scheduler.enqueue_request(request) yield _request(6) yield _request(4, priority=1) yield _request(3, priority=1) def parse(spider, response): return yield await self._test_request_order( start_nums=nums, settings={ "CONCURRENT_REQUESTS": 1, "SCHEDULER_START_MEMORY_QUEUE": "scrapy.squeues.LifoMemoryQueue", }, response_seconds=response_seconds, start_fn=start, parse_fn=parse, ) @coroutine_test async def test_shared_queues(self): """If SCHEDULER_START_*_QUEUE is falsy, start requests and other requests share the same queue, i.e. start requests are not priorized over other requests if their priority matches.""" nums = list(range(1, 14)) response_seconds = 0 download_slots = 1 def _request(num, priority=0): return self.request( num, response_seconds, download_slots, priority=priority ) async def start(spider): # The first CONCURRENT_REQUESTS start requests are sent # immediately. yield _request(1) # Below, priority 1 requests are sent first, and requests are sent # in LIFO order. for request in ( _request(7, priority=1), _request(6, priority=1), _request(13), _request(12), ): spider.crawler.engine._slot.scheduler.enqueue_request(request) yield _request(11) yield _request(10) yield _request(5, priority=1) yield _request(4, priority=1) for request in ( _request(3, priority=1), _request(2, priority=1), _request(9), _request(8), ): spider.crawler.engine._slot.scheduler.enqueue_request(request) def parse(spider, response): return yield await self._test_request_order( start_nums=nums, settings={ "CONCURRENT_REQUESTS": 1, "SCHEDULER_START_MEMORY_QUEUE": None, }, response_seconds=response_seconds, start_fn=start, parse_fn=parse, ) # Examples from the “Start requests” section of the documentation about # spiders. @coroutine_test async def test_lazy(self): start_nums = [1, 2, 4] cb_nums = [3] response_seconds = self.seconds * 2**1 # increase if flaky download_slots = 1 async def start(spider): for num in start_nums: if spider.crawler.engine.needs_backout(): await spider.crawler.signals.wait_for(signals.scheduler_empty) request = self.request(num, response_seconds, download_slots) yield request await self._test_request_order( start_nums=start_nums, cb_nums=cb_nums, settings={ "CONCURRENT_REQUESTS": 1, }, response_seconds=response_seconds, start_fn=start, )
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_engine_loop.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 283, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_spider_start.py
from __future__ import annotations import re import warnings from asyncio import sleep from typing import Any import pytest from testfixtures import LogCapture from scrapy import Spider, signals from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.defer import maybe_deferred_to_future from scrapy.utils.test import get_crawler from .utils import twisted_sleep from .utils.decorators import coroutine_test SLEEP_SECONDS = 0.1 ITEM_A = {"id": "a"} ITEM_B = {"id": "b"} class TestMain: async def _test_spider( self, spider: type[Spider], expected_items: list[Any] | None = None ) -> None: actual_items = [] expected_items = [] if expected_items is None else expected_items def track_item(item, response, spider): actual_items.append(item) crawler = get_crawler(spider) crawler.signals.connect(track_item, signals.item_scraped) await crawler.crawl_async() assert crawler.stats assert crawler.stats.get_value("finish_reason") == "finished" assert actual_items == expected_items @coroutine_test async def test_start_urls(self): class TestSpider(Spider): name = "test" start_urls = ["data:,"] async def parse(self, response): yield ITEM_A with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_spider(TestSpider, [ITEM_A]) @coroutine_test async def test_start(self): class TestSpider(Spider): name = "test" async def start(self): yield ITEM_A with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_spider(TestSpider, [ITEM_A]) @coroutine_test async def test_start_subclass(self): class BaseSpider(Spider): async def start(self): yield ITEM_A class TestSpider(BaseSpider): name = "test" with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_spider(TestSpider, [ITEM_A]) @coroutine_test async def test_deprecated(self): class TestSpider(Spider): name = "test" def start_requests(self): yield ITEM_A with pytest.warns(ScrapyDeprecationWarning): await self._test_spider(TestSpider, [ITEM_A]) @coroutine_test async def test_deprecated_subclass(self): class BaseSpider(Spider): def start_requests(self): yield ITEM_A class TestSpider(BaseSpider): name = "test" # The warning must be about the base class and not the subclass. with pytest.warns(ScrapyDeprecationWarning, match="BaseSpider"): await self._test_spider(TestSpider, [ITEM_A]) @coroutine_test async def test_universal(self): class TestSpider(Spider): name = "test" async def start(self): yield ITEM_A def start_requests(self): yield ITEM_B with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_spider(TestSpider, [ITEM_A]) @coroutine_test async def test_universal_subclass(self): class BaseSpider(Spider): async def start(self): yield ITEM_A def start_requests(self): yield ITEM_B class TestSpider(BaseSpider): name = "test" with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_spider(TestSpider, [ITEM_A]) @coroutine_test async def test_start_deprecated_super(self): class TestSpider(Spider): name = "test" async def start(self): for item_or_request in super().start_requests(): yield item_or_request msg = "use Spider.start() instead" with pytest.warns(ScrapyDeprecationWarning, match=re.escape(msg)) as ws: await self._test_spider(TestSpider, []) for w in ws: if isinstance(w.message, ScrapyDeprecationWarning) and msg in str( w.message ): assert w.filename.endswith("test_spider_start.py") break async def _test_start(self, start_, expected_items=None): class TestSpider(Spider): name = "test" start = start_ await self._test_spider(TestSpider, expected_items) @pytest.mark.only_asyncio @coroutine_test async def test_asyncio_delayed(self): async def start(spider): await sleep(SLEEP_SECONDS) yield ITEM_A await self._test_start(start, [ITEM_A]) @pytest.mark.requires_reactor # needs a reactor for twisted_sleep() @coroutine_test async def test_twisted_delayed(self): async def start(spider): await maybe_deferred_to_future(twisted_sleep(SLEEP_SECONDS)) yield ITEM_A await self._test_start(start, [ITEM_A]) # Exceptions @coroutine_test async def test_deprecated_non_generator_exception(self): class TestSpider(Spider): name = "test" def start_requests(self): raise RuntimeError with ( LogCapture() as log, pytest.warns( ScrapyDeprecationWarning, match=r"defines the deprecated start_requests\(\) method", ), ): await self._test_spider(TestSpider, []) assert "in start_requests\n raise RuntimeError" in str(log)
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_spider_start.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 151, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_spidermiddleware_process_start.py
import warnings from asyncio import sleep import pytest from scrapy import Spider, signals from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.defer import maybe_deferred_to_future from scrapy.utils.test import get_crawler from tests.test_spider_start import SLEEP_SECONDS from .utils import twisted_sleep from .utils.decorators import coroutine_test ITEM_A = {"id": "a"} ITEM_B = {"id": "b"} ITEM_C = {"id": "c"} ITEM_D = {"id": "d"} class AsyncioSleepSpiderMiddleware: async def process_start(self, start): await sleep(SLEEP_SECONDS) async for item_or_request in start: yield item_or_request class NoOpSpiderMiddleware: async def process_start(self, start): async for item_or_request in start: yield item_or_request class TwistedSleepSpiderMiddleware: async def process_start(self, start): await maybe_deferred_to_future(twisted_sleep(SLEEP_SECONDS)) async for item_or_request in start: yield item_or_request class UniversalSpiderMiddleware: async def process_start(self, start): async for item_or_request in start: yield item_or_request def process_start_requests(self, start_requests, spider): raise NotImplementedError # Spiders and spider middlewares for TestMain._test_wrap class ModernWrapSpider(Spider): name = "test" async def start(self): yield ITEM_B class ModernWrapSpiderSubclass(ModernWrapSpider): name = "test" class UniversalWrapSpider(Spider): name = "test" async def start(self): yield ITEM_B def start_requests(self): yield ITEM_D class DeprecatedWrapSpider(Spider): name = "test" def start_requests(self): yield ITEM_B class ModernWrapSpiderMiddleware: async def process_start(self, start): yield ITEM_A async for item_or_request in start: yield item_or_request yield ITEM_C class UniversalWrapSpiderMiddleware: async def process_start(self, start): yield ITEM_A async for item_or_request in start: yield item_or_request yield ITEM_C def process_start_requests(self, start, spider): yield ITEM_A yield from start yield ITEM_C class DeprecatedWrapSpiderMiddleware: def process_start_requests(self, start, spider): yield ITEM_A yield from start yield ITEM_C class TestMain: async def _test(self, spider_middlewares, spider_cls, expected_items): actual_items = [] def track_item(item, response, spider): actual_items.append(item) settings = { "SPIDER_MIDDLEWARES": {cls: n for n, cls in enumerate(spider_middlewares)}, } crawler = get_crawler(spider_cls, settings_dict=settings) crawler.signals.connect(track_item, signals.item_scraped) await crawler.crawl_async() assert crawler.stats.get_value("finish_reason") == "finished" assert actual_items == expected_items, f"{actual_items=} != {expected_items=}" async def _test_wrap(self, spider_middleware, spider_cls, expected_items=None): expected_items = expected_items or [ITEM_A, ITEM_B, ITEM_C] await self._test([spider_middleware], spider_cls, expected_items) async def _test_douple_wrap(self, smw1, smw2, spider_cls, expected_items=None): expected_items = expected_items or [ITEM_A, ITEM_A, ITEM_B, ITEM_C, ITEM_C] await self._test([smw1, smw2], spider_cls, expected_items) @coroutine_test async def test_modern_mw_modern_spider(self): with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_wrap(ModernWrapSpiderMiddleware, ModernWrapSpider) @coroutine_test async def test_modern_mw_universal_spider(self): with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_wrap(ModernWrapSpiderMiddleware, UniversalWrapSpider) @coroutine_test async def test_modern_mw_deprecated_spider(self): with pytest.warns( ScrapyDeprecationWarning, match=r"deprecated start_requests\(\)" ): await self._test_wrap(ModernWrapSpiderMiddleware, DeprecatedWrapSpider) @coroutine_test async def test_universal_mw_modern_spider(self): with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_wrap(UniversalWrapSpiderMiddleware, ModernWrapSpider) @coroutine_test async def test_universal_mw_universal_spider(self): with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_wrap(UniversalWrapSpiderMiddleware, UniversalWrapSpider) @coroutine_test async def test_universal_mw_deprecated_spider(self): with pytest.warns( ScrapyDeprecationWarning, match=r"deprecated start_requests\(\)" ): await self._test_wrap(UniversalWrapSpiderMiddleware, DeprecatedWrapSpider) @coroutine_test async def test_deprecated_mw_modern_spider(self): with ( pytest.warns( ScrapyDeprecationWarning, match=r"deprecated process_start_requests\(\)" ), pytest.raises( ValueError, match=r"only compatible with \(deprecated\) spiders" ), ): await self._test_wrap(DeprecatedWrapSpiderMiddleware, ModernWrapSpider) @coroutine_test async def test_deprecated_mw_modern_spider_subclass(self): with ( pytest.warns( ScrapyDeprecationWarning, match=r"deprecated process_start_requests\(\)" ), pytest.raises( ValueError, match=r"^\S+?\.ModernWrapSpider \(inherited by \S+?.ModernWrapSpiderSubclass\) .*? only compatible with \(deprecated\) spiders", ), ): await self._test_wrap( DeprecatedWrapSpiderMiddleware, ModernWrapSpiderSubclass ) @coroutine_test async def test_deprecated_mw_universal_spider(self): with pytest.warns( ScrapyDeprecationWarning, match=r"deprecated process_start_requests\(\)" ): await self._test_wrap( DeprecatedWrapSpiderMiddleware, UniversalWrapSpider, [ITEM_A, ITEM_D, ITEM_C], ) @coroutine_test async def test_deprecated_mw_deprecated_spider(self): with ( pytest.warns( ScrapyDeprecationWarning, match=r"deprecated process_start_requests\(\)" ), pytest.warns( ScrapyDeprecationWarning, match=r"deprecated start_requests\(\)" ), ): await self._test_wrap(DeprecatedWrapSpiderMiddleware, DeprecatedWrapSpider) @coroutine_test async def test_modern_mw_universal_mw_modern_spider(self): with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_douple_wrap( ModernWrapSpiderMiddleware, UniversalWrapSpiderMiddleware, ModernWrapSpider, ) @coroutine_test async def test_modern_mw_deprecated_mw_modern_spider(self): with pytest.raises(ValueError, match=r"trying to combine spider middlewares"): await self._test_douple_wrap( ModernWrapSpiderMiddleware, DeprecatedWrapSpiderMiddleware, ModernWrapSpider, ) @coroutine_test async def test_universal_mw_deprecated_mw_modern_spider(self): with ( pytest.warns( ScrapyDeprecationWarning, match=r"deprecated process_start_requests\(\)" ), pytest.raises( ValueError, match=r"only compatible with \(deprecated\) spiders" ), ): await self._test_douple_wrap( UniversalWrapSpiderMiddleware, DeprecatedWrapSpiderMiddleware, ModernWrapSpider, ) @coroutine_test async def test_modern_mw_universal_mw_universal_spider(self): with warnings.catch_warnings(): warnings.simplefilter("error") await self._test_douple_wrap( ModernWrapSpiderMiddleware, UniversalWrapSpiderMiddleware, UniversalWrapSpider, ) @coroutine_test async def test_modern_mw_deprecated_mw_universal_spider(self): with pytest.raises(ValueError, match=r"trying to combine spider middlewares"): await self._test_douple_wrap( ModernWrapSpiderMiddleware, DeprecatedWrapSpiderMiddleware, UniversalWrapSpider, ) @coroutine_test async def test_universal_mw_deprecated_mw_universal_spider(self): with pytest.warns( ScrapyDeprecationWarning, match=r"deprecated process_start_requests\(\)" ): await self._test_douple_wrap( UniversalWrapSpiderMiddleware, DeprecatedWrapSpiderMiddleware, UniversalWrapSpider, [ITEM_A, ITEM_A, ITEM_D, ITEM_C, ITEM_C], ) @coroutine_test async def test_modern_mw_universal_mw_deprecated_spider(self): with pytest.warns( ScrapyDeprecationWarning, match=r"deprecated start_requests\(\)" ): await self._test_douple_wrap( ModernWrapSpiderMiddleware, UniversalWrapSpiderMiddleware, DeprecatedWrapSpider, ) @coroutine_test async def test_modern_mw_deprecated_mw_deprecated_spider(self): with pytest.raises(ValueError, match=r"trying to combine spider middlewares"): await self._test_douple_wrap( ModernWrapSpiderMiddleware, DeprecatedWrapSpiderMiddleware, DeprecatedWrapSpider, ) @coroutine_test async def test_universal_mw_deprecated_mw_deprecated_spider(self): with ( pytest.warns( ScrapyDeprecationWarning, match=r"deprecated process_start_requests\(\)" ), pytest.warns( ScrapyDeprecationWarning, match=r"deprecated start_requests\(\)" ), ): await self._test_douple_wrap( UniversalWrapSpiderMiddleware, DeprecatedWrapSpiderMiddleware, DeprecatedWrapSpider, ) async def _test_sleep(self, spider_middlewares): class TestSpider(Spider): name = "test" async def start(self): yield ITEM_A await self._test(spider_middlewares, TestSpider, [ITEM_A]) @pytest.mark.only_asyncio @coroutine_test async def test_asyncio_sleep_single(self): await self._test_sleep([AsyncioSleepSpiderMiddleware]) @pytest.mark.only_asyncio @coroutine_test async def test_asyncio_sleep_multiple(self): await self._test_sleep( [NoOpSpiderMiddleware, AsyncioSleepSpiderMiddleware, NoOpSpiderMiddleware] ) @pytest.mark.requires_reactor @coroutine_test async def test_twisted_sleep_single(self): await self._test_sleep([TwistedSleepSpiderMiddleware]) @pytest.mark.requires_reactor @coroutine_test async def test_twisted_sleep_multiple(self): await self._test_sleep( [NoOpSpiderMiddleware, TwistedSleepSpiderMiddleware, NoOpSpiderMiddleware] )
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_spidermiddleware_process_start.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 288, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
scrapy/scrapy:tests/test_spidermiddleware_start.py
from scrapy.http import Request from scrapy.spidermiddlewares.start import StartSpiderMiddleware from scrapy.spiders import Spider from scrapy.utils.misc import build_from_crawler from scrapy.utils.test import get_crawler from tests.utils.decorators import coroutine_test class TestMiddleware: @coroutine_test async def test_async(self): crawler = get_crawler(Spider) mw = build_from_crawler(StartSpiderMiddleware, crawler) async def start(): yield Request("data:,1") yield Request("data:,2", meta={"is_start_request": True}) yield Request("data:,2", meta={"is_start_request": False}) yield Request("data:,2", meta={"is_start_request": "foo"}) result = [ request.meta["is_start_request"] async for request in mw.process_start(start()) ] assert result == [True, True, False, "foo"] @coroutine_test async def test_sync(self): crawler = get_crawler(Spider) mw = build_from_crawler(StartSpiderMiddleware, crawler) def start(): yield Request("data:,1") yield Request("data:,2", meta={"is_start_request": True}) yield Request("data:,2", meta={"is_start_request": False}) yield Request("data:,2", meta={"is_start_request": "foo"}) result = [ request.meta["is_start_request"] for request in mw.process_start_requests(start(), Spider("test")) ] assert result == [True, True, False, "foo"]
{ "repo_id": "scrapy/scrapy", "file_path": "tests/test_spidermiddleware_start.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
serengil/deepface:deepface/modules/database/inventory.py
# built-in dependencies from typing import TypedDict, Type, Dict # project dependencies from deepface.modules.database.types import Database from deepface.modules.database.postgres import PostgresClient from deepface.modules.database.pgvector import PGVectorClient from deepface.modules.database.mongo import MongoDbClient as MongoClient from deepface.modules.database.weaviate import WeaviateClient from deepface.modules.database.neo4j import Neo4jClient from deepface.modules.database.pinecone import PineconeClient class DatabaseSpec(TypedDict): is_vector_db: bool connection_string: str client: Type["Database"] database_inventory: Dict[str, DatabaseSpec] = { "postgres": { "is_vector_db": False, "connection_string": "DEEPFACE_POSTGRES_URI", "client": PostgresClient, }, "mongo": { "is_vector_db": False, "connection_string": "DEEPFACE_MONGO_URI", "client": MongoClient, }, "weaviate": { "is_vector_db": True, "connection_string": "DEEPFACE_WEAVIATE_URI", "client": WeaviateClient, }, "neo4j": { "is_vector_db": True, "connection_string": "DEEPFACE_NEO4J_URI", "client": Neo4jClient, }, "pgvector": { "is_vector_db": True, "connection_string": "DEEPFACE_POSTGRES_URI", "client": PGVectorClient, }, "pinecone": { "is_vector_db": True, "connection_string": "DEEPFACE_PINECONE_API_KEY", "client": PineconeClient, }, }
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/database/inventory.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
serengil/deepface:deepface/modules/database/pinecone.py
# built-in dependencies import os import json import hashlib import struct import math from typing import Any, Dict, Optional, List, Union # project dependencies from deepface.modules.database.types import Database from deepface.modules.modeling import build_model from deepface.commons.logger import Logger logger = Logger() class PineconeClient(Database): """ Pinecone client for storing and retrieving face embeddings and indices. """ def __init__( self, connection_details: Optional[Union[str, Dict[str, Any]]] = None, connection: Any = None, ): try: from pinecone import Pinecone, ServerlessSpec except (ModuleNotFoundError, ImportError) as e: raise ValueError( "pinecone is an optional dependency. Install with 'pip install pinecone'" ) from e self.pinecone = Pinecone self.serverless_spec = ServerlessSpec if connection is not None: self.client = connection else: self.conn_details = connection_details or os.environ.get("DEEPFACE_PINECONE_API_KEY") if not isinstance(self.conn_details, str): raise ValueError( "Pinecone api key must be provided as a string in connection_details " "or via DEEPFACE_PINECONE_API_KEY environment variable." ) self.client = self.pinecone(api_key=self.conn_details) def initialize_database(self, **kwargs: Any) -> None: """ Ensure Pinecone index exists. """ model_name = kwargs.get("model_name", "VGG-Face") detector_backend = kwargs.get("detector_backend", "opencv") aligned = kwargs.get("aligned", True) l2_normalized = kwargs.get("l2_normalized", False) index_name = self.__generate_index_name( model_name, detector_backend, aligned, l2_normalized ) if self.client.has_index(index_name): logger.debug(f"Pinecone index '{index_name}' already exists.") return model = build_model(task="facial_recognition", model_name=model_name) dimensions = model.output_shape similarity_function = "cosine" if l2_normalized else "euclidean" self.client.create_index( name=index_name, dimension=dimensions, metric=similarity_function, spec=self.serverless_spec( cloud=os.getenv("DEEPFACE_PINECONE_CLOUD", "aws"), region=os.getenv("DEEPFACE_PINECONE_REGION", "us-east-1"), ), ) logger.debug(f"Created Pinecone index '{index_name}' with dimension {dimensions}.") def insert_embeddings(self, embeddings: List[Dict[str, Any]], batch_size: int = 100) -> int: """ Insert embeddings into Pinecone database in batches. """ if not embeddings: raise ValueError("No embeddings to insert.") self.initialize_database( model_name=embeddings[0]["model_name"], detector_backend=embeddings[0]["detector_backend"], aligned=embeddings[0]["aligned"], l2_normalized=embeddings[0]["l2_normalized"], ) index_name = self.__generate_index_name( embeddings[0]["model_name"], embeddings[0]["detector_backend"], embeddings[0]["aligned"], embeddings[0]["l2_normalized"], ) # connect to the index index = self.client.Index(index_name) total = 0 for i in range(0, len(embeddings), batch_size): batch = embeddings[i : i + batch_size] vectors = [] for e in batch: face_json = json.dumps(e["face"].tolist()) face_hash = hashlib.sha256(face_json.encode()).hexdigest() embedding_bytes = struct.pack(f'{len(e["embedding"])}d', *e["embedding"]) embedding_hash = hashlib.sha256(embedding_bytes).hexdigest() vectors.append( { "id": f"{face_hash}:{embedding_hash}", "values": e["embedding"], "metadata": { "img_name": e["img_name"], # "face": e["face"].tolist(), # "face_shape": list(e["face"].shape), }, } ) index.upsert(vectors=vectors) total += len(vectors) return total def search_by_vector( self, vector: List[float], model_name: str = "VGG-Face", detector_backend: str = "opencv", aligned: bool = True, l2_normalized: bool = False, limit: int = 10, ) -> List[Dict[str, Any]]: """ ANN search using the main vector (embedding). """ out: List[Dict[str, Any]] = [] self.initialize_database( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) index_name = self.__generate_index_name( model_name, detector_backend, aligned, l2_normalized ) index = self.client.Index(index_name) results = index.query( vector=vector, top_k=limit, include_metadata=True, include_values=False, ) if not results.matches: return out for res in results.matches: score = float(res.score) if l2_normalized: distance = 1 - score else: distance = math.sqrt(max(score, 0.0)) out.append( { "id": res.id, "distance": distance, "img_name": res.metadata.get("img_name"), } ) return out def fetch_all_embeddings( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, batch_size: int = 1000, ) -> List[Dict[str, Any]]: """ Fetch all embeddings from Pinecone database in batches. """ out: List[Dict[str, Any]] = [] self.initialize_database( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) index_name = self.__generate_index_name( model_name, detector_backend, aligned, l2_normalized ) index = self.client.Index(index_name) # Fetch all IDs ids: List[str] = [] for _id in index.list(): ids.extend(_id) for i in range(0, len(ids), batch_size): batch_ids = ids[i : i + batch_size] fetched = index.fetch(ids=batch_ids) for _id, v in fetched.get("vectors", {}).items(): md = v.get("metadata") or {} out.append( { "id": _id, "embedding": v.get("values"), "img_name": md.get("img_name"), "face_hash": md.get("face_hash"), "embedding_hash": md.get("embedding_hash"), } ) return out def close(self) -> None: """Pinecone client does not require explicit closure""" return @staticmethod def __generate_index_name( model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, ) -> str: """ Generate Pinecone index name based on parameters. """ index_name_attributes = [ "embeddings", model_name.replace("-", ""), detector_backend, "Aligned" if aligned else "Unaligned", "Norm" if l2_normalized else "Raw", ] return "-".join(index_name_attributes).lower()
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/database/pinecone.py", "license": "MIT License", "lines": 216, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
serengil/deepface:deepface/modules/database/pgvector.py
# built-in dependencies import os import json import struct import hashlib from typing import Any, Dict, Optional, List, Union # 3rd party dependencies import numpy as np # project dependencies from deepface.modules.modeling import build_model from deepface.modules.database.types import Database from deepface.modules.exceptions import DuplicateEntryError from deepface.commons.logger import Logger logger = Logger() _SCHEMA_CHECKED: Dict[str, bool] = {} # pylint: disable=too-many-positional-arguments class PGVectorClient(Database): def __init__( self, connection_details: Optional[Union[Dict[str, Any], str]] = None, connection: Any = None, ) -> None: # Import here to avoid mandatory dependency try: import psycopg from psycopg import errors except (ModuleNotFoundError, ImportError) as e: raise ValueError( "psycopg is an optional dependency, ensure the library is installed." "Please install using 'pip install \"psycopg[binary]\"' " ) from e try: from pgvector.psycopg import register_vector except (ModuleNotFoundError, ImportError) as e: raise ValueError( "pgvector is an optional dependency, ensure the library is installed." "Please install using 'pip install pgvector' " ) from e self.psycopg = psycopg self.errors = errors if connection is not None: self.conn = connection else: # Retrieve connection details from parameter or environment variable self.conn_details = connection_details or os.environ.get("DEEPFACE_POSTGRES_URI") if not self.conn_details: raise ValueError( "PostgreSQL connection information not found. " "Please provide connection_details or set the DEEPFACE_POSTGRES_URI" " environment variable." ) if isinstance(self.conn_details, str): self.conn = self.psycopg.connect(self.conn_details) elif isinstance(self.conn_details, dict): self.conn = self.psycopg.connect(**self.conn_details) else: raise ValueError("connection_details must be either a string or a dict.") # is pgvector extension installed? try: if not _SCHEMA_CHECKED.get("pgvector_extension"): with self.conn.cursor() as cur: cur.execute("CREATE EXTENSION IF NOT EXISTS vector;") self.conn.commit() _SCHEMA_CHECKED["pgvector_extension"] = True except Exception as e: raise ValueError( "Ensure pgvector extension is installed properly by running: " "'CREATE EXTENSION IF NOT EXISTS vector;'" ) from e register_vector(self.conn) def close(self) -> None: """Close the database connection.""" self.conn.close() def initialize_database(self, **kwargs: Any) -> None: """ Initialize PostgreSQL database schema for storing embeddings. Args: model_name (str): Name of the facial recognition model. detector_backend (str): Name of the face detector backend. aligned (bool): Whether the faces are aligned. l2_normalized (bool): Whether the embeddings are L2 normalized. """ model_name = kwargs.get("model_name", "VGG-Face") detector_backend = kwargs.get("detector_backend", "opencv") aligned = kwargs.get("aligned", True) l2_normalized = kwargs.get("l2_normalized", False) model = build_model(task="facial_recognition", model_name=model_name) dimensions = model.output_shape table_name = self.__generate_table_name( model_name, detector_backend, aligned, l2_normalized ) if _SCHEMA_CHECKED.get(table_name): logger.debug("PostgreSQL schema already checked, skipping.") return create_table_stmt = f""" CREATE TABLE IF NOT EXISTS {table_name} ( id SERIAL PRIMARY KEY, img_name TEXT NOT NULL, face BYTEA NOT NULL, face_shape INT[] NOT NULL, model_name TEXT NOT NULL, detector_backend TEXT NOT NULL, aligned BOOLEAN DEFAULT true, l2_normalized BOOLEAN DEFAULT false, embedding vector({dimensions}) NOT NULL, created_at TIMESTAMPTZ DEFAULT now(), face_hash TEXT NOT NULL, embedding_hash TEXT NOT NULL, UNIQUE (face_hash, embedding_hash) ); """ index_name = f"{table_name}_{'cosine' if l2_normalized else 'euclidean'}_idx" create_index_stmt = f""" CREATE INDEX {index_name} ON {table_name} USING hnsw (embedding {'vector_cosine_ops' if l2_normalized else 'vector_l2_ops'}); """ try: with self.conn.cursor() as cur: # create table if not exists cur.execute(create_table_stmt) # create index if not exists try: cur.execute(create_index_stmt) except Exception as e: # pylint: disable=broad-except # unfortunately if not exists is not supported for index creation if getattr(e, "sqlstate", None) == "42P07": self.conn.rollback() else: raise self.conn.commit() except Exception as e: if getattr(e, "sqlstate", None) == "42501": # permission denied raise ValueError( "The PostgreSQL user does not have permission to create " f"the required table {table_name}. " "Please ask your database administrator to grant CREATE privileges " "on the schema." ) from e raise _SCHEMA_CHECKED[table_name] = True def insert_embeddings(self, embeddings: List[Dict[str, Any]], batch_size: int = 100) -> int: """ Insert multiple embeddings into PostgreSQL. Args: embeddings (List[Dict[str, Any]]): List of embeddings to insert. batch_size (int): Number of embeddings to insert per batch. Returns: int: Number of embeddings inserted. """ if not embeddings: raise ValueError("No embeddings to insert.") self.initialize_database( model_name=embeddings[0]["model_name"], detector_backend=embeddings[0]["detector_backend"], aligned=embeddings[0]["aligned"], l2_normalized=embeddings[0]["l2_normalized"], ) table_name = self.__generate_table_name( model_name=embeddings[0]["model_name"], detector_backend=embeddings[0]["detector_backend"], aligned=embeddings[0]["aligned"], l2_normalized=embeddings[0]["l2_normalized"], ) query = f""" INSERT INTO {table_name} ( img_name, face, face_shape, model_name, detector_backend, aligned, l2_normalized, embedding, face_hash, embedding_hash ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s); """ values = [] for e in embeddings: face = e["face"] face_shape = list(face.shape) face_bytes = face.astype(np.float32).tobytes() face_json = json.dumps(face.tolist()) embedding_bytes = struct.pack(f'{len(e["embedding"])}d', *e["embedding"]) # uniqueness is guaranteed by face hash and embedding hash face_hash = hashlib.sha256(face_json.encode()).hexdigest() embedding_hash = hashlib.sha256(embedding_bytes).hexdigest() values.append( ( e["img_name"], face_bytes, face_shape, e["model_name"], e["detector_backend"], e["aligned"], e["l2_normalized"], e["embedding"], face_hash, embedding_hash, ) ) try: with self.conn.cursor() as cur: for i in range(0, len(values), batch_size): cur.executemany(query, values[i : i + batch_size]) # commit for every batch self.conn.commit() return len(values) except self.psycopg.errors.UniqueViolation as e: self.conn.rollback() if len(values) == 1: logger.warn("Duplicate detected for extracted face and embedding.") return 0 raise DuplicateEntryError( f"Duplicate detected for extracted face and embedding columns in {i}-th batch" ) from e def fetch_all_embeddings( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, batch_size: int = 1000, ) -> List[Dict[str, Any]]: """ Fetch all embeddings from PostgreSQL. Args: model_name (str): Name of the facial recognition model. detector_backend (str): Name of the face detector backend. aligned (bool): Whether the faces are aligned. l2_normalized (bool): Whether the embeddings are L2 normalized. batch_size (int): Number of embeddings to fetch per batch. Returns: List[Dict[str, Any]]: List of embeddings. """ table_name = self.__generate_table_name( model_name, detector_backend, aligned, l2_normalized ) query = f""" SELECT id, img_name, embedding FROM {table_name} ORDER BY id ASC; """ embeddings: List[Dict[str, Any]] = [] with self.conn.cursor(name="embeddings_cursor") as cur: cur.execute(query) while True: batch = cur.fetchmany(batch_size) if not batch: break for r in batch: embeddings.append( { "id": r[0], "img_name": r[1], "embedding": list(r[2]), "model_name": model_name, "detector_backend": detector_backend, "aligned": aligned, "l2_normalized": l2_normalized, } ) return embeddings def search_by_vector( self, vector: List[float], model_name: str = "VGG-Face", detector_backend: str = "opencv", aligned: bool = True, l2_normalized: bool = False, limit: int = 10, ) -> List[Dict[str, Any]]: """ Search for similar embeddings in PostgreSQL using a given vector. Args: vector (List[float]): The query embedding vector. model_name (str): Name of the facial recognition model. detector_backend (str): Name of the face detector backend. aligned (bool): Whether the faces are aligned. l2_normalized (bool): Whether the embeddings are L2 normalized. limit (int): Number of similar embeddings to return. Returns: List[Dict[str, Any]]: List of similar embeddings with distances. """ table_name = self.__generate_table_name( model_name, detector_backend, aligned, l2_normalized ) self.initialize_database( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) op = "<=>" if l2_normalized else "<->" query = f""" SELECT id, img_name, (embedding {op} (%s::vector)) AS distance FROM {table_name} ORDER BY embedding {op} (%s::vector) LIMIT %s; """ results: List[Dict[str, Any]] = [] with self.conn.cursor() as cur: cur.execute(query, (vector, vector, limit)) rows = cur.fetchall() for r in rows: results.append( { "id": r[0], "img_name": r[1], # "embedding": list(r[2]), # embedding dropped in select query "distance": r[2], "model_name": model_name, "detector_backend": detector_backend, "aligned": aligned, "l2_normalized": l2_normalized, } ) return results @staticmethod def __generate_table_name( model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, ) -> str: """ Generate postgres table name based on parameters. """ class_name_attributes = [ model_name.replace("-", ""), detector_backend, "Aligned" if aligned else "Unaligned", "Norm" if l2_normalized else "Raw", ] return "Embeddings_" + "_".join(class_name_attributes).lower()
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/database/pgvector.py", "license": "MIT License", "lines": 337, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
serengil/deepface:tests/unit/test_signature.py
# built-in dependencies import os import shutil import uuid import unittest # 3rd party dependencies import pytest from lightdsa import LightDSA # project dependencies from deepface import DeepFace from deepface.commons.logger import Logger logger = Logger() ALGORITHMS = ["ecdsa", "eddsa", "rsa", "dsa"] # pylint: disable=line-too-long class TestSignature(unittest.TestCase): def setUp(self): experiment_id = str(uuid.uuid4()) self.db_path = f"/tmp/{experiment_id}" self.expected_ds = ( "ds_model_vggface_detector_opencv_aligned_normalization_base_expand_0.pkl" ) # create experiment folder if not os.path.exists(self.db_path): os.mkdir(self.db_path) # copy some test files os.system(f"cp dataset/img1.jpg /tmp/{experiment_id}/") os.system(f"cp dataset/img2.jpg /tmp/{experiment_id}/") os.system(f"cp dataset/img3.jpg /tmp/{experiment_id}/") def tearDown(self): if os.path.exists(self.db_path): shutil.rmtree(self.db_path) def test_sign_and_verify_happy_path_with_obj(self): for algorithm_name in ALGORITHMS: cs = LightDSA(algorithm_name=algorithm_name) dfs_1st = DeepFace.find( img_path="dataset/img6.jpg", db_path=self.db_path, credentials=cs ) dfs_2nd = DeepFace.find( img_path="dataset/img7.jpg", db_path=self.db_path, credentials=cs ) assert isinstance(dfs_1st, list) assert isinstance(dfs_2nd, list) assert len(dfs_1st) > 0 assert len(dfs_2nd) > 0 assert dfs_1st[0].shape[0] == 2 # img1, img2 assert dfs_2nd[0].shape[0] == 2 # img1, img2 logger.info( f"✅ Signature test for happy path with LightDSA obj passed for {algorithm_name}" ) self.__flush_datastore_and_signature() def test_sign_and_verify_happy_path_with_dict(self): for algorithm_name in ALGORITHMS: cs = LightDSA(algorithm_name=algorithm_name) _ = DeepFace.find( img_path="dataset/img6.jpg", db_path=self.db_path, credentials={**cs.dsa.keys, "algorithm_name": algorithm_name}, ) _ = DeepFace.find( img_path="dataset/img7.jpg", db_path=self.db_path, credentials={**cs.dsa.keys, "algorithm_name": algorithm_name}, ) logger.info(f"✅ Signature test for happy path with dict passed for {algorithm_name}") self.__flush_datastore_and_signature() def test_missing_algorithm_in_dict(self): for algorithm_name in ALGORITHMS: cs = LightDSA(algorithm_name=algorithm_name) with pytest.raises( ValueError, match="credentials dictionary must have 'algorithm_name' key" ): _ = DeepFace.find( img_path="dataset/img6.jpg", db_path=self.db_path, credentials=cs.dsa.keys, ) logger.info(f"✅ Signature test for missing algorithm name passed for {algorithm_name}") self.__flush_datastore_and_signature() def test_tampered_datastore_detection_with_type_error(self): for algorithm_name in ALGORITHMS: cs = LightDSA(algorithm_name=algorithm_name) # this will create and sign the datastore _ = DeepFace.find(img_path="dataset/img6.jpg", db_path=self.db_path, credentials=cs) # Tamper with the datastore file signature = f"{self.db_path}/{self.expected_ds}.ldsa" with open(signature, "w", encoding="utf-8") as f: f.write("'tampering with the datastore'") # signature type is not matching the algorithm with pytest.raises(ValueError, match="Verify the signature"): _ = DeepFace.find(img_path="dataset/img7.jpg", db_path=self.db_path, credentials=cs) self.__flush_datastore_and_signature() logger.info( f"✅ Tampered datastore detection test with type error passed for {algorithm_name}" ) def test_tampered_datastore_detection_with_content(self): for algorithm_name in ALGORITHMS: cs = LightDSA(algorithm_name=algorithm_name) # this will create and sign the datastore _ = DeepFace.find(img_path="dataset/img6.jpg", db_path=self.db_path, credentials=cs) if algorithm_name == "rsa": new_signature = 319561459047296488548458984747399773018716548204273025089624526759359534233284312158510290754391934668693104185451914855617607653930118615834122905987992506015413484111459136235040703307837127330552076394553025514846602694994704058032032682011030896228476574896316764474080643444528752822215665326313975210266100821320428968057729348770126684036043834110914715739798738033680251895412183116783758569626527555756175521592665908984550792405972689418461489583818241720836275237261051794829129609867815663459783380179330918682830834361767346820728010180691232612809687266284664884281497246914633251532570093804727503221592140826938085233362518642240314192925852839183375057159735842181129571046919197169304114361287251975127762914060608489444548355191778055788828924190814939438198679453052886489889714657423399402932343101284126001466450432228046323891788753347814011641443220020734532039664233082527737624947853241639198217834 elif algorithm_name == "dsa": new_signature = ( 9100224601877825638014134863066256026676002678448729267282144204754, 7634803645147310159689393871148731810441463887021966655811033398889, ) elif algorithm_name == "ecdsa": new_signature = ( 21518513378698262440337632884706393342279436822165585485363750050247340191720, 41671206923584596559299832926426077520762049023469772372748973101822889226099, ) elif algorithm_name == "eddsa": new_signature = ( ( 10558823458062709006637242334064065742608369933510637863306601023456142118149, 35629342124183609337373813938440693584938877184586698416611230077459766071, ), 616779964632213973552139846661614990419749880592583320329014277948539725318347638187634255022715560768868643524944455800527501125094189022366431963778314, ) else: raise ValueError(f"Unsupported algorithm name: {algorithm_name}") # Tamper with the datastore file signature = f"{self.db_path}/{self.expected_ds}.ldsa" with open(signature, "w", encoding="utf-8") as f: f.write(str(new_signature)) # signature type is not matching the algorithm with pytest.raises(ValueError, match=r"(Signature is invalid|Invalid signature)"): _ = DeepFace.find(img_path="dataset/img7.jpg", db_path=self.db_path, credentials=cs) self.__flush_datastore_and_signature() logger.info( f"✅ Tampered datastore detection test with content passed for {algorithm_name}" ) def test_unsigned_datastore_detected(self): for algorithm_name in ALGORITHMS: cs = LightDSA(algorithm_name=algorithm_name) # this will create ds without signature _ = DeepFace.find(img_path="dataset/img6.jpg", db_path=self.db_path) with pytest.raises( ValueError, match=".ldsa not found.You may need to re-create the pickle by deleting the existing one.", ): _ = DeepFace.find(img_path="dataset/img7.jpg", db_path=self.db_path, credentials=cs) logger.info( f"✅ Signature test for happy path with LightDSA obj passed for {algorithm_name}" ) self.__flush_datastore_and_signature() def test_signed_datastore_with_no_credentials(self): for algorithm_name in ALGORITHMS: cs = LightDSA(algorithm_name=algorithm_name) # this will create and sign the datastore _ = DeepFace.find(img_path="dataset/img6.jpg", db_path=self.db_path, credentials=cs) signature_path = f"{self.db_path}/{self.expected_ds}.ldsa" with pytest.raises( ValueError, match=f"Credentials not provided but signature file {signature_path} exists.", ): _ = DeepFace.find(img_path="dataset/img7.jpg", db_path=self.db_path) logger.info(f"✅ Signed datastore with no credentials test passed for {algorithm_name}") self.__flush_datastore_and_signature() def test_custom_curves(self): for algorithm_name, form_name, curve_name in [ # default configurations # ("eddsa", "edwards", "ed25519"), # ("ecdsa", "weierstrass", "secp256k1"), # custom configurations ("eddsa", "weierstrass", "secp256k1"), ("eddsa", "koblitz", "k233"), ("eddsa", "edwards", "e521"), ("ecdsa", "edwards", "ed25519"), ("ecdsa", "koblitz", "k233"), ("ecdsa", "weierstrass", "bn638"), ]: cs = LightDSA(algorithm_name=algorithm_name, form_name=form_name, curve_name=curve_name) _ = DeepFace.find( img_path="dataset/img6.jpg", db_path=self.db_path, credentials={ **cs.dsa.keys, "algorithm_name": algorithm_name, "form_name": form_name, "curve_name": curve_name, }, ) _ = DeepFace.find( img_path="dataset/img7.jpg", db_path=self.db_path, credentials={ **cs.dsa.keys, "algorithm_name": algorithm_name, "form_name": form_name, "curve_name": curve_name, }, ) logger.info( f"✅ Signature test for custom curves passed for {algorithm_name}/{form_name}/{curve_name}" ) self.__flush_datastore_and_signature() def __flush_datastore_and_signature(self): if os.path.exists(f"{self.db_path}/{self.expected_ds}"): os.remove(f"{self.db_path}/{self.expected_ds}") if os.path.exists(f"{self.db_path}/{self.expected_ds}.ldsa"): os.remove(f"{self.db_path}/{self.expected_ds}.ldsa")
{ "repo_id": "serengil/deepface", "file_path": "tests/unit/test_signature.py", "license": "MIT License", "lines": 202, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
serengil/deepface:deepface/modules/database/neo4j.py
# built-in dependencies import os import json import hashlib import struct from typing import Any, Dict, Optional, List, Union from urllib.parse import urlparse # project dependencies from deepface.modules.database.types import Database from deepface.modules.modeling import build_model from deepface.modules.verification import find_cosine_distance, find_euclidean_distance from deepface.commons.logger import Logger logger = Logger() _SCHEMA_CHECKED: Dict[str, bool] = {} # pylint: disable=too-many-positional-arguments class Neo4jClient(Database): def __init__( self, connection_details: Optional[Union[Dict[str, Any], str]] = None, connection: Any = None, ) -> None: # Import here to avoid mandatory dependency try: from neo4j import GraphDatabase except (ModuleNotFoundError, ImportError) as e: raise ValueError( "neo4j is an optional dependency, ensure the library is installed." "Please install using 'pip install neo4j' " ) from e self.GraphDatabase = GraphDatabase if connection is not None: self.conn = connection else: self.conn_details = connection_details or os.environ.get("DEEPFACE_NEO4J_URI") if not self.conn_details: raise ValueError( "Neo4j connection information not found. " "Please provide connection_details or set the DEEPFACE_NEO4J_URI" " environment variable." ) if isinstance(self.conn_details, str): parsed = urlparse(self.conn_details) uri = f"{parsed.scheme}://{parsed.hostname}:{parsed.port}" self.conn = self.GraphDatabase.driver(uri, auth=(parsed.username, parsed.password)) else: raise ValueError("connection_details must be a string.") if not self.__is_gds_installed(): raise ValueError( "Neo4j Graph Data Science (GDS) plugin is not installed. " "Please install the GDS plugin to use Neo4j as a database backend." ) def close(self) -> None: """ Close the Neo4j database connection. """ if self.conn: self.conn.close() logger.debug("Neo4j connection closed.") def initialize_database(self, **kwargs: Any) -> None: """ Ensure Neo4j database has the necessary constraints and indexes for storing embeddings. """ model_name = kwargs.get("model_name", "VGG-Face") detector_backend = kwargs.get("detector_backend", "opencv") aligned = kwargs.get("aligned", True) l2_normalized = kwargs.get("l2_normalized", False) node_label = self.__generate_node_label( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) model = build_model(task="facial_recognition", model_name=model_name) dimensions = model.output_shape similarity_function = "cosine" if l2_normalized else "euclidean" if _SCHEMA_CHECKED.get(node_label): logger.debug(f"Neo4j index {node_label} already exists, skipping creation.") return index_query = f""" CREATE VECTOR INDEX {node_label}_embedding_idx IF NOT EXISTS FOR (d:{node_label}) ON (d.embedding) OPTIONS {{ indexConfig: {{ `vector.dimensions`: {dimensions}, `vector.similarity_function`: '{similarity_function}' }} }}; """ uniq_query = f""" CREATE CONSTRAINT {node_label}_unique IF NOT EXISTS FOR (n:{node_label}) REQUIRE (n.face_hash, n.embedding_hash) IS UNIQUE; """ with self.conn.session() as session: session.execute_write(lambda tx: tx.run(index_query)) session.execute_write(lambda tx: tx.run(uniq_query)) _SCHEMA_CHECKED[node_label] = True logger.debug(f"Neo4j index {node_label} ensured.") def insert_embeddings(self, embeddings: List[Dict[str, Any]], batch_size: int = 100) -> int: """ Insert embeddings into Neo4j database in batches. """ if not embeddings: raise ValueError("No embeddings to insert.") self.initialize_database( model_name=embeddings[0]["model_name"], detector_backend=embeddings[0]["detector_backend"], aligned=embeddings[0]["aligned"], l2_normalized=embeddings[0]["l2_normalized"], ) node_label = self.__generate_node_label( model_name=embeddings[0]["model_name"], detector_backend=embeddings[0]["detector_backend"], aligned=embeddings[0]["aligned"], l2_normalized=embeddings[0]["l2_normalized"], ) query = f""" UNWIND $rows AS r MERGE (n:{node_label} {{face_hash: r.face_hash, embedding_hash: r.embedding_hash}}) ON CREATE SET n.img_name = r.img_name, n.embedding = r.embedding, n.face = r.face, n.model_name = r.model_name, n.detector_backend = r.detector_backend, n.aligned = r.aligned, n.l2_normalized = r.l2_normalized RETURN count(*) AS processed """ total = 0 with self.conn.session() as session: for i in range(0, len(embeddings), batch_size): batch = embeddings[i : i + batch_size] rows = [] for e in batch: face_json = json.dumps(e["face"].tolist()) face_hash = hashlib.sha256(face_json.encode()).hexdigest() embedding_bytes = struct.pack(f'{len(e["embedding"])}d', *e["embedding"]) embedding_hash = hashlib.sha256(embedding_bytes).hexdigest() rows.append( { "face_hash": face_hash, "embedding_hash": embedding_hash, "img_name": e["img_name"], "embedding": e["embedding"], # "face": e["face"].tolist(), # "face_shape": list(e["face"].shape), "model_name": e.get("model_name"), "detector_backend": e.get("detector_backend"), "aligned": bool(e.get("aligned", True)), "l2_normalized": bool(e.get("l2_normalized", False)), } ) processed = session.execute_write( lambda tx, q=query, r=rows: int(tx.run(q, rows=r).single()["processed"]) ) total += processed return total def fetch_all_embeddings( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, batch_size: int = 1000, ) -> List[Dict[str, Any]]: """ Fetch all embeddings from Neo4j database in batches. """ node_label = self.__generate_node_label( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) query = f""" MATCH (n:{node_label}) WHERE n.embedding IS NOT NULL AND ($last_eid IS NULL OR elementId(n) > $last_eid) RETURN elementId(n) AS cursor, coalesce(n.id, elementId(n)) AS id, n.img_name AS img_name, n.embedding AS embedding ORDER BY cursor ASC LIMIT $limit """ out: List[Dict[str, Any]] = [] last_eid: Optional[str] = None with self.conn.session() as session: while True: result = session.run(query, last_eid=last_eid, limit=batch_size) rows = list(result) if not rows: break for r in rows: out.append( { "id": r["id"], "img_name": r["img_name"], "embedding": r["embedding"], "model_name": model_name, "detector_backend": detector_backend, "aligned": aligned, "l2_normalized": l2_normalized, } ) # advance cursor using elementId last_eid = rows[-1]["cursor"] return out def search_by_vector( self, vector: List[float], model_name: str = "VGG-Face", detector_backend: str = "opencv", aligned: bool = True, l2_normalized: bool = False, limit: int = 10, ) -> List[Dict[str, Any]]: """ ANN search using the main vector (embedding). """ self.initialize_database( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) node_label = self.__generate_node_label( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) index_name = f"{node_label}_embedding_idx" query = """ CALL db.index.vector.queryNodes($index_name, $limit, $vector) YIELD node, score RETURN elementId(node) AS id, node.img_name AS img_name, node.face_hash AS face_hash, node.embedding AS embedding, node.embedding_hash AS embedding_hash, score AS score ORDER BY score DESC """ with self.conn.session() as session: result = session.run( query, index_name=index_name, limit=limit, vector=vector, ) out: List[Dict[str, Any]] = [] for r in result: if l2_normalized: distance = find_cosine_distance(vector, r.get("embedding")) # distance = 2 * (1 - r.get("score")) else: distance = find_euclidean_distance(vector, r.get("embedding")) # distance = math.sqrt(1.0 / r.get("score")) out.append( { "id": r.get("id"), "img_name": r.get("img_name"), "face_hash": r.get("face_hash"), "embedding_hash": r.get("embedding_hash"), "model_name": model_name, "detector_backend": detector_backend, "aligned": aligned, "l2_normalized": l2_normalized, "distance": distance, } ) return out def __is_gds_installed(self) -> bool: """ Check if the Graph Data Science (GDS) plugin is installed in the Neo4j database. """ query = "RETURN gds.version() AS version" try: with self.conn.session() as session: result = session.run(query).single() logger.debug(f"GDS version: {result['version']}") return True except Exception as e: # pylint: disable=broad-except logger.error(f"GDS plugin not installed or error occurred: {e}") return False @staticmethod def __generate_node_label( model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, ) -> str: """ Generate a Neo4j node label based on model and preprocessing parameters. """ label_parts = [ model_name.replace("-", "_").capitalize(), detector_backend.capitalize(), "Aligned" if aligned else "Unaligned", "Norm" if l2_normalized else "Raw", ] return "".join(label_parts)
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/database/neo4j.py", "license": "MIT License", "lines": 307, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
serengil/deepface:deepface/api/src/dependencies/container.py
# project dependencies from deepface.api.src.modules.auth.service import AuthService from deepface.api.src.dependencies.variables import Variables # pylint: disable=too-few-public-methods class Container: def __init__(self, variables: Variables) -> None: # once you have variables, you can connect dbs and other services here self.auth_service = AuthService(auth_token=variables.auth_token)
{ "repo_id": "serengil/deepface", "file_path": "deepface/api/src/dependencies/container.py", "license": "MIT License", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
serengil/deepface:deepface/api/src/modules/auth/service.py
# built-in dependencies from typing import Optional, Dict, Any # project dependencies from deepface.commons.logger import Logger logger = Logger() # pylint: disable=too-few-public-methods class AuthService: def __init__(self, auth_token: Optional[str] = None) -> None: self.auth_token = auth_token self.is_auth_enabled = auth_token is not None and len(auth_token) > 0 def extract_token(self, auth_header: Optional[str]) -> Optional[str]: if not auth_header: return None parts = auth_header.split() if len(parts) == 2 and parts[0].lower() == "bearer": return parts[1] return None def validate(self, headers: Dict[str, Any]) -> bool: if not self.is_auth_enabled: logger.debug("Authentication is disabled. Skipping token validation.") return True token = self.extract_token(headers.get("Authorization")) if not token: logger.debug("No authentication token provided. Validation failed.") return False if token != self.auth_token: logger.debug("Invalid authentication token provided. Validation failed.") return False logger.debug("Authentication token validated successfully.") return True
{ "repo_id": "serengil/deepface", "file_path": "deepface/api/src/modules/auth/service.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
serengil/deepface:deepface/modules/database/weaviate.py
# built-in dependencies import os import json import hashlib import struct import base64 import uuid import math from typing import Any, Dict, Optional, List, Union # project dependencies from deepface.modules.database.types import Database from deepface.commons.logger import Logger logger = Logger() _SCHEMA_CHECKED: Dict[str, bool] = {} # pylint: disable=too-many-positional-arguments class WeaviateClient(Database): """ Weaviate client for storing and retrieving face embeddings and indices. """ def __init__( self, connection_details: Optional[Union[str, Dict[str, Any]]] = None, connection: Any = None, ): try: import weaviate except (ModuleNotFoundError, ImportError) as e: raise ValueError( "weaviate-client is an optional dependency. " "Install with 'pip install weaviate-client'" ) from e self.weaviate = weaviate if connection is not None: self.client = connection # URL key for _WEAVIATE_CHECKED; fallback if client has no URL self.url = getattr(connection, "url", str(id(connection))) else: self.conn_details = connection_details or os.environ.get("DEEPFACE_WEAVIATE_URL") if isinstance(self.conn_details, str): self.url = self.conn_details self.api_key = os.getenv("WEAVIATE_API_KEY") elif isinstance(self.conn_details, dict): self.url = self.conn_details.get("url") self.api_key = self.conn_details.get("api_key") or os.getenv("WEAVIATE_API_KEY") else: raise ValueError("connection_details must be a string or dict with 'url'.") if not self.url: raise ValueError("Weaviate URL not provided in connection_details.") client_config = {"url": self.url} if getattr(self, "api_key", None): client_config["auth_client_secret"] = self.weaviate.AuthApiKey(api_key=self.api_key) self.client = self.weaviate.Client(**client_config) def initialize_database(self, **kwargs: Any) -> None: """ Ensure Weaviate schemas exist for embeddings using both cosine and L2 (euclidean). """ model_name = kwargs.get("model_name", "VGG-Face") detector_backend = kwargs.get("detector_backend", "opencv") aligned = kwargs.get("aligned", True) l2_normalized = kwargs.get("l2_normalized", False) existing_schema = self.client.schema.get() existing_classes = {c["class"] for c in existing_schema.get("classes", [])} class_name = self.__generate_class_name( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) if _SCHEMA_CHECKED.get(class_name): logger.debug("Weaviate schema already checked, skipping.") return if class_name in existing_classes: logger.debug(f"Weaviate class {class_name} already exists.") return self.client.schema.create_class( { "class": class_name, "vectorIndexType": "hnsw", "vectorizer": "none", "vectorIndexConfig": { "M": int(os.getenv("WEAVIATE_HNSW_M", "16")), "distance": "cosine" if l2_normalized else "l2-squared", }, "properties": [ {"name": "img_name", "dataType": ["text"]}, {"name": "face", "dataType": ["blob"]}, {"name": "face_shape", "dataType": ["int[]"]}, {"name": "model_name", "dataType": ["text"]}, {"name": "detector_backend", "dataType": ["text"]}, {"name": "aligned", "dataType": ["boolean"]}, {"name": "l2_normalized", "dataType": ["boolean"]}, {"name": "face_hash", "dataType": ["text"]}, {"name": "embedding_hash", "dataType": ["text"]}, # embedding property is optional since we pass it as vector {"name": "embedding", "dataType": ["number[]"]}, ], } ) logger.debug(f"Weaviate class {class_name} created successfully.") _SCHEMA_CHECKED[class_name] = True def insert_embeddings(self, embeddings: List[Dict[str, Any]], batch_size: int = 100) -> int: """ Insert multiple embeddings into Weaviate using batch API. """ if not embeddings: raise ValueError("No embeddings to insert.") self.initialize_database( model_name=embeddings[0]["model_name"], detector_backend=embeddings[0]["detector_backend"], aligned=embeddings[0]["aligned"], l2_normalized=embeddings[0]["l2_normalized"], ) class_name = self.__generate_class_name( model_name=embeddings[0]["model_name"], detector_backend=embeddings[0]["detector_backend"], aligned=embeddings[0]["aligned"], l2_normalized=embeddings[0]["l2_normalized"], ) with self.client.batch as batcher: batcher.batch_size = batch_size batcher.timeout_retries = 3 for e in embeddings: face_json = json.dumps(e["face"].tolist()) face_hash = hashlib.sha256(face_json.encode()).hexdigest() embedding_bytes = struct.pack(f'{len(e["embedding"])}d', *e["embedding"]) embedding_hash = hashlib.sha256(embedding_bytes).hexdigest() # Check if embedding already exists query = ( self.client.query.get(class_name, ["embedding_hash"]) .with_where( { "path": ["embedding_hash"], "operator": "Equal", "valueText": embedding_hash, } ) .with_limit(1) .do() ) existing = query.get("data", {}).get("Get", {}).get(class_name, []) if existing: logger.warn( f"Embedding with hash {embedding_hash} already exists in {class_name}." ) continue uid = str(uuid.uuid4()) properties = { "img_name": e["img_name"], "face": base64.b64encode(e["face"].tobytes()).decode("utf-8"), "face_shape": list(e["face"].shape), "model_name": e["model_name"], "detector_backend": e["detector_backend"], "aligned": e["aligned"], "l2_normalized": e["l2_normalized"], "embedding": e["embedding"], # optional "face_hash": face_hash, "embedding_hash": embedding_hash, } batcher.add_data_object(properties, class_name, vector=e["embedding"], uuid=uid) return len(embeddings) def fetch_all_embeddings( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, batch_size: int = 1000, ) -> List[Dict[str, Any]]: """ Fetch all embeddings with filters. """ class_name = self.__generate_class_name( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) self.initialize_database( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) results = ( self.client.query.get(class_name, ["img_name", "embedding"]) .with_additional(["id"]) .do() ) data = results.get("data", {}).get("Get", {}).get(class_name, []) embeddings = [] for r in data: embeddings.append( { "id": r.get("_additional", {}).get("id"), "img_name": r["img_name"], "embedding": r["embedding"], "model_name": model_name, "detector_backend": detector_backend, "aligned": aligned, "l2_normalized": l2_normalized, } ) return embeddings def search_by_vector( self, vector: List[float], model_name: str = "VGG-Face", detector_backend: str = "opencv", aligned: bool = True, l2_normalized: bool = False, limit: int = 10, ) -> List[Dict[str, Any]]: """ ANN search using the main vector (embedding). """ class_name = self.__generate_class_name( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) self.initialize_database( model_name=model_name, detector_backend=detector_backend, aligned=aligned, l2_normalized=l2_normalized, ) query = self.client.query.get(class_name, ["img_name", "embedding"]) query = ( query.with_near_vector({"vector": vector}) .with_limit(limit) .with_additional(["id", "distance"]) ) results = query.do() data = results.get("data", {}).get("Get", {}).get(class_name, []) return [ { "id": r.get("_additional", {}).get("id"), "img_name": r["img_name"], "embedding": r["embedding"], "distance": ( r.get("_additional", {}).get("distance") if l2_normalized else math.sqrt(r.get("_additional", {}).get("distance")) ), } for r in data ] def close(self) -> None: """ Close the Weaviate client connection. """ self.client.close() @staticmethod def __generate_class_name( model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, ) -> str: """ Generate Weaviate class name based on parameters. """ class_name_attributes = [ model_name.replace("-", ""), detector_backend, "Aligned" if aligned else "Unaligned", "Norm" if l2_normalized else "Raw", ] return "Embeddings_" + "_".join(class_name_attributes).lower()
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/database/weaviate.py", "license": "MIT License", "lines": 270, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
serengil/deepface:deepface/modules/database/mongo.py
# built-in dependencies import os import json import hashlib import struct from datetime import datetime, timezone from typing import Any, Dict, List, Optional, Union # 3rd party dependencies import numpy as np # project dependencies from deepface.modules.database.types import Database from deepface.modules.exceptions import DuplicateEntryError from deepface.commons.logger import Logger logger = Logger() # pylint: disable=too-many-positional-arguments, too-many-instance-attributes class MongoDbClient(Database): """ MongoDB equivalent of PostgresClient for DeepFace embeddings storage. """ def __init__( self, connection_details: Optional[Union[str, Dict[str, Any]]] = None, connection: Any = None, db_name: str = "deepface", ) -> None: try: from pymongo import MongoClient, ASCENDING from pymongo.errors import DuplicateKeyError, BulkWriteError from bson import Binary except (ModuleNotFoundError, ImportError) as e: raise ValueError( "pymongo is an optional dependency. Please install it as `pip install pymongo`" ) from e self.MongoClient = MongoClient self.ASCENDING = ASCENDING self.DuplicateKeyError = DuplicateKeyError self.BulkWriteError = BulkWriteError self.Binary = Binary if connection is not None: self.client = connection else: self.conn_details = connection_details or os.environ.get("DEEPFACE_MONGO_URI") if not self.conn_details: raise ValueError( "MongoDB connection information not found. " "Please provide connection_details or set DEEPFACE_MONGO_URI" ) if isinstance(self.conn_details, str): self.client = MongoClient(self.conn_details) else: self.client = MongoClient(**self.conn_details) self.db = self.client[db_name] self.embeddings = self.db.embeddings self.embeddings_index = self.db.embeddings_index self.counters = self.db.counters self.initialize_database() def close(self) -> None: """Close MongoDB connection.""" self.client.close() def initialize_database(self, **kwargs: Any) -> None: """ Ensure required MongoDB indexes exist. """ # Unique constraint for embeddings self.embeddings.create_index( [("face_hash", self.ASCENDING), ("embedding_hash", self.ASCENDING)], unique=True, name="uniq_face_embedding", ) # Unique constraint for embeddings_index self.embeddings_index.create_index( [ ("model_name", self.ASCENDING), ("detector_backend", self.ASCENDING), ("align", self.ASCENDING), ("l2_normalized", self.ASCENDING), ], unique=True, name="uniq_index_config", ) # counters collection for auto-incrementing IDs if not self.counters.find_one({"_id": "embedding_id"}): self.counters.insert_one({"_id": "embedding_id", "seq": 0}) logger.debug("MongoDB indexes ensured.") def upsert_embeddings_index( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, index_data: bytes, ) -> None: """ Upsert embeddings index into MongoDB. Args: model_name (str): Name of the model. detector_backend (str): Name of the detector backend. aligned (bool): Whether the embeddings are aligned. l2_normalized (bool): Whether the embeddings are L2 normalized. index_data (bytes): Serialized index data. """ self.embeddings_index.update_one( { "model_name": model_name, "detector_backend": detector_backend, "align": aligned, "l2_normalized": l2_normalized, }, { "$set": { "index_data": self.Binary(index_data), "updated_at": datetime.now(timezone.utc), }, "$setOnInsert": { "created_at": datetime.now(timezone.utc), }, }, upsert=True, ) def get_embeddings_index( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, ) -> bytes: """ Retrieve embeddings index from MongoDB. Args: model_name (str): Name of the model. detector_backend (str): Name of the detector backend. aligned (bool): Whether the embeddings are aligned. l2_normalized (bool): Whether the embeddings are L2 normalized. Returns: bytes: Serialized index data. """ doc = self.embeddings_index.find_one( { "model_name": model_name, "detector_backend": detector_backend, "align": aligned, "l2_normalized": l2_normalized, }, {"index_data": 1}, ) if not doc: raise ValueError( "No Embeddings index found for the specified parameters " f"{model_name=}, {detector_backend=}, " f"{aligned=}, {l2_normalized=}. " "You must run build_index first." ) return bytes(doc["index_data"]) def insert_embeddings(self, embeddings: List[Dict[str, Any]], batch_size: int = 100) -> int: """ Insert embeddings into MongoDB. Args: embeddings (List[Dict[str, Any]]): List of embedding records to insert. batch_size (int): Number of records to insert in each batch. Returns: int: Number of embeddings successfully inserted. """ if not embeddings: raise ValueError("No embeddings to insert.") docs: List[Dict[str, Any]] = [] for e in embeddings: face = e["face"] face_shape = list(face.shape) binary_face_data = self.Binary(face.astype(np.float32).tobytes()) embedding_bytes = struct.pack(f'{len(e["embedding"])}d', *e["embedding"]) face_hash = hashlib.sha256(json.dumps(face.tolist()).encode()).hexdigest() embedding_hash = hashlib.sha256(embedding_bytes).hexdigest() int_id = self.counters.find_one_and_update( {"_id": "embedding_id"}, {"$inc": {"seq": 1}}, upsert=True, return_document=True )["seq"] docs.append( { "sequence": int_id, "img_name": e["img_name"], "face": binary_face_data, "face_shape": face_shape, "model_name": e["model_name"], "detector_backend": e["detector_backend"], "aligned": e["aligned"], "l2_normalized": e["l2_normalized"], "embedding": e["embedding"], "face_hash": face_hash, "embedding_hash": embedding_hash, "created_at": datetime.now(timezone.utc), } ) inserted = 0 try: for i in range(0, len(docs), batch_size): result = self.embeddings.insert_many(docs[i : i + batch_size], ordered=False) inserted += len(result.inserted_ids) except (self.DuplicateKeyError, self.BulkWriteError) as e: if len(docs) == 1: logger.warn("Duplicate detected for extracted face and embedding.") return inserted raise DuplicateEntryError( f"Duplicate detected for extracted face and embedding in {i}-th batch" ) from e return inserted def fetch_all_embeddings( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, batch_size: int = 1000, ) -> List[Dict[str, Any]]: """ Fetch all embeddings from MongoDB based on specified parameters. Args: model_name (str): Name of the model. detector_backend (str): Name of the detector backend. aligned (bool): Whether the embeddings are aligned. l2_normalized (bool): Whether the embeddings are L2 normalized. batch_size (int): Number of records to fetch in each batch. Returns: List[Dict[str, Any]]: List of embedding records. """ cursor = self.embeddings.find( { "model_name": model_name, "detector_backend": detector_backend, "aligned": aligned, "l2_normalized": l2_normalized, }, { "_id": 1, "sequence": 1, "img_name": 1, "embedding": 1, }, batch_size=batch_size, ).sort("sequence", self.ASCENDING) results: List[Dict[str, Any]] = [] for doc in cursor: results.append( { "_id": str(doc["_id"]), "id": doc["sequence"], "img_name": doc["img_name"], "embedding": doc["embedding"], "model_name": model_name, "detector_backend": detector_backend, "aligned": aligned, "l2_normalized": l2_normalized, } ) return results def search_by_id( self, ids: Union[List[str], List[int]], ) -> List[Dict[str, Any]]: """ Search records by their IDs. """ cursor = self.embeddings.find( {"sequence": {"$in": ids}}, { "_id": 1, "sequence": 1, "img_name": 1, }, ) results: List[Dict[str, Any]] = [] for doc in cursor: results.append( { "_id": str(doc["_id"]), "id": doc["sequence"], "img_name": doc["img_name"], } ) return results
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/database/mongo.py", "license": "MIT License", "lines": 278, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
serengil/deepface:deepface/modules/database/types.py
# built-in dependencies from typing import Any, Dict, List, Union, Optional from abc import ABC, abstractmethod # pylint: disable=unnecessary-pass, too-many-positional-arguments class Database(ABC): @abstractmethod def __init__( self, connection_details: Optional[Union[str, Dict[str, Any]]] = None, connection: Any = None, ): """ Initialize the database client with connection details or an existing connection. """ pass @abstractmethod def initialize_database(self, **kwargs: Any) -> None: """ Ensure that the embeddings table or indexes exist in the database. """ pass @abstractmethod def insert_embeddings(self, embeddings: List[Dict[str, Any]], batch_size: int = 100) -> int: """ Insert embeddings into the database in batches. """ pass @abstractmethod def fetch_all_embeddings( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, batch_size: int = 1000, ) -> List[Dict[str, Any]]: """ Fetch all embeddings from the database in batches. """ pass @abstractmethod def close(self) -> None: """ Close the database connection. """ pass def get_embeddings_index( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, ) -> bytes: """ Retrieve the embeddings index from the database. """ raise NotImplementedError( f"{self.__class__.__name__} does not require storing embeddings index." " Because it handles indexing internally." ) def search_by_vector( self, vector: List[float], model_name: str = "VGG-Face", detector_backend: str = "opencv", aligned: bool = True, l2_normalized: bool = False, limit: int = 10, ) -> List[Dict[str, Any]]: """ ANN search using the main vector (embedding). """ raise NotImplementedError( f"{self.__class__.__name__} does not support ANN search natively." ) def search_by_id( self, ids: Union[List[str], List[int]], ) -> List[Dict[str, Any]]: """ Search records by their IDs. """ raise NotImplementedError( f"{self.__class__.__name__} does not implement search_by_id method." " Because search by vector returns metadata already." ) def upsert_embeddings_index( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, index_data: bytes, ) -> None: """ Insert or update the embeddings index in the database. """ raise NotImplementedError( f"{self.__class__.__name__} does not require storing embeddings index." " Because it handles indexing internally." )
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/database/types.py", "license": "MIT License", "lines": 101, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
serengil/deepface:deepface/api/src/dependencies/variables.py
# built-in dependencies import os # project dependencies from deepface.modules.database.inventory import database_inventory # pylint: disable=too-few-public-methods class Variables: def __init__(self) -> None: self.database_type = os.getenv("DEEPFACE_DATABASE_TYPE", "postgres").lower() if database_inventory.get(self.database_type) is None: raise ValueError(f"Unsupported database type: {self.database_type}") connection_string = database_inventory[self.database_type]["connection_string"] conection_details = os.getenv(connection_string) self.conection_details = os.getenv("DEEPFACE_CONNECTION_DETAILS") or conection_details self.face_recognition_models = os.getenv("DEEPFACE_FACE_RECOGNITION_MODELS") self.face_detection_models = os.getenv("DEEPFACE_FACE_DETECTION_MODELS") self.auth_token = os.getenv("DEEPFACE_AUTH_TOKEN")
{ "repo_id": "serengil/deepface", "file_path": "deepface/api/src/dependencies/variables.py", "license": "MIT License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
serengil/deepface:deepface/modules/database/postgres.py
# built-in dependencies import os import json import hashlib import struct from typing import Any, Dict, Optional, List, Union, cast # 3rd party dependencies import numpy as np # project dependencies from deepface.modules.database.types import Database from deepface.modules.exceptions import DuplicateEntryError from deepface.commons.logger import Logger logger = Logger() _SCHEMA_CHECKED: Dict[str, bool] = {} CREATE_EMBEDDINGS_TABLE_SQL = """ CREATE TABLE IF NOT EXISTS embeddings ( id BIGSERIAL PRIMARY KEY, img_name TEXT NOT NULL, face BYTEA NOT NULL, face_shape INT[] NOT NULL, model_name TEXT NOT NULL, detector_backend TEXT NOT NULL, aligned BOOLEAN DEFAULT true, l2_normalized BOOLEAN DEFAULT false, embedding FLOAT8[] NOT NULL, created_at TIMESTAMPTZ DEFAULT now(), face_hash TEXT NOT NULL, embedding_hash TEXT NOT NULL, UNIQUE (face_hash, embedding_hash) ); """ CREATE_EMBEDDINGS_INDEX_TABLE_SQL = """ CREATE TABLE IF NOT EXISTS embeddings_index ( id SERIAL PRIMARY KEY, model_name TEXT, detector_backend TEXT, align BOOL, l2_normalized BOOL, index_data BYTEA, created_at TIMESTAMPTZ DEFAULT now(), updated_at TIMESTAMPTZ DEFAULT now(), UNIQUE (model_name, detector_backend, align, l2_normalized) ); """ # pylint: disable=too-many-positional-arguments class PostgresClient(Database): def __init__( self, connection_details: Optional[Union[Dict[str, Any], str]] = None, connection: Any = None, ) -> None: # Import here to avoid mandatory dependency try: import psycopg except (ModuleNotFoundError, ImportError) as e: raise ValueError( "psycopg is an optional dependency, ensure the library is installed." "Please install using 'pip install \"psycopg[binary]\"' " ) from e self.psycopg = psycopg if connection is not None: self.conn = connection else: # Retrieve connection details from parameter or environment variable self.conn_details = connection_details or os.environ.get("DEEPFACE_POSTGRES_URI") if not self.conn_details: raise ValueError( "PostgreSQL connection information not found. " "Please provide connection_details or set the DEEPFACE_POSTGRES_URI" " environment variable." ) if isinstance(self.conn_details, str): self.conn = self.psycopg.connect(self.conn_details) elif isinstance(self.conn_details, dict): self.conn = self.psycopg.connect(**self.conn_details) else: raise ValueError("connection_details must be either a string or a dict.") # Ensure the embeddings table exists self.initialize_database() def initialize_database(self, **kwargs: Any) -> None: """ Ensure that the `embeddings` table exists. """ dsn = self.conn.info.dsn if _SCHEMA_CHECKED.get(dsn): logger.debug("PostgreSQL schema already checked, skipping.") return with self.conn.cursor() as cur: try: cur.execute(CREATE_EMBEDDINGS_TABLE_SQL) logger.debug("Ensured 'embeddings' table either exists or was created in Postgres.") cur.execute(CREATE_EMBEDDINGS_INDEX_TABLE_SQL) logger.debug( "Ensured 'embeddings_index' table either exists or was created in Postgres." ) except Exception as e: if getattr(e, "sqlstate", None) == "42501": # permission denied raise ValueError( "The PostgreSQL user does not have permission to create " "the required tables ('embeddings', 'embeddings_index'). " "Please ask your database administrator to grant CREATE privileges " "on the schema." ) from e raise self.conn.commit() _SCHEMA_CHECKED[dsn] = True def close(self) -> None: """Close the database connection.""" self.conn.close() def upsert_embeddings_index( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, index_data: bytes, ) -> None: """ Upsert embeddings index into PostgreSQL. Args: model_name (str): Name of the model. detector_backend (str): Name of the detector backend. aligned (bool): Whether the embeddings are aligned. l2_normalized (bool): Whether the embeddings are L2 normalized. index_data (bytes): Serialized index data. """ query = """ INSERT INTO embeddings_index (model_name, detector_backend, align, l2_normalized, index_data) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (model_name, detector_backend, align, l2_normalized) DO UPDATE SET index_data = EXCLUDED.index_data, updated_at = NOW() """ with self.conn.cursor() as cur: cur.execute( query, (model_name, detector_backend, aligned, l2_normalized, index_data), ) self.conn.commit() def get_embeddings_index( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, ) -> bytes: """ Get embeddings index from PostgreSQL. Args: model_name (str): Name of the model. detector_backend (str): Name of the detector backend. aligned (bool): Whether the embeddings are aligned. l2_normalized (bool): Whether the embeddings are L2 normalized. Returns: bytes: Serialized index data. """ query = """ SELECT index_data FROM embeddings_index WHERE model_name = %s AND detector_backend = %s AND align = %s AND l2_normalized = %s """ with self.conn.cursor() as cur: cur.execute( query, (model_name, detector_backend, aligned, l2_normalized), ) result = cur.fetchone() if result: return cast(bytes, result[0]) raise ValueError( "No Embeddings index found for the specified parameters " f" {model_name=}, {detector_backend=}, {aligned=}, {l2_normalized=}. " "You must run build_index first." ) def insert_embeddings(self, embeddings: List[Dict[str, Any]], batch_size: int = 100) -> int: """ Insert multiple embeddings into PostgreSQL. Args: embeddings (List[Dict[str, Any]]): List of embeddings to insert. batch_size (int): Number of embeddings to insert per batch. Returns: int: Number of embeddings inserted. """ if not embeddings: raise ValueError("No embeddings to insert.") query = """ INSERT INTO embeddings ( img_name, face, face_shape, model_name, detector_backend, aligned, l2_normalized, embedding, face_hash, embedding_hash ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s); """ values = [] for e in embeddings: face = e["face"] face_shape = list(face.shape) face_bytes = face.astype(np.float32).tobytes() face_json = json.dumps(face.tolist()) embedding_bytes = struct.pack(f'{len(e["embedding"])}d', *e["embedding"]) # uniqueness is guaranteed by face hash and embedding hash face_hash = hashlib.sha256(face_json.encode()).hexdigest() embedding_hash = hashlib.sha256(embedding_bytes).hexdigest() values.append( ( e["img_name"], face_bytes, face_shape, e["model_name"], e["detector_backend"], e["aligned"], e["l2_normalized"], e["embedding"], face_hash, embedding_hash, ) ) try: with self.conn.cursor() as cur: for i in range(0, len(values), batch_size): cur.executemany(query, values[i : i + batch_size]) # commit for every batch self.conn.commit() return len(values) except self.psycopg.errors.UniqueViolation as e: self.conn.rollback() if len(values) == 1: logger.warn("Duplicate detected for extracted face and embedding.") return 0 raise DuplicateEntryError( f"Duplicate detected for extracted face and embedding columns in {i}-th batch" ) from e def fetch_all_embeddings( self, model_name: str, detector_backend: str, aligned: bool, l2_normalized: bool, batch_size: int = 1000, ) -> List[Dict[str, Any]]: query = """ SELECT id, img_name, embedding FROM embeddings WHERE model_name = %s AND detector_backend = %s AND aligned = %s AND l2_normalized = %s ORDER BY id ASC; """ embeddings: List[Dict[str, Any]] = [] with self.conn.cursor(name="embeddings_cursor") as cur: cur.execute(query, (model_name, detector_backend, aligned, l2_normalized)) while True: batch = cur.fetchmany(batch_size) if not batch: break for r in batch: embeddings.append( { "id": r[0], "img_name": r[1], "embedding": r[2], "model_name": model_name, "detector_backend": detector_backend, "aligned": aligned, "l2_normalized": l2_normalized, } ) return embeddings def search_by_id( self, ids: Union[List[str], List[int]], ) -> List[Dict[str, Any]]: """ Search records by their IDs. """ if not ids: return [] # we may return the face in the future query = """ SELECT id, img_name FROM embeddings WHERE id = ANY(%s) ORDER BY id ASC; """ results: List[Dict[str, Any]] = [] with self.conn.cursor() as cur: cur.execute(query, (ids,)) rows = cur.fetchall() for r in rows: results.append( { "id": r[0], "img_name": r[1], } ) return results
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/database/postgres.py", "license": "MIT License", "lines": 302, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
serengil/deepface:deepface/modules/datastore.py
# built-in dependencies import os from typing import Any, Dict, IO, List, Union, Optional, cast import uuid import time import math import tempfile # 3rd party dependencies import pandas as pd import numpy as np from numpy.typing import NDArray # project dependencies from deepface.modules.database.types import Database from deepface.modules.database.inventory import database_inventory from deepface.modules.representation import represent from deepface.modules.verification import ( find_angular_distance, find_cosine_distance, find_euclidean_distance, l2_normalize as find_l2_normalize, find_threshold, find_confidence, ) from deepface.commons.logger import Logger logger = Logger() # pylint: disable=too-many-positional-arguments, no-else-return def register( img: Union[str, NDArray[Any], IO[bytes], List[str], List[NDArray[Any]], List[IO[bytes]]], img_name: Optional[str] = None, model_name: str = "VGG-Face", detector_backend: str = "opencv", enforce_detection: bool = True, align: bool = True, l2_normalize: bool = False, expand_percentage: int = 0, normalization: str = "base", anti_spoofing: bool = False, database_type: str = "postgres", connection_details: Optional[Union[Dict[str, Any], str]] = None, connection: Any = None, ) -> Dict[str, Any]: """ Register identities to database for face recognition Args: img (str or np.ndarray or IO[bytes] or list): The exact path to the image, a numpy array in BGR format, a file object that supports at least `.read` and is opened in binary mode, or a base64 encoded image. If a list is provided, each element should be a string or numpy array representing an image, and the function will process images in batch. img_name (optional str): image name to store in db, if not provided then we will try to extract it from given img. model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512, OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet (default is VGG-Face). detector_backend (string): face detector backend. Options: 'opencv', 'retinaface', 'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8n', 'yolov8m', 'yolov8l', 'yolov11n', 'yolov11s', 'yolov11m', 'yolov11l', 'yolov12n', 'yolov12s', 'yolov12m', 'yolov12l', 'centerface' or 'skip' (default is opencv). enforce_detection (boolean): If no face is detected in an image, raise an exception. Set to False to avoid the exception for low-resolution images (default is True). align (bool): Flag to enable face alignment (default is True). l2_normalize (bool): Flag to enable L2 normalization (unit vector normalization) expand_percentage (int): expand detected facial area with a percentage (default is 0). normalization (string): Normalize the input image before feeding it to the model. Options: base, raw, Facenet, Facenet2018, VGGFace, VGGFace2, ArcFace (default is base). anti_spoofing (boolean): Flag to enable anti spoofing (default is False). database_type (str): Type of database to register identities. Options: 'postgres', 'mongo', 'weaviate', 'neo4j', 'pgvector', 'pinecone' (default is 'postgres'). connection_details (dict or str): Connection details for the database. connection (Any): Existing database connection object. If provided, this connection will be used instead of creating a new one. Note: Instead of providing `connection` or `connection_details`, database connection information can be supplied via environment variables: - DEEPFACE_POSTGRES_URI - DEEPFACE_MONGO_URI - DEEPFACE_WEAVIATE_URI - DEEPFACE_NEO4J_URI - DEEPFACE_PINECONE_API_KEY Returns: result (dict): A dictionary containing registration results with following keys. - inserted (int): Number of embeddings successfully registered to the database. """ db_client = __connect_database( database_type=database_type, connection_details=connection_details, connection=connection, ) results = __get_embeddings( img=img, model_name=model_name, detector_backend=detector_backend, enforce_detection=enforce_detection, align=align, anti_spoofing=anti_spoofing, expand_percentage=expand_percentage, normalization=normalization, l2_normalize=l2_normalize, return_face=True, ) embedding_records: List[Dict[str, Any]] = [] for result in results: img_identifier = img_name or ( img if isinstance(img, str) and img.endswith((".jpg", ".jpeg", ".png")) else str(uuid.uuid4()) ) embedding_record = { "id": None, "img_name": img_identifier, "face": result["face"], "model_name": model_name, "detector_backend": detector_backend, "embedding": result["embedding"], "aligned": align, "l2_normalized": l2_normalize, } embedding_records.append(embedding_record) inserted = db_client.insert_embeddings(embedding_records, batch_size=100) logger.debug(f"Successfully registered {inserted} embeddings to the database.") # Close the database connection if it was created internally if connection is None: db_client.close() return {"inserted": inserted} def search( img: Union[str, NDArray[Any], IO[bytes], List[str], List[NDArray[Any]], List[IO[bytes]]], model_name: str = "VGG-Face", detector_backend: str = "opencv", distance_metric: str = "cosine", enforce_detection: bool = True, align: bool = True, l2_normalize: bool = False, expand_percentage: int = 0, normalization: str = "base", anti_spoofing: bool = False, similarity_search: bool = False, k: Optional[int] = None, database_type: str = "postgres", connection_details: Optional[Union[Dict[str, Any], str]] = None, connection: Any = None, search_method: str = "exact", ) -> List[pd.DataFrame]: """ Search for identities in database for face recognition. This is a stateless facial recognition function. Use find function to do it in a stateful way. Args: img (str or np.ndarray or IO[bytes] or list): The exact path to the image, a numpy array in BGR format, a file object that supports at least `.read` and is opened in binary mode, or a base64 encoded image. If a list is provided, each element should be a string or numpy array representing an image, and the function will process images in batch. model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512, OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet (default is VGG-Face). detector_backend (string): face detector backend. Options: 'opencv', 'retinaface', 'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8n', 'yolov8m', 'yolov8l', 'yolov11n', 'yolov11s', 'yolov11m', 'yolov11l', 'yolov12n', 'yolov12s', 'yolov12m', 'yolov12l', 'centerface' or 'skip' (default is opencv). distance_metric (string): Metric for measuring similarity. Options: 'cosine', 'euclidean', 'angular' (default is cosine). enforce_detection (boolean): If no face is detected in an image, raise an exception. Set to False to avoid the exception for low-resolution images (default is True). align (bool): Flag to enable face alignment (default is True). l2_normalize (bool): Flag to enable L2 normalization (unit vector normalization) expand_percentage (int): expand detected facial area with a percentage (default is 0). normalization (string): Normalize the input image before feeding it to the model. Options: base, raw, Facenet, Facenet2018, VGGFace, VGGFace2, ArcFace (default is base). anti_spoofing (boolean): Flag to enable anti spoofing (default is False). similarity_search (boolean): If False, performs identity verification and returns images of the same person. If True, performs similarity search and returns visually similar faces (e.g., celebrity or parental look-alikes). Default is False. k (int): Number of top similar faces to retrieve from the database for each detected face. If not specified, all faces within the threshold will be returned (default is None). search_method (str): Method to use for searching identities. Options: 'exact', 'ann'. To use ann search, you must run build_index function first to create the index. database_type (str): Type of database to search identities. Options: 'postgres', 'mongo', 'weaviate', 'neo4j', 'pgvector', 'pinecone' (default is 'postgres'). connection_details (dict or str): Connection details for the database. connection (Any): Existing database connection object. If provided, this connection will be used instead of creating a new one. Note: Instead of providing `connection` or `connection_details`, database connection information can be supplied via environment variables: - DEEPFACE_POSTGRES_URI - DEEPFACE_MONGO_URI - DEEPFACE_WEAVIATE_URI - DEEPFACE_NEO4J_URI - DEEPFACE_PINECONE_API_KEY Returns: results (List[pd.DataFrame]): A list of pandas dataframes or a list of dicts. Each dataframe or dict corresponds to the identity information for an individual detected in the source image. The DataFrame columns or dict keys include: - id: ID of the detected individual. - img_name: Name of the image file in the database. - model_name: Name of the model used for recognition. - aligned: Whether face alignment was performed. - l2_normalized: Whether L2 normalization was applied. - search_method: Method used for searching identities: exact or ann. - target_x, target_y, target_w, target_h: Bounding box coordinates of the target face in the database. Notice that source image's face coordinates are not included in the result here. - threshold: threshold to determine a pair whether same person or different persons - confidence: Confidence score indicating the likelihood that the images represent the same person. The score is between 0 and 100, where higher values indicate greater confidence in the verification result. - distance_metric: Distance metric used for similarity measurement. Distance metric will be ignored for ann search, and set to cosine if l2_normalize is True, euclidean if l2_normalize is False. - distance: Similarity score between the faces based on the specified model and distance metric """ dfs: List[pd.DataFrame] = [] # adjust distance metric if search_method == "ann": # ann does cosine for l2 normalized vectors, euclidean for non-l2 normalized vectors new_distance_metric = "cosine" if l2_normalize is True else "euclidean" if new_distance_metric != distance_metric: logger.warn( f"Overwriting distance_metric to '{new_distance_metric}' since " f"{'vectors are L2-norm' if l2_normalize else 'vectors are not L2-norm'}." ) distance_metric = new_distance_metric elif search_method != "exact": if l2_normalize is True and distance_metric == "euclidean": logger.warn( "Overwriting distance_metric to 'euclidean_l2' since vectors are L2 normalized." ) distance_metric = "euclidean_l2" threshold = find_threshold(model_name=model_name, distance_metric=distance_metric) db_client = __connect_database( database_type=database_type, connection_details=connection_details, connection=connection, ) results = __get_embeddings( img=img, model_name=model_name, detector_backend=detector_backend, enforce_detection=enforce_detection, align=align, anti_spoofing=anti_spoofing, expand_percentage=expand_percentage, normalization=normalization, l2_normalize=l2_normalize, return_face=False, ) is_vector_db = database_inventory[database_type]["is_vector_db"] if search_method == "ann" and is_vector_db is False: try: import faiss except ImportError as e: raise ValueError( "faiss is not installed. Please install faiss to use approximate nearest neighbour." ) from e embeddings_index_bytes = db_client.get_embeddings_index( model_name=model_name, detector_backend=detector_backend, aligned=align, l2_normalized=l2_normalize, ) embeddings_index_buffer = np.frombuffer(embeddings_index_bytes, dtype=np.uint8) embeddings_index = faiss.deserialize_index(embeddings_index_buffer) logger.info("Loaded embeddings index from database.") for result in results: query_vector = np.array(result["embedding"], dtype="float32").reshape(1, -1) distances, indices = embeddings_index.search(query_vector, k or 20) instances = [] for i, index in enumerate(indices[0]): distance = ( math.sqrt(distances[0][i]) if distance_metric == "euclidean" else distances[0][i] / 2 ) verified = bool(distance <= threshold) instance = { "id": index, # "img_name": "N/A", # need to fetch from DB if required "model_name": model_name, "detector_backend": detector_backend, "aligned": align, "l2_normalized": l2_normalize, "search_method": search_method, "target_x": result.get("facial_area", {}).get("x", None), "target_y": result.get("facial_area", {}).get("y", None), "target_w": result.get("facial_area", {}).get("w", None), "target_h": result.get("facial_area", {}).get("h", None), "threshold": threshold, "distance_metric": distance_metric, "distance": distance, "confidence": find_confidence( distance=distance, model_name=model_name, distance_metric=distance_metric, verified=verified, ), } if similarity_search is False and verified: instances.append(instance) if len(instances) == 0: continue df = pd.DataFrame(instances) df = df.sort_values(by="distance", ascending=True).reset_index(drop=True) if k is not None and k > 0: df = df.nsmallest(k, "distance") # we should query DB to get img_name for each id id_mappings = db_client.search_by_id(ids=df["id"].tolist()) ids_df = pd.DataFrame(id_mappings, columns=["id", "img_name"]) df = df.merge(ids_df, on="id", how="left") del ids_df dfs.append(df) return dfs elif search_method == "ann" and is_vector_db is True: for result in results: target_vector: List[float] = result["embedding"] neighbours = db_client.search_by_vector( vector=target_vector, model_name=model_name, detector_backend=detector_backend, aligned=align, l2_normalized=l2_normalize, limit=k or 20, ) if not neighbours: raise ValueError( "No embeddings found in the database for the criteria " f"{model_name=}, {detector_backend=}, {align=}, {l2_normalize=}." "You must call register some embeddings to the database before using search." ) instances = [] for neighbour in neighbours: distance = neighbour["distance"] verified = bool(distance <= threshold) instance = { "id": neighbour["id"], "img_name": neighbour["img_name"], "model_name": model_name, "detector_backend": detector_backend, "aligned": align, "l2_normalized": l2_normalize, "search_method": search_method, "target_x": result.get("facial_area", {}).get("x", None), "target_y": result.get("facial_area", {}).get("y", None), "target_w": result.get("facial_area", {}).get("w", None), "target_h": result.get("facial_area", {}).get("h", None), "threshold": threshold, "distance_metric": distance_metric, "distance": distance, "confidence": find_confidence( distance=distance, model_name=model_name, distance_metric=distance_metric, verified=verified, ), } if similarity_search is False and verified: instances.append(instance) if len(instances) > 0: df = pd.DataFrame(instances) df = df.sort_values(by="distance", ascending=True).reset_index(drop=True) if k is not None and k > 0: df = df.nsmallest(k, "distance") dfs.append(df) return dfs elif search_method == "exact": source_embeddings = db_client.fetch_all_embeddings( model_name=model_name, detector_backend=detector_backend, aligned=align, l2_normalized=l2_normalize, ) if not source_embeddings: raise ValueError( "No embeddings found in the database for the criteria " f"{model_name=}, {detector_backend=}, {align=}, {l2_normalize=}." "You must call register some embeddings to the database before using search." ) for result in results: target_embedding = cast(List[float], result["embedding"]) df = pd.DataFrame(source_embeddings) df["target_embedding"] = [target_embedding for _ in range(len(df))] df["search_method"] = search_method df["target_x"] = result.get("facial_area", {}).get("x", None) df["target_y"] = result.get("facial_area", {}).get("y", None) df["target_w"] = result.get("facial_area", {}).get("w", None) df["target_h"] = result.get("facial_area", {}).get("h", None) df["threshold"] = threshold df["distance_metric"] = distance_metric if distance_metric == "cosine": df["distance"] = df.apply( lambda row: find_cosine_distance(row["embedding"], row["target_embedding"]), axis=1, ) elif distance_metric == "euclidean": df["distance"] = df.apply( lambda row: find_euclidean_distance(row["embedding"], row["target_embedding"]), axis=1, ) elif distance_metric == "angular": df["distance"] = df.apply( lambda row: find_angular_distance(row["embedding"], row["target_embedding"]), axis=1, ) elif distance_metric == "euclidean_l2": df["distance"] = df.apply( lambda row: find_euclidean_distance( find_l2_normalize(row["embedding"]), find_l2_normalize(row["target_embedding"]), ), axis=1, ) else: raise ValueError(f"Unsupported distance metric: {distance_metric}") df["confidence"] = df.apply( lambda row: find_confidence( distance=row["distance"], model_name=model_name, distance_metric=distance_metric, verified=bool(row["distance"] <= threshold), ), axis=1, ) df = df.drop(columns=["embedding", "target_embedding"]) if similarity_search is False: df = df[df["distance"] <= threshold] if k is not None and k > 0: df = df.nsmallest(k, "distance") df = df.sort_values(by="distance", ascending=True).reset_index(drop=True) dfs.append(df) return dfs else: raise ValueError(f"Unsupported search method: {search_method}") def build_index( model_name: str = "VGG-Face", detector_backend: str = "opencv", align: bool = True, l2_normalize: bool = False, database_type: str = "postgres", connection_details: Optional[Union[Dict[str, Any], str]] = None, connection: Any = None, batch_size: int = 1000, max_neighbors_per_node: int = 32, ) -> None: """ Build index for faster search in the database. You should set search_method to 'ann' in the search function to use the built index. Args: model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512, OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet (default is VGG-Face). detector_backend (string): face detector backend. Options: 'opencv', 'retinaface', 'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8n', 'yolov8m', 'yolov8l', 'yolov11n', 'yolov11s', 'yolov11m', 'yolov11l', 'yolov12n', 'yolov12s', 'yolov12m', 'yolov12l', 'centerface' or 'skip' (default is opencv). align (bool): Flag to enable face alignment (default is True). l2_normalize (bool): Flag to enable L2 normalization (unit vector normalization) max_neighbors_per_node (int): Maximum number of neighbors per node in the index (default is 32). database_type (str): Type of database to build index. Options: 'postgres', 'mongo', 'weaviate', 'neo4j', 'pgvector', 'pinecone' (default is 'postgres'). connection (Any): Existing database connection object. If provided, this connection will be used instead of creating a new one. connection_details (dict or str): Connection details for the database. Note: Instead of providing `connection` or `connection_details`, database connection information can be supplied via environment variables: - DEEPFACE_POSTGRES_URI - DEEPFACE_MONGO_URI - DEEPFACE_WEAVIATE_URI - DEEPFACE_NEO4J_URI - DEEPFACE_PINECONE_API_KEY """ if database_inventory.get(database_type) is None: raise ValueError(f"Unsupported database type: {database_type}") is_vector_db = database_inventory[database_type]["is_vector_db"] if is_vector_db is True: logger.info(f"{database_type} manages its own indexes. No need to build index manually.") return try: import faiss except ImportError as e: raise ValueError("faiss is not installed. Please install faiss to use build_index.") from e db_client = __connect_database( database_type=database_type, connection_details=connection_details, connection=connection, ) index = __get_index( db_client=db_client, model_name=model_name, detector_backend=detector_backend, align=align, l2_normalize=l2_normalize, ) if index is not None: indexed_indices = faiss.vector_to_array(index.id_map) indexed_embeddings = set(indexed_indices) logger.info(f"Found {len(indexed_embeddings)} embeddings already indexed in the database.") else: logger.info("No existing index found in the database. A new index will be created.") indexed_embeddings = set() tic = time.time() source_embeddings = db_client.fetch_all_embeddings( model_name=model_name, detector_backend=detector_backend, aligned=align, l2_normalized=l2_normalize, ) toc = time.time() if not source_embeddings: raise ValueError( "No embeddings found in the database for the criteria " f"{model_name=}, {detector_backend=}, {align=}, {l2_normalize=}." "You must call register some embeddings to the database before using build_index." ) logger.info( f"Fetched {len(source_embeddings)} embeddings from database in {toc - tic:.2f} seconds." ) unindexed_source_embeddings = [ item for item in source_embeddings if item["id"] not in indexed_embeddings ] if not unindexed_source_embeddings: logger.info("All embeddings are already indexed. No new embeddings to index.") return ids = [item["id"] for item in unindexed_source_embeddings] vectors = np.array([item["embedding"] for item in unindexed_source_embeddings], dtype="float32") embedding_dim_size = len(source_embeddings[0]["embedding"]) if index is None: base_index = faiss.IndexHNSWFlat(embedding_dim_size, max_neighbors_per_node) index = faiss.IndexIDMap(base_index) tic = time.time() for i in range(0, len(vectors), batch_size): batch_ids = np.array(ids[i : i + batch_size], dtype="int64") batch_vectors = vectors[i : i + batch_size] index.add_with_ids(batch_vectors, batch_ids) toc = time.time() logger.info(f"Added {len(vectors)} embeddings to index in {toc - tic:.2f} seconds.") index_path = os.path.join( tempfile.gettempdir(), f"{model_name}_{detector_backend}_{align}_{l2_normalize}.faiss" ) # now create index from scratch, then think how to load an index and add new vectors to it tic = time.time() faiss.write_index(index, index_path) toc = time.time() logger.info(f"Saved index to disk in {toc - tic:.2f} seconds") with open(index_path, "rb") as f: index_data = f.read() tic = time.time() db_client.upsert_embeddings_index( model_name=model_name, detector_backend=detector_backend, aligned=align, l2_normalized=l2_normalize, index_data=index_data, ) toc = time.time() logger.info(f"Upserted index to database in {toc - tic:.2f} seconds.") # clean up temp file if os.path.exists(index_path): os.remove(index_path) def __get_embeddings( img: Union[str, NDArray[Any], IO[bytes], List[str], List[NDArray[Any]], List[IO[bytes]]], model_name: str = "VGG-Face", detector_backend: str = "opencv", enforce_detection: bool = True, align: bool = True, l2_normalize: bool = False, expand_percentage: int = 0, normalization: str = "base", anti_spoofing: bool = False, return_face: bool = True, ) -> List[Dict[str, Any]]: """ Get embeddings for given image(s) Args: img (str or np.ndarray or IO[bytes] or list): The exact path to the image, a numpy array in BGR format, a file object that supports at least `.read` and is opened in binary mode, or a base64 encoded image. If a list is provided, each element should be a string or numpy array representing an image, and the function will process images in batch. model_name (str): Model for face recognition. Options: VGG-Face, Facenet, Facenet512, OpenFace, DeepFace, DeepID, Dlib, ArcFace, SFace and GhostFaceNet (default is VGG-Face). detector_backend (string): face detector backend. Options: 'opencv', 'retinaface', 'mtcnn', 'ssd', 'dlib', 'mediapipe', 'yolov8n', 'yolov8m', 'yolov8l', 'yolov11n', 'yolov11s', 'yolov11m', 'yolov11l', 'yolov12n', 'yolov12s', 'yolov12m', 'yolov12l', 'centerface' or 'skip' (default is opencv). enforce_detection (boolean): If no face is detected in an image, raise an exception. Set to False to avoid the exception for low-resolution images (default is True). align (bool): Flag to enable face alignment (default is True). l2_normalize (bool): Flag to enable L2 normalization (unit vector normalization) expand_percentage (int): expand detected facial area with a percentage (default is 0). normalization (string): Normalize the input image before feeding it to the model. Options: base, raw, Facenet, Facenet2018, VGGFace, VGGFace2, ArcFace (default is base). anti_spoofing (boolean): Flag to enable anti spoofing (default is False). return_face (bool): Whether to return the aligned face along with the embedding (default is True). Returns: results (List[Dict]): A list of dictionaries containing embeddings and optionally aligned face images for each detected face in the input image(s). """ results = represent( img_path=img, model_name=model_name, detector_backend=detector_backend, enforce_detection=enforce_detection, align=align, anti_spoofing=anti_spoofing, expand_percentage=expand_percentage, normalization=normalization, l2_normalize=l2_normalize, return_face=return_face, ) if len(results) == 0: raise ValueError("No embeddings were detected in the provided image(s).") flat_results: List[Dict[str, Any]] = [] for result in results: if isinstance(result, dict): flat_results.append(result) elif isinstance(result, list): flat_results.extend(result) return flat_results def __connect_database( database_type: str = "postgres", connection_details: Optional[Union[Dict[str, Any], str]] = None, connection: Any = None, ) -> Database: """ Connect to the specified database type Args: database_type (str): Type of database to connect. Options: 'postgres', 'mongo', 'weaviate', 'neo4j', 'pgvector', 'pinecone' (default is 'postgres'). connection_details (dict or str): Connection details for the database. connection (Any): Existing database connection object. If provided, this connection will be used instead of creating a new one. Note: Instead of providing `connection` or `connection_details`, database connection information can be supplied via environment variables: - DEEPFACE_POSTGRES_URI - DEEPFACE_MONGO_URI - DEEPFACE_WEAVIATE_URI - DEEPFACE_NEO4J_URI - DEEPFACE_PINECONE_API_KEY Returns: db_client (Database): An instance of the connected database client. """ if database_inventory.get(database_type) is None: raise ValueError(f"Unsupported database type: {database_type}") client_class = database_inventory[database_type]["client"] return client_class(connection_details=connection_details, connection=connection) def __get_index( db_client: Database, model_name: str, detector_backend: str, align: bool, l2_normalize: bool, ) -> Any: """ Retrieve the embeddings index from the database Args: db_client (Database): An instance of the connected database client. model_name (str): Model for face recognition. detector_backend (string): face detector backend. align (bool): Flag to enable face alignment. l2_normalize (bool): Flag to enable L2 normalization (unit vector normalization) Returns: embeddings_index (Any): The deserialized embeddings index object, or None if not found. """ import faiss try: embeddings_index_bytes = db_client.get_embeddings_index( model_name=model_name, detector_backend=detector_backend, aligned=align, l2_normalized=l2_normalize, ) embeddings_index_buffer = np.frombuffer(embeddings_index_bytes, dtype=np.uint8) embeddings_index = faiss.deserialize_index(embeddings_index_buffer) return embeddings_index except ValueError: return None
{ "repo_id": "serengil/deepface", "file_path": "deepface/modules/datastore.py", "license": "MIT License", "lines": 674, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex