File size: 8,158 Bytes
1b704ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03b696f
25e7823
 
 
 
 
 
7b5763f
 
 
25e7823
03b696f
0b5b20e
1b704ad
 
03b696f
1b704ad
 
 
03b696f
1b704ad
 
 
 
 
 
 
0b5b20e
25e7823
 
 
 
 
 
03b696f
 
 
 
25e7823
 
 
1b704ad
 
 
 
 
 
03b696f
1b704ad
25e7823
 
 
 
 
 
 
 
03b696f
 
 
25e7823
 
1b704ad
25e7823
 
 
 
1b704ad
25e7823
 
1b704ad
 
 
03b696f
 
 
 
1b704ad
25e7823
 
 
 
 
 
03b696f
0b5b20e
03b696f
 
 
0b5b20e
 
1b704ad
0b5b20e
25e7823
1b704ad
25e7823
 
03b696f
25e7823
 
 
 
 
03b696f
ebb102b
25e7823
 
 
 
 
ebb102b
25e7823
1b704ad
 
 
 
 
 
25e7823
1b704ad
25e7823
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# # core/image_generator.py
# import os
# import torch
# from diffusers import StableDiffusionXLPipeline
# from huggingface_hub import hf_hub_download
# from pathlib import Path
# from typing import List
# from io import BytesIO
# import base64
# from PIL import Image

# # Set cache and model directories early
# HF_CACHE_DIR = Path("/tmp/hf_cache")
# HF_CACHE_DIR.mkdir(parents=True, exist_ok=True)
# os.chmod(HF_CACHE_DIR, 0o777)

# os.environ["HF_HOME"] = str(HF_CACHE_DIR)
# os.environ["TRANSFORMERS_CACHE"] = str(HF_CACHE_DIR)
# os.environ["XDG_CACHE_HOME"] = str(HF_CACHE_DIR)
# os.environ["HF_DATASETS_CACHE"] = str(HF_CACHE_DIR)
# os.environ["HF_MODULES_CACHE"] = str(HF_CACHE_DIR)

# MODEL_DIR = Path("/tmp/models/realvisxl_v4")
# MODEL_DIR.mkdir(parents=True, exist_ok=True)
# os.chmod(MODEL_DIR, 0o777)


# # ---------------- MODEL CONFIG ----------------
# MODEL_REPO = "SG161222/RealVisXL_V4.0"
# MODEL_FILENAME = "realvisxlV40_v40LightningBakedvae.safetensors"
# MODEL_DIR = Path("/tmp/models/realvisxl_v4")
# os.makedirs(MODEL_DIR, exist_ok=True)

# # ---------------- MODEL DOWNLOAD ----------------
# def download_model() -> Path:
#     """
#     Downloads RealVisXL V4.0 model if not present.
#     Returns the local model path.
#     """
#     model_path = MODEL_DIR / MODEL_FILENAME
#     if not model_path.exists():
#         print("[ImageGen] Downloading RealVisXL V4.0 model...")
#         model_path = hf_hub_download(
#             repo_id=MODEL_REPO,
#             filename=MODEL_FILENAME,
#             local_dir=str(MODEL_DIR),
#             cache_dir=str(HF_CACHE_DIR),  # ensure writable cache is used
#             force_download=False,
#         )
#         print(f"[ImageGen] Model downloaded to: {model_path}")
#     else:
#         print("[ImageGen] Model already exists. Skipping download.")
#     return model_path

# # ---------------- PIPELINE LOAD ----------------
# def load_pipeline() -> StableDiffusionXLPipeline:
#     """
#     Loads the RealVisXL V4.0 model for image generation.
#     """
#     model_path = download_model()
#     print("[ImageGen] Loading model into pipeline...")
#     pipe = StableDiffusionXLPipeline.from_single_file(
#         str(model_path),
#         torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
#     )
#     if torch.cuda.is_available():
#         pipe.to("cuda")
#     print("[ImageGen] Model ready.")
#     return pipe

# # ---------------- GLOBAL PIPELINE CACHE ----------------
# pipe: StableDiffusionXLPipeline | None = None

# # ---------------- UTILITY: PIL TO BASE64 ----------------
# def pil_to_base64(img: Image.Image) -> str:
#     """
#     Converts a PIL image to a base64 string for frontend display.
#     """
#     buffered = BytesIO()
#     img.save(buffered, format="PNG")
#     img_bytes = buffered.getvalue()
#     img_b64 = base64.b64encode(img_bytes).decode("utf-8")
#     return f"data:image/png;base64,{img_b64}"

# # ---------------- IMAGE GENERATION ----------------
# def generate_images(prompt: str, seed: int = None, num_images: int = 3) -> List[str]:
#     """
#     Generates high-quality images using RealVisXL V4.0.
#     Supports deterministic generation using a seed.
    
#     Args:
#         prompt (str): Text prompt for image generation.
#         seed (int, optional): Seed for deterministic generation.
#         num_images (int): Number of images to generate.
        
#     Returns:
#         List[str]: List of base64-encoded images.
#     """
#     global pipe
#     if pipe is None:
#         pipe = load_pipeline()

#     print(f"[ImageGen] Generating {num_images} image(s) for prompt: '{prompt}' with seed={seed}")
#     images: List[str] = []

#     for i in range(num_images):
#         generator = None
#         if seed is not None:
#             device = "cuda" if torch.cuda.is_available() else "cpu"
#             generator = torch.Generator(device).manual_seed(seed + i)

#         result = pipe(prompt, num_inference_steps=30, generator=generator).images[0]
#         images.append(pil_to_base64(result))

#     print(f"[ImageGen] Generated {len(images)} images successfully.")
#     return images


# core/image_generator.py
import os
import torch
from diffusers import StableDiffusionXLPipeline
from huggingface_hub import hf_hub_download
from pathlib import Path
from typing import List
from io import BytesIO
import base64
from PIL import Image

# ---------------- CACHE & MODEL DIRECTORIES ----------------
HF_CACHE_DIR = Path("/tmp/hf_cache")
MODEL_DIR = Path("/tmp/models/realvisxl_v4")

# Create directories safely (no chmod)
for d in [HF_CACHE_DIR, MODEL_DIR]:
    d.mkdir(parents=True, exist_ok=True)

# Apply environment variables BEFORE any Hugging Face usage
os.environ.update({
    "HF_HOME": str(HF_CACHE_DIR),
    "TRANSFORMERS_CACHE": str(HF_CACHE_DIR),
    "XDG_CACHE_HOME": str(HF_CACHE_DIR),
    "HF_DATASETS_CACHE": str(HF_CACHE_DIR),
    "HF_MODULES_CACHE": str(HF_CACHE_DIR),
})

# ---------------- MODEL CONFIG ----------------
MODEL_REPO = "SG161222/RealVisXL_V4.0"
MODEL_FILENAME = "realvisxlV40_v40LightningBakedvae.safetensors"

# ---------------- MODEL DOWNLOAD ----------------
def download_model() -> Path:
    """
    Downloads RealVisXL V4.0 model if not present.
    Returns local path.
    """
    model_path = MODEL_DIR / MODEL_FILENAME
    if not model_path.exists():
        print("[ImageGen] Downloading RealVisXL V4.0 model...")
        model_path = Path(
            hf_hub_download(
                repo_id=MODEL_REPO,
                filename=MODEL_FILENAME,
                cache_dir=str(HF_CACHE_DIR),
                force_download=False,
                resume_download=True,  # safer if download interrupted
            )
        )
        print(f"[ImageGen] Model downloaded to: {model_path}")
    else:
        print("[ImageGen] Model already exists. Skipping download.")
    return model_path

# ---------------- PIPELINE LOAD ----------------
def load_pipeline() -> StableDiffusionXLPipeline:
    """
    Loads the RealVisXL V4.0 model for image generation.
    """
    model_path = download_model()
    print("[ImageGen] Loading model into pipeline...")

    pipe = StableDiffusionXLPipeline.from_single_file(
        str(model_path),
        torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    )

    if torch.cuda.is_available():
        pipe.to("cuda")
    else:
        pipe.to("cpu")

    # Optional: skip safety checker to save memory/performance
    pipe.safety_checker = None  
    # Enable attention slicing for memory-efficient CPU usage
    pipe.enable_attention_slicing()  

    print("[ImageGen] Model ready.")
    return pipe

# ---------------- GLOBAL PIPELINE CACHE ----------------
pipe: StableDiffusionXLPipeline | None = None

# ---------------- UTILITY: PIL → BASE64 ----------------
def pil_to_base64(img: Image.Image) -> str:
    """
    Converts PIL image to base64 string for frontend.
    """
    buffered = BytesIO()
    img.save(buffered, format="PNG")
    return f"data:image/png;base64,{base64.b64encode(buffered.getvalue()).decode()}"

# ---------------- IMAGE GENERATION ----------------
def generate_images(prompt: str, seed: int | None = None, num_images: int = 3) -> List[str]:
    """
    Generates high-quality images using RealVisXL V4.0.
    Returns a list of base64-encoded PNGs.
    """
    global pipe
    if pipe is None:
        pipe = load_pipeline()

    print(f"[ImageGen] Generating {num_images} image(s) for prompt: '{prompt}' seed={seed}")
    images: List[str] = []

    for i in range(num_images):
        generator = None
        if seed is not None:
            device = "cuda" if torch.cuda.is_available() else "cpu"
            generator = torch.Generator(device).manual_seed(seed + i)

        try:
            result = pipe(prompt, num_inference_steps=30, generator=generator).images[0]
            images.append(pil_to_base64(result))
        except Exception as e:
            print(f"[ImageGen] ⚠️ Generation failed on image {i}: {e}")
            continue

    print(f"[ImageGen] Generated {len(images)} image(s) successfully.")
    return images