File size: 7,667 Bytes
7591227
 
 
35cddec
7591227
e29d600
 
 
 
 
 
 
7591227
e29d600
7591227
e29d600
7771b9f
 
 
 
 
 
e29d600
7591227
e29d600
 
 
7591227
 
 
 
 
 
 
 
 
 
 
 
35cddec
7591227
 
 
 
 
35cddec
7591227
 
 
35cddec
7591227
 
 
 
 
 
 
 
 
35cddec
7591227
 
 
35cddec
7591227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35cddec
7591227
 
 
e29d600
7591227
 
 
35cddec
7591227
 
 
 
e29d600
 
 
 
 
 
7591227
e29d600
7591227
 
e29d600
7591227
e29d600
 
 
 
7591227
e29d600
7591227
 
 
 
e29d600
35cddec
e29d600
 
 
7591227
e29d600
7591227
 
e29d600
 
 
7591227
e29d600
 
7591227
 
e29d600
 
7591227
e29d600
 
 
 
7591227
e29d600
 
7591227
e29d600
 
 
7591227
 
 
e29d600
 
 
 
 
7591227
 
e29d600
 
7591227
e29d600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6a8969
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# ────────────────────────────────────────────────────────────────────────────
# app.py – Text ➜ 2D (FLUX-mini Kontext) ➜ 3D (Hunyuan3D-2)
#   • Fits into 16 GB system RAM: 경량 모델 + lazy loading + offload
#   • Updated: use device_map="balanced" ("auto" not supported by Flux pipelines)
# ────────────────────────────────────────────────────────────────────────────
import os
import tempfile
from typing import List, Tuple

import gradio as gr
import torch
from PIL import Image
from huggingface_hub import login

# ─────────────────────── Auth ───────────────────────
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
    raise RuntimeError(
        "HF_TOKEN이 설정되지 않았습니다. Space Settings → Secrets에서 "
        "HF_TOKEN=your_read_token 을 등록한 뒤 재시작하세요."
    )
login(token=HF_TOKEN, add_to_git_credential=False)

# ─────────────────────── Device & dtype ───────────────────────
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32

# ─────────────────────── Lazy loaders ───────────────────────
from diffusers import FluxKontextPipeline, FluxPipeline

# Global caches
kontext_pipe = None  # type: FluxKontextPipeline | None
_text2img_pipe = None  # type: FluxPipeline | None
shape_pipe = None
paint_pipe = None

MINI_KONTEXT_REPO = "black-forest-labs/FLUX.1-Kontext-mini"
MINI_T2I_REPO = "black-forest-labs/FLUX.1-mini"
HUNYUAN_REPO = "tencent/Hunyuan3D-2"
DEVICE_MAP_STRATEGY = "balanced"  # "auto" unsupported for Flux pipelines


def load_kontext() -> FluxKontextPipeline:
    global kontext_pipe
    if kontext_pipe is None:
        print("[+] Loading FLUX.1-Kontext-mini … (balanced offload)")
        kontext_pipe = FluxKontextPipeline.from_pretrained(
            MINI_KONTEXT_REPO,
            torch_dtype=DTYPE,
            device_map=DEVICE_MAP_STRATEGY,
            low_cpu_mem_usage=True,
        )
        kontext_pipe.set_progress_bar_config(disable=True)
    return kontext_pipe


def load_text2img() -> FluxPipeline:
    global _text2img_pipe
    if _text2img_pipe is None:
        print("[+] Loading FLUX.1-mini (text→image)…")
        _text2img_pipe = FluxPipeline.from_pretrained(
            MINI_T2I_REPO,
            torch_dtype=DTYPE,
            device_map=DEVICE_MAP_STRATEGY,
            low_cpu_mem_usage=True,
        )
        _text2img_pipe.set_progress_bar_config(disable=True)
    return _text2img_pipe


