DinoFrog commited on
Commit
70f7370
·
verified ·
1 Parent(s): 15a1d6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -19
app.py CHANGED
@@ -16,7 +16,7 @@ def call_zephyr_api(prompt, hf_token=HF_TOKEN):
16
  except Exception as e:
17
  raise gr.Error(f"❌ Erreur d'appel API Hugging Face : {str(e)}")
18
 
19
- # Chargement du modèle de sentiment
20
  classifier = pipeline("sentiment-analysis", model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis")
21
 
22
  # Modèles de traduction
@@ -33,10 +33,38 @@ def suggest_model(text):
33
  else:
34
  return "Précis"
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  # Fonction d'analyse
37
  def full_analysis(text, mode, detail_mode, count, history):
38
  if not text:
39
- return "Entrez une phrase.", "", "", 0, history, None
40
 
41
  try:
42
  lang = detect(text)
@@ -46,26 +74,38 @@ def full_analysis(text, mode, detail_mode, count, history):
46
  if lang != "en":
47
  text = translator_to_en(text, max_length=512)[0]['translation_text']
48
 
49
- result = classifier(text)[0]
50
- sentiment_output = f"Sentiment : {result['label']} (Score: {result['score']:.2f})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- prompt = f"""<|system|>
 
53
  You are a professional financial analyst AI.
54
  </s>
55
  <|user|>
56
- Analyze the following financial news carefully:
57
- "{text}"
58
 
59
- The detected sentiment for this news is: {result['label'].lower()}.
60
 
61
- Now, explain why the sentiment is {result['label'].lower()} using a logical, fact-based explanation.
62
- Base your reasoning only on the given news text.
63
- Do not repeat the news text or the prompt.
64
- Respond only with your financial analysis in one clear paragraph.
65
- Write in a clear and professional tone.
66
  </s>
67
  <|assistant|>"""
68
- explanation_en = call_zephyr_api(prompt)
69
  explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
70
 
71
  count += 1
@@ -77,7 +117,7 @@ Write in a clear and professional tone.
77
  "Explication_FR": explanation_fr
78
  })
79
 
80
- return sentiment_output, explanation_en, explanation_fr, count, history
81
 
82
  # Fonction pour télécharger historique CSV
83
  def download_history(history):
@@ -92,13 +132,13 @@ def download_history(history):
92
  def launch_app():
93
  with gr.Blocks(theme=gr.themes.Base(), css="body {background-color: #0D1117; color: white;} .gr-button {background-color: #161B22; border: 1px solid #30363D;}") as iface:
94
  gr.Markdown("# 📈 Analyse Financière Premium + Explication IA", elem_id="title")
95
- gr.Markdown("Entrez une actualité financière. L'IA analyse et explique en anglais/français. Choisissez votre mode d'explication.")
96
 
97
  count = gr.State(0)
98
  history = gr.State([])
99
 
100
  with gr.Row():
101
- input_text = gr.Textbox(lines=4, placeholder="Entrez une actualité ici...", label="Texte à analyser")
102
 
103
  with gr.Row():
104
  mode_selector = gr.Dropdown(
@@ -117,7 +157,9 @@ def launch_app():
117
  download_btn = gr.Button("Télécharger CSV")
118
 
119
  with gr.Row():
120
- sentiment_output = gr.Textbox(label="Résultat du Sentiment")
 
 
121
 
122
  with gr.Row():
123
  with gr.Column():
@@ -132,7 +174,7 @@ def launch_app():
132
  analyze_btn.click(
133
  full_analysis,
134
  inputs=[input_text, mode_selector, detail_mode_selector, count, history],
135
- outputs=[sentiment_output, explanation_output_en, explanation_output_fr, count, history]
136
  )
137
 
138
  download_btn.click(
 
16
  except Exception as e:
17
  raise gr.Error(f"❌ Erreur d'appel API Hugging Face : {str(e)}")
18
 
19
+ # Chargement du modèle de sentiment pour analyser les réponses
20
  classifier = pipeline("sentiment-analysis", model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis")
21
 
22
  # Modèles de traduction
 
33
  else:
34
  return "Précis"
35
 
36
+ # Fonction pour créer une jauge de sentiment
37
+ def create_sentiment_gauge(sentiment, score):
38
+ score_percentage = score * 100
39
+ if sentiment.lower() == "neutral":
40
+ color = "gray"
41
+ elif sentiment.lower() == "positive":
42
+ color = "green"
43
+ elif sentiment.lower() == "negative":
44
+ color = "red"
45
+ else:
46
+ color = "gray"
47
+
48
+ html = f"""
49
+ <div style='width: 100%; max-width: 300px; margin: 10px 0;'>
50
+ <div style='background-color: #e0e0e0; border-radius: 5px; height: 20px; position: relative;'>
51
+ <div style='background-color: {color}; width: {score_percentage}%; height: 100%; border-radius: 5px;'>
52
+ </div>
53
+ <span style='position: absolute; top: 0; left: 50%; transform: translateX(-50%); color: black; font-size: 12px; line-height: 20px;'>
54
+ {score_percentage:.1f}%
55
+ </span>
56
+ </div>
57
+ <div style='text-align: center; font-size: 14px; margin-top: 5px;'>
58
+ Sentiment: {sentiment}
59
+ </div>
60
+ </div>
61
+ """
62
+ return html
63
+
64
  # Fonction d'analyse
65
  def full_analysis(text, mode, detail_mode, count, history):
66
  if not text:
67
+ return "Entrez une phrase.", "", "", 0, history, None, ""
68
 
69
  try:
70
  lang = detect(text)
 
74
  if lang != "en":
75
  text = translator_to_en(text, max_length=512)[0]['translation_text']
76
 
77
+ # Étape 1 : Poser une question à Zephyr pour prédire l'impact économique
78
+ prediction_prompt = f"""<|system|>
79
+ You are a professional financial analyst AI with expertise in economic forecasting.
80
+ </s>
81
+ <|user|>
82
+ Given the following question about a potential economic event: "{text}"
83
+
84
+ Assume the event happens (e.g., if the question is "Will the Federal Reserve raise interest rates?", assume they do raise rates). What would be the likely economic impact of this event? Provide a concise explanation in one paragraph, focusing on the potential positive or negative effects on the economy. Do not repeat the question or the prompt in your response.
85
+ </s>
86
+ <|assistant|>"""
87
+ prediction_response = call_zephyr_api(prediction_prompt)
88
+
89
+ # Étape 2 : Analyser le sentiment de la réponse de Zephyr
90
+ result = classifier(prediction_response)[0]
91
+ sentiment_output = f"Sentiment prédictif : {result['label']} (Score: {result['score']:.2f})"
92
+ sentiment_gauge = create_sentiment_gauge(result['label'], result['score'])
93
 
94
+ # Étape 3 : Générer une explication détaillée
95
+ explanation_prompt = f"""<|system|>
96
  You are a professional financial analyst AI.
97
  </s>
98
  <|user|>
99
+ Given the following question about a potential economic event: "{text}"
 
100
 
101
+ Based on your prediction of the economic impact, which is: "{prediction_response}"
102
 
103
+ The predicted sentiment for this impact is: {result['label'].lower()}.
104
+
105
+ Now, explain why the sentiment is {result['label'].lower()} using a logical, fact-based explanation. Base your reasoning only on the predicted economic impact. Respond only with your financial analysis in one clear paragraph. Write in a clear and professional tone.
 
 
106
  </s>
107
  <|assistant|>"""
108
+ explanation_en = call_zephyr_api(explanation_prompt)
109
  explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
110
 
111
  count += 1
 
117
  "Explication_FR": explanation_fr
118
  })
119
 
120
+ return sentiment_output, explanation_en, explanation_fr, count, history, sentiment_gauge
121
 
122
  # Fonction pour télécharger historique CSV
123
  def download_history(history):
 
132
  def launch_app():
133
  with gr.Blocks(theme=gr.themes.Base(), css="body {background-color: #0D1117; color: white;} .gr-button {background-color: #161B22; border: 1px solid #30363D;}") as iface:
134
  gr.Markdown("# 📈 Analyse Financière Premium + Explication IA", elem_id="title")
135
+ gr.Markdown("Entrez une question sur un événement économique. L'IA prédit l'impact et attribue un sentiment (positif, négatif, neutre).")
136
 
137
  count = gr.State(0)
138
  history = gr.State([])
139
 
140
  with gr.Row():
141
+ input_text = gr.Textbox(lines=4, placeholder="Entrez une question ici (ex. 'La Réserve fédérale augmentera-t-elle ses taux d'intérêt avant 2025 ?')", label="Question économique")
142
 
143
  with gr.Row():
144
  mode_selector = gr.Dropdown(
 
157
  download_btn = gr.Button("Télécharger CSV")
158
 
159
  with gr.Row():
160
+ sentiment_output = gr.Textbox(label="Résultat du Sentiment Prédictif")
161
+
162
+ sentiment_gauge = gr.HTML(label="Jauge de Sentiment")
163
 
164
  with gr.Row():
165
  with gr.Column():
 
174
  analyze_btn.click(
175
  full_analysis,
176
  inputs=[input_text, mode_selector, detail_mode_selector, count, history],
177
+ outputs=[sentiment_output, explanation_output_en, explanation_output_fr, count, history, sentiment_gauge]
178
  )
179
 
180
  download_btn.click(