Vycka12 commited on
Commit
8135f41
·
verified ·
1 Parent(s): bd3d2e8

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +24 -26
app.py CHANGED
@@ -10,12 +10,14 @@ 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
- # Pataisytas CryptoPanic URL formatas
18
- CRYPTOPANIC_URL = "https://cryptopanic.com/api/v1/posts/"
 
 
19
 
20
  # Globalūs kintamieji
21
  news_buffer = []
@@ -36,19 +38,12 @@ class SentimentSystem:
36
 
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)
@@ -56,7 +51,7 @@ class SentimentSystem:
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,7 +62,6 @@ class SentimentSystem:
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']
@@ -96,9 +90,9 @@ class SentimentSystem:
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"]
@@ -109,7 +103,7 @@ class SentimentSystem:
109
  fig = go.Figure(go.Indicator(
110
  mode = "gauge+number",
111
  value = val,
112
- title = {'text': f"Rinkos nuotaika: {stats['overall']}"},
113
  gauge = {
114
  'axis': {'range': [0, 100]},
115
  'bar': {'color': "black"},
@@ -128,41 +122,45 @@ sys_analyzer = SentimentSystem()
128
  def update_loop():
129
  while True:
130
  sys_analyzer.fetch_and_analyze()
131
- time.sleep(300)
 
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"])
138
 
139
- status_text = f"### 📊 Suvestinė\n**Būsena:** {stats['status']}\n**Geros žinios:** {stats['bullish']} | **Blogos:** {stats['bearish']}"
140
  return gauge, df, status_text
141
 
142
  # --- GRADIO ---
143
  with gr.Blocks(title="Sentiment AI Analyzer", theme=gr.themes.Soft()) as demo:
144
  gr.Markdown("# 🧠 Crypto Sentimentų Vertėjas (AI)")
 
145
 
146
  with gr.Row():
147
  with gr.Column(scale=2):
148
  gauge_output = gr.Plot(label="Nuotaika")
149
  with gr.Column(scale=1):
150
  info_output = gr.Markdown("Inicijuojama sistema...")
151
- refresh_btn = gr.Button("🔄 Tikrinti naujienas dabar", variant="primary")
152
 
153
- gr.Markdown("### 📰 Paskutinės 15 naujienų:")
154
  table_output = gr.Dataframe(
155
  headers=["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas"],
156
  datatype=["str", "str", "str", "str"],
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)
 
10
  from huggingface_hub import HfApi
11
  import plotly.graph_objects as go
12
 
13
+ # --- KONFIGŪRACIJA (DEVELOPER PLAN) ---
14
  MODEL_NAME = "ProsusAI/finbert"
15
  TARGET_DATASET = "Vycka12/Base"
16
  HF_TOKEN = os.environ.get("HF_TOKEN")
17
+
18
+ # Jūsų specifinis Developer Endpoint
19
+ CRYPTOPANIC_API_KEY = "6c0f988f9e33170ccd183c6a14b34e8c2ad0867f"
20
+ CRYPTOPANIC_URL = "https://cryptopanic.com/api/developer/v2/posts/"
21
 
22
  # Globalūs kintamieji
23
  news_buffer = []
 
38
 
39
  def fetch_and_analyze(self):
40
  global news_buffer, stats
41
+ stats["status"] = "Siurbiamos naujienos (24h vėlavimas)..."
 
 
 
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=15)
 
51
  if resp.status_code == 200:
52
  raw_news = resp.json().get("results", [])
53
  if not raw_news:
54
+ stats["status"] = "⚠️ Naujienų kol kas nėra (limitai?)."
55
  return
56
 
57
  temp_news = []
 
62
  if not title: continue
63
 
64
  if sentiment_pipeline:
 
65
  result = sentiment_pipeline(title[:512])[0]
66
  label = result['label']
67
  score = result['score']
 
90
  news_buffer = temp_news
91
  stats["status"] = f"Analizė baigta {datetime.now().strftime('%H:%M:%S')}"
92
  else:
93
+ stats["status"] = f"❌ API Klaida: {resp.status_code}"
94
  except Exception as e:
95
+ stats["status"] = f"❌ Sistemos klaida: {str(e)}"
96
 
97
  def create_gauge(self):
98
  total = stats["bullish"] + stats["bearish"]
 
103
  fig = go.Figure(go.Indicator(
104
  mode = "gauge+number",
105
  value = val,
106
+ title = {'text': f"Nuotaika (vakar): {stats['overall']}"},
107
  gauge = {
108
  'axis': {'range': [0, 100]},
109
  'bar': {'color': "black"},
 
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
  df = pd.DataFrame(news_buffer, columns=["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas"])
131
  if df.empty:
132
+ df = pd.DataFrame([["-", "-", "Kraunama...", "-"]], columns=["Emoji", "Verdiktas", "Antraštė", "Pasitikėjimas"])
133
 
134
+ status_text = f"### 📊 Suvestinė (Developer Plan)\n**Būsena:** {stats['status']}\n**SVARBU:** Naujienos vėluoja 24h dėl plano ribojimų."
135
  return gauge, df, status_text
136
 
137
  # --- GRADIO ---
138
  with gr.Blocks(title="Sentiment AI Analyzer", theme=gr.themes.Soft()) as demo:
139
  gr.Markdown("# 🧠 Crypto Sentimentų Vertėjas (AI)")
140
+ gr.Markdown("Pastaba: Naudojamas Developer planas (24 valandų naujienų vėlavimas).")
141
 
142
  with gr.Row():
143
  with gr.Column(scale=2):
144
  gauge_output = gr.Plot(label="Nuotaika")
145
  with gr.Column(scale=1):
146
  info_output = gr.Markdown("Inicijuojama sistema...")
147
+ refresh_btn = gr.Button("🔄 Tikrinti naujienas (Atsargiai - limitai!)", variant="primary")
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
+ refresh_btn.click(fn=sys_analyzer.fetch_and_analyze)
157
  refresh_btn.click(fn=get_ui_data, outputs=[gauge_output, table_output, info_output])
158
+
159
  demo.load(sys_analyzer.fetch_and_analyze)
160
  demo.load(get_ui_data, outputs=[gauge_output, table_output, info_output])
161
 
162
  threading.Thread(target=update_loop, daemon=True).start()
163
+ gr.Timer(60).tick(get_ui_data, outputs=[gauge_output, table_output, info_output])
164
 
165
  if __name__ == "__main__":
166
  demo.launch(server_name="0.0.0.0", server_port=7860)