Build a Smart Netflix Dashboard That Answers You with Charts
What if you could ask a dataset a question—and get back a chart?
In this beginner-friendly tutorial, you’ll create a Streamlit app that does exactly that:
- Loads Netflix data into your browser
- Lets you ask questions using plain English
- Uses AI to answer your question and dynamically generate a chart
No coding experience? No problem. Follow these steps and you'll have it running locally in minutes.
π§° What You’ll Need
- Python installed from python.org
- Netflix dataset from
Kaggle - Netflix Shows
- A free OpenAI API key from
platform.openai.com
You may need to pre-purchase credits to use the API in this sample app.
π Setup Instructions
- Create a folder called
netflix-ai-dashboard
- Place
netflix_titles.csv
inside that folder
- Install the required Python libraries:
pip install streamlit pandas matplotlib openai
π Full App Code (app.py
)
Create a new file called
app.py
inside your folder and paste this entire code:
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from openai import OpenAI
import io
import re
import textwrap
st.set_page_config(page_title="Netflix AI Chart Assistant", layout="centered")
st.title("πΊ Ask AI to Analyze Netflix Data & Generate Charts")
# Load Netflix dataset
@st.cache_data
def load_data():
df = pd.read_csv("netflix_titles.csv")
df.dropna(subset=["type", "release_year", "country"], inplace=True)
return df
df = load_data()
# Dataset preview
with st.expander("π Preview Netflix Data"):
st.dataframe(df.head(20))
# User inputs
st.subheader("π€ Ask AI About the Netflix Data")
api_key = st.text_input("Enter your OpenAI API Key", type="password")
st.caption("Don't have a key? Get one at [platform.openai.com](https://platform.openai.com/account/api-keys)")
st.markdown(":warning: **Note:** If you see a quota or billing error, you may need to [add credits to your OpenAI account](https://platform.openai.com/account/billing).")
question = st.text_area("Ask a question about the dataset", placeholder="e.g. What countries produce the most Netflix content?")
# Ask AI and Generate Chart
if st.button("Ask AI and Generate Chart"):
if not api_key or not question:
st.warning("Please enter both your API key and a question.")
else:
with st.spinner("Asking AI..."):
try:
client = OpenAI(api_key=api_key)
# Limit data sent to AI for performance
data_csv = df.head(100).to_csv(index=False)
# Compose the prompt
prompt = f"""
You are a helpful data analyst. Based on the Netflix data sample below:
{data_csv}
Answer this question: "{question}"
Your response should include:
1. A short written answer
2. A markdown summary table (max 10 rows)
3. A Python matplotlib code block to generate a relevant chart using the sample data (assume it's in a DataFrame called df)
Only include one chart. Return the Python code as a single code block.
"""
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.5
)
reply = response.choices[0].message.content
st.markdown("### π§ AI Analysis:")
st.markdown(reply)
# Extract and execute chart code
code_blocks = re.findall(r"```(?:python)?\n(.*?)```", reply, re.DOTALL)
if code_blocks:
st.markdown("### π AI-Generated Chart:")
try:
exec_globals = {"df": df.head(100), "plt": plt}
exec(textwrap.dedent(code_blocks[0]), exec_globals)
st.pyplot(plt)
plt.clf()
except Exception as chart_error:
st.error(f"Chart code could not be run: {chart_error}")
else:
st.warning("No Python chart code found in AI's response.")
except Exception as e:
st.error(f"Something went wrong: {e}")
▶️ Run the App
In your terminal, navigate to the project folder and run:
streamlit run app.py
Then visit
http://localhost:8501
in your browser.
π§ Sample Questions to Try
What are the top 5 genres in this sample?
Which countries produce the most Netflix content?
How many movies vs TV shows are there?
Can you plot releases by year?
π ️ Best Practices
- Send only 50–100 rows to the AI for speed and cost efficiency
- Always wrap AI-generated Python in a try block
- Don’t hardcode or share your API key—treat it like a password
π What You Built
You now have an AI-powered data assistant that:
- Loads and filters real Netflix data
- Answers questions in plain English
- Generates custom summary tables and charts from your data
This is a great foundation for dashboards, research assistants, or even business tools!
What’s the best chart AI made for you? Share it below!
Comments
Post a Comment