GoshawkVortexAI commited on
Commit
04d21a3
·
verified ·
1 Parent(s): ad093ef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -39
app.py CHANGED
@@ -1,19 +1,17 @@
1
  import requests
2
- import pandas as pd
3
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
- import torch
5
- import torch.nn.functional as F
6
  from datetime import datetime
7
  import gradio as gr
8
 
9
  # ==========================
10
- # 1️⃣ MODEL LOAD (DistilFinBERT)
11
  # ==========================
12
- MODEL_NAME = "yiyanghkust/finbert-tone-distil" # DistilFinBERT, CPU-friendly
13
-
14
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
15
  model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
16
- model.eval()
 
17
 
18
  # ==========================
19
  # 2️⃣ REUTERS SCRAPER
@@ -43,52 +41,53 @@ def fetch_reuters_articles(section="/business/", size=10):
43
  except Exception as e:
44
  print("Parsing error:", e)
45
 
46
- return pd.DataFrame(articles)
47
 
48
  # ==========================
49
  # 3️⃣ SENTIMENT SCORING
50
  # ==========================
51
- def finbert_score(text):
52
- inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
53
- with torch.no_grad():
54
- outputs = model(**inputs)
55
- probs = F.softmax(outputs.logits, dim=1)
56
- labels = ["negative", "neutral", "positive"]
57
- scores = probs[0].tolist()
58
- return dict(zip(labels, scores))
59
 
60
  # ==========================
61
- # 4️⃣ PIPELINE
62
  # ==========================
63
- def run_pipeline():
64
- df = fetch_reuters_articles(size=10)
65
- sentiments = []
66
- for _, row in df.iterrows():
67
- text = row["headline"] + ". " + row["summary"]
68
- score = finbert_score(text)
69
- sentiments.append(score)
 
70
 
71
- sentiment_df = pd.DataFrame(sentiments)
72
- final_df = pd.concat([df, sentiment_df], axis=1)
73
- final_df["hawkish_score"] = final_df["negative"] - final_df["positive"]
 
 
 
 
74
 
75
- filename = f"reuters_finbert_{datetime.today().date()}.csv"
76
- final_df.to_csv(filename, index=False)
77
- return final_df.head(), filename
78
 
79
  # ==========================
80
- # 5️⃣ GRADIO WEB APP
81
  # ==========================
82
- def gradio_interface(dummy_input):
83
- table, fname = run_pipeline()
84
- return table.to_string(), f"Saved CSV: {fname}"
85
-
86
  iface = gr.Interface(
87
- fn=gradio_interface,
88
  inputs=gr.Textbox(label="Run Scraper (any text)"),
89
  outputs=[gr.Textbox(label="Top Articles"), gr.Textbox(label="CSV Status")],
90
- title="Reuters DistilFinBERT Scraper",
91
- description="Fetch latest Reuters Business news + sentiment via DistilFinBERT"
92
  )
93
 
94
  if __name__ == "__main__":
 
1
  import requests
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
3
+ import csv
 
 
4
  from datetime import datetime
5
  import gradio as gr
6
 
7
  # ==========================
8
+ # 1️⃣ MODEL (CPU-Friendly)
9
  # ==========================
10
+ MODEL_NAME = "cardiffnlp/twitter-roberta-base-financial-sentiment"
 
11
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
12
  model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
13
+
14
+ nlp = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
15
 
16
  # ==========================
17
  # 2️⃣ REUTERS SCRAPER
 
41
  except Exception as e:
42
  print("Parsing error:", e)
43
 
44
+ return articles
45
 
46
  # ==========================
47
  # 3️⃣ SENTIMENT SCORING
48
  # ==========================
49
+ def score_articles(articles):
50
+ scored = []
51
+ for art in articles:
52
+ text = art["headline"] + ". " + art["summary"]
53
+ result = nlp(text)[0] # cardiffnlp döndürür: {'label': 'positive', 'score': 0.95}
54
+ art.update(result)
55
+ scored.append(art)
56
+ return scored
57
 
58
  # ==========================
59
+ # 4️⃣ CSV SAVE
60
  # ==========================
61
+ def save_csv(scored_articles):
62
+ filename = f"reuters_sentiment_{datetime.today().date()}.csv"
63
+ keys = scored_articles[0].keys()
64
+ with open(filename, "w", newline="", encoding="utf-8") as f:
65
+ dict_writer = csv.DictWriter(f, fieldnames=keys)
66
+ dict_writer.writeheader()
67
+ dict_writer.writerows(scored_articles)
68
+ return filename
69
 
70
+ # ==========================
71
+ # 5️⃣ PIPELINE
72
+ # ==========================
73
+ def run_pipeline(dummy_input):
74
+ articles = fetch_reuters_articles(size=10)
75
+ scored = score_articles(articles)
76
+ csv_file = save_csv(scored)
77
 
78
+ # Terminal için tablo görünümü
79
+ display_text = "\n".join([f"{a['headline']} -> {a['label']} ({a['score']:.2f})" for a in scored])
80
+ return display_text, f"Saved CSV: {csv_file}"
81
 
82
  # ==========================
83
+ # 6️⃣ GRADIO WEB APP
84
  # ==========================
 
 
 
 
85
  iface = gr.Interface(
86
+ fn=run_pipeline,
87
  inputs=gr.Textbox(label="Run Scraper (any text)"),
88
  outputs=[gr.Textbox(label="Top Articles"), gr.Textbox(label="CSV Status")],
89
+ title="Reuters Financial Sentiment (CardiffNLP)",
90
+ description="Fetch latest Reuters Business news + sentiment via CardiffNLP Roberta model (CPU-friendly, no pandas)"
91
  )
92
 
93
  if __name__ == "__main__":