Badumetsibb commited on
Commit
4bb8669
·
verified ·
1 Parent(s): 831ec89

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -13
app.py CHANGED
@@ -1,40 +1,109 @@
 
1
  import feedparser
2
  import pandas as pd
3
  import gradio as gr
4
  from transformers import pipeline
 
 
 
 
 
5
 
6
- sentiment = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
 
 
 
 
 
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  def fetch_news():
 
9
  url = "https://www.fxstreet.com/rss/news"
10
  feed = feedparser.parse(url)
11
- headlines = feed.entries[:7]
 
12
  return headlines
13
 
14
  def analyze_news():
 
 
 
15
  headlines = fetch_news()
16
  results = []
 
17
  for h in headlines:
18
  text = h.title
19
- pred = sentiment(text)[0]
 
 
 
 
20
  label = pred["label"].lower()
21
  score = round(pred["score"], 3)
 
22
  if label == "positive":
23
- m = "Bullish"
24
  elif label == "negative":
25
- m = "Bearish"
26
  else:
27
- m = "Neutral"
28
- results.append([text, label, score, m])
29
- df = pd.DataFrame(results, columns=["Headline", "Raw Label", "Confidence", "Market Sentiment"])
30
- return df
 
 
 
 
 
 
31
 
 
32
  demo = gr.Interface(
33
  fn=analyze_news,
34
  inputs=None,
35
- outputs=gr.Dataframe(),
36
- title="📊 Forex Sentiment Agent",
37
- description="Live Forex headlines sentiment (Bullish / Bearish / Neutral)."
 
38
  )
39
 
40
- demo.launch()
 
 
1
+ # app_news_sentiment_firebase.py
2
  import feedparser
3
  import pandas as pd
4
  import gradio as gr
5
  from transformers import pipeline
6
+ from datetime import datetime
7
+ import firebase_admin
8
+ from firebase_admin import credentials, db
9
+ import os
10
+ import json
11
 
12
+ # --- Firebase Configuration ---
13
+ # IMPORTANT: Set these environment variables in your deployment environment (e.g., Hugging Face Spaces Secrets)
14
+ # 1. FIRESTORE_SA_KEY: The full JSON content of your Firebase service account key.
15
+ # 2. FIREBASE_DB_URL: The URL to your Firebase Realtime Database.
16
+ SA_KEY_JSON = os.environ.get('FIRESTORE_SA_KEY')
17
+ DB_URL = os.environ.get('FIREBASE_DB_URL')
18
 
19
+ class NewsRTDBLogger:
20
+ def __init__(self, db_ref_name='news_sentiment'):
21
+ self.ref = None
22
+ if not all([SA_KEY_JSON, DB_URL]):
23
+ print("NEWS LOGGER: Firebase secrets not set. Logger is disabled.")
24
+ return
25
+ try:
26
+ # The service account key is loaded from a JSON string in the environment variable
27
+ cred_dict = json.loads(SA_KEY_JSON)
28
+ cred = credentials.Certificate(cred_dict)
29
+ if not firebase_admin._apps:
30
+ firebase_admin.initialize_app(cred, {'databaseURL': DB_URL})
31
+ self.ref = db.reference(db_ref_name)
32
+ print(f"NEWS LOGGER: Successfully connected to Firebase RTDB at '{db_ref_name}'.")
33
+ except Exception as e:
34
+ print(f"NEWS LOGGER: CRITICAL ERROR - Failed to initialize: {e}")
35
+
36
+ def log_sentiment(self, pub_date, headline, sentiment, confidence):
37
+ if not self.ref:
38
+ return
39
+ try:
40
+ # Create a unique key based on the timestamp to keep logs ordered
41
+ log_entry = {
42
+ "timestamp_published": pub_date,
43
+ "headline": headline,
44
+ "sentiment": sentiment,
45
+ "confidence_score": float(confidence)
46
+ }
47
+ self.ref.push(log_entry)
48
+ # print(f"NEWS LOGGER: Logged '{headline}'")
49
+ except Exception as e:
50
+ print(f"NEWS LOGGER: CRITICAL ERROR - Could not write sentiment log: {e}")
51
+
52
+ # --- Initialize Global Objects ---
53
+ sentiment_pipeline = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
54
+ news_logger = NewsRTDBLogger() # Initialize the logger
55
+
56
+ # --- Core Functions ---
57
  def fetch_news():
58
+ """Fetches the latest news headlines from the FXStreet RSS feed."""
59
  url = "https://www.fxstreet.com/rss/news"
60
  feed = feedparser.parse(url)
61
+ # Fetch a few more headlines to ensure we get recent, unique ones
62
+ headlines = feed.entries[:15]
63
  return headlines
64
 
65
  def analyze_news():
66
+ """
67
+ Analyzes news sentiment, logs it to Firebase, and returns a DataFrame for display.
68
+ """
69
  headlines = fetch_news()
70
  results = []
71
+
72
  for h in headlines:
73
  text = h.title
74
+ # Get the publication date, fallback to now if not present
75
+ pub_date = h.get("published", datetime.utcnow().isoformat())
76
+
77
+ # Perform sentiment analysis
78
+ pred = sentiment_pipeline(text)[0]
79
  label = pred["label"].lower()
80
  score = round(pred["score"], 3)
81
+
82
  if label == "positive":
83
+ market_sentiment = "Bullish"
84
  elif label == "negative":
85
+ market_sentiment = "Bearish"
86
  else:
87
+ market_sentiment = "Neutral"
88
+
89
+ # Log the result to Firebase
90
+ news_logger.log_sentiment(pub_date, text, market_sentiment, score)
91
+
92
+ results.append([pub_date, text, market_sentiment, score])
93
+
94
+ # Create DataFrame for Gradio output, showing the 7 most recent
95
+ df = pd.DataFrame(results, columns=["Date", "Headline", "Market Sentiment", "Confidence"])
96
+ return df.head(7)
97
 
98
+ # --- Gradio Interface ---
99
  demo = gr.Interface(
100
  fn=analyze_news,
101
  inputs=None,
102
+ outputs=gr.Dataframe(headers=["Date", "Headline", "Market Sentiment", "Confidence"]),
103
+ title="📊 Forex Sentiment Agent (Firebase Edition)",
104
+ description="Live Forex headlines sentiment (Bullish / Bearish / Neutral). Now logging results directly to Firebase.",
105
+ allow_flagging='never'
106
  )
107
 
108
+ if __name__ == "__main__":
109
+ demo.launch()