Spaces:
Paused

Fred808 commited on
Commit
90c3295
·
verified ·
1 Parent(s): a5c837e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -102
app.py CHANGED
@@ -1,19 +1,24 @@
1
  import pandas as pd
2
  import numpy as np
3
  import json
4
- import ast
 
 
 
 
 
 
5
  from sklearn.model_selection import train_test_split
6
  from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
7
  from xgboost import XGBRegressor
8
  from sklearn.linear_model import LogisticRegression
9
  from sklearn.metrics import mean_absolute_error, accuracy_score
10
  from sklearn.preprocessing import LabelEncoder
11
- from textblob import TextBlob
12
- import logging
13
  import matplotlib.pyplot as plt
14
  import seaborn as sns
15
  from collections import Counter
16
- import re
17
 
18
  # Set up logging
19
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
@@ -48,13 +53,19 @@ logging.info("Loading competitor data from JSON...")
48
  try:
49
  with open('competitors_data.json', 'r') as f:
50
  competitor_data = json.load(f)
51
- competitor_df = pd.json_normalize(competitor_data['eazylancer_posts'])
 
 
 
 
 
 
52
  except FileNotFoundError:
53
  logging.error("competitors_data.json not found. Please ensure the file exists.")
54
  exit()
55
 
56
  # Ensure required columns exist in your company's data
57
- required_columns = ['likes', 'comments', 'shares', 'posting_time', 'caption', 'hashtags']
58
  missing_columns = [col for col in required_columns if col not in your_df.columns]
59
 
60
  if missing_columns:
@@ -66,10 +77,12 @@ if missing_columns:
66
  your_df[col] = '' # Fill with default value (empty string)
67
  elif col == 'hashtags':
68
  your_df[col] = [[] for _ in range(len(your_df))] # Fill with default value (list of empty lists)
 
 
69
  logging.info("Default values added for missing columns.")
70
 
71
  # Ensure required columns exist in competitor data
72
- required_columns = ['caption', 'hashtags', 'likes', 'comments', 'date']
73
  missing_columns = [col for col in required_columns if col not in competitor_df.columns]
74
 
75
  if missing_columns:
@@ -79,6 +92,8 @@ if missing_columns:
79
  competitor_df[col] = '' # Fill with default value (empty string)
80
  elif col == 'hashtags':
81
  competitor_df[col] = [[] for _ in range(len(competitor_df))] # Fill with default value (list of empty lists)
 
 
82
  else:
83
  competitor_df[col] = 0 # Fill with default value (integer)
84
  logging.info("Default values added for missing columns.")
@@ -107,100 +122,67 @@ competitor_df['sentiment'] = competitor_df['caption_sentiment']
107
  logging.info("Combining your company's data and competitor data for model training...")
108
  combined_df = pd.concat([your_df, competitor_df], ignore_index=True)
109
 
