Compare commits

..

3 Commits

Author SHA1 Message Date
7a43e5da08 auto-git:
[change] .gitignore
2026-05-14 10:24:34 +02:00
68b083a6c4 auto-git:
[add] README.md
2026-05-14 10:24:20 +02:00
56745a1679 auto-git:
[add] .gitignore
2026-05-14 10:24:09 +02:00
6 changed files with 96 additions and 227 deletions

4
.gitignore vendored
View File

@@ -35,8 +35,6 @@ web/output/
PyWebview/web/output/
.hf_cache/
*.log
build/
dist/
# Generated media and 3D assets
*.png
@@ -52,8 +50,6 @@ dist/
*.mov
*.zip
*.tar.gz
!icon.png
!icon.icns
# Local model weights
*.safetensors

View File

@@ -1,121 +0,0 @@
# -*- mode: python ; coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_data_files
from PyInstaller.utils.hooks import collect_submodules
from PyInstaller.utils.hooks import copy_metadata
datas = [('web/index.html', 'web'), ('icon.png', '.'), ('scene_setup.py', '.')]
hiddenimports = [
'image_to_3d',
'generate_equirect',
'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion',
'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint',
'diffusers.pipelines.stable_diffusion.pipeline_output',
'diffusers.models.autoencoders.autoencoder_kl',
'diffusers.models.autoencoders.vae',
'diffusers.models.unets.unet_2d_condition',
'diffusers.models.unets.unet_2d_blocks',
'diffusers.schedulers.scheduling_ddim',
'diffusers.schedulers.scheduling_ddpm',
'diffusers.schedulers.scheduling_dpmsolver_multistep',
'diffusers.schedulers.scheduling_euler_discrete',
'diffusers.schedulers.scheduling_lms_discrete',
'diffusers.schedulers.scheduling_pndm',
'transformers.models.auto.configuration_auto',
'transformers.models.auto.feature_extraction_auto',
'transformers.models.auto.image_processing_auto',
'transformers.models.auto.modeling_auto',
'transformers.models.auto.tokenization_auto',
'transformers.models.clip.configuration_clip',
'transformers.models.clip.image_processing_clip',
'transformers.models.clip.modeling_clip',
'transformers.models.clip.processing_clip',
'transformers.models.clip.tokenization_clip',
'transformers.models.clip.tokenization_clip_fast',
'safetensors.torch',
]
datas += collect_data_files('diffusers')
datas += collect_data_files('transformers')
datas += collect_data_files('huggingface_hub')
datas += copy_metadata('replicate')
hiddenimports += collect_submodules(
'diffusers.schedulers',
filter=lambda name: '.scheduling_' in name and '_flax' not in name,
)
a = Analysis(
['main.py'],
pathex=[],
binaries=[],
datas=datas,
hiddenimports=hiddenimports,
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[
'gi',
'PyQt5',
'PyQt6',
'PySide2',
'PySide6',
'tkinter',
'altair',
'cv2',
'datasets',
'flax',
'jax',
'jaxlib',
'librosa',
'llvmlite',
'matplotlib',
'nltk',
'numba',
'onnx',
'onnxruntime',
'pandas',
'pygame',
'sklearn',
'soundfile',
'spacy',
'tensorflow',
'torchaudio',
'torchvision',
],
noarchive=False,
optimize=0,
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name='3D Model Generator',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=['icon.icns'],
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='3D Model Generator',
)
app = BUNDLE(
coll,
name='3D Model Generator.app',
icon='icon.icns',
bundle_identifier=None,
)

View File

