Spaces:
Build error
Build error
| from flask import Flask, render_template_string, request | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| import os | |
| app = Flask(__name__) | |
| DATA_PATH = 'crime.csv' | |
| IMG_PATH = 'static/plot.png' | |
| # Load data once | |
| df = pd.read_csv(DATA_PATH) | |
| df = df[df['DISTRICT'] != 'ZZ TOTAL'] # Remove aggregate rows | |
| # Unique states and years for dropdowns | |
| states = sorted(df['STATE/UT'].unique()) | |
| years = sorted(df['YEAR'].unique()) | |
| def index(): | |
| selected_state = request.form.get('state') or states[0] | |
| selected_year = request.form.get('year') or 'All' | |
| filtered_df = df[df['STATE/UT'] == selected_state] | |
| if selected_year != 'All': | |
| filtered_df = filtered_df[filtered_df['YEAR'] == int(selected_year)] | |
| # Aggregate crimes per year (or district if single year selected) | |
| if selected_year == 'All': | |
| data_plot = filtered_df.groupby('YEAR')['TOTAL IPC CRIMES'].sum().reset_index() | |
| x, y = 'YEAR', 'TOTAL IPC CRIMES' | |
| title = f"Total IPC Crimes Over Years in {selected_state}" | |
| else: | |
| data_plot = filtered_df.groupby('DISTRICT')['TOTAL IPC CRIMES'].sum().reset_index() | |
| x, y = 'DISTRICT', 'TOTAL IPC CRIMES' | |
| title = f"Total IPC Crimes in {selected_state} ({selected_year}) by District" | |
| # Plot | |
| plt.figure(figsize=(12, 6)) | |
| sns.barplot(data=data_plot, x=x, y=y, palette='magma') | |
| plt.title(title, fontsize=14) | |
| plt.xticks(rotation=45, ha='right') | |
| plt.tight_layout() | |
| # Save plot | |
| os.makedirs('static', exist_ok=True) | |
| plt.savefig(IMG_PATH) | |
| plt.close() | |
| # HTML Template | |
| html = """ | |
| <html> | |
| <head> | |
| <title>Crime Data Dashboard</title> | |
| <style> | |
| body { text-align: center; font-family: sans-serif; } | |
| form { margin-bottom: 20px; } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Crime Data Visualization</h1> | |
| <form method="POST"> | |
| <label for="state">Select State:</label> | |
| <select name="state"> | |
| {% for s in states %} | |
| <option value="{{ s }}" {% if s == selected_state %}selected{% endif %}>{{ s }}</option> | |
| {% endfor %} | |
| </select> | |
| <label for="year">Select Year:</label> | |
| <select name="year"> | |
| <option value="All" {% if selected_year == 'All' %}selected{% endif %}>All</option> | |
| {% for y in years %} | |
| <option value="{{ y }}" {% if y|string == selected_year %}selected{% endif %}>{{ y }}</option> | |
| {% endfor %} | |
| </select> | |
| <input type="submit" value="Filter"> | |
| </form> | |
| <img src="/static/plot.png" width="800"> | |
| </body> | |
| </html> | |
| """ | |
| return render_template_string(html, states=states, years=years, selected_state=selected_state, selected_year=selected_year) | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) | |