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 from transformers import pipeline import warnings warnings.filterwarnings('ignore') # CONFIGURATION - Set your preferred models here CONFIG = { "nlp_models": { # Choose smaller models to save resources "zero_shot": "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli", # Smaller, faster # "zero_shot": "facebook/bart-large-mnli", # Larger, more accurate "ner": "dslim/bert-base-NER", # Good balance # "ner": "dslim/bert-large-NER", # More accurate but slower }, "enable_gpu": False, # Set to True if you have GPU enabled in your Space "max_nlp_samples": 100, # Limit samples to control compute usage "cache_models": True, # Cache models after loading } # 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 # Load NLP models (cached if enabled) def load_nlp_models(): device = 0 if CONFIG["enable_gpu"] else -1 try: classifier = pipeline( "zero-shot-classification", model=CONFIG["nlp_models"]["zero_shot"], device=device ) ner = pipeline( "ner", model=CONFIG["nlp_models"]["ner"], aggregation_strategy="simple", device=device ) return classifier, ner, None except Exception as e: return None, None, f"Error loading models: {str(e)}" # Cache models if configured if CONFIG["cache_models"]: load_nlp_models = gr.cache_data(load_nlp_models) # Create visualizations 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()} ### Space Configuration - **Zero-shot Model**: {CONFIG["nlp_models"]["zero_shot"]} - **NER Model**: {CONFIG["nlp_models"]["ner"]} - **GPU Enabled**: {CONFIG["enable_gpu"]} - **Max NLP Samples**: {CONFIG["max_nlp_samples"]} """ 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 Functions def detect_anomalies(df, contamination=0.05): # 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 anomalies = member_stats[member_stats['anomaly'] == -1].sort_values('anomaly_score') return anomalies, member_stats def plot_anomalies(member_stats): 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 Functions def forecast_spending(df, periods=4): # 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 model = Prophet(yearly_seasonality=True, weekly_seasonality=False, daily_seasonality=False) model.fit(quarterly[['ds', 'y']]) # Make future predictions future = model.make_future_dataframe(periods=periods, freq='Q') forecast = model.predict(future) # Create 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') )) # Confidence intervals fig.add_trace(go.Scatter( x=forecast['ds'].tolist() + forecast['ds'].tolist()[::-1], y=forecast['yhat_upper'].tolist() + forecast['yhat_lower'].tolist()[::-1], fill='toself', fillcolor='rgba(255,0,0,0.2)', line=dict(color='rgba(255,255,255,0)'), name='Confidence Interval', showlegend=True )) fig.update_layout( title='Quarterly Spending Forecast', xaxis_title='Date', yaxis_title='Total Spending ($)', hovermode='x' ) return fig, forecast # NLP Analysis Functions (with resource controls) def analyze_descriptions(df, sample_size=None): if sample_size is None: sample_size = CONFIG["max_nlp_samples"] else: sample_size = min(sample_size, CONFIG["max_nlp_samples"]) classifier, ner, error = load_nlp_models() if error: return pd.DataFrame({"Error": [error]}), pd.DataFrame({"Error": [error]}) # Sample descriptions for analysis sample_df = df[df['description'].notna()].sample(min(sample_size, len(df))) # Zero-shot classification for spending purposes candidate_labels = ["Travel", "Office Supplies", "Consulting", "Events", "Technology", "Staff", "Communications"] classifications = [] # Limit classifications to save resources for i, desc in enumerate(sample_df['description'].head(20)): if i >= 20: # Hard limit break try: result = classifier(desc[:512], candidate_labels) # Truncate long descriptions classifications.append({ 'description': desc[:100] + '...' if len(desc) > 100 else desc, 'predicted_category': result['labels'][0], 'confidence': result['scores'][0] }) except Exception as e: continue classifications_df = pd.DataFrame(classifications) # Entity extraction from supplier names entities = [] unique_suppliers = df['supplier'].dropna().unique()[:30] # Limit suppliers for supplier in unique_suppliers: try: ents = ner(supplier) if ents: entities.append({ 'supplier': supplier, 'entities': ', '.join([f"{e['word']} ({e['entity_group']})" for e in ents]) }) except: continue entities_df = pd.DataFrame(entities) return classifications_df, entities_df 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 # Main app def main(): df = load_data() with gr.Blocks(title="Canadian Parliamentary Expenditures Analysis", theme=gr.themes.Soft()) as app: gr.Markdown("# 🇨🇦 Canadian Parliamentary Expenditures Analysis") gr.Markdown("Explore spending data with advanced analytics: Anomaly Detection, Time Series Forecasting, and NLP") 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, 50, 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("Using Isolation Forest to identify members with anomalous spending behaviors") contamination = gr.Slider(0.01, 0.2, 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="Anomalous Members" ) def run_anomaly_detection(contamination): anomalies, member_stats = detect_anomalies(df, contamination) 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("Using Prophet to predict quarterly spending trends") forecast_periods = gr.Slider(1, 8, value=4, step=1, label="Quarters to Forecast") forecast_btn = gr.Button("Generate Forecast", variant="primary") forecast_plot = gr.Plot() forecast_summary = gr.Markdown() def run_forecast(periods): plot, forecast = forecast_spending(df, periods) # Get last historical and next predicted values last_historical = forecast[forecast['ds'] <= df['date_incurred'].max()]['yhat'].iloc[-1] next_predicted = forecast[forecast['ds'] > df['date_incurred'].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}% """ return plot, summary forecast_btn.click(run_forecast, inputs=[forecast_periods], outputs=[forecast_plot, forecast_summary]) with gr.Tab("🤖 NLP Analysis"): gr.Markdown("### Natural Language Analysis of Expenses") gr.Markdown(f"Using transformer models to analyze descriptions and extract insights") gr.Markdown(f"**Note**: Analysis limited to {CONFIG['max_nlp_samples']} samples to manage compute resources") analyze_btn = gr.Button("Run NLP Analysis", variant="primary") with gr.Row(): with gr.Column(): gr.Markdown("#### Zero-Shot Classification of Descriptions") classification_table = gr.Dataframe( headers=["Description", "Predicted Category", "Confidence"], label="Expense Classifications" ) with gr.Column(): gr.Markdown("#### Named Entity Recognition in Suppliers") entity_table = gr.Dataframe( headers=["Supplier", "Entities Found"], label="Supplier Entities" ) keyword_plot = gr.Plot(label="Spending by Keywords") def run_nlp_analysis(): classifications, entities = analyze_descriptions(df) keyword_chart = analyze_spending_patterns(df) return classifications, entities, keyword_chart analyze_btn.click( run_nlp_analysis, outputs=[classification_table, entity_table, keyword_plot] ) return app if __name__ == "__main__": app = main() app.launch()