Skip to content

Latest commit

Β 

History

103 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Luna AI β€” Monorepo Architecture

Production-oriented monorepo architecture for the Luna AI voice assistant and emotional counseling application.


1. πŸ“ Repository Structure

.
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ luna_mobile/             # Flutter mobile application (UI, Clean Architecture, Riverpod)
β”‚   β”‚
β”‚   └── backend/
β”‚       β”œβ”€β”€ api/                # FastAPI application server (REST, WebSocket, Auth, Sessions)
β”‚       β”‚   β”œβ”€β”€ app/
β”‚       β”‚   β”‚   β”œβ”€β”€ api/        # Routes & dependencies
β”‚       β”‚   β”‚   β”œβ”€β”€ core/       # Logging & config
β”‚       β”‚   β”‚   β”œβ”€β”€ models/     # SQLAlchemy 2.x models
β”‚       β”‚   β”‚   β”œβ”€β”€ schemas/    # Pydantic v2 schemas
β”‚       β”‚   β”‚   β”œβ”€β”€ services/   # Application domain services
β”‚       β”‚   β”‚   └── main.py     # FastAPI entry point
β”‚       β”‚   β”œβ”€β”€ migrations/     # Alembic database migrations
β”‚       β”‚   β”œβ”€β”€ tests/          # Pytest suite for API
β”‚       β”‚   β”œβ”€β”€ pyproject.toml
β”‚       β”‚   └── Dockerfile
β”‚       β”‚
β”‚       β”œβ”€β”€ mcp/                # FastMCP AI tool/context server (Model Context Protocol)
β”‚       β”‚   β”œβ”€β”€ app/
β”‚       β”‚   β”‚   β”œβ”€β”€ tools/      # MCP tools exposed to LLM
β”‚       β”‚   β”‚   β”œβ”€β”€ resources/  # MCP resources
β”‚       β”‚   β”‚   β”œβ”€β”€ services/   # Internal tool services
β”‚       β”‚   β”‚   └── main.py     # FastMCP entry point
β”‚       β”‚   β”œβ”€β”€ tests/          # Pytest suite for MCP
β”‚       β”‚   β”œβ”€β”€ pyproject.toml
β”‚       β”‚   └── Dockerfile
β”‚       β”‚
β”‚       └── workers/            # ARQ async Redis background workers
β”‚           β”œβ”€β”€ app/
β”‚           β”‚   β”œβ”€β”€ tasks/      # Background task definitions (Summarization, Risk, Emotion)
β”‚           β”‚   β”œβ”€β”€ workers/    # ARQ WorkerSettings
β”‚           β”‚   └── main.py     # Worker entry point
β”‚           β”œβ”€β”€ tests/          # Pytest suite for workers
β”‚           β”œβ”€β”€ pyproject.toml
β”‚           └── Dockerfile
β”‚
β”œβ”€β”€ packages/
β”‚   β”œβ”€β”€ shared/                 # Shared domain types, config, errors, DB connections
β”‚   β”‚   β”œβ”€β”€ config.py
β”‚   β”‚   β”œβ”€β”€ database.py
β”‚   β”‚   β”œβ”€β”€ errors.py
β”‚   β”‚   β”œβ”€β”€ types.py
β”‚   β”‚   └── pyproject.toml
β”‚   β”‚
β”‚   └── ai/                     # AI provider interfaces, RAG, emotion detection, orchestrator
β”‚       β”œβ”€β”€ interfaces/
β”‚       β”œβ”€β”€ orchestration/
β”‚       β”œβ”€β”€ services/
β”‚       β”œβ”€β”€ vector_store/
β”‚       └── pyproject.toml
β”‚
β”œβ”€β”€ scripts/                    # Development & Docker automation scripts
β”‚   β”œβ”€β”€ docker-dev.sh / .ps1    # Automated Docker dev setup + auto-migration & seeding
β”‚   β”œβ”€β”€ dev.sh / .ps1           # Local Python services launcher
β”‚   β”œβ”€β”€ setup.sh / .ps1         # Virtual environment & package installation
β”‚   β”œβ”€β”€ seed.py                 # Initial database seeder script
β”‚   └── DOCKER_SETUP.md         # Detailed Docker documentation
β”‚
β”œβ”€β”€ tests/                      # Global & POC test suites
β”‚   β”œβ”€β”€ test_emotion/           # Speech Emotion Recognition (emotion2vec_plus_large) POC
β”‚   └── test_ai_providers.py    # Integration test for AI LLM providers
β”‚
β”œβ”€β”€ docs/                       # Architecture diagrams & business logic specs
β”œβ”€β”€ .env.example                # Environment variables template
β”œβ”€β”€ docker-compose.yml          # Local multi-service Docker setup
β”œβ”€β”€ ruff.toml                   # Root linting & formatting rules
└── README.md                   # Project overview & documentation

2. πŸ›οΈ Core Architecture Overview

Component Technology Primary Role & Responsibilities
FastAPI Backend Python 3.11 / FastAPI Primary API server for mobile clients (REST & WebSocket). Manages auth, sessions, call routing, and enqueues jobs.
FastMCP Server FastMCP Exposes standard Model Context Protocol (MCP) tools and resources to LLMs safely.
ARQ Workers ARQ / Redis Executes async background tasks (e.g., emotion detection, diary synthesis, memory extraction).
PostgreSQL PostgreSQL 16 Relational store for users, conversation logs, call metadata, and application state.
Redis Redis 7 High-performance cache, pub/sub channel for audio streaming, and ARQ task queue storage.
Qdrant Qdrant Vector database for storing and querying long-term semantic memory embeddings.
Flutter Mobile Flutter / Riverpod Mobile application with Clean Architecture and mock/remote data source toggle.

3. πŸš€ Cara Run (Getting Started Guide)

πŸ“Œ Prerequisites

  • Git
  • Docker & Docker Compose (for Docker setup)
  • Python 3.11+ (for local development)
  • Flutter SDK (for running luna_mobile)

🐳 Metode A: Running via Docker (Direkomendasikan β€” Cepat & Ringan)

Script otomatis docker-dev akan memeriksa berkas .env, menjalankan container, melakukan migrasi database (Alembic), dan mengisi data awal (seeding):

Linux / macOS:

chmod +x scripts/docker-dev.sh
./scripts/docker-dev.sh

Windows (PowerShell):

.\scripts\docker-dev.ps1

Manual Docker Command:

# Copas env jika belum ada
cp .env.example .env

# Jalankan semua service
docker compose up --build

🌐 Port Mappings (Docker Host vs Container):

Service Host Port Container Port Endpoint / URL
FastAPI Backend 8888 8888 http://localhost:8888
FastMCP Server 8889 8889 http://localhost:8889
PostgreSQL 5433 5432 localhost:5433
Redis 6380 6379 localhost:6380
Qdrant Vector DB 6333 6333 http://localhost:6333

ℹ️ Detail panduan Docker dapat dibaca di scripts/DOCKER_SETUP.md.


πŸ’» Metode B: Running Local Development (Standalone / Hybrid)

Jika ingin menjalankan service secara langsung di lingkungan lokal Python:

  1. Setup Environment & Virtualenv:

    # Linux/macOS
    ./scripts/setup.sh
    
    # Windows
    .\scripts\setup.ps1
  2. Jalankan Service Backend:

    # Linux/macOS
    ./scripts/dev.sh
    
    # Windows
    .\scripts\dev.ps1
  3. Atau Jalankan Service Secara Manual per Terminal:

    source .venv/bin/activate
    
    # 1. FastAPI API
    cd apps/backend/api && uvicorn app.main:app --reload --port 8888
    
    # 2. FastMCP Server
    cd apps/backend/mcp && python -m app.main
    
    # 3. ARQ Background Worker
    cd apps/backend/workers && arq app.workers.WorkerSettings

πŸ“± Metode C: Running Mobile App (Flutter)

Aplikasi Flutter luna_mobile dapat dijalankan di Perangkat Fisik (HP Android via USB Debugging), Emulator, maupun Web/Desktop.

1. Persiapan HP Android (Physical Device) / Emulator:

  • Pastikan HP Android sudah dalam mode Developer Options dan USB Debugging telah diaktifkan.
  • Hubungkan HP ke laptop/PC menggunakan kabel USB, lalu periksa koneksi perangkat:
    adb devices
    (Pastikan perangkat muncul di daftar dengan status device)

2. Menjalankan Aplikasi Flutter (Mode Lokal vs Production):

Secara default, jika dijalankan dengan flutter run, aplikasi akan terhubung ke server production (172.93.219.133:8888). Untuk menghubungkannya ke server backend lokal laptop:

A. Perangkat Fisik Android (Physical Device via USB) & Desktop / Web:
  1. Lakukan reverse port ADB agar port di dalam HP meneruskan request ke laptop via kabel USB:
    adb reverse tcp:8888 tcp:8888
  2. Jalankan Flutter dengan flag USE_LOCAL_API:
    cd apps/luna_mobile
    flutter run --dart-define=USE_LOCAL_API=true

    ℹ️ Host yang Digunakan: http://127.0.0.1:8888/api/v1 (terhubung langsung ke backend laptop via USB ADB reverse loopback).

B. Android Emulator (Virtual Device):

Jika menggunakan Android Emulator standar (tanpa menjalankan adb reverse), tambahkan flag IS_EMULATOR=true:

cd apps/luna_mobile
flutter run --dart-define=USE_LOCAL_API=true --dart-define=IS_EMULATOR=true

ℹ️ Host yang Digunakan: http://10.0.2.2:8888/api/v1 (karena 10.0.2.2 adalah gateway router virtual emulator untuk mengakses localhost host laptop).

C. Koneksi Wi-Fi LAN / IP Custom (Tanpa Kabel USB):

Jika HP fisik dan laptop berada dalam satu jaringan Wi-Fi yang sama:

cd apps/luna_mobile
flutter run --dart-define=LOCAL_HOST=192.168.1.50:8888

(Ganti 192.168.1.50 dengan IP lokal laptop Anda).

D. Menjalankan Mode Default (Production Cloud Server):
cd apps/luna_mobile
flutter run

3. Konfigurasi VS Code (Debug / Run Langsung):

Tambahkan konfigurasi berikut ke .vscode/launch.json di root workspace agar dapat langsung menekan F5 / Run:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Luna Mobile (HP Fisik USB - Local)",
      "request": "launch",
      "type": "dart",
      "program": "apps/luna_mobile/lib/main.dart",
      "args": [
        "--dart-define=USE_LOCAL_API=true"
      ]
    },
    {
      "name": "Luna Mobile (Android Emulator - Local)",
      "request": "launch",
      "type": "dart",
      "program": "apps/luna_mobile/lib/main.dart",
      "args": [
        "--dart-define=USE_LOCAL_API=true",
        "--dart-define=IS_EMULATOR=true"
      ]
    },
    {
      "name": "Luna Mobile (Production Cloud)",
      "request": "launch",
      "type": "dart",
      "program": "apps/luna_mobile/lib/main.dart"
    }
  ]
}

4. Tombol Pintas Interaktif (flutter run CLI):

  • Tekan r : Hot Reload (Pembaruan UI secara instan tanpa mereset halaman)
  • Tekan R : Hot Restart (Mereset ulang state aplikasi dari awal)
  • Tekan c : Bersihkan layar terminal log
  • Tekan q : Quit / Keluar dari aplikasi

πŸ”‘ Akun Demo (Demo Accounts & Mock Mode)

Untuk keperluan pengujian dan demonstrasi aplikasi:

1. Akun Master Demo (Auto-Seeded di Database):

Saat menjalankan script docker-dev atau python scripts/seed.py, akun demo berikut otomatis tersedia di database:

  • Email: samsul@gmail.com
  • Password: password123
  • User Display Name: Samsul
  • Data Pre-seeded:
    • Kontak Darurat Utama: Ibu (Siti Rahma - 0812-3456-7890) & Dr. Handoko (Psikiater - 0811-9876-5432).
    • Riwayat Jurnal Emosional: Termasuk entri jurnal refleksi krisis darurat (28 Agustus 2026) dan entri stabil (31 Agt & 1 Sep 2026).
    • Rekomendasi Mental Health: Rekomendasi pernapasan 4-7-8, jurnal ekspresif, dan jeda digital.

2. Toggle Offline Mock Mode (Flutter Mobile):

Jika ingin menguji antarmuka aplikasi luna_mobile secara langsung tanpa menghubungkan ke server backend/database:

  • Buka apps/luna_mobile/lib/core/config/app_config.dart.
  • Set variabel static const bool useMockData = true;.

πŸ§ͺ Metode D: Running Tests & Spesifikasi Lingkungan Pengujian

1. πŸ–₯️ Spesifikasi Lingkungan Pengujian (Test Environment Specs):

Komponen Spesifikasi Direkomendasikan Catatan Pengujian
Sistem Operasi Linux (Ubuntu 22.04 LTS / WSL2), macOS 13+, Windows 11 Lintas platform
Python Runtime Python 3.11.x Menggunakan pytest 8.x, pytest-asyncio
Mobile Runtime Flutter SDK 3.22+, Dart 3.4+ Tested di HP Android Fisik (API 34 / Android 14) & Emulator
Database & Cache PostgreSQL 16, Redis 7, Qdrant Vector DB 1.9+ Berjalan via Docker Compose
AI / Speech Model FunASR (emotion2vec_plus_large) Test POC Speech Emotion Recognition

2. Menjalankan Unit/Integration Tests (Pytest):

# Test API
pytest apps/backend/api/tests

# Test MCP Tools
pytest apps/backend/mcp/tests

# Test Workers
pytest apps/backend/workers/tests

# Test AI Packages
pytest packages/ai/tests

3. Menjalankan POC Speech Emotion Recognition (emotion2vec_plus_large):

python3 tests/test_emotion/test_emotion.py

Hasil pengujian emotion recognition akan otomatis ditulis ke tests/test_emotion/poc_result.md.


4. πŸ”„ Service Communication Flow

graph TD
    Client["πŸ“± Luna Mobile (Flutter)"] -->|REST / WebSocket :8888| API["⚑ FastAPI Backend"]
    LLM["πŸ€– LLM Agent / Client"] -->|MCP Protocol :8889| MCP["πŸ› οΈ FastMCP Server"]
    
    API -->|Read/Write| DB[(🐘 PostgreSQL :5433)]
    API -->|Cache / Queue| Redis[(πŸ”΄ Redis :6380)]
    API -->|Vector Search| Qdrant[(🎯 Qdrant :6333)]
    
    API -->|Enqueue Jobs| Redis
    Redis -->|Dequeue Jobs| Worker["βš™οΈ ARQ Background Workers"]
    
    Worker --> DB
    Worker --> Qdrant
    Worker -->|AI Services| AI["🧠 packages/ai"]
    MCP -->|Shared Models| Shared["πŸ“¦ packages/shared"]
Loading

5. πŸ› οΈ Code Style & Standards

  • Python: Linter & formatter dikonfigurasi menggunakan Ruff (ruff.toml).
  • Clean Architecture: luna_mobile memisahkan lapisan domain, data, dan presentation.
  • Decoupled Packages: Module packages/shared dan packages/ai di-install sebagai paket editable (pip install -e) agar bisa digunakan bersama oleh api, mcp, dan workers.

About

πŸŒ™ Luna AI β€” AI-Powered Mental Health Counseling & Emotional Well-Being Companion. Features real-time voice call counseling (VAD + TTS), automated daily AI diary synthesis, mood tracking, and safety gates with emergency crisis intervention protocols. Built with Flutter, FastAPI, FastMCP, Qdrant, & ARQ.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages