modly-image-to-3d

modly-image-to-3d

完全在本地 GPU 上執行 AI 模型,將圖片轉換為 3D 模型的桌面應用程式

78星標
13分支
更新於 2026/7/9
SKILL.md
唯讀
名稱
modly-image-to-3d
描述

完全在本地 GPU 上執行 AI 模型,將圖片轉換為 3D 模型的桌面應用程式

Modly 圖片轉 3D Skill

Skill 由 ara.so 提供 — Daily 2026 Skills 系列。

Modly 是一款開放原始碼的本地桌面應用程式(支援 Windows/Linux),能夠運用完全在您 GPU 上執行的 AI 模型將相片轉換為 3D 網格模型 — 無需雲端服務,也不需要 API 金鑰。


架構概觀

modly/
├── src/                    # Electron + TypeScript 前端
│   ├── main/               # Electron 主程序 (Main process)
│   ├── renderer/           # React UI (渲染程序 Renderer process)
│   └── preload/            # IPC 橋接層
├── api/                    # Python FastAPI 後端
│   ├── generator.py        # 核心生成邏輯
│   └── requirements.txt
├── resources/
│   └── icons/
├── launcher.bat            # Windows 快速啟動檔
├── launcher.sh             # Linux 快速啟動檔
└── package.json

本應用程式採用 Electron 外殼包裹本地的 Python FastAPI 伺服器運作。擴充功能(Extensions)是包含 manifest.json 與 generator.py 的 GitHub 儲存庫,可直接套入擴充功能系統中。


安裝指南

快速啟動(無需編譯)

# Windows
launcher.bat

# Linux
chmod +x launcher.sh
./launcher.sh

開發環境建置

# 1. 克隆儲存庫
git clone https://github.com/lightningpixel/modly
cd modly

# 2. 安裝 JS 依賴套件
npm install

# 3. 建置 Python 後端
cd api
python -m venv .venv

# 啟用虛擬環境 (Windows)
.venv\Scripts\activate

# 啟用虛擬環境 (Linux/macOS)
source .venv/bin/activate

pip install -r requirements.txt
cd ..

# 4. 啟動開發模式(同時啟動 Electron 與 Python 後端)
npm run dev

生產環境打包

# 為當前作業系統平台建立安裝程式
npm run build

# 輸出檔案將位於 dist/

主要 npm 指令

npm run dev        # 以開發模式啟動應用程式(支援熱重載 Hot reload)
npm run build      # 打包應用程式以供分發
npm run lint       # 執行 ESLint 檢查
npm run typecheck  # 執行 TypeScript 型態檢查

擴充功能系統

擴充功能是包含以下檔案的 GitHub 儲存庫:

  • manifest.json — 中繼資料與模型變體(Variants)說明
  • generator.py — 實作 Modly 擴充功能介面的生成邏輯

manifest.json 結構

{
  "name": "My 3D Extension",
  "id": "my-extension-id",
  "description": "Generates 3D models using XYZ model",
  "version": "1.0.0",
  "author": "Your Name",
  "repository": "https://github.com/yourname/my-modly-extension",
  "variants": [
    {
      "id": "model-small",
      "name": "Small (faster)",
      "description": "Lighter variant for faster generation",
      "size_gb": 4.2,
      "vram_gb": 6,
      "files": [
        {
          "url": "https://huggingface.co/yourorg/yourmodel/resolve/main/weights.safetensors",
          "filename": "weights.safetensors",
          "sha256": "abc123..."
        }
      ]
    }
  ]
}

generator.py 介面

# api/extensions/<extension-id>/generator.py
# 每個擴充功能都必須實作的必要介面

import sys
import json
from pathlib import Path

def generate(
    image_path: str,
    output_path: str,
    variant_id: str,
    models_dir: str,
    **kwargs
) -> dict:
    """
    所有 Modly 擴充功能的必要進入點。
    
    引數:
        image_path:  輸入圖片檔案的路徑
        output_path: 輸出的 .glb/.obj 儲存路徑
        variant_id:  要使用的模型變體 ID
        models_dir:  已下載模型權重存放的目錄
    
    回傳值:
        包含以下鍵值的 dict:
            success (bool)
            output_file (str) — 生成網格的路徑
            error (str, 選填)
    """
    try:
        # 載入模型權重
        weights = Path(models_dir) / variant_id / "weights.safetensors"
        
        # 執行推論
        mesh = run_inference(str(weights), image_path)
        
        # 匯出結果
        mesh.export(output_path)
        
        return {
            "success": True,
            "output_file": output_path
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }

安裝擴充功能(介面操作流程)

  1. 開啟 Modly → 切換至 Models 頁面
  2. 點擊 Install from GitHub
  3. 貼上 HTTPS 網址,例如 https://github.com/lightningpixel/modly-hunyuan3d-mini-extension
  4. 安裝完成後,在所需的模型變體上點擊 Download
  5. 選擇已安裝的模型並上傳圖片即可開始生成

官方擴充功能

擴充功能 模型
modly-hunyuan3d-mini-extension Hunyuan3D 2 Mini

Python 後端 API (FastAPI)

後端於本地端執行。Electron 前端使用的主要端點如下:

# 常見的後端路由模式 (api/main.py 或類似檔案)

# GET /extensions         — 列出已安裝的擴充功能
# GET /extensions/{id}    — 取得擴充功能詳細資訊與變體
# POST /extensions/install — 從 GitHub 網址安裝擴充功能
# POST /generate          — 觸發 3D 模型生成
# GET /generate/status    — 輪詢生成進度
# GET /models             — 列出已下載的模型變體
# POST /models/download   — 下載指定的模型變體

從 Electron 呼叫後端(IPC 模式)

