# aquisto535/mind-palette-project architecture

> Architecture diagram of the GitHub repository aquisto535/mind-palette-project, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/aquisto535/mind-palette-project
- Repository: https://github.com/aquisto535/mind-palette-project

## Overview

1. **Repository shape**
   - This is a polyglot microservice monorepo for an HFD-based IQ estimation system.
   - The runtime system is split into four deployable services: React frontend, Node.js API gateway, C++ preprocess server, and Python AI inference server.
   - `docs/` contains the architecture decisions, pipeline descriptions, and operational guidance that mirror the codebase structure.

2. **Primary user-facing flow**
   - The browser app collects child metadata, accepts a drawing upload, shows progress, and renders the final IQ/percentile result.
   - All analysis traffic goes through the API gateway; the frontend does not talk directly to the C++ or Python services.
   - The frontend also supports mock mode for UI-only development.

3. **API gateway as orchestration boundary**
   - `api-gateway/` is the main entry point and coordination layer.
   - It owns request validation, rate limiting, file-type verification, path safety, temporary file lifecycle, and response shaping.
   - It calls the preprocess server first, then passes the processed image to the AI server, then maps the AI response into the user-facing result schema.

4. **Shared file-system integration**
   - The services communicate partly through a shared volume (`shared_volume/`) rather than only through direct in-memory payloads.
   - The gateway writes uploads, the C++ server reads raw uploads and writes processed images, and the gateway later reads the processed output and persists results.
   - This shared storage is an important architectural boundary because it couples orchestration, file cleanup, and reproducibility.

5. **C++ preprocess service responsibilities**
   - `preprocess-server/` is a performance-oriented image pipeline service built in C++17 with OpenCV and Crow.
   - It implements a strategy-style filter pipeline with resize, grayscale, binarization, morphology, denoise, CLAHE, Canny/edge, inversion, RGB conversion, and hybrid 3-channel composition.
   - Its role is to normalize drawings into the AI model’s expected 260×260, 3-channel representation.

6. **Preprocess service concurrency and safety**
   - The preprocess layer has its own worker-thread infrastructure and atomic file writing to avoid contention on disk outputs.
   - This service is optimized for CPU-bound image transforms rather than model inference.
   - Its tests focus on filters, thread pool behavior, writer correctness, and analysis utilities.

7. **Python AI inference service responsibilities**
   - `ai-server/` is the model-serving boundary, implemented with FastAPI and PyTorch.
   - It loads male/female model variants, preprocesses the image tensor, runs inference, and converts predictions into item scores, raw score, IQ, and percentile.
   - It also owns the domain logic for item mapping and score standardization, so the gateway does not embed model semantics.

8. **Inference backend abstraction**
   - The AI server is designed with interchangeable execution backends: native TensorRT, ONNX Runtime, or PyTorch fallback.
   - That backend choice materially affects deployment, performance, and hardware requirements, but not the external API contract.
   - This makes the model-serving tier the main optimization point in the system.

9. **Domain model of the AI output**
   - The model predicts 60 scoring items grouped into 4 heads: head A, B, C, and D.
   - Those head outputs are transformed into a total raw score and then into age/sex-normalized IQ and percentile values.
   - The frontend displays a user-friendly subset of this result, while the gateway preserves the full structured payload and result integrity metadata.

10. **Frontend presentation layer**
   - `frontend/` is a React + Vite SPA responsible for the end-user workflow and result visualization.
   - It contains discrete UI stages: hero, child info form, guide, upload, loading, and result.
   - It also includes PDF export and animated result visualization, but it remains strictly a client of the gateway API.

11. **Security and reliability boundaries**
   - Security controls are concentrated in the gateway: rate limiting, magic-byte file validation, path traversal protection, and log sanitization.
   - Integrity is reinforced with SHA256-based result metadata and temporary-file cleanup after processing.
   - Health endpoints exist on all services, which supports orchestration and operational monitoring across the stack.

12. **Build and deployment structure**
   - Each service has its own build toolchain: Vite/TypeScript for frontend, npm/Jest for gateway, CMake/Google Test for C++, and Python packaging/pytest for AI.
   - Dockerfiles and compose files indicate the system is intended to be containerized as separate services rather than a single app runtime.
   - The `dist/` and `build/` directories show compiled artifacts are maintained per service boundary.

