Pacicap commited on
Commit
c00564d
·
2 Parent(s): 88425243fb45e7

Merge branch 'main' of https://huggingface.co/spaces/Pacicap/api_stable_diffusion

Browse files
Files changed (4) hide show
  1. Dockerfile +19 -0
  2. app.py +61 -0
  3. generated/.gitkeep +0 -0
  4. requirements.txt +0 -0
Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10
2
+
3
+ # Create a non-root user
4
+ RUN useradd -m -u 1000 user
5
+ USER user
6
+ ENV PATH="/home/user/.local/bin:$PATH"
7
+
8
+ # Set the working directory
9
+ WORKDIR /app
10
+
11
+ # Install Python dependencies
12
+ COPY --chown=user ./requirements.txt requirements.txt
13
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
14
+
15
+ # Copy your app code
16
+ COPY --chown=user . /app
17
+
18
+ # Start the FastAPI app
19
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request
2
+ from pydantic import BaseModel
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from diffusers import DiffusionPipeline
5
+ import torch
6
+ import uuid
7
+ import os
8
+ from PIL import Image
9
+ from fastapi.staticfiles import StaticFiles
10
+
11
+ app = FastAPI()
12
+
13
+ app.add_middleware(
14
+ CORSMiddleware,
15
+ allow_origins=["*"], # Accept from all for now
16
+ allow_credentials=True,
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
19
+ )
20
+
21
+ hf_model_ids = {
22
+ "model1": "Pacicap/FineTuned_claude_StableDiffussion_2_1",
23
+ "model2": "Pacicap/FineTuned_gpt4o_StableDiffussion_2_1"
24
+ }
25
+
26
+ loaded_models = {}
27
+
28
+ class PromptInput(BaseModel):
29
+ prompt: str
30
+ model: str
31
+
32
+ @app.post("/generate")
33
+ def generate(data: PromptInput, request: Request):
34
+ model_key = data.model
35
+
36
+ if model_key not in hf_model_ids:
37
+ return {"error": "Invalid model selected"}
38
+
39
+ model_id = hf_model_ids[model_key]
40
+
41
+ if model_key not in loaded_models:
42
+ pipe = DiffusionPipeline.from_pretrained(
43
+ model_id,
44
+ torch_dtype=torch.float32
45
+ ).to("cpu") # CPU-safe for Spaces
46
+ loaded_models[model_key] = pipe
47
+ else:
48
+ pipe = loaded_models[model_key]
49
+
50
+ image = pipe(data.prompt).images[0]
51
+
52
+ os.makedirs("generated", exist_ok=True)
53
+ filename = f"{uuid.uuid4().hex}.png"
54
+ filepath = os.path.join("generated", filename)
55
+ image.save(filepath)
56
+
57
+ return {
58
+ "url": f"{request.base_url}generated/{filename}"
59
+ }
60
+
61
+ app.mount("/generated", StaticFiles(directory="generated"), name="generated")
generated/.gitkeep ADDED
File without changes
requirements.txt ADDED
Binary file (1.68 kB). View file