Skip to content

About

AI-driven retail analytics dashboard featuring XGBoost demand forecasting, inventory safety reordering, and an interactive business intelligence chatbot powered by Google Gemini API.

Topics

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

AIDA: AI Decision Analyst for Grocery Retail

Python Version License XGBoost Accuracy Gemini Integration Docker Support Live Demo

🌐 Live Demo: https://ai-grocery-analytics.onrender.com/

AIDA (AI Decision Analyst) is a production-quality, portfolio-ready business intelligence dashboard and conversational AI analyst designed specifically for grocery retail owners. Instead of relying on generic chat replies, AIDA combines a Glassmorphism frontend UI with a modular database interface, an XGBoost demand forecasting pipeline, and the Google Gemini API to answer concrete retail inquiries and suggest supply chain optimization guidelines. To democratize Data analytics for local retail stores.


1. Core Features

πŸ“Š Modern Business Intelligence Dashboard

  • Aggregate KPI Widgets: Real-time count-up animations tracking gross revenues, sales quantity, net profit margins, customer footfall counts, and active low-stock alerts.
  • Interactive Visualizations (Chart.js): Daily sales & customer trend graphs, category market share distributions, top-selling items, and safety risk polar grids.
  • Theme Controls: Global theme switching (frosted glass dark mode and high-contrast light mode) with localStorage state persistence.
  • Live ML Forecasting Selector: Pick any product and store branch from dropdown selectors to overlay historical transaction trends with XGBoost daily demand predictions.
  • Replenishment Table: Clear logs summarizing safety limits, suggested restocks, order priorities, and alert tags.

πŸ€– AI Conversational Assistant (AIDA)

  • Automatic Function Calling: Gemini evaluates user questions and automatically runs local Python tools to query databases and execute ML models before generating natural language responses.
  • Local Fallback Engine: If the Gemini API Key is missing or rate-limited, a local rule-based engine handles requests, keeping the application fully functional out-of-the-box.
  • Structured Outputs: Formulates complex metrics reports as clean markdown list structures and tables directly in the chat history.

πŸ“₯ Exporters & Reporting

  • PDF Report Exporter: Programmatic vector PDF compilation using ReportLab, complete with headers, KPI grids, reorder tables, and colored warning tags.
  • CSV Catalog Exporter: Downloads full, spreadsheet-compatible inventory reports containing stock risks, suppliers, and profit margins.

2. πŸ“Έ Screenshots & Interface Overview

Analytics Dashboard & AIDA AI Assistant

Analytics Dashboard & AIDA AI Assistant

XGBoost Demand Forecasting Engine

XGBoost Demand Forecast Chart

Inventory Stock Risk & ML Reorder Recommendations

ML Reorder Recommendations


3. Directory Structure

The project layout separates frontend assets, backend blueprints, ML pipelines, and unit tests:

AI-Grocery-Analytics/
β”œβ”€β”€ app.py                      # Flask Application Factory
β”œβ”€β”€ config.py                   # Global system config (SQLite, MongoDB, Gemini)
β”œβ”€β”€ requirements.txt            # Package dependencies
β”œβ”€β”€ Dockerfile                  # Production container configuration
β”œβ”€β”€ LICENSE                     # MIT License specifications
β”œβ”€β”€ CONTRIBUTING.md             # PR workflows & commits conventions
β”œβ”€β”€ CHANGELOG.md                # Project release version logs
β”œβ”€β”€ CODE_OF_CONDUCT.md          # Community codes of conduct
β”‚
β”œβ”€β”€ images/                     # Application Screenshots
β”‚   β”œβ”€β”€ 1.png                   # Dashboard Overview & AIDA Assistant
β”‚   β”œβ”€β”€ 2.png                   # XGBoost Demand Forecasting Chart
β”‚   └── 3.png                   # Inventory Reorder Recommendations Log
β”‚
β”œβ”€β”€ database/                   # Modular DB Layer
β”‚   β”œβ”€β”€ base.py                 # Abstract database interface (ABC)
β”‚   β”œβ”€β”€ sqlite_impl.py          # SQLite database connector implementation
β”‚   β”œβ”€β”€ mongodb_impl.py         # MongoDB NoSQL connector stub
β”‚   β”œβ”€β”€ db_factory.py           # Database Factory pattern
β”‚   └── initialize.py           # DB tables bootstrap and data importer
β”‚
β”œβ”€β”€ dataset/                    # Data simulation
β”‚   β”œβ”€β”€ generator.py            # Synthetic daily retail CSV generator
β”‚   β”œβ”€β”€ products.csv            # Generated product catalog (ignored)
β”‚   └── grocery_sales.csv       # Generated transaction aggregates (ignored)
β”‚
β”œβ”€β”€ ml/                         # Machine Learning Pipeline
β”‚   β”œβ”€β”€ train.py                # Chronological models comparison script
β”‚   └── predict.py              # Demand forecasting & reorder calculations
β”‚
β”œβ”€β”€ models/                     # Deserialized ML components
β”‚   β”œβ”€β”€ demand_forecast_model.joblib # Saved XGBoost regressor
β”‚   └── encoders.joblib         # Categorical label preprocessors
β”‚
β”œβ”€β”€ routes/                     # Flask Blueprints
β”‚   β”œβ”€β”€ auth.py                 # Secure credentials checking & sessions
β”‚   β”œβ”€β”€ api.py                  # Dashboard metrics REST feeds
β”‚   β”œβ”€β”€ chat.py                 # Chat prompts forwarding to Gemini
β”‚   β”œβ”€β”€ reports.py              # CSV/PDF downloads endpoints
β”‚   └── views.py                # Protected template render controllers
β”‚
β”œβ”€β”€ static/                     # Frontend Assets
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   └── dashboard.css       # Frosted glass design system, animations
β”‚   └── js/
β”‚       β”œβ”€β”€ dashboard.js        # Count-ups & Chart.js controllers
β”‚       β”œβ”€β”€ chat.js             # Conversational UI & markdown parser
β”‚       └── theme.js            # Light/Dark toggler, alerts fetcher
β”‚
β”œβ”€β”€ templates/                  # Jinja2 HTML Templates
β”‚   β”œβ”€β”€ base.html               # Master layout shell
β”‚   β”œβ”€β”€ login.html              # Glassmorphic auth portal
β”‚   β”œβ”€β”€ dashboard.html          # Main workspace grids
β”‚   β”œβ”€β”€ profile.html            # User scopes profile panel
β”‚   └── settings.html           # Settings and credentials slider
β”‚
β”œβ”€β”€ utils/                      # Core System Utilities
β”‚   β”œβ”€β”€ logger.py               # Application logs formatter
β”‚   └── pdf_generator.py        # ReportLab PDF compiler
β”‚
β”œβ”€β”€ tests/                      # Full QA test suites
β”‚   β”œβ”€β”€ test_db.py              # Database integrity unit tests
β”‚   β”œβ”€β”€ test_ml.py              # ML inference validation tests
β”‚   └── test_api.py             # Flask REST endpoints integration tests
β”‚
└── docs/                       # Architectural & DB layouts
    β”œβ”€β”€ architecture.md         # Component diagrams & data lifecycles
    β”œβ”€β”€ db_schema.md            # ER diagram & columns specifications
    β”œβ”€β”€ api_docs.md             # REST endpoints payload specifications
    └── deployment.md           # Production server configurations

4. Installation & Local Setup

4.1 Prerequisites

  • Python 3.9, 3.10, 3.11, or 3.13.
  • Pip (Python Package Manager).

4.2 Installation Steps

  1. Clone the repository:
    git clone https://github.com/yourusername/AI-Grocery-Analytics.git
    cd AI-Grocery-Analytics
  2. Create and Activate a Virtual Environment:
    • Windows (PowerShell):
      python -m venv venv
      .\venv\Scripts\Activate.ps1
    • Linux/macOS:
      python3 -m venv venv
      source venv/bin/activate
  3. Install Dependencies:
    pip install -r requirements.txt
  4. Configure Environment Variables: Copy .env.template to .env and fill in your Gemini API Key:
    cp .env.template .env
    Edit .env:
    SECRET_KEY=secure-random-string
    GEMINI_API_KEY=AIzaSyYourActualGoogleGeminiKeyHere
    DB_TYPE=sqlite

4.3 Bootstrap Database & Train Models

AIDA provides automated scripts to compile mock data, index databases, and train forecasts:

# 1. Compile 78,840 synthetic transaction records
python -m dataset.generator

# 2. Schema load, database index, and default admin user registry
python database/initialize.py

# 3. Model preprocessing and XGBoost forecast compilation
python -m ml.train

4.4 Launch Application

Launch the Flask development server:

python app.py

Open your browser and navigate to http://localhost:5000.

  • Default Admin Credentials:
    • Username: admin
    • Password: admin123

5. Machine Learning Workflow

AIDA's ML pipeline reads historical transactions directly from the SQLite database, parses dates, and uses Label Encoders to normalize categorical dimensions. To ensure realistic evaluations, the dataset is split chronologically, holding out the last 30 days for testing.

Four models are trained and compared. In our simulation, the XGBoost Regressor yielded the highest test performance:

Algorithm Name Mean Absolute Error (MAE) Root Mean Squared Error (RMSE) R-squared ((R^2))
Linear Regression 4.9182 6.4549 0.3470
Decision Tree 3.3495 4.5254 0.6791
Random Forest 3.2735 4.4097 0.6953
XGBoost Regressor 3.1672 4.2164 0.7214

The trained best model (demand_forecast_model.joblib) is saved and loaded by the inference engine to suggest safety limits and restocks.


6. Running the Test Suite

The QA framework contains 10 comprehensive unit and integration tests covering database schemas, user registrations, XGBoost predictions, API access bounds, and login sessions.

Execute the test discovery command:

python -m unittest discover -s tests

7. Production Deployments

AIDA is ready for deployment in modern serverless and container architectures.

  • Live Deployment: The application is deployed and running on Render at https://ai-grocery-analytics.onrender.com/.
  • Docker: docker build -t aida:latest . -> docker run -d -p 5000:5000 -e GEMINI_API_KEY="key" aida:latest
  • Render: Connect repository, set build command and start command as gunicorn app:create_app().
  • Railway: Connect repository, attach a persistent Volume to mount /app/database for SQLite persistence.
  • See docs/deployment.md for full server configuration guides.

8. License & Contributions

About

AI-driven retail analytics dashboard featuring XGBoost demand forecasting, inventory safety reordering, and an interactive business intelligence chatbot powered by Google Gemini API.

Topics

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages