# gafar8281/foodsnap-ai architecture

> Architecture diagram of the GitHub repository gafar8281/foodsnap-ai, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-12). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/gafar8281/foodsnap-ai
- Repository: https://github.com/gafar8281/foodsnap-ai

## Overview

##### Project type & purpose (what you’re diagramming)
**FoodSnap AI** is a **backend-centric ML inference + data lookup API**:
- A **FastAPI** web service exposing an image upload endpoint (`/foodsnap/v1/upload`).
- An **ML classification module** (TensorFlow / ResNet50) that predicts the food label from the image.
- A **nutrition data layer** (SQLAlchemy + PostgreSQL) that retrieves macros for the predicted food, scaled by quantity.
- A **data ingestion / population pipeline** (scripts using Selenium/BeautifulSoup/Pandas) that scrapes and loads nutrition data into the DB.

##### Entry / App Wiring
- `main.py` → FastAPI app creation, router inclusion, startup events.
- `config.py` → configuration (likely env vars: DB URL, model path, etc.).

##### API Layer
- `routes/foodsnap.py` → the REST endpoint(s), request parsing (image + quantity), response formatting.

##### Service Layer (business logic)
- `services/nutrition_service.py` → orchestrates nutrition lookup + quantity scaling; likely called by the route.

##### ML Inference Layer
- `ml_model/model.py` → loads model once at startup, preprocesses image, runs inference, returns predicted label.

##### Persistence Layer
- `db/database.py` → SQLAlchemy engine/session setup.
- `db/models.py` → ORM models/tables representing nutrition records.

##### Data Ingestion (offline job)
- `scripts/populate_database.py` → scraping + transformation + DB upsert/insert.

##### Dependencies / Runtime
- `requirements.txt` → confirms frameworks and libraries used.

##### Readme insights to incorporate (critical behaviors)
- **Model loaded once at startup** (startup lifecycle hook → cached singleton model).
- **Upload endpoint** `/foodsnap/v1/upload` (core contract).
- **Quantity-based calculations** (service logic after DB lookup).
- **Database population via web scraping** (separate flow; not on request path).
- Primary tech: FastAPI, TensorFlow, ResNet50, SQLAlchemy, PostgreSQL, Selenium/BS4/Pandas.

##### Client / API Consumer
- e.g., mobile app, web app, Postman—uploads image + quantity.

##### FastAPI Application (FoodSnap AI)
- Subdivide internally into:
- **Route Controller** (`routes/foodsnap.py`)
- **Nutrition Service** (`services/nutrition_service.py`)
- **ML Model Service** (`ml_model/model.py`)
- **DB Access Layer** (`db/database.py`, `db/models.py`)
- **Config** (`config.py`)
- As internal components within the service boundary.

##### PostgreSQL Database
- Stores nutrition facts keyed by food name/label (and macros).

##### Data Population Job (Scraper/ETL)
- `scripts/populate_database.py`
- External websites as data sources.

##### External Data Sources
- “Nutrition websites” (scraped via Selenium/BeautifulSoup).

- “Model artifact storage” (local file / saved model path), if `ml_model/model.py` loads from disk.

##### Online request path (critical)

**Client**
→ (HTTP POST multipart/form-data: image + quantity)
→ **FastAPI Route** (`/foodsnap/v1/upload` in `routes/foodsnap.py`)
→ **ML Model** (`ml_model/model.py`)
→ (predicted label: e.g., “pizza”)
→ **Nutrition Service** (`services/nutrition_service.py`)
→ **SQLAlchemy Session/DAO** (`db/database.py`)
→ **PostgreSQL** (query nutrition by label)
→ back to **Nutrition Service** (scale macros by quantity)
→ back to **Route**
→ **Client** (JSON: calories, carbs, protein, fats, label, etc.)

**FastAPI app startup** → **ML Model load** (“loaded once & cached”).

##### Offline ingestion / DB population path

**External Nutrition Websites**
→ (Selenium/BeautifulSoup scrape)
→ **populate_database.py** (Pandas clean/normalize)
→ **PostgreSQL** (insert/update nutrition table)

##### Architectural patterns/design principles evident here
- **Layered architecture**: Routes (controller) → Services → ML/DB layers.
- **Singleton model lifecycle**: model initialized once at startup for performance.
- **Separation of concerns**: scraping/ETL is out-of-band vs online API.
- **ORM-based persistence**: SQLAlchemy models represent DB schema.

##### Relevant technologies where they matter
- FastAPI (ASGI) in the service boundary
- TensorFlow + ResNet50 in ML component
- SQLAlchemy in DB access
- PostgreSQL in DB
- Selenium/BeautifulSoup/Pandas in ingestion script

Don’t sprinkle every library everywhere—attach them to the component they power.

##### Recommended “component breakdown” (don’t overthink—split aggressively)

- `main.py` (app bootstrap + router registration)
- `routes/foodsnap.py` (HTTP boundary)
- `ml_model/model.py` (preprocess + predict; model singleton cache)
- `services/nutrition_service.py` (business rules: scaling, fallback behavior)
- `db/database.py` (session/engine management)
- `db/models.py` (schema/ORM)
- `config.py` (env/config management)

