guydffdsdsfd commited on
Commit
ea898e8
·
verified ·
1 Parent(s): 2f795db

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +50 -106
Dockerfile CHANGED
@@ -1,114 +1,58 @@
1
- # 1. Use Python base
2
  FROM python:3.10-slim
3
 
4
- # 2. Install dependencies
5
- # 'optimum' helps speed up the model on CPU
6
  RUN apt-get update && apt-get install -y \
7
  libgl1-mesa-glx libglib2.0-0 procps curl && \
8
- pip3 install flask flask-cors requests diffusers transformers accelerate torch --extra-index-url https://download.pytorch.org/whl/cpu
9
 
10
- # 3. Set up environment
 
 
 
 
 
 
 
11
  ENV HOME=/home/user
 
12
  WORKDIR $HOME
13
- RUN mkdir -p $HOME/.cache && chmod -R 777 $HOME
14
-
15
- # --- 4. THE PYTHON APP (Guard + SD Model) ---
16
- RUN cat <<EOF > $HOME/app.py
17
- from flask import Flask, request, Response, jsonify, send_file
18
- import torch
19
- from diffusers import StableDiffusionPipeline
20
- from flask_cors import CORS
21
- import json, os, datetime, io
22
-
23
- app = Flask(__name__)
24
- CORS(app)
25
-
26
- # Note: These files reset every time the Space restarts on the Free Tier
27
- DB_PATH = "$HOME/usage.json"
28
- WL_PATH = "$HOME/whitelist.txt"
29
- LIMIT = 500
30
- UNLIMITED_KEY = "sk-ess4l0ri37"
31
-
32
- # Seed the whitelist with your unique SD keys
33
- if not os.path.exists(WL_PATH):
34
- with open(WL_PATH, "w") as f:
35
- f.write(f"sk-sd-user-1\nsk-sd-pro-99\n{UNLIMITED_KEY}\n")
36
-
37
- print("Loading Stable Diffusion on CPU...")
38
- pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float32)
39
- pipe.to("cpu")
40
- print("Model Ready!")
41
-
42
- def get_whitelist():
43
- try:
44
- with open(WL_PATH, "r") as f:
45
- return set(line.strip() for line in f.readlines())
46
- except:
47
- return {UNLIMITED_KEY}
48
-
49
- @app.route("/", methods=["GET"])
50
- def health():
51
- return "Stable Diffusion CPU Proxy is Running", 200
52
-
53
- @app.route("/api/generate", methods=["POST"])
54
- def proxy():
55
- user_key = request.headers.get("x-api-key", "")
56
-
57
- # 1. Auth Check
58
- if user_key not in get_whitelist():
59
- return jsonify({"error": "Unauthorized: Key not registered for SD"}), 401
60
-
61
- # 2. Usage Check
62
- is_unlimited = (user_key == UNLIMITED_KEY)
63
- if not is_unlimited:
64
- now = datetime.datetime.now()
65
- month_key = now.strftime("%Y-%m")
66
- usage = {}
67
- if os.path.exists(DB_PATH):
68
- try:
69
- with open(DB_PATH, "r") as f:
70
- usage = json.load(f)
71
- except: pass
72
-
73
- key_usage = usage.get(user_key, {}).get(month_key, 0)
74
- if key_usage >= LIMIT:
75
- return jsonify({"error": f"Monthly limit of {LIMIT} reached"}), 429
76
-
77
- # 3. Image Generation
78
- try:
79
- data = request.json
80
- prompt = data.get("prompt", "a simple drawing of a cat")
81
-
82
- # CPU speed tweak: Lower steps (15) for faster turnaround
83
- image = pipe(prompt, num_inference_steps=15).images[0]
84
-
85
- # Log usage
86
- if not is_unlimited:
87
- if user_key not in usage: usage[user_key] = {}
88
- usage[user_key][month_key] = key_usage + 1
89
- with open(DB_PATH, "w") as f:
90
- json.dump(usage, f)
91
-
92
- # Return Image
93
- img_io = io.BytesIO()
94
- image.save(img_io, 'PNG')
95
- img_io.seek(0)
96
- return send_file(img_io, mimetype='image/png')
97
-
98
- except Exception as e:
99
- return jsonify({"error": f"Generation Error: {str(e)}"}), 500
100
-
101
- if __name__ == "__main__":
102
- app.run(host="0.0.0.0", port=7860)
103
- EOF
104
-
105
- # --- 5. THE STARTUP SCRIPT ---
106
- RUN cat <<EOF > $HOME/start.sh
107
- #!/bin/bash
108
- python3 $HOME/app.py
109
- EOF
110
-
111
- RUN chmod +x $HOME/start.sh
112
 
113
- # --- 6. RUN ---
114
- ENTRYPOINT ["/bin/bash", "/home/user/start.sh"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 1. Use a more stable Python image
2
  FROM python:3.10-slim
3
 
4
+ # 2. System dependencies
 
5
  RUN apt-get update && apt-get install -y \
6
  libgl1-mesa-glx libglib2.0-0 procps curl && \
7
+ rm -rf /var/lib/apt/lists/*
8
 
9
+ # 3. Python dependencies
10
+ RUN pip3 install --no-cache-dir \
11
+ flask flask-cors requests diffusers transformers accelerate torch \
12
+ --extra-index-url https://download.pytorch.org/whl/cpu
13
+
14
+ # 4. Set up non-root user (Required for HF)
15
+ RUN useradd -m -u 1000 user
16
+ USER user
17
  ENV HOME=/home/user
18
+ ENV PATH=/home/user/.local/bin:$PATH
19
  WORKDIR $HOME
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # 5. Create the app file directly via a more robust method
22
+ # Using printf instead of cat <<EOF to avoid shell/indentation errors
23
+ RUN printf 'from flask import Flask, request, jsonify, send_file\n\
24
+ import torch, os, datetime, io\n\
25
+ from diffusers import StableDiffusionPipeline\n\
26
+ from flask_cors import CORS\n\
27
+ \n\
28
+ app = Flask(__name__)\n\
29
+ CORS(app)\n\
30
+ \n\
31
+ print("Loading SD Model on CPU...")\n\
32
+ pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float32)\n\
33
+ pipe.to("cpu")\n\
34
+ \n\
35
+ @app.route("/api/generate", methods=["POST"])\n\
36
+ def proxy():\n\
37
+ user_key = request.headers.get("x-api-key", "")\n\
38
+ # Simple check for your key\n\
39
+ if user_key != "sk-sd-user-1" and user_key != "sk-ess4l0ri37":\n\
40
+ return jsonify({"error": "Unauthorized"}), 401\n\
41
+ \n\
42
+ data = request.json\n\
43
+ prompt = data.get("prompt", "a sunset")\n\
44
+ image = pipe(prompt, num_inference_steps=15).images[0]\n\
45
+ \n\
46
+ img_io = io.BytesIO()\n\
47
+ image.save(img_io, "PNG")\n\
48
+ img_io.seek(0)\n\
49
+ return send_file(img_io, mimetype="image/png")\n\
50
+ \n\
51
+ if __name__ == "__main__":\n\
52
+ app.run(host="0.0.0.0", port=7860)\n' > $HOME/app.py
53
+
54
+ # 6. Expose port 7860
55
+ EXPOSE 7860
56
+
57
+ # 7. Start the app
58
+ CMD ["python3", "app.py"]