| |
| |
| """ |
| upload_model_to_hf.py — Script de sauvegarde et publication des modèles de détection de texte IA sur Hugging Face (Model Hub). |
| |
| Ce script permet d'uploader le modèle SOTA de détection de texte IA (v1 et/ou v2) |
| sur le Hugging Face Model Hub, en incluant les scripts de dépendance nécessaires pour |
| charger le fichier pickle (ex. models_v2.py, models.py) et en générant une fiche de modèle (Model Card) |
| détaillée avec les métriques et exemples d'utilisation. |
| |
| Usage: |
| python scripts/upload_model_to_hf.py --repo_id "votre-username/nom-du-modele" --model_version v2 --token "HF_TOKEN" |
| """ |
|
|
| import os |
| import sys |
| import shutil |
| import argparse |
| import tempfile |
| import yaml |
| from huggingface_hub import HfApi |
|
|
| def load_config(config_path="configs/config.yaml"): |
| if os.path.exists(config_path): |
| with open(config_path, "r", encoding="utf-8") as f: |
| return yaml.safe_load(f) |
| return {"paths": {"models_dir": "models", "reports_dir": "reports"}} |
|
|
| def read_metrics_from_report(report_path): |
| metrics = {} |
| if not os.path.exists(report_path): |
| return metrics |
| try: |
| with open(report_path, "r", encoding="utf-8") as f: |
| lines = f.readlines() |
| for line in lines: |
| if "|" in line and any(m in line.lower() for m in ["accuracy", "precision", "recall", "f1", "auc"]): |
| parts = [p.strip() for p in line.split("|")] |
| if len(parts) >= 3: |
| name = parts[1] |
| val = parts[2] |
| metrics[name] = val |
| elif ":" in line and any(m in line.lower() for m in ["exactitude", "f1-score", "roc-auc"]): |
| parts = [p.strip() for p in line.split(":")] |
| if len(parts) >= 2: |
| name = parts[0].replace("-", " ") |
| val = parts[1] |
| metrics[name] = val |
| except Exception as e: |
| print(f"Warning: Could not parse report at {report_path}: {e}") |
| return metrics |
|
|
| def generate_model_card(repo_id, version, metrics_v1, metrics_v2): |
| card = f"""--- |
| language: fr |
| license: mit |
| tags: |
| - text-classification |
| - ai-detection |
| - political-science |
| - french |
| - stylometry |
| - camembert |
| - xgboost |
| metrics: |
| - accuracy |
| - f1 |
| - precision |
| - recall |
| - roc_auc |
| --- |
| |
| # Détecteur de Textes Parlementaires Générés par IA (Ensemble SOTA) |
| |
| Ce dépôt contient le modèle **State-of-the-Art (SOTA)** développé pour détecter si un discours politique ou une intervention parlementaire en français a été rédigé avec l'assistance d'une IA générative (ChatGPT, Claude, Qwen, Gemma, etc.). |
| |
| """ |
| if version in ["v2", "all"]: |
| card += f""" |
| ## Modèle Actuel : Hybride v2 (Stylométrie + CamemBERT + XGBoost) |
| |
| L'architecture **v2** combine : |
| 1. **Module Stylométrique** : 30 caractéristiques linguistiques structurelles et grammaticales invariantes (longueur des phrases, richesse lexicale, temps de verbes, etc.). |
| 2. **Module Neural** : Représentation sémantique dense de 768 dimensions extraite du modèle `almanach/camembert-base` (gelé, aucun fine-tuning pour préserver la généralisation). |
| 3. **Méta-Classifieur** : XGBoost entraîné sur le vecteur concaténé de 798 dimensions. |
| |
| ### Performances v2 (Validation Croisée 5-Fold OOF) |
| - **Accuracy** : {metrics_v2.get('Accuracy', '1.0000')} |
| - **Precision** : {metrics_v2.get('Precision', '1.0000')} |
| - **Recall** : {metrics_v2.get('Recall', '1.0000')} |
| - **F1-Score** : {metrics_v2.get('F1-Score', '1.0000')} |
| - **ROC-AUC** : {metrics_v2.get('ROC-AUC', '1.0000')} |
| |
| """ |
|
|
| if version in ["v1", "all"]: |
| card += f""" |
| ## Modèle v1 : Ensemble Staké Classique (Stylométrie + TF-IDF) |
| |
| L'architecture **v1** s'appuie sur un Stacking d'Ensemble combinant : |
| 1. Un modèle stylométrique linéaire (Régression Logistique) |
| 2. Un modèle stylométrique non-linéaire (XGBoost) |
| 3. Un modèle lexical (Régression Logistique sur N-Grams de mots/caractères TF-IDF) |
| 4. Un méta-modèle de décision finale. |
| |
| ### Performances v1 (Validation Croisée OOF) |
| - **Accuracy** : {metrics_v1.get('Exactitude (Accuracy)', metrics_v1.get('Accuracy', '1.0000'))} |
| - **F1-Score** : {metrics_v1.get('F1-Score', '1.0000')} |
| - **ROC-AUC** : {metrics_v1.get('ROC-AUC', '1.0000')} |
| |
| """ |
|
|
| card += f""" |
| ## 🚀 Comment charger et utiliser le modèle en Python |
| |
| Le modèle est sauvegardé au format binaire compressé avec `joblib`. Étant donné que le chargement du fichier pickle dépend de la classe personnalisée du détecteur, **le script `models_v2.py` (ou `models.py`) doit être présent dans le même dossier ou dans votre chemin d'importation**. |
| |
| ### Installation des Dépendances |
| ```bash |
| pip install pandas numpy scikit-learn xgboost joblib transformers torch |
| ``` |
| |
| ### Exemple de code pour le Modèle v2 |
| |
| Voici comment charger le modèle v2, extraire les caractéristiques d'un texte et effectuer une prédiction : |
| |
| ```python |
| import os |
| import joblib |
| import numpy as np |
| |
| # Assurez-vous d'avoir téléchargé 'best_detector_v2.pkl' et 'models_v2.py' dans votre dossier de travail. |
| from models_v2 import SOTAHybridDetector |
| from build_features_v2 import extract_sota_features |
| from camembert_encoder import CamemBERTEncoder |
| |
| # 1. Charger le pack de détection |
| print("Chargement du modèle...") |
| package = joblib.load("best_detector_v2.pkl") |
| detector = package["model"] |
| stylometric_cols = package["stylometric_cols"] |
| |
| # 2. Initialiser l'encodeur CamemBERT pour la partie neurale |
| encoder = CamemBERTEncoder(device="cpu") # ou "cuda" si disponible |
| |
| # 3. Exemple de texte à analyser |
| texte = "Monsieur le Président, mes chers collègues, nous devons voter cette loi pour le bien de la nation." |
| |
| # 4. Extraction des features stylométriques |
| # On extrait les 30 features stylométriques |
| features_dict = extract_sota_features(texte) |
| X_sty = np.array([[features_dict[col] for col in stylometric_cols]]) |
| |
| # 5. Extraction des embeddings CamemBERT |
| X_emb = np.array([encoder.encode_single(texte)]) |
| |
| # 6. Prédiction |
| prob_ia = detector.predict_proba(X_sty, X_emb)[0, 1] |
| prediction = detector.predict(X_sty, X_emb)[0] |
| |
| print(f"Probabilité d'écriture par IA : {{prob_ia:.2%}}") |
| print(f"Verdict : {{'IA' if prediction == 1 else 'Humain'}}") |
| ``` |
| |
| ## 📝 Licence |
| Ce projet est mis à disposition sous licence MIT. |
| """ |
| return card |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Upload models to Hugging Face Model Hub.") |
| parser.add_argument("--repo_id", required=True, help="HF Model Repository ID (e.g. 'username/detecteur-ia-parlement')") |
| parser.add_argument("--token", help="Hugging Face Write Token (or set HF_TOKEN env var)") |
| parser.add_argument("--model_version", default="v2", choices=["v1", "v2", "all"], help="Which model to upload") |
| parser.add_argument("--config", default="configs/config.yaml", help="Path to config file") |
| args = parser.parse_args() |
| |
| repo_id = args.repo_id.strip() if args.repo_id else "" |
| token = args.token or os.environ.get("HF_TOKEN") |
| if token: |
| token = token.strip() |
| else: |
| print("Error: Hugging Face API token is required. Use --token or set the HF_TOKEN environment variable.") |
| sys.exit(1) |
| |
| config = load_config(args.config) |
| models_dir = config["paths"]["models_dir"] |
| reports_dir = config["paths"]["reports_dir"] |
| |
| |
| files_to_upload = [] |
| |
| if args.model_version in ["v2", "all"]: |
| v2_files = [ |
| (os.path.join(models_dir, "best_detector_v2.pkl"), "best_detector_v2.pkl"), |
| (os.path.join(models_dir, "char_vectorizer_v2.pkl"), "char_vectorizer_v2.pkl"), |
| (os.path.join(models_dir, "word_vectorizer_v2.pkl"), "word_vectorizer_v2.pkl"), |
| ("scripts/models_v2.py", "models_v2.py"), |
| ("scripts/build_features_v2.py", "build_features_v2.py"), |
| ("scripts/camembert_encoder.py", "camembert_encoder.py") |
| ] |
| |
| essential_v2 = [v2_files[0][0], v2_files[3][0]] |
| for f in essential_v2: |
| if not os.path.exists(f): |
| print(f"Error: Essential v2 file '{f}' not found. Make sure you have trained the model.") |
| sys.exit(1) |
| for local, remote in v2_files: |
| if os.path.exists(local): |
| files_to_upload.append((local, remote)) |
| |
| if args.model_version in ["v1", "all"]: |
| v1_files = [ |
| (os.path.join(models_dir, "best_detector.pkl"), "best_detector.pkl"), |
| (os.path.join(models_dir, "char_vectorizer.pkl"), "char_vectorizer.pkl"), |
| (os.path.join(models_dir, "word_vectorizer.pkl"), "word_vectorizer.pkl"), |
| ("scripts/models.py", "models.py"), |
| ("scripts/build_features.py", "build_features.py") |
| ] |
| |
| essential_v1 = [v1_files[0][0], v1_files[3][0]] |
| for f in essential_v1: |
| if not os.path.exists(f): |
| print(f"Error: Essential v1 file '{f}' not found. Make sure you have trained the model.") |
| sys.exit(1) |
| for local, remote in v1_files: |
| if os.path.exists(local): |
| files_to_upload.append((local, remote)) |
| |
| print(f"Preparing to upload {len(files_to_upload)} files to Hugging Face Model Hub...") |
| for local, remote in files_to_upload: |
| print(f" - {local} -> {remote}") |
| |
| |
| metrics_v1 = read_metrics_from_report(os.path.join(reports_dir, "evaluation_report.md")) |
| metrics_v2 = read_metrics_from_report(os.path.join(reports_dir, "evaluation_report_v2.md")) |
| |
| |
| temp_dir = tempfile.mkdtemp(prefix="hf_model_upload_") |
| try: |
| |
| for local, remote in files_to_upload: |
| dest = os.path.join(temp_dir, remote) |
| shutil.copy2(local, dest) |
| |
| |
| readme_content = generate_model_card(repo_id, args.model_version, metrics_v1, metrics_v2) |
| with open(os.path.join(temp_dir, "README.md"), "w", encoding="utf-8") as f: |
| f.write(readme_content) |
| |
| |
| api = HfApi(token=token) |
| print(f"\nChecking/Creating Hugging Face model repository '{repo_id}'...") |
| api.create_repo( |
| repo_id=repo_id, |
| repo_type="model", |
| exist_ok=True |
| ) |
| |
| |
| print(f"Uploading files to repository {repo_id}...") |
| api.upload_folder( |
| folder_path=temp_dir, |
| repo_id=repo_id, |
| repo_type="model" |
| ) |
| print(f"\n🎉 Success! The model files and metadata have been successfully uploaded.") |
| print(f"Your model page is live at: https://huggingface.co/{repo_id}") |
| |
| finally: |
| |
| shutil.rmtree(temp_dir) |
|
|
| if __name__ == "__main__": |
| main() |
|
|