13. **Testing as architecture documentation**
   - The repo has strong service-level test separation: Vitest for frontend, Jest for gateway, Google Test for preprocess, and pytest for AI.
   - Test coverage reflects the architecture: gateway orchestration/security, preprocess filters/concurrency, AI inference/scoring, and end-to-end analysis.
   - This makes the tests a good proxy for the service contract surface areas.

14. **What to draw in an architecture diagram**
   - Draw four boxes for the runtime services, with the gateway in the center as the orchestrator.
   - Show a shared storage boundary between gateway and preprocess/AI services.
   - Emphasize the directional flow: browser upload → gateway validation/storage → preprocess transform → AI inference/scoring → gateway result assembly → browser rendering.

Main entry points: [`api-gateway/src/services/analysisService.ts`](https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/services/analysisService.ts) (Orchestrator), [`preprocess-server/src/core/filter_pipeline.cpp`](https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/core/filter_pipeline.cpp) (Filter Pipeline), [`docs/README.md`](https://github.com/aquisto535/mind-palette-project/blob/main/docs/README.md) (Docs), [`api-gateway/src/routes/analyze.ts`](https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/routes/analyze.ts) (Analyze Route)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_frontend_app["Browser App<br/>React SPA<br/>[App.tsx]"]
  node_frontend_api["API Client<br/>HTTP client<br/>[client.ts]"]
  node_frontend_result["Result View<br/>UI stage<br/>[Result.tsx]"]
end

subgraph group_gateway["API Gateway"]
  node_gateway_routes["Analyze Route<br/>Node route<br/>[analyze.ts]"]
  node_gateway_orchestrator["Orchestrator<br/>Analysis service<br/>[analysisService.ts]"]
  node_gateway_storage["File Storage<br/>filesystem util<br/>[fileStorage.ts]"]
  node_gateway_security["Security Checks<br/>validation utils<br/>[imageValidator.ts]"]
  node_gateway_integrity["Integrity Hash<br/>hash util<br/>[hashIntegrity.ts]"]
end

subgraph group_preprocess["Preprocess Server"]
  node_preprocess_pipeline["Filter Pipeline<br/>C++ image pipeline"]
  node_preprocess_filters["Image Filters<br/>OpenCV transforms"]
  node_preprocess_concurrency["Workers<br/>threading infra<br/>[thread_pool.cpp]"]
  node_preprocess_atomic["Atomic Writer<br/>disk I/O<br/>[atomic_writer.cpp]"]
end

subgraph group_ai["AI Server"]
  node_ai_route["Analyze Route<br/>FastAPI route<br/>[analyze.py]"]
  node_ai_model["Model Core<br/>PyTorch model<br/>[model.py]"]
  node_ai_scoring["IQ Scoring<br/>domain logic<br/>[iq_scorer.py]"]
  node_ai_backend["Execution Backends<br/>backend adapters<br/>[tensorrt_engine.py]"]
  node_ai_preprocess["Tensor Prep<br/>preprocessing<br/>[preprocessing.py]"]
end

subgraph group_shared["Shared/Docs"]
  node_shared_volume[("Shared Volume<br/>filesystem boundary")]
  node_docs_arch["Docs<br/>[README.md]"]
end

node_frontend_app -->|"submit analysis"| node_frontend_api
node_frontend_app -->|"render result"| node_frontend_result
node_frontend_api -->|"HTTP request"| node_gateway_routes
node_gateway_routes -->|"validate upload"| node_gateway_security
node_gateway_routes -->|"dispatch"| node_gateway_orchestrator
node_gateway_orchestrator -->|"persist upload"| node_gateway_storage
node_gateway_orchestrator -->|"read/write files"| node_shared_volume
node_gateway_orchestrator -->|"preprocess first"| node_preprocess_pipeline
node_preprocess_pipeline -->|"apply transforms"| node_preprocess_filters
node_preprocess_pipeline -->|"schedule work"| node_preprocess_concurrency
node_preprocess_concurrency -->|"write output"| node_preprocess_atomic
node_preprocess_atomic -->|"store processed"| node_shared_volume
node_gateway_orchestrator -->|"send processed image"| node_ai_route
node_ai_route -->|"prepare tensor"| node_ai_preprocess
node_ai_route -->|"infer"| node_ai_model
node_ai_model -->|"backend select"| node_ai_backend
node_ai_model -->|"score outputs"| node_ai_scoring
node_ai_scoring -->|"attach metadata"| node_gateway_integrity
node_gateway_orchestrator -->|"return payload"| node_frontend_result
node_docs_arch -.->|"specifies"| node_gateway_orchestrator
node_docs_arch -.->|"documents"| node_preprocess_pipeline
node_docs_arch -.->|"documents"| node_ai_scoring

click node_frontend_app "https://github.com/aquisto535/mind-palette-project/blob/main/frontend/src/App.tsx"
click node_frontend_api "https://github.com/aquisto535/mind-palette-project/blob/main/frontend/src/api/client.ts"
click node_frontend_result "https://github.com/aquisto535/mind-palette-project/blob/main/frontend/src/components/Result.tsx"
click node_gateway_routes "https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/routes/analyze.ts"
click node_gateway_orchestrator "https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/services/analysisService.ts"
click node_gateway_storage "https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/utils/fileStorage.ts"
click node_gateway_security "https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/services/imageValidator.ts"
click node_gateway_integrity "https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/utils/hashIntegrity.ts"
click node_preprocess_pipeline "https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/core/filter_pipeline.cpp"
click node_preprocess_filters "https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/filters/hybrid_preprocess_filter.cpp"
click node_preprocess_concurrency "https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/infra/thread_pool.cpp"
click node_preprocess_atomic "https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/infra/atomic_writer.cpp"
click node_ai_route "https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/routes/analyze.py"
click node_ai_model "https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/core/model.py"
click node_ai_scoring "https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/core/iq_scorer.py"
click node_ai_backend "https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/infra/tensorrt_engine.py"
click node_ai_preprocess "https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/core/preprocessing.py"
click node_shared_volume "https://github.com/aquisto535/mind-palette-project/tree/main/shared_volume"
click node_docs_arch "https://github.com/aquisto535/mind-palette-project/blob/main/docs/README.md"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_frontend_app,node_frontend_api,node_frontend_result toneBlue
class node_gateway_routes,node_gateway_orchestrator,node_gateway_storage,node_gateway_security,node_gateway_integrity toneAmber
class node_preprocess_pipeline,node_preprocess_filters,node_preprocess_concurrency,node_preprocess_atomic toneMint
class node_ai_route,node_ai_model,node_ai_scoring,node_ai_backend,node_ai_preprocess toneRose
class node_shared_volume,node_docs_arch toneIndigo
```

## Components

### Frontend

React/Vite browser app and presentation flow

- [Browser App](https://github.com/aquisto535/mind-palette-project/blob/main/frontend/src/App.tsx): React SPA · User workflow for metadata entry, upload, progress, and results · `frontend/src/App.tsx`
- [API Client](https://github.com/aquisto535/mind-palette-project/blob/main/frontend/src/api/client.ts): HTTP client · Frontend-side gateway integration boundary · `frontend/src/api/client.ts`
- [Result View](https://github.com/aquisto535/mind-palette-project/blob/main/frontend/src/components/Result.tsx): UI stage · Displays IQ, percentile, and exportable result presentation · `frontend/src/components/Result.tsx`

### API Gateway

Orchestration, validation, storage, and response shaping

- [Analyze Route](https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/routes/analyze.ts): Node route · Primary request entrypoint for analysis uploads · `api-gateway/src/routes/analyze.ts`
- [Orchestrator](https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/services/analysisService.ts): Analysis service · Validates requests, sequences preprocess then inference, and shapes responses · `api-gateway/src/services/analysisService.ts`
- [File Storage](https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/utils/fileStorage.ts): filesystem util · Upload persistence, temp files, processed-file reads, and cleanup · `api-gateway/src/utils/fileStorage.ts`
- [Security Checks](https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/services/imageValidator.ts): validation utils · Magic-byte file checks, path safety, and upload hardening · `api-gateway/src/services/imageValidator.ts`
- [Integrity Hash](https://github.com/aquisto535/mind-palette-project/blob/main/api-gateway/src/utils/hashIntegrity.ts): hash util · SHA256-based result metadata and integrity support · `api-gateway/src/utils/hashIntegrity.ts`

### Preprocess Server

C++ image normalization pipeline and atomic disk I/O

- [Filter Pipeline](https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/core/filter_pipeline.cpp): C++ image pipeline · Strategy-style normalization chain for drawing preprocessing · `preprocess-server/src/core/filter_pipeline.cpp`
- [Image Filters](https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/filters/hybrid_preprocess_filter.cpp): OpenCV transforms · Resize, grayscale, binarize, morphology, denoise, CLAHE, Canny, invert, RGB, hybrid compose · `preprocess-server/src/filters/hybrid_preprocess_filter.cpp`
- [Workers](https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/infra/thread_pool.cpp): threading infra · Thread pool and atomic writing for concurrent safe processing · `preprocess-server/src/infra/thread_pool.cpp`
- [Atomic Writer](https://github.com/aquisto535/mind-palette-project/blob/main/preprocess-server/src/infra/atomic_writer.cpp): disk I/O · Atomic output writes to prevent contention on shared files · `preprocess-server/src/infra/atomic_writer.cpp`

### AI Server

Python model serving, scoring, and backend abstraction

- [Analyze Route](https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/routes/analyze.py): FastAPI route · Inference API entrypoint for image analysis requests · `ai-server/src/routes/analyze.py`
- [Model Core](https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/core/model.py): PyTorch model · Loads male/female variants and runs tensor inference · `ai-server/src/core/model.py`
- [IQ Scoring](https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/core/iq_scorer.py): domain logic · Maps item outputs to raw score, IQ, and percentile · `ai-server/src/core/iq_scorer.py`
- [Execution Backends](https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/infra/tensorrt_engine.py): backend adapters · TensorRT, ONNX Runtime, and PyTorch fallback engines · `ai-server/src/infra/tensorrt_engine.py`
- [Tensor Prep](https://github.com/aquisto535/mind-palette-project/blob/main/ai-server/src/core/preprocessing.py): preprocessing · Image tensor preparation and model input normalization · `ai-server/src/core/preprocessing.py`

### Shared/Docs

Shared volume plus architecture and operations docs

- [Shared Volume](https://github.com/aquisto535/mind-palette-project/tree/main/shared_volume): filesystem boundary · Uploads, processed images, and result artifacts shared across services · `shared_volume`
- [Docs](https://github.com/aquisto535/mind-palette-project/blob/main/docs/README.md): architecture docs · Pipeline, decision, and operational guidance mirroring the codebase · `docs/README.md`

## Connections

- Browser App → API Client: submit analysis · Browser workflow sends metadata and drawing upload through the client
- Browser App → Result View: render result · UI transitions to result visualization after analysis completes
- API Client → Analyze Route: HTTP request · Frontend calls only the gateway API
- Analyze Route → Security Checks: validate upload · Route applies file-type and path-safety checks before orchestration
- Analyze Route → Orchestrator: dispatch · Valid requests enter the analysis orchestration layer
- Orchestrator → File Storage: persist upload · Gateway writes uploads and manages temp-file lifecycle
- Orchestrator → Shared Volume: read/write files · Gateway coordinates shared-volume artifacts across stages
- Orchestrator → Filter Pipeline: preprocess first · Gateway sends raw upload through the C++ normalization service
- Filter Pipeline → Image Filters: apply transforms · Pipeline composes the major OpenCV filters into a normalized image
- Filter Pipeline → Workers: schedule work · Worker infrastructure runs CPU-bound processing safely
- Workers → Atomic Writer: write output · Processed images are written atomically to disk
- Atomic Writer → Shared Volume: store processed · Preprocess service publishes normalized images to shared storage
- Orchestrator → Analyze Route: send processed image · Gateway forwards the normalized image to the model-serving boundary
- Analyze Route → Tensor Prep: prepare tensor · AI server converts image input into model-ready tensors
- Analyze Route → Model Core: infer · Route executes the loaded model variant
- Model Core → Execution Backends: backend select · Inference can run through TensorRT, ONNX, or PyTorch fallback
- Model Core → IQ Scoring: score outputs · Model outputs are converted into item scores and standardized metrics
- IQ Scoring → Integrity Hash: attach metadata · Gateway preserves result integrity metadata alongside the structured payload
- Orchestrator → Result View: return payload · Final response is shaped for user-facing rendering
- Docs → Orchestrator: specifies · Docs describe the orchestration, security, and storage boundary
- Docs → Filter Pipeline: documents · Docs cover pipeline stages and preprocessing rationale
- Docs → IQ Scoring: documents · Docs describe domain scoring and output semantics
