Spaces:
Sleeping
Sleeping
Update app (2).py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import gradio as grimport plotly.express as pximport pandas as pd# Load the dataset (assuming it's in the same directory for Hugging Face Spaces)df = pd.read_csv('calorie_efficiency_dataset.csv')# --- Tab 1: Data Explorer Functions ---# Function to display the first 10 rows of the DataFramedef display_data_head():return df.head(10)# Function to get numeric columns for the dropdowndef get_numeric_columns():return df.select_dtypes(include=['number']).columns.tolist()# Function to create a Plotly histogram for the selected columndef create_histogram(column_name):if column_name and column_name in df.columns:fig = px.histogram(df, x=column_name, title=f'Distribution of {column_name}')return figreturn gr.Plot()# --- Tab 2: Efficiency Input Tool Functions ---# Function to analyze inputs and provide a message about calorie burn efficiencydef efficiency_analysis(steps, sleep, body_fat):message = "Based on the dataset, here's a general insight: "# Calculate median values from the dataset for comparisonmedian_steps = df['steps_per_day'].median()median_sleep = df['sleep_hours'].median()median_body_fat = df['body_fat_percentage'].median()avg_efficiency_high_steps = df[df['steps_per_day'] > median_steps]['efficiency_score'].mean()avg_efficiency_high_sleep = df[df['sleep_hours'] > median_sleep]['efficiency_score'].mean()avg_efficiency_low_body_fat = df[df['body_fat_percentage'] < median_body_fat]['efficiency_score'].mean()# Basic logic for message generationif steps > median_steps:message += f"- Your steps per day ({steps:.0f}) are higher than the dataset's median ({median_steps:.0f}), which tends to correlate with a higher calorie efficiency score (average: {avg_efficiency_high_steps:.2f})."else:message += f"- Your steps per day ({steps:.0f}) are around or below the dataset's median ({median_steps:.0f}). Higher steps generally correlate with better calorie efficiency."if sleep > median_sleep:message += f"- Your sleep hours ({sleep:.1f}) are higher than the dataset's median ({median_sleep:.1f}), which is often associated with better efficiency (average: {avg_efficiency_high_sleep:.2f})."else:message += f"- Your sleep hours ({sleep:.1f}) are around or below the dataset's median ({median_sleep:.1f}). Adequate sleep often supports calorie efficiency."if body_fat < median_body_fat:message += f"- Your body fat percentage ({body_fat:.1f}%) is lower than the dataset's median ({median_body_fat:.1f}%), which can be linked to higher calorie efficiency (average: {avg_efficiency_low_body_fat:.2f})."else:message += f"- Your body fat percentage ({body_fat:.1f}%) is around or above the dataset's median ({median_body_fat:.1f}%). A lower body fat percentage is generally associated with better calorie efficiency."return message# --- Gradio App Interface ---# Get numeric columns for the dropdownnumeric_cols = get_numeric_columns()with gr.Blocks(title="Calorie Burn Efficiency Explorer") as app:gr.Markdown("# Calorie Burn Efficiency Explorer")gr.Markdown("Help users input lifestyle factors and visualize how variables like steps, sleep, and body composition relate to calorie burn efficiency.")with gr.Tabs():with gr.TabItem("Data Explorer"):gr.Markdown("### Explore the Dataset")# Display the first 10 rows of the datasetgr.Dataframe(value=display_data_head, label="First 10 Rows of Data")# Dropdown for column selectioncolumn_dropdown = gr.Dropdown(choices=numeric_cols,label="Select a Numeric Column for Histogram",value=numeric_cols[0] if numeric_cols else None # Set a default value if available)# Plotly histogram outputhistogram_plot = gr.Plot(label="Histogram")# Link dropdown to histogram functioncolumn_dropdown.change(create_histogram, inputs=column_dropdown, outputs=histogram_plot)# Initial plot on loadapp.load(fn=lambda: create_histogram(column_dropdown.value), inputs=None, outputs=histogram_plot)with gr.TabItem("Efficiency Input Tool"):gr.Markdown("### Input Your Factors")with gr.Column():# User inputssteps_input = gr.Number(label="Steps Per Day", value=df['steps_per_day'].median())sleep_input = gr.Number(label="Sleep Hours", value=df['sleep_hours'].median())body_fat_input = gr.Number(label="Body Fat Percentage (%)", value=df['body_fat_percentage'].median())# Analyze buttonanalyze_button = gr.Button("Analyze Efficiency")# Output messageefficiency_output = gr.Textbox(label="Efficiency Analysis", lines=5)# Link button to analysis functionanalyze_button.click(efficiency_analysis,inputs=[steps_input, sleep_input, body_fat_input],outputs=efficiency_output)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import pandas as pdimport gradio as grimport plotly.express as pxdf = pd.read_csv("calorie_efficiency_dataset.csv")numeric_cols = df.select_dtypes(include="number").columns.tolist()def show_data():return df.head(10)def dataset_summary():summary = f"""Dataset shape: {df.shape[0]} rows and {df.shape[1]} columnsMissing values:{df.isnull().sum().to_string()}Summary statistics:{df.describe().to_string()}"""return summarydef make_histogram(column):fig = px.histogram(df,x=column,title=f"Distribution of {column}",labels={column: column})explanation = f"This histogram shows the distribution of {column} in the dataset."return fig, explanationdef steps_scatter():fig = px.scatter(df,x="steps_per_day",y="efficiency_score",title="Steps Per Day vs. Efficiency Score",labels={"steps_per_day": "Steps Per Day","efficiency_score": "Efficiency Score"})explanation = "This chart shows whether people with higher daily step counts tend to have higher calorie burn efficiency scores."return fig, explanationdef sleep_scatter():fig = px.scatter(df,x="sleep_hours",y="efficiency_score",title="Sleep Hours vs. Efficiency Score",labels={"sleep_hours": "Sleep Hours","efficiency_score": "Efficiency Score"})explanation = "This chart shows whether sleep hours are related to calorie burn efficiency."return fig, explanationdef body_fat_scatter():fig = px.scatter(df,x="body_fat_percentage",y="efficiency_score",title="Body Fat Percentage vs. Efficiency Score",labels={"body_fat_percentage": "Body Fat Percentage","efficiency_score": "Efficiency Score"})explanation = "This chart shows how body fat percentage may relate to calorie burn efficiency."return fig, explanationdef efficiency_analysis(steps, sleep, body_fat):median_steps = df["steps_per_day"].median()median_sleep = df["sleep_hours"].median()median_body_fat = df["body_fat_percentage"].median()median_efficiency = df["efficiency_score"].median()message = "Based on the dataset, here is your calorie burn efficiency analysis:\n\n"if steps > median_steps:message += f"Your steps per day are above the dataset median of {median_steps:.0f}, which may support higher calorie burn efficiency.\n"else:message += f"Your steps per day are at or below the dataset median of {median_steps:.0f}. Increasing daily movement may improve efficiency.\n"if sleep > median_sleep:message += f"Your sleep is above the dataset median of {median_sleep:.1f} hours, which may support better recovery and efficiency.\n"else:message += f"Your sleep is at or below the dataset median of {median_sleep:.1f} hours. More consistent sleep may support better efficiency.\n"if body_fat < median_body_fat:message += f"Your body fat percentage is below the dataset median of {median_body_fat:.1f}%, which may be associated with higher efficiency in this dataset.\n"else:message += f"Your body fat percentage is at or above the dataset median of {median_body_fat:.1f}%. Body composition may be one factor affecting efficiency.\n"message += f"\nThe dataset median efficiency score is {median_efficiency:.2f}."return messagedef final_recommendation():return """Main finding:The dataset suggests that calorie burn efficiency is connected to a combination of movement, sleep, and body composition.Recommendation:A user who wants to improve calorie burn efficiency should focus on increasing daily steps, staying consistent with exercise, improving sleep, and supporting healthy body composition habits.AI-assisted analysis:AI was used to help organize the project, generate beginner-friendly Gradio code, choose meaningful Plotly visualizations, debug the app structure, and summarize possible patterns in the data."""with gr.Blocks(title="Calorie Burn Efficiency Explorer") as app:gr.Markdown("# Calorie Burn Efficiency Explorer")gr.Markdown("This app explores how lifestyle factors like steps, sleep, and body composition relate to calorie burn efficiency.")with gr.Tabs():with gr.TabItem("Dataset Overview"):gr.Markdown("## Dataset Source")gr.Markdown("This project uses the calorie_efficiency_dataset.csv file provided for the final project.")gr.Markdown("## First 10 Rows")gr.Dataframe(value=show_data(), label="First 10 Rows of Dataset")gr.Markdown("## Dataset Quality Check")summary_button = gr.Button("Show Dataset Summary")summary_output = gr.Textbox(label="Dataset Summary", lines=15)summary_button.click(dataset_summary, outputs=summary_output)with gr.TabItem("Visualizations"):gr.Markdown("## Visualization 1: Histogram")column_dropdown = gr.Dropdown(choices=numeric_cols,value=numeric_cols[0],label="Choose a Numeric Column")histogram_plot = gr.Plot(label="Histogram")histogram_text = gr.Textbox(label="Chart Explanation", lines=3)column_dropdown.change(make_histogram,inputs=column_dropdown,outputs=[histogram_plot, histogram_text])gr.Markdown("## Visualization 2: Steps and Efficiency")steps_fig, steps_explanation = steps_scatter()gr.Plot(value=steps_fig)gr.Textbox(value=steps_explanation, label="Chart Explanation", lines=3)gr.Markdown("## Visualization 3: Sleep and Efficiency")sleep_fig, sleep_explanation = sleep_scatter()gr.Plot(value=sleep_fig)gr.Textbox(value=sleep_explanation, label="Chart Explanation", lines=3)gr.Markdown("## Visualization 4: Body Fat and Efficiency")body_fat_fig, body_fat_explanation = body_fat_scatter()gr.Plot(value=body_fat_fig)gr.Textbox(value=body_fat_explanation, label="Chart Explanation", lines=3)with gr.TabItem("Efficiency Input Tool"):gr.Markdown("## Enter Your Own Health and Lifestyle Factors")steps_input = gr.Number(label="Steps Per Day", value=df["steps_per_day"].median())sleep_input = gr.Number(label="Sleep Hours", value=df["sleep_hours"].median())body_fat_input = gr.Number(label="Body Fat Percentage", value=df["body_fat_percentage"].median())analyze_button = gr.Button("Analyze Efficiency")efficiency_output = gr.Textbox(label="Efficiency Analysis", lines=10)analyze_button.click(efficiency_analysis,inputs=[steps_input, sleep_input, body_fat_input],outputs=efficiency_output)with gr.TabItem("Final Findings"):gr.Markdown("## Final Recommendation")gr.Textbox(value=final_recommendation(), label="Project Conclusion", lines=10)app.launch()
app (2).py+139-68