# Bubble Butt Mexican Boy Denim Fit Lab
## Technical Documentation for Enterprise Review

**Version:** 2.0.0  
**Status:** Ready for Technical Due Diligence  
**Last Updated:** 2026-07-21

---

## 1. Executive Summary

The BBMB Denim Fit Lab is a computer vision and 3D geometry analysis platform designed to quantify and certify denim fit quality for the Chaparrito Nalgón body type. The system combines:

- **Real-time CV pipeline** (Sobel edges → contours → curvature → depth projection → mesh)
- **CNF Certification standard** (Chaparrito Nalgón Fit - 5 geometry classes, 3 compliance tiers)
- **Web-based measurement tools** (pixel-to-inch calibration, arc/angle/distance metrics)
- **Student/analyst workflow** (assessment engine, leaderboard, master mold evolution)

This document is prepared for review by Levi's AI engineering team.

---

## 2. System Architecture

```
┌─────────────────────────────────────────────────────────────────────┐
│                        PRESENTATION LAYER                           │
│  Static HTML (30+ pages) + CSS (style.css, 2,251 lines)           │
│  JS Modules: main.js | cv-pipeline.js | scanner-3d.js            │
│              three-viewer.js | measurement-tools.js               │
├─────────────────────────────────────────────────────────────────────┤
│                        API LAYER (FastAPI)                          │
│  Port 8002                                                          │
│    POST /ingest/frame          - Frame ingestion                    │
│    GET  /metrics/{session_id}  - Live metrics                       │
│    POST /upload                - Photo upload + analysis           │
│    POST /scan                  - CV + 3D scan analysis             │
│    GET  /health                 - Health check                      │
│    GET  /ready                  - Readiness check                   │
│    GET  /api/config             - Frontend configuration           │
│    POST /api/master-mold/update - Mold evolution                   │
│    WS   /ws/live/{session_id}  - WebSocket metrics stream          │
├─────────────────────────────────────────────────────────────────────┤
│                        CV PIPELINE (Python)                         │
│  tools/full_cv_scan.py (796 lines)                                 │
│    StageSobel → StageContours → StageCurvature                     │
│    → StageDepth → StageMesh                                        │
├─────────────────────────────────────────────────────────────────────┤
│                        DATA LAYER                                   │
│  JSON file stores (atomic writes):                                 │
│    data/sessions.json | data/submissions.json                      │
│    data/students.json | data/likes.json                            │
│    data/comments.json | data/scores.json                           │
│    data/training_data/molds/master_mold.json                       │
└─────────────────────────────────────────────────────────────────────┘
```

---

## 3. Technology Stack

| Layer | Technology | Version | Purpose |
|-------|-----------|---------|---------|
| Backend | FastAPI | 0.100+ | REST API + WebSocket |
| CV/Compute | OpenCV | 5.0.0 | Image processing |
| CV/Compute | NumPy | 2.4.6 | Array operations |
| CV/Compute | SciPy | 1.17.1 | Scientific computing |
| CV/Compute | scikit-image | Latest | Image features |
| Frontend | Vanilla JS (ESM) | - | Browser logic |
| 3D | Three.js | 0.157 | WebGL visualization |
| Auth | bcrypt | 4.x | Password hashing |
| Validation | Pydantic | 2.x | Request validation |
| Testing | pytest | 9.x | Unit/integration tests |

---

## 4. Core CV Pipeline

The CV pipeline is implemented as a chain of `PipelineStage` classes:

1. **StageSobel** - Grayscale conversion + Sobel edge detection + adaptive thresholding
2. **StageContours** - Contour extraction with area filtering + sub-pixel refinement
3. **StageCurvature** - 3-point circle-fit curvature + arc length + angle measurement
4. **StageDepth** - Multi-cue pseudo-depth estimation (heuristic projection, NOT metric depth)
5. **StageMesh** - Point cloud → Delaunay triangulation → mesh filtering

### Depth Estimation Transparency

**Important:** True metric 3D reconstruction from a single RGB image is not scientifically valid without:
- A trained monocular depth model (MiDaS, ZoeDepth, etc.)
- A stereo camera pair with known baseline
- A structured light / Time-of-Flight sensor
- A calibrated reference object of known size in frame

The current `StageDepth` produces a **heuristic projection** for visualization purposes. Measurements use 2D pixel geometry with `pixels_per_inch` calibration. This is explicitly documented in the code and API responses.

---

## 5. CNF Certification Standard

### 5.1 Geometry Classes

| Class | Code | Typical SCI | Description |
|-------|------|-------------|-------------|
| High Shelf | `high-shelf` | 28.1° | Upper-glute dominant lift |
| Rounded Projection | `rounded-projection` | 27.4° | Balanced posterior arc |
| Diamond Seat | `diamond-seat` | 26.8° | Lateral expansion + projection |
| Sag-Neutralized | `sag-neutralized` | 25.5° | Compressed lower seat |
| Low-Rise Compression | `low-rise-compression` | 29.2° | High projection, minimal rise |