- Shows online path + offline ingestion + startup model load.
- Emphasizes order and data transformations.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================
    %% External Actors / Sources
    %% =========================
    Client(["Client / API Consumer\n(Mobile/Web/Postman)"]):::external
    Sites{{"External Nutrition Websites"}}:::external

    %% =========================
    %% Runtime: FoodSnap AI Service (FastAPI)
    %% =========================
    subgraph "FoodSnap AI (FastAPI Service)"
        direction TB

        subgraph "App Bootstrap & Configuration"
            direction TB
            Main["main.py\nFastAPI app + router inclusion + startup events"]:::app
            Config["config.py\nSettings (DB URL, model path, env vars)"]:::config
            Req["requirements.txt\nDependencies (FastAPI, TF, SQLAlchemy, etc.)"]:::doc
            Readme["README.md\nBehavioral notes (startup model load,\nendpoint contract, ingestion flow)"]:::doc
        end

        subgraph "API Layer"
            direction TB
            Route["routes/foodsnap.py\nPOST /foodsnap/v1/upload\n(parse image + quantity,\nformat response)"]:::api
        end

        subgraph "Service Layer"
            direction TB
            NutritionSvc["services/nutrition_service.py\nLookup + quantity scaling\n(business logic)"]:::service
        end

        subgraph "ML Inference Layer"
            direction TB
            ModelSvc["ml_model/model.py\nTensorFlow + ResNet50\npreprocess + predict label\n(model cached)"]:::ml
            TrainNB["ml_model/resnet50_finetune.ipynb\nOffline training / fine-tune workflow"]:::offline
        end

        subgraph "Persistence Layer (SQLAlchemy)"
            direction TB
            DBSetup["db/database.py\nEngine + Session (SQLAlchemy)"]:::db
            ORM["db/models.py\nORM models (NutritionFacts table)"]:::db
        end

        Startup(("FastAPI startup event\n(load model once)")):::event
    end

    %% =========================
    %% Database
    %% =========================
    PG[(PostgreSQL\nNutrition Facts DB)]:::database

    %% =========================
    %% Offline Ingestion / ETL
    %% =========================
    subgraph "Offline Data Ingestion / Population (Out-of-band)"
        direction TB
        PopScript["scripts/populate_database.py\nScrape (Selenium/BS4)\nTransform (Pandas)\nUpsert/Insert nutrition data"]:::offline
    end

    %% =========================
    %% Online Request Path (sync)
    %% =========================
    Client -->|"HTTP POST multipart/form-data\n(image,quantity)"| Route
    Route -->|"runs_inference(image)"| ModelSvc
    ModelSvc -->|"predicted_label"| NutritionSvc
    NutritionSvc -->|"open_session()"| DBSetup
    DBSetup -->|"ORM query"| ORM
    ORM -->|"SELECT nutrition_by_label"| PG
    PG -->|"nutrition_facts"| NutritionSvc
    NutritionSvc -->|"scale_macros_by_quantity"| Route
    Route -->|"JSON response\n(predicted_food,macros)"| Client

    %% Startup lifecycle
    Main -->|"register_router()"| Route
    Main -->|"load_settings()"| Config
    Main -->|"startup_hook()"| Startup
    Startup -->|"load_and_cache_model_once"| ModelSvc

    %% =========================
    %% Offline Ingestion Path (async / separate)
    %% =========================
    Sites -.->|"scrape (Selenium/BS4)"| PopScript
    PopScript -.->|"clean/normalize (Pandas)"| PopScript
    PopScript -.->|"upsert/insert"| PG

    %% =========================
    %% Click events (component mapping)
    %% =========================
    click Main "https://github.com/gafar8281/foodsnap-ai/blob/main/main.py"
    click Config "https://github.com/gafar8281/foodsnap-ai/blob/main/config.py"
    click Route "https://github.com/gafar8281/foodsnap-ai/blob/main/routes/foodsnap.py"
    click NutritionSvc "https://github.com/gafar8281/foodsnap-ai/blob/main/services/nutrition_service.py"
    click ModelSvc "https://github.com/gafar8281/foodsnap-ai/blob/main/ml_model/model.py"
    click TrainNB "https://github.com/gafar8281/foodsnap-ai/blob/main/ml_model/resnet50_finetune.ipynb"
    click DBSetup "https://github.com/gafar8281/foodsnap-ai/blob/main/db/database.py"
    click ORM "https://github.com/gafar8281/foodsnap-ai/blob/main/db/models.py"
    click PopScript "https://github.com/gafar8281/foodsnap-ai/blob/main/scripts/populate_database.py"
    click Req "https://github.com/gafar8281/foodsnap-ai/blob/main/requirements.txt"
    click Readme "https://github.com/gafar8281/foodsnap-ai/blob/main/README.md"

    %% =========================
    %% Styles
    %% =========================
    classDef external fill:#E8F3FF,stroke:#2B6CB0,stroke-width:1px,color:#0B2545
    classDef app fill:#E9FFF1,stroke:#2F855A,stroke-width:1px,color:#0B3D2E
    classDef config fill:#F0FFF4,stroke:#38A169,stroke-width:1px,color:#0B3D2E
    classDef api fill:#FFF3E8,stroke:#C05621,stroke-width:1px,color:#4A1D0B
    classDef service fill:#FFF7ED,stroke:#B45309,stroke-width:1px,color:#4A2C0A
    classDef ml fill:#F3E8FF,stroke:#6B46C1,stroke-width:1px,color:#2A0A4A
    classDef db fill:#E6FFFA,stroke:#2C7A7B,stroke-width:1px,color:#083E3E
    classDef database fill:#D9F2FF,stroke:#1D4ED8,stroke-width:2px,color:#06224A
    classDef offline fill:#FCE7F3,stroke:#BE185D,stroke-width:1px,color:#4A0624
    classDef doc fill:#F8FAFC,stroke:#64748B,stroke-width:1px,color:#0F172A
    classDef event fill:#FFF1F2,stroke:#9F1239,stroke-width:1px,color:#4A0618
```
