conhllnd commited on
Commit
105f1ff
·
verified ·
1 Parent(s): a7e527f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -99
app.py CHANGED
@@ -1,34 +1,139 @@
1
  import gradio as gr
2
  import pandas as pd
3
- from huggingface_hub import hf_hub_download
4
  import os
 
 
 
 
 
5
  import plotly.graph_objects as go
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Hugging Face API token and repo setup
8
- hf_token = os.getenv("hfkeymeow") # Ensure your token is correctly stored
9
- repo_id = "conhllnd/Playper-V2" # Repository ID on Hugging Face
10
- repo_type = "space" # Repository type
11
 
12
- # Function to download file from Hugging Face repo
13
- def download_file_from_repo(filename):
14
- file_path = hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type, token=hf_token)
15
- return file_path
16
 
17
  # Function to calculate the follower increase from the CSV
18
  def calculate_follower_increase():
19
- csv_path = download_file_from_repo("Followers.csv") # Download the file from Hugging Face
20
  df = pd.read_csv(csv_path)
21
 
22
  # Ensure proper column naming and strip out any extra spaces
23
  df.columns = df.columns.str.strip()
24
-
25
  # Sort by date to get the two most recent entries
26
  df['Date'] = pd.to_datetime(df['Date'])
27
  df = df.sort_values(by='Date', ascending=False)
28
 
29
  # Get the two most recent entries
30
  recent_data = df.head(2)
31
-
32
  # Calculate the differences for each platform
33
  tiktok_increase = recent_data.iloc[0]['TikTok Followers'] - recent_data.iloc[1]['TikTok Followers']
34
  facebook_increase = recent_data.iloc[0]['Facebook Followers'] - recent_data.iloc[1]['Facebook Followers']
@@ -40,103 +145,27 @@ def calculate_follower_increase():
40
 
41
  # Function to calculate the engagement increase from the CSV
42
  def calculate_engagement_increase():
43
- csv_path = download_file_from_repo("Total Engagement.csv") # Download the file from Hugging Face
44
  df = pd.read_csv(csv_path)
45
 
46
  # Ensure proper column naming and strip out any extra spaces
47
  df.columns = df.columns.str.strip()
48
-
49
  # Sort by date to get the two most recent entries
50
  df['Date'] = pd.to_datetime(df['Date'])
51
  df = df.sort_values(by='Date', ascending=False)
52
 
53
  # Get the two most recent entries
54
  recent_data = df.head(2)
55
-
56
  # Calculate the difference in total engagement
57
  engagement_increase = recent_data.iloc[0]['Total Engagement Across Our Posts'] - recent_data.iloc[1]['Total Engagement Across Our Posts']
58
 
59
  return f"Leonardo got you {int(engagement_increase)} more engagements across TikTok & Facebook!"
60
 
61
- # Function to load and plot the masterpiece data (video and graph)
62
- def load_masterpiece_video_and_plot():
63
- # Download the video file from the Hugging Face repository
64
- masterpiece_video_path = download_file_from_repo("starperformer_viral.mp4")
65
-
66
- # Replace [actual outcome] with the correct label (here it's 'viral' from the filename)
67
- actual_outcome = "viral"
68
-
69
- # Load the data for the TikTok graph
70
- tiktok_csv_path = download_file_from_repo("tiktok_histogram.csv")
71
- df = pd.read_csv(tiktok_csv_path)
72
-
73
- # Assuming the CSV has columns 'Engagement' and 'Density'
74
- x_data = df['Engagement']
75
- y_data = df['Density']
76
-
77
- # Get x_max for the quintile calculation
78
- x_max = max(x_data)
79
-
80
- # Create the plot with actual data
81
- fig = go.Figure()
82
- fig.add_trace(go.Scatter(x=x_data, y=y_data, mode='lines', name="Actual Data"))
83
-
84
- # Highlight the quintile based on the actual outcome
85
- fig = highlight_masterpiece_quintile(fig, actual_outcome, x_max)
86
-
87
- # Return the video path and graph
88
- return masterpiece_video_path, fig
89
-
90
- # Function to highlight the quintile based on prediction label for the masterpiece
91
- def highlight_masterpiece_quintile(fig, actual_outcome, x_max):
92
- label_map = {"normal": 1, "good": 2, "very good": 3, "exceptional": 4, "viral": 5}
93
- quintile = label_map.get(actual_outcome.lower(), 1)
94
-
95
- # Dynamically adjust the x0 and x1 ranges based on x_max
96
- quintile_width = x_max / 5 # Divide x_max into 5 quintiles
97
- x0 = (quintile - 1) * quintile_width
98
- x1 = quintile * quintile_width
99
-
100
- # Add a shaded region in the graph corresponding to the quintile
101
- fig.add_vrect(
102
- x0=x0, x1=x1,
103
- fillcolor="green", opacity=0.25, line_width=0,
104
- annotation_text=f"Actual Outcome: {actual_outcome.capitalize()}"
105
- )
106
- return fig
107
-
108
- # Function to load and plot data (TikTok, Facebook)
109
- def load_data_and_plot(media_type, media_identifier, csv_path, folder_path):
110
- df = pd.read_csv(csv_path)
111
-
112
- # Assuming the CSV has columns 'Engagement' and 'Density'
113
- x_data = df['Engagement']
114
- y_data = df['Density']
115
-
116
- # Create the plot with actual data
117
- fig = go.Figure()
118
- fig.add_trace(go.Scatter(x=x_data, y=y_data, mode='lines', name="Actual Data"))
119
-
120
- # Adjust the x-axis and y-axis
121
- fig.update_layout(
122
- title=f"Predicted Engagement for {media_identifier}",
123
- xaxis=dict(range=[0, max(x_data)]),
124
- yaxis=dict(range=[0, max(y_data)])
125
- )
126
-
127
- media_file_path = None # Assuming you aren't showing media in this function
128
- return media_file_path, fig
129
-
130
  # Create the Gradio interface
