Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| from transformers import pipeline | |
| # --- Configuration --- | |
| APP_NAME = "MoodMapper" | |
| MODEL_ID = "j-hartmann/emotion-english-distilroberta-base" | |
| # --- Initialisation du modèle --- | |
| _clf = None | |
| def get_clf(): | |
| """Charge le modèle de classification d’émotions une seule fois.""" | |
| global _clf | |
| if _clf is None: | |
| _clf = pipeline( | |
| "text-classification", | |
| model=MODEL_ID, | |
| return_all_scores=True, | |
| truncation=True | |
| ) | |
| return _clf | |
| # --- Exemples à afficher --- | |
| EXAMPLES = [ | |
| ["I just got the internship — I'm so happy!"], | |
| ["Je suis déçue et un peu en colère par ce mail."], | |
| ["This is fine, nothing special today."], | |
| ["I'm worried about the deadline..."], | |
| ["Quelle surprise ! Je ne m’y attendais pas."] | |
| ] | |
| # --- Fonction principale --- | |
| def predict_emotion(text): | |
| if not text or not text.strip(): | |
| return {"": 0.0}, "Veuillez entrer un texte." | |
| try: | |
| scores = get_clf()(text)[0] # [{'label': 'joy', 'score': 0.97}, ...] | |
| score_dict = {s["label"]: float(s["score"]) for s in scores} | |
| top = max(scores, key=lambda d: d["score"]) | |
| notes = ( | |
| f"**Émotion prédite :** {top['label']} ({top['score']*100:.1f}%)\n\n" | |
| "- Fonctionne mieux sur des phrases courtes et explicites.\n" | |
| "- Modèle surtout entraîné en anglais ; le français simple passe quand même.\n" | |
| "- L'ironie et le sarcasme peuvent tromper le modèle." | |
| ) | |
| return score_dict, notes | |
| except Exception as e: | |
| return {"error": 1.0}, f"Erreur interne : {e}" | |
| # --- Interface Gradio --- | |
| with gr.Blocks(title=APP_NAME) as demo: | |
| gr.Markdown(f"# 🧠 {APP_NAME} — Détecteur d'émotions dans le texte") | |
| gr.Markdown( | |
| "Entrez un texte en anglais ou en français simple pour découvrir l’émotion principale qu’il exprime." | |
| ) | |
| txt = gr.Textbox( | |
| label="Votre texte", | |
| placeholder="Ex : Je suis déçue et un peu en colère par ce mail.", | |
| lines=3 | |
| ) | |
| btn = gr.Button("Analyser le texte") | |
| out_scores = gr.Label(label="Scores (confiance du modèle)") | |
| out_notes = gr.Markdown() | |
| gr.Examples(inputs=txt, examples=EXAMPLES, label="Exemples à tester") | |
| btn.click(fn=predict_emotion, inputs=txt, outputs=[out_scores, out_notes]) | |
| txt.submit(fn=predict_emotion, inputs=txt, outputs=[out_scores, out_notes]) | |
| # --- IMPORTANT --- | |
| # Hugging Face Spaces détecte automatiquement "app" comme interface principale | |
| app = demo | |