Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
from transformers import pipeline
|
4 |
+
from langdetect import detect
|
5 |
+
import pandas as pd
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
import os
|
8 |
+
|
9 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
10 |
+
|
11 |
+
# Fonction pour appeler l'API Zephyr
|
12 |
+
def call_zephyr_api(prompt, hf_token=HF_TOKEN):
|
13 |
+
API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
|
14 |
+
headers = {"Authorization": f"Bearer {hf_token}"}
|
15 |
+
payload = {"inputs": prompt, "parameters": {"max_new_tokens": 300}}
|
16 |
+
|
17 |
+
try:
|
18 |
+
response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
|
19 |
+
response.raise_for_status()
|
20 |
+
return response.json()[0]["generated_text"]
|
21 |
+
except Exception as e:
|
22 |
+
raise gr.Error(f"❌ Erreur d'appel API Hugging Face : {str(e)}")
|
23 |
+
|
24 |
+
# Chargement du modèle de sentiment
|
25 |
+
classifier = pipeline("sentiment-analysis", model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis")
|
26 |
+
|
27 |
+
# Modèles de traduction
|
28 |
+
translator_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
|
29 |
+
translator_to_fr = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr")
|
30 |
+
|
31 |
+
# Fonction pour suggérer le meilleur modèle
|
32 |
+
def suggest_model(text):
|
33 |
+
word_count = len(text.split())
|
34 |
+
if word_count < 50:
|
35 |
+
return "Rapide"
|
36 |
+
elif word_count <= 200:
|
37 |
+
return "Équilibré"
|
38 |
+
else:
|
39 |
+
return "Précis"
|
40 |
+
|
41 |
+
# Fonction d'analyse
|
42 |
+
def full_analysis(text, mode, detail_mode, count, history):
|
43 |
+
if not text:
|
44 |
+
return "Entrez une phrase.", "", "", 0, history, None
|
45 |
+
|
46 |
+
try:
|
47 |
+
lang = detect(text)
|
48 |
+
except:
|
49 |
+
lang = "unknown"
|
50 |
+
|
51 |
+
if lang != "en":
|
52 |
+
text = translator_to_en(text, max_length=512)[0]['translation_text']
|
53 |
+
|
54 |
+
result = classifier(text)[0]
|
55 |
+
sentiment_output = f"Sentiment : {result['label']} (Score: {result['score']:.2f})"
|
56 |
+
|
57 |
+
prompt = f"""
|
58 |
+
You are a professional financial analyst AI.
|
59 |
+
|
60 |
+
Analyze the following financial news carefully:
|
61 |
+
"{text}"
|
62 |
+
|
63 |
+
The detected sentiment for this news is: {result['label'].lower()}.
|
64 |
+
|
65 |
+
Now, explain why the sentiment is {result['label'].lower()} using a logical, fact-based explanation.
|
66 |
+
Base your reasoning only on the given news text.
|
67 |
+
Do not repeat the news text or the prompt.
|
68 |
+
Respond only with your financial analysis in one clear paragraph.
|
69 |
+
Write in a clear and professional tone.
|
70 |
+
"""
|
71 |
+
|
72 |
+
explanation_en = call_zephyr_api(prompt)
|
73 |
+
explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
|
74 |
+
|
75 |
+
count += 1
|
76 |
+
history.append({
|
77 |
+
"Texte": text,
|
78 |
+
"Sentiment": result['label'],
|
79 |
+
"Score": f"{result['score']:.2f}",
|
80 |
+
"Explication_EN": explanation_en,
|
81 |
+
"Explication_FR": explanation_fr
|
82 |
+
})
|
83 |
+
|
84 |
+
return sentiment_output, explanation_en, explanation_fr, count, history, None
|
85 |
+
|
86 |
+
# Fonction pour télécharger historique CSV
|
87 |
+
def download_history(history):
|
88 |
+
if not history:
|
89 |
+
return None
|
90 |
+
df = pd.DataFrame(history)
|
91 |
+
file_path = "/tmp/analysis_history.csv"
|
92 |
+
df.to_csv(file_path, index=False)
|
93 |
+
return file_path
|
94 |
+
|
95 |
+
# Interface Gradio
|
96 |
+
def launch_app():
|
97 |
+
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:
|
98 |
+
|
99 |
+
gr.Markdown("# 📈 Analyse Financière Premium + Explication IA", elem_id="title")
|
100 |
+
gr.Markdown("Entrez une actualité financière. L'IA analyse et explique en anglais/français. Choisissez votre mode d'explication.")
|
101 |
+
|
102 |
+
count = gr.State(0)
|
103 |
+
history = gr.State([])
|
104 |
+
|
105 |
+
with gr.Row():
|
106 |
+
input_text = gr.Textbox(lines=4, placeholder="Entrez une actualité ici...", label="Texte à analyser")
|
107 |
+
|
108 |
+
with gr.Row():
|
109 |
+
mode_selector = gr.Dropdown(
|
110 |
+
choices=["Rapide", "Équilibré", "Précis"],
|
111 |
+
value="Équilibré",
|
112 |
+
label="Mode recommandé selon la taille"
|
113 |
+
)
|
114 |
+
detail_mode_selector = gr.Dropdown(
|
115 |
+
choices=["Normal", "Expert"],
|
116 |
+
value="Normal",
|
117 |
+
label="Niveau de détail"
|
118 |
+
)
|
119 |
+
|
120 |
+
analyze_btn = gr.Button("Analyser")
|
121 |
+
reset_graph_btn = gr.Button("Reset Graphique")
|
122 |
+
download_btn = gr.Button("Télécharger CSV")
|
123 |
+
|
124 |
+
with gr.Row():
|
125 |
+
sentiment_output = gr.Textbox(label="Résultat du Sentiment")
|
126 |
+
|
127 |
+
with gr.Row():
|
128 |
+
with gr.Column():
|
129 |
+
explanation_output_en = gr.Textbox(label="Explication en Anglais")
|
130 |
+
with gr.Column():
|
131 |
+
explanation_output_fr = gr.Textbox(label="Explication en Français")
|
132 |
+
|
133 |
+
download_file = gr.File(label="Fichier CSV")
|
134 |
+
|
135 |
+
input_text.change(lambda t: gr.update(value=suggest_model(t)), inputs=[input_text], outputs=[mode_selector])
|
136 |
+
|
137 |
+
analyze_btn.click(
|
138 |
+
full_analysis,
|
139 |
+
inputs=[input_text, mode_selector, detail_mode_selector, count, history],
|
140 |
+
outputs=[sentiment_output, explanation_output_en, explanation_output_fr, count, history, None]
|
141 |
+
)
|
142 |
+
|
143 |
+
download_btn.click(
|
144 |
+
download_history,
|
145 |
+
inputs=[history],
|
146 |
+
outputs=[download_file]
|
147 |
+
)
|
148 |
+
|
149 |
+
iface.launch()
|
150 |
+
|
151 |
+
if __name__ == "__main__":
|
152 |
+
launch_app()
|