import gradio as gr import pandas as pd import numpy as np from datasets import load_dataset import plotly.express as px import plotly.graph_objects as go from sklearn.ensemble import IsolationForest from sklearn.preprocessing import StandardScaler from prophet import Prophet import time from datetime import datetime, timedelta import warnings warnings.filterwarnings('ignore') # ANTI-ABUSE CONFIGURATION FOR FREE TIER CONFIG = { "rate_limits": { "nlp_per_minute": 5, # Max NLP requests per minute "forecast_per_minute": 3, # Max forecast requests per minute "anomaly_per_minute": 5, # Max anomaly detection per minute }, "compute_limits": { "max_nlp_samples": 10, # Very limited samples for NLP "max_forecast_periods": 4, # Limit forecast horizon "max_anomaly_contamination": 0.1, # Limit anomaly detection scope }, "model_config": { # Use tiny models for free tier "use_nlp": False, # Disable NLP entirely to save resources # If you enable NLP later, use tiny models: # "zero_shot": "typeform/distilbert-base-uncased-mnli", # 66M params # "ner": "dslim/bert-base-NER", } } # Simple in-memory rate limiting request_history = { "nlp": [], "forecast": [], "anomaly": [] } def check_rate_limit(request_type): """Check if user has exceeded rate limit""" now = datetime.now() one_minute_ago = now - timedelta(minutes=1) # Clean old requests request_history[request_type] = [ req_time for req_time in request_history[request_type] if req_time > one_minute_ago ] # Check limit limit = CONFIG["rate_limits"].get(f"{request_type}_per_minute", 10) if len(request_history[request_type]) >= limit: return False, f"Rate limit exceeded. Max {limit} requests per minute. Please wait." # Add current request request_history[request_type].append(now) return True, "" # Load the dataset @gr.cache_data def load_data(): dataset = load_dataset("irf23/canadian-parliamentary-expenditures") df = pd.DataFrame(dataset['train']) df['amount'] = pd.to_numeric(df['amount']) df['period_year'] = pd.to_numeric(df['period_year']) df['period_quarter'] = pd.to_numeric(df['period_quarter']) # Convert date_incurred to datetime df['date_incurred'] = pd.to_datetime(df['date_incurred'], errors='coerce') return df # Create visualizations (these are lightweight, no rate limiting needed) def create_overview(df): total_spending = df['amount'].sum() total_records = len(df) unique_members = df['member_id'].nunique() return f""" ## Dataset Overview - **Total Spending**: ${total_spending:,.2f} - **Total Records**: {total_records:,} - **Unique Members**: {unique_members} - **Time Period**: {df['period_year'].min()} Q{df[df['period_year']==df['period_year'].min()]['period_quarter'].min()} to {df['period_year'].max()} Q{df[df['period_year']==df['period_year'].max()]['period_quarter'].max()} ### Free Tier Limits - **Anomaly Detection**: {CONFIG['rate_limits']['anomaly_per_minute']} requests/minute - **Forecasting**: {CONFIG['rate_limits']['forecast_per_minute']} requests/minute - **NLP Analysis**: {"Disabled to save resources" if not CONFIG['model_config']['use_nlp'] else f"{CONFIG['rate_limits']['nlp_per_minute']} requests/minute"} """ def spending_by_party(df): party_spending = df.groupby('party')['amount'].sum().sort_values(ascending=True) fig = px.bar( x=party_spending.values, y=party_spending.index, orientation='h', title='Total Spending by Party', labels={'x': 'Total Amount ($)', 'y': 'Party'} ) return fig def spending_by_category(df): category_spending = df.groupby('category')['amount'].sum().sort_values(ascending=False) fig = px.pie( values=category_spending.values, names=category_spending.index, title='Spending Distribution by Category' ) return fig def spending_over_time(df): quarterly_spending = df.groupby(['period_year', 'period_quarter'])['amount'].sum().reset_index() quarterly_spending['period'] = quarterly_spending['period_year'].astype(str) + ' Q' + quarterly_spending['period_quarter'].astype(str) fig = px.line( quarterly_spending, x='period', y='amount', title='Quarterly Spending Trends', labels={'amount': 'Total Amount ($)', 'period': 'Period'} ) fig.update_xaxis(tickangle=-45) return fig def top_spenders(df, n=20): top_members = df.groupby('member_name')['amount'].sum().nlargest(n).sort_values(ascending=True) fig = px.bar( x=top_members.values, y=top_members.index, orientation='h', title=f'Top {n} Spenders', labels={'x': 'Total Amount ($)', 'y': 'Member'} ) fig.update_layout(height=600) return fig # Anomaly Detection with rate limiting def detect_anomalies(df, contamination=0.05): # Check rate limit allowed, message = check_rate_limit("anomaly") if not allowed: return pd.DataFrame({"Error": [message]}), None # Limit contamination to prevent abuse contamination = min(contamination, CONFIG["compute_limits"]["max_anomaly_contamination"]) # Add small delay to prevent rapid requests time.sleep(0.5) # Prepare features for anomaly detection member_stats = df.groupby('member_id').agg({ 'amount': ['sum', 'mean', 'std', 'count'], 'category': lambda x: x.mode()[0] if len(x.mode()) > 0 else 'Unknown' }).reset_index() member_stats.columns = ['member_id', 'total_amount', 'avg_amount', 'std_amount', 'num_expenses', 'main_category'] # Get member names member_names = df.groupby('member_id')['member_name'].first() member_stats = member_stats.merge(member_names, on='member_id') # Features for anomaly detection features = ['total_amount', 'avg_amount', 'std_amount', 'num_expenses'] X = member_stats[features].fillna(0) # Standardize features scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # Detect anomalies clf = IsolationForest(contamination=contamination, random_state=42) member_stats['anomaly'] = clf.fit_predict(X_scaled) member_stats['anomaly_score'] = clf.score_samples(X_scaled) # Get anomalous members (limit to top 20 to save memory) anomalies = member_stats[member_stats['anomaly'] == -1].sort_values('anomaly_score').head(20) return anomalies, member_stats def plot_anomalies(member_stats): if member_stats is None: return None fig = px.scatter( member_stats, x='avg_amount', y='total_amount', size='num_expenses', color='anomaly', color_discrete_map={1: 'blue', -1: 'red'}, hover_data=['member_name', 'main_category'], title='Member Spending Patterns (Red = Anomalous)', labels={'avg_amount': 'Average Expense Amount ($)', 'total_amount': 'Total Spending ($)'} ) return fig # Time Series Forecasting with rate limiting def forecast_spending(df, periods=4): # Check rate limit allowed, message = check_rate_limit("forecast") if not allowed: return None, f"### Error\n{message}" # Limit forecast periods periods = min(periods, CONFIG["compute_limits"]["max_forecast_periods"]) # Add small delay time.sleep(0.5) # Aggregate by quarter quarterly = df.groupby(['period_year', 'period_quarter'])['amount'].sum().reset_index() quarterly['ds'] = pd.to_datetime( quarterly['period_year'].astype(str) + '-' + (quarterly['period_quarter'] * 3).astype(str) + '-01' ) quarterly['y'] = quarterly['amount'] # Create and fit Prophet model with minimal configuration model = Prophet( yearly_seasonality=False, # Disable to save compute weekly_seasonality=False, daily_seasonality=False, seasonality_mode='additive', n_changepoints=10 # Reduce changepoints ) model.fit(quarterly[['ds', 'y']]) # Make future predictions future = model.make_future_dataframe(periods=periods, freq='Q') forecast = model.predict(future) # Create simple plot fig = go.Figure() # Historical data fig.add_trace(go.Scatter( x=quarterly['ds'], y=quarterly['y'], mode='lines+markers', name='Historical', line=dict(color='blue') )) # Forecast fig.add_trace(go.Scatter( x=forecast['ds'], y=forecast['yhat'], mode='lines', name='Forecast', line=dict(color='red', dash='dash') )) fig.update_layout( title='Quarterly Spending Forecast', xaxis_title='Date', yaxis_title='Total Spending ($)', hovermode='x' ) # Calculate summary last_historical = quarterly['y'].iloc[-1] next_predicted = forecast[forecast['ds'] > quarterly['ds'].max()]['yhat'].iloc[0] change_pct = ((next_predicted - last_historical) / last_historical) * 100 summary = f""" ### Forecast Summary - **Last Historical Quarter**: ${last_historical:,.2f} - **Next Predicted Quarter**: ${next_predicted:,.2f} - **Expected Change**: {change_pct:+.1f}% - **Periods Forecasted**: {periods} """ return fig, summary # Simple keyword analysis (no models needed) def analyze_spending_patterns(df): # Analyze spending patterns by description keywords keywords = ['travel', 'hotel', 'flight', 'consulting', 'office', 'technology', 'communication', 'event'] keyword_spending = {} for keyword in keywords: mask = df['description'].str.contains(keyword, case=False, na=False) keyword_spending[keyword] = df[mask]['amount'].sum() fig = px.bar( x=list(keyword_spending.keys()), y=list(keyword_spending.values()), title='Spending by Description Keywords', labels={'x': 'Keyword', 'y': 'Total Spending ($)'} ) return fig # Search function (lightweight, no rate limiting) def search_expenses(df, member_name="", min_amount=0, max_amount=1000000, category="All"): filtered_df = df.copy() if member_name: filtered_df = filtered_df[filtered_df['member_name'].str.contains(member_name, case=False, na=False)] filtered_df = filtered_df[(filtered_df['amount'] >= min_amount) & (filtered_df['amount'] <= max_amount)] if category != "All": filtered_df = filtered_df[filtered_df['category'] == category] # Limit results to save memory result = filtered_df.nlargest(50, 'amount')[['member_name', 'category', 'amount', 'description', 'supplier', 'date_incurred']] return result # Main app def main(): df = load_data() with gr.Blocks( title="Canadian Parliamentary Expenditures Analysis", theme=gr.themes.Soft(), analytics_enabled=False # Disable analytics for privacy ) as app: gr.Markdown("# 🇨🇦 Canadian Parliamentary Expenditures Analysis") gr.Markdown("Free tier version with rate limiting to prevent abuse") with gr.Tab("Overview"): overview_text = gr.Markdown(create_overview(df)) with gr.Row(): party_chart = gr.Plot(spending_by_party(df)) category_chart = gr.Plot(spending_by_category(df)) time_chart = gr.Plot(spending_over_time(df)) with gr.Tab("Top Spenders"): n_spenders = gr.Slider(10, 30, value=20, step=5, label="Number of top spenders to show") spenders_chart = gr.Plot(top_spenders(df, 20)) n_spenders.change(lambda n: top_spenders(df, n), inputs=[n_spenders], outputs=[spenders_chart]) with gr.Tab("🔍 Anomaly Detection"): gr.Markdown("### Detect Unusual Spending Patterns") gr.Markdown(f"⚠️ Rate limited to {CONFIG['rate_limits']['anomaly_per_minute']} requests per minute") contamination = gr.Slider( 0.01, CONFIG["compute_limits"]["max_anomaly_contamination"], value=0.05, step=0.01, label="Contamination Rate (% of anomalies expected)" ) detect_btn = gr.Button("Detect Anomalies", variant="primary") anomaly_plot = gr.Plot() anomaly_table = gr.Dataframe( headers=["Member Name", "Total Spending", "Avg Expense", "Num Expenses", "Main Category", "Anomaly Score"], label="Top 20 Anomalous Members" ) def run_anomaly_detection(contamination): anomalies, member_stats = detect_anomalies(df, contamination) if isinstance(anomalies, pd.DataFrame) and "Error" in anomalies.columns: return None, anomalies plot = plot_anomalies(member_stats) table_data = anomalies[['member_name', 'total_amount', 'avg_amount', 'num_expenses', 'main_category', 'anomaly_score']].round(2) return plot, table_data detect_btn.click(run_anomaly_detection, inputs=[contamination], outputs=[anomaly_plot, anomaly_table]) with gr.Tab("📈 Time Series Forecast"): gr.Markdown("### Forecast Future Spending") gr.Markdown(f"⚠️ Rate limited to {CONFIG['rate_limits']['forecast_per_minute']} requests per minute") forecast_periods = gr.Slider( 1, CONFIG["compute_limits"]["max_forecast_periods"], value=2, step=1, label="Quarters to Forecast" ) forecast_btn = gr.Button("Generate Forecast", variant="primary") forecast_plot = gr.Plot() forecast_summary = gr.Markdown() forecast_btn.click( lambda p: forecast_spending(df, p), inputs=[forecast_periods], outputs=[forecast_plot, forecast_summary] ) with gr.Tab("🔍 Keyword Analysis"): gr.Markdown("### Simple Keyword Analysis") gr.Markdown("Analyze spending patterns by keywords (no ML models required)") analyze_btn = gr.Button("Analyze Keywords", variant="primary") keyword_plot = gr.Plot() analyze_btn.click( lambda: analyze_spending_patterns(df), outputs=[keyword_plot] ) with gr.Tab("Search Expenses"): gr.Markdown("### Search and Filter Expenses") with gr.Row(): member_search = gr.Textbox(label="Member Name (partial match)", placeholder="e.g., Trudeau") category_filter = gr.Dropdown( choices=["All"] + df['category'].unique().tolist(), value="All", label="Category" ) with gr.Row(): min_amount = gr.Number(value=0, label="Minimum Amount ($)") max_amount = gr.Number(value=1000000, label="Maximum Amount ($)") search_btn = gr.Button("Search", variant="primary") results_df = gr.Dataframe( headers=["Member", "Category", "Amount", "Description", "Supplier", "Date"], datatype=["str", "str", "number", "str", "str", "str"], row_count=10, label="Top 50 Results by Amount" ) search_btn.click( search_expenses, inputs=[df, member_search, min_amount, max_amount, category_filter], outputs=[results_df] ) return app if __name__ == "__main__": app = main() app.launch( server_name="0.0.0.0", show_error=True, max_threads=10 # Limit concurrent users )