Update handler.py
Browse files- handler.py +40 -19
handler.py
CHANGED
|
@@ -1,22 +1,43 @@
|
|
| 1 |
-
from
|
| 2 |
import torch
|
|
|
|
|
|
|
| 3 |
|
| 4 |
class EndpointHandler:
|
| 5 |
-
def __init__(self, path="
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict
|
| 2 |
import torch
|
| 3 |
+
from diffusers import DiffusionPipeline
|
| 4 |
+
from compel import Compel
|
| 5 |
|
| 6 |
class EndpointHandler:
|
| 7 |
+
def __init__(self, path: str = ""):
|
| 8 |
+
# Load base FLUX pipeline
|
| 9 |
+
self.pipe = DiffusionPipeline.from_pretrained(
|
| 10 |
+
"black-forest-labs/FLUX.1-dev",
|
| 11 |
+
torch_dtype=torch.float16,
|
| 12 |
+
variant="fp16",
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
# Load your LoRA weights hosted in the same repo
|
| 16 |
+
self.pipe.load_lora_weights("./c1t3_v1.safetensors")
|
| 17 |
+
|
| 18 |
+
# Move to GPU if available
|
| 19 |
+
if torch.cuda.is_available():
|
| 20 |
+
self.pipe.to("cuda")
|
| 21 |
+
else:
|
| 22 |
+
self.pipe.to("cpu")
|
| 23 |
+
|
| 24 |
+
# Optional: enable memory optimization
|
| 25 |
+
self.pipe.enable_model_cpu_offload()
|
| 26 |
+
|
| 27 |
+
# Initialize Compel (prompt parser)
|
| 28 |
+
self.compel = Compel(tokenizer=self.pipe.tokenizer, text_encoder=self.pipe.text_encoder)
|
| 29 |
+
|
| 30 |
+
def __call__(self, data: Dict[str, str]) -> Dict:
|
| 31 |
+
# Get the prompt from request
|
| 32 |
+
prompt = data.get("prompt", "")
|
| 33 |
+
if not prompt:
|
| 34 |
+
return {"error": "No prompt provided."}
|
| 35 |
+
|
| 36 |
+
# Process the prompt with Compel (recommended for FLUX)
|
| 37 |
+
conditioning = self.compel(prompt)
|
| 38 |
+
|
| 39 |
+
# Generate the image
|
| 40 |
+
image = self.pipe(prompt_embeds=conditioning).images[0]
|
| 41 |
+
|
| 42 |
+
# Return the result
|
| 43 |
+
return {"image": image}
|