File size: 3,568 Bytes
ffb571b
e29f507
4504964
ffb571b
e29f507
 
e6ea4ea
e29f507
 
a62a318
a2c7ce8
 
e29f507
a62a318
e6ea4ea
1798572
 
 
e6ea4ea
1798572
a62a318
a2c7ce8
e6ea4ea
 
 
a62a318
1798572
a62a318
e6ea4ea
 
14aa24c
e6ea4ea
a62a318
ec011c8
e6ea4ea
14aa24c
e6ea4ea
 
 
4504964
e6ea4ea
 
d179496
a62a318
e6ea4ea
 
d179496
e6ea4ea
a62a318
850981e
e6ea4ea
850981e
e6ea4ea
 
 
 
850981e
a62a318
e6ea4ea
a62a318
ffb571b
a62a318
4504964
 
e6ea4ea
 
 
4504964
 
a62a318
e6ea4ea
 
4504964
 
 
 
e6ea4ea
4504964
 
850981e
e6ea4ea
ffb571b
e6ea4ea
 
850981e
ffb571b
e6ea4ea
850981e
ffb571b
e6ea4ea
 
ffb571b
a62a318
e6ea4ea
 
a62a318
e6ea4ea
ffb571b
e6ea4ea
ffb571b
 
 
e6ea4ea
a62a318
4504964
ffb571b
 
 
 
e6ea4ea
ffb571b
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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()