Spaces:
Sleeping
Sleeping
File size: 5,597 Bytes
546c04a b811a27 e6455d3 b811a27 991ed79 546c04a 991ed79 8085a83 b811a27 9449219 8085a83 546c04a 991ed79 e6455d3 991ed79 e6455d3 991ed79 e6455d3 b811a27 546c04a b811a27 546c04a b811a27 546c04a 57784e6 991ed79 b811a27 991ed79 546c04a 991ed79 b811a27 991ed79 9449219 e6455d3 991ed79 546c04a e6455d3 991ed79 e6455d3 b811a27 e6455d3 b811a27 9449219 991ed79 e6455d3 9449219 991ed79 e6455d3 b811a27 9449219 991ed79 9449219 991ed79 9449219 57784e6 b811a27 9449219 b811a27 991ed79 b811a27 991ed79 546c04a b811a27 |
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 |
import streamlit as st
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
import pandas as pd
import torch
import io
# --- Configuration de la page ---
st.set_page_config(
page_title="🌍 Analyseur de Sentiment Multilingue V5",
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
)
# --- Chargement des modèles ---
@st.cache_resource
def load_sentiment_model():
return pipeline("text-classification", model="tabularisai/multilingual-sentiment-analysis")
@st.cache_resource
def load_language_model():
tokenizer = AutoTokenizer.from_pretrained("papluca/xlm-roberta-base-language-detection")
model = AutoModelForSequenceClassification.from_pretrained("papluca/xlm-roberta-base-language-detection")
return tokenizer, model
sentiment_model = load_sentiment_model()
tokenizer_lang, model_lang = load_language_model()
# --- Détecteur de langue IA ---
def detect_language(text):
inputs = tokenizer_lang(text, return_tensors="pt", truncation=True, max_length=512)
outputs = model_lang(**inputs)
predicted_class = torch.argmax(outputs.logits, dim=1)
label = model_lang.config.id2label[predicted_class.item()]
return label
# --- Initialiser l'historique ---
if 'history' not in st.session_state:
st.session_state.history = []
# --- Fonction pour 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 - V5")
st.write("Analysez vos textes avec détection IA de langue et sentiment, 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_language(phrase)
except Exception as e:
lang = "Erreur"
analysis = sentiment_model(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
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
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
)
# --- Historique des analyses ---
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 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 de sentiment](https://huggingface.co/tabularisai/multilingual-sentiment-analysis) | 🔗 [Voir le modèle de langue](https://huggingface.co/papluca/xlm-roberta-base-language-detection) | Réalisé avec ❤️ et IA.")
|