0% found this document useful (0 votes)
9 views6 pages

Mainpy (Customer Segmentation)

rreeeeeeeeeeee

Uploaded by

sadnova805
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views6 pages

Mainpy (Customer Segmentation)

rreeeeeeeeeeee

Uploaded by

sadnova805
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

# from fastapi import FastAPI, File, UploadFile

# from fastapi.responses import HTMLResponse


# from fastapi.staticfiles import StaticFiles
# import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
# from sklearn.cluster import KMeans
# from io import BytesIO
# import base64

# app = FastAPI()

# app.mount("/static", StaticFiles(directory="static"), name="static")

# @app.get("/", response_class=HTMLResponse)
# async def main():
# with open("index.html", "r") as f:
# return f.read()

# @app.post("/upload/", response_class=HTMLResponse)
# async def handle_upload(file: UploadFile = File(...)):
# if file.filename.endswith('.csv'):
# dataframe = pd.read_csv(BytesIO(await file.read()))

# # Process data and generate plots


# plot_images = process_data_and_plot(dataframe)

# # Convert plots to inline HTML images and wrap every two plots side by
side
# html_images = []
# for i, img in enumerate(plot_images):
# buffer = BytesIO()
# img.savefig(buffer, format="png")
# buffer.seek(0)
# image_png = buffer.getvalue()
# encoded = base64.b64encode(image_png).decode('utf-8')
# html_img = f'<img src="data:image/png;base64,{encoded}"
class="plot">'
# if i % 2 == 0 and i != 0:
# html_images.append('</div>')
# if i % 2 == 0:
# html_images.append('<div class="row">') # Start a new row every
two plots
# html_images.append(html_img)
# if len(html_images) % 2 != 0:
# html_images.append('</div>') # Close the last row if there's an odd
number of plots

# # Create an enhanced HTML page to display the images


# html_content = f"""
# <!DOCTYPE html>
# <html lang="en">
# <head>
# <meta charset="UTF-8">
# <meta name="viewport" content="width=device-width, initial-
scale=1.0">
# <title>Analysis Results</title>
# <link rel="stylesheet" href="/static/styles.css">
# </head>
# <body>
# <header>
# <h1 style="text-align: center;">Data Analysis Dashboard</h1>
# </header>
# <div class="dashboard">
# <section class="content">
# """ + "".join(html_images) + """
# </section>
# </div>
# <footer>
# <p>© 2024 Data Analysis App</p>
# </footer>
# </body>
# </html>
# """
# return html_content
# return HTMLResponse(content="<html><body><p>Invalid file format. Please
upload a CSV file.</p></body></html>", status_code=400)

# def process_data_and_plot(df):
# figs = []

# # # Univariate Analysis Plots


# # fig, ax = plt.subplots()
# # sns.displot(df['Annual Income (k$)'])
# # figs.append(fig)

# # More Univariate Plots


# columns = ['Age', 'Annual Income (k$)', 'Spending Score (1-100)']
# for col in columns:
# fig, ax = plt.subplots()
# sns.kdeplot(df[col], shade=True, ax=ax)
# figs.append(fig)

# # Bivariate Analysis Plots


# fig, ax = plt.subplots()
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
ax=ax)
# figs.append(fig)

# # Clustering - KMeans for Annual Income


# kmeans = KMeans(n_clusters=3)
# df['Income Cluster'] = kmeans.fit_predict(df[['Annual Income (k$)']])
# fig, ax = plt.subplots()
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
hue='Income Cluster', palette='viridis', ax=ax)
# figs.append(fig)

# # Prepare and fit model for multivariate clustering


# df_numeric = df[['Age', 'Annual Income (k$)', 'Spending Score (1-100)']]
# kmeans = KMeans(n_clusters=5)
# df['Cluster'] = kmeans.fit_predict(df_numeric)
# fig, ax = plt.subplots()
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
hue='Cluster', palette='viridis', ax=ax)
# figs.append(fig)

# return figs
# import webbrowser
# import asyncio
# from fastapi import FastAPI, File, UploadFile
# from fastapi.responses import HTMLResponse
# from fastapi.staticfiles import StaticFiles
# import pandas as pd
# from io import BytesIO
# import base64
# import matplotlib.pyplot as plt
# import seaborn as sns
# from sklearn.cluster import KMeans

# app = FastAPI()

# # Mount static files


# app.mount("/static", StaticFiles(directory="static"), name="static")

# # Open landing page on startup


# @app.on_event("startup")
# async def open_landing_page():
# await asyncio.sleep(1) # Small delay to ensure server starts
# webbrowser.open("http://localhost:8013/") # Open landing page

# # Serve landing page


# @app.get("/", response_class=HTMLResponse)
# async def serve_landing_page():
# with open("landingpage.html", "r") as f:
# return f.read()

# # Serve CSV upload page


# @app.get("/index", response_class=HTMLResponse) # No .html extension in route
# async def serve_upload_page():
# with open("index.html", "r") as f:
# return f.read()

# # Handle CSV uploads


# @app.post("/upload", response_class=HTMLResponse)
# async def upload_csv(file: UploadFile = File(...)):
# if file.filename.endswith(".csv"):
# df = pd.read_csv(BytesIO(await file.read()))

# # Process CSV data and generate HTML


# html_content = process_data_and_plot(df)

# return HTMLResponse(html_content)
# else:
# return HTMLResponse("Invalid file format. Please upload a CSV.",
status_code=400)

# def process_data_and_plot(df):
# figs = []

# # # Univariate Analysis Plots