131
  with gr.Blocks() as dashboard:
132
 
133
- # Section for Leonardo's Last-Week Masterpiece
134
- gr.Markdown("## Leonardo's Last-Week Masterpiece")
135
- with gr.Row():
136
- masterpiece_video, masterpiece_graph = load_masterpiece_video_and_plot()
137
- gr.Video(masterpiece_video, label="Star Performer TikTok Video")
138
- gr.Plot(masterpiece_graph, label="Star Performer TikTok Performance")
139
-
140
  # Add a header for follower impact
141
  gr.Markdown("## Leonardo's Follower Impact")
142
 
@@ -163,19 +192,19 @@ with gr.Blocks() as dashboard:
163
  # Section for TikTok projections (Videos)
164
  with gr.Row():
165
  with gr.Column():
166
- video_path_1, graph_1 = load_data_and_plot("video", "TikTok1", download_file_from_repo("tiktok_histogram.csv"), download_file_from_repo("video_folder"))
167
  if video_path_1:
168
  gr.Video(video_path_1, label="TikTok 1 Video")
169
  gr.Plot(graph_1, label="TikTok 1 Performance")
170
 
171
  with gr.Column():
172
- video_path_2, graph_2 = load_data_and_plot("video", "TikTok2", download_file_from_repo("tiktok_histogram.csv"), download_file_from_repo("video_folder"))
173
  if video_path_2:
174
  gr.Video(video_path_2, label="TikTok 2 Video")
175
  gr.Plot(graph_2, label="TikTok 2 Performance")
176
 
177
  with gr.Column():
178
- video_path_3, graph_3 = load_data_and_plot("video", "TikTok3", download_file_from_repo("tiktok_histogram.csv"), download_file_from_repo("video_folder"))
179
  if video_path_3:
180
  gr.Video(video_path_3, label="TikTok 3 Video")
181
  gr.Plot(graph_3, label="TikTok 3 Performance")
@@ -183,23 +212,22 @@ with gr.Blocks() as dashboard:
183
  # Section for Facebook projections (Statics)
184
  with gr.Row():
185
  with gr.Column():
186
- image_path_1, graph_4 = load_data_and_plot("image", "Static1", download_file_from_repo("facebook_histogram.csv"), download_file_from_repo("image_folder"))
187
  if image_path_1:
188
  gr.Image(image_path_1, label="Facebook Static 1")
189
  gr.Plot(graph_4, label="Facebook Static 1 Performance")
190
 
191
  with gr.Column():
192
- image_path_2, graph_5 = load_data_and_plot("image", "Static2", download_file_from_repo("facebook_histogram.csv"), download_file_from_repo("image_folder"))
193
  if image_path_2:
194
  gr.Image(image_path_2, label="Facebook Static 2")
195
  gr.Plot(graph_5, label="Facebook Static 2 Performance")
196
 
197
  with gr.Column():
198
- image_path_3, graph_6 = load_data_and_plot("image", "Static3", download_file_from_repo("facebook_histogram.csv"), download_file_from_repo("image_folder"))
199
  if image_path_3:
200
  gr.Image(image_path_3, label="Facebook Static 3")
201
  gr.Plot(graph_6, label="Facebook Static 3 Performance")
202
 
203
  # Launch the dashboard
204
- dashboard.launch(debug=True)
205
-
 
1
  import gradio as gr
2
  import pandas as pd
 
3
  import os
4
+ import gradio as gr
5
+ import plotly.express as px
6
+ import pandas as pd
7
+ import numpy as np
8
+ from scipy.optimize import curve_fit
9
  import plotly.graph_objects as go
