Large companies pay thousands of B2B invoices every month. Because contracts and shipping rates are complicated, companies end up overpaying suppliers by 1% to 5% every year due to manual billing errors and inflated freight charges.
This app automatically compares invoices against original purchase orders (PO) to find price differences and flag suspicious shipping rates for manual review.
- Automated Clearance: Automatically approves normal, low-risk invoices so auditors can focus only on the highly suspicious ones.
- Plugs Revenue Leakage: Flags price variances and inflated shipping/freight charges before the bills are actually paid.
- Tracks Vendor Patterns: Surfaces historical patterns of invoice inflation and billing delays per supplier.
graph TD
A[data/inventory.db SQLite] -->|SQL left-join query| B[Clean B2B Transaction Dataset]
B -->|Preprocessing & Feature Engineering| C[Splits & Scaling Preprocessor]
C -->|Phase A training| D[Model 1: RandomForestRegressor]
C -->|Phase B training| E[Model 2: RandomForestClassifier]
subgraph Inference Pipeline
F[New Invoice Input] -->|Interactive simulator / API| G[Predict expected fair freight]
F -->|Run Classifier| H[Evaluate audit risk score]
G -->|Variance Ledger| I[Veriflow Compliance Dashboard]
H -->|Auto-Approved or Flagged| I
end
D -->|Saves price_regressor.pkl| G
E -->|Saves audit_classifier.pkl| H
The app connects to a 424MB SQLite Database (inventory.db) representing Bibitor, LLC, a retail wine and spirits distributor with around 80 stores. The data is structured across five relational tables:
erDiagram
purchases ||--|| vendor_invoice : "Matches via PONumber"
purchase_prices ||--o{ purchases : "Master catalog cost reference"
begin_inventory ||--o{ purchases : "Beginning of month stock"
end_inventory ||--o{ purchases : "End of month stock"
Records the original purchase orders placed by the stores.
- Key Columns:
InventoryId(TEXT): Unique product SKU.Store(BIGINT): Retail store ID.Brand(BIGINT): Brand inventory number.Description(TEXT): Product description (e.g., Grey Goose, Bombay Sapphire).PONumber(BIGINT): Purchase Order number.PODate(TEXT): Date order was placed.PurchasePrice(FLOAT): Contract price per unit.Quantity(BIGINT): Ordered volume.Dollars(FLOAT): Total agreed PO value.
Contains the actual invoices sent to the company by vendors.
- Key Columns:
PONumber(BIGINT): Links back to the original purchase order.InvoiceDate&PayDate(TEXT): Billing and payment dates.Quantity(BIGINT): Billed volume (checked against ordered volume).Dollars(FLOAT): Total billed amount on the invoice.Freight(FLOAT): Actual billed shipping charges (target for overcharge detection).Approval(TEXT): System manual approval comments.
Catalog contract pricing for items across all vendors.
- Key Columns:
Brand(BIGINT): Brand catalog key.PurchasePrice(FLOAT): Standard contract price.
Store inventory snapshots to track sales volumes and verify stock.
To train the machine learning models, the code builds the following custom features:
- Price Variance (
price_variance): The difference between the billed invoice amount and the original PO amount. - Quantity Discrepancy (
quantity_discrepancy): Checks if the vendor billed for more units than were actually ordered. - Freight-to-Invoice Ratio (
freight_to_dollar_ratio): Normalizes shipping charges against the total invoice value to spot padded rates. - Freight per Unit (
freight_per_unit): Shipping cost divided by quantity to spot high shipping rates on small orders. - Billing Delay (
days_to_invoice): Time elapsed from purchase order placement to invoice date.
We tested multiple models (Linear Regression, Decision Trees, Gradient Boosting) and chose Random Forest because:
- Resilient to outliers: Financial data often has massive shipping rate outliers that skew linear models.
- Handles categorical columns: Works perfectly with One-Hot Encoded text columns like
VendorName. - Interpretability: Lets us extract feature importance to show the user exactly why a bill was flagged for audit.
-
$R^2$ Score (Variance Captured):0.9661(Captures 96.6% of freight cost variance) -
Mean Absolute Error (MAE):
$24.84 -
Root Mean Squared Error (RMSE):
$132.29
- Weighted F1-Score:
90.0% - Overall Accuracy:
85.0% - Anomaly Recall (Class 1):
55.0%(Successfully flags over half of the actual overcharge anomalies in a highly imbalanced dataset where anomalies are only 1.8% of the data).
-
Total Invoices Analyzed:
5,543B2B transactions. -
Total Billed Volume Audited:
$21,080,266.39 -
Overcharges Caught:
86extreme freight overcharge anomalies isolated (where shipping charges exceeded$> 0.8%$ of total invoice dollars).
Real-world datasets are messy. The pipeline includes these safeguards to prevent crashes:
- New/Unknown Vendors: If a user inputs a brand new vendor that wasn't in the training data,
OneHotEncoder(handle_unknown='ignore')prevents the app from throwing exceptions. - Zero-Dollar Invoices: Invoices with a billed total of
$0.00(free replacement units) would normally cause division-by-zero crashes. The code uses small offsets (+ 1e-5) to keep the calculations safe. - Missing POs: If an invoice is missing its matching purchase order in the database, the code falls back to tracking the invoice alone rather than breaking the pipeline.
.
βββ data/
β βββ inventory.db # 424MB SQLite enterprise database
β βββ audited_transactions_cache.csv # Pre-computed compliance training data
βββ models/
β βββ price_regressor.pkl # Serialized regression pipeline
β βββ audit_classifier.pkl # Serialized classification pipeline
βββ notebooks/
β βββ exploratory_auditing_eda.ipynb # Interactive analysis & statistical T-tests
βββ src/
β βββ database.py # SQL data extractor & B2B joins
β βββ preprocess.py # Feature scaling, engineering, & anomaly calibration
β βββ train.py # Unified model training & validation metrics
β βββ predict.py # Modular B2B inference API
βββ app.py # Premium Streamlit AP Auditing Portal
βββ requirements.txt # System dependencies
βββ .gitignore # Repository ignore configuration
Displays total audited financial volume, auto-approval compliance rates, cumulative leakage amounts, and interactive statistical scatter charts mapping billed freight against invoice values.

Provides an interactive auditing desk. Users input invoice metrics and instantly receive system auto-clearance status, cost variances, and granular risk contribution indicators.
-
Flagged for Audit (Anomaly Rate Spike): Billed freight of
$120.00exceeds expected shipping contract boundaries, triggering a red warning:
-
Auto-Approved (Logistics Baseline Match): Billed freight adjusted to
$40.00matches contracting benchmarks, triggering automatic clearance:
Offers a multi-filtered tabular interface querying the database, allowing users to isolate flagged high-risk transactions dynamically and export audit lists as clean CSV files.

pip install -r requirements.txtImportant
The 424MB SQLite database (inventory.db) contains millions of rows and is ignored by git. You must place your compiled database or dataset inside the data/ directory. You can download the source transaction files directly from Kaggle:
π¦ Kaggle: Bibitor LLC Inventory Records Analysis
Extract transaction logs, engineer features, train models, and save the pipelines:
python src/train.pyLaunch the Streamlit web dashboard locally:
streamlit run app.pyTo scale this up, the next steps are:
- Docker: Put the training pipeline and dashboard in containers for easy deployment.
- API Endpoint: Wrap the models in
FastAPIso other software can query predictions programmatically. - Database Scale: Move the SQLite backend to PostgreSQL or Snowflake for handling millions of rows.
- Model Tracking: Set up
MLflowto track model training runs and versions.
- Muhammad Taha Nasir
- Email: m.tahanasir.cs@gmail.com
- Portfolio: https://muhammadtahanasir.github.io/
Note
This platform was developed for portfolio analysis and is designed for enterprise integration with SQLite, PostgreSQL, and Oracle accounts payable systems.