Spaces:
Paused

Fred808 commited on
Commit
f3bb3c7
·
verified ·
1 Parent(s): 64d5896

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -146
app.py CHANGED
@@ -49,154 +49,94 @@ except FileNotFoundError:
49
  logging.error("solved.json not found. Please ensure the file exists.")
50
  exit()
51
 
52
- # Check for required columns in engagement data
53
- required_columns = ['posting_time', 'likes', 'comments', 'shares']
54
- missing_columns = [col for col in required_columns if col not in engagement_df.columns]
 
 
 
 
 
 
 
 
 
 
55
 
56
  if missing_columns:
57
- logging.warning(f"Missing required columns in engagement_metrics.json: {missing_columns}")
58
  for col in missing_columns:
59
- engagement_df[col] = 0 # Fill with default value
60
  logging.info("Default values added for missing columns.")
61
 
62
- # Handle missing values in engagement data
63
- engagement_df.fillna({
64
- 'likes': 0,
65
- 'comments': 0,
66
- 'shares': 0
67
- }, inplace=True)
 
 
 
 
 
 
 
 
 
68
 
69
  # Calculate engagement_rate
70
- engagement_df['engagement_rate'] = engagement_df['likes'] + engagement_df['comments'] + engagement_df['shares']
71
 
72
- # Convert posting_time to datetime in engagement data
73
- logging.info("Converting posting_time to datetime...")
74
- engagement_df['posting_time'] = pd.to_datetime(engagement_df['posting_time'], format='%Y-%m-%d %H:%M:%S', errors='coerce')
 
75
 
76
- # Ensure 'caption' is treated as a string column in solved data
77
- solved_df['caption'] = solved_df['caption'].astype(str)
 
 
78
 
79
- # Extract hashtags from the solved data (already provided as a list)
80
- logging.info("Extracting hashtags from solved data...")
81
- solved_df['hashtags'] = solved_df['hashtags'].apply(lambda x: x if isinstance(x, list) else [])
 
82
 
83
- # Filter out rows with invalid posting_time in engagement data
84
- engagement_df = engagement_df[engagement_df['posting_time'].notna()]
85
 
86
- # Ensure required columns exist in the solved dataset
 
 
 
 
87
  if 'content_type' not in solved_df.columns:
 
88
  solved_df['content_type'] = 'photo' # Default value (adjust based on your data)
89
 
90
- if 'media_type' not in solved_df.columns:
91
- solved_df['media_type'] = 'image' # Default value (adjust based on your data)
 
92
 
93
- # Encode categorical columns in the solved dataset
94
- label_encoder = LabelEncoder()
95
- solved_df['content_type_encoded'] = label_encoder.fit_transform(solved_df['content_type'])
96
- solved_df['media_type_encoded'] = label_encoder.fit_transform(solved_df['media_type'])
97
 
98
- # Calculate sentiment for captions in the solved dataset
99
- logging.info("Performing sentiment analysis on captions...")
100
- solved_df['caption_sentiment'] = solved_df['caption'].apply(lambda x: TextBlob(x).sentiment.polarity)
 
 
101
 
