Vycka12 commited on
Commit
bd3d2e8
·
verified ·
1 Parent(s): 771fc8b

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +28 -21
app.py CHANGED
@@ -14,9 +14,10 @@ import plotly.graph_objects as go
14
  MODEL_NAME = "ProsusAI/finbert"
15
  TARGET_DATASET = "Vycka12/Base"
16
  HF_TOKEN = os.environ.get("HF_TOKEN")
17
- CRYPTOPANIC_URL = "https://cryptopanic.com/api/v1/posts/?kind=news&public=true"
 
18
 
19
- # Globalūs kintamieji su pradinėmis reikšmėmis
20
  news_buffer = []
21
  stats = {"bullish": 0, "bearish": 0, "neutral": 0, "overall": "Laukiama...", "status": "Inicijuojama..."}
22
 
@@ -36,12 +37,26 @@ class SentimentSystem:
36
  def fetch_and_analyze(self):
37
  global news_buffer, stats
38
  stats["status"] = "Siurbiamos naujienos..."
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  try:
40
- resp = requests.get(CRYPTOPANIC_URL, timeout=15)
 
41
  if resp.status_code == 200:
42
  raw_news = resp.json().get("results", [])
43
  if not raw_news:
44
- stats["status"] = "⚠️ Nerasta naujų žinučių."
45
  return
46
 
47
  temp_news = []
@@ -52,21 +67,21 @@ class SentimentSystem:
52
  if not title: continue
53
 
54
  if sentiment_pipeline:
 
55
  result = sentiment_pipeline(title[:512])[0]
56
  label = result['label']
57
  score = result['score']
58
  else:
59
  label, score = 'neutral', 0.5
60
 
61
- # Emocijų nustatymas
62
  if label == 'positive':
63
- status, emo, color = "🟢 BULLISH", "🚀", "green"
64
  pos += 1
65
  elif label == 'negative':
66
- status, emo, color = "🔴 BEARISH", "📉", "red"
67
  neg += 1
68
  else:
69
- status, emo, color = "⚪ NEUTRAL", "➖", "gray"
70
  neut += 1
71
 
72
  temp_news.append([emo, status, title, f"{round(score*100)}%"])
@@ -81,13 +96,12 @@ class SentimentSystem:
81
  news_buffer = temp_news
82
  stats["status"] = f"Analizė baigta {datetime.now().strftime('%H:%M:%S')}"
83
  else:
84
- stats["status"] = f"❌ API Klaida: {resp.status_code}"
85
  except Exception as e:
86
- stats["status"] = f"❌ Sistemos klaida: {str(e)}"
87
 
88
  def create_gauge(self):
89
  total = stats["bullish"] + stats["bearish"]
90
- # Jei nėra duomenų, rodome 50 (neutralu)
91
  val = 50
92
  if total > 0:
93
  val = ((stats["bullish"] - stats["bearish"]) / total) * 50 + 50
@@ -106,7 +120,7 @@ class SentimentSystem:
106
  ],
107
  }
108
  ))
109
- fig.update_layout(height=280, margin=dict(l=20, r=20, t=40, b=20))
110
  return fig
111
 
112
  sys_analyzer = SentimentSystem()
@@ -118,7 +132,6 @@ def update_loop():
118
 
119
  def get_ui_data():
120
  gauge = sys_analyzer.create_gauge()
121
- # Užtikriname, kad lentelė visada turi stulpelius
122
  df = pd.DataFrame(news_buffer, columns=["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas"])
123
  if df.empty:
124
  df = pd.DataFrame([["-", "-", "Kraunamos naujienos...", "-"]], columns=["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas"])
@@ -144,18 +157,12 @@ with gr.Blocks(title="Sentiment AI Analyzer", theme=gr.themes.Soft()) as demo:
144
  interactive=False
145
  )
146
 
147
- # Tikrinimo mygtukas
148
  refresh_btn.click(fn=get_ui_data, outputs=[gauge_output, table_output, info_output])
149
-
150
- # Automatinis atnaujinimas
151
- demo.load(sys_analyzer.fetch_and_analyze) # Pirmas paleidimas
152
  demo.load(get_ui_data, outputs=[gauge_output, table_output, info_output])
153
 
154
- # Tikrasis fono threadas
155
  threading.Thread(target=update_loop, daemon=True).start()
156
-
157
- # UI atnaujinimas kas 15s
158
- gr.Timer(15).tick(get_ui_data, outputs=[gauge_output, table_output, info_output])
159
 
160
  if __name__ == "__main__":
161
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
14
  MODEL_NAME = "ProsusAI/finbert"
15
  TARGET_DATASET = "Vycka12/Base"
16
  HF_TOKEN = os.environ.get("HF_TOKEN")
17
+ # Pataisytas CryptoPanic URL formatas
18
+ CRYPTOPANIC_URL = "https://cryptopanic.com/api/v1/posts/"
19
 
20
+ # Globalūs kintamieji
21
  news_buffer = []
22
  stats = {"bullish": 0, "bearish": 0, "neutral": 0, "overall": "Laukiama...", "status": "Inicijuojama..."}
23
 
 
37
  def fetch_and_analyze(self):
38
  global news_buffer, stats
39
  stats["status"] = "Siurbiamos naujienos..."
40
+
41
+ # Pasiimame raktą (jei vartotojas jį įdėjo į Secrets)
42
+ api_key = os.environ.get("CRYPTOPANIC_API_KEY", "")
43
+
44
+ # Baziniai parametrai
45
+ params = {"kind": "news"}
46
+ if api_key:
47
+ params["auth_token"] = api_key
48
+ else:
49
+ # Jei rakto nėra, CryptoPanic leidžia tik viešą hot srautą
50
+ params["public"] = "true"
51
+ params["filter"] = "hot"
52
+
53
  try:
54
+ resp = requests.get(CRYPTOPANIC_URL, params=params, timeout=15)
55
+
56
  if resp.status_code == 200:
57
  raw_news = resp.json().get("results", [])
58
  if not raw_news:
59
+ stats["status"] = "⚠️ API veikia, bet naujienų kol kas nėra."
60
  return
61
 
62
  temp_news = []
 
67
  if not title: continue
68
 
69
  if sentiment_pipeline:
70
+ # FinBERT analizė
71
  result = sentiment_pipeline(title[:512])[0]
72
  label = result['label']
73
  score = result['score']
74
  else:
75
  label, score = 'neutral', 0.5
76
 
 
77
  if label == 'positive':
78
+ status, emo = "🟢 BULLISH", "🚀"
79
  pos += 1
80
  elif label == 'negative':
81
+ status, emo = "🔴 BEARISH", "📉"
82
  neg += 1
83
  else:
84
+ status, emo = "⚪ NEUTRAL", "➖"
85
  neut += 1
86
 
87
  temp_news.append([emo, status, title, f"{round(score*100)}%"])
 
96
  news_buffer = temp_news
97
  stats["status"] = f"Analizė baigta {datetime.now().strftime('%H:%M:%S')}"
98
  else:
99
+ stats["status"] = f"❌ API Klaida: {resp.status_code} (Reikia rakto?)"
100
  except Exception as e:
101
+ stats["status"] = f"❌ Ryšio klaida: {str(e)}"
102
 
103
  def create_gauge(self):
104
  total = stats["bullish"] + stats["bearish"]
 
105
  val = 50
106
  if total > 0:
107
  val = ((stats["bullish"] - stats["bearish"]) / total) * 50 + 50
 
120
  ],
121
  }
122
  ))
123
+ fig.update_layout(height=280, margin=dict(l=20, r=20, t=40, b=20), paper_bgcolor="rgba(0,0,0,0)")
124
  return fig
125
 
126
  sys_analyzer = SentimentSystem()
 
132
 
133
  def get_ui_data():
134
  gauge = sys_analyzer.create_gauge()
 
135
  df = pd.DataFrame(news_buffer, columns=["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas"])
136
  if df.empty:
137
  df = pd.DataFrame([["-", "-", "Kraunamos naujienos...", "-"]], columns=["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas"])
 
157
  interactive=False
158
  )
159
 
 
160
  refresh_btn.click(fn=get_ui_data, outputs=[gauge_output, table_output, info_output])
161
+ demo.load(sys_analyzer.fetch_and_analyze)
 
 
162
  demo.load(get_ui_data, outputs=[gauge_output, table_output, info_output])
163
 
 
164
  threading.Thread(target=update_loop, daemon=True).start()
165
+ gr.Timer(30).tick(get_ui_data, outputs=[gauge_output, table_output, info_output])
 
 
166
 
167
  if __name__ == "__main__":
168
  demo.launch(server_name="0.0.0.0", server_port=7860)