DinoFrog commited on
Commit
38d62de
·
verified ·
1 Parent(s): aa38f56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -39
app.py CHANGED
@@ -4,6 +4,9 @@ from langdetect import detect
4
  from huggingface_hub import InferenceClient
5
  import pandas as pd
6
  import os
 
 
 
7
 
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
 
@@ -11,16 +14,15 @@ HF_TOKEN = os.getenv("HF_TOKEN")
11
  def call_zephyr_api(prompt, mode, hf_token=HF_TOKEN):
12
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)
13
  try:
14
- # Ajuster les paramètres en fonction du mode
15
  if mode == "Rapide":
16
- max_new_tokens = 100 # Réponse courte
17
- temperature = 0.5 # Moins de créativité
18
  elif mode == "Équilibré":
19
- max_new_tokens = 200 # Réponse moyenne
20
- temperature = 0.7 # Créativité modérée
21
  else: # Précis
22
- max_new_tokens = 300 # Réponse longue
23
- temperature = 0.9 # Plus de créativité
24
  response = client.text_generation(prompt, max_new_tokens=max_new_tokens, temperature=temperature)
25
  return response
26
  except Exception as e:
@@ -33,6 +35,20 @@ classifier = pipeline("sentiment-analysis", model="mrm8488/distilroberta-finetun
33
  translator_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
34
  translator_to_fr = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr")
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  # Fonction pour suggérer le meilleur modèle
37
  def suggest_model(text):
38
  word_count = len(text.split())
@@ -57,14 +73,14 @@ def create_sentiment_gauge(sentiment, score):
57
 
58
  html = f"""
59
  <div style='width: 100%; max-width: 300px; margin: 10px 0;'>
60
- <div style='background-color: #e0e0e0; border-radius: 5px; height: 20px; position: relative;'>
61
- <div style='background-color: {color}; width: {score_percentage}%; height: 100%; border-radius: 5px;'>
62
  </div>
63
- <span style='position: absolute; top: 0; left: 50%; transform: translateX(-50%); color: black; font-size: 12px; line-height: 20px;'>
64
  {score_percentage:.1f}%
65
  </span>
66
  </div>
67
- <div style='text-align: center; font-size: 14px; margin-top: 5px;'>
68
  Sentiment: {sentiment}
69
  </div>
70
  </div>
@@ -116,7 +132,7 @@ Now, explain why the sentiment is {result['label'].lower()} using a logical, fac
116
  </s>
117
  <|assistant|>"""
118
  explanation_en = call_zephyr_api(explanation_prompt, mode)
119
- explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
120
 
121
  count += 1
122
  history.append({
@@ -138,44 +154,134 @@ def download_history(history):
138
  df.to_csv(file_path, index=False)
139
  return file_path
140
 
141
- # Interface Gradio
142
  def launch_app():
143
- 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:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  gr.Markdown("# 📈 Analyse Financière Premium + Explication IA", elem_id="title")
145
- gr.Markdown("Entrez une question sur un événement économique. L'IA prédit l'impact et attribue un sentiment (positif, négatif, neutre).")
146
 
147
  count = gr.State(0)
148
  history = gr.State([])
149
 
150
  with gr.Row():
151
- 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")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  with gr.Row():
154
- mode_selector = gr.Dropdown(
155
- choices=["Rapide", "Équilibré", "Précis"],
156
- value="Équilibré",
157
- label="Mode (longueur et style de réponse)"
158
- )
159
- detail_mode_selector = gr.Dropdown(
160
- choices=["Normal", "Expert"],
161
- value="Normal",
162
- label="Niveau de détail (simplicité ou technicité)"
163
- )
164
-
165
- analyze_btn = gr.Button("Analyser")
166
- reset_graph_btn = gr.Button("Reset Graphique")
167
- download_btn = gr.Button("Télécharger CSV")
168
-
169
- with gr.Row():
170
- sentiment_output = gr.Textbox(label="Résultat du Sentiment Prédictif")
171
-
172
- sentiment_gauge = gr.HTML(label="Jauge de Sentiment")
173
 
174
  with gr.Row():
175
- with gr.Column():
176
- explanation_output_en = gr.Textbox(label="Explication en Anglais")
177
- with gr.Column():
178
- explanation_output_fr = gr.Textbox(label="Explication en Français")
 
 
 
179
 
180
  download_file = gr.File(label="Fichier CSV")
181
 
 
4
  from huggingface_hub import InferenceClient
5
  import pandas as pd
6
  import os
7
+ import nltk
8
+ nltk.download('punkt')
9
+ from nltk.tokenize import sent_tokenize
10
 
11
  HF_TOKEN = os.getenv("HF_TOKEN")
12
 
 
14
  def call_zephyr_api(prompt, mode, hf_token=HF_TOKEN):
15
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token)
16
  try:
 
17
  if mode == "Rapide":
18
+ max_new_tokens = 100
19
+ temperature = 0.5
20
  elif mode == "Équilibré":
21
+ max_new_tokens = 200
22
+ temperature = 0.7
23
  else: # Précis
24
+ max_new_tokens = 300
25
+ temperature = 0.9
26
  response = client.text_generation(prompt, max_new_tokens=max_new_tokens, temperature=temperature)
27
  return response
28
  except Exception as e:
 
35
  translator_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
36
  translator_to_fr = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr")
37
 
38
+ # Fonction pour traduire un texte long en le segmentant
39
+ def safe_translate_to_fr(text, max_length=512):
40
+ # Segmenter le texte en phrases
41
+ sentences = sent_tokenize(text)
42
+ translated_sentences = []
43
+
44
+ for sentence in sentences:
45
+ # Traduire chaque phrase individuellement
46
+ translated = translator_to_fr(sentence, max_length=max_length)[0]['translation_text']
47
+ translated_sentences.append(translated)
48
+
49
+ # Recombiner les phrases traduites
50
+ return " ".join(translated_sentences)
51
+
52
  # Fonction pour suggérer le meilleur modèle
53
  def suggest_model(text):
54
  word_count = len(text.split())
 
73
 
74
  html = f"""
75
  <div style='width: 100%; max-width: 300px; margin: 10px 0;'>
76
+ <div style='background-color: #e0e0e0; border-radius: 5px; height: 20px; position: relative; box-shadow: 0 2px 4px rgba(0,0,0,0.2);'>
77
+ <div style='background-color: {color}; width: {score_percentage}%; height: 100%; border-radius: 5px; transition: width 0.3s ease-in-out;'>
78
  </div>
79
+ <span style='position: absolute; top: 0; left: 50%; transform: translateX(-50%); color: black; font-size: 12px; line-height: 20px; font-weight: 600;'>
80
  {score_percentage:.1f}%
81
  </span>
82
  </div>
83
+ <div style='text-align: center; font-size: 14px; margin-top: 5px; color: #E0E0E0;'>
84
  Sentiment: {sentiment}
85
  </div>
86
  </div>
 
132
  </s>
133
  <|assistant|>"""
134
  explanation_en = call_zephyr_api(explanation_prompt, mode)
135
+ explanation_fr = safe_translate_to_fr(explanation_en, max_length=512)
136
 
137
  count += 1
138
  history.append({
 
154
  df.to_csv(file_path, index=False)
155
  return file_path
156
 
157
+ # Interface Gradio améliorée
158
  def launch_app():
159
+ custom_css = """
160
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
161
+
162
+ body {
163
+ background: linear-gradient(135deg, #1A1A2E 0%, #16213E 100%);
164
+ color: #E0E0E0;
165
+ font-family: 'Inter', sans-serif;
166
+ }
167
+
168
+ .gr-box {
169
+ background: #2A2A4A !important;
170
+ border-radius: 12px !important;
171
+ border: 1px solid #3A3A5A !important;
172
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
173
+ padding: 20px !important;
174
+ margin: 10px 0 !important;
175
+ }
176
+
177
+ .gr-textbox, .gr-dropdown {
178
+ background: #3A3A5A !important;
179
+ border: 1px solid #4A4A7A !important;
180
+ border-radius: 8px !important;
181
+ color: #E0E0E0 !important;
182
+ font-size: 16px !important;
183
+ padding: 12px !important;
184
+ transition: border-color 0.3s ease, box-shadow 0.3s ease !important;
185
+ }
186
+
187
+ .gr-textbox:focus, .gr-dropdown:focus {
188
+ border-color: #FFD700 !important;
189
+ box-shadow: 0 0 8px rgba(255, 215, 0, 0.3) !important;
190
+ }
191
+
192
+ .gr-button {
193
+ background: linear-gradient(90deg, #FFD700 0%, #D4AF37 100%) !important;
194
+ color: #1A1A2E !important;
195
+ border: none !important;
196
+ border-radius: 8px !important;
197
+ padding: 12px 24px !important;
198
+ font-weight: 600 !important;
199
+ font-size: 16px !important;
200
+ transition: transform 0.1s ease, box-shadow 0.3s ease !important;
201
+ box-shadow: 0 2px 8px rgba(255, 215, 0, 0.2) !important;
202
+ }
203
+
204
+ .gr-button:hover {
205
+ transform: translateY(-2px) !important;
206
+ box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4) !important;
207
+ }
208
+
209
+ h1, h2, h3 {
210
+ color: #FFD700 !important;
211
+ font-weight: 700 !important;
212
+ text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2) !important;
213
+ }
214
+
215
+ .gr-row {
216
+ margin: 15px 0 !important;
217
+ }
218
+
219
+ .gr-column {
220
+ padding: 10px !important;
221
+ }
222
+
223
+ label {
224
+ color: #FFD700 !important;
225
+ font-weight: 600 !important;
226
+ font-size: 16px !important;
227
+ margin-bottom: 8px !important;
228
+ display: flex !important;
229
+ align-items: center !important;
230
+ }
231
+
232
+ label::before {
233
+ content: '📊 ';
234
+ margin-right: 8px;
235
+ }
236
+
237
+ .gr-html label::before {
238
+ content: '📈 ';
239
+ }
240
+
241
+ .gr-file label::before {
242
+ content: '💾 ';
243
+ }
244
+ """
245
+
246
+ with gr.Blocks(theme=gr.themes.Base(), css=custom_css) as iface:
247
  gr.Markdown("# 📈 Analyse Financière Premium + Explication IA", elem_id="title")
248
+ gr.Markdown("Posez une question sur un événement économique. L'IA prédit l'impact et attribue un sentiment (positif, négatif, neutre).", elem_classes=["subtitle"])
249
 
250
  count = gr.State(0)
251
  history = gr.State([])
252
 
253
  with gr.Row():
254
+ with gr.Column(scale=2):
255
+ input_text = gr.Textbox(
256
+ lines=4,
257
+ placeholder="Entrez une question ici (ex. 'La Réserve fédérale augmentera-t-elle ses taux d'intérêt avant 2025 ?')",
258
+ label="Question Économique"
259
+ )
260
+ with gr.Column(scale=1):
261
+ mode_selector = gr.Dropdown(
262
+ choices=["Rapide", "Équilibré", "Précis"],
263
+ value="Équilibré",
264
+ label="Mode (longueur et style de réponse)"
265
+ )
266
+ detail_mode_selector = gr.Dropdown(
267
+ choices=["Normal", "Expert"],
268
+ value="Normal",
269
+ label="Niveau de détail (simplicité ou technicité)"
270
+ )
271
 
272
  with gr.Row():
273
+ analyze_btn = gr.Button("Analyser")
274
+ reset_graph_btn = gr.Button("Réinitialiser")
275
+ download_btn = gr.Button("Télécharger CSV")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
 
277
  with gr.Row():
278
+ with gr.Column(scale=1):
279
+ sentiment_output = gr.Textbox(label="Résultat du Sentiment Prédictif")
280
+ sentiment_gauge = gr.HTML(label="Jauge de Sentiment")
281
+ with gr.Column(scale=2):
282
+ with gr.Row():
283
+ explanation_output_en = gr.Textbox(label="Explication en Anglais")
284
+ explanation_output_fr = gr.Textbox(label="Explication en Français")
285
 
286
  download_file = gr.File(label="Fichier CSV")
287