110
- # Encode categorical columns if they exist
111
- if 'content_type' in combined_df.columns and 'media_type' in combined_df.columns:
112
- logging.info("Encoding categorical columns...")
113
- label_encoder = LabelEncoder()
114
- combined_df['content_type_encoded'] = label_encoder.fit_transform(combined_df['content_type'])
115
- combined_df['media_type_encoded'] = label_encoder.fit_transform(combined_df['media_type'])
116
- features = ['caption_length', 'hashtag_count', 'sentiment', 'content_type_encoded', 'media_type_encoded']
117
- else:
118
- logging.warning("'content_type' or 'media_type' columns not found. Skipping encoding.")
119
- features = ['caption_length', 'hashtag_count', 'sentiment']
120
-
121
- # Log the features being used
122
- logging.info(f"Features for model training: {features}")
123
-
124
- # Viral Potential Prediction
125
- logging.info("Training viral potential prediction model...")
126
- combined_viral_threshold = combined_df['engagement_rate'].quantile(0.9)
127
- combined_df['viral'] = combined_df['engagement_rate'].apply(lambda x: 1 if x >= combined_viral_threshold else 0)
128
-
129
- X = combined_df[features]
130
- y = combined_df['viral']
131
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
132
-
133
- viral_model = RandomForestClassifier(random_state=42)
134
- viral_model.fit(X_train, y_train)
135
- y_pred = viral_model.predict(X_test)
136
- accuracy = accuracy_score(y_test, y_pred)
137
- logging.info(f"Viral Potential Model Accuracy: {accuracy:.4f}")
138
-
139
- # Engagement Rate Prediction
140
- logging.info("Training engagement rate prediction model...")
141
- X = combined_df[features]
142
- y = combined_df['engagement_rate']
143
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
144
-
145
- engagement_model = XGBRegressor(random_state=42)
146
- engagement_model.fit(X_train, y_train)
147
- y_pred = engagement_model.predict(X_test)
148
- mae = mean_absolute_error(y_test, y_pred)
149
- logging.info(f"Engagement Rate Prediction Model - MAE: {mae:.4f}")
150
-
151
- # Promotion Strategy
152
- logging.info("Training promotion prediction model...")
153
- promotion_threshold = combined_df['engagement_rate'].quantile(0.8)
154
- combined_df['promote'] = combined_df['engagement_rate'].apply(lambda x: 1 if x >= promotion_threshold else 0)
155
-
156
- X = combined_df[features]
157
- y = combined_df['promote']
158
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
159
-
160
- promotion_model = LogisticRegression(random_state=42)
161
- promotion_model.fit(X_train, y_train)
162
- y_pred = promotion_model.predict(X_test)
163
- accuracy = accuracy_score(y_test, y_pred)
164
- logging.info(f"Promotion Prediction Model Accuracy: {accuracy:.4f}")
165
-
166
- # Sentiment Analysis
167
- logging.info("Performing sentiment analysis on captions...")
168
- combined_df['sentiment_category'] = combined_df['sentiment'].apply(lambda x: 'Positive' if x > 0 else 'Negative' if x < 0 else 'Neutral')
169
- logging.info("Sentiment Analysis Results:")
170
- print(combined_df['sentiment_category'].value_counts())
171
-
172
- # Niche Trend Analysis
173
- logging.info("Analyzing niche trends...")
174
- if 'content_type' in combined_df.columns:
175
- niche_trends = combined_df.groupby('content_type')['sentiment'].mean().sort_values(ascending=False)
176
- logging.info("Top Performing Content Types by Sentiment:")
177
- print(niche_trends)
178
- else:
179
- logging.warning("'content_type' column not found. Skipping niche trend analysis.")
180
-
181
- # Trending Hashtags
182
- logging.info("Analyzing trending hashtags...")
183
- trending_hashtags = combined_df['hashtags'].explode().value_counts().head(10)
184
- logging.info("Top 10 Trending Hashtags:")
185
- print(trending_hashtags)
186
-
187
- # Trending Keywords
188
- logging.info("Analyzing trending keywords in captions...")
189
- words = combined_df['caption'].apply(lambda x: re.findall(r'\b\w+\b', x.lower())).explode()
190
- trending_keywords = Counter(words).most_common(10)
191
- logging.info("Top 10 Trending Keywords in Captions:")
192
- print(trending_keywords)
193
-
194
- # Engagement Heatmap by Time of Day (using combined data)
195
- logging.info("Creating engagement heatmap by time of day...")
196
- combined_df['hour'] = combined_df['posting_time'].dt.hour
197
- engagement_by_hour = combined_df.groupby('hour')['engagement_rate'].mean().reset_index()
198
-
199
- plt.figure(figsize=(10, 6))
200
- sns.heatmap(engagement_by_hour.pivot_table(index='hour', values='engagement_rate'), annot=True, cmap='YlGnBu')
201
- plt.title('Engagement Heatmap by Time of Day')
202
- plt.xlabel('Engagement Rate')
203
- plt.ylabel('Hour of Day')
204
- plt.show()
205
 
206
  logging.info("Analysis complete!")
 
1
  import pandas as pd
2
  import numpy as np
3
  import json
4
+ import logging
5
+ import re
6
+ import requests
7
+ from io import BytesIO
8
+ from PIL import Image
9
+ import pytesseract
10
+ from textblob import TextBlob
11
  from sklearn.model_selection import train_test_split
12
  from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
13
  from xgboost import XGBRegressor
14
  from sklearn.linear_model import LogisticRegression
15
  from sklearn.metrics import mean_absolute_error, accuracy_score
16
  from sklearn.preprocessing import LabelEncoder
17
+ import torch
18
+ from torchvision import models, transforms
19
  import matplotlib.pyplot as plt
20
  import seaborn as sns
21
  from collections import Counter
 
22
 
23
  # Set up logging
24
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
 
53
  try:
54
  with open('competitors_data.json', 'r') as f:
55
  competitor_data = json.load(f)
56
+ # Combine all competitors' data into a single DataFrame
57
+ competitor_dfs = []
58
+ for competitor, posts in competitor_data.items():
59
+ df = pd.json_normalize(posts)
60
+ df['competitor'] = competitor # Add competitor name for tracking
61
+ competitor_dfs.append(df)
62
+ competitor_df = pd.concat(competitor_dfs, ignore_index=True)
63
  except FileNotFoundError:
