File size: 4,856 Bytes
546c04a
 
e6455d3
 
991ed79
546c04a
991ed79
8085a83
991ed79
9449219
8085a83
 
546c04a
991ed79
 
 
 
 
 
 
e6455d3
991ed79
e6455d3
991ed79
 
 
 
 
 
 
 
e6455d3
 
 
 
 
991ed79
546c04a
 
 
 
 
 
57784e6
991ed79
 
 
57784e6
991ed79
 
 
 
546c04a
991ed79
 
 
 
 
9449219
 
e6455d3
991ed79
546c04a
e6455d3
 
 
 
991ed79
e6455d3
 
 
 
 
 
 
9449219
 
 
991ed79
e6455d3
 
9449219
 
991ed79
 
 
e6455d3
57784e6
9449219
991ed79
9449219
 
991ed79
9449219
 
 
 
57784e6
 
 
 
 
 
 
 
 
 
991ed79
9449219
 
 
 
 
 
 
 
 
 
 
991ed79
 
 
 
 
 
 
57784e6
991ed79
 
 
 
 
 
 
 
 
 
 
 
 
546c04a
991ed79
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
import streamlit as st
from transformers import pipeline
from langdetect import detect
import pandas as pd
import io

# --- Configuration de la page ---
st.set_page_config(
    page_title="🌍 Analyseur de Sentiment Multilingue V4",
    page_icon="🎯",
    layout="centered",
)

# --- Mode Dark/Light ---
theme = st.sidebar.selectbox("🎨 Choisissez le thème :", ["Clair", "Sombre"])
if theme == "Clair":
    background_color = "#f0f2f6"
else:
    background_color = "#222222"

st.markdown(
    f"""
    <style>
    .stApp {{
        background-color: {background_color};
    }}
    textarea {{
        border: 2px solid #5DADE2 !important;
        border-radius: 10px !important;
        background-color: #ffffff !important;
    }}
    </style>
    """,
    unsafe_allow_html=True
)

# --- Charger le modèle ---
@st.cache_resource
def load_model():
    return pipeline("text-classification", model="tabularisai/multilingual-sentiment-analysis")

classifier = load_model()

# --- Initialiser l'historique ---
if 'history' not in st.session_state:
    st.session_state.history = []

# --- Fonction pour la couleur de la barre ---
def sentiment_color(score):
    red = int(255 * (1 - score))
    green = int(255 * score)
    return f'rgb({red},{green},0)'

# --- Interface principale ---
st.title("🎯 Analyseur de Sentiment Multilingue - V4")
st.write("Analysez vos textes avec détection automatique de langue, visualisation dynamique, historique et téléchargement. 🚀")

user_input = st.text_area("✍️ Entrez vos phrases séparées par un point-virgule ';'", height=180)

if st.button("🔎 Analyser"):
    if not user_input.strip():
        st.warning("⚠️ Merci d'entrer au moins une phrase complète.")
    else:
        phrases = [phrase.strip() for phrase in user_input.split(';') if phrase.strip()]
        st.info(f"Nombre de phrases détectées : {len(phrases)}")
        results = []

        with st.spinner("Analyse en cours... ⏳"):
            for phrase in phrases:
                try:
                    lang = detect(phrase)
                except:
                    lang = "indéterminée"

                analysis = classifier(phrase)[0]
                sentiment = analysis["label"]
                score = round(analysis["score"], 2)

                result_entry = {
                    "Texte": phrase,
                    "Langue": lang,
                    "Sentiment": sentiment,
                    "Score": score
                }
                results.append(result_entry)
                st.session_state.history.append(result_entry)

                # Réactions selon le sentiment
                if "negative" in sentiment.lower():
                    st.toast("🚨 Sentiment négatif détecté !", icon="⚡")
                    st.error(f"😞 Texte : {phrase}")
                elif "positive" in sentiment.lower():
                    st.balloons()
                    st.success(f"😊 Texte : {phrase}")
                else:
                    st.warning(f"😐 Texte : {phrase}")

                # Explication du slider
                st.markdown(
                    """
                    <p style="margin-top:20px; text-align:center;">
                    <em>Le score de confiance indique la certitude du modèle concernant l'émotion détectée. Plus le score est élevé, plus la prédiction est fiable.</em>
                    </p>
                    """,
                    unsafe_allow_html=True
                )

                # Barre colorée de score
                color = sentiment_color(score)
                st.markdown(
                    f"""
                    <div style="margin:10px 0;">
                        <div style="height:20px;width:100%;background:linear-gradient(to right, {color} {score*100}%, #d3d3d3 {score*100}%);border-radius:10px;"></div>
                        <center><small><b>Score de confiance : {score:.0%}</b></small></center>
                    </div>
                    """,
                    unsafe_allow_html=True
                )

# --- Résultats stockés et affichés ---
if st.session_state.history:
    st.markdown("---")
    st.subheader("📄 Historique des Analyses")
    df_history = pd.DataFrame(st.session_state.history)
    st.dataframe(df_history)

    # Bouton pour télécharger l'historique en CSV
    csv = df_history.to_csv(index=False)
    buffer = io.BytesIO()
    buffer.write(csv.encode())
    buffer.seek(0)

    st.download_button(
        label="📥 Télécharger l'historique en CSV",
        data=buffer,
        file_name="historique_sentiment.csv",
        mime="text/csv"
    )

# --- Footer ---
st.markdown("---")
st.markdown("🔗 [Voir le modèle Hugging Face](https://huggingface.co/tabularisai/multilingual-sentiment-analysis) | App réalisée avec ❤️ en Python et Streamlit.")