Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import pipeline | |
from langdetect import detect | |
from huggingface_hub import InferenceClient | |
import pandas as pd | |
import os | |
HF_TOKEN = os.getenv("HF_TOKEN") | |
# Fonction pour appeler l'API Zephyr avec des paramètres ajustés | |
def call_zephyr_api(prompt, mode, hf_token=HF_TOKEN): | |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hf_token) | |
try: | |
# Ajuster les paramètres en fonction du mode | |
if mode == "Rapide": | |
max_new_tokens = 100 # Réponse courte | |
temperature = 0.5 # Moins de créativité | |
elif mode == "Équilibré": | |
max_new_tokens = 200 # Réponse moyenne | |
temperature = 0.7 # Créativité modérée | |
else: # Précis | |
max_new_tokens = 300 # Réponse longue | |
temperature = 0.9 # Plus de créativité | |
response = 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 | |
translator_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en") | |
translator_to_fr = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr") | |
# 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 = "gray" | |
elif sentiment.lower() == "positive": | |
color = "green" | |
elif sentiment.lower() == "negative": | |
color = "red" | |
else: | |
color = "gray" | |
html = f""" | |
<div style='width: 100%; max-width: 300px; margin: 10px 0;'> | |
<div style='background-color: #e0e0e0; border-radius: 5px; height: 20px; position: relative;'> | |
<div style='background-color: {color}; width: {score_percentage}%; height: 100%; border-radius: 5px;'> | |
</div> | |
<span style='position: absolute; top: 0; left: 50%; transform: translateX(-50%); color: black; font-size: 12px; line-height: 20px;'> | |
{score_percentage:.1f}% | |
</span> | |
</div> | |
<div style='text-align: center; font-size: 14px; margin-top: 5px;'> | |
Sentiment: {sentiment} | |
</div> | |
</div> | |
""" | |
return html | |
# Fonction d'analyse | |
def full_analysis(text, mode, detail_mode, count, history): | |
if not text: | |
return "Entrez une phrase.", "", "", 0, history, None, "" | |
try: | |
lang = detect(text) | |
except: | |
lang = "unknown" | |
if lang != "en": | |
text = translator_to_en(text, max_length=512)[0]['translation_text'] | |
# Étape 1 : Poser une question à Zephyr pour prédire l'impact économique | |
prediction_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}" | |
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. | |
</s> | |
<|assistant|>""" | |
prediction_response = call_zephyr_api(prediction_prompt, mode) | |
# Étape 2 : Analyser le sentiment de la réponse de Zephyr | |
result = classifier(prediction_response)[0] | |
sentiment_output = f"Sentiment prédictif : {result['label']} (Score: {result['score']:.2f})" | |
sentiment_gauge = create_sentiment_gauge(result['label'], result['score']) | |
# Étape 3 : Générer une explication détaillée en fonction du niveau de détail | |
explanation_prompt = f"""<|system|> | |
You are a professional financial analyst AI. | |
</s> | |
<|user|> | |
Given the following question about a potential economic event: "{text}" | |
Based on your prediction of the economic impact, which is: "{prediction_response}" | |
The predicted sentiment for this impact is: {result['label'].lower()}. | |
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. {"Use simple language for a general audience." if detail_mode == "Normal" else "Use detailed financial terminology for an expert audience."} | |
</s> | |
<|assistant|>""" | |
explanation_en = call_zephyr_api(explanation_prompt, mode) | |
explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text'] | |
count += 1 | |
history.append({ | |
"Texte": text, | |
"Sentiment": result['label'], | |
"Score": f"{result['score']:.2f}", | |
"Explication_EN": explanation_en, | |
"Explication_FR": explanation_fr | |
}) | |
return 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 | |
def launch_app(): | |
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: | |
gr.Markdown("# 📈 Analyse Financière Premium + Explication IA", elem_id="title") | |
gr.Markdown("Entrez une question sur un événement économique. L'IA prédit l'impact et attribue un sentiment (positif, négatif, neutre).") | |
count = gr.State(0) | |
history = gr.State([]) | |
with gr.Row(): | |
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") | |
with gr.Row(): | |
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é)" | |
) | |
analyze_btn = gr.Button("Analyser") | |
reset_graph_btn = gr.Button("Reset Graphique") | |
download_btn = gr.Button("Télécharger CSV") | |
with gr.Row(): | |
sentiment_output = gr.Textbox(label="Résultat du Sentiment Prédictif") | |
sentiment_gauge = gr.HTML(label="Jauge de Sentiment") | |
with gr.Row(): | |
with gr.Column(): | |
explanation_output_en = gr.Textbox(label="Explication en Anglais") | |
with gr.Column(): | |
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] | |
) | |
download_btn.click( | |
download_history, | |
inputs=[history], | |
outputs=[download_file] | |
) | |
iface.launch() | |
if __name__ == "__main__": | |
launch_app() |