Spaces:
Runtime error
Runtime error
File size: 6,537 Bytes
420ac85 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
"""
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)
|