DinoFrog commited on
Commit
5b0e9a8
·
verified ·
1 Parent(s): 4504964

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -27
app.py CHANGED
@@ -3,7 +3,7 @@ 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(
8
  "sentiment-analysis",
9
  model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis"
@@ -19,21 +19,36 @@ translator_to_fr = pipeline(
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:
@@ -49,11 +64,11 @@ def full_analysis(text, mode, count, history):
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
@@ -64,12 +79,12 @@ def full_analysis(text, mode, count, history):
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
@@ -78,23 +93,24 @@ def download_history(history):
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")
@@ -115,13 +131,24 @@ with gr.Blocks() as iface:
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"),
@@ -132,7 +159,6 @@ with gr.Blocks() as iface:
132
  outputs=[loading_text]
133
  )
134
 
135
- # Clic sur "Télécharger historique"
136
  download_btn.click(
137
  download_history,
138
  inputs=[history],
 
3
  import gradio as gr
4
  import pandas as pd
5
 
6
+ # Chargement modèle de sentiment
7
  classifier = pipeline(
8
  "sentiment-analysis",
9
  model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis"
 
19
  model="Helsinki-NLP/opus-mt-en-fr"
20
  )
21
 
22
+ # Modèles disponibles
23
+ MODEL_OPTIONS = {
24
+ "Flan-T5 Small (rapide)" : "google/flan-t5-small",
25
+ "Flan-T5 Base (équilibré)" : "google/flan-t5-base",
26
+ "Flan-T5 Large (précis)" : "google/flan-t5-large",
27
+ }
28
+
29
+ # Fonction pour charger un modèle d'explication
30
+ def load_explainer(model_choice):
31
+ model_name = MODEL_OPTIONS.get(model_choice, "google/flan-t5-small")
32
  return pipeline("text2text-generation", model=model_name)
33
 
34
+ # Fonction pour suggérer le meilleur modèle
35
+ def suggest_model(text):
36
+ word_count = len(text.split())
37
+ if word_count < 50:
38
+ suggestion = "Flan-T5 Small (rapide)"
39
+ elif word_count <= 200:
40
+ suggestion = "Flan-T5 Base (équilibré)"
41
+ else:
42
+ suggestion = "Flan-T5 Large (précis)"
43
+ return suggestion
44
+
45
  # Fonction complète d'analyse + explication
46
+ def full_analysis(text, model_choice, count, history):
47
  if not text:
48
  return "Entrez une phrase.", "", "", count, history, None
49
 
50
+ # Charger modèle sélectionné
51
+ explainer = load_explainer(model_choice)
52
 
53
  # Détection de langue
54
  try:
 
64
  result = classifier(text)[0]
65
  sentiment_output = f"Sentiment : {result['label']} (Score: {result['score']:.2f})"
66
 
67
+ # Prompt amélioré pour meilleure explication
68
+ prompt = f"""Given the following financial news: \"{text}\", explain in natural, clear and detailed language why the sentiment is {result['label'].lower()}. Focus on the main financial aspects and keep it concise."""
69
+ explanation_en = explainer(prompt, max_length=150)[0]['generated_text']
70
 
71
+ # Traduction française
72
  explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
73
 
74
  # Mise à jour historique
 
79
  "Score": f"{result['score']:.2f}",
80
  "Explication_EN": explanation_en,
81
  "Explication_FR": explanation_fr,
82
+ "Modèle utilisé": model_choice
83
  })
84
 
85
  return sentiment_output, explanation_en, explanation_fr, count, history, None
86
 
87
+ # Fonction pour générer historique CSV
88
  def download_history(history):
89
  if not history:
90
  return None
 
93
  df.to_csv(file_path, index=False)
94
  return file_path
95
 
96
+ # Interface
97
  with gr.Blocks() as iface:
98
+ gr.Markdown("# 📈 Analyse de Sentiment Financier Multilingue + Raisonnement 🌍")
99
+ gr.Markdown("Entrez une actualité financière. L'analyse détecte automatiquement le sentiment et génère une explication **bilingue**.\nChoisissez ou laissez l'IA vous suggérer le meilleur modèle selon la longueur de votre texte.")
100
 
101
  count = gr.State(0)
102
  history = gr.State([])
103
 
104
  with gr.Row():
105
  input_text = gr.Textbox(lines=4, placeholder="Entrez votre actualité ici...")
106
+
107
  with gr.Row():
108
+ model_selector = gr.Dropdown(
109
+ choices=list(MODEL_OPTIONS.keys()),
110
+ label="Choisissez le modèle d'explication",
111
+ value="Flan-T5 Base (équilibré)"
112
  )
113
+ model_suggestion = gr.Markdown("")
114
 
115
  analyze_btn = gr.Button("Analyser")
116
  download_btn = gr.Button("Télécharger l'historique CSV")
 
131
 
132
  download_file = gr.File(label="Téléchargement du CSV")
133
 
134
+ # Suggestions dynamiques du modèle
135
+ input_text.change(
136
+ lambda text: gr.update(value=suggest_model(text)),
137
+ inputs=[input_text],
138
+ outputs=[model_selector]
139
+ ).then(
140
+ lambda text: gr.update(value=f"💡 Suggestion IA : {suggest_model(text)}"),
141
+ inputs=[input_text],
142
+ outputs=[model_suggestion]
143
+ )
144
+
145
+ # Actions boutons
146
  analyze_btn.click(
147
  lambda: gr.update(visible=True),
148
  outputs=[loading_text]
149
  ).then(
150
  full_analysis,
151
+ inputs=[input_text, model_selector, count, history],
152
  outputs=[sentiment_output, explanation_output_en, explanation_output_fr, count, history, download_file]
153
  ).then(
154
  lambda c: gr.update(value=f"{c} analyses réalisées"),
 
159
  outputs=[loading_text]
160
  )
161
 
 
162
  download_btn.click(
163
  download_history,
164
  inputs=[history],