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