Skip to content

Commit

Permalink
initial release
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanebert committed Nov 27, 2024
0 parents commit 97d7af7
Show file tree
Hide file tree
Showing 23 changed files with 917 additions and 0 deletions.
47 changes: 47 additions & 0 deletions .github/workflows/package-release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Package Release
on:
push:
branches:
- "releases/**"
workflow_dispatch:

jobs:
package-release:
strategy:
matrix:
platform:
- requirements: win-linux-cuda.txt
os: windows-latest
filename: windows-cuda
- requirements: mac-mps-cpu.txt
os: macos-14
filename: macos-arm
runs-on: ${{ matrix.platform.os }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
path: meshgen

- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'

- name: Install dependencies
shell: bash
run: "python -m pip install -r requirements/${{ matrix.platform.requirements }} --no-cache-dir --target .python_dependencies"
working-directory: meshgen

- name: Archive release
uses: thedoctor0/zip-release@main
with:
type: zip
filename: meshgen-${{ matrix.platform.filename }}.zip
exclusions: '*.git*'

- name: Archive and upload artifact
uses: actions/upload-artifact@v4
with:
name: meshgen-${{ matrix.platform.filename }}
path: meshgen-${{ matrix.platform.filename }}.zip
49 changes: 49 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
.DS_Store

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.python_dependencies.zip
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
2 changes: 2 additions & 0 deletions .python_dependencies/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!.gitignore
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Hugging Face

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
45 changes: 45 additions & 0 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
bl_info = {
"name": "MeshGen",
"description": "A Blender addon for generating meshes with AI",
"author": "Hugging Face",
"version": (0, 2, 3),
"blender": (4, 1, 0),
"category": "Mesh",
"support": "COMMUNITY",
"update_url": "https://github.com/huggingface/meshgen",
}


import bpy

from .operators import *
from .panels import *
from .preferences import *
from .property_groups import *

classes = (
MeshGenPreferences,
MeshGenProperties,
MESHGEN_OT_InstallDependencies,
MESHGEN_OT_UninstallDependencies,
MESHGEN_OT_DownloadRequiredModels,
MESHGEN_OT_LoadGenerator,
MESHGEN_OT_GenerateMesh,
MESHGEN_OT_CancelGeneration,
MESHGEN_PT_Panel,
MESHGEN_PT_Settings,
MESHGEN_PT_Warning,
MESHGEN_PT_Setup,
)


def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.meshgen_props = bpy.props.PointerProperty(type=MeshGenProperties)


def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
del bpy.types.Scene.meshgen_props
1 change: 1 addition & 0 deletions generator/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .generator import Generator
125 changes: 125 additions & 0 deletions generator/generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import json
import os
import sys
import traceback
from threading import Lock


from ..operators.install_dependencies import load_dependencies
from ..utils import absolute_path


class Generator:
_instance = None
_lock = Lock()

def __new__(cls):
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = super(Generator, cls).__new__(cls)
cls._instance.initialized = False
return cls._instance

def __init__(self):
if self.initialized:
return
self.required_models = ["Zhengyi/LLaMa-Mesh"]
self.downloaded_models = []
self.dependencies_installed = False
self.dependencies_loaded = False
self.device = "cpu"
self.tokenizer = None
self.pipeline = None
self.terminators = []
self.initialized = True

def _process_model_dir(self, dir_name):
from huggingface_hub.constants import HF_HUB_CACHE

model_dir = os.path.join(HF_HUB_CACHE, dir_name)
if not os.path.isdir(model_dir):
return None
model_name = os.path.basename(model_dir).replace("models--", "").replace("--", "/")
return model_name

def _list_downloaded_models(self):
from huggingface_hub.constants import HF_HUB_CACHE

models = []

if not os.path.exists(HF_HUB_CACHE):
self.downloaded_models = models
return

for dir_name in os.listdir(HF_HUB_CACHE):
model_name = self._process_model_dir(dir_name)
if model_name:
models.append(model_name)

self.downloaded_models = models

def _ensure_dependencies(self):
if not self.dependencies_installed:
self.dependencies_installed = len(os.listdir(absolute_path(".python_dependencies"))) > 2

if self.dependencies_installed and not self.dependencies_loaded:
load_dependencies()
self.dependencies_loaded = True

def has_dependencies(self):
self._ensure_dependencies()
return self.dependencies_installed

def has_required_models(self):
self._list_downloaded_models()
return all(model in self.downloaded_models for model in self.required_models)

def is_generator_loaded(self):
return self.pipeline is not None

def load_generator(self):
print("Loading generator...")

self._ensure_dependencies()

try:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

if torch.cuda.is_available():
self.device = "cuda"
print("Using CUDA")
elif torch.backends.mps.is_available():
self.device = "mps"
print("Using MPS")
else:
print("Running on CPU")

model_path = "Zhengyi/LLaMa-Mesh"
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
self.pipeline = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
).to(self.device)
self.terminators = [
self.tokenizer.eos_token_id,
self.tokenizer.convert_tokens_to_ids("<|eot_id|>")
]

print("Finished loading generator.")

except RuntimeError as e:
if "out of memory" in str(e).lower():
print("Failed to load generator: Insufficient memory.", file=sys.stderr)
else:
print(f"Failed to load generator: {e}", file=sys.stderr)
traceback.print_exc()

except Exception as e:
print(f"Failed to load generator: {e}", file=sys.stderr)
traceback.print_exc()

@classmethod
def instance(cls):
return cls()
4 changes: 4 additions & 0 deletions operators/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from .download_models import MESHGEN_OT_DownloadRequiredModels
from .install_dependencies import MESHGEN_OT_InstallDependencies, MESHGEN_OT_UninstallDependencies
from .load_generator import MESHGEN_OT_LoadGenerator
from .generate_mesh import MESHGEN_OT_GenerateMesh, MESHGEN_OT_CancelGeneration
30 changes: 30 additions & 0 deletions operators/download_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import bpy
import sys

from ..generator.generator import Generator
from ..utils import open_console


class MESHGEN_OT_DownloadRequiredModels(bpy.types.Operator):
bl_idname = "meshgen.download_required_models"
bl_label = "Download Required Models"
bl_options = {"REGISTER", "INTERNAL"}

def execute(self, context):
if sys.platform == "win32":
open_console()

from huggingface_hub import snapshot_download

generator = Generator.instance()
models_to_download = [model for model in generator.required_models if model not in generator.downloaded_models]

if not models_to_download:
print("All required models are already downloaded.")
return

for model in models_to_download:
print(f"Downloading model: {model}")
snapshot_download(model)
generator._list_downloaded_models()
return {"FINISHED"}
Loading

0 comments on commit 97d7af7

Please sign in to comment.