102
- # Use caption sentiment as the overall sentiment
103
- solved_df['sentiment'] = solved_df['caption_sentiment']
104
-
105
- # Feature Engineering in the solved dataset
106
- logging.info("Performing feature engineering...")
107
- solved_df['caption_length'] = solved_df['caption'].apply(len)
108
- solved_df['hashtag_count'] = solved_df['hashtags'].apply(len)
109
-
110
- # Analyze engagement data separately
111
- logging.info("Analyzing engagement data separately...")
112
- engagement_summary = engagement_df.groupby('posting_time').agg({
113
- 'likes': 'sum',
114
- 'comments': 'sum',
115
- 'shares': 'sum',
116
- 'engagement_rate': 'mean'
117
- }).reset_index()
118
-
119
- # Plot engagement rate over time
120
- plt.figure(figsize=(10, 6))
121
- plt.plot(engagement_summary['posting_time'], engagement_summary['engagement_rate'])
122
- plt.title('Engagement Rate Over Time')
123
- plt.xlabel('Time')
124
- plt.ylabel('Engagement Rate')
125
- plt.show()
126
-
127
- # Time-Series Model: Optimal Posting Times (using Prophet)
128
- logging.info("Training time-series model for optimal posting times using Prophet...")
129
- time_series_data = engagement_summary[['posting_time', 'engagement_rate']].rename(columns={'posting_time': 'ds', 'engagement_rate': 'y'})
130
-
131
- # Train Prophet model
132
- prophet_model = Prophet()
133
- prophet_model.fit(time_series_data)
134
-
135
- # Make future predictions
136
- future = prophet_model.make_future_dataframe(periods=30) # Predict for the next 30 days
137
- forecast = prophet_model.predict(future)
138
-
139
- # Plot the forecast
140
- fig = prophet_model.plot(forecast)
141
- plt.title('Engagement Rate Forecast (Prophet)')
142
- plt.xlabel('Date')
143
- plt.ylabel('Engagement Rate')
144
- plt.show()
145
-
146
- # Evaluate the model
147
- from sklearn.metrics import mean_absolute_error
148
- y_true = time_series_data['y']
149
- y_pred = forecast.loc[:len(y_true)-1, 'yhat'] # Align predictions with true values
150
- mae = mean_absolute_error(y_true, y_pred)
151
- logging.info(f"Prophet Model - MAE: {mae:.4f}")
152
-
153
- # Ensure 'hashtags' column is properly formatted
154
- solved_df['hashtags'] = solved_df['hashtags'].apply(lambda x: x if isinstance(x, list) and len(x) > 0 else ['no_hashtag'])
155
-
156
- # Recommendation System: Hashtag and Keyword Recommendations (using solved dataset)
157
- logging.info("Training recommendation system for hashtags...")
158
- hashtags = solved_df['hashtags'].apply(lambda x: ' '.join(x)) # Convert list of hashtags to a single string
159
-
160
- # Check if hashtags are empty
161
- if hashtags.str.strip().eq('').all():
162
- logging.warning("The 'hashtags' column is empty or contains only stop words. Skipping recommendation system.")
163
- else:
164
- vectorizer = TfidfVectorizer()
165
- tfidf_matrix = vectorizer.fit_transform(hashtags)
166
- cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)
167
-
168
- def recommend_hashtags(post_index, top_n=5):
169
- sim_scores = list(enumerate(cosine_sim[post_index]))
170
- sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
171
- top_indices = [i[0] for i in sim_scores[1:top_n+1]]
172
- return solved_df.iloc[top_indices]['hashtags']
173
-
174
- # Example: Recommend hashtags for the first post
175
- logging.info("Example Hashtag Recommendations:")
176
- print(recommend_hashtags(0))
177
-
178
- # Sentiment Analysis: Audience Reactions (using solved dataset)
179
- logging.info("Performing sentiment analysis on captions...")
180
- solved_df['sentiment_category'] = solved_df['sentiment'].apply(lambda x: 'Positive' if x > 0 else 'Negative' if x < 0 else 'Neutral')
181
- logging.info("Sentiment Analysis Results:")
182
- print(solved_df['sentiment_category'].value_counts())
183
-
184
- # Niche Trend Analysis (using solved dataset)
185
- logging.info("Analyzing niche trends...")
186
- niche_trends = solved_df.groupby('content_type')['sentiment'].mean().sort_values(ascending=False)
187
- logging.info("Top Performing Content Types by Sentiment:")
188
- print(niche_trends)
189
-
190
- # Viral Potential of Posts
191
- logging.info("Training model for viral potential prediction...")
192
- viral_threshold = engagement_df['engagement_rate'].quantile(0.9)
193
- engagement_df['viral'] = engagement_df['engagement_rate'].apply(lambda x: 1 if x >= viral_threshold else 0)
194
- solved_df['viral'] = engagement_df['viral']
195
 
196
  # Features for viral potential prediction
197
  features = ['caption_length', 'hashtag_count', 'sentiment', 'content_type_encoded', 'media_type_encoded']
198
- X = solved_df[features]
199
- y = solved_df['viral']
200
 
201
  # Split data into training and testing sets
202
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
@@ -208,18 +148,17 @@ viral_model.fit(X_train, y_train)
208
  # Evaluate the model
209
  y_pred = viral_model.predict(X_test)
210
  accuracy = accuracy_score(y_test, y_pred)
211
- logging.info(f"Viral Potential Model Accuracy: {accuracy:.4f}")
212
 
213
  # Feature importance
214
  importance = viral_model.feature_importances_
215
  for feature, score in zip(features, importance):
216
  logging.info(f"Feature Importance - {feature}: {score:.4f}")
217
 
218
- # Engagement Rate Predictions
219
- logging.info("Training model for engagement rate prediction...")
220
- features = ['caption_length', 'hashtag_count', 'sentiment', 'content_type_encoded', 'media_type_encoded']
221
- X = solved_df[features]
222
- y = engagement_df['engagement_rate']
223
 
224
  # Split data into training and testing sets
225
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
@@ -231,23 +170,21 @@ engagement_model.fit(X_train, y_train)
231
  # Evaluate the model
