Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,24 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
import numpy as np
|
| 3 |
import json
|
| 4 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 12 |
-
import
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
#
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
logging.info(
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 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!")
|