### 5.2 Compliance Tiers

| Tier | Criteria | Use Case |
|------|----------|----------|
| CNF-Compliant | Meets baseline SCI + YGA thresholds | General fit reviews |
| CNF-Optimized | Enhanced alignment + optimal RPR | Recommended fits |
| CNF-Elite | Near-perfect across all metrics | Best-in-class awards |

### 5.3 Metrics Definitions

| Metric | Full Name | Range | Description |
|--------|-----------|-------|-------------|
| SCI | Seat Curvature Index | 24°–32° | Arc angle from waistband to gluteal apex |
| YGA | Yoke-Glute Alignment | -5 to 5 cm | Offset of yoke seam from apex |
| PD | Pocket Displacement | centered/high-set/diamond | Pocket position relative to apex |
| RPR | Rise-Projection Ratio | 1.5–3.0 | Rise height ÷ projection depth |
| CG | Compression Gradient | uniform/upper/lower/bipolar | Tension distribution across seat |

---

## 6. Security Posture

### Implemented

- ✅ Password hashing with bcrypt (cost factor 12)
- ✅ Input validation on all registration forms (email format, username regex, password length)
- ✅ CORS restricted to specific origins (no wildcard `*`)
- ✅ HTML output sanitized (escapeHtml utility)
- ✅ Atomic file writes to prevent JSON corruption
- ✅ Health/readiness endpoints for orchestration
- ✅ Structured JSON logging (console + file)

### Recommended Before Production

- [ ] JWT or session-based authentication for protected routes
- [ ] Rate limiting on `/upload` and `/scan` endpoints
- [ ] Content-Security-Policy headers
- [ ] Request size limits (currently 10MB max)
- [ ] Secrets management (move `CONSENT_EMAIL` to environment)
- [ ] HTTPS enforcement
- [ ] Database migration from JSON files to PostgreSQL/SQLite

---

## 7. Testing

**Current coverage:** 29 tests across 7 test classes

| Test Class | Tests | Coverage |
|-----------|-------|----------|
| `TestPasswordHashing` | 3 | bcrypt hash/verify |
| `TestValidation` | 4 | email/username validation |
| `TestStudentRegistration` | 6 | registration logic + edge cases |
| `TestStudentAuthentication` | 4 | login/password verification |
| `TestLikes` | 2 | like/unlike flow |
| `TestComments` | 2 | comment CRUD |
| `TestScores` | 2 | score recording + aggregation |
| `TestAPIConfig` | 3 | health/config endpoints |
| `TestCVRPipeline` | 2 | pipeline stage verification |
| `TestSchemas` | 5 | Pydantic validation |

**Run tests:**
```bash
cd /root/bubblebuttmexicanboy.com
python3 -m pytest tests/test_suite.py -v
```

---

## 8. API Reference

### GET /health
Returns service health status.

```json
{
  "status": "healthy",
  "timestamp": "2026-07-21T17:00:00Z"
}
```

### GET /ready
Returns service readiness status.

```json
{
  "status": "ready",
  "timestamp": "2026-07-21T17:00:00Z"
}
```

### GET /api/config
Returns public configuration for frontend initialization.

```json
{
  "consentEmail": "",
  "maxFileSize": 10485760,
  "cvAvailable": true,
  "version": "2.0.0"
}
```

### POST /api/master-mold/update
Updates the master mold with new geometry data. Requires JSON body conforming to `MasterMoldUpdate` schema.

**Request:**
```json
{
  "version": "v7.0",
  "analyst_id": "VN-01",
  "geometry_class": "rounded-projection",
  "compliance_tier": "elite",
  "metrics": {
    "sci": 27.4,
    "yga_alignment_cm": 0.0,
    "pd_pattern": "centered",
    "rpr": 2.18,
    "cg_profile": "uniform"
  },
  "notes": "Rosetta-aligned sample"
}
```

### POST /api/score-config
Updates scoring coefficients (weights must sum to 1.0).

**Request:**
```json
{
  "curvature_weight": 0.30,
  "tension_weight": 0.25,
  "stf_weight": 0.25,
  "symmetry_weight": 0.20
}
```

---

## 9. Data Model

### Student
```json
{
  "id": 1,
  "username": "testuser",
  "email": "test@example.com",
  "password_hash": "$2b$12$...",
  "created": "2026-07-21T17:00:00",
  "approved": true,
  "role": "student"
}
```

### Submission
```json
{
  "id": 1,
  "username": "testuser",
  "score": 96.5,
  "tier": "Elite",
  "date": "2026-07-21",
  "curvature": "0.85/0.92",
  "photo_filename": "session_12345.jpg"
}
```

