webnowa commited on
Commit
d90a28e
·
verified ·
1 Parent(s): b4d6d6a

Update api.py

Browse files
Files changed (1) hide show
  1. api.py +110 -145
api.py CHANGED
@@ -1,18 +1,13 @@
1
  import os
2
- import glob
3
  import torch
4
- from flask import Flask, request, jsonify, send_file, render_template_string
5
- from diffusers import StableDiffusionPipeline, AutoencoderKL
6
  from PIL import Image, ImageFilter
7
  from deep_translator import GoogleTranslator
8
 
9
  print("IMAGE PRO AI STARTING...")
10
 
11
- # ===============================
12
- # PATHS
13
- # ===============================
14
-
15
- CACHE_DIR = "F:/AI_models"
16
  OUTPUT_DIR = "outputs"
17
 
18
  os.makedirs(OUTPUT_DIR, exist_ok=True)
@@ -22,6 +17,7 @@ os.makedirs(OUTPUT_DIR, exist_ok=True)
22
  # ===============================
23
 
24
  def translate_prompt(prompt):
 
25
  try:
26
  prompt_en = GoogleTranslator(source="pl", target="en").translate(prompt)
27
  print("PL:", prompt)
@@ -30,44 +26,17 @@ def translate_prompt(prompt):
30
  except:
31
  return prompt
32
 
33
- # ===============================
34
- # FIND VAE
35
- # ===============================
36
-
37
- print("Searching VAE...")
38
-
39
- vae = None
40
-
41
- vae_files = glob.glob(
42
- r"F:\AI_models\models--stabilityai--sd-vae-ft-mse\snapshots\*\vae-ft-mse-840000-ema-pruned.safetensors"
43
- )
44
-
45
- if len(vae_files) > 0:
46
-
47
- VAE_PATH = vae_files[0]
48
-
49
- print("VAE FOUND:", VAE_PATH)
50
-
51
- try:
52
- vae = AutoencoderKL.from_single_file(
53
- VAE_PATH,
54
- torch_dtype=torch.float32
55
- )
56
- except:
57
- print("VAE LOAD FAILED")
58
-
59
  # ===============================
60
  # LOAD MODEL
61
  # ===============================
62
 
63
- print("Loading AI model...")
64
 
65
  pipe = StableDiffusionPipeline.from_pretrained(
66
  "SG161222/Realistic_Vision_V5.1_noVAE",
67
  cache_dir=CACHE_DIR,
68
  torch_dtype=torch.float32,
69
- safety_checker=None,
70
- vae=vae
71
  )
72
 
73
  pipe.enable_attention_slicing()
@@ -80,76 +49,110 @@ print("MODEL READY")
80
 
81
  app = Flask(__name__)
82
 
83
- # ======================================================
84
- # WEB PANEL (TEST GENERATORA)
85
- # ======================================================
 
 
86
 
87
- HTML_PAGE = """
88
- <!DOCTYPE html>
89
  <html>
 
90
  <head>
 
91
  <title>IMAGE PRO AI</title>
 
92
  <style>
93
- body{font-family:Arial;background:#111;color:white;text-align:center;padding:40px}
94
- input{width:400px;padding:10px}
95
- button{padding:10px 20px;background:#ff6a00;border:none;color:white;font-size:16px}
96
- img{margin-top:20px;max-width:512px}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  </style>
 
98
  </head>
 
99
  <body>
100
 
101
  <h1>IMAGE PRO AI</h1>
102
 
103
- <form action="/generate_web" method="post">
104
- <input name="prompt" placeholder="Wpisz prompt (np. kot w butach)">
105
  <br><br>
106
- <button type="submit">GENERUJ</button>
107
- </form>
108
 
109
- {% if image %}
 
110
  <h2>Wynik</h2>
111
- <img src="{{image}}">
112
- {% endif %}
113
 
114
- </body>
115
- </html>
116
- """
117
 
118
- @app.route("/", methods=["GET"])
119
- def home():
120
- return render_template_string(HTML_PAGE)
121
 
122
- # ======================================================
123
- # GENERATE FROM WEB PANEL
124
- # ======================================================
125
 
126
- @app.route("/generate_web", methods=["POST"])
127
- def generate_web():
128
 
129
- prompt = request.form["prompt"]
130
- prompt = translate_prompt(prompt)
131
 
132
- image = pipe(
133
- prompt,
134
- num_inference_steps=30,
135
- guidance_scale=7.5
136
- ).images[0]
137
 
138
- path = OUTPUT_DIR + "/web_gen.png"
139
- image.save(path)
 
 
 
 
 
 
 
 
 
 
 
140
 
141
- return render_template_string(
142
- HTML_PAGE,
143
- image="/image/web_gen.png"
144
- )
145
 
146
- @app.route("/image/<filename>")
147
- def serve_image(filename):
148
- return send_file(OUTPUT_DIR + "/" + filename, mimetype="image/png")
149
 
150
- # ======================================================
151
- # API GENERATE
152
- # ======================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  @app.route("/generate", methods=["POST"])
155
  def generate():
@@ -164,40 +167,35 @@ def generate():
164
  ).images[0]
165
 
166
  path = OUTPUT_DIR + "/gen.png"
 
167
  image.save(path)
168
 
169
  return send_file(path, mimetype="image/png")
170
 
171
- # ======================================================
172
  # PRODUCT AD
173
- # ======================================================
174
 
175
  @app.route("/product_ad", methods=["POST"])
176
  def product_ad():
177
 
178
  data = request.json
 
179
  prompt = translate_prompt(data["prompt"])
180
 
181
- style1 = prompt + ", luxury product photography, studio lighting"
182
- style2 = prompt + ", commercial advertising, dramatic lighting"
183
 
184
- img1 = pipe(style1).images[0]
185
- img2 = pipe(style2).images[0]
186
 
187
- p1 = OUTPUT_DIR + "/ad1.png"
188
- p2 = OUTPUT_DIR + "/ad2.png"
189
 
190
- img1.save(p1)
191
- img2.save(p2)
192
 
193
- return jsonify({
194
- "image1": p1,
195
- "image2": p2
196
- })
197
 
198
- # ======================================================
199
  # RESTORE PHOTO
200
- # ======================================================
201
 
202
  @app.route("/restore", methods=["POST"])
203
  def restore():
@@ -205,6 +203,7 @@ def restore():
205
  file = request.files["image"]
206
 
207
  img = Image.open(file.stream)
 
208
  img = img.filter(ImageFilter.SHARPEN)
209
 
210
  path = OUTPUT_DIR + "/restored.png"
@@ -213,9 +212,9 @@ def restore():
213
 
214
  return send_file(path, mimetype="image/png")
215
 
216
- # ======================================================
217
- # UPSCALE HD
218
- # ======================================================
219
 
220
  @app.route("/upscale", methods=["POST"])
221
  def upscale():
@@ -224,12 +223,9 @@ def upscale():
224
 
225
  img = Image.open(file.stream)
226
 
227
- width, height = img.size
228
 
229
- img = img.resize(
230
- (width*2, height*2),
231
- Image.LANCZOS
232
- )
233
 
234
  path = OUTPUT_DIR + "/hd.png"
235
 
@@ -237,9 +233,9 @@ def upscale():
237
 
238
  return send_file(path, mimetype="image/png")
239
 
240
- # ======================================================
241
  # COLORIZE
242
- # ======================================================
243
 
244
  @app.route("/colorize", methods=["POST"])
245
  def colorize():
@@ -247,6 +243,7 @@ def colorize():
247
  file = request.files["image"]
248
 
249
  img = Image.open(file.stream)
 
250
  img = img.convert("RGB")
251
 
252
  path = OUTPUT_DIR + "/color.png"
@@ -255,47 +252,15 @@ def colorize():
255
 
256
  return send_file(path, mimetype="image/png")
257
 
258
- # ======================================================
259
- # STUDIO PRO
260
- # ======================================================
261
-
262
- @app.route("/studio_pro", methods=["POST"])
263
- def studio_pro():
264
-
265
- data = request.json
266
- prompt = translate_prompt(data["prompt"])
267
-
268
- prompts = [
269
- prompt + ", luxury studio lighting",
270
- prompt + ", product on marble table",
271
- prompt + ", premium advertising photo",
272
- prompt + ", instagram product ad",
273
- prompt + ", minimal product photography"
274
- ]
275
-
276
- results = []
277
-
278
- for p in prompts:
279
-
280
- img = pipe(p).images[0]
281
-
282
- path = OUTPUT_DIR + "/" + str(len(results)) + ".png"
283
- img.save(path)
284
-
285
- results.append(path)
286
-
287
- return jsonify(results)
288
-
289
- # ======================================================
290
  # START SERVER
291
- # ======================================================
292
 
293
  if __name__ == "__main__":
294
 
295
- print("IMAGE PRO API READY")
296
 
297
  app.run(
298
  host="0.0.0.0",
299
- port=7860,
300
- debug=False
301
  )
 
1
  import os
 
2
  import torch
3
+ from flask import Flask, request, send_file, jsonify, render_template_string
4
+ from diffusers import StableDiffusionPipeline
5
  from PIL import Image, ImageFilter
6
  from deep_translator import GoogleTranslator
7
 
8
  print("IMAGE PRO AI STARTING...")
9
 
10
+ CACHE_DIR = "./models"
 
 
 
 
11
  OUTPUT_DIR = "outputs"
12
 
13
  os.makedirs(OUTPUT_DIR, exist_ok=True)
 
17
  # ===============================
18
 
19
  def translate_prompt(prompt):
20
+
21
  try:
22
  prompt_en = GoogleTranslator(source="pl", target="en").translate(prompt)
23
  print("PL:", prompt)
 
26
  except:
27
  return prompt
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  # ===============================
30
  # LOAD MODEL
31
  # ===============================
32
 
33
+ print("Loading model...")
34
 
35
  pipe = StableDiffusionPipeline.from_pretrained(
36
  "SG161222/Realistic_Vision_V5.1_noVAE",
37
  cache_dir=CACHE_DIR,
38
  torch_dtype=torch.float32,
39
+ safety_checker=None
 
40
  )
