DinoFrog commited on
Commit
4504964
·
verified ·
1 Parent(s): 3f9d1b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -45
app.py CHANGED
@@ -1,6 +1,7 @@
1
  from transformers import pipeline
2
  from langdetect import detect
3
  import gradio as gr
 
4
 
5
  # Chargement du modèle de sentiment
6
  classifier = pipeline(
@@ -8,42 +9,39 @@ classifier = pipeline(
8
  model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis"
9
  )
10
 
11
- # Modèle génératif pour créer des explications
12
- explainer = pipeline(
13
- "text2text-generation",
14
- model="google/flan-t5-small"
15
- )
16
-
17
- # Modèle de traduction multilingue -> anglais
18
  translator_to_en = pipeline(
19
  "translation",
20
  model="Helsinki-NLP/opus-mt-mul-en"
21
  )
22
-
23
- # Modèle de traduction anglais -> français
24
  translator_to_fr = pipeline(
25
  "translation",
26
  model="Helsinki-NLP/opus-mt-en-fr"
27
  )
28
 
29
- # Variables globales pour stocker le dernier texte/sentiment
30
- last_text = ""
31
- last_sentiment = ""
32
-
33
- # Fonction d'analyse de sentiment
34
- def analyze_sentiment(text):
35
- global last_text, last_sentiment
36
 
 
 
37
  if not text:
38
- return "Entrez une phrase.", "", ""
 
 
 
39
 
40
- # Détection de la langue
41
  try:
42
  lang = detect(text)
43
  except:
44
  lang = "unknown"
45
 
46
- # Traduire si nécessaire
47
  if lang != "en":
48
  text = translator_to_en(text, max_length=512)[0]['translation_text']
49
 
@@ -51,45 +49,94 @@ def analyze_sentiment(text):
51
  result = classifier(text)[0]
52
  sentiment_output = f"Sentiment : {result['label']} (Score: {result['score']:.2f})"
53
 
54
- # Sauvegarder pour explication
55
- last_text = text
56
- last_sentiment = result['label']
57
-
58
- return sentiment_output, "", ""
59
-
60
- # Fonction pour générer explication en anglais + français
61
- def generate_explanation():
62
- if not last_text or not last_sentiment:
63
- return "", "Aucune analyse récente trouvée."
64
-
65
- # Préparer le prompt
66
- prompt = f"Explain why the following financial news is {last_sentiment.lower()}: \"{last_text}\""
67
  explanation_en = explainer(prompt, max_length=100)[0]['generated_text']
68
 
69
- # Traduire en français
70
  explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
71
 
72
- return explanation_en, explanation_fr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  # Interface Gradio
75
  with gr.Blocks() as iface:
76
  gr.Markdown("# 📈 Analyse de Sentiment Financier Multilingue + Explication 🌍")
77
- gr.Markdown("Entrez une actualité financière. L'analyse détecte le sentiment et peut expliquer en anglais **et en français** !")
78
 
79
- with gr.Row():
80
- input_text = gr.Textbox(lines=4, placeholder="Entrez votre actualité financière ici...")
81
 
82
  with gr.Row():
83
- sentiment_output = gr.Textbox(label="Résultat du sentiment")
84
-
85
  with gr.Row():
86
- explanation_output_en = gr.Textbox(label="Explication (anglais)")
87
- explanation_output_fr = gr.Textbox(label="Explication (français)")
 
 
 
88
 
89
  analyze_btn = gr.Button("Analyser")
90
- explain_btn = gr.Button("Générer explication")
 
 
 
 
 
91
 
92
- analyze_btn.click(analyze_sentiment, inputs=[input_text], outputs=[sentiment_output, explanation_output_en, explanation_output_fr])
93
- explain_btn.click(generate_explanation, outputs=[explanation_output_en, explanation_output_fr])
 
 
 
94
 
95
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from transformers import pipeline
2
  from langdetect import detect
3
  import gradio as gr
4
+ import pandas as pd
5
 
6
  # Chargement du modèle de sentiment
7
  classifier = pipeline(
 
9
  model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis"
10
  )
11
 
12
+ # Modèles de traduction
 
 
 
 
 
 
13
  translator_to_en = pipeline(
14
  "translation",
15
  model="Helsinki-NLP/opus-mt-mul-en"
16
  )
 
 
17
  translator_to_fr = pipeline(
18
  "translation",
19
  model="Helsinki-NLP/opus-mt-en-fr"
20
  )
21
 
22
+ # Fonction pour charger dynamiquement le modèle d'explication
23
+ def load_explainer(mode):
24
+ if mode == "Rapide":
25
+ model_name = "google/flan-t5-small"
26
+ else: # Précis
27
+ model_name = "google/flan-t5-base"
28
+ return pipeline("text2text-generation", model=model_name)
29
 
30
+ # Fonction complète d'analyse + explication
31
+ def full_analysis(text, mode, count, history):
32
  if not text:
33
+ return "Entrez une phrase.", "", "", count, history, None
34
+
35
+ # Charger l'explainer correspondant
36
+ explainer = load_explainer(mode)
37
 
38
+ # Détection de langue
39
  try:
40
  lang = detect(text)
41
  except:
42
  lang = "unknown"
43
 
44
+ # Traduction si besoin
45
  if lang != "en":
46
  text = translator_to_en(text, max_length=512)[0]['translation_text']
47
 
 
49
  result = classifier(text)[0]
50
  sentiment_output = f"Sentiment : {result['label']} (Score: {result['score']:.2f})"
51
 
52
+ # Génération de l'explication
53
+ prompt = f"Explain why the following financial news is {result['label'].lower()}: \"{text}\""
 
 
 
 
 
 
 
 
 
 
 
54
  explanation_en = explainer(prompt, max_length=100)[0]['generated_text']
55
 
56
+ # Traduction de l'explication
57
  explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
58
 
59
+ # Mise à jour historique
60
+ count += 1
61
+ history.append({
62
+ "Texte": text,
63
+ "Sentiment": result['label'],
64
+ "Score": f"{result['score']:.2f}",
65
+ "Explication_EN": explanation_en,
66
+ "Explication_FR": explanation_fr,
67
+ "Mode": mode
68
+ })
69
+
70
+ return sentiment_output, explanation_en, explanation_fr, count, history, None
71
+
72
+ # Fonction pour télécharger historique
73
+ def download_history(history):
74
+ if not history:
75
+ return None
76
+ df = pd.DataFrame(history)
77
+ file_path = "/tmp/analysis_history.csv"
78
+ df.to_csv(file_path, index=False)
79
+ return file_path
80
 
81
  # Interface Gradio
82
  with gr.Blocks() as iface:
83
  gr.Markdown("# 📈 Analyse de Sentiment Financier Multilingue + Explication 🌍")
84
+ gr.Markdown("Entrez une actualité financière. Analyse automatique du sentiment et génération d'une explication **bilingue** avec choix du modèle.")
85
 
86
+ count = gr.State(0)
87
+ history = gr.State([])
88
 
89
  with gr.Row():
90
+ input_text = gr.Textbox(lines=4, placeholder="Entrez votre actualité ici...")
91
+
92
  with gr.Row():
93
+ mode_selector = gr.Dropdown(
94
+ choices=["Rapide", "Précis"],
95
+ label="Choisissez le mode d'explication",
96
+ value="Rapide"
97
+ )
98
 
99
  analyze_btn = gr.Button("Analyser")
100
+ download_btn = gr.Button("Télécharger l'historique CSV")
101
+
102
+ loading_text = gr.Markdown("⏳ Analyse en cours...", visible=False)
103
+
104
+ with gr.Row():
105
+ sentiment_output = gr.Textbox(label="Résultat du sentiment")
106
 
107
+ with gr.Row():
108
+ with gr.Column():
109
+ explanation_output_en = gr.Textbox(label="Explication en Anglais")
110
+ with gr.Column():
111
+ explanation_output_fr = gr.Textbox(label="Explication en Français")
112
 
113
+ with gr.Row():
114
+ analysis_count_display = gr.Textbox(label="Nombre total d'analyses", interactive=False)
115
+
116
+ download_file = gr.File(label="Téléchargement du CSV")
117
+
118
+ # Clic sur "Analyser"
119
+ analyze_btn.click(
120
+ lambda: gr.update(visible=True),
121
+ outputs=[loading_text]
122
+ ).then(
123
+ full_analysis,
124
+ inputs=[input_text, mode_selector, count, history],
125
+ outputs=[sentiment_output, explanation_output_en, explanation_output_fr, count, history, download_file]
126
+ ).then(
127
+ lambda c: gr.update(value=f"{c} analyses réalisées"),
128
+ inputs=[count],
129
+ outputs=[analysis_count_display]
130
+ ).then(
131
+ lambda: gr.update(visible=False),
132
+ outputs=[loading_text]
133
+ )
134
+
135
+ # Clic sur "Télécharger historique"
136
+ download_btn.click(
137
+ download_history,
138
+ inputs=[history],
139
+ outputs=[download_file]
140
+ )
141
+
142
+ iface.launch()