### Master Mold
```json
{
  "model_id": "vicente_noriega",
  "version": "v7.0",
  "timestamp": "2026-07-21T17:00:00",
  "analyst_id": "VN-01",
  "geometry_class": "rounded-projection",
  "compliance_tier": "elite",
  "metrics": {
    "sci": 27.4,
    "yga_alignment_cm": 0.0,
    "pd_pattern": "centered",
    "rpr": 2.18,
    "cg_profile": "uniform"
  },
  "avg_curvature": 0.89,
  "notes": "Rosetta-aligned"
}
```

---

## 10. Frontend Architecture

### JS Module Structure

| Module | Purpose | Pattern |
|--------|---------|---------|
| `main.js` | Shared nav, DataStore, utilities, toast system | IIFE + global `window.BBMB` |
| `cv-pipeline.js` | Client-side Sobel + contour tracing | ESM export class |
| `scanner-3d.js` | Webcam capture + heuristic depth + point cloud | ESM export class |
| `three-viewer.js` | Three.js mesh visualization with heatmap modes | ESM export class |
| `measurement-tools.js` | Pixel-to-inch calibration + distance/angle/arc | ESM export class |
| `live-room.js` | Live study room with simulated metrics | ESM export class |
| `community.js` | Leaderboard, hall of fame, comments | ESM export class |
| `elite_moment_engine.js` | Elite event detection + HUD overlay | IIFE class |

### Known Limitations

- **Mixed module patterns** (IIFE + ESM) create confusion about global state boundaries
- **No state management library** - relies on `window.BBMB.DataStore` global
- **InnerHTML sanitization added** - see `escapeHtml()` in `community.js` and `elite_moment_engine.js`
- **No lazy loading** - all JS modules loaded on every page

---

## 11. Performance Characteristics

### Python CV Pipeline (measured on synthetic 640×480 input)

| Stage | Time | Complexity |
|-------|------|-----------|
| Grayscale + Sobel | ~12ms | O(W×H) |
| Contour extraction | ~0ms | O(edges) |
| Curvature (3-point) | ~3ms | O(N × window) |
| Depth estimation | ~420ms | O(W×H×step²) |
| Mesh reconstruction | ~7.7s | O(P) Delaunay |

**Bottleneck:** Mesh reconstruction (Delaunay triangulation). For production, consider:
- Poisson surface reconstruction (Open3D) if available
- Pre-computed mesh templates
- WebGL-based client-side mesh generation

### JavaScript Performance

| Component | Concern |
|-----------|---------|
| `cv-pipeline.js` Sobel | O(W×H) pure JS - blocks main thread for ~50ms |
| `scanner-3d.js` depth | Runs at 60fps on main thread - Web Worker recommended |
| Three.js rendering | Properly uses `requestAnimationFrame` |

---

## 12. Known Limitations & Future Work

### Scientific Validity

1. **Depth estimation is heuristic** - documented as pseudo-3D projection
2. **Synthetic data fallback** - exists for testing but should be opt-in only
3. **No camera calibration protocol** - `pixelsPerInch` is user-supplied, not camera-intrinsic based

### Engineering Debt

1. **Monolithic backend** - `backend_main.py` is 694 lines; should split into routers
2. **JSON file database** - not concurrent-safe despite atomic writes; needs PostgreSQL
3. **No CI/CD** - no GitHub Actions, pre-commit hooks, or automated deployment
4. **Duplicated HTML nav** - 30+ pages repeat the same navigation markup

### Enterprise Readiness

1. **Add OpenAPI docs** - FastAPI auto-generates at `/docs` and `/redoc`
2. **Add observability** - Prometheus metrics, structured logging, error tracking (Sentry)
3. **Add rate limiting** - `/upload` and `/scan` endpoints are currently unlimited
4. **Add authentication** - JWT or OAuth2 for protected routes
5. **Add model card** - document training data, failure modes, intended use cases

---

## 13. Quick Start

```bash
# Clone repository
cd /root/bubblebuttmexicanboy.com

# Run tests
python3 -m pytest tests/test_suite.py -v

# Start API server
cd api
python3 backend_main.py

# Access OpenAPI docs
open http://localhost:8002/docs

# Run CV pipeline (headless)
cd tools
python3 full_cv_scan.py

# Serve static site
python3 -m http.server 8080
# Visit http://localhost:8080
```

---

## 14. Contact & Collaboration

This system is prepared for technical review by Levi's AI engineering team. Key artifacts for evaluation:

- [ ] `tests/test_suite.py` - 29 passing tests
- [ ] `api/schemas.py` - Pydantic validation schemas
- [ ] `api/logging_config.py` - Structured JSON logging
- [ ] `tools/full_cv_scan.py` - Full CV pipeline with depth disclaimer
- [ ] `cnf-certification.html` - CNF label generator
- [ ] `contour_evolution.py` - Evolved contour geometry module

For questions or collaboration, refer to the project repository.
