mirror of
https://github.com/guezoloic/millesima_projetS6.git
synced 2026-03-29 11:33:43 +00:00
Compare commits
37 Commits
0f6eb856c6
...
jalon3
| Author | SHA1 | Date | |
|---|---|---|---|
| 68dffa6486 | |||
| c7d2077b23 | |||
| 106877a073 | |||
|
|
416cfcbf8b | ||
| 32c5310e37 | |||
| 9dfc7457a0 | |||
| f5d5703e49 | |||
| 888defb6b6 | |||
| 734e3898e9 | |||
| 4bb3112dd0 | |||
| 54e4b7860b | |||
| b865a59aba | |||
|
|
fde1f36148 | ||
| 6fbb36ea37 | |||
| 4b3c3c26e8 | |||
|
|
bcacd7a915 | ||
| de1d325fb7 | |||
| f4ded6d8b5 | |||
| acf4ddd881 | |||
| 69b8b4ce1f | |||
| 8047b06253 | |||
| 5303d36988 | |||
|
|
d182e08f9b | ||
| 0d96ff7714 | |||
| ebd9d15f77 | |||
| 8a888f583c | |||
|
|
cefdb94dd5 | ||
|
|
06097c257e | ||
|
|
b0eb5df07e | ||
| e6c649b433 | |||
| 3619890dc4 | |||
| 123c43aa05 | |||
| a163e7687f | |||
|
|
5afb6e38fe | ||
|
|
f31de22693 | ||
|
|
73c6221080 | ||
|
|
99dd71989d |
18
.github/dependabot.yml
vendored
Normal file
18
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# To get started with Dependabot version updates, you'll need to specify which
|
||||||
|
# package ecosystems to update and where the package manifests are located.
|
||||||
|
# Please see the documentation for all configuration options:
|
||||||
|
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||||
|
|
||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "pip"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "weekly"
|
||||||
|
day: "saturday"
|
||||||
|
open-pull-requests-limit: 5
|
||||||
|
groups:
|
||||||
|
python-dependencies:
|
||||||
|
patterns:
|
||||||
|
- "*"
|
||||||
|
|
||||||
45
.github/workflows/python-app.yml
vendored
45
.github/workflows/python-app.yml
vendored
@@ -5,35 +5,34 @@ name: Python application
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ "main" ]
|
branches: ["main"]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ "main" ]
|
branches: ["main"]
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Set up Python 3.10
|
|
||||||
uses: actions/setup-python@v3
|
- name: Set up Python 3.x
|
||||||
with:
|
uses: actions/setup-python@v4
|
||||||
python-version: "3.10"
|
with:
|
||||||
- name: Install dependencies
|
python-version: "3.x"
|
||||||
run: |
|
|
||||||
python -m pip install --upgrade pip
|
- name: install dependencies
|
||||||
pip install flake8 pytest
|
run: |
|
||||||
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
python -m pip install --upgrade pip
|
||||||
- name: Lint with flake8
|
pip install ".[test]"
|
||||||
run: |
|
|
||||||
# stop the build if there are Python syntax errors or undefined names
|
- name: Lint with flake8
|
||||||
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
|
run: |
|
||||||
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
|
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
|
||||||
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
|
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
|
||||||
- name: Test with pytest
|
|
||||||
run: |
|
- name: Test with pytest
|
||||||
pytest
|
run: pytest
|
||||||
|
|||||||
57
.github/workflows/static.yml
vendored
Normal file
57
.github/workflows/static.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
# Simple workflow for deploying static content to GitHub Pages
|
||||||
|
name: Deploy static content to Pages
|
||||||
|
|
||||||
|
on:
|
||||||
|
# Runs on pushes targeting the default branch
|
||||||
|
push:
|
||||||
|
branches: ["main"]
|
||||||
|
|
||||||
|
# Allows you to run this workflow manually from the Actions tab
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pages: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
|
||||||
|
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
|
||||||
|
concurrency:
|
||||||
|
group: "pages"
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# Single deploy job since we're just deploying
|
||||||
|
deploy:
|
||||||
|
environment:
|
||||||
|
name: github-pages
|
||||||
|
url: ${{ steps.deployment.outputs.page_url }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python 3.x
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.x'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install -e ".[doc]"
|
||||||
|
|
||||||
|
- name: Setup Pages
|
||||||
|
uses: actions/configure-pages@v5
|
||||||
|
|
||||||
|
- name: Build Documentation
|
||||||
|
run: mkdocs build
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-pages-artifact@v3
|
||||||
|
with:
|
||||||
|
# Upload entire repository
|
||||||
|
path: './site'
|
||||||
|
- name: Deploy to GitHub Pages
|
||||||
|
id: deployment
|
||||||
|
uses: actions/deploy-pages@v4
|
||||||
38
README.md
38
README.md
@@ -1 +1,37 @@
|
|||||||
# millesima_projetS6
|
# Millesima AI Engine 🍷
|
||||||
|
|
||||||
|
> A **University of Paris-Est Créteil (UPEC)** Semester 6 project.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
- 🇫🇷 [Version Française](https://guezoloic.github.io/millesima-ai-engine)
|
||||||
|
> note: only french version enabled for now.
|
||||||
|
---
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
> Make sure you have **Python 3.10+** installed.
|
||||||
|
|
||||||
|
1. **Clone the repository:**
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/votre-pseudo/millesima-ai-engine.git
|
||||||
|
cd millesima-ai-engine
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Set up a virtual environment:**
|
||||||
|
```bash
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Install dependencies:**
|
||||||
|
```bash
|
||||||
|
pip install -e .
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### 1. Data Extraction (Scraping)
|
||||||
|
To fetch the latest wine data from Millesima:
|
||||||
|
```bash
|
||||||
|
python3 src/scraper.py
|
||||||
|
```
|
||||||
|
> Note: that will take some time to fetch all data depending on the catalog size.
|
||||||
17
docs/cleaning.md
Normal file
17
docs/cleaning.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Cleaning
|
||||||
|
|
||||||
|
## Sommaire
|
||||||
|
[TOC]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Classe `Cleaning`
|
||||||
|
::: src.cleaning.Cleaning
|
||||||
|
options:
|
||||||
|
heading_level: 3
|
||||||
|
members:
|
||||||
|
- __init__
|
||||||
|
- getVins
|
||||||
|
- drop_empty_appellation
|
||||||
|
- fill_missing_scores
|
||||||
|
- encode_appellation
|
||||||
16
docs/index.md
Normal file
16
docs/index.md
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# Millesima
|
||||||
|
|
||||||
|
L’objectif de ce projet est d’étudier, en utilisant des méthodes d’apprentissage automatique, l’impact de différents critères (notes des critiques, appelation) sur le prix d’un vin. Pour ce faire, on s’appuiera sur le site Millesima (https://www.millesima.fr/), qui a l’avantage de ne pas posséder de protection contre les bots. Par respect pour l’hébergeur du site, on veillera à limiter au maximum le nombre de requêtes. En particulier, on s’assurera d’avoir un code fonctionnel avant de scraper l’intégralité du site, pour éviter les répétitions.
|
||||||
|
|
||||||
|
## projet
|
||||||
|
<div style="text-align: center;">
|
||||||
|
<object
|
||||||
|
data="/millesima-ai-engine/projet.pdf"
|
||||||
|
type="application/pdf"
|
||||||
|
width="100%"
|
||||||
|
height="1000px"
|
||||||
|
>
|
||||||
|
<p>Votre navigateur ne peut pas afficher ce PDF.
|
||||||
|
<a href="/millesima-ai-engine/projet.pdf">Cliquez ici pour le télécharger.</a></p>
|
||||||
|
</object>
|
||||||
|
</div>
|
||||||
Binary file not shown.
31
docs/scraper.md
Normal file
31
docs/scraper.md
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
# Scraper
|
||||||
|
|
||||||
|
## Sommaire
|
||||||
|
[TOC]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Classe `Scraper`
|
||||||
|
::: scraper.Scraper
|
||||||
|
options:
|
||||||
|
members:
|
||||||
|
- __init__
|
||||||
|
- getvins
|
||||||
|
- getjsondata
|
||||||
|
- getresponse
|
||||||
|
- getsoup
|
||||||
|
heading_level: 4
|
||||||
|
|
||||||
|
## Classe `_ScraperData`
|
||||||
|
::: scraper._ScraperData
|
||||||
|
options:
|
||||||
|
members:
|
||||||
|
- __init__
|
||||||
|
- getdata
|
||||||
|
- appellation
|
||||||
|
- parker
|
||||||
|
- robinson
|
||||||
|
- suckling
|
||||||
|
- prix
|
||||||
|
- informations
|
||||||
|
heading_level: 4
|
||||||
387
learning.ipynb
Normal file
387
learning.ipynb
Normal file
File diff suppressed because one or more lines are too long
20
mkdocs.yml
Normal file
20
mkdocs.yml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
site_name: "Projet Millesima S6"
|
||||||
|
site_url: "https://github.guezoloic.com/millesima-ai-engine/"
|
||||||
|
|
||||||
|
theme:
|
||||||
|
name: "material"
|
||||||
|
|
||||||
|
plugins:
|
||||||
|
- search
|
||||||
|
- mkdocstrings
|
||||||
|
|
||||||
|
extra:
|
||||||
|
generator: false
|
||||||
|
|
||||||
|
copyright: "Loïc GUEZO & Chahrazad DAHMANI – UPEC S6 – 2026"
|
||||||
|
|
||||||
|
markdown_extensions:
|
||||||
|
- admonition
|
||||||
|
- pymdownx.details
|
||||||
|
- pymdownx.superfences
|
||||||
|
- pymdownx.tabbed
|
||||||
@@ -5,11 +5,19 @@ dependencies = [
|
|||||||
"requests==2.32.5",
|
"requests==2.32.5",
|
||||||
"beautifulsoup4==4.14.3",
|
"beautifulsoup4==4.14.3",
|
||||||
"pandas==2.3.3",
|
"pandas==2.3.3",
|
||||||
|
"tqdm==4.67.3",
|
||||||
|
"scikit-learn==1.7.2",
|
||||||
|
"matplotlib==3.10.8"
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
pythonpath = "src"
|
||||||
|
testpaths = ["tests"]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
test = ["pytest==8.4.2", "requests-mock==1.12.1"]
|
test = ["pytest==8.4.2", "requests-mock==1.12.1", "flake8==7.3.0"]
|
||||||
|
doc = ["mkdocs<2.0.0", "mkdocs-material==9.6.23", "mkdocstrings[python]"]
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["setuptools"]
|
requires = ["setuptools", "wheel"]
|
||||||
build-backend = "setuptools.build_meta"
|
build-backend = "setuptools.build_meta"
|
||||||
119
src/cleaning.py
Executable file
119
src/cleaning.py
Executable file
@@ -0,0 +1,119 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from os import getcwd
|
||||||
|
from os.path import normpath, join
|
||||||
|
from typing import cast
|
||||||
|
from pandas import DataFrame, read_csv, to_numeric, get_dummies
|
||||||
|
from sys import argv
|
||||||
|
|
||||||
|
|
||||||
|
def path_filename(filename: str) -> str:
|
||||||
|
return normpath(join(getcwd(), filename))
|
||||||
|
|
||||||
|
|
||||||
|
class Cleaning:
|
||||||
|
def __init__(self, filename) -> None:
|
||||||
|
self._vins: DataFrame = read_csv(filename)
|
||||||
|
# créer la liste de tout les scores
|
||||||
|
self.SCORE_COLS: list[str] = [
|
||||||
|
c for c in self._vins.columns if c not in ["Appellation", "Prix"]
|
||||||
|
]
|
||||||
|
# transforme tout les colonnes score en numérique
|
||||||
|
for col in self.SCORE_COLS:
|
||||||
|
self._vins[col] = to_numeric(self._vins[col], errors="coerce")
|
||||||
|
|
||||||
|
def getVins(self) -> DataFrame:
|
||||||
|
return self._vins.copy(deep=True)
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
"""
|
||||||
|
Affiche un résumé du DataFrame
|
||||||
|
- la taille
|
||||||
|
- types des colonnes
|
||||||
|
- valeurs manquantes
|
||||||
|
- statistiques numériques
|
||||||
|
"""
|
||||||
|
return (
|
||||||
|
f"Shape : {self._vins.shape[0]} lignes x {self._vins.shape[1]} colonnes\n\n"
|
||||||
|
f"Types des colonnes :\n{self._vins.dtypes}\n\n"
|
||||||
|
f"Valeurs manquantes :\n{self._vins.isna().sum()}\n\n"
|
||||||
|
f"Statistiques numériques :\n{self._vins.describe().round(2)}\n\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def drop_empty_appellation(self) -> "Cleaning":
|
||||||
|
self._vins = self._vins.dropna(subset=["Appellation"])
|
||||||
|
return self
|
||||||
|
|
||||||
|
def _mean_score(self, col: str) -> DataFrame:
|
||||||
|
"""
|
||||||
|
Calcule la moyenne d'une colonne de score par appellation.
|
||||||
|
- Convertit les valeurs en numériques, en remplaçant les non-convertibles par NaN
|
||||||
|
- Calcule la moyenne par appellation
|
||||||
|
- Remplace les NaN résultants par 0
|
||||||
|
|
||||||
|
"""
|
||||||
|
means = self._vins.groupby("Appellation", as_index=False)[col].mean()
|
||||||
|
means = means.rename(
|
||||||
|
columns={col: f"mean_{col}"}
|
||||||
|
) # pyright: ignore[reportCallIssue]
|
||||||
|
return cast(DataFrame, means.fillna(0))
|
||||||
|
|
||||||
|
def _mean_robert(self) -> DataFrame:
|
||||||
|
return self._mean_score("Robert")
|
||||||
|
|
||||||
|
def _mean_robinson(self) -> DataFrame:
|
||||||
|
return self._mean_score("Robinson")
|
||||||
|
|
||||||
|
def _mean_suckling(self) -> DataFrame:
|
||||||
|
return self._mean_score("Suckling")
|
||||||
|
|
||||||
|
def fill_missing_scores(self) -> "Cleaning":
|
||||||
|
"""
|
||||||
|
Remplacer les notes manquantes par la moyenne
|
||||||
|
des vins de la même appellation.
|
||||||
|
"""
|
||||||
|
for element in self.SCORE_COLS:
|
||||||
|
means = self._mean_score(element)
|
||||||
|
self._vins = self._vins.merge(means, on="Appellation", how="left")
|
||||||
|
|
||||||
|
mean_col = f"mean_{element}"
|
||||||
|
self._vins[element] = self._vins[element].fillna(self._vins[mean_col])
|
||||||
|
|
||||||
|
self._vins = self._vins.drop(columns=["mean_" + element])
|
||||||
|
return self
|
||||||
|
|
||||||
|
def encode_appellation(self, column: str = "Appellation") -> "Cleaning":
|
||||||
|
"""
|
||||||
|
Remplace la colonne 'Appellation' par des colonnes indicatrices
|
||||||
|
"""
|
||||||
|
appellations = self._vins[column].astype(str).str.strip()
|
||||||
|
appellation_dummies = get_dummies(appellations, prefix="App")
|
||||||
|
self._vins = self._vins.drop(columns=[column])
|
||||||
|
self._vins = self._vins.join(appellation_dummies)
|
||||||
|
return self
|
||||||
|
|
||||||
|
def drop_empty_price(self) -> "Cleaning":
|
||||||
|
self._vins = self._vins.dropna(subset=["Prix"])
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
if len(argv) != 2:
|
||||||
|
raise ValueError(f"Usage: {argv[0]} <filename.csv>")
|
||||||
|
|
||||||
|
filename = argv[1]
|
||||||
|
cleaning: Cleaning = (
|
||||||
|
Cleaning(filename)
|
||||||
|
.drop_empty_appellation()
|
||||||
|
.fill_missing_scores()
|
||||||
|
.encode_appellation()
|
||||||
|
.drop_empty_price()
|
||||||
|
)
|
||||||
|
cleaning.getVins().to_csv("clean.csv", index=False)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"ERREUR: {e}")
|
||||||
93
src/learning.py
Executable file
93
src/learning.py
Executable file
@@ -0,0 +1,93 @@
|
|||||||
|
|
||||||
|
|
||||||
|
from typing import Any, Callable
|
||||||
|
from pandas import DataFrame
|
||||||
|
from sklearn.linear_model import LinearRegression
|
||||||
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
from sklearn.model_selection import train_test_split
|
||||||
|
from sklearn.pipeline import make_pipeline
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
from cleaning import Cleaning
|
||||||
|
|
||||||
|
|
||||||
|
class Learning:
|
||||||
|
def __init__(self, vins: DataFrame, target: str) -> None:
|
||||||
|
self.X = vins.drop(target, axis=1)
|
||||||
|
self.y = vins[target]
|
||||||
|
|
||||||
|
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(
|
||||||
|
self.X, self.y, test_size=0.25, random_state=49
|
||||||
|
)
|
||||||
|
|
||||||
|
def evaluate(
|
||||||
|
self,
|
||||||
|
estimator,
|
||||||
|
pretreatment=None,
|
||||||
|
fn_score=lambda m, xt, yt: m.score(xt, yt),
|
||||||
|
):
|
||||||
|
|
||||||
|
pipeline = make_pipeline(pretreatment, estimator) if pretreatment else estimator
|
||||||
|
pipeline.fit(self.X_train, self.y_train)
|
||||||
|
score = fn_score(pipeline, self.X_test, self.y_test)
|
||||||
|
prediction = pipeline.predict(self.X_test)
|
||||||
|
|
||||||
|
return score, prediction
|
||||||
|
|
||||||
|
def draw(self, predictions, y_actual):
|
||||||
|
plt.figure(figsize=(8, 6))
|
||||||
|
|
||||||
|
plt.scatter(
|
||||||
|
predictions,
|
||||||
|
y_actual,
|
||||||
|
alpha=0.5,
|
||||||
|
c="royalblue",
|
||||||
|
edgecolors="k",
|
||||||
|
label="Vins",
|
||||||
|
)
|
||||||
|
|
||||||
|
mn = min(predictions.min(), y_actual.min())
|
||||||
|
mx = max(predictions.max(), y_actual.max())
|
||||||
|
plt.plot(
|
||||||
|
[mn, mx],
|
||||||
|
[mn, mx],
|
||||||
|
color="red",
|
||||||
|
linestyle="--",
|
||||||
|
lw=2,
|
||||||
|
label="Prédiction Parfaite",
|
||||||
|
)
|
||||||
|
|
||||||
|
plt.xlabel("Prix estimés (estim_LR)")
|
||||||
|
plt.ylabel("Prix réels (y_test)")
|
||||||
|
plt.title("titre")
|
||||||
|
plt.legend()
|
||||||
|
plt.grid(True, linestyle=":", alpha=0.6)
|
||||||
|
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
|
||||||
|
df_vins = (
|
||||||
|
Cleaning("data.csv")
|
||||||
|
.drop_empty_appellation()
|
||||||
|
.fill_missing_scores()
|
||||||
|
.encode_appellation()
|
||||||
|
.drop_empty_price()
|
||||||
|
.getVins()
|
||||||
|
)
|
||||||
|
|
||||||
|
etude = Learning(df_vins, target="Prix")
|
||||||
|
|
||||||
|
print("--- Question 16 & 17 ---")
|
||||||
|
score_simple, estim_simple = etude.evaluate(LinearRegression())
|
||||||
|
print(f"Score R² (LR Simple) : {score_simple:.4f}")
|
||||||
|
|
||||||
|
etude.draw(estim_simple, etude.y_test)
|
||||||
|
|
||||||
|
|
||||||
|
print("\n--- Question 18 ---")
|
||||||
|
score_std, estim_std = etude.evaluate(
|
||||||
|
estimator=LinearRegression(), pretreatment=StandardScaler()
|
||||||
|
)
|
||||||
|
print(f"Score R² (Standardisation + LR) : {score_std:.4f}")
|
||||||
|
|
||||||
|
etude.draw(estim_std, etude.y_test)
|
||||||
20
src/main.py
20
src/main.py
@@ -1,20 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
|
|
||||||
from os import getcwd
|
|
||||||
from os.path import normpath, join
|
|
||||||
from sys import argv
|
|
||||||
from pandas import read_csv, DataFrame
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
if len(argv) != 2:
|
|
||||||
raise ValueError(f"{argv[0]} <filename.csv>")
|
|
||||||
|
|
||||||
path: str = normpath(join(getcwd(), argv[1]))
|
|
||||||
db: DataFrame = read_csv(path)
|
|
||||||
print(db.all())
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except Exception as e:
|
|
||||||
print(f"ERREUR: {e}")
|
|
||||||
306
src/scraper.py
306
src/scraper.py
@@ -1,29 +1,78 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
from sys import argv
|
|
||||||
from typing import cast
|
|
||||||
from requests import HTTPError, Response, Session
|
|
||||||
from bs4 import BeautifulSoup, Tag
|
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
from io import SEEK_END, SEEK_SET, BufferedWriter, TextIOWrapper
|
||||||
from json import JSONDecodeError, loads
|
from json import JSONDecodeError, loads
|
||||||
|
from os import makedirs
|
||||||
|
from os.path import dirname, exists, join, normpath, realpath
|
||||||
|
from pickle import UnpicklingError, dump, load
|
||||||
|
from sys import argv
|
||||||
|
from tqdm.std import tqdm
|
||||||
|
from typing import Any, Callable, Literal, TypeVar, cast
|
||||||
|
from bs4 import BeautifulSoup, Tag
|
||||||
|
from requests import HTTPError, Response, Session
|
||||||
|
|
||||||
|
_dir: str = dirname(realpath(__name__))
|
||||||
|
|
||||||
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
|
||||||
|
def _getcache(mode: Literal["rb", "wb"], fn: Callable[[Any], T]) -> T | None:
|
||||||
|
"""_summary_
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
_type_: _description_
|
||||||
|
"""
|
||||||
|
cache_dirname = normpath(join(_dir, ".cache"))
|
||||||
|
save_path = normpath(join(cache_dirname, "save"))
|
||||||
|
|
||||||
|
if not exists(cache_dirname):
|
||||||
|
makedirs(cache_dirname)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(save_path, mode) as f:
|
||||||
|
return fn(f)
|
||||||
|
except (FileNotFoundError, EOFError, UnpicklingError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def savestate(data: tuple[int, set[str]]) -> None:
|
||||||
|
def save(f: BufferedWriter) -> None:
|
||||||
|
_ = f.seek(0)
|
||||||
|
_ = f.truncate()
|
||||||
|
dump(data, f)
|
||||||
|
f.flush()
|
||||||
|
|
||||||
|
_getcache("wb", save)
|
||||||
|
|
||||||
|
|
||||||
|
def loadstate() -> tuple[int, set[str]] | None:
|
||||||
|
return _getcache("rb", lambda f: load(f))
|
||||||
|
|
||||||
|
|
||||||
class _ScraperData:
|
class _ScraperData:
|
||||||
"""_summary_"""
|
"""
|
||||||
|
Conteneur de données spécialisé pour extraire les informations des dictionnaires JSON.
|
||||||
|
|
||||||
|
Cette classe agit comme une interface simplifiée au-dessus du dictionnaire brut
|
||||||
|
renvoyé par la balise __NEXT_DATA__ du site Millesima.
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self, data: dict[str, object]) -> None:
|
def __init__(self, data: dict[str, object]) -> None:
|
||||||
"""_summary_
|
"""
|
||||||
|
Initialise le conteneur avec un dictionnaire de données.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
data (dict[str, object]): _description_
|
data (dict[str, object]): Le dictionnaire JSON brut extrait de la page.
|
||||||
"""
|
"""
|
||||||
self._data: dict[str, object] = data
|
self._data: dict[str, object] = data
|
||||||
|
|
||||||
def _getcontent(self) -> dict[str, object] | None:
|
def _getcontent(self) -> dict[str, object] | None:
|
||||||
"""_summary_
|
"""
|
||||||
|
Navigue dans l'arborescence Redux pour atteindre le contenu du produit.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict[str, object]: _description_
|
dict[str, object] | None: Le dictionnaire du produit ou None si la structure diffère.
|
||||||
"""
|
"""
|
||||||
current_data: dict[str, object] = self._data
|
current_data: dict[str, object] = self._data
|
||||||
for key in ["initialReduxState", "product", "content"]:
|
for key in ["initialReduxState", "product", "content"]:
|
||||||
@@ -35,10 +84,11 @@ class _ScraperData:
|
|||||||
return current_data
|
return current_data
|
||||||
|
|
||||||
def _getattributes(self) -> dict[str, object] | None:
|
def _getattributes(self) -> dict[str, object] | None:
|
||||||
"""_summary_
|
"""
|
||||||
|
Extrait les attributs techniques (notes, appellations, etc.) du produit.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict[str, object]: _description_
|
dict[str, object] | None: Les attributs du vin ou None.
|
||||||
"""
|
"""
|
||||||
current_data: object = self._getcontent()
|
current_data: object = self._getcontent()
|
||||||
if current_data is None:
|
if current_data is None:
|
||||||
@@ -47,9 +97,13 @@ class _ScraperData:
|
|||||||
|
|
||||||
def prix(self) -> float | None:
|
def prix(self) -> float | None:
|
||||||
"""
|
"""
|
||||||
Retourne le prix unitaire d'une bouteille (75cl).
|
Calcule le prix unitaire d'une bouteille (standardisée à 75cl).
|
||||||
|
|
||||||
Si aucun prix n'est disponible, retourne None.
|
Le site vend souvent par caisses (6, 12 bouteilles) ou formats (Magnum).
|
||||||
|
Cette méthode normalise le prix pour obtenir celui d'une seule unité.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
float | None: Le prix calculé arrondi à 2 décimales, ou None.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
content = self._getcontent()
|
content = self._getcontent()
|
||||||
@@ -91,13 +145,13 @@ class _ScraperData:
|
|||||||
return prix_calcule
|
return prix_calcule
|
||||||
|
|
||||||
def appellation(self) -> str | None:
|
def appellation(self) -> str | None:
|
||||||
"""_summary_
|
"""
|
||||||
|
Extrait le nom de l'appellation du vin.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str: _description_
|
str | None: Le nom (ex: 'Pauillac') ou None.
|
||||||
"""
|
"""
|
||||||
attrs: dict[str, object] | None = self._getattributes()
|
attrs: dict[str, object] | None = self._getattributes()
|
||||||
|
|
||||||
if attrs is not None:
|
if attrs is not None:
|
||||||
app_dict: object | None = attrs.get("appellation")
|
app_dict: object | None = attrs.get("appellation")
|
||||||
if isinstance(app_dict, dict):
|
if isinstance(app_dict, dict):
|
||||||
@@ -105,13 +159,16 @@ class _ScraperData:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def _getcritiques(self, name: str) -> str | None:
|
def _getcritiques(self, name: str) -> str | None:
|
||||||
"""_summary_
|
"""
|
||||||
|
Méthode générique pour parser les notes des critiques (Parker, Suckling, etc.).
|
||||||
|
|
||||||
|
Gère les notes simples ("95") et les plages de notes ("95-97") en faisant la moyenne.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
name (str): _description_
|
name (str): La clé de l'attribut dans le JSON (ex: 'note_rp').
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str | None: _description_
|
str | None: La note formatée en chaîne de caractères ou None.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
current_value: dict[str, object] | None = self._getattributes()
|
current_value: dict[str, object] | None = self._getattributes()
|
||||||
@@ -130,45 +187,54 @@ class _ScraperData:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def parker(self) -> str | None:
|
def parker(self) -> str | None:
|
||||||
|
"""Note Robert Parker."""
|
||||||
return self._getcritiques("note_rp")
|
return self._getcritiques("note_rp")
|
||||||
|
|
||||||
def robinson(self) -> str | None:
|
def robinson(self) -> str | None:
|
||||||
|
"""Note Jancis Robinson."""
|
||||||
return self._getcritiques("note_jr")
|
return self._getcritiques("note_jr")
|
||||||
|
|
||||||
def suckling(self) -> str | None:
|
def suckling(self) -> str | None:
|
||||||
|
"""Note James Suckling."""
|
||||||
return self._getcritiques("note_js")
|
return self._getcritiques("note_js")
|
||||||
|
|
||||||
def getdata(self) -> dict[str, object]:
|
def getdata(self) -> dict[str, object]:
|
||||||
|
"""Retourne le dictionnaire de données complet."""
|
||||||
return self._data
|
return self._data
|
||||||
|
|
||||||
def informations(self) -> str:
|
def informations(self) -> str:
|
||||||
"""
|
"""
|
||||||
Retourne toutes les informations sous la forme :
|
Agrège les données clés pour l'export CSV.
|
||||||
"Appelation,Parker,J.Robinson,J.Suckling,Prix"
|
|
||||||
|
Returns:
|
||||||
|
str: Ligne formatée : "Appellation,Parker,Robinson,Suckling,Prix".
|
||||||
"""
|
"""
|
||||||
|
|
||||||
appellation = self.appellation()
|
appellation = self.appellation()
|
||||||
parker = self.parker()
|
parker = self.parker()
|
||||||
robinson = self.robinson()
|
robinson = self.robinson()
|
||||||
suckling = self.suckling()
|
suckling = self.suckling()
|
||||||
try:
|
prix = self.prix()
|
||||||
prix = self.prix()
|
prix = self.prix()
|
||||||
except ValueError:
|
|
||||||
prix = None
|
|
||||||
|
|
||||||
return f"{appellation},{parker},{robinson},{suckling},{prix}"
|
return f"{appellation},{parker},{robinson},{suckling},{prix}"
|
||||||
|
|
||||||
|
|
||||||
class Scraper:
|
class Scraper:
|
||||||
"""
|
"""
|
||||||
Scraper est une classe qui permet de gerer
|
Client HTTP optimisé pour le scraping de millesima.fr.
|
||||||
de façon dynamique des requetes uniquement
|
|
||||||
sur le serveur https de Millesima
|
Gère la session persistante, les headers de navigation et un cache double
|
||||||
|
pour optimiser les performances et la discrétion.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
"""
|
"""
|
||||||
Initialise la session de scraping.
|
Initialise l'infrastructure de navigation:
|
||||||
|
|
||||||
|
- créer une session pour éviter de faire un handshake pour chaque requête
|
||||||
|
- ajout d'un header pour éviter le blocage de l'accès au site
|
||||||
|
- ajout d'un système de cache
|
||||||
"""
|
"""
|
||||||
self._url: str = "https://www.millesima.fr/"
|
self._url: str = "https://www.millesima.fr/"
|
||||||
# Très utile pour éviter de renvoyer toujours les mêmes handshake
|
# Très utile pour éviter de renvoyer toujours les mêmes handshake
|
||||||
@@ -178,16 +244,16 @@ class Scraper:
|
|||||||
# bloque car on serait des robots
|
# bloque car on serait des robots
|
||||||
self._session.headers.update(
|
self._session.headers.update(
|
||||||
{
|
{
|
||||||
"User-Agent":
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
|
|
||||||
AppleWebKit/537.36 (KHTML, like Gecko) \
|
AppleWebKit/537.36 (KHTML, like Gecko) \
|
||||||
Chrome/122.0.0.0 Safari/537.36",
|
Chrome/122.0.0.0 Safari/537.36",
|
||||||
"Accept-Language":
|
"Accept-Language": "fr-FR,fr;q=0.9,en;q=0.8",
|
||||||
"fr-FR,fr;q=0.9,en;q=0.8",
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
# Système de cache pour éviter de solliciter le serveur inutilement
|
# Système de cache pour éviter de solliciter le serveur inutilement
|
||||||
|
# utilise pour _request
|
||||||
self._latest_request: tuple[(str, Response)] | None = None
|
self._latest_request: tuple[(str, Response)] | None = None
|
||||||
|
# utilise pour getsoup
|
||||||
self._latest_soups: OrderedDict[str, BeautifulSoup] = OrderedDict[
|
self._latest_soups: OrderedDict[str, BeautifulSoup] = OrderedDict[
|
||||||
str, BeautifulSoup
|
str, BeautifulSoup
|
||||||
]()
|
]()
|
||||||
@@ -202,7 +268,7 @@ class Scraper:
|
|||||||
Returns:
|
Returns:
|
||||||
Response: L'objet réponse de la requête.
|
Response: L'objet réponse de la requête.
|
||||||
|
|
||||||
Raise:
|
Raises:
|
||||||
HTTPError: Si le serveur renvoie un code d'erreur (4xx, 5xx).
|
HTTPError: Si le serveur renvoie un code d'erreur (4xx, 5xx).
|
||||||
"""
|
"""
|
||||||
target_url: str = self._url + subdir.lstrip("/")
|
target_url: str = self._url + subdir.lstrip("/")
|
||||||
@@ -223,7 +289,7 @@ class Scraper:
|
|||||||
Returns:
|
Returns:
|
||||||
Response: L'objet réponse (cache ou nouvelle requête).
|
Response: L'objet réponse (cache ou nouvelle requête).
|
||||||
|
|
||||||
Raise:
|
Raises:
|
||||||
HTTPError: Si le serveur renvoie un code d'erreur (4xx, 5xx).
|
HTTPError: Si le serveur renvoie un code d'erreur (4xx, 5xx).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -253,7 +319,7 @@ class Scraper:
|
|||||||
Returns:
|
Returns:
|
||||||
BeautifulSoup: L'objet parsé pour extraction de données.
|
BeautifulSoup: L'objet parsé pour extraction de données.
|
||||||
|
|
||||||
Raise:
|
Raises:
|
||||||
HTTPError: Si le serveur renvoie un code d'erreur (4xx, 5xx).
|
HTTPError: Si le serveur renvoie un code d'erreur (4xx, 5xx).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -274,23 +340,20 @@ class Scraper:
|
|||||||
def getjsondata(self, subdir: str, id: str = "__NEXT_DATA__") -> _ScraperData:
|
def getjsondata(self, subdir: str, id: str = "__NEXT_DATA__") -> _ScraperData:
|
||||||
"""
|
"""
|
||||||
Extrait les données JSON contenues dans la balise __NEXT_DATA__ du site.
|
Extrait les données JSON contenues dans la balise __NEXT_DATA__ du site.
|
||||||
Beaucoup de sites modernes (Next.js) stockent leur état initial dans
|
|
||||||
une balise <script> pour l'hydratation côté client.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
subdir (str): Le chemin de la page.
|
subdir (str): Le chemin de la page.
|
||||||
id (str, optional): L'identifiant de la balise script (par défaut __NEXT_DATA__).
|
id (str, optional): L'identifiant de la balise script.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
HTTPError: Soulevée par `getresponse` si le serveur renvoie un code d'erreur (4xx, 5xx).
|
HTTPError: Erreur renvoyée par le serveur (4xx, 5xx).
|
||||||
JSONDecodeError: Soulevée par `loads` si le contenu de la balise n'est pas un JSON valide.
|
JSONDecodeError: Si le contenu de la balise n'est pas un JSON valide.
|
||||||
ValueError: Soulevée manuellement si l'une des clés attendues (props, pageProps, etc.)
|
ValueError: Si les clés 'props' ou 'pageProps' sont absentes.
|
||||||
est absente de la structure JSON.
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict[str, object]: Un dictionnaire contenant les données utiles
|
_ScraperData: Instance contenant les données extraites.
|
||||||
ou un dictionnaire vide en cas d'erreur.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
soup: BeautifulSoup = self.getsoup(subdir)
|
soup: BeautifulSoup = self.getsoup(subdir)
|
||||||
script: Tag | None = soup.find("script", id=id)
|
script: Tag | None = soup.find("script", id=id)
|
||||||
|
|
||||||
@@ -307,75 +370,134 @@ class Scraper:
|
|||||||
|
|
||||||
return _ScraperData(cast(dict[str, object], current_data))
|
return _ScraperData(cast(dict[str, object], current_data))
|
||||||
|
|
||||||
def _geturlproductslist(self, subdir: str) -> list[str] | None:
|
def _geturlproductslist(self, subdir: str) -> list[dict[str, Any]] | None:
|
||||||
"""_summary_
|
"""
|
||||||
|
Récupère la liste des produits d'une page de catégorie.
|
||||||
Args:
|
|
||||||
subdir (str): _description_
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
_type_: _description_
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
data: dict[str, object] = self.getjsondata(subdir).getdata()
|
data: dict[str, object] = self.getjsondata(subdir).getdata()
|
||||||
|
|
||||||
for element in ["initialReduxState", "categ", "content"]:
|
products: list[dict[str, Any]] = cast(
|
||||||
data: dict[str, object] = cast(dict[str, object], data.get(element))
|
list[dict[str, Any]], data.get("products")
|
||||||
if not isinstance(data, dict):
|
)
|
||||||
return None
|
|
||||||
|
|
||||||
products: list[str] = cast(list[str], data.get("products"))
|
return products
|
||||||
if isinstance(products, list):
|
|
||||||
return products
|
|
||||||
|
|
||||||
except (JSONDecodeError, HTTPError):
|
except (JSONDecodeError, HTTPError):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def getvins(self, subdir: str, filename: str) -> None:
|
def _writevins(self, cache: set[str], product: dict[str, Any], f: Any) -> None:
|
||||||
"""_summary_
|
"""_summary_
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
subdir (str): _description_
|
cache (set[str]): _description_
|
||||||
filename (str): _description_
|
product (dict): _description_
|
||||||
|
f (Any): _description_
|
||||||
"""
|
"""
|
||||||
with open(filename, "w") as f:
|
if isinstance(product, dict):
|
||||||
cache: set[str] = set[str]()
|
link: Any | None = product.get("seoKeyword")
|
||||||
page = 0
|
if link and link not in cache:
|
||||||
_ = f.write("Appellation,Robert,Robinson,Suckling,Prix\n")
|
try:
|
||||||
|
infos = self.getjsondata(link).informations()
|
||||||
|
_ = f.write(infos + "\n")
|
||||||
|
cache.add(link)
|
||||||
|
except (JSONDecodeError, HTTPError) as e:
|
||||||
|
print(f"Erreur sur le produit {link}: {e}")
|
||||||
|
|
||||||
while True:
|
def _initstate(self, reset: bool) -> tuple[int, set[str]]:
|
||||||
page += 1
|
"""
|
||||||
products_list: list[str] | None = \
|
appelle la fonction pour load le cache, si il existe
|
||||||
self._geturlproductslist(f"{subdir}?page={page}")
|
pas, il utilise les variables de base sinon il override
|
||||||
|
toute les variables pour continuer et pas recommencer le
|
||||||
|
processus en entier.
|
||||||
|
|
||||||
if not products_list:
|
Args:
|
||||||
break
|
reset (bool): pouvoir le reset ou pas
|
||||||
|
|
||||||
products_list_length = len(products_list)
|
Returns:
|
||||||
for i, product in enumerate(products_list):
|
tuple[int, set[str]]: le contenu de la page et du cache
|
||||||
if not isinstance(product, dict):
|
"""
|
||||||
continue
|
if not reset:
|
||||||
|
#
|
||||||
|
serializable: tuple[int, set[str]] | None = loadstate()
|
||||||
|
if isinstance(serializable, tuple):
|
||||||
|
return serializable
|
||||||
|
return 1, set()
|
||||||
|
|
||||||
link = product.get("seoKeyword")
|
def _ensuretitle(self, f: TextIOWrapper, title: str) -> None:
|
||||||
|
"""
|
||||||
|
check si le titre est bien présent au début du buffer
|
||||||
|
sinon il l'ecrit, petit bug potentiel, a+ ecrit tout le
|
||||||
|
temps a la fin du buffer, si on a ecrit des choses avant
|
||||||
|
le titre sera apres ces données mais on part du principe
|
||||||
|
que personne va toucher le fichier.
|
||||||
|
|
||||||
if link and link not in cache:
|
Args:
|
||||||
try:
|
f (TextIOWrapper): buffer stream fichier
|
||||||
infos = self.getjsondata(link).informations()
|
title (str): titre du csv
|
||||||
_ = f.write(infos + "\n")
|
"""
|
||||||
print(
|
_ = f.seek(0, SEEK_SET)
|
||||||
f"page: {page} | {i + 1}/{products_list_length} {link}"
|
if not (f.read(len(title)) == title):
|
||||||
)
|
_ = f.write(title)
|
||||||
cache.add(link)
|
else:
|
||||||
except (JSONDecodeError, HTTPError) as e:
|
_ = f.seek(0, SEEK_END)
|
||||||
print(f"Erreur sur le produit {link}: {e}")
|
|
||||||
f.flush()
|
def getvins(self, subdir: str, filename: str, reset: bool = False) -> None:
|
||||||
|
"""
|
||||||
|
Scrape toutes les pages d'une catégorie et sauvegarde en CSV.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subdir (str): La catégorie (ex: '/vins-rouges').
|
||||||
|
filename (str): Nom du fichier de sortie (ex: 'vins.csv').
|
||||||
|
reset (bool): (Optionnel) pour réinitialiser le processus.
|
||||||
|
"""
|
||||||
|
# mode d'écriture fichier
|
||||||
|
mode: Literal["w", "a+"] = "w" if reset else "a+"
|
||||||
|
# titre
|
||||||
|
title: str = "Appellation,Robert,Robinson,Suckling,Prix\n"
|
||||||
|
# page: page où commence le scraper
|
||||||
|
# cache: tout les pages déjà parcourir
|
||||||
|
page, cache = self._initstate(reset)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(filename, mode) as f:
|
||||||
|
self._ensuretitle(f, title)
|
||||||
|
while True:
|
||||||
|
products_list: list[dict[str, Any]] | None = (
|
||||||
|
self._geturlproductslist(f"{subdir}?page={page}")
|
||||||
|
)
|
||||||
|
if not products_list:
|
||||||
|
break
|
||||||
|
|
||||||
|
pbar: tqdm[dict[str, Any]] = tqdm(
|
||||||
|
products_list, bar_format="{l_bar} {bar:20} {r_bar}"
|
||||||
|
)
|
||||||
|
for product in pbar:
|
||||||
|
keyword: str = cast(
|
||||||
|
str, product.get("seoKeyword", "Inconnu")[:40]
|
||||||
|
)
|
||||||
|
pbar.set_description(
|
||||||
|
f"Page: {page:<3} | Product: {keyword:<40}"
|
||||||
|
)
|
||||||
|
self._writevins(cache, product, f)
|
||||||
|
page += 1
|
||||||
|
# va créer un fichier au début et l'override
|
||||||
|
# tout les 5 pages au cas où SIGHUP ou autre
|
||||||
|
if page % 5 == 0 and not reset:
|
||||||
|
savestate((page, cache))
|
||||||
|
except (Exception, HTTPError, KeyboardInterrupt, JSONDecodeError):
|
||||||
|
if not reset:
|
||||||
|
savestate((page, cache))
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
if len(argv) != 2:
|
if len(argv) != 3:
|
||||||
raise ValueError(f"{argv[0]} <sous-url>")
|
raise ValueError(f"{argv[0]} <filename> <sous-url>")
|
||||||
|
filename = argv[1]
|
||||||
|
suburl = argv[2]
|
||||||
|
|
||||||
scraper: Scraper = Scraper()
|
scraper: Scraper = Scraper()
|
||||||
scraper.getvins(argv[1], "donnee.csv")
|
scraper.getvins(suburl, filename)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
67
tests/test_cleaning.py
Executable file
67
tests/test_cleaning.py
Executable file
@@ -0,0 +1,67 @@
|
|||||||
|
import pytest
|
||||||
|
from unittest.mock import patch, mock_open
|
||||||
|
from cleaning import Cleaning
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cleaning_raw() -> Cleaning:
|
||||||
|
"""
|
||||||
|
"Appellation": ["Pauillac", "Pauillac ", "Margaux", None , "Pomerol", "Pomerol"],
|
||||||
|
"Robert": ["95" , None , "bad" , 90 , None , None ],
|
||||||
|
"Robinson": [None , "93" , 18 , None , None , None ],
|
||||||
|
"Suckling": [96 , None , None , None , 91 , None ],
|
||||||
|
"Prix": ["10.0" , "11.0" , "20.0" , "30.0", "40.0" , "50.0" ],
|
||||||
|
"""
|
||||||
|
csv_content = """Appellation,Robert,Robinson,Suckling,Prix
|
||||||
|
Pauillac,95,,96,10.0
|
||||||
|
Pauillac ,,93,,11.0
|
||||||
|
Margaux,bad,18,,20.0
|
||||||
|
,90,,,30.0
|
||||||
|
Pomerol,,,91,40.0
|
||||||
|
Pomerol,,,,50.0
|
||||||
|
"""
|
||||||
|
m = mock_open(read_data=csv_content)
|
||||||
|
with patch("builtins.open", m):
|
||||||
|
return Cleaning("donnee.csv")
|
||||||
|
|
||||||
|
|
||||||
|
def test_drop_empty_appellation(cleaning_raw: Cleaning) -> None:
|
||||||
|
out = cleaning_raw.drop_empty_appellation().getVins()
|
||||||
|
assert out["Appellation"].isna().sum() == 0
|
||||||
|
assert len(out) == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_mean_score_zero_when_no_scores(cleaning_raw: Cleaning) -> None:
|
||||||
|
out = cleaning_raw.drop_empty_appellation()
|
||||||
|
m = out._mean_score("Robert")
|
||||||
|
assert list(m.columns) == ["Appellation", "mean_Robert"]
|
||||||
|
pomerol_mean = m.loc[m["Appellation"].str.strip() == "Pomerol", "mean_Robert"].iloc[
|
||||||
|
0
|
||||||
|
]
|
||||||
|
assert pomerol_mean == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_missing_scores(cleaning_raw: Cleaning):
|
||||||
|
cleaning_raw._vins["Appellation"] = cleaning_raw._vins["Appellation"].str.strip()
|
||||||
|
|
||||||
|
cleaning_raw.drop_empty_appellation()
|
||||||
|
filled = cleaning_raw.fill_missing_scores().getVins()
|
||||||
|
for col in cleaning_raw.SCORE_COLS:
|
||||||
|
assert filled[col].isna().sum() == 0
|
||||||
|
|
||||||
|
pauillac_robert = filled[filled["Appellation"] == "Pauillac"]["Robert"]
|
||||||
|
assert (pauillac_robert == 95.0).all()
|
||||||
|
|
||||||
|
|
||||||
|
def test_encode_appellation(cleaning_raw: Cleaning):
|
||||||
|
cleaning_raw._vins["Appellation"] = cleaning_raw._vins["Appellation"].str.strip()
|
||||||
|
|
||||||
|
out = (
|
||||||
|
cleaning_raw.drop_empty_appellation()
|
||||||
|
.fill_missing_scores()
|
||||||
|
.encode_appellation()
|
||||||
|
.getVins()
|
||||||
|
)
|
||||||
|
assert "App_Appellation" not in out.columns
|
||||||
|
assert "App_Pauillac" in out.columns
|
||||||
|
assert int(out.loc[0, "App_Pauillac"]) == 1
|
||||||
28
tests/test_scraper.py
Normal file → Executable file
28
tests/test_scraper.py
Normal file → Executable file
@@ -185,17 +185,11 @@ def mock_site():
|
|||||||
{dumps({
|
{dumps({
|
||||||
"props": {
|
"props": {
|
||||||
"pageProps": {
|
"pageProps": {
|
||||||
"initialReduxState": {
|
"products": [
|
||||||
"categ": {
|
{"seoKeyword": "/nino-negri-5-stelle-sfursat-2022.html",},
|
||||||
"content": {
|
{"seoKeyword": "/poubelle",},
|
||||||
"products": [
|
{"seoKeyword": "/",}
|
||||||
{"seoKeyword": "/nino-negri-5-stelle-sfursat-2022.html",},
|
]
|
||||||
{"seoKeyword": "/poubelle",},
|
|
||||||
{"seoKeyword": "/",}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -213,14 +207,8 @@ def mock_site():
|
|||||||
{dumps({
|
{dumps({
|
||||||
"props": {
|
"props": {
|
||||||
"pageProps": {
|
"pageProps": {
|
||||||
"initialReduxState": {
|
"products": [
|
||||||
"categ": {
|
]
|
||||||
"content": {
|
|
||||||
"products": [
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -319,7 +307,7 @@ def test_informations(scraper: Scraper):
|
|||||||
def test_search(scraper: Scraper):
|
def test_search(scraper: Scraper):
|
||||||
m = mock_open()
|
m = mock_open()
|
||||||
with patch("builtins.open", m):
|
with patch("builtins.open", m):
|
||||||
scraper.getvins("wine.html", "fake_file.csv")
|
scraper.getvins("wine.html", "fake_file.csv", True)
|
||||||
|
|
||||||
assert m().write.called
|
assert m().write.called
|
||||||
all_writes = "".join(call.args[0] for call in m().write.call_args_list)
|
all_writes = "".join(call.args[0] for call in m().write.call_args_list)
|
||||||
|
|||||||
Reference in New Issue
Block a user