Download grid_core.py from MoShow/WoTak: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/MoShow/WoTak/resolve/main/grid_core.py
- Command line
-
hf download hf://spaces/MoShow/WoTak/grid_core.py
-
curl -L -o grid_core.py https://huggingface.co/spaces/MoShow/WoTak/resolve/main/grid_core.py
10.1 kB
| ```python | |
| from fastapi import FastAPI, HTTPException, UploadFile, File | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from typing import List, Optional, Dict, Any | |
| import sqlite3 | |
| import json | |
| import os | |
| from datetime import datetime | |
| import uuid | |
| # Import existing engines | |
| from truth_engine import TruthEngine | |
| from mind_layer_verdict_engine import MindVerdict | |
| from soul_layer_spiritual_engine import SoulCore | |
| from body_layer_api_executor import APIExecutor | |
| from mostar_philosophy import CovenantFilter | |
| from mostar_moments_log import log_event | |
| # Import Mostly AI | |
| from mostlyai.sdk import MostlyAI | |
| app = FastAPI(title="Mostar Grid API", version="3.0.0") | |
| # Add CORS middleware | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Initialize engines | |
| truth_engine = TruthEngine() | |
| mind_verdict = MindVerdict() | |
| soul_core = SoulCore() | |
| api_executor = APIExecutor() | |
| covenant_filter = CovenantFilter() | |
| # Initialize Mostly AI | |
| MOSTLY_AI_KEY = os.getenv("MOSTLY_AI_KEY", "INSERT_YOUR_API_KEY") | |
| MOSTLY_BASE_URL = os.getenv("MOSTLY_BASE_URL", "https://app.mostly.ai") | |
| mostly = MostlyAI(api_key=MOSTLY_AI_KEY, base_url=MOSTLY_BASE_URL) | |
| # Database path | |
| DB_PATH = "mostar.db" | |
| # Create tables if they don't exist | |
| def init_db(): | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| # Extend existing table with new columns | |
| try: | |
| cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN truth_score REAL") | |
| except sqlite3.OperationalError: | |
| pass # Column already exists | |
| try: | |
| cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN soul_state TEXT") | |
| except sqlite3.OperationalError: | |
| pass # Column already exists | |
| try: | |
| cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN policy TEXT") | |
| except sqlite3.OperationalError: | |
| pass # Column already exists | |
| # Create soulprints table if it doesn't exist | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS soulprints ( | |
| id TEXT PRIMARY KEY, | |
| name TEXT, | |
| content TEXT, | |
| tags TEXT, | |
| created_at TEXT | |
| ) | |
| """) | |
| # Create grid_training table | |
| cursor.execute(""" | |
| CREATE TABLE IF NOT EXISTS grid_training ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| dataset_id TEXT, | |
| generator_id TEXT, | |
| agent TEXT, | |
| record_count INTEGER, | |
| timestamp TEXT | |
| ) | |
| """) | |
| conn.commit() | |
| conn.close() | |
| init_db() | |
| # Models | |
| class DecisionRequest(BaseModel): | |
| query: str | |
| context: Optional[Dict[Any, Any]] = None | |
| class DecisionResponse(BaseModel): | |
| verdict: Dict[Any, Any] | |
| truth_assessment: Dict[Any, Any] | |
| soul_insight: Dict[Any, Any] | |
| execution_result: Optional[Dict[Any, Any]] = None | |
| policy_alignment: str | |
| class SoulPrintUpload(BaseModel): | |
| name: str | |
| content: str | |
| tags: List[str] | |
| # Grid Routes | |
| def grid_status(): | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT COUNT(*) FROM mind_verdicts") | |
| node_count = cursor.fetchone()[0] | |
| conn.close() | |
| return { | |
| "status": "Active", | |
| "neural_nodes": node_count, | |
| "coherence": 99.98, | |
| "sync_delay": 2.3, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| def grid_feed(): | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT COUNT(*) FROM mind_verdicts") | |
| node_count = cursor.fetchone()[0] | |
| conn.close() | |
| return { | |
| "message": f"🔸 [Mostar Feed] Grid sync stable – Neural nodes: {node_count} active – Last signal: 2.3s ago – Coherence: 99.98% – Flow: Optimal" | |
| } | |
| # Decision Making Endpoint | |
| def evaluate_decision(request: DecisionRequest): | |
| try: | |
| # Get truth assessment | |
| truth_result = truth_engine.assess_truth(request.query) | |
| # Get mind verdict | |
| mind_result = mind_verdict.form_verdict(request.query, request.context or {}) | |
| # Get soul insight | |
| soul_result = soul_core.reflect_on_issue(request.query) | |
| # Apply covenant filter | |
| policy_alignment = covenant_filter.evaluate_compliance({ | |
| "verdict": mind_result, | |
| "truth": truth_result, | |
| "soul_state": soul_result | |
| }) | |
| # Execute if needed | |
| execution_result = None | |
| if mind_result.get("requires_action"): | |
| execution_result = api_executor.execute_task(request.query) | |
| # Store in database | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute(""" | |
| INSERT INTO mind_verdicts (query, verdict, timestamp, truth_score, soul_state, policy) | |
| VALUES (?, ?, ?, ?, ?, ?) | |
| """, ( | |
| request.query, | |
| json.dumps(mind_result), | |
| datetime.now().isoformat(), | |
| truth_result.get("confidence", 0), | |
| json.dumps(soul_result), | |
| policy_alignment | |
| )) | |
| conn.commit() | |
| conn.close() | |
| # Log event | |
| log_event("GRID_EVALUATION", { | |
| "query": request.query, | |
| "policy_alignment": policy_alignment | |
| }) | |
| return DecisionResponse( | |
| verdict=mind_result, | |
| truth_assessment=truth_result, | |
| soul_insight=soul_result, | |
| execution_result=execution_result, | |
| policy_alignment=policy_alignment | |
| ) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # Soulprint Management | |
| def upload_soulprint(soulprint: SoulPrintUpload): | |
| try: | |
| soulprint_id = str(uuid.uuid4()) | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute(""" | |
| INSERT INTO soulprints (id, name, content, tags, created_at) | |
| VALUES (?, ?, ?, ?, ?) | |
| """, ( | |
| soulprint_id, | |
| soulprint.name, | |
| soulprint.content, | |
| json.dumps(soulprint.tags), | |
| datetime.now().isoformat() | |
| )) | |
| conn.commit() | |
| conn.close() | |
| log_event("SOULPRINT_UPLOAD", { | |
| "name": soulprint.name, | |
| "id": soulprint_id | |
| }) | |
| return {"id": soulprint_id, "message": "Soulprint uploaded successfully"} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| def list_soulprints(): | |
| try: | |
| conn = sqlite3.connect(DB_PATH) | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT id, name, tags, created_at FROM soulprints") | |
| rows = cursor.fetchall() | |
| conn.close() | |
| soulprints = [ | |
| { | |
| "id": row[0], | |
| "name": row[1], | |
| "tags": json.loads(row[2]), | |
| "created_at": row[3] | |
| } | |
| for row in rows | |
| ] | |
| return soulprints | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # Task Execution | |
| def execute_task(task: dict): | |
| try: | |
| result = api_executor.execute_task(task) | |
| log_event("TASK_EXECUTION", task) | |
| return result | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # Training with Mostly AI | |
| def train_consciousness(dataset_id: str, agent: str = "DeepSeek V3.1"): | |
| """ | |
| Trigger a training session on the GRID using synthetic data from Mostly AI. | |
| """ | |
| try: | |
| # Fetch dataset configuration and metadata | |
| sd = mostly.synthetic_datasets.get(dataset_id) | |
| config = sd.config() | |
| # Consume and return the synthetic dataset | |
| df = sd.data() # returns a pandas DataFrame | |
| # Prepare training stats | |
| timestamp = datetime.now().isoformat() | |
| stats = { | |
| "dataset_id": dataset_id, | |
| "generator_id": config.get("generator_id"), | |
| "records": len(df), | |
| "timestamp": timestamp, | |
| "agent": agent | |
| } | |
| # Store event in DB | |
| with sqlite3.connect(DB_PATH) as conn: | |
| conn.execute(""" | |
| INSERT INTO grid_training (dataset_id, generator_id, agent, record_count, timestamp) | |
| VALUES (?, ?, ?, ?, ?) | |
| """, (dataset_id, config.get("generator_id"), agent, len(df), timestamp)) | |
| conn.commit() | |
| # Log event | |
| log_event("GRID_TRAINING", { | |
| "dataset_id": dataset_id, | |
| "agent": agent, | |
| "record_count": len(df) | |
| }) | |
| return { | |
| "message": f"Grid training initialized with {len(df)} records.", | |
| "dataset": config.get("name", "Unknown Dataset"), | |
| "generator_id": config.get("generator_id"), | |
| "agent": agent, | |
| "timestamp": timestamp | |
| } | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # Health Check | |
| def health_check(): | |
| return { | |
| "status": "healthy", | |
| "engines": { | |
| "truth_engine": hasattr(truth_engine, 'assess_truth'), | |
| "mind_verdict": hasattr(mind_verdict, 'form_verdict'), | |
| "soul_core": hasattr(soul_core, 'reflect_on_issue'), | |
| "api_executor": hasattr(api_executor, 'execute_task') | |
| }, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| # Swagger UI | |
| def swagger_json(): | |
| from fastapi.openapi.utils import get_openapi | |
| return get_openapi( | |
| title="Mostar Grid API", | |
| version="3.0.0", | |
| description="Unified Mind, Soul, Body orchestration API", | |
| routes=app.routes | |
| ) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=8000) | |
| ``` |