Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
from flask import Flask, request, jsonify, send_file, render_template_string, make_response
|
2 |
-
import
|
|
|
3 |
import io
|
4 |
import random
|
5 |
from PIL import Image
|
@@ -7,63 +8,49 @@ from deep_translator import GoogleTranslator
|
|
7 |
|
8 |
app = Flask(__name__)
|
9 |
|
10 |
-
|
11 |
-
|
|
|
12 |
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
15 |
if not prompt:
|
16 |
return None, "Prompt is required"
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
# Translate the prompt from Russian to English if necessary
|
21 |
prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
|
22 |
-
print(f
|
23 |
|
24 |
-
# Add
|
25 |
prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
image_bytes = response.content
|
49 |
-
image = Image.open(io.BytesIO(image_bytes))
|
50 |
-
return image, None
|
51 |
-
except requests.exceptions.Timeout:
|
52 |
-
if attempt < 2: # 最後の試行でない場合は再試行
|
53 |
-
print("Timeout occurred, retrying...")
|
54 |
-
continue
|
55 |
-
return None, "Error: The request timed out. Please try again."
|
56 |
-
except requests.exceptions.RequestException as e:
|
57 |
-
return None, f"Request Exception: {str(e)}"
|
58 |
-
except Exception as e:
|
59 |
-
return None, f"Error when trying to open the image: {e}"
|
60 |
-
|
61 |
-
# Content-Security-Policyヘッダーを設定するための関数
|
62 |
@app.after_request
|
63 |
def add_security_headers(response):
|
64 |
response.headers['Content-Security-Policy'] = (
|
65 |
"default-src 'self'; "
|
66 |
-
"connect-src 'self' ^https?:\/\/[\w.-]+\.[\w.-]+(\/[\w.-]*)*(\?[^\s]*)?$"
|
67 |
"img-src 'self' data:; "
|
68 |
"style-src 'self' 'unsafe-inline'; "
|
69 |
"script-src 'self' 'unsafe-inline'; "
|
@@ -74,7 +61,17 @@ def add_security_headers(response):
|
|
74 |
index_html = """
|
75 |
<!DOCTYPE html>
|
76 |
<html lang="ja">
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
</html>
|
79 |
"""
|
80 |
|
@@ -83,22 +80,22 @@ def index():
|
|
83 |
return render_template_string(index_html)
|
84 |
|
85 |
@app.route('/generate', methods=['GET'])
|
86 |
-
def
|
87 |
prompt = request.args.get("prompt", "")
|
88 |
negative_prompt = request.args.get("negative_prompt", "")
|
89 |
steps = int(request.args.get("steps", 35))
|
90 |
-
cfg_scale = float(request.args.get("
|
91 |
-
sampler = request.args.get("sampler", "DPM++ 2M Karras")
|
92 |
-
strength = float(request.args.get("strength", 0.7))
|
93 |
seed = int(request.args.get("seed", -1))
|
94 |
width = int(request.args.get("width", 1024))
|
95 |
height = int(request.args.get("height", 1024))
|
96 |
|
97 |
-
|
|
|
98 |
|
99 |
if error:
|
100 |
return jsonify({"error": error}), 400
|
101 |
|
|
|
102 |
img_bytes = io.BytesIO()
|
103 |
image.save(img_bytes, format='PNG')
|
104 |
img_bytes.seek(0)
|
|
|
1 |
from flask import Flask, request, jsonify, send_file, render_template_string, make_response
|
2 |
+
import torch
|
3 |
+
from diffusers import StableDiffusionPipeline
|
4 |
import io
|
5 |
import random
|
6 |
from PIL import Image
|
|
|
8 |
|
9 |
app = Flask(__name__)
|
10 |
|
11 |
+
# Load the model once globally
|
12 |
+
model_id = "Ojimi/anime-kawai-diffusion" # Replace with appropriate model if needed
|
13 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
14 |
|
15 |
+
print(f"Using device: {device}")
|
16 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to(device)
|
17 |
+
|
18 |
+
# Function to generate the image locally using the Diffusers pipeline
|
19 |
+
def generate_image_locally(prompt, negative_prompt="", steps=35, cfg_scale=7, seed=-1, width=1024, height=1024):
|
20 |
if not prompt:
|
21 |
return None, "Prompt is required"
|
22 |
|
23 |
+
# Translate the prompt from Russian to English (if needed)
|
|
|
|
|
24 |
prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
|
25 |
+
print(f"Translated prompt: {prompt}")
|
26 |
|
27 |
+
# Add artistic flair to the prompt
|
28 |
prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
|
29 |
+
|
30 |
+
# Set random seed if not provided
|
31 |
+
generator = torch.manual_seed(seed if seed != -1 else random.randint(1, 1000000000))
|
32 |
+
|
33 |
+
try:
|
34 |
+
# Generate the image using the Diffusers pipeline
|
35 |
+
image = pipe(
|
36 |
+
prompt=prompt,
|
37 |
+
negative_prompt=negative_prompt,
|
38 |
+
num_inference_steps=steps,
|
39 |
+
guidance_scale=cfg_scale,
|
40 |
+
generator=generator,
|
41 |
+
height=height,
|
42 |
+
width=width,
|
43 |
+
).images[0]
|
44 |
+
|
45 |
+
return image, None
|
46 |
+
except Exception as e:
|
47 |
+
return None, f"Error generating image: {str(e)}"
|
48 |
+
|
49 |
+
# Content-Security-Policy headers for added security
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
@app.after_request
|
51 |
def add_security_headers(response):
|
52 |
response.headers['Content-Security-Policy'] = (
|
53 |
"default-src 'self'; "
|
|
|
54 |
"img-src 'self' data:; "
|
55 |
"style-src 'self' 'unsafe-inline'; "
|
56 |
"script-src 'self' 'unsafe-inline'; "
|
|
|
61 |
index_html = """
|
62 |
<!DOCTYPE html>
|
63 |
<html lang="ja">
|
64 |
+
<head>
|
65 |
+
<title>Kawai Diffusion</title>
|
66 |
+
</head>
|
67 |
+
<body>
|
68 |
+
<h1>Welcome to Kawai Diffusion</h1>
|
69 |
+
<form action="/generate" method="get">
|
70 |
+
<label for="prompt">Prompt:</label>
|
71 |
+
<input type="text" id="prompt" name="prompt" required><br><br>
|
72 |
+
<button type="submit">Generate</button>
|
73 |
+
</form>
|
74 |
+
</body>
|
75 |
</html>
|
76 |
"""
|
77 |
|
|
|
80 |
return render_template_string(index_html)
|
81 |
|
82 |
@app.route('/generate', methods=['GET'])
|
83 |
+
def generate():
|
84 |
prompt = request.args.get("prompt", "")
|
85 |
negative_prompt = request.args.get("negative_prompt", "")
|
86 |
steps = int(request.args.get("steps", 35))
|
87 |
+
cfg_scale = float(request.args.get("cfg_scale", 7))
|
|
|
|
|
88 |
seed = int(request.args.get("seed", -1))
|
89 |
width = int(request.args.get("width", 1024))
|
90 |
height = int(request.args.get("height", 1024))
|
91 |
|
92 |
+
# Generate the image locally
|
93 |
+
image, error = generate_image_locally(prompt, negative_prompt, steps, cfg_scale, seed, width, height)
|
94 |
|
95 |
if error:
|
96 |
return jsonify({"error": error}), 400
|
97 |
|
98 |
+
# Send the generated image as a PNG file
|
99 |
img_bytes = io.BytesIO()
|
100 |
image.save(img_bytes, format='PNG')
|
101 |
img_bytes.seek(0)
|