import gradio as gr import pandas as pd import numpy as np import torch # from transformers import AutoTokenizer, AutoModelForSequenceClassification # import json from scipy.spatial.distance import jensenshannon, cosine # import shap import os import plotly.graph_objects as go import plotly.express as px from plotly.subplots import make_subplots from backend.model_manager import ModelManager from backend.data_manager import DataManager from backend.helpers import jensen_shannon_distance model_manager = ModelManager() data_manager = DataManager() def load_datasets(): """Load sample datasets with hardcoded examples""" return True def load_model(model_name): """Load model and tokenizer""" try: wrapped_model, tokenizer = model_manager.load_model(model_name) return wrapped_model, tokenizer except Exception as e: print(f"Error loading model {model_name}: {e}") return None, None def get_sentiment_prediction(text, model, tokenizer): """Get sentiment prediction from model""" if model is None: # Fallback to dummy predictions for demo return { "label": "NM", "probabilities": {"Negative": 0.01, "Neutral": 0.01, "Positive": 0.01} } try: # Build full prompt for analysis prefix = "Analyze the sentiment of this statement extracted from a financial news article. Provide your answer as either negative, positive, or neutral.. Text: " suffix = ".. Answer: " full_prompt = f"{prefix}{text}{suffix}" # Added a small comment here. result = model.generate(prompt=full_prompt) return result except Exception as e: print(f"Error in prediction: {e}") return {"label": "NA", "probabilities": {"Negative": 0.0, "Neutral": 0.0, "Positive": 0.0}} def calculate_distances(orig_probs, mut_probs): """Calculate Jensen-Shannon distance and Cosine similarity""" try: js_distance = jensen_shannon_distance(orig_probs, mut_probs) # Convert to arrays for cosine similarity orig_array = np.array(list(orig_probs.values())) mut_array = np.array(list(mut_probs.values())) cos_sim = 1 - cosine(orig_array, mut_array) return js_distance, cos_sim except Exception as e: print(f"Error calculating distances: {e}") return 0.0, 1.0 def load_bias_dictionary(): """Load bias terms from the bias dictionary files""" bias_terms = set() bias_dir = "data/bias" try: for category in ["gender", "age", "race"]: file_path = os.path.join(bias_dir, category, f"{category}_terms.csv") if os.path.exists(file_path): df = pd.read_csv(file_path) # Assuming the CSV has a column with bias terms if 'term' in df.columns: bias_terms.update(df['term'].str.lower().tolist()) elif len(df.columns) > 0: # Use first column if 'term' column doesn't exist bias_terms.update(df.iloc[:, 0].str.lower().tolist()) except Exception as e: print(f"[v0] Error loading bias dictionary: {e}") # Add some common bias terms as fallback bias_terms.update(['people', 'person', 'man', 'woman', 'male', 'female', 'young', 'old', 'white', 'black', 'asian', 'hispanic', 'russian', 'american', 'european']) return bias_terms def find_bias_tokens_in_sentence(sentence, bias_dictionary): """Find bias tokens present in a sentence""" words = sentence.lower().split() bias_tokens_found = {} for i, word in enumerate(words): # Clean word of punctuation clean_word = word.strip('.,!?;:"()[]{}') if clean_word in bias_dictionary: bias_tokens_found[clean_word] = { 'position': i, 'original_word': word } return bias_tokens_found def calculate_shapley_values(original_text, atomic1_text, atomic2_text, intersectional_text, model_name): """Calculate SHAP values for bias tokens using BiasAnalyzer and show rank changes""" try: print(f"[v0] Starting SHAP calculation for model: {model_name}") analyzer = model_manager.get_bias_analyzer(model_name) print(f"[v0] BiasAnalyzer created successfully") sentences = { 'original': original_text, 'atomic1': atomic1_text, 'atomic2': atomic2_text, 'intersectional': intersectional_text } sentence_results = {} for sentence_type, sentence_text in sentences.items(): try: print(f"[v0] Analyzing {sentence_type}: {sentence_text}") result = analyzer.analyze_sentence( sentence_text, sampling_ratio=0.1, max_combinations=50 ) sentence_results[sentence_type] = result print(f"[v0] {sentence_type} analysis completed") except Exception as e: print(f"[v0] Error analyzing {sentence_type}: {e}") sentence_results[sentence_type] = {'Bias Token Ranks': {}} print(f"[v0] SHAP analysis completed successfully") return { "sentence_results": sentence_results } except Exception as e: print(f"[v0] Error calculating SHAP: {e}") import traceback print(f"[v0] Full traceback: {traceback.format_exc()}") return { "error": str(e) } def analyze_dataset_bias(dataset_name, model_name, progress=gr.Progress()): """Analyze all sentences in a dataset and compute bias statistics""" progress(0, desc="Loading model...") model, tokenizer = load_model(model_name) # Get all sentences from dataset dataset_info = data_manager.datasets[dataset_name] sentences = dataset_info["sentences"] results = [] for idx, sentence_data in enumerate(progress.tqdm(sentences, desc="Analyzing sentences")): orig_pred = get_sentiment_prediction(sentence_data["original"], model, tokenizer) atomic1_pred = get_sentiment_prediction(sentence_data["mutant_1"], model, tokenizer) atomic2_pred = get_sentiment_prediction(sentence_data["mutant_2"], model, tokenizer) intersectional_pred = get_sentiment_prediction(sentence_data["intersectional"], model, tokenizer) atomic1_bias = orig_pred["label"] != atomic1_pred["label"] atomic2_bias = orig_pred["label"] != atomic2_pred["label"] intersectional_bias = orig_pred["label"] != intersectional_pred["label"] # Calculate distances js1, cos1 = calculate_distances(orig_pred["probabilities"], atomic1_pred["probabilities"]) js2, cos2 = calculate_distances(orig_pred["probabilities"], atomic2_pred["probabilities"]) js_int, cos_int = calculate_distances(orig_pred["probabilities"], intersectional_pred["probabilities"]) # Determine if hidden bias exists (intersectional bias without individual atomic bias) hidden_bias = intersectional_bias and not (atomic1_bias or atomic2_bias) # Determine atomic bias (any of the two) atomic_bias = atomic1_bias or atomic2_bias # Average atomic distance for boxplot grouping avg_atomic_js = (js1 + js2) / 2.0 avg_atomic_cos = (cos1 + cos2) / 2.0 results.append({ "sentence_idx": idx, "model": model_name, "original": sentence_data["original"][:100] + "..." if len(sentence_data["original"]) > 100 else sentence_data["original"], "word_1": sentence_data["word_1"], "replacement_1": sentence_data["replacement_1"], "word_2": sentence_data["word_2"], "replacement_2": sentence_data["replacement_2"], "atomic1_bias": atomic1_bias, "atomic2_bias": atomic2_bias, "atomic_bias": atomic_bias, "intersectional_bias": intersectional_bias, "hidden_bias": hidden_bias, "any_bias": atomic_bias or intersectional_bias, "js_atomic1": js1, "js_atomic2": js2, "js_atomic_avg": avg_atomic_js, "js_intersectional": js_int, "cos_atomic1": cos1, "cos_atomic2": cos2, "cos_atomic_avg": avg_atomic_cos, "cos_intersectional": cos_int, "orig_label": orig_pred["label"], "atomic1_label": atomic1_pred["label"], "atomic2_label": atomic2_pred["label"], "intersectional_label": intersectional_pred["label"] }) return results def create_bias_visualizations(dataset_name, model_selection): """Create comprehensive bias analysis visualizations""" # Determine which models to analyze if model_selection == "All Models": models_to_analyze = list(model_manager.model_configs.keys()) is_multi_model = True else: models_to_analyze = [model_selection] is_multi_model = False # Analyze each model all_results = [] for model_name in models_to_analyze: results = analyze_dataset_bias(dataset_name, model_name) all_results.extend(results) df = pd.DataFrame(all_results) # Create visualizations based on single or multi-model if is_multi_model: return create_multi_model_visualizations(df, dataset_name, models_to_analyze) else: return create_single_model_visualizations(df, dataset_name, model_selection) def create_single_model_visualizations(df, dataset_name, model_name): """Create visualizations for a single model""" total_samples = len(df) atomic_bias_pct = (df['atomic_bias'].sum() / total_samples) * 100 intersectional_bias_pct = (df['intersectional_bias'].sum() / total_samples) * 100 hidden_bias_pct = (df['hidden_bias'].sum() / total_samples) * 100 any_bias_pct = (df['any_bias'].sum() / total_samples) * 100 # 1. Bias Detection Rates fig1 = go.Figure(data=[ go.Bar( x=['Atomic', 'Intersectional', 'Hidden Intersectional', 'Any Bias'], y=[atomic_bias_pct, intersectional_bias_pct, hidden_bias_pct, any_bias_pct], marker_color=['#1b9e77', '#d95f02', '#7570b3', '#e7298a'], text=[f'{x:.1f}%' for x in [atomic_bias_pct, intersectional_bias_pct, hidden_bias_pct, any_bias_pct]], textposition='auto', ) ]) fig1.update_layout( title=f'Bias Detection Rates - {model_name} on {dataset_name}', xaxis_title='Bias Type', yaxis_title='Detection Rate (%)', yaxis_range=[0, 100], template='plotly_white', height=450 ) # 2. JSD Boxplots (4 groups: Atomic-Biased, Atomic-NonBiased, Intersectional-Biased, Intersectional-NonBiased) jsd_records = [] for _, row in df.iterrows(): # Intersectional jsd_records.append({ 'Category': 'Intersectional', 'Group': 'Biased' if row['intersectional_bias'] else 'Non-Biased', 'Distance': row['js_intersectional'] }) # Atomic (average) jsd_records.append({ 'Category': 'Atomic', 'Group': 'Biased' if row['atomic_bias'] else 'Non-Biased', 'Distance': row['js_atomic_avg'] }) jsd_df = pd.DataFrame(jsd_records) jsd_df['Subtype'] = jsd_df['Category'] + ' - ' + jsd_df['Group'] fig2 = go.Figure() colors = { 'Intersectional - Biased': '#d95f02', 'Intersectional - Non-Biased': '#fc8d62', 'Atomic - Biased': '#1b9e77', 'Atomic - Non-Biased': '#66c2a5', } for subtype in ['Intersectional - Biased', 'Intersectional - Non-Biased', 'Atomic - Biased', 'Atomic - Non-Biased']: data = jsd_df[jsd_df['Subtype'] == subtype]['Distance'] fig2.add_trace(go.Box( y=data, name=subtype, marker_color=colors[subtype], boxmean=True )) fig2.update_layout( title=f'Jensen-Shannon Distance Distribution - {model_name}', yaxis_title='JSD', xaxis_title='', template='plotly_white', height=450, showlegend=True ) # 3. Cosine Similarity Boxplots cos_records = [] for _, row in df.iterrows(): cos_records.append({ 'Category': 'Intersectional', 'Group': 'Biased' if row['intersectional_bias'] else 'Non-Biased', 'Similarity': row['cos_intersectional'] }) cos_records.append({ 'Category': 'Atomic', 'Group': 'Biased' if row['atomic_bias'] else 'Non-Biased', 'Similarity': row['cos_atomic_avg'] }) cos_df = pd.DataFrame(cos_records) cos_df['Subtype'] = cos_df['Category'] + ' - ' + cos_df['Group'] fig3 = go.Figure() for subtype in ['Intersectional - Biased', 'Intersectional - Non-Biased', 'Atomic - Biased', 'Atomic - Non-Biased']: data = cos_df[cos_df['Subtype'] == subtype]['Similarity'] fig3.add_trace(go.Box( y=data, name=subtype, marker_color=colors[subtype], boxmean=True )) fig3.update_layout( title=f'Cosine Similarity Distribution - {model_name}', yaxis_title='Cosine Similarity', xaxis_title='', template='plotly_white', height=450, showlegend=True ) # Statistics text stats_text = f""" ## 📊 Statistical Summary - {model_name} **Dataset:** {dataset_name} | **Total Samples:** {total_samples} ### Bias Detection Rates - **Atomic Bias:** {atomic_bias_pct:.1f}% ({df['atomic_bias'].sum()}/{total_samples}) - **Intersectional Bias:** {intersectional_bias_pct:.1f}% ({df['intersectional_bias'].sum()}/{total_samples}) - **Hidden Intersectional Bias:** {hidden_bias_pct:.1f}% ({df['hidden_bias'].sum()}/{total_samples}) - **Any Bias Detected:** {any_bias_pct:.1f}% ({df['any_bias'].sum()}/{total_samples}) ### Distance Metrics (Mean) - **JSD (Atomic):** {df['js_atomic_avg'].mean():.4f} - **JSD (Intersectional):** {df['js_intersectional'].mean():.4f} - **Cosine Sim (Atomic):** {df['cos_atomic_avg'].mean():.4f} - **Cosine Sim (Intersectional):** {df['cos_intersectional'].mean():.4f} """ return fig1, fig2, fig3, None, None, stats_text def create_multi_model_visualizations(df, dataset_name, models): """Create visualizations comparing multiple models""" # 1. Atomic and Intersectional side by side for each model fig1_data = [] for model in models: model_df = df[df['model'] == model] total = len(model_df) atomic_pct = (model_df['atomic_bias'].sum() / total) * 100 intersectional_pct = (model_df['intersectional_bias'].sum() / total) * 100 fig1_data.append(go.Bar( name=model, x=['Atomic', 'Intersectional'], y=[atomic_pct, intersectional_pct], text=[f'{atomic_pct:.1f}%', f'{intersectional_pct:.1f}%'], textposition='auto' )) fig1 = go.Figure(data=fig1_data) fig1.update_layout( title=f'Bias Detection Rates Comparison - {dataset_name}', xaxis_title='Bias Type', yaxis_title='Detection Rate (%)', yaxis_range=[0, 100], barmode='group', template='plotly_white', height=450 ) # 2. Hidden Intersectional for all models fig2_data = [] x_labels = [] y_values = [] for model in models: model_df = df[df['model'] == model] total = len(model_df) hidden_pct = (model_df['hidden_bias'].sum() / total) * 100 x_labels.append(model) y_values.append(hidden_pct) fig2 = go.Figure(data=[ go.Bar( x=x_labels, y=y_values, marker_color='#7570b3', text=[f'{v:.1f}%' for v in y_values], textposition='auto' ) ]) fig2.update_layout( title=f'Hidden Intersectional Bias Comparison - {dataset_name}', xaxis_title='Model', yaxis_title='Detection Rate (%)', yaxis_range=[0, 100], template='plotly_white', height=450, showlegend=False ) # 3. Model Overlap Venn (which samples are detected by which models) model_sets = {} for model in models: model_df = df[df['model'] == model] biased_indices = set(model_df[model_df['any_bias']]['sentence_idx']) model_sets[model] = biased_indices # Calculate overlaps for 3-way Venn if len(models) == 3: m1, m2, m3 = models set1, set2, set3 = model_sets[m1], model_sets[m2], model_sets[m3] only_1 = len(set1 - set2 - set3) only_2 = len(set2 - set1 - set3) only_3 = len(set3 - set1 - set2) overlap_12 = len((set1 & set2) - set3) overlap_13 = len((set1 & set3) - set2) overlap_23 = len((set2 & set3) - set1) overlap_all = len(set1 & set2 & set3) # Create Venn diagram using shapes fig3 = go.Figure() # Add circles as scatter plots with text fig3.add_trace(go.Scatter( x=[1.5, 2.5, 2], y=[2, 2, 1.2], mode='text', text=[m1, m2, m3], textfont=dict(size=14, color='black'), showlegend=False )) # Add overlap numbers fig3.add_trace(go.Scatter( x=[1.5, 2.5, 2, 2, 1.75, 2.25, 2], y=[2.3, 2.3, 0.9, 1.7, 1.8, 1.8, 1.4], mode='text', text=[f'{only_1}', f'{only_2}', f'{only_3}', f'{overlap_all}', f'{overlap_12}', f'{overlap_23}', f'{overlap_13}'], textfont=dict(size=16, color='darkblue'), showlegend=False )) # Add circles theta = np.linspace(0, 2*np.pi, 100) for center_x, center_y, color in [(1.5, 2, '#FF6B6B'), (2.5, 2, '#4ECDC4'), (2, 1.2, '#45B7D1')]: x_circle = center_x + 0.6 * np.cos(theta) y_circle = center_y + 0.6 * np.sin(theta) fig3.add_trace(go.Scatter( x=x_circle, y=y_circle, mode='lines', line=dict(color=color, width=3), fill='toself', fillcolor=color, opacity=0.3, showlegend=False )) fig3.update_layout( title=f'Model Bias Detection Overlap - {dataset_name}', xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False), template='plotly_white', height=500, width=600 ) else: # Simple bar chart for non-3-model case fig3 = go.Figure() # 4. JSD Boxplots for all models jsd_records = [] for _, row in df.iterrows(): jsd_records.append({ 'Model': row['model'], 'Category': 'Intersectional', 'Group': 'Biased' if row['intersectional_bias'] else 'Non-Biased', 'Distance': row['js_intersectional'] }) jsd_records.append({ 'Model': row['model'], 'Category': 'Atomic', 'Group': 'Biased' if row['atomic_bias'] else 'Non-Biased', 'Distance': row['js_atomic_avg'] }) jsd_df = pd.DataFrame(jsd_records) jsd_df['Subtype'] = jsd_df['Category'] + ' - ' + jsd_df['Group'] fig4 = go.Figure() colors = { 'Intersectional - Biased': '#d95f02', 'Intersectional - Non-Biased': '#fc8d62', 'Atomic - Biased': '#1b9e77', 'Atomic - Non-Biased': '#66c2a5', } for subtype in ['Intersectional - Biased', 'Intersectional - Non-Biased', 'Atomic - Biased', 'Atomic - Non-Biased']: for model in models: data = jsd_df[(jsd_df['Subtype'] == subtype) & (jsd_df['Model'] == model)]['Distance'] show_legend = (model == models[0]) fig4.add_trace(go.Box( y=data, name=subtype, legendgroup=subtype, marker_color=colors[subtype], boxmean=True, showlegend=show_legend, x=[model] * len(data), offsetgroup=subtype )) fig4.update_layout( title=f'Jensen-Shannon Distance Distribution - All Models', yaxis_title='JSD', xaxis_title='Model', template='plotly_white', height=450, boxmode='group' ) # 5. Cosine Similarity Boxplots for all models cos_records = [] for _, row in df.iterrows(): cos_records.append({ 'Model': row['model'], 'Category': 'Intersectional', 'Group': 'Biased' if row['intersectional_bias'] else 'Non-Biased', 'Similarity': row['cos_intersectional'] }) cos_records.append({ 'Model': row['model'], 'Category': 'Atomic', 'Group': 'Biased' if row['atomic_bias'] else 'Non-Biased', 'Similarity': row['cos_atomic_avg'] }) cos_df = pd.DataFrame(cos_records) cos_df['Subtype'] = cos_df['Category'] + ' - ' + cos_df['Group'] fig5 = go.Figure() for subtype in ['Intersectional - Biased', 'Intersectional - Non-Biased', 'Atomic - Biased', 'Atomic - Non-Biased']: for model in models: data = cos_df[(cos_df['Subtype'] == subtype) & (cos_df['Model'] == model)]['Similarity'] show_legend = (model == models[0]) fig5.add_trace(go.Box( y=data, name=subtype, legendgroup=subtype, marker_color=colors[subtype], boxmean=True, showlegend=show_legend, x=[model] * len(data), offsetgroup=subtype )) fig5.update_layout( title=f'Cosine Similarity Distribution - All Models', yaxis_title='Cosine Similarity', xaxis_title='Model', template='plotly_white', height=450, boxmode='group' ) # Statistics text stats_text = f"## 📊 Statistical Summary - All Models\n\n**Dataset:** {dataset_name}\n\n" for model in models: model_df = df[df['model'] == model] total = len(model_df) stats_text += f"\n### {model}\n" stats_text += f"- **Atomic Bias:** {(model_df['atomic_bias'].sum() / total * 100):.1f}%\n" stats_text += f"- **Intersectional Bias:** {(model_df['intersectional_bias'].sum() / total * 100):.1f}%\n" stats_text += f"- **Hidden Bias:** {(model_df['hidden_bias'].sum() / total * 100):.1f}%\n" return fig1, fig2, fig3, fig4, fig5, stats_text def run_bias_detection(dataset_name, sentence_display, model_name, show_distances, show_shapley): """Main function to run bias detection analysis""" try: sentences = data_manager.get_dataset_sentences(dataset_name) sentence_index = sentences.index(sentence_display) sentence_data = data_manager.get_sentence_data(dataset_name, sentence_index) # Get the actual sentence variations from the data original_sentence = sentence_data["original"] atomic1_sentence = sentence_data["mutant_1"] # Changed from "atomic_1" to "mutant_1" atomic2_sentence = sentence_data["mutant_2"] # Changed from "atomic_2" to "mutant_2" intersectional_sentence = sentence_data["intersectional"] except Exception as e: print(f"[v0] Error parsing sentence selection: {e}") return f"Error: Could not parse sentence selection - {str(e)}" # Load model model, tokenizer = load_model(model_name) mutations = { "original": original_sentence, "atomic_1": atomic1_sentence, "atomic_2": atomic2_sentence, "intersectional": intersectional_sentence } # Get predictions for all variations orig_pred = get_sentiment_prediction(mutations["original"], model, tokenizer) atomic1_pred = get_sentiment_prediction(mutations["atomic_1"], model, tokenizer) atomic2_pred = get_sentiment_prediction(mutations["atomic_2"], model, tokenizer) intersectional_pred = get_sentiment_prediction(mutations["intersectional"], model, tokenizer) atomic1_bias = orig_pred["label"] != atomic1_pred["label"] atomic2_bias = orig_pred["label"] != atomic2_pred["label"] intersectional_bias = orig_pred["label"] != intersectional_pred["label"] bias_detected = atomic1_bias or atomic2_bias or intersectional_bias results = f"""# 🔬 Bias Detection Analysis **Model:** {model_name} | **Dataset:** {dataset_name} --- ## 📊 Sentence Variations ### 🔸 Original Sentence > {mutations["original"]} **Prediction:** `{orig_pred["label"].upper()}` | **Probabilities:** {format_probabilities(orig_pred["probabilities"])} ### 🔸 Atomic Mutation 1 > {mutations["atomic_1"]} **Prediction:** `{atomic1_pred["label"].upper()}` | **Probabilities:** {format_probabilities(atomic1_pred["probabilities"])} ### 🔸 Atomic Mutation 2 > {mutations["atomic_2"]} **Prediction:** `{atomic2_pred["label"].upper()}` | **Probabilities:** {format_probabilities(atomic2_pred["probabilities"])} ### 🔸 Intersectional Mutation > {mutations["intersectional"]} **Prediction:** `{intersectional_pred["label"].upper()}` | **Probabilities:** {format_probabilities(intersectional_pred["probabilities"])} --- ## 🎯 Bias Detection Results ### {"⚠️ BIAS DETECTED" if bias_detected else "✅ NO BIAS DETECTED"} **🔍 Atomic Bias 1:** {"🚨 DETECTED" if atomic1_bias else "✅ NOT DETECTED"} *Original: {orig_pred["label"]} → Mutated: {atomic1_pred["label"]}* **🔍 Atomic Bias 2:** {"🚨 DETECTED" if atomic2_bias else "✅ NOT DETECTED"} *Original: {orig_pred["label"]} → Mutated: {atomic2_pred["label"]}* **🔍 Intersectional Bias:** {"🚨 DETECTED" if intersectional_bias else "✅ NOT DETECTED"} *Original: {orig_pred["label"]} → Mutated: {intersectional_pred["label"]}* """ if show_distances: js1, cos1 = calculate_distances(orig_pred["probabilities"], atomic1_pred["probabilities"]) js2, cos2 = calculate_distances(orig_pred["probabilities"], atomic2_pred["probabilities"]) js3, cos3 = calculate_distances(orig_pred["probabilities"], intersectional_pred["probabilities"]) results += f"""--- ## 📏 Distance Metrics Analysis ### 🔸 Atomic Mutation 1 **Jensen-Shannon Distance:** `{js1:.6f}` | **Cosine Similarity:** `{cos1:.6f}` ### 🔸 Atomic Mutation 2 **Jensen-Shannon Distance:** `{js2:.6f}` | **Cosine Similarity:** `{cos2:.6f}` ### 🔸 Intersectional Mutation **Jensen-Shannon Distance:** `{js3:.6f}` | **Cosine Similarity:** `{cos3:.6f}` """ if show_shapley: try: shap_data = calculate_shapley_values( mutations["original"], mutations["atomic_1"], mutations["atomic_2"], mutations["intersectional"], model_name ) if "error" in shap_data: results += f"""--- ## 🎯 SHAP Values Analysis *SHAP calculation failed: {shap_data["error"]}* *This feature requires significant computational resources.* """ else: results += f"""--- ## 🎯 SHAP Values Analysis - Bias Tokens Only """ def format_bias_tokens_from_analyzer(sentence_results, sentence_type, title): result = f"### 🔸 {title}\n\n" # Get bias token ranks from BiasAnalyzer results bias_token_ranks = sentence_results.get(sentence_type, {}).get('Bias Token Ranks', {}) if not bias_token_ranks: return result + "*No bias tokens detected*\n\n" for token, token_data in bias_token_ranks.items(): shap_val = token_data.get('shapley_value', 0.0) rank = token_data.get('rank', 'N/A') percentile = token_data.get('percentile', 'N/A') token_type = token_data.get('type', 'single_word') importance_level = "🔴 HIGH" if abs(shap_val) > 0.1 else "🟡 MED" if abs(shap_val) > 0.05 else "🟢 LOW" result += f"**{token}** | `{shap_val:.3f}` | {importance_level} | *rank: {rank} ({percentile}%) | type: {token_type}*\n\n" return result sentence_results = shap_data.get("sentence_results", {}) results += format_bias_tokens_from_analyzer(sentence_results, 'original', "Original Sentence Bias Tokens") results += format_bias_tokens_from_analyzer(sentence_results, 'atomic1', "Atomic Mutation 1 Bias Tokens") results += format_bias_tokens_from_analyzer(sentence_results, 'atomic2', "Atomic Mutation 2 Bias Tokens") results += format_bias_tokens_from_analyzer(sentence_results, 'intersectional', "Intersectional Mutation Bias Tokens") results += "### 🔸 Bias Token Rank Changes by Mutation Words\n\n" # Get mutation word information from sentence data word1 = sentence_data.get("word_1", "Word 1") replacement1 = sentence_data.get("replacement_1", "Replacement 1") word2 = sentence_data.get("word_2", "Word 2") replacement2 = sentence_data.get("replacement_2", "Replacement 2") original_ranks = sentence_results.get('original', {}).get('Bias Token Ranks', {}) atomic1_ranks = sentence_results.get('atomic1', {}).get('Bias Token Ranks', {}) atomic2_ranks = sentence_results.get('atomic2', {}).get('Bias Token Ranks', {}) intersectional_ranks = sentence_results.get('intersectional', {}).get('Bias Token Ranks', {}) # Track rank changes for mutation words mutation_changes_found = False # Check Word 1 -> Replacement 1 (Atomic Mutation 1) results += f"**Word 1 ({word1} → {replacement1}):**\n\n" replacement1_lower = replacement1.lower() word1_lower = word1.lower() # Check if replacement word appears in atomic1 mutation replacement1_found = False for token, token_data in atomic1_ranks.items(): if token.lower() == replacement1_lower: atomic1_rank = token_data['rank'] # Check if original word was in original sentence original_word_found = False for orig_token, orig_data in original_ranks.items(): if orig_token.lower() == word1_lower: orig_rank = orig_data['rank'] rank_diff = atomic1_rank - orig_rank change_indicator = "📈" if rank_diff < 0 else "📉" if rank_diff > 0 else "➡️" results += f"- **{replacement1}**: {orig_rank} → {atomic1_rank} {change_indicator}\n\n" mutation_changes_found = True original_word_found = True replacement1_found = True break if not original_word_found: results += f"- **{replacement1}**: New bias token (rank: {atomic1_rank})\n\n" mutation_changes_found = True replacement1_found = True break if not replacement1_found: # Check if replacement word might be detected under different tokenization for token, token_data in atomic1_ranks.items(): if replacement1_lower in token.lower() or token.lower() in replacement1_lower: atomic1_rank = token_data['rank'] original_word_found = False for orig_token, orig_data in original_ranks.items(): if orig_token.lower() == word1_lower: orig_rank = orig_data['rank'] rank_diff = atomic1_rank - orig_rank change_indicator = "📈" if rank_diff < 0 else "📉" if rank_diff > 0 else "➡️" results += f"- **{token}** (from {replacement1}): {orig_rank} → {atomic1_rank} {change_indicator}\n\n" mutation_changes_found = True original_word_found = True replacement1_found = True break if not original_word_found: results += f"- **{token}** (from {replacement1}): New bias token (rank: {atomic1_rank})\n\n" mutation_changes_found = True replacement1_found = True break if not replacement1_found: results += f"- **{replacement1}**: Not detected as bias token\n\n" # Check Word 2 -> Replacement 2 (Atomic Mutation 2) results += f"**Word 2 ({word2} → {replacement2}):**\n\n" replacement2_lower = replacement2.lower() word2_lower = word2.lower() replacement2_found = False for token, token_data in atomic2_ranks.items(): if token.lower() == replacement2_lower: atomic2_rank = token_data['rank'] # Check if original word was in original sentence original_word_found = False for orig_token, orig_data in original_ranks.items(): if orig_token.lower() == word2_lower: orig_rank = orig_data['rank'] rank_diff = atomic2_rank - orig_rank change_indicator = "📈" if rank_diff < 0 else "📉" if rank_diff > 0 else "➡️" results += f"- **{replacement2}**: {orig_rank} → {atomic2_rank} {change_indicator}\n\n" mutation_changes_found = True original_word_found = True replacement2_found = True break if not original_word_found: results += f"- **{replacement2}**: New bias token (rank: {atomic2_rank})\n\n" mutation_changes_found = True replacement2_found = True break if not replacement2_found: # Check if replacement word might be detected under different tokenization for token, token_data in atomic2_ranks.items(): if replacement2_lower in token.lower() or token.lower() in replacement2_lower: atomic2_rank = token_data['rank'] original_word_found = False for orig_token, orig_data in original_ranks.items(): if orig_token.lower() == word2_lower: orig_rank = orig_data['rank'] rank_diff = atomic2_rank - orig_rank change_indicator = "📈" if rank_diff < 0 else "📉" if rank_diff > 0 else "➡️" results += f"- **{token}** (from {replacement2}): {orig_rank} → {atomic2_rank} {change_indicator} (Δ{rank_diff:+d})\n\n" mutation_changes_found = True original_word_found = True replacement2_found = True break if not original_word_found: results += f"- **{token}** (from {replacement2}): New bias token (rank: {atomic2_rank})\n\n" mutation_changes_found = True replacement2_found = True break if not replacement2_found: results += f"- **{replacement2}**: Not detected as bias token\n\n" # Check Intersectional changes results += f"**Intersectional Mutation ({word1}→{replacement1} + {word2}→{replacement2}):**\n\n" intersectional_changes_found = False replacement1_intersectional_found = False for token, token_data in intersectional_ranks.items(): if token.lower() == replacement1_lower: intersectional_rank = token_data['rank'] original_word_found = False for orig_token, orig_data in original_ranks.items(): if orig_token.lower() == word1_lower: orig_rank = orig_data['rank'] rank_diff = intersectional_rank - orig_rank change_indicator = "📈" if rank_diff < 0 else "📉" if rank_diff > 0 else "➡️" results += f"- **{replacement1}**: {orig_rank} → {intersectional_rank} {change_indicator} (Δ{rank_diff:+d})\n" intersectional_changes_found = True original_word_found = True replacement1_intersectional_found = True break if not original_word_found: results += f"- **{replacement1}**: New bias token (rank: {intersectional_rank})\n" intersectional_changes_found = True replacement1_intersectional_found = True break if not replacement1_intersectional_found: # Check partial matches for replacement 1 for token, token_data in intersectional_ranks.items(): if replacement1_lower in token.lower() or token.lower() in replacement1_lower: intersectional_rank = token_data['rank'] original_word_found = False for orig_token, orig_data in original_ranks.items(): if orig_token.lower() == word1_lower: orig_rank = orig_data['rank'] rank_diff = intersectional_rank - orig_rank change_indicator = "📈" if rank_diff < 0 else "📉" if rank_diff > 0 else "➡️" results += f"- **{token}** (from {replacement1}): {orig_rank} → {intersectional_rank} {change_indicator} (Δ{rank_diff:+d})\n" intersectional_changes_found = True original_word_found = True replacement1_intersectional_found = True break if not original_word_found: results += f"- **{token}** (from {replacement1}): New bias token (rank: {intersectional_rank})\n" intersectional_changes_found = True replacement1_intersectional_found = True break replacement2_intersectional_found = False for token, token_data in intersectional_ranks.items(): if token.lower() == replacement2_lower: intersectional_rank = token_data['rank'] original_word_found = False for orig_token, orig_data in original_ranks.items(): if orig_token.lower() == word2_lower: orig_rank = orig_data['rank'] rank_diff = intersectional_rank - orig_rank change_indicator = "📈" if rank_diff < 0 else "📉" if rank_diff > 0 else "➡️" results += f"- **{replacement2}**: {orig_rank} → {intersectional_rank} {change_indicator} (Δ{rank_diff:+d})\n" intersectional_changes_found = True original_word_found = True replacement2_intersectional_found = True break if not original_word_found: results += f"- **{replacement2}**: New bias token (rank: {intersectional_rank})\n" intersectional_changes_found = True replacement2_intersectional_found = True break if not replacement2_intersectional_found: # Check partial matches for replacement 2 for token, token_data in intersectional_ranks.items(): if replacement2_lower in token.lower() or token.lower() in replacement2_lower: intersectional_rank = token_data['rank'] original_word_found = False for orig_token, orig_data in original_ranks.items(): if orig_token.lower() == word2_lower: orig_rank = orig_data['rank'] rank_diff = intersectional_rank - orig_rank change_indicator = "📈" if rank_diff < 0 else "📉" if rank_diff > 0 else "➡️" results += f"- **{token}** (from {replacement2}): {orig_rank} → {intersectional_rank} {change_indicator} (Δ{rank_diff:+d})\n" intersectional_changes_found = True original_word_found = True replacement2_intersectional_found = True break if not original_word_found: results += f"- **{token}** (from {replacement2}): New bias token (rank: {intersectional_rank})\n" intersectional_changes_found = True replacement2_intersectional_found = True break if not intersectional_changes_found: results += "*No bias tokens detected for intersectional mutation words*\n" if not mutation_changes_found and not intersectional_changes_found: results += "*No bias tokens detected for mutation words*\n" except Exception as e: results += f"""--- ## 🎯 SHAP Values Analysis *SHAP calculation failed: {str(e)}* *This feature requires significant computational resources.* """ return results def format_probabilities(probs_dict): """Format probability dictionary for display""" return " | ".join([f"{k}: {v:.6f}" for k, v in probs_dict.items()]) def update_sentences(dataset_name): """Update sentence dropdown based on selected dataset""" try: sentences = data_manager.get_dataset_sentences(dataset_name) return gr.Dropdown(choices=sentences, value=sentences[0] if sentences else None) except Exception as e: print(f"[v0] Error updating sentences: {e}") return gr.Dropdown(choices=[], value=None) # Initialize datasets load_datasets() # Create Gradio interface with gr.Blocks(title="Bias Detection Framework", theme=gr.themes.Soft()) as demo: gr.Markdown("# 🔬 Financial Bias Detection Framework") gr.Markdown("Demo interface for detecting bias in financial sentiment analysis models") with gr.Tabs(): # Tab 1: Individual Sentence Analysis with gr.Tab("📝 Individual Sentence Analysis"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("## ⚙️ Configuration") dataset_dropdown = gr.Dropdown( choices=["FPB", "FinSen"], label="📊 Select Dataset", value="FPB" ) sentence_dropdown = gr.Dropdown( choices=[], label="📝 Select Sentence", interactive=True ) model_dropdown = gr.Dropdown( choices=list(model_manager.model_configs.keys()), label="🤖 Select Model", value="FinBERT" ) show_distances = gr.Checkbox( label="📏 Show Original to Mutated Distances", value=False ) show_shapley = gr.Checkbox( label="🎯 Show SHAP Values", value=False ) analyze_btn = gr.Button("🚀 Run Bias Analysis", variant="primary") with gr.Column(scale=2): gr.Markdown("## 📋 Results") results_output = gr.Markdown("") # Event handlers for Tab 1 dataset_dropdown.change( fn=update_sentences, inputs=[dataset_dropdown], outputs=[sentence_dropdown] ) analyze_btn.click( fn=run_bias_detection, inputs=[dataset_dropdown, sentence_dropdown, model_dropdown, show_distances, show_shapley], outputs=[results_output] ) # Tab 2: Dataset Statistics & Visualizations with gr.Tab("📊 Dataset Statistics & Visualizations"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("## ⚙️ Configuration") viz_dataset_dropdown = gr.Dropdown( choices=["FPB", "FinSen"], label="📊 Select Dataset Sample", value="FPB" ) viz_model_dropdown = gr.Dropdown( choices=["All Models"] + list(model_manager.model_configs.keys()), label="🤖 Select Model(s)", value="All Models" ) generate_viz_btn = gr.Button("📈 Generate Visualizations", variant="primary", size="lg") gr.Markdown(""" ### 💡 About This tab analyzes the dataset sample and provides: - **Bias Detection Rates**: Overall detection percentages - **Hidden Intersectional Bias**: Bias only in intersectional mutations - **Model Overlap** (All Models): Venn diagram showing which models detect bias in the same samples - **JSD/Cosine Distributions**: Boxplots grouped by bias type and status Select "All Models" to compare all models side-by-side. """) with gr.Column(scale=2): gr.Markdown("## 📊 Visualization Results") stats_md = gr.Markdown("") # Plots container (shown after generation) plots_container = gr.Column(visible=True) with plots_container: plot1 = gr.Plot(visible=False) plot2 = gr.Plot(visible=False) plot3 = gr.Plot(visible=False) plot4 = gr.Plot(visible=False) plot5 = gr.Plot(visible=False) # Event handler for Tab 2 def generate_and_show(dataset, model): fig1, fig2, fig3, fig4, fig5, stats = create_bias_visualizations(dataset, model) # Determine visibility based on what's returned updates = [ gr.update(value=fig1, visible=True) if fig1 is not None else gr.update(visible=False), gr.update(value=fig2, visible=True) if fig2 is not None else gr.update(visible=False), gr.update(value=fig3, visible=True) if fig3 is not None else gr.update(visible=False), gr.update(value=fig4, visible=True) if fig4 is not None else gr.update(visible=False), gr.update(value=fig5, visible=True) if fig5 is not None else gr.update(visible=False), stats ] return updates generate_viz_btn.click( fn=generate_and_show, inputs=[viz_dataset_dropdown, viz_model_dropdown], outputs=[plot1, plot2, plot3, plot4, plot5, stats_md] ) # Initialize sentence dropdown on load demo.load( fn=update_sentences, inputs=[dataset_dropdown], outputs=[sentence_dropdown] ) if __name__ == "__main__": demo.launch()