64
  logging.error("competitors_data.json not found. Please ensure the file exists.")
65
  exit()
66
 
67
  # Ensure required columns exist in your company's data
68
+ required_columns = ['likes', 'comments', 'shares', 'posting_time', 'caption', 'hashtags', 'image_url']
69
  missing_columns = [col for col in required_columns if col not in your_df.columns]
70
 
71
  if missing_columns:
 
77
  your_df[col] = '' # Fill with default value (empty string)
78
  elif col == 'hashtags':
79
  your_df[col] = [[] for _ in range(len(your_df))] # Fill with default value (list of empty lists)
80
+ elif col == 'image_url':
81
+ your_df[col] = '' # Fill with default value (empty string)
82
  logging.info("Default values added for missing columns.")
83
 
84
  # Ensure required columns exist in competitor data
85
+ required_columns = ['caption', 'hashtags', 'likes', 'comments', 'date', 'image_url']
86
  missing_columns = [col for col in required_columns if col not in competitor_df.columns]
87
 
88
  if missing_columns:
 
92
  competitor_df[col] = '' # Fill with default value (empty string)
93
  elif col == 'hashtags':
94
  competitor_df[col] = [[] for _ in range(len(competitor_df))] # Fill with default value (list of empty lists)
95
+ elif col == 'image_url':
96
+ competitor_df[col] = '' # Fill with default value (empty string)
97
  else:
98
  competitor_df[col] = 0 # Fill with default value (integer)
99
  logging.info("Default values added for missing columns.")
 
122
  logging.info("Combining your company's data and competitor data for model training...")
123
  combined_df = pd.concat([your_df, competitor_df], ignore_index=True)
124
 
125
+ # Extract text from images using OCR
126
+ def extract_text_from_image(image_url):
127
+ """Extract text from an image using OCR."""
128
+ try:
129
+ response = requests.get(image_url)
130
+ image = Image.open(BytesIO(response.content))
131
+ text = pytesseract.image_to_string(image)
132
+ return text
133
+ except Exception as e:
134
+ logging.error(f"Error extracting text from image: {e}")
135
+ return ""
136
+
137
+ logging.info("Extracting text from images...")
138
+ combined_df['image_text'] = combined_df['image_url'].apply(extract_text_from_image)
139
+
140
+ # Analyze image content using a pre-trained model
141
+ def analyze_image(image_url):
142
+ """Analyze image content using a pre-trained model."""
143
+ try:
144
+ response = requests.get(image_url)
145
+ image = Image.open(BytesIO(response.content))
146
+ preprocess = transforms.Compose([
147
+ transforms.Resize(256),
148
+ transforms.CenterCrop(224),
149
+ transforms.ToTensor(),
150
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
151
+ ])
152
+ image_tensor = preprocess(image).unsqueeze(0)
153
+ model = models.resnet50(pretrained=True)
154
+ model.eval()
155
+ with torch.no_grad():
156
+ output = model(image_tensor)
157
+ return output
158
+ except Exception as e:
159
+ logging.error(f"Error analyzing image: {e}")
160
+ return None
161
+
162
+ logging.info("Analyzing image content...")
163
+ combined_df['image_analysis'] = combined_df['image_url'].apply(analyze_image)
164
+
165
+ # Define scoring criteria for posts
166
+ def rate_post(row):
167
+ """Rate a post based on visual appeal, text quality, and predictive metrics."""
168
+ # Visual appeal (image clarity, colors, and elements)
169
+ visual_appeal = 0.5 # Placeholder for image analysis score
170
+
171
+ # Text quality (engagement-focused, sentiment-aligned, or informative)
172
+ text_quality = 0.3 * row['caption_sentiment'] + 0.2 * len(row['caption'])
173
+
174
+ # Predictive metrics (virality potential, relevance to trends)
175
+ predictive_metrics = 0.2 * row['engagement_rate']
176
+
177
+ # Combine factors into a weighted score
178
+ score = 0.4 * visual_appeal + 0.3 * text_quality + 0.3 * predictive_metrics
179
+ return score
180
+
181
+ logging.info("Rating posts...")
182
+ combined_df['post_score'] = combined_df.apply(rate_post, axis=1)
183
+
184
+ # Log the results
185
+ logging.info("Post Ratings:")
186
+ print(combined_df[['post_id', 'post_score']].head())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
  logging.info("Analysis complete!")