@@ -34,13 +34,23 @@ def unshift_image(img: Image.Image, shift: int) -> Image.Image:
out.paste(img.crop((0, 0, w - shift, h)), (shift, 0))
return out
def generate_equirect(prompt: str, output: str, work_dir: str | None = None) -> str | None:
def main():
parser = argparse.ArgumentParser(
description="Generate an equirectangular HDRI, make it seamless, and upscale it with Topaz Photo AI CLI."
)
parser.add_argument("--prompt", required=True,
help="Text prompt for generation and inpainting")
parser.add_argument("--output", required=True,
help="Filename for the final upscaled image (e.g. seamless.png)")
parser.add_argument("--work-dir", default=os.path.dirname(os.path.abspath(__file__)),
help="Working directory for intermediates and final outputs")
args = parser.parse_args()
# Output-Ordner (bleibt wie gehabt)
output_abs = os.path.abspath(output)
work_dir = work_dir or os.path.dirname(os.path.abspath(__file__))
output_abs = os.path.abspath(args.output)
# Zwischenschritte landen im eigenem temp-Ordner:
with tempfile.TemporaryDirectory(dir=work_dir) as tempdir:
with tempfile.TemporaryDirectory(dir=args.work_dir) as tempdir:
print(f"→ Using tempdir: {tempdir}")
model_path = "/Volumes/SD/ML-Models/diffusers/hdri-panorama-v1-diffusers"
@@ -66,7 +76,7 @@ def generate_equirect(prompt: str, output: str, work_dir: str | None = None) ->
print("→ Generating equirectangular HDRI…")
image = gen_pipe(
prompt=prompt,
prompt=args.prompt,
num_inference_steps=steps,
guidance_scale=scale-1.5,
width=width,
@@ -92,7 +102,7 @@ def generate_equirect(prompt: str, output: str, work_dir: str | None = None) ->
print("→ Inpainting seam for seamless tiling…")
inpainted = inpaint_pipe(
prompt=prompt,
prompt=args.prompt,
image=shifted,
mask_image=mask,
num_inference_steps=steps,
@@ -101,7 +111,7 @@ def generate_equirect(prompt: str, output: str, work_dir: str | None = None) ->
height=height
).images[0]
seamless_path = os.path.join(tempdir, os.path.basename(output_abs))
seamless_path = os.path.join(tempdir, os.path.basename(args.output))
inpainted = unshift_image(inpainted, shift_amt)
inpainted.save(seamless_path)
print(f"→ Crafted seamless image: {seamless_path}")
@@ -122,26 +132,11 @@ def generate_equirect(prompt: str, output: str, work_dir: str | None = None) ->
)
if not upscaled_files:
print("→ No PNG output found in tempdir after Topaz run!")
return None
return
upscaled = upscaled_files[0]
shutil.move(upscaled, output_abs)
print(f"→ Upscaled image moved to {output_abs}")
return output_abs
def main():
parser = argparse.ArgumentParser(
description="Generate an equirectangular HDRI, make it seamless, and upscale it with Topaz Photo AI CLI."
)
parser.add_argument("--prompt", required=True,
help="Text prompt for generation and inpainting")
parser.add_argument("--output", required=True,
help="Filename for the final upscaled image (e.g. seamless.png)")
parser.add_argument("--work-dir", default=os.path.dirname(os.path.abspath(__file__)),
help="Working directory for intermediates and final outputs")
args = parser.parse_args()
generate_equirect(args.prompt, args.output, args.work_dir)
if __name__ == "__main__":
main()
main()

BIN
icon.icns

Binary file not shown.

BIN
icon.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 961 KiB

155
main.py
View File

@@ -1,22 +1,5 @@
import os
import sys
import multiprocessing
if __name__ == "__main__":
multiprocessing.freeze_support()
EARLY_IS_FROZEN = getattr(sys, "frozen", False)
EARLY_BASE_DIR = os.path.dirname(sys.executable) if EARLY_IS_FROZEN else os.path.dirname(os.path.abspath(__file__))
EARLY_APP_SUPPORT_DIR = os.path.join(
os.path.expanduser("~"),
"Library",
"Application Support",
"3d-model-generator",
)
EARLY_HF_HOME = os.path.join(EARLY_APP_SUPPORT_DIR if EARLY_IS_FROZEN else EARLY_BASE_DIR, ".hf_cache")
os.environ.setdefault("HF_HOME", EARLY_HF_HOME)
os.environ.setdefault("HUGGINGFACE_HUB_CACHE", os.path.join(EARLY_HF_HOME, "hub"))
import json
import re
import requests
@@ -28,7 +11,6 @@ import webview
import random
import subprocess
import concurrent.futures
import shutil
from PIL import Image, PngImagePlugin
from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
import torch
@@ -42,43 +24,22 @@ MODEL = "mistral:latest" # or "mistral-small3.1:24b"
# Path to your diffusers-converted model
MODEL_PATH = "/Volumes/SD/ML-Models/diffusers/dreamshaper_8_diffusers"
IS_FROZEN = getattr(sys, "frozen", False)
BASE_DIR = os.path.dirname(sys.executable) if IS_FROZEN else os.path.dirname(os.path.abspath(__file__))
BUNDLE_DIR = getattr(sys, "_MEIPASS", BASE_DIR)
APP_SUPPORT_DIR = EARLY_APP_SUPPORT_DIR
# Where to save generated images
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# ────────────────────────────────────────────────────────────────────────────
# Store everything under web/output instead of project_root/output
WEB_DIR = os.path.join(BASE_DIR, "web")
OUTPUT_DIR = os.path.join(WEB_DIR, "output")
os.makedirs(OUTPUT_DIR, exist_ok=True)
APP_SUPPORT_DIR = os.path.join(
os.path.expanduser("~"),
"Library",
"Application Support",
"3d-model-generator",
)
SETTINGS_PATH = os.path.join(APP_SUPPORT_DIR, "settings.json")
# ────────────────────────────────────────────────────────────────────────────
def resource_path(*parts: str) -> str:
return os.path.join(BUNDLE_DIR, *parts)
def prepare_web_dir() -> str:
if not IS_FROZEN:
return os.path.join(BASE_DIR, "web")
src = resource_path("web")
dst = os.path.join(APP_SUPPORT_DIR, "web")
os.makedirs(dst, exist_ok=True)
for root, dirs, files in os.walk(src):
dirs[:] = [d for d in dirs if d != "output"]
rel = os.path.relpath(root, src)
out_root = dst if rel == "." else os.path.join(dst, rel)
os.makedirs(out_root, exist_ok=True)
for fname in files:
shutil.copy2(os.path.join(root, fname), os.path.join(out_root, fname))
return dst
WEB_DIR = prepare_web_dir()
WEB_INDEX = os.path.join(WEB_DIR, "index.html")
OUTPUT_DIR = os.path.join(WEB_DIR, "output")
APP_ICON_PATH = resource_path("icon.png")
os.makedirs(OUTPUT_DIR, exist_ok=True)
IMAGE_BACKEND_LOCAL = "local"
IMAGE_BACKEND_REPLICATE = "replicate"
DEFAULT_IMAGE_BACKEND = IMAGE_BACKEND_LOCAL
@@ -849,7 +810,7 @@ class Api:
# oder als Startscript mitgibst!
cmd = [
"/Applications/Blender.app/Contents/MacOS/Blender",
"--python", resource_path("scene_setup.py"),
"--python", "scene_setup.py",
"--", glb_path, hdri_path or ""
]
try:
@@ -863,7 +824,7 @@ class Api:
def edit_external(self, filepath: str):
# filepath kommt von 2D als "output/foo.png" oder von 3D als "output/foo.png"
ext = os.path.splitext(filepath)[1].lower()
full_path = os.path.join(WEB_DIR, filepath)
full_path = os.path.join(BASE_DIR, "web", filepath)
# Ist es ein Bild oder das PNG eines 3D-Modells?
if ext == ".png":
# Prüfe, ob ein GLB daneben liegt
@@ -891,7 +852,7 @@ class Api:
# ------------- Generate 3D Model -------------
def generate_3d_model(self, filepath: str):
# filepath kommt aus JS als "output/flower-1.png"
full_path = os.path.join(WEB_DIR, filepath)
full_path = os.path.join(BASE_DIR, "web", filepath)
if not os.path.isfile(full_path):
self._js("window.on_error", f"Image not found: {full_path}")
return {"status": "missing_file"}
@@ -913,8 +874,33 @@ class Api:
)
return
glb_path = self._run_generate_3d_and_return(img_path)
self._js("window.on_3d_generated", glb_path)
# Construct the command: sys.executable ensures we run with same Python interpreter
script_path = os.path.join(BASE_DIR, "image_to_3d.py")
cmd = [sys.executable, script_path, img_path]
base, _ = os.path.splitext(img_path)
glb_path = base + ".glb"
previous_mtime = os.path.getmtime(glb_path) if os.path.isfile(glb_path) else None
result = subprocess.run(
cmd,
capture_output=True,
text=True,
env=self._subprocess_env(),
)
# Check for success: sidecar or actual .glb in same folder
current_mtime = os.path.getmtime(glb_path) if os.path.isfile(glb_path) else None
if current_mtime is not None and current_mtime != previous_mtime:
# Notify JavaScript
self._js("window.on_3d_generated", glb_path)
else:
# If the script failed or no .glb was produced, send an error
err_msg = (
result.stderr.strip()
or result.stdout.strip()
or "3D conversion did not produce .glb"
)
self._js("window.on_error", f"3D Model failed: {err_msg}")
except Exception as e:
self._js("window.on_error", f"3D conversion exception: {e}")
@@ -929,7 +915,7 @@ class Api:
Called when user wants both 3D model and equirectangular HDRI for an image.
Kicks off both processes, waits for both, and (later) calls the next step.
"""
full_path = os.path.join(WEB_DIR, filepath)
full_path = os.path.join(BASE_DIR, "web", filepath)
if not os.path.isfile(full_path):
self._js("window.on_error", f"Image not found: {full_path}")
return {"status": "missing_file"}
@@ -1055,32 +1041,45 @@ Do NOT mention the object itself. Describe the environment in a concise way, e.g
if not self._get_replicate_api_token():
raise RuntimeError("Replicate API token missing. Open settings and add it.")
import image_to_3d
result = image_to_3d.process_image(img_path, self._get_replicate_api_token())
if result and os.path.isfile(result):
return result
raise RuntimeError("3D conversion did not produce .glb")
script_path = os.path.join(BASE_DIR, "image_to_3d.py")
cmd = [sys.executable, script_path, img_path]
base, _ = os.path.splitext(img_path)
glb_path = base + ".glb"
previous_mtime = os.path.getmtime(glb_path) if os.path.isfile(glb_path) else None
result = subprocess.run(
cmd,
capture_output=True,
text=True,
env=self._subprocess_env(),
)
current_mtime = os.path.getmtime(glb_path) if os.path.isfile(glb_path) else None
if current_mtime is not None and current_mtime != previous_mtime:
self._js("window.on_3d_generated", glb_path)
return glb_path
else:
err_msg = (
result.stderr.strip()
or result.stdout.strip()
or "3D conversion did not produce .glb"
)
raise RuntimeError(err_msg)
def _run_equirect_map(self, prompt: str, output_path: str):
"""
Calls your equi map generator script.
Logs command and full output for debugging.
"""
import generate_equirect
print(f"[HDRI] Generating to: {output_path}")
result = generate_equirect.generate_equirect(
prompt,
output_path,
work_dir=APP_SUPPORT_DIR if IS_FROZEN else BASE_DIR,
)
if result and os.path.isfile(output_path):
script_path = os.path.join(BASE_DIR, "generate_equirect.py")
cmd = [sys.executable, script_path, "--prompt", prompt, "--output", output_path]
print(f"[HDRI CMD] {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
print(f"[HDRI STDOUT]\n{result.stdout}")
print(f"[HDRI STDERR]\n{result.stderr}")
if result.returncode == 0 and os.path.isfile(output_path):
print(f"[HDRI OK] Created: {output_path}")
return output_path
else:
raise RuntimeError(f"HDRI generation failed for {output_path}")
raise RuntimeError(result.stderr.strip() or f"HDRI generation failed for {output_path}")
def _on_3d_and_hdri_ready(self, glb_path: str, hdri_path: str):
"""
@@ -1169,7 +1168,7 @@ Do NOT mention the object itself. Describe the environment in a concise way, e.g
def get_image_json(self, filepath: str):
# filepath kommt aus JS als "output/flower-1.png"
full_path = os.path.join(WEB_DIR, filepath)
full_path = os.path.join(BASE_DIR, "web", filepath)
try:
# Always prefer the sidecar if available (contains most up-to-date data)
sidecar = full_path + ".json"
@@ -1231,7 +1230,7 @@ if __name__ == "__main__":
api = Api()
window = webview.create_window(
"SD 3D Model Image Gen",
WEB_INDEX,
"web/index.html",
js_api=api,
width=900,
height=1000,
@@ -1239,4 +1238,4 @@ if __name__ == "__main__":
resizable=True
)
api.set_window(window)
webview.start(debug=not IS_FROZEN, icon=APP_ICON_PATH if os.path.isfile(APP_ICON_PATH) else None)
webview.start(debug=True)