10
+ import os
11
+ import datetime
12
+ import logging
13
+
14
+ # Example paths for engagement data
15
+ tiktok_csv_path = "tiktok_histogram.csv"
16
+ facebook_csv_path = "facebook_histogram.csv"
17
+ video_folder = "videos"
18
+ image_folder = "images"
19
+
20
+ # Function to extract the prediction label from filenames
21
+ def extract_prediction_label(filename, media_type):
22
+ if media_type == "video":
23
+ return filename.split('_')[3] # Extracting the label from video filenames
24
+ elif media_type == "image":
25
+ return filename.split('_')[3] # Extracting the label from image filenames
26
+
27
+ # Function to extract the version number from filenames
28
+ def extract_version_number(filename):
29
+ version_with_v = filename.split('_')[1] # Extracting something like 'v1'
30
+ version_number = version_with_v[1:] # Remove the 'v' and keep only the number
31
+ return version_number
32
+
33
+ # Function to get the highest prediction for each TikTok/Static type (e.g., TikTok1, Static2)
34
+ def get_highest_prediction_for_media(folder_path, media_type, media_identifier):
35
+ highest_file = None
36
+ highest_score = None
37
+
38
+ # Loop over all files in the folder
39
+ for filename in os.listdir(folder_path):
40
+ if (media_type == "video" and filename.endswith('.mp4')) or (media_type == "image" and filename.endswith('.jpeg')):
41
+ if media_identifier in filename: # Check for TikTok1, TikTok2, etc.
42
+ # Extract the prediction label from the file
43
+ prediction_label = extract_prediction_label(filename, media_type)
44
+
45
+ label_map = {"normal": 1, "good": 2, "very good": 3, "exceptional": 4, "viral": 5}
46
+ score = label_map.get(prediction_label.lower(), 1) # Default to 1 if not found
47
+
48
+ # Check for highest score
49
+ if highest_score is None or score > highest_score:
50
+ highest_score = score
51
+ highest_file = filename
52
+
53
+ return highest_file
54
+
55
+ # Function to load and plot CSV data directly
56
+ def load_and_plot_csv(csv_path):
57
+ df = pd.read_csv(csv_path)
58
+
59
+ # Assuming the CSV has columns 'Engagement' and 'Density'
60
+ x_data = df['Engagement']
61
+ y_data = df['Density']
62
+
63
+ # Get x_max and y_max for graph range
64
+ x_max = max(x_data)
65
+ y_max = max(y_data)
66
+
67
+ # Create the plot with just the actual data
68
+ fig = go.Figure()
69
+ fig.add_trace(go.Scatter(x=x_data, y=y_data, mode='lines', name="Actual Data"))
70
+
71
+ return fig, x_data.min(), x_max, y_data.min(), y_max
72
+
73
+ # Function to highlight the quintile based on prediction label
74
+ def highlight_quintile(fig, label, x_max):
75
+ label_map = {"normal": 1, "good": 2, "very good": 3, "exceptional": 4, "viral": 5}
76
+ quintile = label_map.get(label.lower(), 1) # Default to normal if label not found
77
+
78
+ # Dynamically adjust the x0 and x1 ranges based on x_max
79
+ quintile_width = x_max / 5 # Divide x_max into 5 quintiles
80
+ x0 = (quintile - 1) * quintile_width
81
+ x1 = quintile * quintile_width
82
+
83
+ # Add a shaded region in the graph corresponding to the quintile
84
+ fig.add_vrect(
85
+ x0=x0, x1=x1,
86
+ fillcolor="green", opacity=0.25, line_width=0,
87
+ annotation_text=f"Predicted: {label.capitalize()}"
88
+ )
89
+ return fig
90
+
91
+ # Function to load video/image and its corresponding engagement data and plot the graph
92
+ def load_data_and_plot(media_type, media_identifier, csv_path, folder_path):
93
+ # Get the file with the highest prediction for the given TikTok/Static type
94
+ media_file = get_highest_prediction_for_media(folder_path, media_type, media_identifier)
95
+
96
+ # Proceed if we found a valid file
97
+ if media_file:
98
+ prediction_label = extract_prediction_label(media_file, media_type)
99
+ version_number = extract_version_number(media_file)
100
+
101
+ # Get the full path to the media file
102
+ media_path = os.path.join(folder_path, media_file)
103
+
104
+ # Load and plot the actual data from the CSV
105
+ fig, x_min, x_max, y_min, y_max = load_and_plot_csv(csv_path)
106
+
107
+ # Highlight the quintile based on the label
108
+ fig = highlight_quintile(fig, prediction_label, x_max)
109
+
110
+ # Ensure the x-axis and y-axis start from 0 and dynamically set max values
111
+ fig.update_layout(
112
+ title=f"Predicted Engagement for {media_identifier} (Version {version_number})", # Show version in title as "Version #"
113
+ xaxis=dict(range=[0, x_max]), # Start from 0 and go up to the max x value
114
+ yaxis=dict(range=[0, y_max]) # Start from 0 and go up to the max y value
115
+ )
116
+
117
+ return media_path, fig
118
+ return None, None
119
 
 
 
 
 
