DinoFrog commited on
Commit
8c2b49e
·
verified ·
1 Parent(s): 78d147f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -240
app.py CHANGED
@@ -6,12 +6,27 @@ import pandas as pd
6
  import os
7
  import nltk
8
  import asyncio
9
- nltk.download('punkt_tab')
 
10
  from nltk.tokenize import sent_tokenize
11
 
12
  HF_TOKEN = os.getenv("HF_TOKEN")
13
 
14
- # Fonction pour appeler l'API Zephyr avec des paramètres ajustés
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  async def call_zephyr_api(prompt, mode, hf_token=HF_TOKEN):
16
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)
17
  try:
@@ -21,27 +36,15 @@ async def call_zephyr_api(prompt, mode, hf_token=HF_TOKEN):
21
  elif mode == "Équilibré":
22
  max_new_tokens = 100
23
  temperature = 0.5
24
- else: # Précis
25
  max_new_tokens = 150
26
  temperature = 0.7
27
  response = await asyncio.to_thread(client.text_generation, prompt, max_new_tokens=max_new_tokens, temperature=temperature)
28
  return response
29
  except Exception as e:
30
- raise gr.Error(f"❌ Erreur d'appel API Hugging Face : {str(e)}")
31
-
32
- # Chargement du modèle de sentiment pour analyser les réponses
33
- classifier = pipeline("sentiment-analysis", model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis")
34
-
35
- # Modèles de traduction (optionnels, désactivés pour optimisation)
36
- translator_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
37
- # Traduction en français désactivée pour l'instant
38
- # translator_to_fr = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr")
39
 
40
- # Fonction pour traduire un texte long en le segmentant (désactivée pour l'instant)
41
- def safe_translate_to_fr(text, max_length=512):
42
- return "Traduction désactivée pour l'instant pour améliorer la vitesse."
43
-
44
- # Fonction pour suggérer le meilleur modèle
45
  def suggest_model(text):
46
  word_count = len(text.split())
47
  if word_count < 50:
@@ -51,42 +54,33 @@ def suggest_model(text):
51
  else:
52
  return "Précis"
53
 
54
- # Fonction pour créer une jauge de sentiment
55
  def create_sentiment_gauge(sentiment, score):
56
  score_percentage = score * 100
57
- if sentiment.lower() == "neutral":
58
- color = "#A9A9A9"
59
- elif sentiment.lower() == "positive":
60
  color = "#2E8B57"
61
  elif sentiment.lower() == "negative":
62
  color = "#DC143C"
63
- else:
64
- color = "#A9A9A9"
65
 
66
  html = f"""
67
  <div style='width: 100%; max-width: 300px; margin: 10px 0;'>
68
- <div style='background-color: #D3D3D3; border-radius: 5px; height: 20px; position: relative; box-shadow: 0 2px 4px rgba(0,0,0,0.2);'>
69
- <div style='background-color: {color}; width: {score_percentage}%; height: 100%; border-radius: 5px; transition: width 0.3s ease-in-out;'>
70
- </div>
71
- <span style='position: absolute; top: 0; left: 50%; transform: translateX(-50%); color: #0A1D37; font-size: 12px; line-height: 20px; font-weight: 600;'>
72
- {score_percentage:.1f}%
73
- </span>
74
- </div>
75
- <div style='text-align: center; font-size: 14px; margin-top: 5px; color: #E0E0E0;'>
76
- Sentiment: {sentiment}
77
  </div>
 
78
  </div>
79
  """
80
  return html
81
 
82
- # Fonction d'analyse corrigée
83
  async def full_analysis(text, mode, detail_mode, count, history):
84
  if not text:
85
- yield "Entrez une phrase.", "", "", 0, history, None, ""
86
  return
87
 
88
- # Message de progression
89
- yield "Analyse en cours... (Étape 1 : Détection de la langue)", "", "", count, history, None, ""
90
 
91
  try:
92
  lang = detect(text)
@@ -98,17 +92,15 @@ async def full_analysis(text, mode, detail_mode, count, history):
98
  else:
99
  text_en = text
100
 
101
- yield "Analyse en cours... (Étape 2 : Analyse du sentiment)", "", "", count, history, None, ""
102
 
103
- # Analyse du sentiment avec RoBERTa sur le texte d'entrée
104
  result = await asyncio.to_thread(classifier, text_en)
105
  result = result[0]
106
  sentiment_output = f"Sentiment prédictif : {result['label']} (Score: {result['score']:.2f})"
107
  sentiment_gauge = create_sentiment_gauge(result['label'], result['score'])
108
 
109
- yield "Analyse en cours... (Étape 3 : Explication de l'impact)", "", "", count, history, None, ""
110
 
111
- # Appel à Zephyr pour expliquer l'impact basé sur le sentiment
112
  explanation_prompt = f"""<|system|>
113
  You are a professional financial analyst AI with expertise in economic forecasting.
114
  </s>
@@ -117,15 +109,14 @@ Given the following question about a potential economic event: "{text}"
117
 
118
  The predicted sentiment for this event is: {result['label'].lower()}.
119
 
120
- Assume the event happens (e.g., if the question is "Will the Federal Reserve raise interest rates?", assume they do raise rates). Explain why this event would likely have a {result['label'].lower()} economic impact. Provide a concise explanation in one paragraph, focusing on the potential effects on the economy. {"Use simple language for a general audience." if detail_mode == "Normal" else "Use detailed financial terminology for an expert audience."}
121
  </s>
122
  <|assistant|>"""
123
  explanation_en = await call_zephyr_api(explanation_prompt, mode)
124
 
125
- yield "Analyse en cours... (Étape 4 : Traduction)", "", "", count, history, None, ""
126
 
127
- # Traduction (désactivée pour l'instant)
128
- explanation_fr = safe_translate_to_fr(explanation_en, max_length=512)
129
 
130
  count += 1
131
  history.append({
@@ -136,9 +127,9 @@ Assume the event happens (e.g., if the question is "Will the Federal Reserve rai
136
  "Explication_FR": explanation_fr
137
  })
138
 
139
- yield sentiment_output, explanation_en, explanation_fr, count, history, sentiment_gauge, ""
140
 
141
- # Fonction pour télécharger historique CSV
142
  def download_history(history):
143
  if not history:
144
  return None
@@ -147,222 +138,62 @@ def download_history(history):
147
  df.to_csv(file_path, index=False)
148
  return file_path
149
 
150
- # Interface Gradio améliorée
151
  def launch_app():
152
  custom_css = """
153
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
154
- @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
155
-
156
  body {
157
- background-image: url('https://images.unsplash.com/photo-1593672715438-d88a70629abe?q=80&w=2070&auto=format&fit=crop');
158
- background-size: cover;
159
- background-position: center;
160
- background-attachment: fixed;
161
- background-color: #0A1D37;
162
- background-blend-mode: overlay;
163
- color: #E0E0E0;
164
  font-family: 'Inter', sans-serif;
165
- margin: 0;
166
  padding: 20px;
167
  }
168
-
169
  .gr-box {
170
- background: #1A3C34 !important;
171
- border-radius: 12px !important;
172
  border: 1px solid #FFD700 !important;
173
- box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4) !important;
174
- padding: 25px !important;
175
- margin: 15px 0 !important;
176
- transition: transform 0.2s ease, box-shadow 0.3s ease !important;
177
- }
178
-
179
- .gr-box:hover {
180
- transform: translateY(-3px) !important;
181
- box-shadow: 0 8px 20px rgba(255, 215, 0, 0.3) !important;
182
- }
183
-
184
- .gr-textbox, .gr-dropdown {
185
- background: #2E4A43 !important;
186
- border: 1px solid #FFD700 !important;
187
- border-radius: 8px !important;
188
- color: #E0E0E0 !important;
189
- font-size: 16px !important;
190
- padding: 12px !important;
191
- transition: border-color 0.3s ease, box-shadow 0.3s ease !important;
192
- }
193
-
194
- .gr-textbox:focus, .gr-dropdown:focus {
195
- border-color: #FFD700 !important;
196
- box-shadow: 0 0 10px rgba(255, 215, 0, 0.4) !important;
197
  }
198
-
199
  .gr-button {
200
- background: linear-gradient(90deg, #FFD700 0%, #D4AF37 100%) !important;
201
- color: #0A1D37 !important;
202
- border: none !important;
203
- border-radius: 8px !important;
204
- padding: 12px 24px !important;
205
- font-weight: 600 !important;
206
- font-size: 16px !important;
207
- transition: transform 0.1s ease, box-shadow 0.3s ease !important;
208
- box-shadow: 0 3px 10px rgba(255, 215, 0, 0.3) !important;
209
  }
210
-
211
  .gr-button:hover {
212
- transform: translateY(-2px) !important;
213
- box-shadow: 0 6px 14px rgba(255, 215, 0, 0.5) !important;
214
- }
215
-
216
- h1, h2, h3 {
217
- color: #FFD700 !important;
218
- font-weight: 700 !important;
219
- text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3) !important;
220
- animation: fadeIn 1s ease-in-out;
221
- }
222
-
223
- @keyframes fadeIn {
224
- from { opacity: 0; transform: translateY(-10px); }
225
- to { opacity: 1; transform: translateY(0); }
226
- }
227
-
228
- .gr-row {
229
- margin: 20px 0 !important;
230
- }
231
-
232
- .gr-column {
233
- padding: 15px !important;
234
- }
235
-
236
- label {
237
- color: #FFD700 !important;
238
- font-weight: 600 !important;
239
- font-size: 16px !important;
240
- margin-bottom: 8px !important;
241
- display: flex !important;
242
- align-items: center !important;
243
- }
244
-
245
- label::before {
246
- font-family: "Font Awesome 6 Free";
247
- font-weight: 900;
248
- margin-right: 8px;
249
- }
250
-
251
- .gr-textbox label::before {
252
- content: '\\f201';
253
- }
254
-
255
- .gr-html label::before {
256
- content: '\\f080';
257
- }
258
-
259
- .gr-file label::before {
260
- content: '\\f019';
261
- }
262
-
263
- .economic-question-section {
264
- background: rgba(26, 60, 52, 0.9) !important;
265
- border-radius: 12px;
266
- padding: 25px;
267
- margin: 20px 0;
268
- box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
269
- }
270
-
271
- .economic-question-section .gr-textbox {
272
- background: rgba(46, 74, 67, 0.8) !important;
273
- border: 2px solid #FFD700 !important;
274
- box-shadow: 0 3px 10px rgba(255, 215, 0, 0.3) !important;
275
- font-size: 18px !important;
276
- padding: 15px !important;
277
- }
278
-
279
- .economic-question-section .gr-textbox:focus {
280
- border-color: #FFD700 !important;
281
- box-shadow: 0 0 12px rgba(255, 215, 0, 0.5) !important;
282
- }
283
-
284
- .prompt-box {
285
- background: rgba(46, 74, 67, 0.6) !important;
286
- border: 1px solid #FFD700 !important;
287
- border-radius: 8px !important;
288
- color: #E0E0E0 !important;
289
- font-size: 16px !important;
290
- padding: 12px !important;
291
- margin-top: 10px !important;
292
- }
293
-
294
- .prompt-box label::before {
295
- content: '\\f075';
296
- }
297
-
298
- .options-section {
299
- display: flex;
300
- flex-direction: column;
301
- gap: 15px;
302
- margin-top: 15px;
303
- }
304
-
305
- .options-section .gr-dropdown {
306
- width: 200px !important;
307
- }
308
-
309
- .options-section .gr-dropdown label::before {
310
- content: '\\f0c9';
311
- }
312
-
313
- .progress-message {
314
- color: #FFD700 !important;
315
- font-style: italic;
316
- margin-bottom: 10px;
317
  }
318
  """
319
 
320
  with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface:
321
- gr.Markdown("# 📈 Analyse Financière Premium + Explication IA", elem_id="title")
322
- gr.Markdown("Posez une question sur un événement économique. L'IA analyse le sentiment et explique l'impact.", elem_classes=["subtitle"])
323
 
324
  count = gr.State(0)
325
  history = gr.State([])
326
 
327
- with gr.Row(elem_classes=["economic-question-section"]):
328
  with gr.Column(scale=2):
329
- with gr.Column():
330
- input_text = gr.Textbox(
331
- lines=4,
332
- label="Question Économique"
333
- )
334
- prompt_display = gr.Textbox(
335
- value="Une hausse des taux causerait-elle une récession ?",
336
- label="Exemple de Prompt",
337
- interactive=False,
338
- elem_classes=["prompt-box"]
339
- )
340
- with gr.Column(scale=1, elem_classes=["options-section"]):
341
- mode_selector = gr.Dropdown(
342
- choices=["Rapide", "Équilibré", "Précis"],
343
- value="Équilibré",
344
- label="Mode (longueur et style de réponse)"
345
- )
346
- detail_mode_selector = gr.Dropdown(
347
- choices=["Normal", "Expert"],
348
- value="Normal",
349
- label="Niveau de détail (simplicité ou technicité)"
350
- )
351
 
352
- with gr.Row():
353
- analyze_btn = gr.Button("Analyser")
354
- reset_graph_btn = gr.Button("Réinitialiser")
355
- download_btn = gr.Button("Télécharger CSV")
356
 
357
  with gr.Row():
358
- with gr.Column(scale=1):
359
- progress_message = gr.Textbox(label="Progression", elem_classes=["progress-message"], interactive=False)
360
- sentiment_output = gr.Textbox(label="Sentiment Prédictif")
361
- sentiment_gauge = gr.HTML(label="Jauge de Sentiment")
362
- with gr.Column(scale=2):
363
- with gr.Row():
364
- explanation_output_en = gr.Textbox(label="Explication en Anglais")
365
- explanation_output_fr = gr.Textbox(label="Explication en Français")
366
 
367
  download_file = gr.File(label="Fichier CSV")
368
 
@@ -371,7 +202,7 @@ def launch_app():
371
  analyze_btn.click(
372
  full_analysis,
373
  inputs=[input_text, mode_selector, detail_mode_selector, count, history],
374
- outputs=[sentiment_output, explanation_output_en, explanation_output_fr, count, history, sentiment_gauge, progress_message]
375
  )
376
 
377
  download_btn.click(
@@ -383,4 +214,4 @@ def launch_app():
383
  iface.launch(share=True)
384
 
385
  if __name__ == "__main__":
386
- launch_app()
 
6
  import os
7
  import nltk
8
  import asyncio
9
+ nltk.download('punkt') # CORRECT : 'punkt' !
10
+
11
  from nltk.tokenize import sent_tokenize
12
 
13
  HF_TOKEN = os.getenv("HF_TOKEN")
14
 
15
+ # Chargement modèles
16
+ translator_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
17
+ translator_to_fr = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr")
18
+ classifier = pipeline("sentiment-analysis", model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis")
19
+
20
+ # Fonction traduction segmentée
21
+ def safe_translate_to_fr(text, max_length=512):
22
+ sentences = sent_tokenize(text)
23
+ translated_sentences = []
24
+ for sentence in sentences:
25
+ translated = translator_to_fr(sentence, max_length=max_length)[0]['translation_text']
26
+ translated_sentences.append(translated)
27
+ return " ".join(translated_sentences)
28
+
29
+ # Appel API Zephyr
30
  async def call_zephyr_api(prompt, mode, hf_token=HF_TOKEN):
31
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)
32
  try:
 
36
  elif mode == "Équilibré":
37
  max_new_tokens = 100
38
  temperature = 0.5
39
+ else:
40
  max_new_tokens = 150
41
  temperature = 0.7
42
  response = await asyncio.to_thread(client.text_generation, prompt, max_new_tokens=max_new_tokens, temperature=temperature)
43
  return response
44
  except Exception as e:
45
+ raise gr.Error(f"❌ Erreur API Hugging Face : {str(e)}")
 
 
 
 
 
 
 
 
46
 
47
+ # Suggestion mode
 
 
 
 
48
  def suggest_model(text):
49
  word_count = len(text.split())
50
  if word_count < 50:
 
54
  else:
55
  return "Précis"
56
 
57
+ # Jauge sentiment
58
  def create_sentiment_gauge(sentiment, score):
59
  score_percentage = score * 100
60
+ color = "#A9A9A9"
61
+ if sentiment.lower() == "positive":
 
62
  color = "#2E8B57"
63
  elif sentiment.lower() == "negative":
64
  color = "#DC143C"
 
 
65
 
66
  html = f"""
67
  <div style='width: 100%; max-width: 300px; margin: 10px 0;'>
68
+ <div style='background-color: #D3D3D3; border-radius: 5px; height: 20px; position: relative;'>
69
+ <div style='background-color: {color}; width: {score_percentage}%; height: 100%; border-radius: 5px;'></div>
70
+ <span style='position: absolute; top: 0; left: 50%; transform: translateX(-50%); font-weight: bold;'>{score_percentage:.1f}%</span>
 
 
 
 
 
 
71
  </div>
72
+ <div style='text-align: center; margin-top: 5px;'>Sentiment : {sentiment}</div>
73
  </div>
74
  """
75
  return html
76
 
77
+ # Analyse principale
78
  async def full_analysis(text, mode, detail_mode, count, history):
79
  if not text:
80
+ yield "Entrez une phrase.", "", "", "", 0, history, "", "Aucune analyse effectuée."
81
  return
82
 
83
+ yield "Analyse en cours... (Étape 1 : Détection de la langue)", "", "", "", count, history, "", "Détection de la langue"
 
84
 
85
  try:
86
  lang = detect(text)
 
92
  else:
93
  text_en = text
94
 
95
+ yield "Analyse en cours... (Étape 2 : Analyse du sentiment)", "", "", "", count, history, "", "Analyse du sentiment"
96
 
 
97
  result = await asyncio.to_thread(classifier, text_en)
98
  result = result[0]
99
  sentiment_output = f"Sentiment prédictif : {result['label']} (Score: {result['score']:.2f})"
100
  sentiment_gauge = create_sentiment_gauge(result['label'], result['score'])
101
 
102
+ yield "Analyse en cours... (Étape 3 : Explication IA)", "", "", "", count, history, "", "Génération de l'explication"
103
 
 
104
  explanation_prompt = f"""<|system|>
105
  You are a professional financial analyst AI with expertise in economic forecasting.
106
  </s>
 
109
 
110
  The predicted sentiment for this event is: {result['label'].lower()}.
111
 
112
+ Assume the event happens. Explain why this event would likely have a {result['label'].lower()} economic impact.
113
  </s>
114
  <|assistant|>"""
115
  explanation_en = await call_zephyr_api(explanation_prompt, mode)
116
 
117
+ yield "Analyse en cours... (Étape 4 : Traduction en français)", "", "", "", count, history, "", "Traduction en français"
118
 
119
+ explanation_fr = safe_translate_to_fr(explanation_en)
 
120
 
121
  count += 1
122
  history.append({
 
127
  "Explication_FR": explanation_fr
128
  })
129
 
130
+ yield sentiment_output, text, explanation_en, explanation_fr, count, history, sentiment_gauge, "✅ Analyse terminée."
131
 
132
+ # Historique CSV
133
  def download_history(history):
134
  if not history:
135
  return None
 
138
  df.to_csv(file_path, index=False)
139
  return file_path
140
 
141
+ # Lancement Gradio
142
  def launch_app():
143
  custom_css = """
144
+ /* Ici tout ton CSS personnalisé pour style de fond, couleurs, boutons */
 
 
145
  body {
146
+ background: linear-gradient(135deg, #0A1D37 0%, #1A3C34 100%);
 
 
 
 
 
 
147
  font-family: 'Inter', sans-serif;
148
+ color: #E0E0E0;
149
  padding: 20px;
150
  }
 
151
  .gr-box {
152
+ background: #2A4A43 !important;
 
153
  border: 1px solid #FFD700 !important;
154
+ border-radius: 12px !important;
155
+ padding: 20px !important;
156
+ box-shadow: 0px 4px 12px rgba(255, 215, 0, 0.4);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  }
 
158
  .gr-button {
159
+ background: linear-gradient(90deg, #FFD700, #D4AF37);
160
+ color: #0A1D37;
161
+ font-weight: bold;
162
+ border: none;
163
+ border-radius: 8px;
164
+ padding: 12px 24px;
165
+ transition: transform 0.2s;
 
 
166
  }
 
167
  .gr-button:hover {
168
+ transform: translateY(-2px);
169
+ box-shadow: 0 6px 12px rgba(255, 215, 0, 0.5);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  }
171
  """
172
 
173
  with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface:
174
+ gr.Markdown("# 📈 Analyse Financière Premium avec IA")
175
+ gr.Markdown("**Posez une question économique.** L'IA analyse et explique l'impact.")
176
 
177
  count = gr.State(0)
178
  history = gr.State([])
179
 
180
+ with gr.Row():
181
  with gr.Column(scale=2):
182
+ input_text = gr.Textbox(lines=4, label="Votre question économique")
183
+ with gr.Column(scale=1):
184
+ mode_selector = gr.Dropdown(choices=["Rapide", "Équilibré", "Précis"], value="Équilibré", label="Mode de réponse")
185
+ detail_mode_selector = gr.Dropdown(choices=["Normal", "Expert"], value="Normal", label="Niveau de détail")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
+ analyze_btn = gr.Button("Analyser")
188
+ download_btn = gr.Button("Télécharger l'historique")
 
 
189
 
190
  with gr.Row():
191
+ sentiment_output = gr.Textbox(label="Sentiment prédictif")
192
+ displayed_prompt = gr.Textbox(label="Texte utilisé (anglais)", interactive=False)
193
+ explanation_output_en = gr.Textbox(label="Explication en anglais")
194
+ explanation_output_fr = gr.Textbox(label="Explication en français")
195
+ sentiment_gauge = gr.HTML()
196
+ progress_message = gr.Textbox(label="Progression", interactive=False)
 
 
197
 
198
  download_file = gr.File(label="Fichier CSV")
199
 
 
202
  analyze_btn.click(
203
  full_analysis,
204
  inputs=[input_text, mode_selector, detail_mode_selector, count, history],
205
+ outputs=[sentiment_output, displayed_prompt, explanation_output_en, explanation_output_fr, count, history, sentiment_gauge, progress_message]
206
  )
207
 
208
  download_btn.click(
 
214
  iface.launch(share=True)
215
 
216
  if __name__ == "__main__":
217
+ launch_app()