File size: 10,818 Bytes
4e22ed3
998a052
105f1ff
 
 
 
 
7740bd4
105f1ff
 
 
 
 
 
 
 
 
 
e313b64
 
ac427a8
e313b64
 
d9a4d3c
e313b64
 
 
 
 
 
 
 
 
 
105f1ff
 
 
 
 
2b8c44a
105f1ff
 
2b8c44a
 
 
 
 
 
105f1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2b9c52
105f1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
998a052
91042f5
 
998a052
 
1436d49
998a052
 
 
 
105f1ff
998a052
 
 
 
 
 
105f1ff
998a052
 
 
 
 
 
 
 
 
 
 
1436d49
998a052
 
 
 
105f1ff
998a052
 
 
 
 
 
105f1ff
998a052
 
 
ade15c5
998a052
 
 
e313b64
 
 
 
 
 
 
 
 
 
 
 
998a052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e22ed3
998a052
 
 
 
 
 
 
 
105f1ff
998a052
 
 
 
 
105f1ff
998a052
 
 
 
 
105f1ff
998a052
 
 
 
 
 
 
105f1ff
998a052
 
 
 
 
105f1ff
998a052
 
 
 
 
105f1ff
998a052
 
 
4e22ed3
998a052
db63343
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import gradio as gr
import pandas as pd
import gradio as gr
import plotly.express as px
import pandas as pd
import numpy as np
from scipy.optimize import curve_fit
import plotly.graph_objects as go
import os
import datetime
import logging

# Example paths for engagement data
tiktok_csv_path = "tiktok_histogram.csv"
facebook_csv_path = "facebook_histogram.csv"
video_folder = "videos"
image_folder = "images"

# Function to load and plot the masterpiece data (video and graph)
def load_masterpiece_video_and_plot():
    masterpiece_video_path = os.path.join("starperformer_normal.mp4")

    # Assuming 'viral' is the actual outcome from the video filename
    actual_outcome = "normal"

    # Load the TikTok engagement data from the CSV
    fig, x_min, x_max, y_min, y_max = load_and_plot_csv(tiktok_csv_path)

    # Highlight the quintile based on the actual outcome 'viral'
    fig = highlight_quintile(fig, actual_outcome, x_max)

    return masterpiece_video_path, fig


# Function to extract the prediction label from filenames
def extract_prediction_label(filename, media_type):
    if media_type == "video":
        return filename.split('_')[3]  # Extracting the label from video filenames
    elif media_type == "image":
        return filename.split('_')[3]  # Extracting the label from image filenames

# Function to extract the version number from filenames
def extract_version_number(filename, media_type):
    if media_type == "video":
        version_with_v = filename.split('_')[1]  # For videos, version is at index 1
    elif media_type == "image":
        version_with_v = filename.split('_')[2]  # For images, version is at index 2
    
    version_number = version_with_v[1:]  # Remove the 'v' and keep only the number
    return version_number

# Function to get the highest prediction for each TikTok/Static type (e.g., TikTok1, Static2)
def get_highest_prediction_for_media(folder_path, media_type, media_identifier):
    highest_file = None
    highest_score = None

    # Loop over all files in the folder
    for filename in os.listdir(folder_path):
        if (media_type == "video" and filename.endswith('.mp4')) or (media_type == "image" and filename.endswith('.jpeg')):
            if media_identifier in filename:  # Check for TikTok1, TikTok2, etc.
                # Extract the prediction label from the file
                prediction_label = extract_prediction_label(filename, media_type)

                label_map = {"normal": 1, "good": 2, "very good": 3, "exceptional": 4, "viral": 5}
                score = label_map.get(prediction_label.lower(), 1)  # Default to 1 if not found

                # Check for highest score
                if highest_score is None or score > highest_score:
                    highest_score = score
                    highest_file = filename

    return highest_file

# Function to load and plot CSV data directly
def load_and_plot_csv(csv_path):
    df = pd.read_csv(csv_path)

    # Assuming the CSV has columns 'Engagement' and 'Density'
    x_data = df['Engagement']
    y_data = df['Density']

    # Get x_max and y_max for graph range
    x_max = max(x_data)
    y_max = max(y_data)

    # Create the plot with just the actual data
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=x_data, y=y_data, mode='lines', name="Actual Data"))

    return fig, x_data.min(), x_max, y_data.min(), y_max

# Function to highlight the quintile based on prediction label
def highlight_quintile(fig, label, x_max):
    label_map = {"normal": 1, "good": 2, "very good": 3, "exceptional": 4, "viral": 5}
    quintile = label_map.get(label.lower(), 1)  # Default to normal if label not found

    # Dynamically adjust the x0 and x1 ranges based on x_max
    quintile_width = x_max / 5  # Divide x_max into 5 quintiles
    x0 = (quintile - 1) * quintile_width
    x1 = quintile * quintile_width

    # Add a shaded region in the graph corresponding to the quintile
    fig.add_vrect(
        x0=x0, x1=x1,
        fillcolor="green", opacity=0.25, line_width=0,
        annotation_text=f"Predicted: {label.capitalize()}"
    )
    return fig

# Function to load video/image and its corresponding engagement data and plot the graph
def load_data_and_plot(media_type, media_identifier, csv_path, folder_path):
    # Get the file with the highest prediction for the given TikTok/Static type
    media_file = get_highest_prediction_for_media(folder_path, media_type, media_identifier)

    # Proceed if we found a valid file
    if media_file:
        prediction_label = extract_prediction_label(media_file, media_type)
        version_number = extract_version_number(media_file, media_type)

        # Get the full path to the media file
        media_path = os.path.join(folder_path, media_file)

        # Load and plot the actual data from the CSV
        fig, x_min, x_max, y_min, y_max = load_and_plot_csv(csv_path)

        # Highlight the quintile based on the label
        fig = highlight_quintile(fig, prediction_label, x_max)

        # Ensure the x-axis and y-axis start from 0 and dynamically set max values
        fig.update_layout(
            title=f"Predicted Engagement for {media_identifier} (Version {version_number})",  # Show version in title as "Version #"
            xaxis=dict(range=[0, x_max]),  # Start from 0 and go up to the max x value
            yaxis=dict(range=[0, y_max])   # Start from 0 and go up to the max y value
        )

        return media_path, fig
    return None, None



