DinoFrog's picture
Update app.py
a62a318 verified
raw
history blame
3.57 kB
import gradio as gr
import requests
import pandas as pd
import textstat
import os
# Récupération du token Hugging Face
HF_TOKEN = os.getenv("HF_TOKEN")
# Fonction pour appeler l'API Zephyr-7B
def call_zephyr_api(prompt, hf_token=HF_TOKEN):
API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
headers = {"Authorization": f"Bearer {hf_token}"}
payload = {"inputs": prompt}
try:
response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
response.raise_for_status()
return response.json()[0]["generated_text"].strip()
except Exception as e:
raise gr.Error(f"❌ Erreur d'appel API Hugging Face : {str(e)}")
# Fonction principale d'analyse
def full_analysis(text, history):
if not text:
return "Entrez une phrase.", "", 0, history, 0
# 1. Demander à Zephyr de détecter le sentiment
prompt_sentiment = f"""
You are a financial news sentiment detector.
Given the following news text:
\"{text}\"
Respond only with one word: positive, neutral, or negative.
Do not add any explanation or extra text.
"""
detected_sentiment = call_zephyr_api(prompt_sentiment).lower()
if detected_sentiment not in ["positive", "neutral", "negative"]:
detected_sentiment = "neutral"
# 2. Demander à Zephyr d'expliquer
prompt_explanation = f"""
You are a financial analyst AI.
Given the following financial news:
\"{text}\"
The detected sentiment is: {detected_sentiment}.
Now explain clearly why the sentiment is {detected_sentiment}.
Write a concise paragraph.
"""
explanation = call_zephyr_api(prompt_explanation)
# 3. Calculer la clarté
clarity_score = textstat.flesch_reading_ease(explanation)
clarity_score = max(0, min(clarity_score, 100)) # Limité entre 0-100
# 4. Sauvegarder dans l'historique
history.append({
"Texte": text,
"Sentiment": detected_sentiment.capitalize(),
"Clarté": f"{clarity_score:.1f}",
"Explication": explanation
})
return detected_sentiment.capitalize(), explanation, clarity_score, history, int(clarity_score)
# Fonction pour télécharger l'historique
def download_history(history):
if not history:
return None
df = pd.DataFrame(history)
file_path = "/tmp/history.csv"
df.to_csv(file_path, index=False)
return file_path
# Gradio Interface
def launch_app():
with gr.Blocks() as iface:
gr.Markdown("# 📈 Analyse Financière Premium - Zephyr7B")
with gr.Row():
input_text = gr.Textbox(label="Entrez votre question financière", lines=3)
with gr.Row():
analyze_btn = gr.Button("Analyser")
download_btn = gr.Button("Télécharger l'historique")
sentiment_output = gr.Textbox(label="Sentiment Détecté")
explanation_output = gr.Textbox(label="Explication de l'IA", lines=5)
clarity_score_text = gr.Textbox(label="Score de Clarté (%)")
clarity_slider = gr.Slider(0, 100, label="Clarté (%)", interactive=False)
file_output = gr.File(label="Fichier CSV")
history = gr.State([])
analyze_btn.click(
full_analysis,
inputs=[input_text, history],
outputs=[sentiment_output, explanation_output, clarity_score_text, history, clarity_slider]
)
download_btn.click(
download_history,
inputs=[history],
outputs=[file_output]
)
iface.launch()
if __name__ == "__main__":
launch_app()