Download app.py from conhllnd/dashtest: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/spaces/conhllnd/dashtest/resolve/main/app.py
- Command line
-
hf download hf://spaces/conhllnd/dashtest/app.py
-
curl -L -o app.py https://huggingface.co/spaces/conhllnd/dashtest/resolve/main/app.py
10.8 kB
| 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) |