File size: 9,171 Bytes
125ae19 c752cde 125ae19 c752cde 125ae19 | 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 | from pathlib import Path
import joblib
import spaces
import gradio as gr
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestRegressor
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
BASE_DIR = Path(__file__).resolve().parent
DATA_PATH = BASE_DIR / "kannada_movies_synthetic_dataset.csv"
TARGET = "Average Monthly Ad Payout"
RANDOM_STATE = 42
# Add these as Hugging Face Space secrets if you want to use the deployed API
# from your notebook instead of the local model:
# API_URL=https://your-modal-or-mlflow-endpoint
# API_TOKEN=optional_token
def normalize_columns(df):
df = df.copy()
df.columns = (
df.columns.str.strip()
.str.replace(r"\s+", "_", regex=True)
.str.replace(r"[()]", "", regex=True)
)
return df
raw_df = normalize_columns(pd.read_csv(DATA_PATH))
target_column = TARGET.replace(" ", "_")
input_df = raw_df.drop(columns=[target_column])
# The saved MLflow signature incorrectly includes the training target as a
# required input. Supply a stable training-data baseline so inference can pass
# schema validation; retrain the model without the target in X to remove this.
target_baseline = int(raw_df[target_column].median())
def make_input_row(
creator_name,
creator_platform,
total_followers,
average_views_per_video,
average_engagement_rate,
years_as_creator,
previous_short_films,
previous_short_film_average_views,
previous_short_film_average_revenue,
tv_appearance_count,
reality_show_participation,
awards_won,
collaboration_creator_popularity_score,
production_budget,
genre,
movie_length,
release_platform,
promotional_posts,
trailer_views,
trailer_engagement_rate,
release_month,
sponsor_count,
brand_partnership_value,
production_house,
):
return {
"Creator_Name": creator_name,
"Creator_Platform": creator_platform,
"Total_Followers": total_followers,
"Average_Views_Per_Video": average_views_per_video,
"Average_Engagement_Rate": average_engagement_rate / 100,
"Years_as_Creator": years_as_creator,
"Number_of_Previous_Short_Films": previous_short_films,
"Previous_Short_Film_Average_Views": previous_short_film_average_views,
"Previous_Short_Film_Average_Revenue": previous_short_film_average_revenue,
"TV_Appearance_Count": tv_appearance_count,
"Reality_Show_Participation": reality_show_participation,
"Awards_Won": awards_won,
"Collaboration_Creator_Popularity_Score": collaboration_creator_popularity_score,
"Production_Budget": production_budget,
"Genre": genre,
"Movie_Length": movie_length,
"Release_Platform": release_platform,
"Number_of_Promotional_Posts": promotional_posts,
"Trailer_Views": trailer_views,
"Trailer_Engagement_Rate": trailer_engagement_rate / 100,
"Release_Month": release_month,
"Sponsor_Count": sponsor_count,
"Brand_Partnership_Value": brand_partnership_value,
"Production_House_if_any": production_house,
}
def add_features(df):
"""Create practical ratio and interaction features."""
df = df.copy()
df["Creator_Name_Length"] = df["Creator_Name"].astype(str).str.len()
df["Has_Production_House"] = (
df["Production_House_if_any"].astype(str).str.lower().ne("independent").astype(int)
)
df["Reality_Show_Participation_Flag"] = (
df["Reality_Show_Participation"].astype(str).str.lower().eq("yes").astype(int)
)
df["Views_per_Follower"] = df["Average_Views_Per_Video"] / df["Total_Followers"].replace(0, np.nan)
df["Trailer_Views_per_Follower"] = df["Trailer_Views"] / df["Total_Followers"].replace(0, np.nan)
df["Budget_per_Minute"] = df["Production_Budget"] / df["Movie_Length"].replace(0, np.nan)
df["Promo_Intensity"] = df["Number_of_Promotional_Posts"] / df["Movie_Length"].replace(0, np.nan)
df["Prior_Revenue_per_Short"] = (
df["Previous_Short_Film_Average_Revenue"]
/ df["Number_of_Previous_Short_Films"].replace(0, np.nan)
)
df["Sponsor_Value_per_Sponsor"] = (
df["Brand_Partnership_Value"] / df["Sponsor_Count"].replace(0, np.nan)
)
df["Audience_Momentum"] = (
df["Average_Views_Per_Video"] * df["Average_Engagement_Rate"]
+ df["Trailer_Views"] * df["Trailer_Engagement_Rate"]
)
df["Experience_Score"] = (
df["Years_as_Creator"]
+ 0.5 * df["Number_of_Previous_Short_Films"]
+ 1.5 * df["Awards_Won"]
+ 0.8 * df["TV_Appearance_Count"]
)
df.replace([np.inf, -np.inf], np.nan, inplace=True)
return df
def build_preprocessor(X):
numeric_features = X.select_dtypes(include=[np.number]).columns.tolist()
categorical_features = X.select_dtypes(include=["object", "category"]).columns.tolist()
numeric_pipeline = Pipeline(
steps=[
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
]
)
categorical_pipeline = Pipeline(
steps=[
("imputer", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]
)
return ColumnTransformer(
transformers=[
("num", numeric_pipeline, numeric_features),
("cat", categorical_pipeline, categorical_features),
],
remainder="drop",
).set_output(transform="default")
preprocessor = build_preprocessor(input_df)
model = joblib.load("model.pkl")
@spaces.GPU
def predict(*inputs):
row = make_input_row(*inputs)
df = add_features(pd.DataFrame([row]))
df[target_column] = target_baseline
prediction_output = model.predict(df)
prediction = float(np.asarray(prediction_output).reshape(-1)[0])
return f"Predicted Average Monthly Ad Payout: ₹{prediction:,.0f}"
def choices(column: str) -> list[str]:
return sorted(input_df[column].dropna().astype(str).unique().tolist())
example = input_df.sample(3, random_state=7).iloc[1]
inputs = [
gr.Textbox(label="Creator Name", value=str(example["Creator_Name"])),
gr.Dropdown(choices("Creator_Platform"), label="Creator Platform", value=str(example["Creator_Platform"])),
gr.Number(label="Total Followers", value=float(example["Total_Followers"])),
gr.Number(label="Average Views Per Video", value=float(example["Average_Views_Per_Video"])),
gr.Slider(0, 20, value=float(example["Average_Engagement_Rate"] * 100), step=0.1,
label="Average Engagement Rate (%)"),
gr.Number(label="Years as Creator", value=float(example["Years_as_Creator"])),
gr.Number(label="Number of Previous Short Films", value=float(example["Number_of_Previous_Short_Films"])),
gr.Number(label="Previous Short Film Average Views", value=float(example["Previous_Short_Film_Average_Views"])),
gr.Number(label="Previous Short Film Average Revenue", value=float(example["Previous_Short_Film_Average_Revenue"])),
gr.Number(label="TV Appearance Count", value=float(example["TV_Appearance_Count"])),
gr.Radio(["Yes", "No"], label="Reality Show Participation", value=str(example["Reality_Show_Participation"])),
gr.Number(label="Awards Won", value=float(example["Awards_Won"])),
gr.Slider(0, 100, value=float(example["Collaboration_Creator_Popularity_Score"]), step=1,
label="Collaboration Creator Popularity Score"),
gr.Number(label="Production Budget", value=float(example["Production_Budget"])),
gr.Dropdown(choices("Genre"), label="Genre", value=str(example["Genre"])),
gr.Number(label="Movie Length", value=float(example["Movie_Length"])),
gr.Dropdown(choices("Release_Platform"), label="Release Platform", value=str(example["Release_Platform"])),
gr.Number(label="Number of Promotional Posts", value=float(example["Number_of_Promotional_Posts"])),
gr.Number(label="Trailer Views", value=float(example["Trailer_Views"])),
gr.Slider(0, 20, value=float(example["Trailer_Engagement_Rate"] * 100), step=0.1,
label="Trailer Engagement Rate (%)"),
gr.Dropdown(choices("Release_Month"), label="Release Month", value=str(example["Release_Month"])),
gr.Number(label="Sponsor Count", value=float(example["Sponsor_Count"])),
gr.Number(label="Brand Partnership Value", value=float(example["Brand_Partnership_Value"])),
gr.Dropdown(choices("Production_House_if_any"), label="Production House",
value=str(example["Production_House_if_any"])),
]
demo = gr.Interface(
fn=predict,
inputs=inputs,
outputs=gr.Textbox(label="Prediction"),
title="Kannada Movie Monthly Payout Predictor",
description="Predict average monthly ad payout from creator, audience, promotion, release, and sponsorship features.",
flagging_mode="never",
)
if __name__ == "__main__":
demo.launch()
|