DinoFrog's picture
Update app.py
78d147f verified
raw
history blame
13.6 kB
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()