Spaces:
Runtime error
Runtime error
Rx Codex AI
commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,83 +1,85 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
from fastapi import FastAPI, HTTPException
|
| 3 |
-
from pydantic import BaseModel
|
| 4 |
-
import torch
|
| 5 |
-
from diffusers import AutoPipelineForText2Image
|
| 6 |
-
from contextlib import asynccontextmanager
|
| 7 |
-
import io
|
| 8 |
-
import base64
|
| 9 |
-
import os
|
| 10 |
-
|
| 11 |
-
# --- Pydantic Models ---
|
| 12 |
-
class ImageRequest(BaseModel):
|
| 13 |
-
prompt: str
|
| 14 |
-
negative_prompt: str = ""
|
| 15 |
-
steps: int = 25
|
| 16 |
-
|
| 17 |
-
class ImageResponse(BaseModel):
|
| 18 |
-
image_base64: str
|
| 19 |
-
|
| 20 |
-
# --- App State and Lifespan ---
|
| 21 |
-
app_state = {}
|
| 22 |
-
|
| 23 |
-
@asynccontextmanager
|
| 24 |
-
async def lifespan(app: FastAPI):
|
| 25 |
-
# Load the model on startup
|
| 26 |
-
hf_token = os.getenv("HF_TOKEN")
|
| 27 |
-
if not hf_token:
|
| 28 |
-
raise RuntimeError("HF_TOKEN environment variable not set!")
|
| 29 |
-
|
| 30 |
-
model_id = "rxmha125/sdxl-base-1.0-private" #
|
| 31 |
-
print(f"Loading model: {model_id}")
|
| 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 |
-
image
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
from fastapi import FastAPI, HTTPException
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
import torch
|
| 5 |
+
from diffusers import AutoPipelineForText2Image
|
| 6 |
+
from contextlib import asynccontextmanager
|
| 7 |
+
import io
|
| 8 |
+
import base64
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
# --- Pydantic Models ---
|
| 12 |
+
class ImageRequest(BaseModel):
|
| 13 |
+
prompt: str
|
| 14 |
+
negative_prompt: str = ""
|
| 15 |
+
steps: int = 25
|
| 16 |
+
|
| 17 |
+
class ImageResponse(BaseModel):
|
| 18 |
+
image_base64: str
|
| 19 |
+
|
| 20 |
+
# --- App State and Lifespan ---
|
| 21 |
+
app_state = {}
|
| 22 |
+
|
| 23 |
+
@asynccontextmanager
|
| 24 |
+
async def lifespan(app: FastAPI):
|
| 25 |
+
# Load the model on startup
|
| 26 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 27 |
+
if not hf_token:
|
| 28 |
+
raise RuntimeError("HF_TOKEN environment variable not set!")
|
| 29 |
+
|
| 30 |
+
model_id = "rxmha125/sdxl-base-1.0-private" # Your private model ID
|
| 31 |
+
print(f"Loading model: {model_id}")
|
| 32 |
+
|
| 33 |
+
# --- *** THIS IS THE CORRECTED PART *** ---
|
| 34 |
+
# We removed variant="fp16" and use_safetensors=True
|
| 35 |
+
# to load the available .bin files instead of the missing .safetensors.
|
| 36 |
+
pipe = AutoPipelineForText2Image.from_pretrained(
|
| 37 |
+
model_id,
|
| 38 |
+
torch_dtype=torch.float16, # Keep for memory optimization
|
| 39 |
+
token=hf_token
|
| 40 |
+
).to("cuda")
|
| 41 |
+
# --- *********************************** ---
|
| 42 |
+
|
| 43 |
+
# Optimization for speed and memory
|
| 44 |
+
pipe.enable_model_cpu_offload()
|
| 45 |
+
|
| 46 |
+
app_state["pipe"] = pipe
|
| 47 |
+
print("Model loaded successfully.")
|
| 48 |
+
yield
|
| 49 |
+
# Clean up on shutdown
|
| 50 |
+
app_state.clear()
|
| 51 |
+
print("Resources cleaned up.")
|
| 52 |
+
|
| 53 |
+
# --- FastAPI App ---
|
| 54 |
+
app = FastAPI(lifespan=lifespan)
|
| 55 |
+
|
| 56 |
+
@app.get("/")
|
| 57 |
+
def root():
|
| 58 |
+
return {"status": "Text-to-Image API is running"}
|
| 59 |
+
|
| 60 |
+
@app.post("/generate-image", response_model=ImageResponse)
|
| 61 |
+
def generate_image(request: ImageRequest):
|
| 62 |
+
if "pipe" not in app_state:
|
| 63 |
+
raise HTTPException(status_code=503, detail="Model is not ready.")
|
| 64 |
+
|
| 65 |
+
pipe = app_state["pipe"]
|
| 66 |
+
|
| 67 |
+
print(f"Generating image for prompt: '{request.prompt}'")
|
| 68 |
+
try:
|
| 69 |
+
# Generate the image
|
| 70 |
+
image = pipe(
|
| 71 |
+
prompt=request.prompt,
|
| 72 |
+
negative_prompt=request.negative_prompt,
|
| 73 |
+
num_inference_steps=request.steps
|
| 74 |
+
).images[0]
|
| 75 |
+
|
| 76 |
+
# Convert image to Base64
|
| 77 |
+
buffer = io.BytesIO()
|
| 78 |
+
image.save(buffer, format="PNG")
|
| 79 |
+
img_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
| 80 |
+
|
| 81 |
+
return ImageResponse(image_base64=img_str)
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f"Error during image generation: {e}")
|
| 85 |
raise HTTPException(status_code=500, detail=str(e))
|