# Function to calculate the follower increase from the CSV
def calculate_follower_increase():
    csv_path = "Followers.csv"  # Use the hardcoded path directly
    df = pd.read_csv(csv_path)

    # Ensure proper column naming and strip out any extra spaces
    df.columns = df.columns.str.strip()

    # Sort by date to get the two most recent entries
    df['Date'] = pd.to_datetime(df['Date'])
    df = df.sort_values(by='Date', ascending=False)

    # Get the two most recent entries
    recent_data = df.head(2)

    # Calculate the differences for each platform
    tiktok_increase = recent_data.iloc[0]['TikTok Followers'] - recent_data.iloc[1]['TikTok Followers']
    facebook_increase = recent_data.iloc[0]['Facebook Followers'] - recent_data.iloc[1]['Facebook Followers']

    # Calculate the total increase across platforms
    total_increase = tiktok_increase + facebook_increase

    return f"Leonardo got you {int(total_increase)} more followers across TikTok & Facebook!"

# Function to calculate the engagement increase from the CSV
def calculate_engagement_increase():
    csv_path = "Total Engagement.csv"  # Path to the uploaded CSV
    df = pd.read_csv(csv_path)

    # Ensure proper column naming and strip out any extra spaces
    df.columns = df.columns.str.strip()

    # Sort by date to get the two most recent entries
    df['Date'] = pd.to_datetime(df['Date'])
    df = df.sort_values(by='Date', ascending=False)

    # Get the two most recent entries
    recent_data = df.head(2)

    # Calculate the difference in total engagement
    engagement_increase = recent_data.iloc[0]['Total Engagement Across Our Posts'] - recent_data.iloc[1]['Total Engagement Across Our Posts']

    return f"Leonardo got you {int(engagement_increase)} more engagements than last week on Instagram!"

# Create the Gradio interface
with gr.Blocks() as dashboard:
    # Section for Leonardo's Last-Week Masterpiece
    gr.Markdown("# Leonardo's Masterpiece from Last Week")
    
    # Load the masterpiece video and graph
    masterpiece_video, masterpiece_graph = load_masterpiece_video_and_plot()
    
    # Display the video
    gr.Video(masterpiece_video, label="Star Performer TikTok Video")
    
    # Display the graph with quintile highlighting
    gr.Plot(masterpiece_graph, label="Star Performer TikTok Performance")
    
    # Add a header for follower impact
    gr.Markdown("## Leonardo's Follower Impact")

    # Create the textbox for follower count (initial message)
    follower_text = gr.Textbox(label="Follower Update", value="Click the button to see the increase.", interactive=False)

    # Add the button and set it to update the follower count
    with gr.Row():
        gr.Button("See New Followers").click(fn=calculate_follower_increase, inputs=[], outputs=[follower_text])

    # Add a header for engagement impact
    gr.Markdown("## Leonardo's Engagement Impact")

    # Create the textbox for engagement count (initial message)
    engagement_text = gr.Textbox(label="Engagement Update", value="Click the button to see the increase.", interactive=False)

    # Add the button and set it to update the engagement count
    with gr.Row():
        gr.Button("See New Engagement").click(fn=calculate_engagement_increase, inputs=[], outputs=[engagement_text])

    # Add the main title
    gr.Markdown("# Leonardo's Plans for This Week")

    # Section for TikTok projections (Videos)
    with gr.Row():
        with gr.Column():
            video_path_1, graph_1 = load_data_and_plot("video", "TikTok1", tiktok_csv_path, video_folder)
            if video_path_1:
                gr.Video(video_path_1, label="TikTok 1 Video")
                gr.Plot(graph_1, label="TikTok 1 Performance")

        with gr.Column():
            video_path_2, graph_2 = load_data_and_plot("video", "TikTok2", tiktok_csv_path, video_folder)
            if video_path_2:
                gr.Video(video_path_2, label="TikTok 2 Video")
                gr.Plot(graph_2, label="TikTok 2 Performance")

        with gr.Column():
            video_path_3, graph_3 = load_data_and_plot("video", "TikTok3", tiktok_csv_path, video_folder)
            if video_path_3:
                gr.Video(video_path_3, label="TikTok 3 Video")
                gr.Plot(graph_3, label="TikTok 3 Performance")

    # Section for Facebook projections (Statics)
    with gr.Row():
        with gr.Column():
            image_path_1, graph_4 = load_data_and_plot("image", "Static1", facebook_csv_path, image_folder)
            if image_path_1:
                gr.Image(image_path_1, label="Facebook Static 1")
                gr.Plot(graph_4, label="Facebook Static 1 Performance")

        with gr.Column():
            image_path_2, graph_5 = load_data_and_plot("image", "Static2", facebook_csv_path, image_folder)
            if image_path_2:
                gr.Image(image_path_2, label="Facebook Static 2")
                gr.Plot(graph_5, label="Facebook Static 2 Performance")

        with gr.Column():
            image_path_3, graph_6 = load_data_and_plot("image", "Static3", facebook_csv_path, image_folder)
            if image_path_3:
                gr.Image(image_path_3, label="Facebook Static 3")
                gr.Plot(graph_6, label="Facebook Static 3 Performance")

# Launch the dashboard
dashboard.launch(share=True, debug=True)