DinoFrog commited on
Commit
e6ea4ea
·
verified ·
1 Parent(s): 8397e5f

Update app.py

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