Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -10,18 +10,18 @@ from datetime import datetime, timezone
|
|
| 10 |
from huggingface_hub import HfApi
|
| 11 |
import plotly.graph_objects as go
|
| 12 |
|
| 13 |
-
# --- KONFIGŪRACIJA
|
| 14 |
MODEL_NAME = "ProsusAI/finbert"
|
| 15 |
TARGET_DATASET = "Vycka12/Base"
|
| 16 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 17 |
|
| 18 |
-
#
|
| 19 |
CRYPTOPANIC_API_KEY = "6c0f988f9e33170ccd183c6a14b34e8c2ad0867f"
|
| 20 |
CRYPTOPANIC_URL = "https://cryptopanic.com/api/developer/v2/posts/"
|
| 21 |
|
| 22 |
# Globalūs kintamieji
|
| 23 |
news_buffer = []
|
| 24 |
-
stats = {"bullish": 0, "bearish": 0, "neutral": 0, "overall": "
|
| 25 |
|
| 26 |
# Krauname AI
|
| 27 |
print("⌛ Kraunamas AI modelis...")
|
|
@@ -38,29 +38,33 @@ class SentimentSystem:
|
|
| 38 |
|
| 39 |
def fetch_and_analyze(self):
|
| 40 |
global news_buffer, stats
|
| 41 |
-
stats["status"] = "
|
| 42 |
|
|
|
|
| 43 |
params = {
|
| 44 |
"auth_token": CRYPTOPANIC_API_KEY,
|
| 45 |
"kind": "news"
|
| 46 |
}
|
| 47 |
|
| 48 |
try:
|
| 49 |
-
resp = requests.get(CRYPTOPANIC_URL, params=params, timeout=
|
| 50 |
|
| 51 |
if resp.status_code == 200:
|
| 52 |
-
|
|
|
|
|
|
|
| 53 |
if not raw_news:
|
| 54 |
-
stats["status"] = "⚠️
|
| 55 |
return
|
| 56 |
|
| 57 |
temp_news = []
|
| 58 |
pos, neg, neut = 0, 0, 0
|
| 59 |
|
| 60 |
-
for item in raw_news
|
| 61 |
title = item.get("title", "")
|
| 62 |
if not title: continue
|
| 63 |
|
|
|
|
| 64 |
if sentiment_pipeline:
|
| 65 |
result = sentiment_pipeline(title[:512])[0]
|
| 66 |
label = result['label']
|
|
@@ -68,6 +72,7 @@ class SentimentSystem:
|
|
| 68 |
else:
|
| 69 |
label, score = 'neutral', 0.5
|
| 70 |
|
|
|
|
| 71 |
if label == 'positive':
|
| 72 |
status, emo = "🟢 BULLISH", "🚀"
|
| 73 |
pos += 1
|
|
@@ -78,32 +83,42 @@ class SentimentSystem:
|
|
| 78 |
status, emo = "⚪ NEUTRAL", "➖"
|
| 79 |
neut += 1
|
| 80 |
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
stats["bullish"] = pos
|
| 84 |
stats["bearish"] = neg
|
| 85 |
stats["neutral"] = neut
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
news_buffer = temp_news
|
| 91 |
-
stats["status"] = f"
|
| 92 |
else:
|
| 93 |
stats["status"] = f"❌ API Klaida: {resp.status_code}"
|
| 94 |
except Exception as e:
|
| 95 |
-
stats["status"] = f"❌
|
| 96 |
|
| 97 |
def create_gauge(self):
|
| 98 |
-
total = stats["bullish"] + stats["bearish"]
|
| 99 |
val = 50
|
| 100 |
if total > 0:
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
fig = go.Figure(go.Indicator(
|
| 104 |
mode = "gauge+number",
|
| 105 |
value = val,
|
| 106 |
-
title = {'text': f"
|
| 107 |
gauge = {
|
| 108 |
'axis': {'range': [0, 100]},
|
| 109 |
'bar': {'color': "black"},
|
|
@@ -114,53 +129,59 @@ class SentimentSystem:
|
|
| 114 |
],
|
| 115 |
}
|
| 116 |
))
|
| 117 |
-
fig.update_layout(height=
|
| 118 |
return fig
|
| 119 |
|
| 120 |
sys_analyzer = SentimentSystem()
|
| 121 |
|
| 122 |
def update_loop():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
while True:
|
|
|
|
|
|
|
| 124 |
sys_analyzer.fetch_and_analyze()
|
| 125 |
-
# Laukiame 8 valandas (taupome 100 req/mėn limitą)
|
| 126 |
-
time.sleep(28800)
|
| 127 |
|
| 128 |
def get_ui_data():
|
| 129 |
gauge = sys_analyzer.create_gauge()
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
status_text = f"### 📊
|
| 135 |
return gauge, df, status_text
|
| 136 |
|
| 137 |
-
# --- GRADIO ---
|
| 138 |
-
with gr.Blocks(title="Sentiment AI
|
| 139 |
-
gr.Markdown("# 🧠
|
| 140 |
-
gr.Markdown("
|
| 141 |
|
| 142 |
with gr.Row():
|
| 143 |
-
with gr.Column(
|
| 144 |
gauge_output = gr.Plot(label="Nuotaika")
|
| 145 |
-
with gr.Column(
|
| 146 |
-
|
| 147 |
-
refresh_btn = gr.Button("🔄
|
| 148 |
-
|
| 149 |
-
gr.Markdown("### 📰 Paskutinės perskaitytos naujienos:")
|
| 150 |
-
table_output = gr.Dataframe(
|
| 151 |
-
headers=["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas"],
|
| 152 |
-
datatype=["str", "str", "str", "str"],
|
| 153 |
-
interactive=False
|
| 154 |
-
)
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
| 161 |
|
|
|
|
| 162 |
threading.Thread(target=update_loop, daemon=True).start()
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
if __name__ == "__main__":
|
| 166 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 10 |
from huggingface_hub import HfApi
|
| 11 |
import plotly.graph_objects as go
|
| 12 |
|
| 13 |
+
# --- KONFIGŪRACIJA ---
|
| 14 |
MODEL_NAME = "ProsusAI/finbert"
|
| 15 |
TARGET_DATASET = "Vycka12/Base"
|
| 16 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 17 |
|
| 18 |
+
# API Raktas ir URL (Griežtai nustatyti)
|
| 19 |
CRYPTOPANIC_API_KEY = "6c0f988f9e33170ccd183c6a14b34e8c2ad0867f"
|
| 20 |
CRYPTOPANIC_URL = "https://cryptopanic.com/api/developer/v2/posts/"
|
| 21 |
|
| 22 |
# Globalūs kintamieji
|
| 23 |
news_buffer = []
|
| 24 |
+
stats = {"bullish": 0, "bearish": 0, "neutral": 0, "overall": "Inicijuojama...", "status": "Startuoja..."}
|
| 25 |
|
| 26 |
# Krauname AI
|
| 27 |
print("⌛ Kraunamas AI modelis...")
|
|
|
|
| 38 |
|
| 39 |
def fetch_and_analyze(self):
|
| 40 |
global news_buffer, stats
|
| 41 |
+
stats["status"] = "Gaunamos naujienos..."
|
| 42 |
|
| 43 |
+
# Pataisyti parametrai - tik būtiniausi
|
| 44 |
params = {
|
| 45 |
"auth_token": CRYPTOPANIC_API_KEY,
|
| 46 |
"kind": "news"
|
| 47 |
}
|
| 48 |
|
| 49 |
try:
|
| 50 |
+
resp = requests.get(CRYPTOPANIC_URL, params=params, timeout=20)
|
| 51 |
|
| 52 |
if resp.status_code == 200:
|
| 53 |
+
data = resp.json()
|
| 54 |
+
raw_news = data.get("results", [])
|
| 55 |
+
|
| 56 |
if not raw_news:
|
| 57 |
+
stats["status"] = "⚠️ API grąžino tuščią sąrašą."
|
| 58 |
return
|
| 59 |
|
| 60 |
temp_news = []
|
| 61 |
pos, neg, neut = 0, 0, 0
|
| 62 |
|
| 63 |
+
for item in raw_news:
|
| 64 |
title = item.get("title", "")
|
| 65 |
if not title: continue
|
| 66 |
|
| 67 |
+
# AI Analizė
|
| 68 |
if sentiment_pipeline:
|
| 69 |
result = sentiment_pipeline(title[:512])[0]
|
| 70 |
label = result['label']
|
|
|
|
| 72 |
else:
|
| 73 |
label, score = 'neutral', 0.5
|
| 74 |
|
| 75 |
+
# Emocijos
|
| 76 |
if label == 'positive':
|
| 77 |
status, emo = "🟢 BULLISH", "🚀"
|
| 78 |
pos += 1
|
|
|
|
| 83 |
status, emo = "⚪ NEUTRAL", "➖"
|
| 84 |
neut += 1
|
| 85 |
|
| 86 |
+
# Laikas
|
| 87 |
+
pub_time = item.get("published_at", "")[:16].replace("T", " ")
|
| 88 |
+
|
| 89 |
+
temp_news.append([emo, status, title, f"{round(score*100)}%", pub_time])
|
| 90 |
|
| 91 |
stats["bullish"] = pos
|
| 92 |
stats["bearish"] = neg
|
| 93 |
stats["neutral"] = neut
|
| 94 |
+
|
| 95 |
+
total = pos + neg + neut
|
| 96 |
+
if total > 0:
|
| 97 |
+
ratio = (pos - neg) / total
|
| 98 |
+
if ratio > 0.2: stats["overall"] = "OPTIMIZMAS 📈"
|
| 99 |
+
elif ratio < -0.2: stats["overall"] = "BAIMĖ 📉"
|
| 100 |
+
else: stats["overall"] = "NEUTRALU ⚖️"
|
| 101 |
|
| 102 |
news_buffer = temp_news
|
| 103 |
+
stats["status"] = f"Atnaujinta: {datetime.now().strftime('%H:%M:%S')}"
|
| 104 |
else:
|
| 105 |
stats["status"] = f"❌ API Klaida: {resp.status_code}"
|
| 106 |
except Exception as e:
|
| 107 |
+
stats["status"] = f"❌ Klaida: {str(e)}"
|
| 108 |
|
| 109 |
def create_gauge(self):
|
| 110 |
+
total = stats["bullish"] + stats["bearish"] + stats["neutral"]
|
| 111 |
val = 50
|
| 112 |
if total > 0:
|
| 113 |
+
# Formulė: 50 + (teigiami - neigiami) * koeficientas
|
| 114 |
+
# Jei visi teigiami -> 100, visi neigiami -> 0
|
| 115 |
+
net_sentiment = (stats["bullish"] - stats["bearish"]) / total
|
| 116 |
+
val = 50 + (net_sentiment * 50)
|
| 117 |
|
| 118 |
fig = go.Figure(go.Indicator(
|
| 119 |
mode = "gauge+number",
|
| 120 |
value = val,
|
| 121 |
+
title = {'text': f"Rinkos Emocija: {stats['overall']}"},
|
| 122 |
gauge = {
|
| 123 |
'axis': {'range': [0, 100]},
|
| 124 |
'bar': {'color': "black"},
|
|
|
|
| 129 |
],
|
| 130 |
}
|
| 131 |
))
|
| 132 |
+
fig.update_layout(height=300, margin=dict(l=20, r=20, t=50, b=20))
|
| 133 |
return fig
|
| 134 |
|
| 135 |
sys_analyzer = SentimentSystem()
|
| 136 |
|
| 137 |
def update_loop():
|
| 138 |
+
# Pirmas paleidimas po 10 sek
|
| 139 |
+
time.sleep(10)
|
| 140 |
+
sys_analyzer.fetch_and_analyze()
|
| 141 |
+
|
| 142 |
while True:
|
| 143 |
+
# Atnaujiname kas 4 valandas (taupome limitą)
|
| 144 |
+
time.sleep(14400)
|
| 145 |
sys_analyzer.fetch_and_analyze()
|
|
|
|
|
|
|
| 146 |
|
| 147 |
def get_ui_data():
|
| 148 |
gauge = sys_analyzer.create_gauge()
|
| 149 |
+
cols = ["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas", "Laikas"]
|
| 150 |
+
|
| 151 |
+
if not news_buffer:
|
| 152 |
+
df = pd.DataFrame([["-", "-", "Kraunama...", "-", "-"]], columns=cols)
|
| 153 |
+
else:
|
| 154 |
+
df = pd.DataFrame(news_buffer, columns=cols)
|
| 155 |
|
| 156 |
+
status_text = f"### 📊 Statistika\n**Būsena:** {stats['status']}\n**Geros:** {stats['bullish']} | **Blogos:** {stats['bearish']} | **Viso:** {stats['bullish']+stats['bearish']+stats['neutral']}"
|
| 157 |
return gauge, df, status_text
|
| 158 |
|
| 159 |
+
# --- GRADIO UI ---
|
| 160 |
+
with gr.Blocks(title="Sentiment AI", theme=gr.themes.Soft()) as demo:
|
| 161 |
+
gr.Markdown("# 🧠 Sentiment AI Analyzer")
|
| 162 |
+
gr.Markdown("Analizuoja realias crypto naujienas naudodamas ProsusAI FinBERT modelį.")
|
| 163 |
|
| 164 |
with gr.Row():
|
| 165 |
+
with gr.Column():
|
| 166 |
gauge_output = gr.Plot(label="Nuotaika")
|
| 167 |
+
with gr.Column():
|
| 168 |
+
status_output = gr.Markdown("Laukiama duomenų...")
|
| 169 |
+
refresh_btn = gr.Button("🔄 Atnaujinti Dabar", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
gr.Markdown("### 📰 Naujienų srautas ir AI vertinimas")
|
| 172 |
+
table_output = gr.Dataframe(interactive=False)
|
| 173 |
+
|
| 174 |
+
# Eventai
|
| 175 |
+
refresh_btn.click(fn=sys_analyzer.fetch_and_analyze).then(
|
| 176 |
+
fn=get_ui_data, outputs=[gauge_output, table_output, status_output]
|
| 177 |
+
)
|
| 178 |
|
| 179 |
+
# Auto-start
|
| 180 |
threading.Thread(target=update_loop, daemon=True).start()
|
| 181 |
+
|
| 182 |
+
# UI atnaujinimas (tik vaizdo, ne duomenų siurbimo)
|
| 183 |
+
demo.load(get_ui_data, outputs=[gauge_output, table_output, status_output])
|
| 184 |
+
gr.Timer(5).tick(get_ui_data, outputs=[gauge_output, table_output, status_output])
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|