# # fig, ax = plt.subplots()
# # sns.displot(df['Annual Income (k$)'])
# # figs.append(fig)
# # More Univariate Plots
# columns = ['Age', 'Annual Income (k$)', 'Spending Score (1-100)']
# for col in columns:
# fig, ax = plt.subplots()
# sns.kdeplot(df[col], fill=True, ax=ax)
# figs.append(fig)

# # Bivariate Analysis Plots


# fig, ax = plt.subplots()
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
ax=ax)
# figs.append(fig)

# # Clustering - KMeans for Annual Income


# kmeans = KMeans(n_clusters=3)
# df['Income Cluster'] = kmeans.fit_predict(df[['Annual Income (k$)']])
# fig, ax = plt.subplots()
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
hue='Income Cluster', palette='viridis', ax=ax)
# figs.append(fig)

# # Prepare and fit model for multivariate clustering


# df_numeric = df[['Age', 'Annual Income (k$)', 'Spending Score (1-100)']]
# kmeans = KMeans(n_clusters=5)
# df['Cluster'] = kmeans.fit_predict(df_numeric)
# fig, ax = plt.subplots()
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
hue='Cluster', palette='viridis', ax=ax)
# figs.append(fig)

# # Convert plots to base64-encoded images


# plot_html = ""
# for fig in figs:
# buffer = BytesIO()
# fig.savefig(buffer, format="png")
# buffer.seek(0)
# image_png = buffer.getvalue()
# encoded = base64.b64encode(image_png).decode("utf-8")
# plot_html += f'<img src="data:image/png;base64,{encoded}" class="plot">'

# # Create HTML content to display plots


# html_content = f"""
# <html>
# <head>
# <title>CSV Analysis Results</title>
# <link rel="stylesheet" href="/static/styles.css">
# </head>
# <body>
# <header>
# <h1>CSV Analysis Results</h1>
# </header>
# {plot_html} <!-- Embed generated plot -->
# </body>
# </html>
# """

# return html_content
# import webbrowser
# import asyncio
# from fastapi import FastAPI, File, UploadFile
# from fastapi.responses import HTMLResponse
# from fastapi.staticfiles import StaticFiles
# import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
# from sklearn.cluster import KMeans
# from io import BytesIO
# import base64

# # Initialize FastAPI app


# app = FastAPI()

# # Mount static files


# app.mount("/static", StaticFiles(directory="static"), name="static")

# # Open landing page on startup


# @app.on_event("startup")
# async def open_landing_page():
# await asyncio.sleep(1) # Allow server time to start
# webbrowser.open("http://localhost:8013/") # Open landing page

# # Serve landing page


# @app.get("/", response_class=HTMLResponse)
# async def serve_landing_page():
# with open("landingpage.html", "r") as f:
# return f.read()

# # Serve CSV upload page


# @app.get("/index", response_class=HTMLResponse)
# async def serve_upload_page():
# with open("index.html", "r") as f:
# return f.read()

# @app.post("/upload", response_class=HTMLResponse)
# async def upload_csv(file: UploadFile = File(...)):
# if not file.filename.endswith(".csv"):
# return HTMLResponse(content="<p>Invalid file format. Please upload a CSV
file.</p>", status_code=400)

# # Read the CSV data


# dataframe = pd.read_csv(BytesIO(await file.read()))

# # Generate plots and convert them to base64-encoded images


# plot_images = []
# for fig in process_data_and_plot(dataframe):
# buffer = BytesIO()
# fig.savefig(buffer, format="png")
# buffer.seek(0)
# image_png = buffer.getvalue()
# encoded = base64.b64encode(image_png).decode("utf-8")
# plot_images.append(encoded)

# # Create the HTML content with dynamic plots


# plot_content = "".join([f'<img src="data:image/png;base64,{img}" alt="Plot">'
for img in plot_images])
# with open("analysis_results.html", "r") as f:
# html_template = f.read()

# final_html = html_template.replace("{{plot_images}}", plot_content)

# return HTMLResponse(content=final_html)

# # Process CSV data and generate plots


# # Adjusted plot size to fit two plots in a single line
# def process_data_and_plot(df):
# figs = []

# # Set smaller `figsize` to fit two plots side by side


# plot_size = (5, 4) # Small enough for two plots in one line
# plot_dpi = 150 # Maintain good quality with smaller plots

# # Univariate Analysis
# for col in ['Age', 'Annual Income (k$)', 'Spending Score (1-100)']:
# fig, ax = plt.subplots(figsize=plot_size, dpi=plot_dpi) # Smaller plot
# sns.kdeplot(df[col], fill=True, ax=ax)
# figs.append(fig)

# # Bivariate Analysis
# fig, ax = plt.subplots(figsize=plot_size, dpi=plot_dpi) # Smaller plot
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
ax=ax)
# figs.append(fig)

# # Clustering Analysis
# kmeans = KMeans(n_clusters=3)
# df['Income Cluster'] = kmeans.fit_predict(df[['Annual Income (k$)']])
# fig, ax = plt.subplots(figsize=plot_size, dpi=plot_dpi) # Smaller plot
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
hue='Income Cluster', ax=ax)
# figs.append(fig)

# # Multivariate Clustering
# kmeans = KMeans(n_clusters=5)
# df['Cluster'] = kmeans.fit_predict(df[['Age', 'Annual Income (k$)', 'Spending
Score (1-100)']])
# fig, ax = plt.subplots(figsize=plot_size, dpi=plot_dpi) # Smaller plot
# sns.scatterplot(data=df, x='Annual Income (k$)', y='Spending Score (1-100)',
hue='Cluster', ax=ax)
# figs.append(fig)

# return figs

You might also like