data-mining-tp / components /prediction.py
Kacemath's picture
Deploy gradio movie revenue app with model and preprocessing
b490ee7
"""Prediction logic and output formatting."""
from __future__ import annotations
from typing import Any
from src.preprocess import predict_revenue
INPUT_ORDER = [
"budget",
"popularity",
"runtime",
"release_date",
"original_language",
"belongs_to_collection",
"homepage",
"title",
"tagline",
"overview",
"num_of_cast",
"num_of_crew",
"gender_cast_1",
"gender_cast_2",
"count_cast_other",
"genres",
"production_companies",
"keywords",
"cast",
]
def format_currency(value: float) -> str:
"""Format a number as currency."""
if value >= 1_000_000_000:
return f"${value / 1_000_000_000:.2f}B"
elif value >= 1_000_000:
return f"${value / 1_000_000:.2f}M"
else:
return f"${value:,.0f}"
def predict_revenue_from_form(model: Any, *values: Any) -> tuple[str, str]:
"""
Predict revenue from form inputs and return formatted results.
Returns:
Tuple of (prediction_text, profitability_text)
"""
if model is None:
return "❌ Model not available", ""
# Build payload from form values
payload = dict(zip(INPUT_ORDER, values))
payload["belongs_to_collection"] = int(bool(payload.get("belongs_to_collection")))
payload["homepage"] = int(bool(payload.get("homepage")))
payload["has_tagline"] = 1 if str(payload.get("tagline") or "").strip() else 0
try:
prediction = predict_revenue(model, payload)
budget = float(payload.get("budget") or 0.0)
# Format prediction
prediction_text = f"## πŸ’° Predicted Revenue\n### {format_currency(prediction)}"
# Calculate ROI
if budget > 0:
roi = (prediction - budget) / budget * 100
multiple = prediction / budget
if roi > 100:
status = "🟒 **Highly Profitable**"
elif roi > 0:
status = "🟑 **Profitable**"
else:
status = "πŸ”΄ **Loss Expected**"
profitability_text = f"""
{status}
- **Budget:** {format_currency(budget)}
- **Revenue Multiple:** {multiple:.2f}x
- **ROI:** {roi:+.1f}%
- **Estimated Profit:** {format_currency(prediction - budget)}
"""
else:
profitability_text = "ℹ️ Enter a budget to see profitability analysis"
return prediction_text, profitability_text
except Exception as exc:
return f"❌ Prediction Error\n```\n{str(exc)}\n```", ""