def load_hunyuan() -> tuple:
    global shape_pipe, paint_pipe
    if shape_pipe is None or paint_pipe is None:
        print("[+] Loading Hunyuan3D-2 (shape & texture)…")
        from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
        from hy3dgen.texgen import Hunyuan3DPaintPipeline

        shape_pipe = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
            HUNYUAN_REPO,
            torch_dtype=DTYPE,
            device_map=DEVICE_MAP_STRATEGY,
            low_cpu_mem_usage=True,
        )
        shape_pipe.set_progress_bar_config(disable=True)

        paint_pipe = Hunyuan3DPaintPipeline.from_pretrained(
            HUNYUAN_REPO,
            torch_dtype=DTYPE,
            device_map=DEVICE_MAP_STRATEGY,
            low_cpu_mem_usage=True,
        )
        paint_pipe.set_progress_bar_config(disable=True)
    return shape_pipe, paint_pipe

# ───────────────────────────────────────────────
# Helper functions
# ───────────────────────────────────────────────

def generate_single_2d(prompt: str, image: Image.Image | None, guidance_scale: float) -> Image.Image:
    kontext = load_kontext()
    if image is None:
        t2i = load_text2img()
        result = t2i(prompt=prompt, guidance_scale=guidance_scale).images[0]
    else:
        result = kontext(image=image, prompt=prompt, guidance_scale=guidance_scale).images[0]
    return result


def generate_multiview(prompt: str, base_image: Image.Image, guidance_scale: float) -> List[Image.Image]:
    kontext = load_kontext()
    views = [
        base_image,
        kontext(image=base_image, prompt=f"{prompt}, left side view", guidance_scale=guidance_scale).images[0],
        kontext(image=base_image, prompt=f"{prompt}, right side view", guidance_scale=guidance_scale).images[0],
        kontext(image=base_image, prompt=f"{prompt}, back view", guidance_scale=guidance_scale).images[0],
    ]
    return views


def build_3d_mesh(prompt: str, images: List[Image.Image]) -> str:
    shape, paint = load_hunyuan()
    single_or_multi = images if len(images) > 1 else images[0]
    mesh = shape(image=single_or_multi, prompt=prompt)[0]
    mesh = paint(mesh, image=single_or_multi)

    tmpdir = tempfile.mkdtemp()
    out_path = os.path.join(tmpdir, "mesh.glb")
    mesh.export(out_path)
    return out_path

# ──────────────────────────────── UI ────────────────────────────────
CSS = """footer {visibility:hidden;}"""


def workflow(prompt: str, input_image: Image.Image | None, multiview: bool, guidance_scale: float):
    if not prompt:
        raise gr.Error("프롬프트(설명)를 입력하세요 📌")

    base_img = generate_single_2d(prompt, input_image, guidance_scale)
    images = generate_multiview(prompt, base_img, guidance_scale) if multiview else [base_img]

    model_path = build_3d_mesh(prompt, images)
    return images, model_path, model_path


def build_ui():
    with gr.Blocks(css=CSS, title="Text ➜ 2D ➜ 3D (mini)") as demo:
        gr.Markdown("# 🌀 텍스트 → 2D → 3D 생성기 (경량 버전)")
        gr.Markdown("Kontext-mini + Hunyuan3D-2. 16 GB RAM에서도 동작합니다.")

        with gr.Row():
            with gr.Column():
                prompt = gr.Textbox(label="프롬프트 / 설명", placeholder="예: 파란 모자를 쓴 귀여운 로봇")
                input_image = gr.Image(label="(선택) 편집할 참조 이미지", type="pil")
                multiview = gr.Checkbox(label="멀티뷰(좌/우/후면 포함)", value=True)
                guidance = gr.Slider(0.5, 7.5, 2.5, step=0.1, label="Guidance Scale")
                run_btn = gr.Button("🚀 생성하기", variant="primary")
            with gr.Column():
                gallery = gr.Gallery(label="🎨 2D 결과", columns=2, height="auto")
                model3d = gr.Model3D(label="🧱 3D 미리보기", clear_color=[1, 1, 1, 0])
                download = gr.File(label="⬇️ GLB 다운로드")

        run_btn.click(
            fn=workflow,
            inputs=[prompt, input_image, multiview, guidance],
            outputs=[gallery, model3d, download],
            api_name="generate",
            scroll_to_output=True,
            show_progress="full",
        )
    return demo


if __name__ == "__main__":
    build_ui().queue(max_size=3).launch()