120
 
 
 
 
 
121
 
122
  # Function to calculate the follower increase from the CSV
123
  def calculate_follower_increase():
124
+ csv_path = "/content/drive/My Drive/Client Folder: Playper/Email Updates/Dashboard/Followers.csv" # Use the hardcoded path directly
125
  df = pd.read_csv(csv_path)
126
 
127
  # Ensure proper column naming and strip out any extra spaces
128
  df.columns = df.columns.str.strip()
129
+
130
  # Sort by date to get the two most recent entries
131
  df['Date'] = pd.to_datetime(df['Date'])
132
  df = df.sort_values(by='Date', ascending=False)
133
 
134
  # Get the two most recent entries
135
  recent_data = df.head(2)
136
+
137
  # Calculate the differences for each platform
138
  tiktok_increase = recent_data.iloc[0]['TikTok Followers'] - recent_data.iloc[1]['TikTok Followers']
139
  facebook_increase = recent_data.iloc[0]['Facebook Followers'] - recent_data.iloc[1]['Facebook Followers']
 
145
 
146
  # Function to calculate the engagement increase from the CSV
147
  def calculate_engagement_increase():
148
+ csv_path = "/content/drive/My Drive/Client Folder: Playper/Email Updates/Dashboard/Total Engagement.csv" # Path to the uploaded CSV
149
  df = pd.read_csv(csv_path)
150
 
151
  # Ensure proper column naming and strip out any extra spaces
152
  df.columns = df.columns.str.strip()
153
+
154
  # Sort by date to get the two most recent entries
155
  df['Date'] = pd.to_datetime(df['Date'])
156
  df = df.sort_values(by='Date', ascending=False)
157
 
158
  # Get the two most recent entries
159
  recent_data = df.head(2)
160
+
161
  # Calculate the difference in total engagement
162
  engagement_increase = recent_data.iloc[0]['Total Engagement Across Our Posts'] - recent_data.iloc[1]['Total Engagement Across Our Posts']
163
 
164
  return f"Leonardo got you {int(engagement_increase)} more engagements across TikTok & Facebook!"
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  # Create the Gradio interface
167
  with gr.Blocks() as dashboard:
168
 
 
 
 
 
 
 
 
169
  # Add a header for follower impact
170
  gr.Markdown("## Leonardo's Follower Impact")
171
 
 
192
  # Section for TikTok projections (Videos)
193
  with gr.Row():
194
  with gr.Column():
195
+ video_path_1, graph_1 = load_data_and_plot("video", "TikTok1", tiktok_csv_path, video_folder)
196
  if video_path_1:
197
  gr.Video(video_path_1, label="TikTok 1 Video")
198
  gr.Plot(graph_1, label="TikTok 1 Performance")
199
 
200
  with gr.Column():
201
+ video_path_2, graph_2 = load_data_and_plot("video", "TikTok2", tiktok_csv_path, video_folder)
202
  if video_path_2:
203
  gr.Video(video_path_2, label="TikTok 2 Video")
204
  gr.Plot(graph_2, label="TikTok 2 Performance")
205
 
206
  with gr.Column():
207
+ video_path_3, graph_3 = load_data_and_plot("video", "TikTok3", tiktok_csv_path, video_folder)
208
  if video_path_3:
209
  gr.Video(video_path_3, label="TikTok 3 Video")
210
  gr.Plot(graph_3, label="TikTok 3 Performance")
 
212
  # Section for Facebook projections (Statics)
213
  with gr.Row():
214
  with gr.Column():
215
+ image_path_1, graph_4 = load_data_and_plot("image", "Static1", facebook_csv_path, image_folder)
216
  if image_path_1:
217
  gr.Image(image_path_1, label="Facebook Static 1")
218
  gr.Plot(graph_4, label="Facebook Static 1 Performance")
219
 
220
  with gr.Column():
221
+ image_path_2, graph_5 = load_data_and_plot("image", "Static2", facebook_csv_path, image_folder)
222
  if image_path_2:
223
  gr.Image(image_path_2, label="Facebook Static 2")
224
  gr.Plot(graph_5, label="Facebook Static 2 Performance")
225
 
226
  with gr.Column():
227
+ image_path_3, graph_6 = load_data_and_plot("image", "Static3", facebook_csv_path, image_folder)
228
  if image_path_3:
229
  gr.Image(image_path_3, label="Facebook Static 3")
230
  gr.Plot(graph_6, label="Facebook Static 3 Performance")
231
 
232
  # Launch the dashboard
233
+ dashboard.launch(share=True, debug=True))