Spaces:
Runtime error
Runtime error
| """ | |
| Application Gradio pour l'analyse de sentiment d'avis Amazon | |
| avec génération automatique de réponses pour le service client | |
| VERSION avec CroissantLLMChat - Modèle français bilingue 1.3B | |
| VERSION avec envoi d'emails | |
| """ | |
| import gradio as gr | |
| from data_processing import clean_text, label_to_sentiment | |
| from generate_response import generer_reponse, load_model | |
| from email_sender import send_analysis_email | |
| import time | |
| # Précharger le modèle CroissantLLMChat au démarrage | |
| print("🥐 Préchargement de CroissantLLMChat (modèle français 1.3B)...") | |
| load_model() | |
| print("✅ Application prête !") | |
| def analyze_review(review_text: str, sentiment_choice: str = "auto", recipient_email: str = None) -> tuple: | |
| """ | |
| Analyse un avis client et génère une réponse si négatif | |
| Args: | |
| review_text (str): Texte de l'avis client | |
| sentiment_choice (str): "auto" pour détection auto, ou "positif"/"negatif" | |
| recipient_email (str, optional): Email pour recevoir les résultats | |
| Returns: | |
| tuple: (texte_nettoye, sentiment_affichage, reponse_affichage, temps, email_status) | |
| """ | |
| start_time = time.time() | |
| # 1. Nettoyage du texte | |
| cleaned = clean_text(review_text) | |
| # 2. Détection du sentiment | |
| if sentiment_choice == "auto": | |
| # Détection automatique basique | |
| mots_negatifs = ["mauvais", "nul", "déçu", "cassé", "retard", "problème", | |
| "défectueux", "horrible", "arnaque", "pas", "ne", "aucun", | |
| "inacceptable", "mécontentent", "insatisfait"] | |
| mots_avis = cleaned.lower().split() | |
| count_negatif = sum(1 for mot in mots_avis if any(neg in mot for neg in mots_negatifs)) | |
| sentiment = "negatif" if count_negatif >= 1 else "positif" | |
| else: | |
| sentiment = sentiment_choice.lower() | |
| # Affichage du sentiment | |
| if sentiment == "negatif": | |
| sentiment_display = "🔴 **NÉGATIF**" | |
| sentiment_label = "Négatif" | |
| else: | |
| sentiment_display = "🟢 **POSITIF**" | |
| sentiment_label = "Positif" | |
| # 3. Génération de réponse (uniquement si négatif) | |
| if sentiment == "negatif": | |
| try: | |
| response = generer_reponse(cleaned, max_tokens=120, temperature=0.7) | |
| response_display = f"📧 **Réponse générée (CroissantLLMChat) :**\n\n{response}" | |
| except Exception as e: | |
| response = f"[Erreur : {e}]" | |
| response_display = f"❌ Erreur lors de la génération : {e}" | |
| else: | |
| response = "" | |
| response_display = "✅ Avis positif - Aucune réponse nécessaire" | |
| # 4. Envoi par email si adresse fournie | |
| email_status = "" | |
| if recipient_email and recipient_email.strip() and "@" in recipient_email: | |
| try: | |
| success, message = send_analysis_email( | |
| recipient_email=recipient_email.strip(), | |
| avis_text=review_text, | |
| sentiment=sentiment_label, | |
| response_text=response if response else "Aucune réponse générée (avis positif)" | |
| ) | |
| email_status = message | |
| except Exception as e: | |
| email_status = f"❌ Erreur email : {str(e)}" | |
| else: | |
| email_status = "ℹ️ Pas d'email spécifié (optionnel)" | |
| # Temps d'exécution | |
| elapsed_time = time.time() - start_time | |
| return ( | |
| f"**Texte nettoyé :** {cleaned}", | |
| f"**Sentiment détecté :** {sentiment_display}", | |
| response_display, | |
| f"⏱️ **Analyse terminée en {elapsed_time:.2f}s**", | |
| f"**Statut email :** {email_status}" | |
| ) | |
| # Interface Gradio | |
| with gr.Blocks(title="Analyse de Sentiment Amazon + Réponses Auto") as demo: | |
| gr.Markdown(""" | |
| # 🛍️ Analyse de Sentiment d'Avis Amazon | |
| ## Pipeline IA complet : Nettoyage + Sentiment + Génération de réponses | |
| **Projet Master IA** - Coralie | **Modèle** : CroissantLLMChat (1.3B, bilingue FR/EN) | |
| 🥐 **Version avec CroissantLLM** - Modèle français développé par CentraleSupélec. | |
| Ce projet utilise un **pipeline CI/CD automatique** via Hugging Face Spaces. | |
| 📧 **Nouveau** : Recevez les résultats par email (optionnel) | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### 📝 Avis client Amazon") | |
| review_input = gr.Textbox( | |
| label="Avis client Amazon", | |
| placeholder="Le produit est arrivé cassé et le service client ne répond pas. Très déçu !", | |
| lines=5 | |
| ) | |
| sentiment_radio = gr.Radio( | |
| choices=["auto", "positif", "negatif"], | |
| value="auto", | |
| label="🎯 Sentiment (optionnel - sinon détection auto)", | |
| info="Laissez sur 'auto' pour détection automatique" | |
| ) | |
| email_input = gr.Textbox( | |
| label="📧 Email destinataire (optionnel)", | |
| placeholder="exemple@email.com", | |
| lines=1, | |
| info="Laissez vide si vous ne souhaitez pas recevoir d'email" | |
| ) | |
| analyze_btn = gr.Button("🔍 Analyser l'avis", variant="primary") | |
| with gr.Column(): | |
| gr.Markdown("### 📊 Résultats de l'analyse") | |
| timing_output = gr.Markdown(label="Temps d'exécution") | |
| cleaned_output = gr.Markdown(label="Texte nettoyé") | |
| sentiment_output = gr.Markdown(label="Sentiment") | |
| response_output = gr.Markdown(label="Réponse générée") | |
| email_status_output = gr.Markdown(label="Statut email") | |
| # Bouton d'analyse | |
| analyze_btn.click( | |
| fn=analyze_review, | |
| inputs=[review_input, sentiment_radio, email_input], | |
| outputs=[cleaned_output, sentiment_output, response_output, timing_output, email_status_output] | |
| ) | |
| # Section d'exemples | |
| gr.Markdown(""" | |
| --- | |
| ### 💡 Exemples d'avis à tester : | |
| **Avis négatif :** "Le produit est arrivé cassé et le service client ne répond pas. Très déçu !" | |
| **Avis positif :** "Excellent produit, livraison rapide. Je recommande !" | |
| """) | |
| # Debug toggle | |
| with gr.Accordion("🔧 Texte nettoyé (debug)", open=False): | |
| gr.Markdown("Affiche le texte après nettoyage") | |
| # Lancer l'application | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |