DinoFrog's picture
Update app.py
ffb571b verified
raw
history blame
4.77 kB
import gradio as gr
from transformers import pipeline
from langdetect import detect
import pandas as pd
import textstat
# Chargement du modèle de sentiment
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")
# Modèle explicatif CPU-friendly
explainer = pipeline("text2text-generation", model="facebook/blenderbot-1B-distill")
# 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 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']
result = classifier(text)[0]
sentiment_output = f"Sentiment : {result['label']} (Score: {result['score']:.2f})"
prompt = f"""
You are a financial analyst AI.
Based on the following financial news: \"{text}\",
explain clearly why the sentiment is {result['label'].lower()}.
{"Write a concise paragraph." if detail_mode == "Normal" else "Write a detailed explanation over multiple paragraphs."}
"""
explanation_en = explainer(prompt, max_length=300 if detail_mode == "Expert" else 150)[0]['generated_text']
explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
clarity_score = textstat.flesch_reading_ease(explanation_en)
count += 1
history.append({
"Texte": text,
"Sentiment": result['label'],
"Score": f"{result['score']:.2f}",
"Explication_EN": explanation_en,
"Explication_FR": explanation_fr,
"Clarté": f"{clarity_score:.1f}"
})
return sentiment_output, explanation_en, explanation_fr, clarity_score, count, history, None
# 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 actualité financière. L'IA analyse et explique en anglais/français. Choisissez votre mode d'explication.")
count = gr.State(0)
history = gr.State([])
with gr.Row():
input_text = gr.Textbox(lines=4, placeholder="Entrez une actualité ici...", label="Texte à analyser")
with gr.Row():
mode_selector = gr.Dropdown(
choices=["Rapide", "Équilibré", "Précis"],
value="Équilibré",
label="Mode recommandé selon la taille"
)
detail_mode_selector = gr.Dropdown(
choices=["Normal", "Expert"],
value="Normal",
label="Niveau de détail"
)
analyze_btn = gr.Button("Analyser")
download_btn = gr.Button("Télécharger CSV")
with gr.Row():
sentiment_output = gr.Textbox(label="Résultat du 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")
clarity_score_output = gr.Textbox(label="Score de Clarté (Flesch Reading Ease)")
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, clarity_score_output, count, history, download_file]
)
download_btn.click(
download_history,
inputs=[history],
outputs=[download_file]
)
iface.launch()
if __name__ == "__main__":
launch_app()