Spaces:
Sleeping
Sleeping
File size: 13,229 Bytes
cdd3fb5 cacbc07 cdd3fb5 e166b24 cdd3fb5 4694bcd cdd3fb5 4694bcd cdd3fb5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | ---
title: "BiasGuard Pro"
emoji: "π‘οΈ"
colorFrom: "purple"
colorTo: "pink"
sdk: "gradio"
sdk_version: "6.2.0"
python_version: "3.10"
app_file: "app.py"
pinned: false
---
<div align="center">
<img src="assets/dashboard.png" alt="BiasXplainer Dashboard Preview" width="820"/>






**An Explainable Text Bias Auditing & Counterfactual Suggestion Toolkit**
[π Live Demo](#live-demo) | [β¨ Features](#features) | [π― Usage Guide](#usage-guide) | [π§ Technical Details](#technical-details) | [π€ Contributing](#contributing)
</div>
---
## π Overview
**BiasXplainer** (a.k.a. BiasGuard Pro) is an interactive and programmatic toolkit for:
- π Detecting potential bias (e.g. gendered language) in short text inputs
- π§ͺ Explaining classifier outputs via token-level SHAP attributions (with graceful fallbacks)
- π Generating neutral counterfactual rewrites while preserving semantics
- π Running batch analyses with aggregation statistics & comparative subgroup views
- π Exporting structured outputs (JSON/CSV) for downstream pipelines
This toolkit is designed as an **exploratory auditing aid**βideal for rapid experimentation, prototype fairness evaluation, educational demonstrations, and workflow integration proof-of-concepts.
> β οΈ **Important**: This is **not** a definitive bias measurement instrument. For production or compliance use:
> - Apply validated, domain-appropriate bias and fairness metrics
> - Use diverse, representative corpora (not isolated sentences)
> - Incorporate human review and domain expertise
> - Follow established AI ethics & governance frameworks
---
## π― Purpose & Scope
BiasXplainer helps you:
- Understand *why* a sentence may be flagged: token impacts clearly visualized
- Explore neutral alternatives via structured counterfactual suggestions
- Analyze variability across groups in batch mode (substring-based comparative lens)
- Export artifacts for integration with other auditing pipelines
---
## π Why This Toolkit?
| Goal | How It's Achieved |
|------|-------------------|
| Transparency | Token-level impact via SHAP + heuristic fallback |
| Counterfactual Exploration | Template + semantic replacements + FLANβT5 polish |
| Batch Insight | Aggregated stats: mean bias, class distribution, top impactful terms |
| Fairness Prototyping | Simple comparative view (e.g., βwomenβ vs βmenβ substring focus) |
| Extensibility | Modular architecture for adding models / exporters / fairness metrics |
| Developer Friendliness | Clean Python modules + minimal dependency surface |
---
<a id="features"></a>
## β¨ Features
### π¬ Core Capabilities
- **Single Text Analysis**: Bias score + classification + SHAP impact chart + highlighted tokens
- **Counterfactual Suggestions**: Structured rewrite candidates (neutralization focus)
- **Batch Mode**: Accepts `.txt`, `.csv`, `.json` and runs background jobs
- **Comparative View**: Substring-based group comparison (basic fairness proxy)
- **Exports**: JSON & CSV from UI or programmatic API
- **Model Override**: Auto-load local fine-tuned DistilBERT if present under `./models/`
- **Profiling Panel**: Inline latency breakdown (tokenization, SHAP, rewrite phases)
### π§© Extended Features
- β‘ Parallel bias + SHAP computation
- π§ͺ Resilient fallback keyword scoring if SHAP fails
- π FLANβT5-backed grammar polishing for counterfactuals
- π§± Batched inference APIs (`predict_batch_batched`)
- π§ͺ Hooks for future fairness metrics (equalized odds, subgroup performance gaps)
---
<a id="live-demo"></a>
## π Live Demo
Try it instantly on Hugging Face Spaces:
### π [Launch Interactive Demo](https://huggingface.co/spaces/Dyra1204/BiasGuard-Pro)
---
## π Project Structure
```
BiasXplainer/
β
βββ main.py # Gradio entrypoint (BiasGuardDashboard)
βββ requirements.txt # Python dependencies
βββ README.md # This file
β
βββ core/
β βββ bias_detector.py # DistilBERT classifier logic
β βββ explainer.py # SHAP integration + fallback heuristic
β βββ counterfactuals.py # Rewrite engine + FLANβT5 polishing
β βββ utils.py # Helpers (token merging, formatting, etc.)
β
βββ export/
β βββ json_export.py # JSON serialization helper
β βββ csv_export.py # CSV serialization helper
β
βββ models/ # (Optional) Local fine-tuned model artifacts
βββ tests/ # Pytest suite (add fairness & stability tests)
βββ docs/
β βββ usage.md # Advanced usage patterns
β βββ api.md # Programmatic interface reference
β βββ roadmap.md # Extended roadmap details
β
βββ assets/ # (Optional) Screenshots / banners
βββ results/
β βββ latency_before_after.csv # Placeholder performance metrics file
βββ LICENSE # MIT license (add full text)
```
---
<a id="usage-guide"></a>
## π― Usage Guide
### Quick Start (Local)
```bash
git clone https://github.com/dyra-12/BiasXplainer.git
cd BiasXplainer
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python main.py
```
Open the printed local URL to start auditing text.
### GUI Workflows
1. **Single Analysis** β Paste text β Analyze β View bias score, class, SHAP token chart, highlighted impacts, and counterfactual suggestions.
2. **Batch & Compare** β Paste multi-line text OR upload `.txt / .csv / .json` β Start job β Poll status β Download results. Optionally specify two substrings (e.g., `women`, `men`).
3. **Export** β Use Export buttons (JSON/CSV) or programmatic API calls. Files saved under `./export/`.
### Supported Input Formats
| Format | Structure |
|--------|-----------|
| `.txt` | Newline-separated sentences |
| `.csv` | Must include a `text` column (fallback to first column) |
| `.json` | List of strings OR list of objects with `text` field |
### Minimal Programmatic API
```python
from main import BiasGuardDashboard
dashboard = BiasGuardDashboard()
texts = [
"Women should be nurses because they are compassionate.",
"Men are naturally better at engineering roles.",
"This is a neutral sentence."
]
results = dashboard.analyzer.detector.predict_batch_batched(texts)
print(results) # [{'bias_probability': ..., 'classification': ..., 'confidence': ...}, ...]
```
---
## π§ͺ Example Analysis Flow
```
1. User enters text
2. BiasDetector.predict_bias(text) β {probability, class, confidence}
3. Explainer.get_shap_values(text) β token-level impacts
4. CounterfactualGenerator.generate_counterfactuals(text, shap) β neutral rewrite candidates
5. UI renders gauge + impact bar + highlighted text + suggestions + profiling
```
### Batch Flow
- Batched DistilBERT inference
- Async background job collects: mean bias probability, class distribution counts, top impactful tokens
- Optional simple substring comparison overlay
---
<a id="technical-details"></a>
## π§ Technical Details
### Core Modules
| Module | Responsibility |
|--------|----------------|
| `core/bias_detector.py` | DistilBERT-based classification (single + batched + efficient batching) |
| `core/explainer.py` | SHAP token attribution + fallback keyword heuristic |
| `core/counterfactuals.py` | Template-driven neutralization + FLANβT5 grammar refinement |
| `export/json_export.py` | Structured JSON serialization |
| `export/csv_export.py` | CSV export with impact flattening |
| `main.py` | Gradio composition, UI orchestration, profiling |
### Models
- **Classifier**: DistilBERT (`distilbert-base-uncased` or local fine-tune under `./models`)
- **Polisher**: `google/flan-t5-small` (light rewrite improvements)
### Performance Strategy
- Parallel futures for classifier + SHAP tasks
- Batching reduces tokenizer & forward overhead
- Token merging converts subword fragments into user-friendly units
- Inline profiling block surfaces latency bottlenecks
### Counterfactual Strategy
1. Extract high-impact tokens (SHAP or fallback keyword list)
2. Apply neutral replacements or paraphrase templates
3. Polish grammar & semantics via FLANβT5 Small
4. Return ranked suggestions (preserving original intent)
---
## π Performance
Record metrics in `results/latency_before_after.csv` (create if missing).
The project stores per-step latency measurements with the CSV schema: `step,before_s,after_s,improvement_pct`.
| Step | Before (s) | After (s) | Improvement (%) |
|------|-----------:|----------:|----------------:|
| predict_bias | 0.90 | 0.35 | 61.11 |
| get_shap_values | 24.00 | 6.60 | 72.50 |
| generate_counterfactuals | 2.50 | 1.00 | 60.00 |
| create_shap_chart | 0.80 | 0.50 | 37.50 |
| create_bias_meter | 0.20 | 0.15 | 25.00 |
| highlight_biased_words | 0.60 | 0.40 | 33.33 |
| total | 29.00 | 9.00 | 68.97 |
---
## β
Testing
```bash
pytest -q
```
Recommended test categories:
- Neutral vs biased fixtures (classification stability)
- SHAP fallback path when primary explainer errors
- Export correctness (headers + row counts)
- Deterministic counterfactual generation for controlled inputs
---
## πΊ Roadmap
Short-Term:
- Live progress streaming (websocket / SSE)
- Extended fairness metrics (e.g., equalized odds, subgroup delta charts)
- Persistent job queue (Celery / RQ + Redis)
- Confidence calibration & uncertainty indicators
- Pluggable backbone registry (RoBERTa, DeBERTa, ALBERT)
Long-Term:
- Embedding-based semantic group comparison
- Multi-lingual model support
- Explanation fusion (SHAP + Integrated Gradients comparison)
- Audit session export bundles (results + metadata + configuration hash)
---
## π Use Cases
### Research
- Rapid prototyping of bias detection workflows
- Comparing attribution stability across variants
### Industry
- Early-stage content moderation tool exploration
- Internal fairness experimentation sandbox
### Education
- Teaching interpretability concepts interactively
- Student projects on ethical AI + XAI
---
<a id="contributing"></a>
## π€ Contributing
We welcome improvements!
### Ways to Contribute
1. π Bug Reports: Open an issue with reproduction steps
2. β¨ Feature Requests: Suggest metrics, exporters, or model options
3. π Documentation: Improve guides, add examples
4. π» Code: Submit well-scoped PRs with tests
5. π Performance: Optimize latency & update benchmarking CSV
### Development Setup
```bash
# Fork the repo, then:
git clone https://github.com/YOUR-USERNAME/BiasXplainer.git
cd BiasXplainer
# Create a branch
git checkout -b feat/your-feature-name
# Install & test
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
pytest -q
# Commit & push
git commit -m "Feat: descriptive summary"
git push origin feat/your-feature-name
```
### Code Style
- Follow PEP 8
- Use type hints where practical
- Add docstrings to public functions
- Include tests for new logic paths
- Avoid large, multi-purpose PRs
---
## βοΈ Ethical Use & Disclaimer
This toolkit provides **heuristic insights** into potential linguistic bias patterns. It does **not** guarantee:
- Fairness across real-world demographic groups
- Complete coverage of subtle stereotypes
- Context-aware ethical judgments
Always complement automated signals with:
- Human expert review
- Diverse, representative evaluation sets
- Formal fairness metrics and governance policies
---
## π Security Notes
- Avoid submitting PII or confidential corpora to public hosted demos.
- For enterprise usage: run locally, restrict model paths, audit dependencies.
- Consider dependency pinning & vulnerability scanning (e.g., `pip-audit`, `safety`).
---
## π License
This project is licensed under the **MIT License** β see the [LICENSE](LICENSE) file.
```
MIT License
Copyright (c) 2024 BiasXplainer Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction...
[Full license text here]
```
---
## π Additional Resources
- `docs/usage.md` β Advanced usage & troubleshooting
- `docs/api.md` β Programmatic interface guide
- `docs/roadmap.md` β Expanded roadmap details (optional)
- Hugging Face Transformers Docs: https://huggingface.co/docs/transformers
- SHAP Documentation: https://shap.readthedocs.io/
---
## π¬ Contact & Support
- Email: dyutidasmahaptra@gmail.com
- Hugging Face Space: https://huggingface.co/spaces/Dyra1204/BiasGuard-Pro
<div align="center">
**Built with β€οΈ by the community**
[β¬ Back to Top](#-overview)
</div>
|