// src/preload/index.ts — 將後端呼叫暴露給渲染程序
import { contextBridge, ipcRenderer } from 'electron'

contextBridge.exposeInMainWorld('modly', {
  generate: (imagePath: string, extensionId: string, variantId: string) =>
    ipcRenderer.invoke('generate', { imagePath, extensionId, variantId }),

  installExtension: (repoUrl: string) =>
    ipcRenderer.invoke('install-extension', { repoUrl }),

  listExtensions: () =>
    ipcRenderer.invoke('list-extensions'),
})
// src/main/ipc-handlers.ts — 主程序處理
import { ipcMain } from 'electron'

ipcMain.handle('generate', async (_event, { imagePath, extensionId, variantId }) => {
  const response = await fetch('http://localhost:PORT/generate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ image_path: imagePath, extension_id: extensionId, variant_id: variantId }),
  })
  return response.json()
})
// src/renderer/components/GenerateButton.tsx — UI 元件使用範例
declare global {
  interface Window {
    modly: {
      generate: (imagePath: string, extensionId: string, variantId: string) => Promise<{ success: boolean; output_file?: string; error?: string }>
      installExtension: (repoUrl: string) => Promise<{ success: boolean }>
      listExtensions: () => Promise<Extension[]>
    }
  }
}

async function handleGenerate(imagePath: string) {
  const result = await window.modly.generate(
    imagePath,
    'modly-hunyuan3d-mini-extension',
    'hunyuan3d-mini-turbo'
  )

  if (result.success) {
    console.log('Mesh saved to:', result.output_file)
  } else {
    console.error('Generation failed:', result.error)
  }
}

撰寫自訂擴充功能

最小擴充功能儲存庫結構

my-modly-extension/
├── manifest.json
└── generator.py

範例:封裝 HuggingFace 擴散模型

# generator.py
import torch
from PIL import Image
from pathlib import Path

def generate(image_path, output_path, variant_id, models_dir, **kwargs):
    device = "cuda" if torch.cuda.is_available() else "cpu"
    weights_dir = Path(models_dir) / variant_id

    try:
        # 載入模型(範例模式)
        from your_model_lib import ImageTo3DPipeline
        
        pipe = ImageTo3DPipeline.from_pretrained(
            str(weights_dir),
            torch_dtype=torch.float16
        ).to(device)

        image = Image.open(image_path).convert("RGB")
        
        with torch.no_grad():
            mesh = pipe(image).mesh

        mesh.export(output_path)

        return {"success": True, "output_file": output_path}

    except Exception as e:
        return {"success": False, "error": str(e)}

設定與環境

Modly 完全在本地執行 — 無需設定環境變數或 API 金鑰。擴充功能中的 PyTorch 會自動偵測 GPU/CUDA。

相關設定檔包含:

package.json          # Electron 應用程式中繼資料、打包目標
api/requirements.txt  # 後端 Python 依賴套件

若需要設定後端埠號或擴充功能目錄,請查看 Electron 主程序設定檔(通常為 src/main/index.ts)中的 API_PORT 或 EXTENSIONS_DIR 等常數。


常見模式

在擴充功能中檢查 CUDA 是否可用

import torch

def get_device():
    if torch.cuda.is_available():
        print(f"Using GPU: {torch.cuda.get_device_name(0)}")
        return "cuda"
    print("No GPU found, falling back to CPU (slow)")
    return "cpu"

從 generator.py 回報進度

import sys
import json

def report_progress(percent: int, message: str):
    """將進度寫入 stdout,以便 Modly 讀取並顯示。"""
    print(json.dumps({"progress": percent, "message": message}), flush=True)

def generate(image_path, output_path, variant_id, models_dir, **kwargs):
    report_progress(0, "Loading model...")
    # ... 載入模型 ...
    report_progress(30, "Processing image...")
    # ... 執行推論 ...
    report_progress(90, "Exporting mesh...")
    # ... 匯出網格 ...
    report_progress(100, "Done")
    return {"success": True, "output_file": output_path}

在渲染程序 (React) 中新增頁面

// src/renderer/pages/MyPage.tsx
import React, { useEffect, useState } from 'react'

interface Extension {
  id: string
  name: string
  description: string
}

export default function MyPage() {
  const [extensions, setExtensions] = useState<Extension[]>([])

  useEffect(() => {
    window.modly.listExtensions().then(setExtensions)
  }, [])

  return (
    <div>
      <h1>Installed Extensions</h1>
      {extensions.map(ext => (
        <div key={ext.id}>
          <h2>{ext.name}</h2>
          <p>{ext.description}</p>
        </div>
      ))}
    </div>
  )
}

疑難排解

問題 解決方式
npm run dev — Python 後端未啟動 請確認已建立虛擬環境:cd api && python -m venv .venv && pip install -r requirements.txt
CUDA 記憶體不足 (Out of memory) 使用較小的模型變體,或關閉其他佔用 GPU 的程式
擴充功能安裝失敗 確認 GitHub 網址為 HTTPS,且儲存庫根目錄包含 manifest.json
生成過程卡住 檢查 GPU 驅動程式與 CUDA Toolkit 版本是否與 requirements.txt 中的 PyTorch 相符
在 Linux 上無法啟動應用程式 請將 launcher.sh 設定為可執行檔:chmod +x launcher.sh
模型下載中斷或卡住 檢查硬碟空間;大型模型(4–10 GB)需要足夠的剩餘空間
擴充功能提示找不到 torch 請確保 PyTorch 已寫入 api/requirements.txt,而非僅放在擴充功能本身的依賴中

驗證是否正確偵測到 GPU

cd api
source .venv/bin/activate   # Windows 請使用 .venv\Scripts\activate
python -c "import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'no GPU')"

相關資源