Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,116 +1,174 @@
|
|
1 |
import gradio as gr
|
2 |
import requests
|
|
|
|
|
3 |
import pandas as pd
|
4 |
import textstat
|
|
|
5 |
import os
|
6 |
|
7 |
-
# Récupération du token Hugging Face
|
8 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
9 |
|
10 |
-
|
|
|
11 |
def call_zephyr_api(prompt, hf_token=HF_TOKEN):
|
12 |
API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
|
13 |
headers = {"Authorization": f"Bearer {hf_token}"}
|
14 |
-
payload = {"inputs": prompt}
|
15 |
-
|
16 |
try:
|
17 |
response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
|
18 |
response.raise_for_status()
|
19 |
-
return response.json()[0]["generated_text"]
|
20 |
except Exception as e:
|
21 |
raise gr.Error(f"❌ Erreur d'appel API Hugging Face : {str(e)}")
|
22 |
|
23 |
-
# Fonction principale d'analyse
|
24 |
-
def full_analysis(text, history):
|
25 |
-
if not text:
|
26 |
-
return "Entrez une phrase.", "", 0, history, 0
|
27 |
-
|
28 |
-
# 1. Demander à Zephyr de détecter le sentiment
|
29 |
-
prompt_sentiment = f"""
|
30 |
-
You are a financial news sentiment detector.
|
31 |
-
|
32 |
-
Given the following news text:
|
33 |
-
\"{text}\"
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
-
|
42 |
-
|
|
|
|
|
43 |
|
44 |
-
|
45 |
-
|
46 |
-
You are a financial analyst AI.
|
47 |
|
48 |
-
|
49 |
-
|
50 |
|
51 |
-
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
-
|
54 |
-
|
55 |
-
"""
|
56 |
-
explanation = call_zephyr_api(prompt_explanation)
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
clarity_score = max(0, min(clarity_score, 100)) # Limité entre 0-100
|
61 |
|
62 |
-
|
63 |
history.append({
|
64 |
"Texte": text,
|
65 |
-
"Sentiment":
|
66 |
-
"
|
67 |
-
"
|
|
|
|
|
68 |
})
|
69 |
|
70 |
-
return
|
71 |
|
72 |
-
# Fonction pour télécharger
|
73 |
def download_history(history):
|
74 |
if not history:
|
75 |
return None
|
76 |
df = pd.DataFrame(history)
|
77 |
-
file_path = "/tmp/
|
78 |
df.to_csv(file_path, index=False)
|
79 |
return file_path
|
80 |
|
81 |
-
# Gradio
|
82 |
def launch_app():
|
83 |
-
with gr.Blocks() as iface:
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
with gr.Row():
|
87 |
-
input_text = gr.Textbox(
|
88 |
|
89 |
with gr.Row():
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
-
|
94 |
-
|
95 |
-
clarity_score_text = gr.Textbox(label="Score de Clarté (%)")
|
96 |
-
clarity_slider = gr.Slider(0, 100, label="Clarté (%)", interactive=False)
|
97 |
-
file_output = gr.File(label="Fichier CSV")
|
98 |
|
99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
|
101 |
analyze_btn.click(
|
102 |
full_analysis,
|
103 |
-
inputs=[input_text, history],
|
104 |
-
outputs=[sentiment_output,
|
|
|
|
|
|
|
|
|
|
|
105 |
)
|
106 |
|
107 |
download_btn.click(
|
108 |
download_history,
|
109 |
inputs=[history],
|
110 |
-
outputs=[
|
111 |
)
|
112 |
|
113 |
iface.launch()
|
114 |
|
115 |
if __name__ == "__main__":
|
116 |
-
launch_app()
|
|
|
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 textstat
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
import os
|
9 |
|
|
|
10 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
11 |
|
12 |
+
|
13 |
+
# Fonction pour appeler l'API Zephyr
|
14 |
def call_zephyr_api(prompt, hf_token=HF_TOKEN):
|
15 |
API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
|
16 |
headers = {"Authorization": f"Bearer {hf_token}"}
|
17 |
+
payload = {"inputs": prompt, "parameters": {"max_new_tokens": 300}}
|
18 |
+
|
19 |
try:
|
20 |
response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
|
21 |
response.raise_for_status()
|
22 |
+
return response.json()[0]["generated_text"]
|
23 |
except Exception as e:
|
24 |
raise gr.Error(f"❌ Erreur d'appel API Hugging Face : {str(e)}")
|
25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
+
# Chargement du modèle de sentiment
|
28 |
+
classifier = pipeline("sentiment-analysis", model="mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis")
|
29 |
+
|
30 |
+
# Modèles de traduction
|
31 |
+
translator_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en")
|
32 |
+
translator_to_fr = pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr")
|
33 |
+
|
34 |
+
# Fonction pour suggérer le meilleur modèle
|
35 |
+
def suggest_model(text):
|
36 |
+
word_count = len(text.split())
|
37 |
+
if word_count < 50:
|
38 |
+
return "Rapide"
|
39 |
+
elif word_count <= 200:
|
40 |
+
return "Équilibré"
|
41 |
+
else:
|
42 |
+
return "Précis"
|
43 |
+
|
44 |
+
# Fonction pour générer un graphique de clarté
|
45 |
+
def plot_clarity(clarity_scores):
|
46 |
+
plt.figure(figsize=(8, 4))
|
47 |
+
plt.plot(range(1, len(clarity_scores) + 1), clarity_scores, marker='o')
|
48 |
+
plt.title("Évolution du Score de Clarté")
|
49 |
+
plt.xlabel("Numéro d'analyse")
|
50 |
+
plt.ylabel("Score de Clarté")
|
51 |
+
plt.ylim(0, 100)
|
52 |
+
plt.grid(True)
|
53 |
+
return plt.gcf()
|
54 |
+
|
55 |
+
# Fonction pour reset le graphique
|
56 |
+
def reset_clarity_graph():
|
57 |
+
return [], plot_clarity([])
|
58 |
+
|
59 |
+
# Fonction d'analyse
|
60 |
+
def full_analysis(text, mode, detail_mode, count, history, clarity_scores):
|
61 |
+
if not text:
|
62 |
+
return "Entrez une phrase.", "", "", 0, history, clarity_scores, None, None
|
63 |
|
64 |
+
try:
|
65 |
+
lang = detect(text)
|
66 |
+
except:
|
67 |
+
lang = "unknown"
|
68 |
|
69 |
+
if lang != "en":
|
70 |
+
text = translator_to_en(text, max_length=512)[0]['translation_text']
|
|
|
71 |
|
72 |
+
result = classifier(text)[0]
|
73 |
+
sentiment_output = f"Sentiment : {result['label']} (Score: {result['score']:.2f})"
|
74 |
|
75 |
+
prompt = f"""
|
76 |
+
You are a financial analyst AI.
|
77 |
+
Based on the following financial news: \"{text}\",
|
78 |
+
explain clearly why the sentiment is {result['label'].lower()}.
|
79 |
+
{"Write a concise paragraph." if detail_mode == "Normal" else "Write a detailed explanation over multiple paragraphs."}
|
80 |
+
"""
|
81 |
|
82 |
+
explanation_en = call_zephyr_api(prompt)
|
83 |
+
explanation_fr = translator_to_fr(explanation_en, max_length=512)[0]['translation_text']
|
|
|
|
|
84 |
|
85 |
+
clarity_score = textstat.flesch_reading_ease(explanation_en)
|
86 |
+
clarity_scores.append(clarity_score)
|
|
|
87 |
|
88 |
+
count += 1
|
89 |
history.append({
|
90 |
"Texte": text,
|
91 |
+
"Sentiment": result['label'],
|
92 |
+
"Score": f"{result['score']:.2f}",
|
93 |
+
"Explication_EN": explanation_en,
|
94 |
+
"Explication_FR": explanation_fr,
|
95 |
+
"Clarté": f"{clarity_score:.1f}"
|
96 |
})
|
97 |
|
98 |
+
return sentiment_output, explanation_en, explanation_fr, clarity_score, count, history, clarity_scores, plot_clarity(clarity_scores)
|
99 |
|
100 |
+
# Fonction pour télécharger historique CSV
|
101 |
def download_history(history):
|
102 |
if not history:
|
103 |
return None
|
104 |
df = pd.DataFrame(history)
|
105 |
+
file_path = "/tmp/analysis_history.csv"
|
106 |
df.to_csv(file_path, index=False)
|
107 |
return file_path
|
108 |
|
109 |
+
# Interface Gradio
|
110 |
def launch_app():
|
111 |
+
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:
|
112 |
+
|
113 |
+
gr.Markdown("# 📈 Analyse Financière Premium + Explication IA", elem_id="title")
|
114 |
+
gr.Markdown("Entrez une actualité financière. L'IA analyse et explique en anglais/français. Choisissez votre mode d'explication.")
|
115 |
+
|
116 |
+
count = gr.State(0)
|
117 |
+
history = gr.State([])
|
118 |
+
clarity_scores = gr.State([])
|
119 |
|
120 |
with gr.Row():
|
121 |
+
input_text = gr.Textbox(lines=4, placeholder="Entrez une actualité ici...", label="Texte à analyser")
|
122 |
|
123 |
with gr.Row():
|
124 |
+
mode_selector = gr.Dropdown(
|
125 |
+
choices=["Rapide", "Équilibré", "Précis"],
|
126 |
+
value="Équilibré",
|
127 |
+
label="Mode recommandé selon la taille"
|
128 |
+
)
|
129 |
+
detail_mode_selector = gr.Dropdown(
|
130 |
+
choices=["Normal", "Expert"],
|
131 |
+
value="Normal",
|
132 |
+
label="Niveau de détail"
|
133 |
+
)
|
134 |
+
|
135 |
+
analyze_btn = gr.Button("Analyser")
|
136 |
+
reset_graph_btn = gr.Button("Reset Graphique")
|
137 |
+
download_btn = gr.Button("Télécharger CSV")
|
138 |
|
139 |
+
with gr.Row():
|
140 |
+
sentiment_output = gr.Textbox(label="Résultat du Sentiment")
|
|
|
|
|
|
|
141 |
|
142 |
+
with gr.Row():
|
143 |
+
with gr.Column():
|
144 |
+
explanation_output_en = gr.Textbox(label="Explication en Anglais")
|
145 |
+
with gr.Column():
|
146 |
+
explanation_output_fr = gr.Textbox(label="Explication en Français")
|
147 |
+
|
148 |
+
clarity_score_output = gr.Textbox(label="Score de Clarté (Flesch Reading Ease)")
|
149 |
+
clarity_plot = gr.Plot(label="Graphique des Scores de Clarté")
|
150 |
+
download_file = gr.File(label="Fichier CSV")
|
151 |
+
|
152 |
+
input_text.change(lambda t: gr.update(value=suggest_model(t)), inputs=[input_text], outputs=[mode_selector])
|
153 |
|
154 |
analyze_btn.click(
|
155 |
full_analysis,
|
156 |
+
inputs=[input_text, mode_selector, detail_mode_selector, count, history, clarity_scores],
|
157 |
+
outputs=[sentiment_output, explanation_output_en, explanation_output_fr, clarity_score_output, count, history, clarity_scores, clarity_plot]
|
158 |
+
)
|
159 |
+
|
160 |
+
reset_graph_btn.click(
|
161 |
+
reset_clarity_graph,
|
162 |
+
outputs=[clarity_scores, clarity_plot]
|
163 |
)
|
164 |
|
165 |
download_btn.click(
|
166 |
download_history,
|
167 |
inputs=[history],
|
168 |
+
outputs=[download_file]
|
169 |
)
|
170 |
|
171 |
iface.launch()
|
172 |
|
173 |
if __name__ == "__main__":
|
174 |
+
launch_app()
|