41
 
42
  pipe.enable_attention_slicing()
 
49
 
50
  app = Flask(__name__)
51
 
52
+ # ===============================
53
+ # HTML PANEL
54
+ # ===============================
55
+
56
+ HTML = """
57
 
 
 
58
  <html>
59
+
60
  <head>
61
+
62
  <title>IMAGE PRO AI</title>
63
+
64
  <style>
65
+
66
+ body{
67
+ background:black;
68
+ color:white;
69
+ font-family:Arial;
70
+ text-align:center;
71
+ }
72
+
73
+ input{
74
+ width:400px;
75
+ padding:10px;
76
+ }
77
+
78
+ button{
79
+ padding:10px 20px;
80
+ background:orange;
81
+ border:none;
82
+ color:white;
83
+ font-size:16px;
84
+ cursor:pointer;
85
+ }
86
+
87
+ img{
88
+ margin-top:20px;
89
+ max-width:512px;
90
+ }
91
+
92
  </style>
93
+
94
  </head>
95
+
96
  <body>
97
 
98
  <h1>IMAGE PRO AI</h1>
99
 
100
+ <input id="prompt" placeholder="np. truskawka na stole"/>
 
101
  <br><br>
 
 
102
 
103
+ <button onclick="generate()">GENERUJ</button>
104
+
105
  <h2>Wynik</h2>
 
 
106
 
107
+ <img id="result"/>
 
 
108
 
109
+ <script>
 
 
110
 
111
+ async function generate(){
 
 
112
 
113
+ prompt = document.getElementById("prompt").value
 
114
 
115
+ response = await fetch("/generate",{
 
116
 
117
+ method:"POST",
 
 
 
 
118
 
119
+ headers:{
120
+ "Content-Type":"application/json"
121
+ },
122
+
123
+ body:JSON.stringify({
124
+ prompt:prompt
125
+ })
126
+
127
+ })
128
+
129
+ blob = await response.blob()
130
+
131
+ url = URL.createObjectURL(blob)
132
 
133
+ document.getElementById("result").src = url
 
 
 
134
 
135
+ }
 
 
136
 
137
+ </script>
138
+
139
+ </body>
140
+
141
+ </html>
142
+
143
+ """
144
+
145
+ # ===============================
146
+ # HOME
147
+ # ===============================
148
+
149
+ @app.route("/")
150
+ def home():
151
+ return render_template_string(HTML)
152
+
153
+ # ===============================
154
+ # GENERATE IMAGE
155
+ # ===============================
156
 
157
  @app.route("/generate", methods=["POST"])
158
  def generate():
 
167
  ).images[0]
168
 
169
  path = OUTPUT_DIR + "/gen.png"
170
+
171
  image.save(path)
172
 
173
  return send_file(path, mimetype="image/png")
174
 
175
+ # ===============================
176
  # PRODUCT AD
177
+ # ===============================
178
 
179
  @app.route("/product_ad", methods=["POST"])
180
  def product_ad():
181
 
182
  data = request.json
183
+
184
  prompt = translate_prompt(data["prompt"])
185
 
186
+ style = prompt + ", luxury product photography"
 
187
 
188
+ image = pipe(style).images[0]
 
189
 
190
+ path = OUTPUT_DIR + "/product.png"
 
191
 
192
+ image.save(path)
 
193
 
194
+ return send_file(path, mimetype="image/png")
 
 
 
195
 
196
+ # ===============================
197
  # RESTORE PHOTO
198
+ # ===============================
199
 
200
  @app.route("/restore", methods=["POST"])
201
  def restore():
 
203
  file = request.files["image"]
204
 
205
  img = Image.open(file.stream)
206
+
207
  img = img.filter(ImageFilter.SHARPEN)
208
 
209
  path = OUTPUT_DIR + "/restored.png"
 
212
 
213
  return send_file(path, mimetype="image/png")
214
 
215
+ # ===============================
216
+ # UPSCALE
217
+ # ===============================
218
 
219
  @app.route("/upscale", methods=["POST"])
220
  def upscale():
 
223
 
224
  img = Image.open(file.stream)
225
 
226
+ w,h = img.size
227
 
228
+ img = img.resize((w*2,h*2), Image.LANCZOS)
 
 
 
229
 
230
  path = OUTPUT_DIR + "/hd.png"
231
 
 
233
 
234
  return send_file(path, mimetype="image/png")
235
 
236
+ # ===============================
237
  # COLORIZE
238
+ # ===============================
239
 
240
  @app.route("/colorize", methods=["POST"])
241
  def colorize():
 
243
  file = request.files["image"]
244
 
245
  img = Image.open(file.stream)
246
+
247
  img = img.convert("RGB")
248
 
249
  path = OUTPUT_DIR + "/color.png"
 
252
 
253
  return send_file(path, mimetype="image/png")
254
 
255
+ # ===============================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  # START SERVER
257
+ # ===============================
258
 
259
  if __name__ == "__main__":
260
 
261
+ print("SERVER READY")
262
 
263
  app.run(
264
  host="0.0.0.0",
265
+ port=7860
 
266
  )