stpete2 commited on
Commit
7237554
·
verified ·
1 Parent(s): f8a1e3b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -19
app.py CHANGED
@@ -1,26 +1,82 @@
1
- FROM nvidia/cuda:11.6.2-base-ubuntu20.04
 
 
 
 
 
 
 
 
2
 
3
- ENV DEBIAN_FRONTEND=noninteractive
4
- WORKDIR /code
5
 
6
- # Install Python and dependencies
7
- RUN apt-get update && \
8
- apt-get install -y python3 python3-pip git && \
9
- apt-get clean && \
10
- rm -rf /var/lib/apt/lists/*
 
 
 
 
11
 
12
- # Copy requirements and install
13
- COPY requirements.txt .
14
- RUN pip3 install --no-cache-dir -r requirements.txt
15
 
16
- # Copy app files
17
- COPY app.py .
 
 
18
 
19
- # Set environment variables for HF
20
- ENV HF_HOME=/code
 
21
 
22
- # Expose port
23
- EXPOSE 7860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- # Run the application with proper host to expose externally
26
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
1
+ import torch
2
+ from diffusers import StableDiffusionPipeline
3
+ from fastapi import FastAPI, Response
4
+ from fastapi.responses import JSONResponse
5
+ from pydantic import BaseModel
6
+ import io
7
+ import base64
8
+ from typing import Optional
9
+ import uvicorn
10
 
11
+ # Initialize FastAPI app
12
+ app = FastAPI(title="Stable Diffusion API")
13
 
14
+ # Define input model
15
+ class TextToImageRequest(BaseModel):
16
+ prompt: str
17
+ negative_prompt: Optional[str] = None
18
+ num_inference_steps: Optional[int] = 50
19
+ guidance_scale: Optional[float] = 7.5
20
+ height: Optional[int] = 512
21
+ width: Optional[int] = 512
22
+ seed: Optional[int] = None
23
 
24
+ # Load the model (will be loaded when the Space is initialized)
25
+ model_id = "CompVis/stable-diffusion-v1-4"
 
26
 
27
+ # Check if CUDA is available
28
+ device = "cuda" if torch.cuda.is_available() else "cpu"
29
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True)
30
+ pipe = pipe.to(device)
31
 
32
+ @app.get("/")
33
+ def read_root():
34
+ return {"message": "Stable Diffusion API is running. Use POST /generate endpoint."}
35
 
36
+ @app.post("/generate")
37
+ async def generate_image(request: TextToImageRequest):
38
+ try:
39
+ # Set seed if provided
40
+ if request.seed is not None:
41
+ generator = torch.Generator(device=device).manual_seed(request.seed)
42
+ else:
43
+ generator = None
44
+
45
+ # Generate image
46
+ image = pipe(
47
+ prompt=request.prompt,
48
+ negative_prompt=request.negative_prompt,
49
+ num_inference_steps=request.num_inference_steps,
50
+ guidance_scale=request.guidance_scale,
51
+ height=request.height,
52
+ width=request.width,
53
+ generator=generator
54
+ ).images[0]
55
+
56
+ # Convert to base64
57
+ buffer = io.BytesIO()
58
+ image.save(buffer, format="PNG")
59
+ img_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
60
+
61
+ return JSONResponse({
62
+ "status": "success",
63
+ "image": img_str,
64
+ "parameters": {
65
+ "prompt": request.prompt,
66
+ "negative_prompt": request.negative_prompt,
67
+ "steps": request.num_inference_steps,
68
+ "guidance_scale": request.guidance_scale,
69
+ "dimensions": f"{request.width}x{request.height}",
70
+ "seed": request.seed
71
+ }
72
+ })
73
+
74
+ except Exception as e:
75
+ return JSONResponse(
76
+ status_code=500,
77
+ content={"status": "error", "message": str(e)}
78
+ )
79
 
80
+ # For local testing, not necessary in Spaces
81
+ if __name__ == "__main__":
82
+ uvicorn.run(app, host="0.0.0.0", port=7860)