Rowan Martnishn commited on
Commit
e574b74
·
verified ·
1 Parent(s): f6fe878

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -0
app.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import schedule
3
+ import time
4
+ import datetime
5
+ import praw
6
+ import joblib
7
+ import scipy.sparse as sp
8
+ import torch.nn as nn
9
+ import pandas as pd
10
+ import re
11
+ import numpy as np
12
+ import matplotlib.pyplot as plt
13
+ from scipy.interpolate import make_interp_spline
14
+ from transformers import AutoTokenizer
15
+ import matplotlib.font_manager as fm
16
+
17
+ # Load models and data (your existing code)
18
+ autovectorizer = joblib.load('AutoVectorizer.pkl')
19
+ autoclassifier = joblib.load('AutoClassifier.pkl')
20
+ MODEL = "cardiffnlp/xlm-twitter-politics-sentiment"
21
+ tokenizer = AutoTokenizer.from_pretrained(MODEL)
22
+
23
+ class ScorePredictor(nn.Module):
24
+ # ... (Your ScorePredictor class)
25
+ def __init__(self, vocab_size, embedding_dim=128, hidden_dim=256, output_dim=1):
26
+ super(ScorePredictor, self).__init__()
27
+ self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)
28
+ self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True)
29
+ self.fc = nn.Linear(hidden_dim, output_dim)
30
+ self.sigmoid = nn.Sigmoid()
31
+
32
+ def forward(self, input_ids, attention_mask):
33
+ embedded = self.embedding(input_ids)
34
+ lstm_out, _ = self.lstm(embedded)
35
+ final_hidden_state = lstm_out[:, -1, :]
36
+ output = self.fc(final_hidden_state)
37
+ return self.sigmoid(output)
38
+
39
+ score_model = ScorePredictor(tokenizer.vocab_size)
40
+ score_model.load_state_dict(torch.load("score_predictor.pth"))
41
+ score_model.eval()
42
+
43
+ sentiment_model = joblib.load('sentiment_forecast_model.pkl')
44
+
45
+ reddit = praw.Reddit(
46
+ client_id="PH99oWZjM43GimMtYigFvA",
47
+ client_secret="3tJsXQKEtFFYInxzLEDqRZ0s_w5z0g",
48
+ user_agent='MyAPI/0.0.1',
49
+ check_for_async=False)
50
+
51
+ subreddits = [
52
+ "florida",
53
+ "ohio",
54
+ "libertarian",
55
+ "southpark",
56
+ "walkaway",
57
+ "truechristian",
58
+ "conservatives"
59
+ ]
60
+
61
+ # Global variables for data
62
+ global prediction_plot_base64
63
+
64
+ def process_data():
65
+ """Fetches data, performs analysis, and generates the plot."""
66
+ global prediction_plot_base64
67
+ end_date = datetime.datetime.utcnow()
68
+ start_date = end_date - datetime.timedelta(days=14)
69
+
70
+ def fetch_all_recent_posts(subreddit_name, start_time, limit=500):
71
+ # ... (Your fetch_all_recent_posts function)
72
+ subreddit = reddit.subreddit(subreddit_name)
73
+ posts = []
74
+
75
+ try:
76
+ for post in subreddit.new(limit=limit): # Fetch recent posts
77
+ post_time = datetime.datetime.utcfromtimestamp(post.created_utc)
78
+ if post_time >= start_time: # Filter only within last 14 days
79
+ posts.append({
80
+ "subreddit": subreddit_name,
81
+ "timestamp": post.created_utc,
82
+ "date": post_time.strftime('%Y-%m-%d %H:%M:%S'),
83
+ "post_text": post.title
84
+ })
85
+ except Exception as e:
86
+ print(f"Error fetching posts from r/{subreddit_name}: {e}")
87
+
88
+ return posts
89
+
90
+ def preprocess_text(text):
91
+ # ... (Your preprocess_text function)
92
+ text = text.lower()
93
+ text = re.sub(r'http\S+', '', text)
94
+ text = re.sub(r'[^a-zA-Z0-9\s.,!?]', '', text)
95
+ text = re.sub(r'\s+', ' ', text).strip()
96
+ return text
97
+
98
+ def predict_score(text):
99
+ # ... (Your predict_score function)
100
+ if not text:
101
+ return 0.0
102
+ max_length = 512
103
+
104
+ encoded_input = tokenizer(
105
+ text.split(),
106
+ return_tensors='pt',
107
+ padding=True,
108
+ truncation=True,
109
+ max_length=max_length
110
+ )
111
+
112
+ input_ids, attention_mask = encoded_input["input_ids"], encoded_input["attention_mask"]
113
+ with torch.no_grad():
114
+ score = score_model(input_ids, attention_mask)[0].item()
115
+ return score
116
+
117
+ start_time = datetime.datetime.utcnow() - datetime.timedelta(days=14)
118
+ all_posts = []
119
+ for sub in subreddits:
120
+ print(f"Fetching posts from r/{sub}")
121
+ posts = fetch_all_recent_posts(sub, start_time)
122
+ all_posts.extend(posts)
123
+ print(f"Fetched {len(posts)} posts from r/{sub}")
124
+
125
+ filtered_posts = []
126
+ for post in all_posts:
127
+ vector = autovectorizer.transform([post['post_text']])
128
+ prediction = autoclassifier.predict(vector)
129
+ if prediction[0] == 1:
130
+ filtered_posts.append(post)
131
+ all_posts = filtered_posts
132
+
133
+ df = pd.DataFrame(all_posts)
134
+ df['date'] = pd.to_datetime(df['date'])
135
+ df['date_only'] = df['date'].dt.date
136
+ df = df.sort_values(by=['date_only'])
137
+ df['sentiment_score'] = df['post_text'].apply(predict_score)
138
+
139
+ last_14_dates = df['date_only'].unique()
140
+ num_dates = min(len(last_14_dates), 14)
141
+ last_14_dates = sorted(last_14_dates, reverse=True)[:num_dates]
142
+
143
+ filtered_df = df[df['date_only'].isin(last_14_dates)]
144
+ daily_sentiment = filtered_df.groupby('date_only')['sentiment_score'].median()
145
+
146
+ if len(daily_sentiment) < 14:
147
+ mean_sentiment = daily_sentiment.mean()
148
+ padding = [mean_sentiment] * (14 - len(daily_sentiment))
149
+ daily_sentiment = np.concatenate([daily_sentiment.values, padding])
150
+ daily_sentiment = pd.Series(daily_sentiment)
151
+
152
+ sentiment_scores_np = daily_sentiment.values.reshape(1, -1)
153
+ prediction = sentiment_model.predict(sentiment_scores_np)
154
+ pred = (prediction[0])
155
+
156
+ font_path = "AfacadFlux-VariableFont_slnt,wght[1].ttf"
157
+ custom_font = fm.FontProperties(fname=font_path)
158
+
159
+ today = datetime.date.today()
160
+ days = [today + datetime.timedelta(days=i) for i in range(7)]
161
+ days_str = [day.strftime('%a %m/%d') for day in days]
162
+
163
+ xnew = np.linspace(0, 6, 300)
164
+ spline = make_interp_spline(np.arange(7), pred, k=3)
165
+ pred_smooth = spline(xnew)
166
+
167
+ fig, ax = plt.subplots(figsize=(12, 7))
168
+ ax.fill_between(xnew, pred_smooth, color='#244B48', alpha=0.4)
169
+ ax.plot(xnew, pred_smooth, color='#244B48', lw=3, label='Forecast')
170
+ ax.scatter(np.arange(7), pred, color='#244B48', s=100, zorder=5)
171
+
172
+ ax.set_title("7-Day Political Sentiment Forecast", fontsize=22, fontweight='bold', pad=20, fontproperties=custom_font)
173
+ ax.set_xlabel("Day", fontsize=16, fontproperties=custom_font)
174
+ ax.set_ylabel("Negative Sentiment (0-1)", fontsize=16, fontproperties=custom_font)
175
+ ax.set_xticks(np.arange(7))
176
+ ax.set_xticklabels(days_str, fontsize=14, fontproperties=custom_font)