232
  y_pred = engagement_model.predict(X_test)
233
  mae = mean_absolute_error(y_test, y_pred)
234
- logging.info(f"Engagement Rate Prediction Model - MAE: {mae:.4f}")
235
 
236
  # Feature importance
237
  importance = engagement_model.feature_importances_
238
  for feature, score in zip(features, importance):
239
  logging.info(f"Feature Importance - {feature}: {score:.4f}")
240
 
241
- # Which Type of Posts Yield Greater Results When Promoted
242
- logging.info("Training model for promotion prediction...")
243
- promotion_threshold = engagement_df['engagement_rate'].quantile(0.8)
244
- engagement_df['promote'] = engagement_df['engagement_rate'].apply(lambda x: 1 if x >= promotion_threshold else 0)
245
- solved_df['promote'] = engagement_df['promote']
246
 
247
  # Features for promotion prediction
248
- features = ['caption_length', 'hashtag_count', 'sentiment', 'content_type_encoded', 'media_type_encoded']
249
- X = solved_df[features]
250
- y = solved_df['promote']
251
 
252
  # Split data into training and testing sets
253
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
@@ -259,11 +196,11 @@ promotion_model.fit(X_train, y_train)
259
  # Evaluate the model
260
  y_pred = promotion_model.predict(X_test)
261
  accuracy = accuracy_score(y_test, y_pred)
262
- logging.info(f"Promotion Prediction Model Accuracy: {accuracy:.4f}")
263
 
264
  # Analyze content type impact
265
- content_type_impact = solved_df.groupby('content_type')['promote'].mean().sort_values(ascending=False)
266
- logging.info("Content Type Impact on Promotion:")
267
  print(content_type_impact)
268
 
269
- logging.info("Analysis complete!")
 
49
  logging.error("solved.json not found. Please ensure the file exists.")
50
  exit()
51
 
52
+ # Load competitor data from JSON
53
+ logging.info("Loading competitor data from JSON...")
54
+ try:
55
+ with open('competitors_data.json', 'r') as f:
56
+ competitor_data = json.load(f)
57
+ competitor_df = pd.json_normalize(competitor_data['eazylancer_posts'])
58
+ except FileNotFoundError:
59
+ logging.error("competitors_data.json not found. Please ensure the file exists.")
60
+ exit()
61
+
62
+ # Ensure required columns exist in competitor data
63
+ required_columns = ['caption', 'hashtags', 'likes', 'comments', 'date']
64
+ missing_columns = [col for col in required_columns if col not in competitor_df.columns]
65
 
66
  if missing_columns:
67
+ logging.warning(f"Missing required columns in competitor data: {missing_columns}")
68
  for col in missing_columns:
69
+ competitor_df[col] = '' if col == 'caption' else [] if col == 'hashtags' else 0
70
  logging.info("Default values added for missing columns.")
71
 
72
+ # Process competitor data
73
+ logging.info("Processing competitor data...")
74
+
75
+ # Convert 'caption' to string
76
+ competitor_df['caption'] = competitor_df['caption'].astype(str)
77
+
78
+ # Convert 'hashtags' to list (if stored as a string)
79
+ if isinstance(competitor_df['hashtags'].iloc[0], str):
80
+ competitor_df['hashtags'] = competitor_df['hashtags'].apply(ast.literal_eval)
81
+
82
+ # Convert 'date' to datetime
83
+ competitor_df['posting_time'] = pd.to_datetime(competitor_df['date'], format='%Y-%m-%d %H:%M:%S', errors='coerce')
84
+
85
+ # Drop rows with invalid posting_time
86
+ competitor_df = competitor_df[competitor_df['posting_time'].notna()]
87
 
88
  # Calculate engagement_rate
89
+ competitor_df['engagement_rate'] = competitor_df['likes'] + competitor_df['comments']
90
 
91
+ # Perform sentiment analysis on captions
92
+ logging.info("Performing sentiment analysis on captions...")
93
+ competitor_df['caption_sentiment'] = competitor_df['caption'].apply(lambda x: TextBlob(x).sentiment.polarity)
94
+ competitor_df['sentiment'] = competitor_df['caption_sentiment']
95
 
96
+ # Feature engineering
97
+ logging.info("Performing feature engineering...")
98
+ competitor_df['caption_length'] = competitor_df['caption'].apply(len)
99
+ competitor_df['hashtag_count'] = competitor_df['hashtags'].apply(len)
100
 
