"""MVPKILLCADDSS — FastAPI Backend""" from fastapi import FastAPI, HTTPException, Depends, UploadFile, File from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from pydantic import BaseModel from typing import Optional import httpx import os import re import json from datetime import datetime import sys import asyncio import time sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "ai_prompts")) from prompt_tokens import prompt_token_matrix, category_descriptions, platform_to_domain from model_manager import model_manager from dsl_parser import parse_dsl_to_mesh app = FastAPI(title="MVPKILLCADDSS", version="0.3.0") @app.on_event("startup") async def startup(): asyncio.create_task(model_manager.health_check_loop()) # CORS — allow frontend (any origin in dev) app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) # ── Config ────────────────────────────────────────────── SUPABASE_URL = os.getenv("SUPABASE_URL", "") SUPABASE_KEY = os.getenv("SUPABASE_SERVICE_KEY", "") HF_TOKEN = os.getenv("HF_TOKEN", "") OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434") AI_PROMPTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ai_prompts") if not os.path.exists(AI_PROMPTS_DIR): AI_PROMPTS_DIR = "/home/mart/dsafd/backend/ai_prompts" # ── Load AI Prompt Files ──────────────────────────────── def load_prompt_file(filename: str) -> str: path = os.path.join(AI_PROMPTS_DIR, filename) if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: return f.read() print(f"WARNING: Prompt file not found: {path}") return "" SYSTEM_PROMPT_FULL = load_prompt_file("system_prompt.txt") DOMAIN_KEYWORDS_RAW = load_prompt_file("domain_keywords.txt") # ── Parse Domain Keywords ─────────────────────────────── def parse_domain_keywords() -> dict[str, dict[str, str]]: """Returns {domain: {keyword: dsl_pattern}}""" domains = {} current_domain = None for line in DOMAIN_KEYWORDS_RAW.split("\n"): line = line.strip() if not line or line.startswith("#"): continue if line.startswith("[") and line.endswith("]"): current_domain = line[1:-1] domains[current_domain] = {} continue if current_domain and "|" in line: parts = line.split("|", 1) keyword = parts[0].strip().lower() pattern = parts[1].strip() if len(parts) > 1 else "" if keyword: domains[current_domain][keyword] = pattern return domains DOMAIN_KEYWORDS = parse_domain_keywords() # ── Domain Detection ──────────────────────────────────── def detect_domains(text: str) -> list[str]: """Detect domains from text using keyword matching. Multi-domain: returns ALL matching domains (not just one).""" lower = text.lower() matched = set() for domain, keywords in DOMAIN_KEYWORDS.items(): if domain == "altalanos": continue # always included as fallback for kw in keywords: if kw in lower: matched.add(domain) break # one keyword match per domain is enough # Always include altalanos as base domains = list(matched) if not domains: domains = ["altalanos"] else: domains.insert(0, "altalanos") return domains def get_domain_names(domains: list[str]) -> list[str]: """Map domain keys to display names""" name_map = { "altalanos": "🔧 General", "banyagepek": "🏗️ Mining", "jatek": "🎮 Game Dev", "film": "🎬 Film/VFX", "uripar": "🚀 Aerospace", } return [name_map.get(d, d) for d in domains] # ── System prompts by domain ─────────────────────────── def get_domain_prompt(domain: str) -> str: prompts = { "altalanos": "You are a CAD modeling AI. Convert text descriptions into DSAFD DSL code. Focus on standard mechanical parts: bolts, bearings, gears, springs, plates, hinges, clamps. Use primitives (box, cylinder, sphere, cone, torus) and operations (subtract for holes, fillet for edges, shell for hollow parts). Units: millimeters (mm). Respond ONLY with the DSL code, nothing else.", "banyagepek": "You are a heavy machinery CAD expert for mining equipment. Convert descriptions into DSAFD DSL code. Focus on: gears, hydraulics, pistons, chains, tracks, buckets, excavator booms, crushers, conveyors, drill bits. Use robust thick-walled designs with shell() for structural parts. Units: millimeters. Respond ONLY with the DSL code.", "jatek": "You are a game asset 3D artist. Convert descriptions into DSAFD DSL code for LOW-POLY game-ready assets. Minimize vertex count — use box primitives wherever possible instead of cylinders. Avoid fillet and chamfer unless essential. Focus on: weapons, characters, props, terrain, buildings. Units: generic. Respond ONLY with the DSL code.", "film": "You are a VFX/Cinematic 3D artist. Convert descriptions into DSAFD DSL code for HIGH-POLY cinematic models. Use fillet, chamfer, and shell extensively for realistic detail. Focus on: vehicles, spaceships, robots, monsters, architecture, explosions. Units: millimeters. Respond ONLY with the DSL code.", "uripar": "You are an aerospace engineer. Convert descriptions into DSAFD DSL code for aerospace-grade precision parts with TIGHT TOLERANCES (0.01mm). Use minimal fillet to preserve precision. Focus on: satellites, rockets, turbines, nozzles, heat shields, landers, space stations. Units: millimeters. Respond ONLY with the DSL code.", } return prompts.get(domain, prompts["altalanos"]) def build_combined_prompt(domains: list[str], user_text: str) -> str: """Build a combined system prompt for multiple domains""" domain_descriptions = [] for d in domains: domain_descriptions.append(get_domain_prompt(d)) if len(domains) > 1: intro = f"You are a CAD modeling AI with combined expertise in: {', '.join(get_domain_names(domains))}. " intro += "The user's request involves elements from multiple domains. " intro += "Blend the approaches from each domain into a unified DSL model. " intro += "Use the DSAFD DSL syntax as follows:\n\n" else: intro = "" return intro + "\n\n---\n\n".join(domain_descriptions) + "\n\n" + SYSTEM_PROMPT_FULL + f"\n\nUser request: {user_text}\n\nGenerate DSL:" # ── Models ────────────────────────────────────────────── class GenerateRequest(BaseModel): prompt: str package_type: str = "altalanos" resolution: str = "medium" class ChatRequest(BaseModel): message: str history: list[dict] = [] # [{role: "user"|"ai", content: str}] use_hf: bool = True use_ollama: bool = True class ChatResponse(BaseModel): ai_response: str dsl_code: str | None = None model_name: str = "" domains: list[str] = [] domain_names: list[str] = [] mesh_data: dict | None = None class ExportRequest(BaseModel): model_name: str format: str # stl | obj | gltf positions: list[float] = [] indices: list[int] = [] class CreditInfo(BaseModel): user_id: str credits: int class PackageInfo(BaseModel): key: str name: str description: str price_credits: int class ForumModel(BaseModel): name: str prompt: str dsl_code: str package_type: str = "altalanos" is_public: bool = True vertex_count: int = 0 sdf_weights: list[float] = [] clifford_rotors: list[float] = [] class SettingsRequest(BaseModel): use_hf: bool = True use_ollama: bool = True # ── AI: Keyword fallback ──────────────────────────────── def keyword_generate(prompt: str) -> dict: lower = prompt.lower() name = re.sub(r"[^a-zA-Z0-9]", "_", prompt[:20]) or "model" dsl = f'model "{name}" {{\n' has_primitive = False # Standard shape keywords if any(w in lower for w in ["cube","box","kocka","téglatest","plate","panel","enclosure","chassis","crate","chest","wall","frame","bracket","flange","fixture","clamp","housing"]): dsl += " primitive box(center: [0, 0, 0], size: [10, 10, 10])\n"; has_primitive = True if any(w in lower for w in ["sphere","ball","gömb","helmet","hel","visor","skull","creature","head","dome","mask"]): dsl += " primitive sphere(center: [0, 0, 10], radius: 12)\n"; has_primitive = True if any(w in lower for w in ["cylinder","bolt","csavar","henger","pipe","tube","shaft","piston","barrel","nozzle","pin","plug","rivet","rod","pillar","tower"]): dsl += " primitive cylinder(center: [0, 0, 0], radius: 3, height: 15)\n"; has_primitive = True if any(w in lower for w in ["cone","rocket","nose","spike","drill","bit"]): dsl += " primitive cone(center: [0, 0, 0], radius_bottom: 5, height: 10)\n"; has_primitive = True if any(w in lower for w in ["torus","ring","bearing","seal","washer","donut","tire","wheel","rim"]): dsl += " primitive torus(center: [0, 0, 0], major_radius: 10, minor_radius: 2)\n"; has_primitive = True if any(w in lower for w in ["gear","fogaskerék","sprocket","pinion","cog"]): dsl += " component gear_teeth { primitive extrude(profile: gear_profile, height: 2) }\n"; has_primitive = True if any(w in lower for w in ["thread","menet","screw","spiral","coil","helix"]): dsl += " component screw_thread { primitive helixe(pitch: 1.25, depth: 1, length: 20) }\n"; has_primitive = True # CAD token matrix fallback (subjects) cad_subjects = ["arm","pump","generator","armor","rifle","drone","turbine","engine","reactor","chamber","cockpit","rover","exoskeleton","hand","sword","dagger","axe","hammer","shield","bow","arrow","key","potion","coin","chest","door","window","stairs","tower","fortress","castle"] for s in cad_subjects: if s in lower and not has_primitive: dsl += " primitive box(center: [0, 0, 0], size: [10, 10, 10])\n"; has_primitive = True; break # Default fallback: at least ONE primitive if not has_primitive: dsl += " primitive sphere(center: [0, 0, 0], radius: 5)\n" dsl += "}\n" return {"dsl": dsl, "model_name": name, "raw_response": "[keyword fallback]"} # ═══════════════ ENDPOINTS ═══════════════════════════════ @app.get("/api/health") async def health(): return {"status": "ok", "version": "0.3.0"} # ── Model Farm Endpoints ──────────────────────────────── @app.get("/api/models") async def get_models(): return model_manager.get_status() @app.get("/api/models/status") async def get_models_status(): return model_manager.get_status() @app.get("/api/models/stats") async def get_models_stats(): return model_manager.get_stats() @app.get("/api/tokens") async def get_tokens(): """Return the prompt token matrix for intellisense/autocomplete""" return { "token_matrix": prompt_token_matrix, "category_descriptions": category_descriptions, } @app.get("/api/prompts") async def get_prompts(): return { "system_prompt": SYSTEM_PROMPT_FULL[:2000] + "...", "domains_available": list(DOMAIN_KEYWORDS.keys()), "keyword_count": sum(len(v) for v in DOMAIN_KEYWORDS.values()), } # ── Domain Detection ──────────────────────────────────── @app.post("/api/domains/detect") async def detect_domains_endpoint(req: ChatRequest): domains = detect_domains(req.message) return { "domains": domains, "domain_names": get_domain_names(domains), "matched_keywords": count_matched_keywords(req.message, domains), } def count_matched_keywords(text: str, domains: list[str]) -> dict: lower = text.lower() result = {} for d in domains: if d in DOMAIN_KEYWORDS: matched = [kw for kw in DOMAIN_KEYWORDS[d] if kw in lower] result[d] = len(matched) return result # ── AI Generate (legacy) ──────────────────────────────── @app.post("/api/generate") async def generate(req: GenerateRequest): """Generate DSL from text prompt via HuggingFace or Ollama""" if not req.prompt.strip(): raise HTTPException(400, "Prompt is required") domains = detect_domains(req.prompt) full_prompt = build_combined_prompt(domains, req.prompt) # Try HuggingFace if HF_TOKEN: try: async with httpx.AsyncClient(timeout=30) as client: resp = await client.post( "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2", headers={"Authorization": f"Bearer {HF_TOKEN}"}, json={"inputs": full_prompt, "parameters": {"max_new_tokens": 512, "temperature": 0.7, "return_full_text": False}}, ) if resp.status_code == 200: data = resp.json() raw = data[0].get("generated_text", "") if isinstance(data, list) else "" return {**parse_dsl(raw, req.prompt), "domains": domains, "domain_names": get_domain_names(domains)} except Exception as e: print(f"HF error: {e}") # Try Ollama try: async with httpx.AsyncClient(timeout=60) as client: resp = await client.post( f"{OLLAMA_URL}/api/generate", json={"model": "mistral:7b", "prompt": full_prompt, "stream": False, "options": {"temperature": 0.7, "num_predict": 512}}, ) if resp.status_code == 200: raw = resp.json().get("response", "") return {**parse_dsl(raw, req.prompt), "domains": domains, "domain_names": get_domain_names(domains)} except Exception as e: print(f"Ollama error: {e}") # Fallback return {**keyword_generate(req.prompt), "domains": domains, "domain_names": get_domain_names(domains)} # ── Chat Endpoint ─────────────────────────────────────── @app.post("/api/chat") async def chat(req: ChatRequest): """Intelligent chat with multi-domain detection and mesh generation""" if not req.message.strip(): raise HTTPException(400, "Message is required") # Detect domains domains = detect_domains(req.message) domain_names = get_domain_names(domains) # Build context from history context = "" for h in req.history[-10:]: # last 10 messages role = "User" if h.get("role") == "user" else "AI" context += f"{role}: {h.get('content', '')}\n" full_prompt = build_combined_prompt(domains, req.message) if context: full_prompt = f"Previous conversation:\n{context}\n---\n{full_prompt}" ai_response = "" dsl_code = "" raw_response = "" # Try Model Farm first (3 HF Space models) model_id, model_info = model_manager.select_model(domains) if model_id and req.use_hf: result = await model_manager.chat_with_model(model_id, req.message, req.history) if result and not result.get("error"): raw_response = result.get("response", "") # Try direct HuggingFace if not raw_response and req.use_hf and HF_TOKEN: try: async with httpx.AsyncClient(timeout=60) as client: resp = await client.post( "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3", headers={"Authorization": f"Bearer {HF_TOKEN}"}, json={"inputs": full_prompt, "parameters": {"max_new_tokens": 512, "temperature": 0.7, "return_full_text": False}}, ) if resp.status_code == 200: data = resp.json() raw_response = data[0].get("generated_text", "") if isinstance(data, list) else "" except Exception as e: print(f"HF chat error: {e}") # Try Ollama if not raw_response and req.use_ollama: try: async with httpx.AsyncClient(timeout=90) as client: resp = await client.post( f"{OLLAMA_URL}/api/generate", json={"model": "mistral:7b", "prompt": full_prompt, "stream": False, "options": {"temperature": 0.7, "num_predict": 512}}, ) if resp.status_code == 200: raw_response = resp.json().get("response", "") except Exception as e: print(f"Ollama chat error: {e}") # Fallback if not raw_response: kw = keyword_generate(req.message) dsl_code = kw["dsl"] ai_response = f"[Keyword fallback] I generated this {', '.join(domain_names)} model based on: '{req.message}'\n\n```dsl\n{dsl_code}\n```" else: parsed = parse_dsl(raw_response, req.message) dsl_code = parsed["dsl"] ai_response = raw_response.strip() if dsl_code and dsl_code not in ai_response: ai_response += f"\n\n```dsl\n{dsl_code}\n```" # Generate mesh data model_name = parse_dsl(raw_response, req.message).get("model_name", "model") if raw_response else keyword_generate(req.message)["model_name"] mesh_data = parse_dsl_to_mesh(dsl_code or "") return ChatResponse( ai_response=ai_response, dsl_code=dsl_code, model_name=model_name, domains=domains, domain_names=domain_names, mesh_data=mesh_data, ) # ── Mesh Generate ─────────────────────────────────────── @app.post("/api/mesh/generate") async def mesh_generate(req: ChatRequest): """Generate mesh from DSL code or text prompt""" if not req.message.strip(): raise HTTPException(400, "Message is required") # If the message looks like DSL code, parse it directly if "model " in req.message and "{" in req.message: dsl_code = req.message else: # Generate DSL first gen_result = await generate(GenerateRequest(prompt=req.message)) dsl_code = gen_result.get("dsl", "") mesh_data = parse_dsl_to_mesh(dsl_code) return {"mesh": mesh_data, "dsl": dsl_code} # ── Forum Endpoints ───────────────────────────────────── forum_store: list[dict] = [] # in-memory store (localStorage-compatible) @app.get("/api/forum") async def get_forum_models(search: str = "", domain: str = ""): """Get public forum models""" results = forum_store if search: q = search.lower() results = [m for m in results if q in m["name"].lower() or q in m["prompt"].lower()] if domain: results = [m for m in results if domain in m.get("domains", [])] return list(reversed(results[-50:])) # last 50, newest first @app.post("/api/forum") async def publish_forum_model(req: ForumModel): """Publish a model to the forum""" entry = { **req.model_dump(), "id": f"forum_{datetime.utcnow().timestamp()}", "created_at": datetime.utcnow().isoformat(), "downloads": 0, } forum_store.append(entry) return {"status": "published", "id": entry["id"]} # ── Legacy endpoints ──────────────────────────────────── def parse_dsl(raw: str, prompt: str) -> dict: name = re.sub(r"[^a-zA-Z0-9]", "_", prompt[:20]) or "model" m = re.search(r'model\s+"[^"]*"\s*\{[\s\S]*?\}', raw) dsl = m.group(0) if m else raw return {"dsl": dsl, "model_name": name, "raw_response": raw} @app.post("/api/export/stl") async def export_stl(req: ExportRequest): """Generate binary STL file""" if not req.indices or not req.positions: raise HTTPException(400, "Mesh data required") tri = len(req.indices) // 3 buf = bytearray(84 + tri * 50) name = req.model_name[:79].encode() buf[:len(name)] = name import struct struct.pack_into("