sebtick commited on
Commit
d4ccf04
·
verified ·
1 Parent(s): b811a27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -16
app.py CHANGED
@@ -4,20 +4,21 @@ import pandas as pd
4
  import torch
5
  import io
6
 
7
- # --- Configuration de la page ---
8
  st.set_page_config(
9
- page_title="🌍 Analyseur de Sentiment Multilingue V5",
10
  page_icon="🎯",
11
  layout="centered",
12
  )
13
 
14
- # --- Mode Dark/Light ---
15
  theme = st.sidebar.selectbox("🎨 Choisissez le thème :", ["Clair", "Sombre"])
16
  if theme == "Clair":
17
  background_color = "#f0f2f6"
18
  else:
19
  background_color = "#222222"
20
 
 
21
  st.markdown(
22
  f"""
23
  <style>
@@ -34,13 +35,15 @@ st.markdown(
34
  unsafe_allow_html=True
35
  )
36
 
37
- # --- Chargement des modèles ---
38
  @st.cache_resource
39
  def load_sentiment_model():
 
40
  return pipeline("text-classification", model="tabularisai/multilingual-sentiment-analysis")
41
 
42
  @st.cache_resource
43
  def load_language_model():
 
44
  tokenizer = AutoTokenizer.from_pretrained("papluca/xlm-roberta-base-language-detection")
45
  model = AutoModelForSequenceClassification.from_pretrained("papluca/xlm-roberta-base-language-detection")
46
  return tokenizer, model
@@ -48,30 +51,34 @@ def load_language_model():
48
  sentiment_model = load_sentiment_model()
49
  tokenizer_lang, model_lang = load_language_model()
50
 
51
- # --- Détecteur de langue IA ---
52
  def detect_language(text):
 
53
  inputs = tokenizer_lang(text, return_tensors="pt", truncation=True, max_length=512)
54
  outputs = model_lang(**inputs)
55
  predicted_class = torch.argmax(outputs.logits, dim=1)
56
  label = model_lang.config.id2label[predicted_class.item()]
57
  return label
58
 
59
- # --- Initialiser l'historique ---
60
  if 'history' not in st.session_state:
61
  st.session_state.history = []
62
 
63
- # --- Fonction pour couleur de la barre ---
64
  def sentiment_color(score):
 
65
  red = int(255 * (1 - score))
66
  green = int(255 * score)
67
  return f'rgb({red},{green},0)'
68
 
69
  # --- Interface principale ---
70
- st.title("🎯 Analyseur de Sentiment Multilingue - V5")
71
- st.write("Analysez vos textes avec détection IA de langue et sentiment, historique et téléchargement. 🚀")
72
 
 
73
  user_input = st.text_area("✍️ Entrez vos phrases séparées par un point-virgule ';'", height=180)
74
 
 
75
  if st.button("🔎 Analyser"):
76
  if not user_input.strip():
77
  st.warning("⚠️ Merci d'entrer au moins une phrase complète.")
@@ -80,17 +87,21 @@ if st.button("🔎 Analyser"):
80
  st.info(f"Nombre de phrases détectées : {len(phrases)}")
81
  results = []
82
 
 
83
  with st.spinner("Analyse en cours... ⏳"):
84
  for phrase in phrases:
 
85
  try:
86
  lang = detect_language(phrase)
87
  except Exception as e:
88
  lang = "Erreur"
89
 
 
90
  analysis = sentiment_model(phrase)[0]
91
  sentiment = analysis["label"]
92
  score = round(analysis["score"], 2)
93
 
 
94
  result_entry = {
95
  "Texte": phrase,
96
  "Langue": lang,
@@ -100,7 +111,7 @@ if st.button("🔎 Analyser"):
100
  results.append(result_entry)
101
  st.session_state.history.append(result_entry)
102
 
103
- # Réactions
104
  if "negative" in sentiment.lower():
105
  st.toast("🚨 Sentiment négatif détecté !", icon="⚡")
106
  st.error(f"😞 Texte : {phrase}")
@@ -110,7 +121,7 @@ if st.button("🔎 Analyser"):
110
  else:
111
  st.warning(f"😐 Texte : {phrase}")
112
 
113
- # Explication du slider
114
  st.markdown(
115
  """
116
  <p style="margin-top:20px; text-align:center;">
@@ -120,7 +131,7 @@ if st.button("🔎 Analyser"):
120
  unsafe_allow_html=True
121
  )
122
 
123
- # Barre colorée
124
  color = sentiment_color(score)
125
  st.markdown(
126
  f"""
@@ -132,14 +143,14 @@ if st.button("🔎 Analyser"):
132
  unsafe_allow_html=True
133
  )
134
 
135
- # --- Historique des analyses ---
136
  if st.session_state.history:
137
  st.markdown("---")
138
  st.subheader("📄 Historique des Analyses")
139
  df_history = pd.DataFrame(st.session_state.history)
140
  st.dataframe(df_history)
141
 
142
- # Bouton pour télécharger CSV
143
  csv = df_history.to_csv(index=False)
144
  buffer = io.BytesIO()
145
  buffer.write(csv.encode())
@@ -152,6 +163,11 @@ if st.session_state.history:
152
  mime="text/csv"
153
  )
154
 
155
- # --- Footer ---
156
  st.markdown("---")
157
- 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.")
 
 
 
 
 
 
4
  import torch
5
  import io
6
 
7
+ # --- Configuration générale de la page ---
8
  st.set_page_config(
9
+ page_title="🌍 Analyseur de Sentiment Multilingue",
10
  page_icon="🎯",
11
  layout="centered",
12
  )
13
 
14
+ # --- Choix du thème (clair/sombre) par l'utilisateur ---
15
  theme = st.sidebar.selectbox("🎨 Choisissez le thème :", ["Clair", "Sombre"])
16
  if theme == "Clair":
17
  background_color = "#f0f2f6"
18
  else:
19
  background_color = "#222222"
20
 
21
+ # --- Application du fond selon le thème choisi ---
22
  st.markdown(
23
  f"""
24
  <style>
 
35
  unsafe_allow_html=True
36
  )
37
 
38
+ # --- Chargement des modèles IA ---
39
  @st.cache_resource
40
  def load_sentiment_model():
41
+ """Charge le modèle de détection de sentiment."""
42
  return pipeline("text-classification", model="tabularisai/multilingual-sentiment-analysis")
43
 
44
  @st.cache_resource
45
  def load_language_model():
46
+ """Charge le modèle de détection de langue."""
47
  tokenizer = AutoTokenizer.from_pretrained("papluca/xlm-roberta-base-language-detection")
48
  model = AutoModelForSequenceClassification.from_pretrained("papluca/xlm-roberta-base-language-detection")
49
  return tokenizer, model
 
51
  sentiment_model = load_sentiment_model()
52
  tokenizer_lang, model_lang = load_language_model()
53
 
54
+ # --- Fonction de détection de langue avec IA ---
55
  def detect_language(text):
56
+ """Détecte automatiquement la langue du texte fourni."""
57
  inputs = tokenizer_lang(text, return_tensors="pt", truncation=True, max_length=512)
58
  outputs = model_lang(**inputs)
59
  predicted_class = torch.argmax(outputs.logits, dim=1)
60
  label = model_lang.config.id2label[predicted_class.item()]
61
  return label
62
 
63
+ # --- Initialisation de l'historique si non existant ---
64
  if 'history' not in st.session_state:
65
  st.session_state.history = []
66
 
67
+ # --- Fonction pour calculer la couleur de la barre selon le score ---
68
  def sentiment_color(score):
69
+ """Retourne une couleur RGB en fonction du score de confiance."""
70
  red = int(255 * (1 - score))
71
  green = int(255 * score)
72
  return f'rgb({red},{green},0)'
73
 
74
  # --- Interface principale ---
75
+ st.title("🎯 Analyseur de Sentiment Multilingue")
76
+ st.write("Cette application utilise deux modèles d'IA pour détecter la langue et analyser le sentiment d'un texte.")
77
 
78
+ # --- Saisie utilisateur ---
79
  user_input = st.text_area("✍️ Entrez vos phrases séparées par un point-virgule ';'", height=180)
80
 
81
+ # --- Bouton pour déclencher l'analyse ---
82
  if st.button("🔎 Analyser"):
83
  if not user_input.strip():
84
  st.warning("⚠️ Merci d'entrer au moins une phrase complète.")
 
87
  st.info(f"Nombre de phrases détectées : {len(phrases)}")
88
  results = []
89
 
90
+ # --- Traitement de chaque phrase ---
91
  with st.spinner("Analyse en cours... ⏳"):
92
  for phrase in phrases:
93
+ # Détection de la langue
94
  try:
95
  lang = detect_language(phrase)
96
  except Exception as e:
97
  lang = "Erreur"
98
 
99
+ # Analyse du sentiment
100
  analysis = sentiment_model(phrase)[0]
101
  sentiment = analysis["label"]
102
  score = round(analysis["score"], 2)
103
 
104
+ # Stockage des résultats
105
  result_entry = {
106
  "Texte": phrase,
107
  "Langue": lang,
 
111
  results.append(result_entry)
112
  st.session_state.history.append(result_entry)
113
 
114
+ # --- Affichage des résultats pour chaque phrase ---
115
  if "negative" in sentiment.lower():
116
  st.toast("🚨 Sentiment négatif détecté !", icon="⚡")
117
  st.error(f"😞 Texte : {phrase}")
 
121
  else:
122
  st.warning(f"😐 Texte : {phrase}")
123
 
124
+ # --- Explication du slider de confiance ---
125
  st.markdown(
126
  """
127
  <p style="margin-top:20px; text-align:center;">
 
131
  unsafe_allow_html=True
132
  )
133
 
134
+ # --- Barre colorée de score ---
135
  color = sentiment_color(score)
136
  st.markdown(
137
  f"""
 
143
  unsafe_allow_html=True
144
  )
145
 
146
+ # --- Affichage de l'historique des analyses ---
147
  if st.session_state.history:
148
  st.markdown("---")
149
  st.subheader("📄 Historique des Analyses")
150
  df_history = pd.DataFrame(st.session_state.history)
151
  st.dataframe(df_history)
152
 
153
+ # --- Téléchargement de l'historique en CSV ---
154
  csv = df_history.to_csv(index=False)
155
  buffer = io.BytesIO()
156
  buffer.write(csv.encode())
 
163
  mime="text/csv"
164
  )
165
 
166
+ # --- Footer avec crédits modèles ---
167
  st.markdown("---")
168
+ st.markdown(
169
+ """
170
+ 🔗 [Voir le modèle de sentiment utilisé](https://huggingface.co/tabularisai/multilingual-sentiment-analysis)
171
+ 🔗 [Voir le modèle de détection de langue utilisé](https://huggingface.co/papluca/xlm-roberta-base-language-detection)
172
+ """
173
+ )