101
+ # Ensure 'is_video' exists in competitor_df
102
+ if 'is_video' not in competitor_df.columns:
103
+ logging.warning("'is_video' column not found in competitor data. Adding a default value.")
104
+ competitor_df['is_video'] = False # Default value (assume it's not a video)
105
 
106
+ # Set 'content_type' based on 'is_video'
107
+ competitor_df['content_type'] = competitor_df['is_video'].apply(lambda x: 'video' if x else 'photo')
108
 
109
+ # Log the updated competitor DataFrame
110
+ logging.info("Updated Competitor DataFrame with 'content_type':")
111
+ print(competitor_df[['is_video', 'content_type']].head())
112
+
113
+ # Ensure 'content_type' exists in solved_df
114
  if 'content_type' not in solved_df.columns:
115
+ logging.warning("'content_type' column not found in solved data. Adding a default value.")
116
  solved_df['content_type'] = 'photo' # Default value (adjust based on your data)
117
 
118
+ # Combine your data with competitor data for enhanced analysis
119
+ logging.info("Combining your data with competitor data...")
120
+ combined_df = pd.concat([solved_df, competitor_df], ignore_index=True)
121
 
122
+ # Log the column names of the combined DataFrame
123
+ logging.info(f"Combined DataFrame Columns: {combined_df.columns.tolist()}")
 
 
124
 
125
+ # Enhanced niche trend analysis using combined data
126
+ logging.info("Analyzing enhanced niche trends using combined data...")
127
+ combined_niche_trends = combined_df.groupby('content_type')['sentiment'].mean().sort_values(ascending=False)
128
+ logging.info("Top Performing Content Types by Sentiment (Combined Data):")
129
+ print(combined_niche_trends)
130
 
131
+ # Enhanced viral potential prediction using combined data
132
+ logging.info("Training enhanced viral potential prediction model using combined data...")
133
+ combined_viral_threshold = combined_df['engagement_rate'].quantile(0.9)
134
+ combined_df['viral'] = combined_df['engagement_rate'].apply(lambda x: 1 if x >= combined_viral_threshold else 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  # Features for viral potential prediction
137
  features = ['caption_length', 'hashtag_count', 'sentiment', 'content_type_encoded', 'media_type_encoded']
138
+ X = combined_df[features]
139
+ y = combined_df['viral']
140
 
141
  # Split data into training and testing sets
142
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
148
  # Evaluate the model
149
  y_pred = viral_model.predict(X_test)
150
  accuracy = accuracy_score(y_test, y_pred)
151
+ logging.info(f"Enhanced Viral Potential Model Accuracy: {accuracy:.4f}")
152
 
153
  # Feature importance
154
  importance = viral_model.feature_importances_
155
  for feature, score in zip(features, importance):
156
  logging.info(f"Feature Importance - {feature}: {score:.4f}")
157
 
158
+ # Enhanced engagement rate predictions using combined data
159
+ logging.info("Training enhanced engagement rate prediction model using combined data...")
160
+ X = combined_df[features]
161
+ y = combined_df['engagement_rate']
 
162
 
163
  # Split data into training and testing sets
164
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
170
  # Evaluate the model
171
  y_pred = engagement_model.predict(X_test)
172
  mae = mean_absolute_error(y_test, y_pred)
173
+ logging.info(f"Enhanced Engagement Rate Prediction Model - MAE: {mae:.4f}")
174
 
175
  # Feature importance
176
  importance = engagement_model.feature_importances_
177
  for feature, score in zip(features, importance):
178
  logging.info(f"Feature Importance - {feature}: {score:.4f}")
179
 
180
+ # Enhanced promotion strategy using combined data
181
+ logging.info("Training enhanced promotion prediction model using combined data...")
182
+ promotion_threshold = combined_df['engagement_rate'].quantile(0.8)
183
+ combined_df['promote'] = combined_df['engagement_rate'].apply(lambda x: 1 if x >= promotion_threshold else 0)
 
184
 
185
  # Features for promotion prediction
186
+ X = combined_df[features]
187
+ y = combined_df['promote']
 
188
 
189
  # Split data into training and testing sets
190
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
196
  # Evaluate the model
197
  y_pred = promotion_model.predict(X_test)
198
  accuracy = accuracy_score(y_test, y_pred)
199
+ logging.info(f"Enhanced Promotion Prediction Model Accuracy: {accuracy:.4f}")
200
 
201
  # Analyze content type impact
202
+ content_type_impact = combined_df.groupby('content_type')['promote'].mean().sort_values(ascending=False)
203
+ logging.info("Enhanced Content Type Impact on Promotion:")
204
  print(content_type_impact)
205
 
206
+ logging.info("Enhanced analysis complete!")