Skip to content

About

NLP-based financial complaint classification, priority scoring, and department routing system served via FastAPI and Streamlit

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Complaint Intelligence System

NLP-Based Financial Complaint Classification and Priority Routing

1. Problem Statement

Financial institutions and regulators receive tens of thousands of consumer complaints every year through the CFPB's public complaint pipeline. Manually reading, categorizing, prioritizing, and routing each complaint to the right team is slow and inconsistent. This project builds an automated Complaint Intelligence System that classifies a complaint's underlying Issue from its free-text narrative, assigns a priority level, and recommends a routing department — all served through a FastAPI backend.

2. Business Objective

  • Reduce manual triage time for incoming financial complaints.
  • Surface high-risk complaints (fraud, identity theft, legal threats) for immediate attention via rule-based priority scoring.
  • Provide a consistent, auditable classification + routing decision that can plug into a support/ops workflow (ticketing system, dashboard, etc.).
  • Demonstrate a full, production-shaped ML system: real data ingestion, reproducible preprocessing, model comparison/tuning, and a served API — not just a notebook.

3. Architecture

CFPB Consumer Complaint Database API
              |
              v
   FastAPI Data Fetching Layer        (app/api/routes_data.py, services/cfpb_client.py)
              |
              v
      Raw Dataset Storage             (data/raw/cfpb_complaints_raw.csv)
              |
              v
 Data Cleaning + NLP Preprocessing    (services/preprocessing_service.py, utils/text_cleaner.py)
              |
              v
  Feature Engineering + Vectorization (TF-IDF, engineered text features)
              |
              v
        ML Model Training             (services/model_training_service.py)
              |
              v
       Saved Model Artifacts          (models/*.pkl, models/metrics.json)
              |
              v
      FastAPI Prediction API          (app/api/routes_prediction.py)
              |
              v
   User / Streamlit UI / Swagger Docs

FastAPI is the intermediary layer at every stage: it is the only component that talks to the CFPB API, the only component that touches the trained model, and the only interface the outside world (UI, other services, or a human via Swagger docs) interacts with.

4. Dataset Source

  • Source: CFPB Consumer Complaint Database API (public, no API key required).
  • Verified live endpoint: https://www.consumerfinance.gov/data-research/consumer-complaints/search/api/v1/
  • Key params used: size, frm (pagination offset), has_narrative, product, state, company, date_received_min, date_received_max, no_aggs.
  • Gotcha discovered during integration: the API's WAF returns 403 for custom/browser-spoofed User-Agent headers but allows default tool UAs (curl/..., python-httpx/...) — so the client deliberately does not override the User-Agent. Also, sorting by created_date_desc clusters mass-filed near-duplicate template complaints together and tanks post-dedup yield (~6% unique); using the API's default relevance-style ordering instead yields ~60%+ unique narratives per page.

5. Features Used

Raw fields collected: Complaint ID, Date received, Product, Sub-product, Issue, Sub-issue, Consumer complaint narrative, Company, State, Submitted via, Company response to consumer, Timely response?

Model input: TF-IDF vectors (unigrams + bigrams, max_features=20000) over the cleaned Consumer complaint narrative.

Engineered features (EDA/analytics): character count, word count, sentence count, average word length, stopword count, punctuation count, digit count, capital letter count.

Target: Issue.

6. Tech Stack

Python, FastAPI, Uvicorn, Pydantic, HTTPX, Pandas, NumPy, Scikit-learn, Imbalanced-learn, NLTK, Matplotlib, Seaborn, WordCloud, Joblib, Pytest, Streamlit.

7. EDA Summary

Full EDA lives in notebooks/complaint_intelligence_eda_modeling.ipynb. Highlights:

  • The Issue target is long-tailed and imbalanced; rare classes (< MIN_CLASS_COUNT examples) are filtered out before training.
  • Complaint narratives are heavily duplicated in the raw CFPB feed (template filings); deduplication is essential before train/test splitting.
  • Narrative length (char/word/sentence count) is right-skewed; the engineered length features correlate strongly with each other but weakly with average word length.
  • A word cloud and per-class top-word analysis confirm each issue category has a distinguishable vocabulary fingerprint, supporting a TF-IDF/bag-of- words modeling approach.

8. Model Comparison

Trained on 12,054 processed complaints across 54 issue classes (9,643 train / 2,411 test, 80/20 stratified split, random_state=42):

Model Accuracy Precision (weighted) Recall (weighted) F1 (weighted)
Multinomial Naive Bayes 0.359 0.328 0.359 0.250
Decision Tree 0.362 0.354 0.362 0.357
K-Nearest Neighbors 0.456 0.443 0.456 0.438

Live numbers are always available via GET /model/evaluate or python scripts/evaluate_model.py; the full comparison table is under all_model_scores in the /model/train response and in models/metrics.json.

9. Best Model Result

K-Nearest Neighbors was selected (highest weighted F1) and tuned with RandomizedSearchCV to {'weights': 'distance', 'n_neighbors': 21, 'metric': 'cosine'}, improving to:

Metric Score
Accuracy 0.493
Precision (weighted) 0.484
Recall (weighted) 0.493
F1-score (weighted) 0.461

Persisted to models/trained_model.pkl. See models/metrics.json for the full classification report and reports/figures/confusion_matrix.png for the confusion matrix. With 54 fine-grained issue classes (several semantically overlapping, e.g. multiple credit-reporting-dispute variants), this is a reasonable classical-ML baseline result — see Section 18 (Limitations) in the project report for discussion.

10. API Endpoint Documentation

Method Path Description
GET / Project name, status, version
GET /health API/model/dataset availability
GET /data/fetch Fetch complaints from CFPB, save raw CSV
GET /data/summary Summary stats over the raw dataset
POST /data/preprocess Clean/dedupe/engineer features, save processed CSV
POST /model/train Train, tune, and save the best classifier
GET /model/evaluate Return saved model metrics
POST /predict Classify a single complaint
POST /predict/batch Classify a list of complaints
GET /analytics/overview Aggregated dataset analytics

Interactive docs: http://localhost:8000/docs (Swagger) once the server is running.

Example: POST /predict

Request:

{
  "complaint_text": "My credit report shows an account I never opened and the company is refusing to remove it."
}

Response:

{
  "predicted_issue": "Incorrect information on your report",
  "confidence_score": 0.87,
  "priority": "High",
  "priority_reason": "Contains high-risk keyword: 'credit report error'",
  "recommended_department": "Credit Reporting Dispute Team",
  "cleaned_text": "credit report show account never opened company refusing remove",
  "top_predictions": [
    {"issue": "Incorrect information on your report", "confidence": 0.87},
    {"issue": "Improper use of your report", "confidence": 0.08},
    {"issue": "Problem with a credit reporting company's investigation", "confidence": 0.03}
  ]
}

11. Setup Instructions

git clone <this-repo>
cd complaint-intelligence-system
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -r requirements.txt
python -c "import nltk; [nltk.download(p) for p in ['punkt','punkt_tab','stopwords','wordnet','omw-1.4']]"

12. How to Fetch Data

python scripts/fetch_data.py --size 10000
# or via the running API:
curl "http://localhost:8000/data/fetch?size=10000&has_narrative=true"

13. How to Preprocess Data

curl -X POST "http://localhost:8000/data/preprocess"

14. How to Train the Model

python scripts/train_model.py
# or:
curl -X POST "http://localhost:8000/model/train"

15. How to Run FastAPI

uvicorn app.main:app --reload
# or:
python run_api.py

Visit http://localhost:8000/docs for interactive Swagger docs.

16. How to Make a Prediction

curl -X POST "http://localhost:8000/predict" \
  -H "Content-Type: application/json" \
  -d '{"complaint_text": "My credit report shows an account I never opened and the company is refusing to remove it."}'

17. Optional Streamlit UI

uvicorn app.main:app --reload &
streamlit run streamlit_app.py

18. Folder Structure

complaint-intelligence-system/
├── app/
│   ├── main.py
│   ├── config.py
│   ├── schemas.py
│   ├── api/
│   │   ├── routes_data.py
│   │   ├── routes_model.py
│   │   ├── routes_prediction.py
│   │   └── routes_analytics.py
│   ├── services/
│   │   ├── cfpb_client.py
│   │   ├── data_service.py
│   │   ├── preprocessing_service.py
│   │   ├── model_training_service.py
│   │   ├── prediction_service.py
│   │   └── routing_service.py
│   └── utils/
│       ├── text_cleaner.py
│       └── logger.py
├── data/
│   ├── raw/
│   └── processed/
├── models/
│   ├── trained_model.pkl
│   ├── vectorizer.pkl
│   ├── label_encoder.pkl
│   └── metrics.json
├── notebooks/
│   └── complaint_intelligence_eda_modeling.ipynb
├── reports/
│   ├── figures/
│   └── Project_Report.md
├── scripts/
│   ├── fetch_data.py
│   ├── train_model.py
│   └── evaluate_model.py
├── tests/
│   ├── test_api.py
│   ├── test_preprocessing.py
│   └── test_prediction.py
├── streamlit_app.py
├── README.md
├── requirements.txt
├── .gitignore
└── run_api.py

19. Future Scope

  • Replace TF-IDF with transformer embeddings (e.g. sentence-transformers) to better disambiguate semantically-close issue categories.
  • Add Product, Company response to consumer, and Timely response? as secondary prediction targets.
  • Blend engineered numerical features with TF-IDF via ColumnTransformer/ FeatureUnion once a baseline is validated.
  • Add authentication and rate limiting for a multi-tenant deployment.
  • Persist predictions + human feedback for active-learning-based model improvement.

20. Screenshots

Add Swagger UI and Streamlit UI screenshots here after running the app locally (reports/figures/).

21. Author

Johnny Wilson Dougherty GitHub: JohnnyWilson-Portfolio

About

NLP-based financial complaint classification, priority scoring, and department routing system served via FastAPI and Streamlit

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages