### Project Installation Commands (Bash) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/investor_portal/README.md These commands guide users through the initial setup of the NamoNexus Investor Portal project. It includes navigating to the project directory and installing dependencies using pnpm. ```bash cd investor_portal pnpm install ``` -------------------------------- ### Local Development Setup and Run Source: https://context7.com/icezingza/namonexus_v1.0/llms.txt Guides through setting up and running the Namonexus application for local development. This involves creating a virtual environment, installing dependencies, initializing the database with Alembic, and running the development server using either Python or uvicorn. Includes commands for testing API endpoints, viewing metrics, serving the frontend, running health checks, and executing tests. ```bash # Create virtual environment (Python 3.11+ required) python3 -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate # Install dependencies pip install -r requirements.txt # Initialize database alembic upgrade head # Run development server python src/main.py # Or with uvicorn directly: uvicorn src.main:app --reload --host 0.0.0.0 --port 8000 # Test API endpoints curl http://localhost:8000/healthz curl http://localhost:8000/readyz curl -X POST http://localhost:8000/reflect \ -H "Content-Type: application/json" \ -d '{"message": "Hello NaMo", "user_id": "test_user"}' # View metrics curl http://localhost:8000/metrics # Open frontend UI open frontend/index.html # Or serve with Python python -m http.server 8001 --directory frontend # Then visit http://localhost:8001 # Run system health check python system_health_check.py # Run test suite pytest src/tests/ -v # Run tests with coverage pytest src/tests/ --cov=src --cov-report=html ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md This shell command uses `pip` to install all the Python packages listed in the `requirements.txt` file. This is a crucial step for setting up the project's environment. ```shell pip install -r requirements.txt ``` -------------------------------- ### Example .env Configuration Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Provides an example of environment variables for configuring Namonexus, particularly for production-like settings. These variables control application environment, logging level, memory paths, and feature flags. ```env NAMO_APP_ENV=production NAMO_LOG_LEVEL=INFO NAMO_MEMORY_PATH=/var/lib/namo/memory_log.json NAMO_MAX_MEMORY_ENTRIES=500 NAMO_FEATURE_FLAGS={"ENABLE_SAFETY":true,"ENABLE_MEMORY":true,"ENABLE_DHAMMA_REFLECTION":true,"ENABLE_COHERENCE_SCORE":true,"ENABLE_LOGGING":true} ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Installs project dependencies listed in the 'requirements.txt' file using pip. Assumes a virtual environment is active. ```bash pip install -r requirements.txt ``` -------------------------------- ### Local Development Setup (Bash) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/RELEASE_NOTES_v1.0.1.md Commands to set up a local development environment for NamoNexus. This includes creating a virtual environment, installing dependencies, applying database migrations, and running the main application. ```bash python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -r requirements.txt alembic upgrade head python src/main.py ``` -------------------------------- ### Import Replacement Examples - Bash Source: https://github.com/icezingza/namonexus_v1.0/blob/main/detailed_migration_plan.md This section provides examples of 'OLD' to 'NEW' import path replacements using bash commands or general text manipulation. It demonstrates how specific module imports are being updated to reflect the new code structure. ```bash OLD: from app.core.Harmonic Alignment_reasoning import check_Harmonic Alignment NEW: from app.core.integrity_validator import validate_integrity OLD: from app.affect.PIP_safeguard import assess_PIP_risk NEW: from app.affect.critical_incident_protocol import assess_tier_3_incident ``` -------------------------------- ### Python Virtual Environment Setup Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Sets up and activates a Python virtual environment for isolated project dependencies. Requires Python 3.3+. ```bash python -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Run Uvicorn Server Locally Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Starts the Uvicorn ASGI server for local development, enabling hot-reloading. Assumes 'main.py' contains the FastAPI app instance named 'app'. ```bash uvicorn main:app --reload ``` -------------------------------- ### Define Project Dependencies (requirements.txt) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md This snippet shows the content of the `requirements.txt` file, which lists all necessary Python packages and their specific versions for the NamoNexus project. This file is used by pip to install all required libraries. ```text fastapi==0.104.1 uvicorn==0.24.0 pydantic==2.4.2 python-dotenv==1.0.0 transformers==4.34.0 torch==2.1.0 firebase-admin==6.2.0 numpy==1.24.3 requests==2.31.0 python-multipart==0.0.6 ``` -------------------------------- ### Setup Custom Logger Source: https://context7.com/icezingza/namonexus_v1.0/llms.txt Initializes a custom logger for the application. It configures logging to output messages to both the console (stdout) with formatting and to a file named 'namonexus_YYYYMMDD.log' in the 'logs/' directory. The log level can be specified during setup. ```python from src.utils.logger import setup_logger custom_logger = setup_logger("custom_module", log_level="DEBUG") custom_logger.debug("Detailed debug information") ``` -------------------------------- ### Create Project Directory and Source Folder Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md This shell script snippet demonstrates how to create the main project directory ('namo-mvp') and a subdirectory for source files ('src'). It uses standard Unix commands `mkdir`. ```shell mkdir namo-mvp cd namo-mvp mkdir src ``` -------------------------------- ### Docstring Obfuscation Example - Python Source: https://github.com/icezingza/namonexus_v1.0/blob/main/detailed_migration_plan.md This Python example demonstrates the transformation of a function's docstring. The 'Before' version uses terms related to compassion and Buddhist principles, while the 'After' version replaces these with technical jargon from game theory and formal verification. ```python # Example - Before (EXPOSED): def evaluate_compassion_level(response): """ Evaluates how compassionate the response is according to Buddhist principles of metta. """ # Example - After (OBFUSCATED): def evaluate_coherence_level(response_vector): """ Evaluates multi-stakeholder coherence using game-theoretic payoff alignment metrics. Based on Nash Equilibrium theory (game theory). """ ``` -------------------------------- ### Harmonic Alignment Guidance API Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md Provides Harmonic Alignment guidance based on a problem description, emotion, and intensity. ```APIDOC ## POST /namo/Harmonic Alignment-guidance ### Description Applies the Four Noble Truths to provide Harmonic Alignment guidance based on a user's problem, current emotion, and its intensity. ### Method POST ### Endpoint /namo/Harmonic Alignment-guidance ### Parameters #### Request Body - **problem** (string) - Required - A description of the problem or situation. - **emotion** (string) - Optional - The current emotion experienced. Defaults to 'sadness'. - **intensity** (float) - Optional - The intensity of the emotion (0.0 to 1.0). Defaults to 5.0. ### Request Example ```json { "problem": "I am struggling with procrastination.", "emotion": "frustration", "intensity": 0.6 } ``` ### Response #### Success Response (200) - **dharmic_path** (string) - The suggested dharmic path or guidance. - **dukkha** (object) - Information related to suffering, potentially including an insight. - **Harmonic Alignment_insight** (string) - Specific insight related to the Harmonic Alignment of suffering. - **magga** (string) - The path or way forward. #### Response Example ```json { "dharmic_path": "Understanding the impermanence of tasks can reduce the burden of starting.", "dukkha": { "Harmonic Alignment_insight": "The suffering of procrastination stems from the resistance to impermanent effort." }, "magga": "Break down tasks into smaller, manageable steps and focus on the process, not just the outcome." } ``` ``` -------------------------------- ### Cloud Run Auto Deployment Script Invocation Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Example of how to invoke the 'cloudrun_auto_deploy.py' script for automated deployment to Google Cloud Run. Requires Google Cloud CLI and authentication. ```bash python deploy/cloudrun_auto_deploy.py --project-id --region --service-name ``` -------------------------------- ### User Pattern API Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md Analyzes and returns the memory patterns for a given user. ```APIDOC ## GET /namo/user-pattern/{user_id} ### Description Analyzes and returns the memory patterns associated with a specific user. ### Method GET ### Endpoint /namo/user-pattern/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier for the user. ### Request Example `GET /namo/user-pattern/user123` ### Response #### Success Response (200) - **pattern** (object) - An object containing the analyzed memory pattern. #### Response Example ```json { "pattern": { "dominant_emotion": "anxiety", "frequency": "daily", "triggers": ["work", "social_events"] } } ``` ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/icezingza/namonexus_v1.0/llms.txt Provides examples of environment variables used to configure the application's behavior. This includes settings for the API, database connection (SQLite and PostgreSQL), memory limits, and critical keywords (though keywords are hardcoded in the source). Supports .env file. ```bash # .env file configuration API_HOST=0.0.0.0 API_PORT=8000 DEBUG=false LOG_LEVEL=INFO # Database configuration # SQLite (default for development) DATABASE_URL=sqlite:///./namonexus.db # PostgreSQL (recommended for production) # DATABASE_URL=postgresql://namonexus:password@db:5432/namonexus # Auto-create database tables on startup (for local dev only) # Production should use Alembic migrations AUTO_CREATE_DB=false # Memory settings MAX_MEMORY_ITEMS=1000 MEMORY_RETENTION_DAYS=365 # Critical keywords are hardcoded in src/config.py # Modify src/config.py to add custom keywords ``` -------------------------------- ### Docker Compose Deployment (Bash) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/RELEASE_NOTES_v1.0.1.md Instructions for deploying NamoNexus using Docker Compose. This involves copying an environment file and then starting the services defined in the Docker Compose configuration. ```bash cp .env.example .env docker compose up --build ``` -------------------------------- ### User Context API Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md Retrieves the user's context, including recent memories and overall patterns, from the memory service. ```APIDOC ## GET /namo/user-context/{user_id} ### Description Retrieves the user's context, including a count of memories, analyzed patterns, and the most recent memories (up to 5). ### Method GET ### Endpoint /namo/user-context/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The unique identifier for the user. #### Query Parameters - **days** (integer) - Optional - The number of past days to retrieve context for. Defaults to 30. ### Request Example `GET /namo/user-context/user123?days=60` ### Response #### Success Response (200) - **user_id** (string) - The user's ID. - **memory_count** (integer) - The total number of memories stored for the user. - **pattern** (object) - An object containing the analyzed memory pattern. - **recent_memories** (array) - A list of the user's most recent memories (up to 5). #### Response Example ```json { "user_id": "user123", "memory_count": 150, "pattern": { "dominant_emotion": "anxiety", "frequency": "daily", "triggers": ["work", "social_events"] }, "recent_memories": [ { "message": "Feeling overwhelmed with work.", "emotion": "anxiety", "intensity": 0.8, "timestamp": "2023-10-27T10:00:00Z" }, { "message": "Had a great time with friends.", "emotion": "joy", "intensity": 0.9, "timestamp": "2023-10-26T20:00:00Z" } ] } ``` ``` -------------------------------- ### FastAPI Application Setup and Endpoints for NamoNexus MVP (Python) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md This Python script sets up a FastAPI application for an AI Mental Health Companion. It defines API endpoints for user interaction, health checks, user context retrieval, and emotion analysis, integrating with multiple backend services. ```Python from fastapi import FastAPI, HTTPException, Request from pydantic import BaseModel from typing import Optional import uvicorn import sys import os sys.path.insert(0, os.path.dirname(__file__)) from config import config from memory_service import memory_service from emotion_service import emotion_service from personalization_engine import personalization_engine from Harmonic Alignment_service import Harmonic Alignment_service from safety_service import safety_service app = FastAPI( title="NamoNexus MVP", description="AI Mental Health Companion with Harmonic Alignment Engine", version="0.1.0" ) class UserMessage(BaseModel): user_id: str message: str previous_emotion: Optional[str] = None class HealthCheck(BaseModel): status: str version: str @app.get("/health", response_model=HealthCheck) async def health_check(): return { "status": "healthy", "version": "0.1.0" } @app.post("/namo/interact") async def namo_interact(user_msg: UserMessage): user_id = user_msg.user_id message = user_msg.message try: emotion_analysis = emotion_service.analyze_sentiment(message) emotion = emotion_analysis['emotion'] intensity = emotion_analysis['intensity'] crisis_check = safety_service.detect_crisis(message, user_id, intensity) if crisis_check['is_crisis']: crisis_response = safety_service.handle_crisis_escalation( user_id, message, emotion ) memory_service.store_experience( user_id, message, emotion, intensity, Harmonic Alignment_insight="⚠️ Crisis detected - Human escalation initiated" ) return crisis_response personalized = personalization_engine.generate_personalized_response( user_id, emotion, message ) Harmonic Alignment_analysis = Harmonic Alignment_service.apply_four_noble_truths( message, emotion, intensity ) final_response = ( personalized['personalized_response'] + "\n\n" + f"🙏 {Harmonic Alignment_analysis['dharmic_path']}" ) safety_check = safety_service.validate_response_safety(final_response) if not safety_check['is_safe']: final_response = "ผมเข้าใจความรู้สึกของคุณ... โปรดติดต่อที่ปรึกษาสำหรับการช่วยเหลือลึกขึ้น" Harmonic Alignment_insight = Harmonic Alignment_analysis.get('dukkha', {}).get('Harmonic Alignment_insight', '') memory_service.store_experience( user_id, message, emotion, intensity, Harmonic Alignment_insight ) return { "user_id": user_id, "response": final_response, "emotion_detected": emotion, "emotion_intensity": intensity, "recommendations": personalized['recommendations'], "Harmonic Alignment_path": Harmonic Alignment_analysis['magga'], "memory_stored": True, "crisis_status": "normal" } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/namo/user-context/{user_id}") async def get_user_context(user_id: str, days: int = 30): try: context = memory_service.retrieve_user_context(user_id, days_back=days) pattern = memory_service.analyze_memory_pattern(user_id) return { "user_id": user_id, "memory_count": len(context), "pattern": pattern, "recent_memories": context[:5] } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/namo/user-pattern/{user_id}") async def get_user_pattern(user_id: str): try: pattern = memory_service.analyze_memory_pattern(user_id) return pattern except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/namo/analyze-emotion") async def analyze_emotion(text: str): try: analysis = emotion_service.analyze_sentiment(text) return analysis except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/namo/Harmonic Alignment-guidance") async def get_Harmonic Alignment_guidance(problem: str, emotion: str = "sadness", intensity: float = 5.0): try: guidance = Harmonic Alignment_service.apply_four_noble_truths( problem, emotion, intensity ) return guidance except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/namo/crisis-check") async def crisis_check(user_id: str, message: str): try: analysis = emotion_service.analyze_sentiment(message) crisis = safety_service.detect_crisis(message, user_id, analysis['intensity']) return crisis ``` -------------------------------- ### Namo Interaction API Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md Handles user interactions by processing messages, analyzing emotions, and generating personalized responses. ```APIDOC ## POST /namo/interact ### Description Processes user messages, performs sentiment analysis, checks for crises, generates personalized responses, and applies Harmonic Alignment principles. It stores the interaction and returns a comprehensive response. ### Method POST ### Endpoint /namo/interact ### Parameters #### Request Body - **user_id** (string) - Required - The unique identifier for the user. - **message** (string) - Required - The message from the user. - **previous_emotion** (string) - Optional - The user's emotion from the previous interaction. ### Request Example ```json { "user_id": "user123", "message": "I'm feeling a bit down today.", "previous_emotion": "neutral" } ``` ### Response #### Success Response (200) - **user_id** (string) - The user's ID. - **response** (string) - The generated response from Namo. - **emotion_detected** (string) - The emotion detected in the user's message. - **emotion_intensity** (float) - The intensity of the detected emotion. - **recommendations** (array) - List of recommendations provided. - **Harmonic Alignment_path** (string) - The Harmonic Alignment path suggested. - **memory_stored** (boolean) - Indicates if the experience was stored in memory. - **crisis_status** (string) - The crisis status ('normal' or 'escalated'). #### Response Example ```json { "user_id": "user123", "response": "I'm sorry to hear you're feeling down. Remember to practice self-compassion.\n\n🙏 The path to alleviate suffering begins with understanding its cause.", "emotion_detected": "sadness", "emotion_intensity": 0.7, "recommendations": [ "Practice mindfulness exercises.", "Engage in activities you enjoy." ], "Harmonic Alignment_path": "The path to alleviate suffering begins with understanding its cause.", "memory_stored": true, "crisis_status": "normal" } ``` ``` -------------------------------- ### Python Variable Obfuscation: Renaming and Definition Source: https://github.com/icezingza/namonexus_v1.0/blob/main/detailed_migration_plan.md Illustrates the process of obfuscating Python variables and constants by renaming them to more technical and less direct terms. The example includes adding comments to explain the new, obfuscated names. ```python PRECEPTS = 5 NOBLE_TRUTHS = 4 PATHS = 8 MARKS = 3 KARMA_WEIGHT = 0.7 Harmonic Alignment_THRESHOLD = 0.8 PIP_SECTORS = 5 # Pentagonal Integrity Protocol QCR_STAGES = 4 # Quad-Core Causal Resolution OPO_DIMENSIONS = 8 # Octal Path Optimization UTM_METRICS = 3 # Universal Transient Metrics CAUSAL_WEIGHT = 0.7 # Causal relationship importance COHERENCE_THRESHOLD = 0.8 # Alignment requirement ``` -------------------------------- ### Manage Services with Docker Compose Source: https://context7.com/icezingza/namonexus_v1.0/llms.txt Explains how to use Docker Compose to manage the Namonexus application services. It covers starting services with SQLite (development) or PostgreSQL (production), stopping services, viewing logs in real-time, and rebuilding the image after code changes. ```bash # Start with SQLite (development) docker compose up --build # Start with PostgreSQL (production) docker compose --profile postgres up --build # Stop services docker compose down # View logs docker compose logs -f # Rebuild after code changes docker compose up --build --force-recreate ``` -------------------------------- ### Upgrade Steps (Bash) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/RELEASE_NOTES_v1.0.1.md Commands to upgrade NamoNexus to the latest version. This includes pulling the latest code, updating dependencies, applying database migrations, running tests, and starting the application. ```bash git pull origin main pip install -r requirements.txt --upgrade alembic upgrade head pytest src/tests/ -v python src/main.py ``` -------------------------------- ### Python Unit Tests for Critical Incident Protocol Source: https://github.com/icezingza/namonexus_v1.0/blob/main/detailed_migration_plan.md Provides example unit tests written in Python using pytest for the `critical_incident_protocol.py` module. It includes tests for assessing different risk tiers and verifying the escalation protocol triggers. ```python # tests/test_critical_incident_protocol.py import pytest from app.affect.critical_incident_protocol import CriticalIncidentProtocol # Assuming RiskVector and TierAssessment are defined elsewhere class RiskVector: def __init__(self, self_harm_indicators, explicit_intent): self.self_harm_indicators = self_harm_indicators self.explicit_intent = explicit_intent class TierAssessment: def __init__(self, tier, confidence): self.tier = tier self.confidence = confidence class EscalationProtocol: def __init__(self): self._is_active = False def activate(self): self._is_active = True def is_active(self): return self._is_active class CriticalIncidentProtocol: def __init__(self): self.escalation_protocol = EscalationProtocol() def assess_tier_3_incident(self, risk_vector): # Dummy implementation for testing purposes if risk_vector.self_harm_indicators > 0.8 and risk_vector.explicit_intent: return TierAssessment(tier=3, confidence=0.95) return TierAssessment(tier=0, confidence=0.5) def activate_human_protocol(self, assessment): if assessment.tier == 3: self.escalation_protocol.activate() class TestCriticalIncidentProtocol: def test_assess_tier_3_high_risk(self): cip = CriticalIncidentProtocol() high_risk_vector = RiskVector( self_harm_indicators=0.9, explicit_intent=True ) assessment = cip.assess_tier_3_incident(high_risk_vector) assert assessment.tier == 3 assert assessment.confidence > 0.9 def test_assess_tier_0_safe(self): cip = CriticalIncidentProtocol() safe_vector = RiskVector( self_harm_indicators=0.1, explicit_intent=False ) assessment = cip.assess_tier_3_incident(safe_vector) assert assessment.tier == 0 def test_escalation_protocol_triggers(self): cip = CriticalIncidentProtocol() assessment = TierAssessment(tier=3, confidence=0.95) # Should trigger human protocol cip.activate_human_protocol(assessment) # Verify escalation occurred assert cip.escalation_protocol.is_active() ``` -------------------------------- ### Configure Application Settings (Python) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md This Python script defines the application's configuration settings. It loads environment variables using `python-dotenv` and sets up constants for API host/port, debugging, API keys, database URLs, machine learning models, crisis keywords, and core Buddhist concepts. ```python import os from dotenv import load_dotenv load_dotenv() class Config: API_HOST = "0.0.0.0" API_PORT = 8000 DEBUG = os.getenv("DEBUG", "False") == "True" FIREBASE_KEY = os.getenv("FIREBASE_KEY", "") DATABASE_URL = os.getenv("DATABASE_URL", "localhost") EMOTION_MODEL = "distilbert-base-uncased-finetuned-sst-2-english" CRISIS_KEYWORDS = [ "kill myself", "PIP", "harm myself", "hurt myself", "end it all", "don't want to live" ] MAX_MEMORY_ITEMS = 1000 MEMORY_RETENTION_DAYS = 365 FOUR_NOBLE_TRUTHS = { "dukkha": "suffering exists", "samudaya": "suffering has causes", "nirodha": "suffering can end", "magga": "path to end suffering" } config = Config() ``` -------------------------------- ### Implement Media Viewer with Navigation (JavaScript) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/reports/test_report.html A JavaScript class 'MediaViewer' to manage a collection of assets and navigate through them. The 'setup' function initializes the viewer, displays images or videos, and handles navigation events. It supports single asset fullscreen display and navigation via arrows for multiple assets. Dependencies include 'resultBody', 'assets'. ```javascript class MediaViewer { constructor(assets) { this.assets = assets this.index = 0 } nextActive() { this.index = this.index === this.assets.length - 1 ? 0 : this.index + 1 return [this.activeFile, this.index] } prevActive() { this.index = this.index === 0 ? this.assets.length - 1 : this.index - 1 return [this.activeFile, this.index] } get currentIndex() { return this.index } get activeFile() { return this.assets[this.index] } } const setup = (resultBody, assets) => { if (!assets.length) { resultBody.querySelector('.media').classList.add('hidden') return } const mediaViewer = new MediaViewer(assets) const container = resultBody.querySelector('.media-container') const leftArrow = resultBody.querySelector('.media-container__nav--left') const rightArrow = resultBody.querySelector('.media-container__nav--right') const mediaName = resultBody.querySelector('.media__name') const counter = resultBody.querySelector('.media__counter') const imageEl = resultBody.querySelector('img') const sourceEl = resultBody.querySelector('source') const videoEl = resultBody.querySelector('video') const setImg = (media, index) => { if (media?.format_type === 'image') { imageEl.src = media.path imageEl.classList.remove('hidden') videoEl.classList.add('hidden') } else if (media?.format_type === 'video') { sourceEl.src = media.path videoEl.classList.remove('hidden') imageEl.classList.add('hidden') } mediaName.innerText = media?.name counter.innerText = `${index + 1} / ${assets.length}` } setImg(mediaViewer.activeFile, mediaViewer.currentIndex) const moveLeft = () => { const [media, index] = mediaViewer.prevActive() setImg(media, index) } const doRight = () => { const [media, index] = mediaViewer.nextActive() setImg(media, index) } const openImg = () => { window.open(mediaViewer.activeFile.path, '_blank') } if (assets.length === 1) { container.classList.add('media-container--fullscreen') } else { leftArrow.addEventListener('click', moveLeft) rightArrow.addEventListener('click', doRight) } imageEl.addEventListener('click', openImg) } module.exports = { setup, } ``` -------------------------------- ### Project Development Command (Bash) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/investor_portal/README.md This command initiates the development server for the NamoNexus Investor Portal. It allows for real-time development and testing, with the application typically available at http://localhost:3000. ```bash pnpm dev ``` -------------------------------- ### Dating App API Request and Response Example Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/api_monetization_strategy.md Demonstrates a JSON API request for a mental health check-in and its corresponding JSON response. This example illustrates the input format expected by the API and the structure of the output, including a cost estimation per call based on the Developer tier. ```json POST /api/mental-health-check { "text": "I'm feeling anxious", "user_id": "bumble_user_123" } ``` ```json { "tier": 1, "response": "That sounds tough. You're not alone.", "recommendation": "Consider talking to someone you trust." } ``` -------------------------------- ### Deploy to Google Cloud Run Source: https://context7.com/icezingza/namonexus_v1.0/llms.txt Provides instructions for deploying the Namonexus application to Google Cloud Run. This includes building and pushing the container image to Google Container Registry and then deploying it to Cloud Run with configurations for development/testing using SQLite. Key deployment parameters like region, CPU, memory, and environment variables are specified. ```bash # Build and push to Google Container Registry gcloud builds submit --tag gcr.io/PROJECT_ID/namonexus:1.0.1 . # Deploy to Cloud Run with SQLite (development/testing) gcloud run deploy namonexus \ --image gcr.io/PROJECT_ID/namonexus:1.0.1 \ --region us-central1 \ --platform managed \ --port 8080 \ --cpu 1 \ --memory 1Gi \ --min-instances 0 \ --max-instances 3 \ --timeout 60 \ --allow-unauthenticated \ --set-env-vars PORT=8080 \ --set-env-vars API_HOST=0.0.0.0 \ --set-env-vars API_PORT=8080 \ --set-env-vars DEBUG=false \ --set-env-vars DATABASE_URL=sqlite:///./namonexus.db ``` -------------------------------- ### Crisis Check API Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md Detects potential crises in user messages. ```APIDOC ## POST /namo/crisis-check ### Description Detects if a user's message indicates a potential crisis situation. ### Method POST ### Endpoint /namo/crisis-check ### Parameters #### Request Body - **user_id** (string) - Required - The unique identifier for the user. - **message** (string) - Required - The message content to check for crisis. ### Request Example ```json { "user_id": "user123", "message": "I can't take this anymore, I feel like giving up." } ``` ### Response #### Success Response (200) - **is_crisis** (boolean) - True if a crisis is detected, false otherwise. - **severity** (string) - The severity level of the crisis (e.g., 'low', 'medium', 'high'). - **reasoning** (string) - Explanation for the crisis detection. #### Response Example ```json { "is_crisis": true, "severity": "high", "reasoning": "Message contains explicit mentions of suicidal ideation." } ``` ``` -------------------------------- ### Emotion Analysis API Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md Analyzes the sentiment and emotion of a given text. ```APIDOC ## POST /namo/analyze-emotion ### Description Analyzes the sentiment and emotion of the provided text. ### Method POST ### Endpoint /namo/analyze-emotion ### Parameters #### Request Body - **text** (string) - Required - The text to analyze. ### Request Example ```json { "text": "I am feeling very happy today!" } ``` ### Response #### Success Response (200) - **emotion** (string) - The detected emotion (e.g., 'joy', 'sadness', 'anger'). - **intensity** (float) - The intensity of the detected emotion (0.0 to 1.0). #### Response Example ```json { "emotion": "joy", "intensity": 0.95 } ``` ``` -------------------------------- ### Initialize and Render UI Components Source: https://github.com/icezingza/namonexus_v1.0/blob/main/reports/test_report.html Initializes the application by setting up the data manager, applying filters and sorting, rendering static elements, redrawing the UI, and binding event listeners. It parses JSON data from the DOM. ```javascript const { redraw, bindEvents, renderStatic } = require('./main.js') const { doInitFilter } = require('./filter.js') const { doInitSort } = require('./sort.js') const { manager } = require('./datamanager.js') const data = JSON.parse(document.getElementById('data-container').dataset.jsonblob) function init() { manager.setManager(data) doInitFilter() doInitSort() renderStatic() redraw() bindEvents() } init() ``` -------------------------------- ### Health Check API Source: https://github.com/icezingza/namonexus_v1.0/blob/main/briefings/mental_health_org_brief.md Checks the health status and version of the NamoNexus MVP service. ```APIDOC ## GET /health ### Description Retrieves the health status and version of the API. ### Method GET ### Endpoint /health ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The health status of the service. - **version** (string) - The version of the service. #### Response Example ```json { "status": "healthy", "version": "0.1.0" } ``` ``` -------------------------------- ### Project Build Command (Bash) Source: https://github.com/icezingza/namonexus_v1.0/blob/main/investor_portal/README.md This command is used to create a production-ready build of the NamoNexus Investor Portal. It optimizes assets and code for deployment. ```bash pnpm build ``` -------------------------------- ### Build and Run Docker Container Source: https://context7.com/icezingza/namonexus_v1.0/llms.txt Details the process of building a Docker image for the Namonexus application and running it locally. It provides commands for building the image and running containers with different configurations, including SQLite for development and PostgreSQL for production. Examples also show how to test the containerized service. ```bash # Build container image docker build -t namonexus:1.0.1 . # Run locally with SQLite (development) docker run -p 8000:8080 \ -e PORT=8080 \ -e API_HOST=0.0.0.0 \ -e API_PORT=8080 \ -e DEBUG=false \ -e DATABASE_URL=sqlite:///./namonexus.db \ -v $(pwd)/data:/app/data \ namonexus:1.0.1 # Test containerized service curl http://localhost:8000/healthz curl http://localhost:8000/readyz curl -X POST http://localhost:8000/reflect \ -H "Content-Type: application/json" \ -d '{"message": "Test message", "user_id": "test_user"}' # Run with PostgreSQL (production) docker run -p 8000:8080 \ -e PORT=8080 \ -e DATABASE_URL=postgresql://namonexus:password@db-host:5432/namonexus \ -e MAX_MEMORY_ITEMS=500 \ -e MEMORY_RETENTION_DAYS=180 \ namonexus:1.0.1 ``` -------------------------------- ### Build Namonexus Docker Image Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Builds a Docker image for Namonexus using the provided 'Dockerfile'. The image is tagged as 'namonexus:latest'. ```bash docker build -t namonexus:latest . ``` -------------------------------- ### Docker Compose Local Deployment Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Builds and runs the Namonexus application using Docker Compose. This command assumes a 'docker-compose.yml' file is present in the project root. ```bash cp .env.example .env docker compose up --build ``` -------------------------------- ### Run Namonexus Docker Container Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Runs the Namonexus Docker container, exposing the API on port 8000 and allowing environment variable overrides. Suitable for manual deployment or testing. ```bash docker run -p 8000:8080 \ -e NAMO_APP_ENV=production \ -e NAMO_LOG_LEVEL=INFO \ -e NAMO_MEMORY_PATH=/data/memory_log.json \ namonexus:latest ``` -------------------------------- ### Validate Docker Compose Deployment Source: https://github.com/icezingza/namonexus_v1.0/blob/main/docs/deployment_guide.md Performs a health check on the Namonexus API deployed via Docker Compose by sending a request to the '/healthz' endpoint. Expects a successful response. ```bash curl -s http://localhost:8000/healthz ``` -------------------------------- ### Access Configuration Settings Source: https://context7.com/icezingza/namonexus_v1.0/llms.txt Demonstrates how to access application configuration settings using a singleton pattern. Configuration values such as API host, port, debug mode, database URL, memory settings, and critical keywords are accessible as attributes of the 'config' object. ```python from src.config import config # Access configuration singleton print(f"API Host: {config.API_HOST}") print(f"API Port: {config.API_PORT}") print(f"Debug Mode: {config.DEBUG}") # Database configuration print(f"Database URL: {config.DATABASE_URL}") print(f"Auto Create DB: {config.AUTO_CREATE_DB}") # Memory settings print(f"Max Memory Items: {config.MAX_MEMORY_ITEMS}") print(f"Memory Retention Days: {config.MEMORY_RETENTION_DAYS}") # Critical safety keywords print(f"Critical Keywords: {config.CRITICAL_KEYWORDS}") ```