Spaces:
Runtime error

johan frachon commited on
Commit
dbd78a4
·
0 Parent(s):

envoi code src sans notebooks

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. .gitignore +10 -0
  3. LANCER_DEMO.bat +30 -0
  4. README.md +45 -0
  5. requirements.txt +16 -0
  6. src/__init__.py +0 -0
  7. src/desktop.ini +0 -0
  8. src/features/__init__.py +0 -0
  9. src/features/build_features.py +23 -0
  10. src/features/build_features_herymicka.py +75 -0
  11. src/features/build_features_nlp.py +170 -0
  12. src/features/desktop.ini +0 -0
  13. src/image_models/__init__.py +0 -0
  14. src/image_models/build_features_image.py +52 -0
  15. src/image_models/desktop.ini +0 -0
  16. src/image_models/predict/__init__.py +0 -0
  17. src/image_models/predict/desktop.ini +0 -0
  18. src/image_models/predict/predict_M1_dino.py +33 -0
  19. src/image_models/predict/predict_M2_xgboost.py +44 -0
  20. src/image_models/predict/predict_M3_effnet.py +33 -0
  21. src/image_models/predict/predict_M4_overfit.py +40 -0
  22. src/image_models/predict/predict_M5_voting.py +54 -0
  23. src/image_models/preprocessing.py +32 -0
  24. src/image_models/streamlit/app.py +1 -0
  25. src/image_models/streamlit/desktop.ini +0 -0
  26. src/image_models/train/__init__.py +0 -0
  27. src/image_models/train/desktop.ini +0 -0
  28. src/image_models/train/train_M1_dino.py +83 -0
  29. src/image_models/train/train_M2_xgboost.py +61 -0
  30. src/image_models/train/train_M3_effnet.py +90 -0
  31. src/image_models/train/train_M4_overfit.py +67 -0
  32. src/image_models/visualization/__init__.py +0 -0
  33. src/image_models/visualization/desktop.ini +0 -0
  34. src/image_models/visualization/visualize.py +0 -0
  35. src/streamlit/README.md +62 -0
  36. src/streamlit/app.py +127 -0
  37. src/streamlit/assets/desktop.ini +0 -0
  38. src/streamlit/assets/examples/.gitkeep +0 -0
  39. src/streamlit/assets/examples/desktop.ini +0 -0
  40. src/streamlit/assets/heatmap clair .png +3 -0
  41. src/streamlit/assets/heatmap_clair.png +3 -0
  42. src/streamlit/assets/style.css +294 -0
  43. src/streamlit/components/__init__.py +10 -0
  44. src/streamlit/components/desktop.ini +0 -0
  45. src/streamlit/config.py +54 -0
  46. src/streamlit/desktop.ini +0 -0
  47. src/streamlit/docs/TESTING_STRATEGY.md +982 -0
  48. src/streamlit/docs/desktop.ini +0 -0
  49. src/streamlit/pages/1_📊_Données.py +139 -0
  50. src/streamlit/pages/2_⚙️_Preprocessing.py +142 -0
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ data/
2
+ models/
3
+ implementation/
4
+ notebooks/
5
+ *.pth
6
+ *.joblib
7
+ *.pkl
8
+ *.json
9
+ __pycache__/
10
+ .ipynb_checkpoints/
LANCER_DEMO.bat ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ G:
3
+ cd "G:\Mon Drive\travail final\FULL_BACKUP_RAPIDE\datascientest_projet"
4
+
5
+ echo Nettoyage des fichiers temporaires...
6
+ for /d /r . %%d in (__pycache__) do @if exist "%%d" rd /s /q "%%d"
7
+
8
+ echo Recherche de Conda...
9
+ set CONDA_PATH=%USERPROFILE%\anaconda3\Scripts\activate.bat
10
+ if not exist "%CONDA_PATH%" set CONDA_PATH=C:\anaconda3\Scripts\activate.bat
11
+ if not exist "%CONDA_PATH%" set CONDA_PATH=%USERPROFILE%\Miniconda3\Scripts\activate.bat
12
+
13
+ if exist "%CONDA_PATH%" (
14
+ echo Activation de l'environnement via %CONDA_PATH%
15
+ call "%CONDA_PATH%" base
16
+ ) else (
17
+ echo [ATTENTION] Anaconda n'a pas ete trouve dans les dossiers standards.
18
+ )
19
+
20
+ echo Verification/Creation de l'environnement Python...
21
+ call conda create -n rakuten_env python=3.10 -y
22
+ call conda activate rakuten_env
23
+
24
+ echo Installation/Mise a jour des dependances...
25
+ pip install -r requirements.txt
26
+
27
+ echo Lancement du Dashboard Rakuten...
28
+ streamlit run src/streamlit/app.py
29
+
30
+ pause
README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Project Name
2
+ ==============================
3
+
4
+ This repo is a Starting Pack for DS projects. You can rearrange the structure to make it fits your project.
5
+
6
+ Project Organization
7
+ ------------
8
+
9
+ ├── LICENSE
10
+ ├── README.md <- The top-level README for developers using this project.
11
+ ├── data <- Should be in your computer but not on Github (only in .gitignore)
12
+ │   ├── processed <- The final, canonical data sets for modeling.
13
+ │   └── raw <- The original, immutable data dump.
14
+ │
15
+ ├── models <- Trained and serialized models, model predictions, or model summaries
16
+ │
17
+ ├── notebooks <- Jupyter notebooks. Naming convention is a number (for ordering),
18
+ │ the creator's name, and a short `-` delimited description, e.g.
19
+ │ `1.0-alban-data-exploration`.
20
+ │
21
+ ├── references <- Data dictionaries, manuals, links, and all other explanatory materials.
22
+ │
23
+ ├── reports <- The reports that you'll make during this project as PDF
24
+ │   └── figures <- Generated graphics and figures to be used in reporting
25
+ │
26
+ ├── requirements.txt <- The requirements file for reproducing the analysis environment, e.g.
27
+ │ generated with `pip freeze > requirements.txt`
28
+ │
29
+ ├── src <- Source code for use in this project.
30
+ │   ├── __init__.py <- Makes src a Python module
31
+ │ │
32
+ │   ├── features <- Scripts to turn raw data into features for modeling
33
+ │   │   └── build_features.py
34
+ │ │
35
+ │   ├── models <- Scripts to train models and then use trained models to make
36
+ │ │ │ predictions
37
+ │   │   ├── predict_model.py
38
+ │   │   └── train_model.py
39
+ │ │
40
+ │   ├── visualization <- Scripts to create exploratory and results oriented visualizations
41
+ │   │ └── visualize.py
42
+
43
+ --------
44
+
45
+ <p><small>Project based on the <a target="_blank" href="https://drivendata.github.io/cookiecutter-data-science/">cookiecutter data science project template</a>. #cookiecutterdatascience</small></p>
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ numpy
4
+ Pillow
5
+ scikit-learn
6
+ xgboost
7
+ torch
8
+ torchvision
9
+ transformers
10
+ graphviz
11
+ joblib
12
+ plotly
13
+ matplotlib
14
+ seaborn
15
+ timm
16
+ openpyxl
src/__init__.py ADDED
File without changes
src/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/features/__init__.py ADDED
File without changes
src/features/build_features.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import transforms
3
+ from PIL import Image
4
+
5
+ def preprocess_image(img_path, mode="standard"):
6
+ # nous chargeons image
7
+ img = Image.open(img_path).convert('RGB')
8
+ if mode == "dino":
9
+ # dino veut du 518x518
10
+ tr = transforms.Compose([
11
+ transforms.Resize(518),
12
+ transforms.CenterCrop(518),
13
+ transforms.ToTensor(),
14
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
15
+ ])
16
+ else:
17
+ # standard reste a 224
18
+ tr = transforms.Compose([
19
+ transforms.Resize((224, 224)),
20
+ transforms.ToTensor(),
21
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
22
+ ])
23
+ return tr(img).unsqueeze(0)
src/features/build_features_herymicka.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import re
3
+ import html
4
+ import pandas as pd
5
+ from bs4 import BeautifulSoup
6
+
7
+ # Si tu veux forcer l'usage du fichier traduit (s'il existe)
8
+ USE_TRANSLATIONS_IF_AVAILABLE = True
9
+
10
+ def strip_html(text: str) -> str:
11
+ text = "" if text is None else str(text)
12
+ text = html.unescape(text)
13
+ return BeautifulSoup(text, "html.parser").get_text(separator=" ")
14
+
15
+ def basic_clean(text: str) -> str:
16
+ text = "" if text is None else str(text)
17
+ text = text.lower()
18
+ text = re.sub(r"\s+", " ", text).strip()
19
+ return text
20
+
21
+ def build_product_txt(df: pd.DataFrame) -> pd.Series:
22
+ des = df.get("designation", pd.Series([""] * len(df), index=df.index)).fillna("").astype(str)
23
+ desc = df.get("description", pd.Series([""] * len(df), index=df.index)).fillna("").astype(str)
24
+
25
+ des = des.map(strip_html).map(basic_clean)
26
+ desc = desc.map(strip_html).map(basic_clean)
27
+
28
+ return (des + " . -//- " + desc).fillna("").astype(str)
29
+
30
+ def main():
31
+ ROOT = Path(__file__).resolve().parents[2] # OCT25_BMLE_RAKUTEN/
32
+ RAW = ROOT / "data" / "raw"
33
+ PROCESSED = ROOT / "data" / "processed"
34
+ PROCESSED.mkdir(parents=True, exist_ok=True)
35
+
36
+ # Fichiers bruts
37
+ X_train_path = RAW / "X_train_update.csv"
38
+ y_train_path = RAW / "Y_train_CVw08PX.csv"
39
+
40
+ # Fichier déjà traduit (si tu veux l'utiliser)
41
+ translations_path = PROCESSED / "Rak_train_translations.csv"
42
+
43
+ # Labels
44
+ y = pd.read_csv(y_train_path, index_col=0).iloc[:, 0]
45
+
46
+ if USE_TRANSLATIONS_IF_AVAILABLE and translations_path.exists():
47
+ print(f"✅ Using translations: {translations_path}")
48
+ df = pd.read_csv(translations_path, index_col=0)
49
+
50
+ if "product_txt_transl" not in df.columns:
51
+ raise ValueError("Rak_train_translations.csv doit contenir la colonne 'product_txt_transl'")
52
+
53
+ df["product_txt"] = df["product_txt_transl"].fillna("").astype(str)
54
+
55
+ # si le label n'est pas dans le fichier traduit, on le rajoute
56
+ if "prdtypecode" not in df.columns:
57
+ df["prdtypecode"] = y.reindex(df.index)
58
+
59
+ else:
60
+ print("⚙️ No translations file found (or disabled). Building product_txt from raw.")
61
+ X_train = pd.read_csv(X_train_path, index_col=0)
62
+ df = pd.DataFrame(index=X_train.index)
63
+ df["product_txt"] = build_product_txt(X_train)
64
+ df["prdtypecode"] = y.reindex(df.index)
65
+
66
+ # Nettoyage final anti-NaN
67
+ df["product_txt"] = df["product_txt"].fillna("").astype(str)
68
+ df["prdtypecode"] = df["prdtypecode"].astype(int)
69
+
70
+ out_path = PROCESSED / "train_ready.csv"
71
+ df[["product_txt", "prdtypecode"]].to_csv(out_path)
72
+ print(f"✅ Saved: {out_path}")
73
+
74
+ if __name__ == "__main__":
75
+ main()
src/features/build_features_nlp.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from nltk.tokenize import word_tokenize
4
+ from nltk.tokenize.regexp import RegexpTokenizer
5
+ from nltk.corpus import stopwords
6
+ import langid
7
+ from bs4 import BeautifulSoup
8
+ import html
9
+ from imblearn.over_sampling import RandomOverSampler, SMOTEN
10
+ from libretranslatepy import LibreTranslateAPI
11
+ from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
12
+ from sklearn.ensemble import GradientBoostingClassifier
13
+
14
+
15
+
16
+ ##import original data
17
+ ##data is already split into Training/Testing, no need to re-split
18
+ Rak_train_raw = pd.read_csv('../data/raw/X_train_update.csv', index_col=0) ##raw X train data
19
+ RakY_train_raw = pd.read_csv('../data/raw/Y_train_CVw08PX.csv', index_col=0) ##raw Y train data
20
+ Rak_test_raw = pd.read_csv('../data/raw/X_test_update.csv', index_col=0) ##raw X test data
21
+
22
+ #####
23
+ ##Clean-up strings
24
+ def rak_data_cleanup(rak_data_raw):
25
+ ##Fix problematic strings for text clean-up
26
+ ##FIXME not sure if deep copy inside function is needed
27
+ rak_data = rak_data_raw.copy(deep = True)
28
+
29
+ ## Replace NaN with ''
30
+ ## (for some reason strings can include numeric NaN values)
31
+ rak_data['description'] = rak_data['description'].fillna('')
32
+
33
+ ## lower case
34
+ rak_data['designation'] = rak_data['designation'].str.lower()
35
+ rak_data['description'] = rak_data['description'].str.lower()
36
+
37
+ ##FIXME simplify syntax
38
+ ##Unescape HTML
39
+ rak_data['designation'] = rak_data.apply(lambda row: html.unescape(row['designation']), axis = 1)
40
+ rak_data['description'] = rak_data.apply(lambda row: html.unescape(row['description']), axis = 1)
41
+
42
+ ## Remove HTML tags
43
+ rak_data['designation'] = rak_data.apply(lambda row: BeautifulSoup(row['designation'], "html.parser").get_text(separator=" "), axis = 1)
44
+ rak_data['description'] = rak_data.apply(lambda row: BeautifulSoup(row['description'], "html.parser").get_text(separator=" "), axis = 1)
45
+
46
+ ##FIXME drop empty designation & description rows
47
+ ##FIXME make fun to clean-up data (to apply to test as well)
48
+
49
+
50
+ ##FIXME list of problematic strings to fix
51
+ ## àªtre
52
+
53
+ ##Regex replacements
54
+ repl_dict = {
55
+ ##FIXME nltk.classify.textcat.TextCat().remove_punctuation()
56
+ r'n°': r' numéro ',
57
+
58
+ ##FIXME not sure how to handle '¿' or '?'
59
+ ##insert space around any non-digit, non-word and non-whitespace with (e.g. '\?' -> ' \? ', 'n°' -> 'n ° ')
60
+ ##except ¿'
61
+ r"[^\d\w\s¿\?'\-]": r' \g<0> ',
62
+
63
+ ##FIXME possibly remove digits after translation
64
+ r"\b\S*[0-9]+\S*\b": '' ##drop all words that contain digits (so drop all digits as well)
65
+ }
66
+
67
+ rak_data = rak_data.replace(to_replace = {'designation': repl_dict,
68
+ 'description': repl_dict},
69
+ regex = True)
70
+
71
+
72
+
73
+ ##Concat strings
74
+ rak_data['product_txt'] = rak_data['designation'] + ' . -//- ' + rak_data['description']
75
+
76
+ rak_data['product_txt_len'] = rak_data['product_txt'].apply(len)
77
+
78
+ return rak_data
79
+
80
+ ##clean-up X train data
81
+ Rak_train = rak_data_cleanup(Rak_train_raw)
82
+
83
+ ##clean-up X test data
84
+ Rak_test = rak_data_cleanup(Rak_test_raw)
85
+
86
+
87
+ #####
88
+ ##foreign language handling
89
+ ##detect phrase language using 'langid' on product_txt
90
+ def lang_detect(data):
91
+ # langid.set_languages(langs=None)
92
+ langid.set_languages(langs=['fr', 'en', 'de', 'it', 'es', 'pt'])
93
+ data['lang'] = data['product_txt'].apply(lambda x: langid.classify(x)[0])
94
+
95
+ return data
96
+
97
+ ##detect languages on Rakuten processed data
98
+ Rak_train = lang_detect(data = Rak_train)
99
+ Rak_test = lang_detect(data = Rak_test)
100
+
101
+
102
+ ##translate using libretranslate (self-hosted process)
103
+ ##func to obtain translations
104
+ ## if rerun == True then run translation code, if False (default) then just load csv from supplied path
105
+ def translate_txt(data = None, rerun = False, csv_file = '../data/processed/Rak_train_translations.csv'):
106
+ ##FIXME improve func not to require data if just loading csv
107
+ if rerun == True:
108
+ ##NOTE: need to start external process first (and this code is time-consuming)
109
+ # libretranslate --update-models --load-only fr,en,es,de,it,pt
110
+ # libretranslate --load-only fr,en,es,de,it,pt
111
+ lt = LibreTranslateAPI("http://localhost:5000/")
112
+
113
+ ##re-use detected language
114
+ def lt_fun(row):
115
+ if row.name % 5000 == 0: print(row.name)
116
+ # print(row['lang'])
117
+ transl = row['product_txt'] if row['lang'] == 'fr' else lt.translate(
118
+ row['product_txt'], source=row['lang'], target="fr")
119
+ return transl
120
+
121
+
122
+ data['product_txt_transl'] = data.apply(lambda row: lt_fun(row), axis=1)
123
+
124
+ ##save translations to csv (overwrites existing file)
125
+ data.to_csv(csv_file)
126
+ else:
127
+ ##load translations from stored csv file
128
+ data = pd.read_csv(csv_file)
129
+
130
+ return data
131
+
132
+ ##translate X train (by default load existing csv file with translations)
133
+ Rak_train = translate_txt(data = None, rerun = False, csv_file = '../data/processed/Rak_train_translations.csv')
134
+ ##FIXME run translations for X test as well
135
+
136
+
137
+ #####
138
+ ##Training Sample Rebalancing
139
+ RakX_train = Rak_train[['product_txt_transl']]
140
+
141
+ ##Oversampling (only on training data)
142
+ ##SMOTEN
143
+ smo = SMOTEN(random_state=27732)
144
+ RakX_train_sm, Raky_train_sm = smo.fit_resample(RakX_train, RakY_train_raw)
145
+
146
+
147
+ #####
148
+ ##Tokenization
149
+ ##FIXME def tokenization fun to reuse with test data as well
150
+
151
+ ##Stop Words
152
+ fr_stop_words = stopwords.words('french')
153
+
154
+ # Créer un vectorisateur
155
+ ##FIXME consider custom tokenizer and max_features
156
+ # regexp_tokenizer = RegexpTokenizer("[a-zA-ZÀÂÆÇÉÈÊËÎÏÔŒÙÛÜŸàâæçéèêëîïôœùûüÿ]{3,}") ##words with at least 3 characaters
157
+ vect_tfidf = TfidfVectorizer(
158
+ max_features=10000,
159
+ stop_words=fr_stop_words
160
+ # , tokenizer = regexp_tokenizer
161
+ )
162
+
163
+ # Mettre à jour la valeur de X_train_tfidf et X_test_tfidf
164
+ ##FIXME need to finalize tokenization
165
+ RakX_train_sm_tfidf = vect_tfidf.fit_transform(RakX_train_sm['product_txt_transl'])
166
+
167
+
168
+
169
+
170
+
src/features/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/image_models/__init__.py ADDED
File without changes
src/image_models/build_features_image.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/features/build_features.py
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ from torchvision import transforms
6
+ from PIL import Image
7
+
8
+ # je definis les constantes globales
9
+ IMG_SIZE_DINO = 518
10
+ IMG_SIZE_EFF = 224
11
+
12
+ # je prepare la transformation pour dino
13
+ def get_dino_transforms():
14
+ # augmentation specifique dino
15
+ # resize bicubic + normalisation imagenet
16
+ return transforms.Compose([
17
+ transforms.ToPILImage(),
18
+ transforms.Resize((IMG_SIZE_DINO, IMG_SIZE_DINO), interpolation=transforms.InterpolationMode.BICUBIC),
19
+ transforms.ToTensor(),
20
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
21
+ ])
22
+
23
+ # je prepare la transformation pour efficientnet
24
+ def get_efficientnet_transforms():
25
+ # resize standard 224
26
+ return transforms.Compose([
27
+ transforms.ToPILImage(),
28
+ transforms.Resize((IMG_SIZE_EFF, IMG_SIZE_EFF)),
29
+ transforms.ToTensor(),
30
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
31
+ ])
32
+
33
+ # je charge une image depuis le disque
34
+ def load_and_process_image(image_path, model_type='dino'):
35
+ try:
36
+ # lecture opencv
37
+ img = cv2.imread(image_path)
38
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
39
+
40
+ # choix transform
41
+ if model_type == 'dino':
42
+ trans = get_dino_transforms()
43
+ else:
44
+ trans = get_efficientnet_transforms()
45
+
46
+ # application
47
+ tensor = trans(img)
48
+ # ajout dimension batch (1, 3, h, w)
49
+ return tensor.unsqueeze(0)
50
+ except Exception as e:
51
+ print(f"err lecture img: {e}")
52
+ return None
src/image_models/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/image_models/predict/__init__.py ADDED
File without changes
src/image_models/predict/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/image_models/predict/predict_M1_dino.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import timm
3
+ import os
4
+ import sys
5
+ import torch.nn.functional as F
6
+ sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
7
+ from image_models.preprocessing import get_preprocessing, load_image
8
+
9
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
+
11
+ class PredictorM1:
12
+ def __init__(self, model_path):
13
+ self.model = timm.create_model('vit_large_patch14_reg4_dinov2.lvd142m', pretrained=False, num_classes=27)
14
+ self.model.load_state_dict(torch.load(model_path, map_location=DEVICE))
15
+ self.model.to(DEVICE).eval()
16
+ self.transform = get_preprocessing('M1')
17
+
18
+ def predict_proba(self, image_path):
19
+ """Renvoie le vecteur de probabilités (27,)"""
20
+ img = load_image(image_path)
21
+ if img is None: return None
22
+ tensor = self.transform(img).unsqueeze(0).to(DEVICE)
23
+ with torch.no_grad():
24
+ output = self.model(tensor)
25
+ # Softmax pour transformer les scores bruts en %
26
+ probs = F.softmax(output, dim=1)
27
+ return probs.cpu().numpy()[0]
28
+
29
+ def predict(self, image_path):
30
+ """Renvoie la classe finale (pour compatibilité)"""
31
+ probs = self.predict_proba(image_path)
32
+ if probs is None: return None
33
+ return int(probs.argmax())
src/image_models/predict/predict_M2_xgboost.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import xgboost as xgb
2
+ import joblib
3
+ import torch
4
+ import timm
5
+ import os
6
+ import sys
7
+ sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
8
+ from image_models.preprocessing import get_preprocessing, load_image
9
+
10
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+
12
+ class PredictorM2:
13
+ def __init__(self, xgb_path, encoder_path):
14
+ # Extracteur de features (ResNet50)
15
+ self.extractor = timm.create_model('resnet50', pretrained=True, num_classes=0)
16
+ self.extractor.to(DEVICE).eval()
17
+ self.transform = get_preprocessing('M3') # M3/M4 utilisent la transfo standard 224
18
+
19
+ # XGBoost
20
+ self.xgb_model = xgb.XGBClassifier()
21
+ self.xgb_model.load_model(xgb_path)
22
+ self.le = joblib.load(encoder_path)
23
+
24
+ def predict_proba(self, image_path):
25
+ """Renvoie le vecteur de probabilités (27,)"""
26
+ img = load_image(image_path)
27
+ if img is None: return None
28
+ tensor = self.transform(img).unsqueeze(0).to(DEVICE)
29
+
30
+ with torch.no_grad():
31
+ features = self.extractor(tensor).cpu().numpy()
32
+
33
+ # XGBoost renvoie directement les probas
34
+ probs = self.xgb_model.predict_proba(features)
35
+ return probs[0]
36
+
37
+ def predict(self, image_path):
38
+ """Renvoie la classe finale décodée"""
39
+ probs = self.predict_proba(image_path)
40
+ if probs is None: return None
41
+ # On récupère l'index max
42
+ pred_idx = probs.argmax()
43
+ # On décode avec le LabelEncoder pour avoir le vrai ProductCode
44
+ return self.le.inverse_transform([pred_idx])[0]
src/image_models/predict/predict_M3_effnet.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import models
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import os
6
+ import sys
7
+ sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
8
+ from image_models.preprocessing import get_preprocessing, load_image
9
+
10
+ DEVICE = torch.device("cpu") # M3 sur CPU pour alléger la VRAM du Voting
11
+
12
+ class PredictorM3:
13
+ def __init__(self, model_path):
14
+ self.model = models.efficientnet_b0(weights=None)
15
+ self.model.classifier[1] = nn.Linear(1280, 27)
16
+ self.model.load_state_dict(torch.load(model_path, map_location=DEVICE))
17
+ self.model.to(DEVICE).eval()
18
+ self.transform = get_preprocessing('M3')
19
+
20
+ def predict_proba(self, image_path):
21
+ """Renvoie le vecteur de probabilités (27,)"""
22
+ img = load_image(image_path)
23
+ if img is None: return None
24
+ tensor = self.transform(img).unsqueeze(0).to(DEVICE)
25
+ with torch.no_grad():
26
+ output = self.model(tensor)
27
+ probs = F.softmax(output, dim=1)
28
+ return probs.cpu().numpy()[0]
29
+
30
+ def predict(self, image_path):
31
+ probs = self.predict_proba(image_path)
32
+ if probs is None: return None
33
+ return int(probs.argmax())
src/image_models/predict/predict_M4_overfit.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchvision import models
4
+ import os
5
+ import sys
6
+ sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
7
+ from image_models.preprocessing import get_preprocessing, load_image
8
+
9
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
+
11
+ # on doit redefinir la tete pour charger les poids
12
+ class LegendMLP(nn.Module):
13
+ def __init__(self, input_dim, num_classes):
14
+ super().__init__()
15
+ self.net = nn.Sequential(
16
+ nn.Linear(input_dim, 2048), nn.BatchNorm1d(2048), nn.GELU(), nn.Dropout(0.2),
17
+ nn.Linear(2048, 1024), nn.BatchNorm1d(1024), nn.GELU(), nn.Dropout(0.2),
18
+ nn.Linear(1024, 512), nn.BatchNorm1d(512), nn.GELU(), nn.Dropout(0.2),
19
+ nn.Linear(512, num_classes)
20
+ )
21
+ def forward(self, x): return self.net(x)
22
+
23
+ class PredictorM4:
24
+ def __init__(self, model_path):
25
+ # M4 = ResNet50 + LegendMLP
26
+ self.model = models.resnet50(weights=None)
27
+ self.model.fc = LegendMLP(2048, 27)
28
+
29
+ self.model.load_state_dict(torch.load(model_path, map_location=DEVICE))
30
+ self.model.to(DEVICE).eval()
31
+ # M4 utilise la transfo standard ImageNet (224px)
32
+ self.transform = get_preprocessing('M3') # Reuse la transfo 224px
33
+
34
+ def predict(self, image_path):
35
+ img = load_image(image_path)
36
+ if img is None: return None
37
+ tensor = self.transform(img).unsqueeze(0).to(DEVICE)
38
+ with torch.no_grad():
39
+ output = self.model(tensor)
40
+ return int(output.argmax(1).item())
src/image_models/predict/predict_M5_voting.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import os
3
+ import sys
4
+
5
+ # imports relatifs
6
+ sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
7
+
8
+ from image_models.predict.predict_M1_dino import PredictorM1
9
+ from image_models.predict.predict_M3_effnet import PredictorM3
10
+ # on n'importe pas m2 car il nécessite des features npy introuvables sur images brutes
11
+
12
+ class PredictorVoting:
13
+ def __init__(self, dir_models):
14
+ print("initialisation voting classifier (mode image : m1 + m3)...")
15
+
16
+ # chemins
17
+ path_m1 = os.path.join(dir_models, "M1_IMAGE_DeepLearning_DINOv3.pth")
18
+ path_m3 = os.path.join(dir_models, "M3_IMAGE_Classic_EfficientNetB0.pth")
19
+
20
+ # chargement
21
+ self.p1 = PredictorM1(path_m1)
22
+ self.p3 = PredictorM3(path_m3)
23
+
24
+ # poids (dino majoritaire)
25
+ self.w1 = 2.0
26
+ self.w3 = 1.0
27
+
28
+ def predict_proba(self, image_path):
29
+ # recuperation probas
30
+ probs_1 = self.p1.predict_proba(image_path)
31
+ probs_3 = self.p3.predict_proba(image_path)
32
+
33
+ if probs_1 is None or probs_3 is None:
34
+ return None
35
+
36
+ # moyenne ponderee
37
+ final_probs = (probs_1 * self.w1 + probs_3 * self.w3) / (self.w1 + self.w3)
38
+ return final_probs
39
+
40
+ def predict(self, image_path):
41
+ # on recupere les probas fusionnees
42
+ probs = self.predict_proba(image_path)
43
+ if probs is None: return None
44
+
45
+ # decision finale
46
+ final_idx = probs.argmax()
47
+
48
+ # on utilise le decodeur de m3 (label encoder) pour renvoyer le vrai code produit
49
+ # (les classes sont alignees entre m1 et m3 lors de l'entrainement)
50
+ # ici on assume que p1 et p3 ont les memes classes (ce qui est le cas dans notre projet)
51
+ return self.p1.le.inverse_transform([final_idx])[0] # ou p3, c'est pareil
52
+
53
+ if __name__ == "__main__":
54
+ print("voting m1+m3 prêt.")
src/image_models/preprocessing.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import torch
3
+ from torchvision import transforms
4
+
5
+ # TAILLES
6
+ SIZE_DINO = 518
7
+ SIZE_STD = 224
8
+
9
+ def get_preprocessing(model_id):
10
+ if model_id == 'M1': # DINO
11
+ return transforms.Compose([
12
+ transforms.ToPILImage(),
13
+ transforms.Resize((SIZE_DINO, SIZE_DINO), interpolation=transforms.InterpolationMode.BICUBIC),
14
+ transforms.ToTensor(),
15
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
16
+ ])
17
+
18
+ elif model_id in ['M3', 'M4']: # EffNet et ResNet Overfit
19
+ return transforms.Compose([
20
+ transforms.ToPILImage(),
21
+ transforms.Resize((SIZE_STD, SIZE_STD)),
22
+ transforms.ToTensor(),
23
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
24
+ ])
25
+
26
+ else: raise ValueError(f"ID inconnu {model_id}")
27
+
28
+ def load_image(path):
29
+ try:
30
+ img = cv2.imread(path)
31
+ return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
32
+ except: return None
src/image_models/streamlit/app.py ADDED
@@ -0,0 +1 @@
 
 
1
+
src/image_models/streamlit/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/image_models/train/__init__.py ADDED
File without changes
src/image_models/train/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/image_models/train/train_M1_dino.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ import timm
5
+ import os
6
+ import pandas as pd
7
+ from sklearn.model_selection import train_test_split
8
+ from sklearn import preprocessing
9
+ from torchvision import transforms
10
+ from torch.utils.data import DataLoader, Dataset
11
+ import cv2
12
+
13
+ # config
14
+ DEVICE = torch.device("cuda")
15
+ BATCH_SIZE = 4
16
+ ACCUM_STEPS = 16
17
+ IMG_SIZE = 518
18
+ BASE_DIR = r"C:\Users\amisf\Desktop\datascientest_projet"
19
+ OUT_DIR = os.path.join(BASE_DIR, "implementation", "outputs")
20
+
21
+ class RakutenDataset(Dataset):
22
+ def __init__(self, df, transform=None):
23
+ self.paths = df['path'].values
24
+ self.labels = df['label'].values
25
+ self.transform = transform
26
+ def __len__(self): return len(self.paths)
27
+ def __getitem__(self, idx):
28
+ try:
29
+ img = cv2.imread(self.paths[idx])
30
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
31
+ if self.transform: img = self.transform(img)
32
+ return img, torch.tensor(self.labels[idx], dtype=torch.long)
33
+ except:
34
+ return torch.zeros((3, IMG_SIZE, IMG_SIZE)), torch.tensor(self.labels[idx], dtype=torch.long)
35
+
36
+ def train_m1():
37
+ print("lancement train m1 (dino deep learning)")
38
+ # data setup
39
+ path_img = os.path.join(BASE_DIR, "data", "raw", "images", "images")
40
+ df = pd.read_csv(os.path.join(BASE_DIR, "data", "raw", "X_train_update.csv"))
41
+ y = pd.read_csv(os.path.join(BASE_DIR, "data", "raw", "Y_train_CVw08PX.csv"))
42
+ if 'prdtypecode' not in y.columns: y = y.rename(columns={y.columns[1]: 'prdtypecode'})
43
+ df = df.merge(y, left_index=True, right_index=True)
44
+ df['path'] = df.apply(lambda r: os.path.join(path_img, f"image_{r['imageid']}_product_{r['productid']}.jpg"), axis=1)
45
+ df = df[df['path'].apply(os.path.exists)]
46
+
47
+ le = preprocessing.LabelEncoder()
48
+ df['label'] = le.fit_transform(df['prdtypecode'])
49
+ train_df, _ = train_test_split(df, test_size=0.15, stratify=df['label'])
50
+
51
+ trans = transforms.Compose([
52
+ transforms.ToPILImage(),
53
+ transforms.Resize((IMG_SIZE, IMG_SIZE)),
54
+ transforms.ToTensor(),
55
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
56
+ ])
57
+
58
+ train_loader = DataLoader(RakutenDataset(train_df, trans), batch_size=BATCH_SIZE, shuffle=True, num_workers=0)
59
+
60
+ # model dino reg4
61
+ model = timm.create_model('vit_large_patch14_reg4_dinov2.lvd142m', pretrained=True, num_classes=27)
62
+ model.to(DEVICE)
63
+
64
+ optimizer = optim.AdamW(model.parameters(), lr=1e-5)
65
+ criterion = nn.CrossEntropyLoss()
66
+ scaler = torch.amp.GradScaler('cuda')
67
+
68
+ # boucle rapide demo
69
+ for ep in range(1):
70
+ model.train()
71
+ for i, (bx, by) in enumerate(train_loader):
72
+ bx, by = bx.to(DEVICE), by.to(DEVICE)
73
+ with torch.amp.autocast('cuda'):
74
+ out = model(bx)
75
+ loss = criterion(out, by) / ACCUM_STEPS
76
+ scaler.scale(loss).backward()
77
+ if (i+1) % ACCUM_STEPS == 0:
78
+ scaler.step(optimizer); scaler.update(); optimizer.zero_grad()
79
+
80
+ torch.save(model.state_dict(), os.path.join(OUT_DIR, "M1_IMAGE_DeepLearning_DINOv3.pth"))
81
+
82
+ if __name__ == "__main__":
83
+ train_m1()
src/image_models/train/train_M2_xgboost.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import xgboost as xgb
2
+ import os
3
+ import numpy as np
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.preprocessing import LabelEncoder
6
+ import joblib
7
+
8
+ # chemins
9
+ BASE_DIR = r"C:\Users\amisf\Desktop\datascientest_projet"
10
+ OUT_DIR = os.path.join(BASE_DIR, "implementation", "outputs")
11
+
12
+ def train_m2():
13
+ print("lancement train m2 xgboost")
14
+
15
+ # je charge les features numpy extraites
16
+ x_path = os.path.join(OUT_DIR, 'train_features_resnet50_augmented.npy')
17
+ y_path = os.path.join(OUT_DIR, 'train_labels_augmented.npy')
18
+
19
+ if not os.path.exists(x_path):
20
+ print("features introuvables")
21
+ return
22
+
23
+ x_data = np.load(x_path)
24
+ y_data = np.load(y_path)
25
+
26
+ # encode labels
27
+ le = LabelEncoder()
28
+ y_enc = le.fit_transform(y_data)
29
+
30
+ # je sauvegarde l encodeur pour la predict
31
+ joblib.dump(le, os.path.join(OUT_DIR, "M2_encoder.pkl"))
32
+
33
+ # split
34
+ x_train, x_val, y_train, y_val = train_test_split(x_data, y_enc, test_size=0.2)
35
+
36
+ # config gpu hist
37
+ params = {
38
+ 'objective': 'multi:softmax',
39
+ 'num_class': len(le.classes_),
40
+ 'n_estimators': 3000,
41
+ 'max_depth': 8,
42
+ 'learning_rate': 0.05,
43
+ 'tree_method': 'hist',
44
+ 'device': 'cuda',
45
+ 'early_stopping_rounds': 50
46
+ }
47
+
48
+ # fit
49
+ model = xgb.XGBClassifier(**params)
50
+ model.fit(
51
+ x_train, y_train,
52
+ eval_set=[(x_val, y_val)],
53
+ verbose=100
54
+ )
55
+
56
+ # save format json xgboost
57
+ model.save_model(os.path.join(OUT_DIR, "M2_IMAGE_Classic_XGBoost.json"))
58
+ print("modele m2 sauvegarde")
59
+
60
+ if __name__ == "__main__":
61
+ train_m2()
src/image_models/train/train_M3_effnet.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ from torchvision import models, transforms
5
+ import os
6
+ import pandas as pd
7
+ from sklearn.model_selection import train_test_split
8
+ from sklearn import preprocessing
9
+ from torch.utils.data import DataLoader, Dataset
10
+ import cv2
11
+
12
+ # config
13
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
+ BATCH_SIZE = 32
15
+ IMG_SIZE = 224
16
+
17
+ # chemins
18
+ BASE_DIR = r"C:\Users\amisf\Desktop\datascientest_projet"
19
+ OUT_DIR = os.path.join(BASE_DIR, "implementation", "outputs")
20
+
21
+ class RakutenDataset(Dataset):
22
+ def __init__(self, df, transform=None):
23
+ self.paths = df['path'].values
24
+ self.labels = df['label'].values
25
+ self.transform = transform
26
+ def __len__(self): return len(self.paths)
27
+ def __getitem__(self, idx):
28
+ try:
29
+ img = cv2.imread(self.paths[idx])
30
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
31
+ if self.transform: img = self.transform(img)
32
+ return img, torch.tensor(self.labels[idx], dtype=torch.long)
33
+ except:
34
+ return torch.zeros((3, IMG_SIZE, IMG_SIZE)), torch.tensor(self.labels[idx], dtype=torch.long)
35
+
36
+ def train_m3():
37
+ print("lancement train m3 efficientnet")
38
+
39
+ # chargement data
40
+ path_img = os.path.join(BASE_DIR, "data", "raw", "images", "images")
41
+ df = pd.read_csv(os.path.join(BASE_DIR, "data", "raw", "X_train_update.csv"))
42
+ y = pd.read_csv(os.path.join(BASE_DIR, "data", "raw", "Y_train_CVw08PX.csv"))
43
+
44
+ if 'prdtypecode' not in y.columns: y = y.rename(columns={y.columns[1]: 'prdtypecode'})
45
+ df = df.merge(y, left_index=True, right_index=True)
46
+ df['path'] = df.apply(lambda r: os.path.join(path_img, f"image_{r['imageid']}_product_{r['productid']}.jpg"), axis=1)
47
+ df = df[df['path'].apply(os.path.exists)]
48
+
49
+ le = preprocessing.LabelEncoder()
50
+ df['label'] = le.fit_transform(df['prdtypecode'])
51
+ train_df, val_df = train_test_split(df, test_size=0.15, stratify=df['label'])
52
+
53
+ trans = transforms.Compose([
54
+ transforms.ToPILImage(),
55
+ transforms.Resize((IMG_SIZE, IMG_SIZE)),
56
+ transforms.ToTensor(),
57
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
58
+ ])
59
+
60
+ train_ds = RakutenDataset(train_df, transform=trans)
61
+ train_loader = DataLoader(train_ds, batch_size=BATCH_SIZE, shuffle=True, num_workers=0)
62
+
63
+ # load model effnet b0
64
+ model = models.efficientnet_b0(weights="DEFAULT")
65
+
66
+ # modif tete
67
+ in_features = model.classifier[1].in_features
68
+ model.classifier[1] = nn.Linear(in_features, 27)
69
+ model.to(DEVICE)
70
+
71
+ optimizer = optim.AdamW(model.parameters(), lr=1e-3)
72
+ criterion = nn.CrossEntropyLoss()
73
+
74
+ # train rapide
75
+ for ep in range(5):
76
+ model.train()
77
+ for bx, by in train_loader:
78
+ bx, by = bx.to(DEVICE), by.to(DEVICE)
79
+ optimizer.zero_grad()
80
+ out = model(bx)
81
+ loss = criterion(out, by)
82
+ loss.backward()
83
+ optimizer.step()
84
+ print(f"fin epoch {ep+1}")
85
+
86
+ torch.save(model.state_dict(), os.path.join(OUT_DIR, "M3_IMAGE_Classic_EfficientNetB0.pth"))
87
+ print("modele m3 sauvegarde")
88
+
89
+ if __name__ == "__main__":
90
+ train_m3()
src/image_models/train/train_M4_overfit.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ from torch.utils.data import TensorDataset, DataLoader
5
+ from torchvision import models
6
+ import numpy as np
7
+ import os
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.preprocessing import LabelEncoder
10
+
11
+ # config
12
+ DEVICE = torch.device("cuda")
13
+ BASE_DIR = r"C:\Users\amisf\Desktop\datascientest_projet"
14
+ OUT_DIR = os.path.join(BASE_DIR, "implementation", "outputs")
15
+
16
+ # architecture legend (mlp custom)
17
+ class LegendMLP(nn.Module):
18
+ def __init__(self, input_dim, num_classes):
19
+ super().__init__()
20
+ self.net = nn.Sequential(
21
+ nn.Linear(input_dim, 2048), nn.BatchNorm1d(2048), nn.GELU(), nn.Dropout(0.2),
22
+ nn.Linear(2048, 1024), nn.BatchNorm1d(1024), nn.GELU(), nn.Dropout(0.2),
23
+ nn.Linear(1024, 512), nn.BatchNorm1d(512), nn.GELU(), nn.Dropout(0.2),
24
+ nn.Linear(512, num_classes)
25
+ )
26
+ def forward(self, x): return self.net(x)
27
+
28
+ def train_m4():
29
+ print("lancement train m4 (overfit phoenix)")
30
+
31
+ # chargement npy
32
+ try:
33
+ x_all = np.load(os.path.join(OUT_DIR, 'train_features_resnet50_augmented.npy'))
34
+ y_all_raw = np.load(os.path.join(OUT_DIR, 'train_labels_augmented.npy'))
35
+ except:
36
+ print("fichiers npy introuvables"); return
37
+
38
+ le = LabelEncoder()
39
+ y_all = le.fit_transform(y_all_raw)
40
+ x_train, x_val, y_train, y_val = train_test_split(x_all, y_all, test_size=0.2, stratify=y_all)
41
+
42
+ train_ds = TensorDataset(torch.tensor(x_train).float().to(DEVICE), torch.tensor(y_train).long().to(DEVICE))
43
+ train_loader = DataLoader(train_ds, batch_size=4096, shuffle=True)
44
+
45
+ # mlp training
46
+ mlp = LegendMLP(2048, len(le.classes_)).to(DEVICE)
47
+ optimizer = optim.Adam(mlp.parameters(), lr=0.001)
48
+ criterion = nn.CrossEntropyLoss()
49
+
50
+ for ep in range(20):
51
+ mlp.train()
52
+ for bx, by in train_loader:
53
+ optimizer.zero_grad()
54
+ out = mlp(bx)
55
+ loss = criterion(out, by)
56
+ loss.backward()
57
+ optimizer.step()
58
+ print(f"epoch {ep+1} ok")
59
+
60
+ # assemblage final resnet + mlp
61
+ full_model = models.resnet50(weights="IMAGENET1K_V1")
62
+ full_model.fc = mlp
63
+ torch.save(full_model.state_dict(), os.path.join(OUT_DIR, "M4_IMAGE_DeepLearning_OVERFIT_ResNet.pth"))
64
+ print("modele m4 sauvegarde")
65
+
66
+ if __name__ == "__main__":
67
+ train_m4()
src/image_models/visualization/__init__.py ADDED
File without changes
src/image_models/visualization/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/image_models/visualization/visualize.py ADDED
File without changes
src/streamlit/README.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rakuten Product Classifier
2
+
3
+ Application de classification automatique de produits e-commerce en 27 catégories.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ cd src/streamlit
9
+ pip install -r requirements.txt
10
+ ```
11
+
12
+ ## Lancer l'app
13
+
14
+ ```bash
15
+ streamlit run app.py
16
+ ```
17
+
18
+ L'app tourne sur `http://localhost:8501`
19
+
20
+ ## Structure
21
+
22
+ ```
23
+ ├── app.py # Page d'accueil
24
+ ├── pages/
25
+ │ ├── 1_Données # Stats du dataset (84K produits, distribution)
26
+ │ ├── 2_Preprocessing # Pipeline NLP et image
27
+ │ ├── 3_Modèles # Comparaison des 6 modèles (3 texte, 3 image)
28
+ │ ├── 4_Démo # Tester la classification
29
+ │ ├── 5_Performance # Métriques (accuracy, F1, confusion matrix)
30
+ │ ├── 6_Conclusions # Résultats et perspectives
31
+ │ ├── 7_Qualité # Tests automatisés et couverture
32
+ │ └── 8_Explicabilité # SHAP, LIME, Grad-CAM
33
+ ├── utils/ # Code métier
34
+ └── tests/ # Tests pytest
35
+ ```
36
+
37
+ ## Fonctionnalités
38
+
39
+ - Classification texte ou image (pas de multimodal)
40
+ - 3 modèles texte : TF-IDF+SVM, TF-IDF+RF, CamemBERT
41
+ - 3 modèles image : ResNet50+SVM, ResNet50+RF, VGG16+SVM
42
+ - Comparaison côte à côte des modèles
43
+ - Visualisations interactives (Plotly)
44
+
45
+ ## Tests
46
+
47
+ ```bash
48
+ pip install -r requirements-test.txt
49
+ pytest
50
+ ```
51
+
52
+ ## Mode démo
53
+
54
+ L'app fonctionne en mode simulation (mock) sans les vrais modèles ML.
55
+ Pour utiliser les vrais modèles, placer les fichiers `.joblib` dans `models/`.
56
+
57
+ ## Stack
58
+
59
+ - Streamlit
60
+ - Plotly
61
+ - scikit-learn
62
+ - Pillow
src/streamlit/app.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Application Streamlit - Classification de produits Rakuten.
3
+ """
4
+ import streamlit as st
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ # --- GESTION DES CHEMINS ROBUSTE ---
9
+ # Ajout de la racine du projet au path pour trouver 'config' et 'utils'
10
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
11
+
12
+ from config import APP_CONFIG, MODEL_CONFIG, ASSETS_DIR
13
+ from utils.ui_utils import load_css
14
+ from utils.category_mapping import get_all_categories
15
+
16
+ # Configuration de la page
17
+ st.set_page_config(
18
+ page_title=APP_CONFIG["title"],
19
+ page_icon=APP_CONFIG["icon"],
20
+ layout=APP_CONFIG["layout"],
21
+ initial_sidebar_state=APP_CONFIG["initial_sidebar_state"],
22
+ )
23
+
24
+ # Chargement du style CSS
25
+ if (ASSETS_DIR / "style.css").exists():
26
+ load_css(ASSETS_DIR / "style.css")
27
+
28
+ # --- INITIALISATION DU CLASSIFIEUR (SESSION STATE) ---
29
+ if "classifier" not in st.session_state:
30
+ with st.spinner("Chargement des cerveaux numériques (DINO + XGBoost + EfficientNet)..."):
31
+ # On importe la classe CORRECTEMENT NOMMÉE
32
+ from utils.real_classifier import MultimodalClassifier
33
+ try:
34
+ # On instancie le vrai classifieur
35
+ st.session_state.classifier = MultimodalClassifier()
36
+ st.session_state.use_mock = False
37
+ except Exception as e:
38
+ st.error(f"Echec chargement modèle : {e}")
39
+ # En cas d'erreur critique, on charge le mock pour ne pas planter l'app
40
+ from utils.mock_classifier import DemoClassifier
41
+ st.session_state.classifier = DemoClassifier()
42
+ st.session_state.use_mock = True
43
+
44
+ if "use_mock" not in st.session_state:
45
+ st.session_state.use_mock = MODEL_CONFIG["use_mock"]
46
+
47
+ # --- HEADER & TITRE ---
48
+ st.title("Rakuten Product Classifier")
49
+ st.markdown("Classification automatique de produits e-commerce en 27 catégories.")
50
+
51
+ st.divider()
52
+
53
+ # Métriques clés
54
+ col1, col2, col3, col4 = st.columns(4)
55
+ col1.metric("Produits", "84 916")
56
+ col2.metric("Catégories", "27")
57
+ col3.metric("Modalités", "Texte + Image")
58
+ col4.metric("Précision", "86.5%") # Chiffre mis à jour (Multimodal)
59
+
60
+ st.divider()
61
+
62
+ # Contexte
63
+ st.header("Le Projet")
64
+ st.markdown("""
65
+ Rakuten France traite des millions de produits chaque année.
66
+ Ce projet automatise la classification par Deep Learning multimodal,
67
+ combinant analyse de texte (désignation, description) et d'image.
68
+ """)
69
+
70
+ # Pipeline
71
+ st.header("Pipeline")
72
+ col1, col2, col3 = st.columns(3)
73
+
74
+ with col1:
75
+ st.subheader("Texte")
76
+ st.markdown("TF-IDF + LinearSVC")
77
+
78
+ with col2:
79
+ st.subheader("Image")
80
+ st.markdown("Voting : DINOv3 + XGBoost + EfficientNet")
81
+
82
+ with col3:
83
+ st.subheader("Fusion")
84
+ st.markdown("Pondération Dynamique (50/50)")
85
+
86
+ st.divider()
87
+
88
+ # Catégories (grille compacte)
89
+ st.header("27 Catégories")
90
+ try:
91
+ categories = get_all_categories()
92
+ cat_list = list(categories.items())
93
+
94
+ for i in range(0, 27, 9):
95
+ cols = st.columns(9)
96
+ for j, col in enumerate(cols):
97
+ if i + j < len(cat_list):
98
+ code, (name, full_name, emoji) = cat_list[i + j]
99
+ col.markdown(f"{emoji} **{name}**")
100
+ except:
101
+ st.info("Chargement des catégories en cours...")
102
+
103
+ st.divider()
104
+
105
+ # Navigation
106
+ st.header("Tester")
107
+ col1, col2 = st.columns(2)
108
+ with col1:
109
+ if st.button("Classifier un produit", use_container_width=True, type="primary"):
110
+ st.switch_page("pages/4_🔍_Démo.py")
111
+ with col2:
112
+ if st.button("Explorer les données", use_container_width=True, type="primary"):
113
+ st.switch_page("pages/1_📊_Données.py")
114
+
115
+ # Footer
116
+ st.divider()
117
+ st.caption("Projet DataScientest — Formation BMLE Octobre 2025")
118
+
119
+ # Sidebar
120
+ with st.sidebar:
121
+ st.markdown("### Rakuten")
122
+ st.markdown("Product Classifier")
123
+ st.divider()
124
+ if st.session_state.use_mock:
125
+ st.warning("Mode Démo (Mock)")
126
+ else:
127
+ st.success("Production (GPU)")
src/streamlit/assets/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/streamlit/assets/examples/.gitkeep ADDED
File without changes
src/streamlit/assets/examples/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/streamlit/assets/heatmap clair .png ADDED

Git LFS Details

  • SHA256: f06439e54e7d133ff13566fe76851e0696bc188a02fcf6bbd76c7295dbea273f
  • Pointer size: 131 Bytes
  • Size of remote file: 372 kB
src/streamlit/assets/heatmap_clair.png ADDED

Git LFS Details

  • SHA256: f06439e54e7d133ff13566fe76851e0696bc188a02fcf6bbd76c7295dbea273f
  • Pointer size: 131 Bytes
  • Size of remote file: 372 kB
src/streamlit/assets/style.css ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Styles Rakuten - Thème clair
3
+ * Inspiré du site officiel Rakuten
4
+ */
5
+
6
+ /* Variables CSS */
7
+ :root {
8
+ --rakuten-red: #BF0000;
9
+ --rakuten-red-dark: #990000;
10
+ --rakuten-white: #FFFFFF;
11
+ --rakuten-bg: #FAFAFA;
12
+ --rakuten-gray-light: #F5F5F5;
13
+ --rakuten-gray: #666666;
14
+ --rakuten-gray-dark: #333333;
15
+ --rakuten-border: #E0E0E0;
16
+ --success-green: #28A745;
17
+ --warning-yellow: #FF9800;
18
+ --error-red: #DC3545;
19
+ }
20
+
21
+ /* Force light mode - Application background */
22
+ .stApp {
23
+ background-color: var(--rakuten-bg) !important;
24
+ color: var(--rakuten-gray-dark) !important;
25
+ }
26
+
27
+ /* All text dark */
28
+ .stApp p, .stApp span, .stApp label, .stApp li {
29
+ color: var(--rakuten-gray-dark) !important;
30
+ }
31
+
32
+ /* Headers red */
33
+ h1, h2, h3, h4 {
34
+ color: var(--rakuten-red) !important;
35
+ }
36
+
37
+ /* Primary buttons */
38
+ .stButton > button {
39
+ background-color: var(--rakuten-red) !important;
40
+ color: #FFFFFF !important;
41
+ border: none !important;
42
+ border-radius: 8px;
43
+ padding: 0.5rem 1.5rem;
44
+ font-weight: bold;
45
+ transition: background-color 0.2s ease;
46
+ }
47
+
48
+ .stButton > button:hover {
49
+ background-color: var(--rakuten-red-dark) !important;
50
+ color: #FFFFFF !important;
51
+ }
52
+
53
+ .stButton > button p,
54
+ .stButton > button span,
55
+ .stButton > button div {
56
+ color: #FFFFFF !important;
57
+ }
58
+
59
+ /* Primary type button */
60
+ .stButton > button[kind="primary"],
61
+ .stButton > button[data-testid="stBaseButton-primary"] {
62
+ background-color: var(--rakuten-red) !important;
63
+ color: #FFFFFF !important;
64
+ }
65
+
66
+ .stButton > button[kind="primary"] p,
67
+ .stButton > button[kind="primary"] span,
68
+ .stButton > button[data-testid="stBaseButton-primary"] p,
69
+ .stButton > button[data-testid="stBaseButton-primary"] span {
70
+ color: #FFFFFF !important;
71
+ }
72
+
73
+ /* Secondary buttons (gray background) */
74
+ .stButton > button[kind="secondary"],
75
+ .stButton > button[data-testid="stBaseButton-secondary"] {
76
+ background-color: #F0F0F0 !important;
77
+ color: #333333 !important;
78
+ border: 1px solid #CCCCCC !important;
79
+ }
80
+
81
+ .stButton > button[kind="secondary"] p,
82
+ .stButton > button[kind="secondary"] span,
83
+ .stButton > button[data-testid="stBaseButton-secondary"] p,
84
+ .stButton > button[data-testid="stBaseButton-secondary"] span {
85
+ color: #333333 !important;
86
+ }
87
+
88
+ /* Download button */
89
+ .stDownloadButton > button {
90
+ background-color: var(--rakuten-red) !important;
91
+ color: #FFFFFF !important;
92
+ border: none !important;
93
+ }
94
+
95
+ .stDownloadButton > button p,
96
+ .stDownloadButton > button span,
97
+ .stDownloadButton > button div {
98
+ color: #FFFFFF !important;
99
+ }
100
+
101
+ .stDownloadButton > button:hover {
102
+ background-color: var(--rakuten-red-dark) !important;
103
+ }
104
+
105
+ /* Cards */
106
+ .prediction-card {
107
+ background-color: white;
108
+ padding: 1.5rem;
109
+ border-radius: 12px;
110
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
111
+ margin-bottom: 1rem;
112
+ color: var(--rakuten-gray-dark);
113
+ }
114
+
115
+ /* Category badge */
116
+ .category-badge {
117
+ display: inline-block;
118
+ background-color: var(--rakuten-red);
119
+ color: white !important;
120
+ padding: 0.5rem 1rem;
121
+ border-radius: 20px;
122
+ font-size: 1.1rem;
123
+ font-weight: bold;
124
+ }
125
+
126
+ /* Confidence indicators */
127
+ .confidence-high {
128
+ color: var(--success-green) !important;
129
+ font-weight: bold;
130
+ }
131
+
132
+ .confidence-medium {
133
+ color: var(--warning-yellow) !important;
134
+ font-weight: bold;
135
+ }
136
+
137
+ .confidence-low {
138
+ color: var(--error-red) !important;
139
+ }
140
+
141
+ /* Sidebar - Light */
142
+ [data-testid="stSidebar"] {
143
+ background-color: var(--rakuten-white) !important;
144
+ border-right: 1px solid var(--rakuten-border);
145
+ }
146
+
147
+ [data-testid="stSidebar"] p,
148
+ [data-testid="stSidebar"] span,
149
+ [data-testid="stSidebar"] label {
150
+ color: var(--rakuten-gray-dark) !important;
151
+ }
152
+
153
+ /* Progress bars */
154
+ .stProgress > div > div {
155
+ background-color: var(--rakuten-red) !important;
156
+ }
157
+
158
+ /* File uploader */
159
+ [data-testid="stFileUploader"] {
160
+ background-color: white !important;
161
+ border: 2px dashed var(--rakuten-border) !important;
162
+ border-radius: 10px;
163
+ padding: 1rem;
164
+ transition: border-color 0.2s ease;
165
+ }
166
+
167
+ [data-testid="stFileUploader"]:hover {
168
+ border-color: var(--rakuten-red) !important;
169
+ }
170
+
171
+ /* Metrics */
172
+ [data-testid="stMetric"] {
173
+ background-color: white !important;
174
+ padding: 1rem;
175
+ border-radius: 8px;
176
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
177
+ }
178
+
179
+ [data-testid="stMetricLabel"] {
180
+ color: var(--rakuten-gray) !important;
181
+ }
182
+
183
+ [data-testid="stMetricValue"] {
184
+ color: var(--rakuten-red) !important;
185
+ }
186
+
187
+ /* Tabs */
188
+ .stTabs [data-baseweb="tab-list"] {
189
+ background-color: transparent !important;
190
+ gap: 8px;
191
+ }
192
+
193
+ .stTabs [data-baseweb="tab"] {
194
+ background-color: var(--rakuten-gray-light) !important;
195
+ color: #333333 !important;
196
+ border-radius: 8px 8px 0 0;
197
+ padding: 0.5rem 1rem;
198
+ }
199
+
200
+ .stTabs [data-baseweb="tab"] p,
201
+ .stTabs [data-baseweb="tab"] span,
202
+ .stTabs [data-baseweb="tab"] div {
203
+ color: #333333 !important;
204
+ }
205
+
206
+ .stTabs [aria-selected="true"] {
207
+ background-color: var(--rakuten-red) !important;
208
+ color: #FFFFFF !important;
209
+ }
210
+
211
+ .stTabs [aria-selected="true"] p,
212
+ .stTabs [aria-selected="true"] span,
213
+ .stTabs [aria-selected="true"] div {
214
+ color: #FFFFFF !important;
215
+ }
216
+
217
+ /* Mode indicator */
218
+ .mode-indicator {
219
+ background-color: #FFF3CD;
220
+ border: 1px solid #FFE69C;
221
+ border-radius: 5px;
222
+ padding: 0.5rem 1rem;
223
+ font-size: 0.9rem;
224
+ margin-bottom: 1rem;
225
+ color: #856404;
226
+ }
227
+
228
+ /* Result display */
229
+ .result-header {
230
+ text-align: center;
231
+ padding: 1.5rem;
232
+ background: linear-gradient(135deg, var(--rakuten-red) 0%, var(--rakuten-red-dark) 100%);
233
+ border-radius: 10px;
234
+ color: white !important;
235
+ margin-bottom: 1rem;
236
+ }
237
+
238
+ /* Top predictions list */
239
+ .prediction-item {
240
+ display: flex;
241
+ align-items: center;
242
+ padding: 0.75rem;
243
+ background-color: white;
244
+ border-radius: 8px;
245
+ margin-bottom: 0.5rem;
246
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
247
+ color: var(--rakuten-gray-dark);
248
+ }
249
+
250
+ .prediction-item:first-child {
251
+ border-left: 4px solid var(--rakuten-red);
252
+ }
253
+
254
+ /* Inputs - Light */
255
+ .stTextInput > div > div > input,
256
+ .stTextArea > div > div > textarea {
257
+ background-color: white !important;
258
+ color: var(--rakuten-gray-dark) !important;
259
+ border: 1px solid var(--rakuten-border) !important;
260
+ }
261
+
262
+ /* Select boxes */
263
+ [data-baseweb="select"] {
264
+ background-color: white !important;
265
+ }
266
+
267
+ [data-baseweb="select"] * {
268
+ color: var(--rakuten-gray-dark) !important;
269
+ }
270
+
271
+ /* Expander */
272
+ .streamlit-expanderHeader {
273
+ background-color: white !important;
274
+ color: var(--rakuten-gray-dark) !important;
275
+ }
276
+
277
+ /* Alerts - keep readable */
278
+ .stAlert {
279
+ color: var(--rakuten-gray-dark) !important;
280
+ }
281
+
282
+ /* Captions */
283
+ .stCaption, [data-testid="stCaptionContainer"] {
284
+ color: var(--rakuten-gray) !important;
285
+ }
286
+
287
+ /* Footer */
288
+ .app-footer {
289
+ text-align: center;
290
+ color: var(--rakuten-gray);
291
+ padding: 1rem;
292
+ margin-top: 2rem;
293
+ border-top: 1px solid var(--rakuten-border);
294
+ }
src/streamlit/components/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Composants réutilisables pour l'application Streamlit Rakuten.
3
+
4
+ Ce module contiendra les widgets et composants UI réutilisables:
5
+ - image_uploader: Widget d'upload d'images amélioré
6
+ - text_input: Widget de saisie de texte structuré
7
+ - result_display: Composants d'affichage des résultats
8
+ - charts: Graphiques Plotly réutilisables
9
+ - sidebar: Composants de navigation
10
+ """
src/streamlit/components/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/streamlit/config.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ # --- RACINE DU PROJET ---
4
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
5
+
6
+ # --- ARBORESCENCE DONNÉES (Vital pour page 1_Données) ---
7
+ DATA_DIR = PROJECT_ROOT / "data"
8
+ RAW_DATA_DIR = DATA_DIR / "raw"
9
+ PROCESSED_DATA_DIR = DATA_DIR / "processed" # <--- C'était l'erreur manquante
10
+ IMAGES_DIR = RAW_DATA_DIR / "images" / "images" / "image_train"
11
+
12
+ # --- ARBORESCENCE MODÈLES ---
13
+ MODELS_DIR = PROJECT_ROOT / "models"
14
+ OUTPUTS_DIR = PROJECT_ROOT / "implementation" / "outputs"
15
+
16
+ # --- ARBORESCENCE STREAMLIT ---
17
+ STREAMLIT_DIR = Path(__file__).parent
18
+ ASSETS_DIR = STREAMLIT_DIR / "assets"
19
+
20
+ # --- CHEMINS MODÈLES (LES PERFORMANTS) ---
21
+ # 1. DINOv3
22
+ IMAGE_MODEL_PATH = OUTPUTS_DIR / "model_DINOv3_BEST.pth"
23
+ if not IMAGE_MODEL_PATH.exists():
24
+ IMAGE_MODEL_PATH = MODELS_DIR / "M1_IMAGE_DeepLearning_DINOv3.pth"
25
+
26
+ # 2. XGBoost (Le fichier json + l'encodeur pkl)
27
+ XGB_MODEL_PATH = OUTPUTS_DIR / "M2_IMAGE_Classic_XGBoost.json"
28
+ XGB_ENC_PATH = OUTPUTS_DIR / "M2_IMAGE_XGBoost_Encoder.pkl"
29
+
30
+ # 3. EfficientNet
31
+ EFF_MODEL_PATH = OUTPUTS_DIR / "M3_IMAGE_Classic_EfficientNetB0.pth"
32
+
33
+ # 4. Texte & Mapping
34
+ TEXT_MODEL_PATH = MODELS_DIR / "text_classifier.joblib"
35
+ # On essaie le tfidf dans models, sinon implementation/outputs
36
+ TFIDF_VECTORIZER_PATH = MODELS_DIR / "tfidf_vectorizer.joblib"
37
+ CATEGORY_MAPPING_PATH = MODELS_DIR / "category_mapping.json"
38
+
39
+ # --- CONFIG APPLICATION ---
40
+ APP_CONFIG = {
41
+ "title": "Rakuten Product Classifier",
42
+ "icon": "🛒",
43
+ "layout": "wide",
44
+ "initial_sidebar_state": "expanded"
45
+ }
46
+
47
+ # --- CONFIG MODÈLE ---
48
+ MODEL_CONFIG = {
49
+ "use_mock": False,
50
+ # Poids Fusion : 30% Texte / 70% Image
51
+ "fusion_weights_global": {"text": 0.3, "image": 0.7},
52
+ # Poids Voting Image : DINO(4) / XGB(2) / Eff(1)
53
+ "voting_weights": {"dino": 4.0, "xgb": 2.0, "effnet": 1.0}
54
+ }
src/streamlit/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/streamlit/docs/TESTING_STRATEGY.md ADDED
@@ -0,0 +1,982 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🧪 Stratégie de Tests - Rakuten Product Classifier
2
+
3
+ ## Executive Summary
4
+
5
+ Ce document définit une stratégie de tests **enterprise-grade** pour garantir la qualité, la fiabilité et la maintenabilité de l'application Rakuten Product Classifier.
6
+
7
+ **Objectif de couverture**: ≥ 85% du code critique
8
+
9
+ ---
10
+
11
+ ## 📊 Pyramide des Tests
12
+
13
+ ```
14
+ ┌─────────────────┐
15
+ │ E2E Tests │ ← 5% (Playwright)
16
+ │ (UI/Browser) │
17
+ ├─────────────────┤
18
+ │ Integration │ ← 20% (Streamlit + ML)
19
+ │ Tests │
20
+ ├─────────────────┤
21
+ │ ML-Specific │ ← 25% (Model Quality)
22
+ │ Tests │
23
+ ├─────────────────┤
24
+ │ │
25
+ │ Unit Tests │ ← 50% (Functions/Classes)
26
+ │ │
27
+ └─────────────────┘
28
+ ```
29
+
30
+ ---
31
+
32
+ ## 🎯 1. TESTS UNITAIRES (Unit Tests)
33
+
34
+ ### 1.1 Module `utils/mock_classifier.py`
35
+
36
+ | Test ID | Fonction testée | Description | Priorité |
37
+ |---------|----------------|-------------|----------|
38
+ | UT-MC-001 | `DemoClassifier.__init__` | Initialisation avec/sans config | HIGH |
39
+ | UT-MC-002 | `DemoClassifier.predict(text=...)` | Prédiction texte seul | HIGH |
40
+ | UT-MC-003 | `DemoClassifier.predict(image=...)` | Prédiction image seule | HIGH |
41
+ | UT-MC-004 | `DemoClassifier.predict(text, image)` | Prédiction multimodale | HIGH |
42
+ | UT-MC-005 | `ClassificationResult` | Dataclass attributes | MEDIUM |
43
+ | UT-MC-006 | `_generate_predictions` | Distribution probabilités | HIGH |
44
+ | UT-MC-007 | `ModelConfig` | Validation dataclass | MEDIUM |
45
+ | UT-MC-008 | `TEXT_MODELS` | 3 modèles texte présents | HIGH |
46
+ | UT-MC-009 | `IMAGE_MODELS` | 3 modèles image présents | HIGH |
47
+ | UT-MC-010 | `MultiModelClassifier` | Prédictions multi-modèles | HIGH |
48
+
49
+ **Assertions clés**:
50
+ ```python
51
+ # UT-MC-002: Prédiction texte
52
+ def test_predict_text_returns_valid_result():
53
+ clf = DemoClassifier()
54
+ result = clf.predict(text="iPhone 15 Pro Max")
55
+
56
+ assert result is not None
57
+ assert result.category in CATEGORY_MAPPING.keys()
58
+ assert 0.0 <= result.confidence <= 1.0
59
+ assert len(result.top_k_predictions) == 5
60
+ assert sum(p[1] for p in result.top_k_predictions) <= 1.0
61
+ assert result.source in ["mock_text", "text", "demo"]
62
+ ```
63
+
64
+ ### 1.2 Module `utils/category_mapping.py`
65
+
66
+ | Test ID | Fonction testée | Description | Priorité |
67
+ |---------|----------------|-------------|----------|
68
+ | UT-CM-001 | `CATEGORY_MAPPING` | 27 catégories présentes | HIGH |
69
+ | UT-CM-002 | `get_category_info(code)` | Retourne (name, full, emoji) | HIGH |
70
+ | UT-CM-003 | `get_category_info(invalid)` | Gestion code invalide | MEDIUM |
71
+ | UT-CM-004 | `get_category_emoji(code)` | Retourne emoji correct | LOW |
72
+ | UT-CM-005 | `get_all_categories()` | Retourne dict complet | MEDIUM |
73
+
74
+ **Assertions clés**:
75
+ ```python
76
+ # UT-CM-001: Vérification 27 catégories
77
+ def test_category_mapping_has_27_categories():
78
+ assert len(CATEGORY_MAPPING) == 27
79
+
80
+ # UT-CM-002: Structure correcte
81
+ def test_get_category_info_returns_tuple():
82
+ name, full, emoji = get_category_info("2583")
83
+ assert isinstance(name, str)
84
+ assert isinstance(full, str)
85
+ assert len(emoji) > 0 # Emoji présent
86
+ ```
87
+
88
+ ### 1.3 Module `utils/preprocessing.py`
89
+
90
+ | Test ID | Fonction testée | Description | Priorité |
91
+ |---------|----------------|-------------|----------|
92
+ | UT-PP-001 | `preprocess_product_text` | Nettoyage HTML | HIGH |
93
+ | UT-PP-002 | `preprocess_product_text` | Combinaison designation+description | HIGH |
94
+ | UT-PP-003 | `preprocess_product_text` | Gestion texte vide | MEDIUM |
95
+ | UT-PP-004 | `preprocess_product_text` | Caractères spéciaux | MEDIUM |
96
+ | UT-PP-005 | `validate_text_input` | Validation longueur | HIGH |
97
+ | UT-PP-006 | `clean_html` | Suppression balises | HIGH |
98
+
99
+ **Cas de test**:
100
+ ```python
101
+ @pytest.mark.parametrize("input_text,expected_contains", [
102
+ ("<p>Test</p>", "Test"), # HTML removal
103
+ (" spaces ", "spaces"), # Trim
104
+ ("UPPERCASE", "uppercase"), # Lowercase (si applicable)
105
+ ("", ""), # Empty string
106
+ (None, ""), # None handling
107
+ ])
108
+ def test_preprocess_handles_various_inputs(input_text, expected_contains):
109
+ result = preprocess_product_text(input_text, "")
110
+ if expected_contains:
111
+ assert expected_contains in result.lower()
112
+ ```
113
+
114
+ ### 1.4 Module `utils/image_utils.py`
115
+
116
+ | Test ID | Fonction testée | Description | Priorité |
117
+ |---------|----------------|-------------|----------|
118
+ | UT-IU-001 | `load_image_from_upload` | Chargement JPEG | HIGH |
119
+ | UT-IU-002 | `load_image_from_upload` | Chargement PNG | HIGH |
120
+ | UT-IU-003 | `validate_image` | Image valide | HIGH |
121
+ | UT-IU-004 | `validate_image` | Image trop petite | MEDIUM |
122
+ | UT-IU-005 | `validate_image` | Image trop grande | MEDIUM |
123
+ | UT-IU-006 | `get_image_info` | Métadonnées correctes | LOW |
124
+ | UT-IU-007 | `resize_image` | Redimensionnement | MEDIUM |
125
+
126
+ ### 1.5 Module `utils/data_loader.py`
127
+
128
+ | Test ID | Fonction testée | Description | Priorité |
129
+ |---------|----------------|-------------|----------|
130
+ | UT-DL-001 | `is_data_available` | Détection données réelles | HIGH |
131
+ | UT-DL-002 | `get_dataset_summary` | Retourne dict valide | HIGH |
132
+ | UT-DL-003 | `get_category_distribution` | DataFrame correct | HIGH |
133
+ | UT-DL-004 | `get_text_statistics` | Stats texte | MEDIUM |
134
+ | UT-DL-005 | `load_training_data` | Fallback mode démo | HIGH |
135
+
136
+ ### 1.6 Module `config.py`
137
+
138
+ | Test ID | Fonction testée | Description | Priorité |
139
+ |---------|----------------|-------------|----------|
140
+ | UT-CF-001 | `APP_CONFIG` | Clés requises présentes | HIGH |
141
+ | UT-CF-002 | `MODEL_CONFIG` | Configuration modèle | HIGH |
142
+ | UT-CF-003 | `THEME` | Couleurs définies | LOW |
143
+ | UT-CF-004 | `ASSETS_DIR` | Path existe | MEDIUM |
144
+
145
+ ---
146
+
147
+ ## 🔗 2. TESTS D'INTÉGRATION (Integration Tests)
148
+
149
+ ### 2.1 Tests de chargement des pages
150
+
151
+ | Test ID | Page testée | Description | Priorité |
152
+ |---------|-------------|-------------|----------|
153
+ | IT-PG-001 | `app.py` | Page accueil charge sans erreur | CRITICAL |
154
+ | IT-PG-002 | `1_📊_Données.py` | Page données charge | CRITICAL |
155
+ | IT-PG-003 | `2_⚙️_Preprocessing.py` | Page preprocessing charge | CRITICAL |
156
+ | IT-PG-004 | `3_🧠_Modèles.py` | Page modèles charge | CRITICAL |
157
+ | IT-PG-005 | `4_🔍_Démo.py` | Page démo charge | CRITICAL |
158
+ | IT-PG-006 | `5_📈_Performance.py` | Page performance charge | CRITICAL |
159
+ | IT-PG-007 | `6_💡_Conclusions.py` | Page conclusions charge | CRITICAL |
160
+
161
+ **Implémentation avec `streamlit.testing`**:
162
+ ```python
163
+ from streamlit.testing.v1 import AppTest
164
+
165
+ def test_home_page_loads():
166
+ """Test que la page d'accueil charge sans erreur."""
167
+ at = AppTest.from_file("app.py")
168
+ at.run(timeout=30)
169
+
170
+ assert not at.exception
171
+ assert "Rakuten" in at.markdown[0].value
172
+
173
+ def test_demo_page_classification_flow():
174
+ """Test du flow complet de classification."""
175
+ at = AppTest.from_file("pages/4_🔍_Démo.py")
176
+ at.run()
177
+
178
+ # Simuler saisie texte
179
+ at.text_input[0].set_value("iPhone 15 Pro Max")
180
+ at.text_area[0].set_value("Smartphone Apple dernière génération")
181
+ at.button[0].click()
182
+ at.run()
183
+
184
+ assert not at.exception
185
+ # Vérifier qu'un résultat est affiché
186
+ assert any("Catégorie" in str(m.value) for m in at.markdown)
187
+ ```
188
+
189
+ ### 2.2 Tests de Session State
190
+
191
+ | Test ID | Description | Priorité |
192
+ |---------|-------------|----------|
193
+ | IT-SS-001 | Persistance du classifier entre pages | HIGH |
194
+ | IT-SS-002 | Historique des classifications | HIGH |
195
+ | IT-SS-003 | Sélection de modèle persiste | HIGH |
196
+ | IT-SS-004 | Reset session fonctionne | MEDIUM |
197
+
198
+ ### 2.3 Tests de Navigation
199
+
200
+ | Test ID | Description | Priorité |
201
+ |---------|-------------|----------|
202
+ | IT-NV-001 | Navigation accueil → démo | HIGH |
203
+ | IT-NV-002 | Navigation accueil → données | HIGH |
204
+ | IT-NV-003 | Navigation démo → comparaison | HIGH |
205
+ | IT-NV-004 | Sidebar navigation | MEDIUM |
206
+
207
+ ### 2.4 Tests d'intégration Classifier + UI
208
+
209
+ | Test ID | Description | Priorité |
210
+ |---------|-------------|----------|
211
+ | IT-CL-001 | Classification texte end-to-end | CRITICAL |
212
+ | IT-CL-002 | Classification image end-to-end | CRITICAL |
213
+ | IT-CL-003 | Changement de modèle | HIGH |
214
+ | IT-CL-004 | Comparaison 3 modèles simultanés | HIGH |
215
+
216
+ ---
217
+
218
+ ## 🤖 3. TESTS SPÉCIFIQUES ML (Machine Learning Tests)
219
+
220
+ ### 3.1 Tests de Performance du Modèle (Model Quality Gates)
221
+
222
+ | Test ID | Métrique | Seuil minimum | Priorité |
223
+ |---------|----------|---------------|----------|
224
+ | ML-PF-001 | Accuracy globale | ≥ 75% | CRITICAL |
225
+ | ML-PF-002 | F1-Score macro | ≥ 70% | CRITICAL |
226
+ | ML-PF-003 | F1-Score weighted | ≥ 75% | HIGH |
227
+ | ML-PF-004 | Precision macro | ≥ 70% | HIGH |
228
+ | ML-PF-005 | Recall macro | ≥ 65% | HIGH |
229
+
230
+ **Implémentation**:
231
+ ```python
232
+ import pytest
233
+ from sklearn.metrics import accuracy_score, f1_score, classification_report
234
+
235
+ class TestModelPerformance:
236
+ """Tests de qualité du modèle avec seuils minimaux."""
237
+
238
+ ACCURACY_THRESHOLD = 0.75
239
+ F1_MACRO_THRESHOLD = 0.70
240
+
241
+ @pytest.fixture(scope="class")
242
+ def model_predictions(self, test_dataset):
243
+ """Génère les prédictions sur le jeu de test."""
244
+ clf = load_production_model()
245
+ X_test, y_true = test_dataset
246
+ y_pred = clf.predict(X_test)
247
+ return y_true, y_pred
248
+
249
+ def test_accuracy_above_threshold(self, model_predictions):
250
+ """L'accuracy doit être ≥ 75%."""
251
+ y_true, y_pred = model_predictions
252
+ accuracy = accuracy_score(y_true, y_pred)
253
+
254
+ assert accuracy >= self.ACCURACY_THRESHOLD, \
255
+ f"Accuracy {accuracy:.2%} below threshold {self.ACCURACY_THRESHOLD:.2%}"
256
+
257
+ def test_f1_macro_above_threshold(self, model_predictions):
258
+ """Le F1-score macro doit être ≥ 70%."""
259
+ y_true, y_pred = model_predictions
260
+ f1 = f1_score(y_true, y_pred, average='macro')
261
+
262
+ assert f1 >= self.F1_MACRO_THRESHOLD, \
263
+ f"F1-macro {f1:.2%} below threshold {self.F1_MACRO_THRESHOLD:.2%}"
264
+ ```
265
+
266
+ ### 3.2 Tests de Non-Régression (Regression Tests)
267
+
268
+ | Test ID | Description | Priorité |
269
+ |---------|-------------|----------|
270
+ | ML-RG-001 | Accuracy ne baisse pas vs baseline | CRITICAL |
271
+ | ML-RG-002 | F1-score ne baisse pas | CRITICAL |
272
+ | ML-RG-003 | Prédictions identiques pour inputs fixes | HIGH |
273
+ | ML-RG-004 | Distribution des classes stable | MEDIUM |
274
+
275
+ **Implémentation avec snapshot**:
276
+ ```python
277
+ import json
278
+ from pathlib import Path
279
+
280
+ BASELINE_FILE = Path("tests/baselines/model_baseline.json")
281
+
282
+ class TestModelRegression:
283
+ """Tests de non-régression du modèle."""
284
+
285
+ REGRESSION_TOLERANCE = 0.02 # 2% de tolérance
286
+
287
+ @pytest.fixture
288
+ def baseline_metrics(self):
289
+ """Charge les métriques de référence."""
290
+ with open(BASELINE_FILE) as f:
291
+ return json.load(f)
292
+
293
+ def test_no_accuracy_regression(self, current_metrics, baseline_metrics):
294
+ """L'accuracy ne doit pas baisser de plus de 2%."""
295
+ current = current_metrics["accuracy"]
296
+ baseline = baseline_metrics["accuracy"]
297
+
298
+ assert current >= baseline - self.REGRESSION_TOLERANCE, \
299
+ f"Regression detected: {current:.2%} vs baseline {baseline:.2%}"
300
+
301
+ def test_deterministic_predictions(self):
302
+ """Mêmes inputs = mêmes outputs (déterminisme)."""
303
+ clf = DemoClassifier(seed=42)
304
+
305
+ input_text = "Console PlayStation 5"
306
+ result1 = clf.predict(text=input_text)
307
+ result2 = clf.predict(text=input_text)
308
+
309
+ assert result1.category == result2.category
310
+ assert abs(result1.confidence - result2.confidence) < 0.001
311
+ ```
312
+
313
+ ### 3.3 Tests de Robustesse (Robustness Tests)
314
+
315
+ | Test ID | Cas de test | Comportement attendu | Priorité |
316
+ |---------|-------------|---------------------|----------|
317
+ | ML-RB-001 | Texte vide | Retourne prédiction par défaut | HIGH |
318
+ | ML-RB-002 | Texte très long (10K chars) | Tronque et prédit | MEDIUM |
319
+ | ML-RB-003 | Caractères spéciaux/emojis | Nettoie et prédit | MEDIUM |
320
+ | ML-RB-004 | Image corrompue | Erreur gracieuse | HIGH |
321
+ | ML-RB-005 | Image très petite (10x10) | Erreur ou upscale | MEDIUM |
322
+ | ML-RB-006 | Image très grande (8000x8000) | Redimensionne | MEDIUM |
323
+ | ML-RB-007 | Texte multilingue | Traduit et prédit | HIGH |
324
+ | ML-RB-008 | HTML malicieux | Sanitize et prédit | HIGH |
325
+
326
+ **Implémentation**:
327
+ ```python
328
+ class TestModelRobustness:
329
+ """Tests de robustesse du modèle face aux edge cases."""
330
+
331
+ @pytest.mark.parametrize("edge_case_text", [
332
+ "", # Empty
333
+ " " * 100, # Whitespace only
334
+ "a" * 10000, # Very long
335
+ "<script>alert('xss')</script>", # XSS attempt
336
+ "🎮📱💻🖥️", # Emojis only
337
+ "价格便宜质量好", # Chinese
338
+ "Ценa хорошая", # Russian
339
+ None, # None value
340
+ ])
341
+ def test_handles_edge_case_text(self, edge_case_text):
342
+ """Le modèle gère les cas limites sans crash."""
343
+ clf = DemoClassifier()
344
+
345
+ # Ne doit pas lever d'exception
346
+ try:
347
+ result = clf.predict(text=edge_case_text or "")
348
+ assert result is not None
349
+ assert result.category in CATEGORY_MAPPING
350
+ except ValueError:
351
+ pass # ValueError acceptable pour entrée invalide
352
+
353
+ def test_handles_adversarial_input(self):
354
+ """Test d'input adversarial."""
355
+ clf = DemoClassifier()
356
+
357
+ # Texte conçu pour confondre le modèle
358
+ adversarial = "livre console telephone jardin piscine figurine"
359
+ result = clf.predict(text=adversarial)
360
+
361
+ # Doit quand même retourner une prédiction valide
362
+ assert result.category in CATEGORY_MAPPING
363
+ # Confiance devrait être plus basse
364
+ assert result.confidence < 0.95
365
+ ```
366
+
367
+ ### 3.4 Tests de Consistance Inter-Modèles
368
+
369
+ | Test ID | Description | Priorité |
370
+ |---------|-------------|----------|
371
+ | ML-CS-001 | 3 modèles texte donnent top-3 similaires | MEDIUM |
372
+ | ML-CS-002 | 3 modèles image donnent top-3 similaires | MEDIUM |
373
+ | ML-CS-003 | Corrélation des confidences entre modèles | LOW |
374
+
375
+ ### 3.5 Tests de Performance (Latency/Throughput)
376
+
377
+ | Test ID | Métrique | Seuil | Priorité |
378
+ |---------|----------|-------|----------|
379
+ | ML-LT-001 | Latence inférence texte | < 100ms | HIGH |
380
+ | ML-LT-002 | Latence inférence image | < 500ms | HIGH |
381
+ | ML-LT-003 | Throughput batch 100 | > 10/s | MEDIUM |
382
+ | ML-LT-004 | Mémoire max | < 2 GB | MEDIUM |
383
+
384
+ **Implémentation**:
385
+ ```python
386
+ import time
387
+ import pytest
388
+
389
+ class TestInferencePerformance:
390
+ """Tests de performance d'inférence."""
391
+
392
+ MAX_TEXT_LATENCY_MS = 100
393
+ MAX_IMAGE_LATENCY_MS = 500
394
+
395
+ def test_text_inference_latency(self):
396
+ """L'inférence texte doit être < 100ms."""
397
+ clf = DemoClassifier()
398
+ text = "Console PlayStation 5 nouvelle génération"
399
+
400
+ # Warmup
401
+ clf.predict(text=text)
402
+
403
+ # Mesure
404
+ start = time.perf_counter()
405
+ for _ in range(100):
406
+ clf.predict(text=text)
407
+ elapsed = (time.perf_counter() - start) * 1000 / 100 # ms par inférence
408
+
409
+ assert elapsed < self.MAX_TEXT_LATENCY_MS, \
410
+ f"Text inference too slow: {elapsed:.1f}ms > {self.MAX_TEXT_LATENCY_MS}ms"
411
+
412
+ @pytest.mark.slow
413
+ def test_batch_throughput(self):
414
+ """Le throughput batch doit être > 10 prédictions/seconde."""
415
+ clf = DemoClassifier()
416
+ texts = [f"Product {i}" for i in range(100)]
417
+
418
+ start = time.perf_counter()
419
+ for text in texts:
420
+ clf.predict(text=text)
421
+ elapsed = time.perf_counter() - start
422
+
423
+ throughput = len(texts) / elapsed
424
+ assert throughput > 10, f"Throughput too low: {throughput:.1f}/s"
425
+ ```
426
+
427
+ ### 3.6 Tests de Data Quality (Validation des données)
428
+
429
+ | Test ID | Description | Priorité |
430
+ |---------|-------------|----------|
431
+ | ML-DQ-001 | Pas de NaN dans features | CRITICAL |
432
+ | ML-DQ-002 | Toutes les catégories présentes | HIGH |
433
+ | ML-DQ-003 | Distribution des classes cohérente | MEDIUM |
434
+ | ML-DQ-004 | Pas de doublons dans test set | HIGH |
435
+ | ML-DQ-005 | Train/Test split correct (pas de fuite) | CRITICAL |
436
+
437
+ **Implémentation avec Great Expectations style**:
438
+ ```python
439
+ class TestDataQuality:
440
+ """Tests de qualité des données."""
441
+
442
+ def test_no_nan_in_features(self, training_data):
443
+ """Aucune valeur NaN dans les features."""
444
+ X, y = training_data
445
+ assert not X.isnull().any().any(), "NaN values found in features"
446
+
447
+ def test_all_categories_represented(self, training_data):
448
+ """Les 27 catégories sont représentées."""
449
+ X, y = training_data
450
+ unique_categories = y['prdtypecode'].unique()
451
+
452
+ assert len(unique_categories) == 27, \
453
+ f"Expected 27 categories, found {len(unique_categories)}"
454
+
455
+ def test_no_data_leakage(self, train_data, test_data):
456
+ """Pas de fuite de données train→test."""
457
+ train_ids = set(train_data.index)
458
+ test_ids = set(test_data.index)
459
+
460
+ overlap = train_ids & test_ids
461
+ assert len(overlap) == 0, f"Data leakage: {len(overlap)} samples in both sets"
462
+ ```
463
+
464
+ ---
465
+
466
+ ## 🌐 4. TESTS END-TO-END (E2E Tests)
467
+
468
+ ### 4.1 Tests Playwright (Browser Automation)
469
+
470
+ | Test ID | Scénario | Priorité |
471
+ |---------|----------|----------|
472
+ | E2E-001 | Parcours complet: accueil → classification → résultat | CRITICAL |
473
+ | E2E-002 | Upload image et classification | HIGH |
474
+ | E2E-003 | Comparaison des 3 modèles | HIGH |
475
+ | E2E-004 | Navigation complète (6 pages) | HIGH |
476
+ | E2E-005 | Galerie d'exemples | MEDIUM |
477
+ | E2E-006 | Export CSV distribution | LOW |
478
+
479
+ **Implémentation**:
480
+ ```python
481
+ from playwright.sync_api import Page, expect
482
+ import pytest
483
+
484
+ class TestE2EClassification:
485
+ """Tests E2E avec Playwright."""
486
+
487
+ BASE_URL = "http://localhost:8501"
488
+
489
+ def test_full_classification_journey(self, page: Page):
490
+ """Parcours utilisateur complet."""
491
+ # 1. Page d'accueil
492
+ page.goto(self.BASE_URL)
493
+ expect(page.locator("text=Rakuten")).to_be_visible()
494
+
495
+ # 2. Click sur "Classifier un Produit"
496
+ page.click("button:has-text('Classifier')")
497
+ page.wait_for_url("**/4_*Démo*")
498
+
499
+ # 3. Remplir le formulaire
500
+ page.fill("input[aria-label='Désignation']", "iPhone 15 Pro Max")
501
+ page.fill("textarea[aria-label='Description']", "Smartphone Apple")
502
+
503
+ # 4. Classifier
504
+ page.click("button:has-text('Classifier le Produit')")
505
+
506
+ # 5. Vérifier le résultat
507
+ expect(page.locator(".result-card")).to_be_visible(timeout=10000)
508
+ expect(page.locator("text=Catégorie")).to_be_visible()
509
+
510
+ def test_model_comparison(self, page: Page):
511
+ """Test comparaison des modèles."""
512
+ page.goto(f"{self.BASE_URL}/3_🧠_Modèles")
513
+
514
+ # Sélectionner mode texte
515
+ page.click("text=Modèles Texte")
516
+
517
+ # Remplir input
518
+ page.fill("input", "Console PlayStation 5")
519
+
520
+ # Lancer comparaison
521
+ page.click("button:has-text('Comparer')")
522
+
523
+ # Vérifier 3 résultats
524
+ expect(page.locator(".model-card")).to_have_count(3)
525
+ ```
526
+
527
+ ### 4.2 Tests de Snapshot UI
528
+
529
+ ```python
530
+ def test_home_page_snapshot(page: Page, assert_snapshot):
531
+ """Snapshot de la page d'accueil."""
532
+ page.goto(BASE_URL)
533
+ page.wait_for_load_state("networkidle")
534
+
535
+ assert_snapshot(page.screenshot(), "home_page.png")
536
+ ```
537
+
538
+ ---
539
+
540
+ ## 🔒 5. TESTS DE SÉCURITÉ (Security Tests)
541
+
542
+ | Test ID | Vulnérabilité | Test | Priorité |
543
+ |---------|--------------|------|----------|
544
+ | SEC-001 | XSS | Injection script dans input | HIGH |
545
+ | SEC-002 | Path Traversal | Upload fichier malicieux | HIGH |
546
+ | SEC-003 | DoS | Input très volumineux | MEDIUM |
547
+ | SEC-004 | Injection | Caractères spéciaux SQL-like | LOW |
548
+
549
+ ```python
550
+ class TestSecurity:
551
+ """Tests de sécurité."""
552
+
553
+ XSS_PAYLOADS = [
554
+ "<script>alert('xss')</script>",
555
+ "<img src=x onerror=alert('xss')>",
556
+ "javascript:alert('xss')",
557
+ "<svg onload=alert('xss')>",
558
+ ]
559
+
560
+ @pytest.mark.parametrize("payload", XSS_PAYLOADS)
561
+ def test_xss_prevention(self, payload):
562
+ """Les payloads XSS sont sanitizés."""
563
+ result = preprocess_product_text(payload, "")
564
+
565
+ assert "<script>" not in result
566
+ assert "javascript:" not in result
567
+ assert "onerror=" not in result
568
+ ```
569
+
570
+ ---
571
+
572
+ ## 📁 6. STRUCTURE DES FICHIERS DE TEST
573
+
574
+ ```
575
+ tests/
576
+ ├── __init__.py
577
+ ├── conftest.py # Fixtures partagées
578
+ ├── pytest.ini # Configuration pytest
579
+ │
580
+ ├── unit/ # Tests unitaires
581
+ │ ├── __init__.py
582
+ │ ├── test_mock_classifier.py
583
+ │ ├── test_category_mapping.py
584
+ │ ├── test_preprocessing.py
585
+ │ ├── test_image_utils.py
586
+ │ ├── test_data_loader.py
587
+ │ └── test_config.py
588
+ │
589
+ ├── integration/ # Tests d'intégration
590
+ │ ├── __init__.py
591
+ │ ├── test_page_loading.py
592
+ │ ├── test_session_state.py
593
+ │ ├── test_navigation.py
594
+ │ └── test_classification_flow.py
595
+ │
596
+ ├── ml/ # Tests ML spécifiques
597
+ │ ├── __init__.py
598
+ │ ├── test_model_performance.py
599
+ │ ├── test_model_regression.py
600
+ │ ├── test_model_robustness.py
601
+ │ ├── test_inference_latency.py
602
+ │ └── test_data_quality.py
603
+ │
604
+ ├── e2e/ # Tests end-to-end
605
+ │ ├── __init__.py
606
+ │ ├── test_classification_journey.py
607
+ │ ├── test_model_comparison.py
608
+ │ └── snapshots/ # Screenshots de référence
609
+ │
610
+ ├── security/ # Tests de sécurité
611
+ │ ├── __init__.py
612
+ │ └── test_input_sanitization.py
613
+ │
614
+ ├── baselines/ # Données de référence
615
+ │ ├── model_baseline.json # Métriques baseline
616
+ │ └── golden_predictions.json # Prédictions de référence
617
+ │
618
+ └── fixtures/ # Données de test
619
+ ├── sample_images/
620
+ │ ├── valid_product.jpg
621
+ │ ├── corrupted.jpg
622
+ │ └── too_small.png
623
+ └── sample_texts/
624
+ └── test_products.csv
625
+ ```
626
+
627
+ ---
628
+
629
+ ## ⚙️ 7. CONFIGURATION
630
+
631
+ ### 7.1 `pytest.ini`
632
+
633
+ ```ini
634
+ [pytest]
635
+ testpaths = tests
636
+ python_files = test_*.py
637
+ python_classes = Test*
638
+ python_functions = test_*
639
+
640
+ # Markers
641
+ markers =
642
+ unit: Unit tests (fast)
643
+ integration: Integration tests
644
+ ml: Machine Learning specific tests
645
+ e2e: End-to-end browser tests
646
+ slow: Slow tests (>5s)
647
+ security: Security tests
648
+
649
+ # Options par défaut
650
+ addopts =
651
+ -v
652
+ --tb=short
653
+ --strict-markers
654
+ -ra
655
+ --cov=utils
656
+ --cov=pages
657
+ --cov-report=html:coverage_report
658
+ --cov-report=term-missing
659
+ --cov-fail-under=80
660
+
661
+ # Timeout par test
662
+ timeout = 30
663
+
664
+ # Parallel execution
665
+ # addopts = -n auto # Décommenter pour exécution parallèle
666
+ ```
667
+
668
+ ### 7.2 `conftest.py`
669
+
670
+ ```python
671
+ """
672
+ Fixtures partagées pour tous les tests.
673
+ """
674
+ import pytest
675
+ import sys
676
+ from pathlib import Path
677
+ from PIL import Image
678
+ import pandas as pd
679
+ import io
680
+
681
+ # Ajouter le répertoire source au path
682
+ sys.path.insert(0, str(Path(__file__).parent.parent / "src" / "streamlit"))
683
+
684
+ from utils.mock_classifier import DemoClassifier, TEXT_MODELS, IMAGE_MODELS
685
+ from utils.category_mapping import CATEGORY_MAPPING
686
+
687
+
688
+ # =============================================================================
689
+ # FIXTURES CLASSIFIER
690
+ # =============================================================================
691
+ @pytest.fixture
692
+ def demo_classifier():
693
+ """Retourne un classifier initialisé."""
694
+ return DemoClassifier()
695
+
696
+
697
+ @pytest.fixture
698
+ def text_classifier():
699
+ """Classifier configuré pour le texte."""
700
+ from utils.mock_classifier import TEXT_MODELS
701
+ config = TEXT_MODELS["camembert"]
702
+ return DemoClassifier(model_config=config)
703
+
704
+
705
+ @pytest.fixture
706
+ def image_classifier():
707
+ """Classifier configuré pour les images."""
708
+ from utils.mock_classifier import IMAGE_MODELS
709
+ config = IMAGE_MODELS["resnet50_svm"]
710
+ return DemoClassifier(model_config=config)
711
+
712
+
713
+ # =============================================================================
714
+ # FIXTURES DONNÉES
715
+ # =============================================================================
716
+ @pytest.fixture
717
+ def sample_text():
718
+ """Texte produit exemple."""
719
+ return "Console PlayStation 5 nouvelle génération Sony"
720
+
721
+
722
+ @pytest.fixture
723
+ def sample_image():
724
+ """Image produit exemple (100x100 rouge)."""
725
+ img = Image.new('RGB', (100, 100), color='red')
726
+ return img
727
+
728
+
729
+ @pytest.fixture
730
+ def sample_image_bytes():
731
+ """Image en bytes pour simuler upload."""
732
+ img = Image.new('RGB', (100, 100), color='blue')
733
+ buffer = io.BytesIO()
734
+ img.save(buffer, format='JPEG')
735
+ buffer.seek(0)
736
+ return buffer
737
+
738
+
739
+ @pytest.fixture
740
+ def all_category_codes():
741
+ """Liste de tous les codes catégorie."""
742
+ return list(CATEGORY_MAPPING.keys())
743
+
744
+
745
+ # =============================================================================
746
+ # FIXTURES DONNÉES ML
747
+ # =============================================================================
748
+ @pytest.fixture(scope="session")
749
+ def training_data():
750
+ """Charge les données d'entraînement (cache session)."""
751
+ # À adapter selon votre structure de données
752
+ data_path = Path(__file__).parent.parent / "data"
753
+ X_train = pd.read_csv(data_path / "X_train.csv")
754
+ Y_train = pd.read_csv(data_path / "Y_train.csv")
755
+ return X_train, Y_train
756
+
757
+
758
+ @pytest.fixture
759
+ def model_baseline():
760
+ """Charge les métriques baseline."""
761
+ baseline_path = Path(__file__).parent / "baselines" / "model_baseline.json"
762
+ if baseline_path.exists():
763
+ import json
764
+ with open(baseline_path) as f:
765
+ return json.load(f)
766
+ return {
767
+ "accuracy": 0.75,
768
+ "f1_macro": 0.70,
769
+ "f1_weighted": 0.75,
770
+ }
771
+
772
+
773
+ # =============================================================================
774
+ # FIXTURES EDGE CASES
775
+ # =============================================================================
776
+ @pytest.fixture(params=[
777
+ "",
778
+ " " * 100,
779
+ "a" * 10000,
780
+ "<script>alert('xss')</script>",
781
+ "🎮📱💻",
782
+ None,
783
+ ])
784
+ def edge_case_text(request):
785
+ """Paramétrise les cas limites de texte."""
786
+ return request.param
787
+
788
+
789
+ @pytest.fixture
790
+ def corrupted_image():
791
+ """Retourne des bytes invalides (pas une image)."""
792
+ return io.BytesIO(b"not an image content")
793
+
794
+
795
+ @pytest.fixture
796
+ def oversized_image():
797
+ """Image très grande (8000x8000)."""
798
+ img = Image.new('RGB', (8000, 8000), color='green')
799
+ return img
800
+
801
+
802
+ # =============================================================================
803
+ # FIXTURES STREAMLIT
804
+ # =============================================================================
805
+ @pytest.fixture
806
+ def streamlit_app():
807
+ """Initialise AppTest pour les tests Streamlit."""
808
+ from streamlit.testing.v1 import AppTest
809
+ return AppTest
810
+
811
+
812
+ # =============================================================================
813
+ # CONFIGURATION PLAYWRIGHT (E2E)
814
+ # =============================================================================
815
+ @pytest.fixture(scope="session")
816
+ def browser_context_args(browser_context_args):
817
+ """Configuration du contexte navigateur."""
818
+ return {
819
+ **browser_context_args,
820
+ "viewport": {"width": 1280, "height": 720},
821
+ "locale": "fr-FR",
822
+ }
823
+
824
+
825
+ # =============================================================================
826
+ # HELPERS
827
+ # =============================================================================
828
+ def pytest_configure(config):
829
+ """Configuration pytest au démarrage."""
830
+ # Ajouter des markers personnalisés
831
+ config.addinivalue_line("markers", "gpu: tests requiring GPU")
832
+ config.addinivalue_line("markers", "real_model: tests with real ML model")
833
+ ```
834
+
835
+ ---
836
+
837
+ ## 🚀 8. COMMANDES D'EXÉCUTION
838
+
839
+ ### 8.1 Exécution par type
840
+
841
+ ```bash
842
+ # Tous les tests
843
+ pytest
844
+
845
+ # Tests unitaires uniquement (rapides)
846
+ pytest -m unit
847
+
848
+ # Tests d'intégration
849
+ pytest -m integration
850
+
851
+ # Tests ML
852
+ pytest -m ml
853
+
854
+ # Tests E2E (nécessite serveur Streamlit)
855
+ pytest -m e2e
856
+
857
+ # Tests de sécurité
858
+ pytest -m security
859
+
860
+ # Exclure les tests lents
861
+ pytest -m "not slow"
862
+ ```
863
+
864
+ ### 8.2 Avec rapport de couverture
865
+
866
+ ```bash
867
+ # HTML report
868
+ pytest --cov=. --cov-report=html
869
+
870
+ # Terminal report
871
+ pytest --cov=. --cov-report=term-missing
872
+
873
+ # Fail si couverture < 80%
874
+ pytest --cov=. --cov-fail-under=80
875
+ ```
876
+
877
+ ### 8.3 CI/CD Pipeline
878
+
879
+ ```yaml
880
+ # .github/workflows/tests.yml
881
+ name: Tests
882
+
883
+ on: [push, pull_request]
884
+
885
+ jobs:
886
+ test:
887
+ runs-on: ubuntu-latest
888
+
889
+ steps:
890
+ - uses: actions/checkout@v4
891
+
892
+ - name: Set up Python
893
+ uses: actions/setup-python@v5
894
+ with:
895
+ python-version: '3.10'
896
+
897
+ - name: Install dependencies
898
+ run: |
899
+ pip install -r requirements.txt
900
+ pip install -r requirements-test.txt
901
+
902
+ - name: Run unit tests
903
+ run: pytest -m unit --cov=. --cov-report=xml
904
+
905
+ - name: Run integration tests
906
+ run: pytest -m integration
907
+
908
+ - name: Run ML tests
909
+ run: pytest -m ml
910
+
911
+ - name: Upload coverage
912
+ uses: codecov/codecov-action@v3
913
+ with:
914
+ files: ./coverage.xml
915
+ ```
916
+
917
+ ---
918
+
919
+ ## 📊 9. MÉTRIQUES DE QUALITÉ
920
+
921
+ ### Dashboard de Tests
922
+
923
+ | Métrique | Cible | Status |
924
+ |----------|-------|--------|
925
+ | Couverture code | ≥ 80% | 🔴 |
926
+ | Tests unitaires passants | 100% | 🔴 |
927
+ | Tests intégration passants | 100% | 🔴 |
928
+ | Tests ML passants | 100% | 🔴 |
929
+ | Temps d'exécution total | < 5 min | 🔴 |
930
+ | Accuracy modèle | ≥ 75% | 🔴 |
931
+ | F1-Score modèle | ≥ 70% | 🔴 |
932
+
933
+ ### Badges README
934
+
935
+ ```markdown
936
+ ![Tests](https://github.com/xxx/rakuten-classifier/actions/workflows/tests.yml/badge.svg)
937
+ ![Coverage](https://codecov.io/gh/xxx/rakuten-classifier/branch/main/graph/badge.svg)
938
+ ![Model Accuracy](https://img.shields.io/badge/accuracy-85%25-green)
939
+ ```
940
+
941
+ ---
942
+
943
+ ## 🎯 10. PRIORISATION D'IMPLÉMENTATION
944
+
945
+ ### Phase 1: Foundation (Critique) - 2h
946
+ 1. ✅ Structure des dossiers tests
947
+ 2. ✅ `conftest.py` avec fixtures de base
948
+ 3. ✅ Tests unitaires `mock_classifier.py`
949
+ 4. ✅ Tests unitaires `category_mapping.py`
950
+
951
+ ### Phase 2: Core (Haute priorité) - 3h
952
+ 5. Tests unitaires `preprocessing.py`
953
+ 6. Tests unitaires `image_utils.py`
954
+ 7. Tests d'intégration chargement pages
955
+ 8. Tests ML performance baseline
956
+
957
+ ### Phase 3: Robustness (Moyenne priorité) - 2h
958
+ 9. Tests de robustesse (edge cases)
959
+ 10. Tests de non-régression ML
960
+ 11. Tests de latence inférence
961
+
962
+ ### Phase 4: E2E & Polish (Si temps) - 2h
963
+ 12. Tests E2E Playwright
964
+ 13. Tests de sécurité
965
+ 14. Configuration CI/CD
966
+
967
+ ---
968
+
969
+ ## ✅ Checklist Soutenance
970
+
971
+ - [ ] ≥ 50 tests unitaires passants
972
+ - [ ] ≥ 10 tests d'intégration passants
973
+ - [ ] ≥ 5 tests ML spécifiques passants
974
+ - [ ] Couverture ≥ 80%
975
+ - [ ] Rapport HTML de couverture généré
976
+ - [ ] Temps d'exécution < 2 minutes
977
+ - [ ] Badge de tests dans README
978
+ - [ ] Démonstration live `pytest -v` pendant soutenance
979
+
980
+ ---
981
+
982
+ *Document créé le 16 janvier 2025 - Stratégie de Tests Enterprise-Grade*
src/streamlit/docs/desktop.ini ADDED
Binary file (246 Bytes). View file
 
src/streamlit/pages/1_📊_Données.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Page d'exploration des données Rakuten.
3
+ """
4
+ import streamlit as st
5
+ import plotly.express as px
6
+ import pandas as pd
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ sys.path.insert(0, str(Path(__file__).parent.parent))
11
+
12
+ from config import APP_CONFIG, ASSETS_DIR
13
+ from utils.category_mapping import CATEGORY_MAPPING, get_category_info
14
+ from utils.data_loader import (
15
+ is_data_available,
16
+ get_category_distribution,
17
+ get_text_statistics,
18
+ get_sample_products,
19
+ get_dataset_summary,
20
+ load_training_data
21
+ )
22
+ from utils.ui_utils import load_css
23
+
24
+ st.set_page_config(
25
+ page_title=f"Données - {APP_CONFIG['title']}",
26
+ page_icon="📊",
27
+ layout=APP_CONFIG["layout"],
28
+ )
29
+
30
+ load_css(ASSETS_DIR / "style.css")
31
+
32
+ # Header
33
+ st.title("Exploration des Données")
34
+
35
+ if is_data_available():
36
+ st.success("Données réelles chargées")
37
+ else:
38
+ st.info("Mode démonstration")
39
+
40
+ # Métriques
41
+ st.divider()
42
+ summary = get_dataset_summary()
43
+
44
+ col1, col2, col3, col4 = st.columns(4)
45
+ col1.metric("Train", f"{summary['train_samples']:,}".replace(",", " "))
46
+ col2.metric("Test", f"{summary['test_samples']:,}".replace(",", " ") if isinstance(summary['test_samples'], int) else summary['test_samples'])
47
+ col3.metric("Catégories", summary['num_categories'])
48
+ col4.metric("Features", len(summary['features']))
49
+
50
+ # Distribution des catégories
51
+ st.divider()
52
+ st.header("Distribution des Catégories")
53
+
54
+ dist_df = get_category_distribution()
55
+
56
+ tab_bar, tab_table = st.tabs(["Graphique", "Tableau"])
57
+
58
+ with tab_bar:
59
+ fig_bar = px.bar(
60
+ dist_df,
61
+ x='count',
62
+ y='category_name',
63
+ orientation='h',
64
+ color='count',
65
+ color_continuous_scale=['#FFE5E5', '#BF0000'],
66
+ labels={'count': 'Produits', 'category_name': 'Catégorie'},
67
+ text='count'
68
+ )
69
+ fig_bar.update_layout(
70
+ height=700,
71
+ yaxis={'categoryorder': 'total ascending'},
72
+ showlegend=False,
73
+ coloraxis_showscale=False,
74
+ )
75
+ fig_bar.update_traces(textposition='outside')
76
+ st.plotly_chart(fig_bar, use_container_width=True)
77
+
78
+ with tab_table:
79
+ display_df = dist_df[['emoji', 'category_name', 'count', 'percentage']].copy()
80
+ display_df.columns = ['', 'Catégorie', 'Produits', '%']
81
+ display_df['Produits'] = display_df['Produits'].apply(lambda x: f"{x:,}".replace(",", " "))
82
+ display_df['%'] = display_df['%'].apply(lambda x: f"{x:.1f}%")
83
+ st.dataframe(display_df, use_container_width=True, hide_index=True, height=600)
84
+
85
+ # Statistiques texte
86
+ st.divider()
87
+ st.header("Statistiques Texte")
88
+
89
+ text_stats = get_text_statistics()
90
+
91
+ col1, col2 = st.columns(2)
92
+
93
+ with col1:
94
+ st.subheader("Désignation")
95
+ desg = text_stats['designation']
96
+ st.markdown(f"- Moyenne: **{desg['mean_length']:.0f}** car.")
97
+ st.markdown(f"- Min/Max: **{desg['min_length']}** / **{desg['max_length']}**")
98
+
99
+ with col2:
100
+ st.subheader("Description")
101
+ desc = text_stats['description']
102
+ st.markdown(f"- Moyenne: **{desc['mean_length']:.0f}** car.")
103
+ st.markdown(f"- Remplissage: **{desc['non_empty_pct']:.0f}%**")
104
+
105
+ # Exemples
106
+ st.divider()
107
+ st.header("Exemples par Catégorie")
108
+
109
+ categories_list = [(f"{info[2]} {info[0]}", code) for code, info in CATEGORY_MAPPING.items()]
110
+ selected = st.selectbox("Catégorie", categories_list, format_func=lambda x: x[0])
111
+
112
+ X_train, Y_train = load_training_data()
113
+ samples = get_sample_products(X_train, Y_train, category_code=selected[1], n_samples=3)
114
+
115
+ if len(samples) > 0:
116
+ for _, row in samples.iterrows():
117
+ with st.expander(f"{row['designation'][:60]}..."):
118
+ st.write(f"**Désignation:** {row['designation']}")
119
+ desc = row.get('description', '')
120
+ if pd.notna(desc) and str(desc).strip():
121
+ st.write(f"**Description:** {str(desc)[:300]}...")
122
+
123
+ # Déséquilibre
124
+ st.divider()
125
+ st.header("Déséquilibre des Classes")
126
+
127
+ col1, col2, col3 = st.columns(3)
128
+ col1.metric("Majoritaire", dist_df.iloc[0]['category_name'], f"{dist_df.iloc[0]['count']:,}".replace(",", " "))
129
+ col2.metric("Minoritaire", dist_df.iloc[-1]['category_name'], f"{dist_df.iloc[-1]['count']:,}".replace(",", " "))
130
+ col3.metric("Ratio", f"{dist_df['count'].max() / dist_df['count'].min():.1f}x")
131
+
132
+ st.info("Le déséquilibre est géré par class weighting et SMOTE.")
133
+
134
+ # Sidebar
135
+ with st.sidebar:
136
+ st.markdown("### Données")
137
+ st.divider()
138
+ csv_data = dist_df.to_csv(index=False)
139
+ st.download_button("Télécharger CSV", csv_data, "distribution.csv", "text/csv")
src/streamlit/pages/2_⚙️_Preprocessing.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Page de présentation du pipeline de preprocessing.
3
+ """
4
+ import streamlit as st
5
+ import re
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ sys.path.insert(0, str(Path(__file__).parent.parent))
10
+
11
+ from config import APP_CONFIG, ASSETS_DIR
12
+ from utils.ui_utils import load_css
13
+
14
+ st.set_page_config(
15
+ page_title=f"Preprocessing - {APP_CONFIG['title']}",
16
+ page_icon="⚙️",
17
+ layout=APP_CONFIG["layout"],
18
+ )
19
+
20
+ load_css(ASSETS_DIR / "style.css")
21
+
22
+ # Header
23
+ st.title("Pipeline de Preprocessing")
24
+
25
+ # Métriques
26
+ col1, col2, col3, col4 = st.columns(4)
27
+ col1.metric("Produits", "84 916")
28
+ col2.metric("Vocabulaire TF-IDF", "~15K")
29
+ col3.metric("Features Image", "2 048")
30
+ col4.metric("Langues", "5")
31
+
32
+ # Pipeline Texte
33
+ st.divider()
34
+ st.header("Pipeline Texte")
35
+
36
+ col1, col2, col3 = st.columns(3)
37
+ with col1:
38
+ st.subheader("1. Nettoyage")
39
+ st.markdown("""
40
+ - Suppression HTML
41
+ - Caractères spéciaux
42
+ - Normalisation espaces
43
+ """)
44
+
45
+ with col2:
46
+ st.subheader("2. Langue")
47
+ st.markdown("""
48
+ - Détection (langid)
49
+ - Traduction → FR
50
+ - ~85% déjà en français
51
+ """)
52
+
53
+ with col3:
54
+ st.subheader("3. Vectorisation")
55
+ st.markdown("""
56
+ - TF-IDF
57
+ - ~15K dimensions
58
+ - designation + description
59
+ """)
60
+
61
+ # Pipeline Image
62
+ st.divider()
63
+ st.header("Pipeline Image")
64
+
65
+ col1, col2, col3 = st.columns(3)
66
+ with col1:
67
+ st.subheader("1. Resize")
68
+ st.markdown("""
69
+ - 224 × 224 pixels
70
+ - Format attendu ResNet
71
+ """)
72
+
73
+ with col2:
74
+ st.subheader("2. Normalisation")
75
+ st.markdown("""
76
+ - Mean/std ImageNet
77
+ - [0.485, 0.456, 0.406]
78
+ """)
79
+
80
+ with col3:
81
+ st.subheader("3. Extraction")
82
+ st.markdown("""
83
+ - ResNet50 pré-entraîné
84
+ - 2048 features (avg_pool)
85
+ """)
86
+
87
+ # Choix techniques
88
+ st.divider()
89
+ st.header("Choix Techniques")
90
+
91
+ tab_text, tab_image = st.tabs(["Texte", "Image"])
92
+
93
+ with tab_text:
94
+ st.markdown("""
95
+ | Choix | Justification |
96
+ |-------|---------------|
97
+ | TF-IDF (pas Word2Vec) | Performance équivalente, meilleure interprétabilité |
98
+ | Traduction FR | 85% FR, vocabulaire unifié |
99
+ | Pas de lemmatisation | Préserver marques (iPhone, PlayStation) |
100
+ """)
101
+
102
+ with tab_image:
103
+ st.markdown("""
104
+ | Choix | Justification |
105
+ |-------|---------------|
106
+ | ResNet50 (pas VGG16) | Meilleur compromis taille/performance |
107
+ | avg_pool (pas flatten) | Moins de dimensions, moins d'overfitting |
108
+ | Pas d'augmentation | Dataset assez grand (85K) |
109
+ """)
110
+
111
+ # Démo
112
+ st.divider()
113
+ st.header("Démo")
114
+
115
+ col1, col2 = st.columns(2)
116
+
117
+ with col1:
118
+ st.subheader("Input")
119
+ demo_text = st.text_area(
120
+ "Texte brut",
121
+ value="<p>iPhone 15 Pro Max</p> - Smartphone Apple, écran OLED 6.7\"",
122
+ height=100
123
+ )
124
+
125
+ with col2:
126
+ st.subheader("Output")
127
+ if demo_text:
128
+ cleaned = re.sub(r'<[^>]+>', '', demo_text)
129
+ cleaned = re.sub(r'[^\w\s\-]', ' ', cleaned)
130
+ cleaned = ' '.join(cleaned.lower().split())
131
+ st.code(cleaned)
132
+ st.caption(f"{len(cleaned)} caractères, {len(cleaned.split())} mots")
133
+
134
+ # Sidebar
135
+ with st.sidebar:
136
+ st.markdown("### Preprocessing")
137
+ st.divider()
138
+ st.markdown("""
139
+ **Texte**: Nettoyage → Langue → TF-IDF
140
+
141
+ **Image**: Resize → Norm → ResNet50
142
+ """)