soiz commited on
Commit
95d6160
1 Parent(s): 2729a09

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -51
app.py CHANGED
@@ -1,6 +1,5 @@
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,49 +7,63 @@ from deep_translator import GoogleTranslator
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,17 +74,7 @@ def add_security_headers(response):
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,26 +83,26 @@ def index():
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)
102
  return send_file(img_bytes, mimetype='image/png')
103
 
104
  if __name__ == "__main__":
105
- app.run(host='0.0.0.0', port=7860)
 
1
  from flask import Flask, request, jsonify, send_file, render_template_string, make_response
2
+ import requests
 
3
  import io
4
  import random
5
  from PIL import Image
 
7
 
8
  app = Flask(__name__)
9
 
10
+ API_URL = "https://api-inference.huggingface.co/models/Ojimi/anime-kawai-diffusion"
11
+ timeout = 3000 # タイムアウトを300秒に設定
 
12
 
13
+ # Function to query the API and return the generated image
14
+ def query(prompt, negative_prompt="", steps=35, cfg_scale=7, sampler="DPM++ 2M Karras", seed=-1, strength=0.7, width=1024, height=1024):
 
 
 
15
  if not prompt:
16
  return None, "Prompt is required"
17
 
18
+ key = random.randint(0, 999)
19
+
20
+ # Translate the prompt from Russian to English if necessary
21
  prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
22
+ print(f'Generation {key} translation: {prompt}')
23
 
24
+ # Add some extra flair to the prompt
25
  prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
26
+ print(f'Generation {key}: {prompt}')
27
+
28
+ payload = {
29
+ "inputs": prompt,
30
+ "is_negative": False,
31
+ "steps": steps,
32
+ "cfg_scale": cfg_scale,
33
+ "seed": seed if seed != -1 else random.randint(1, 1000000000),
34
+ "strength": strength,
35
+ "parameters": {
36
+ "width": width,
37
+ "height": height
38
+ }
39
+ }
40
+
41
+ for attempt in range(3): # 最大3回の再試行
42
+ try:
43
+ # Authorization header is removed
44
+ response = requests.post(API_URL, json=payload, timeout=timeout)
45
+ if response.status_code != 200:
46
+ return None, f"Error: Failed to get image. Status code: {response.status_code}, Details: {response.text}"
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
  index_html = """
75
  <!DOCTYPE html>
76
  <html lang="ja">
77
+ kawai diffusion
 
 
 
 
 
 
 
 
 
 
78
  </html>
79
  """
80
 
 
83
  return render_template_string(index_html)
84
 
85
  @app.route('/generate', methods=['GET'])
86
+ def generate_image():
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("cfgs", 7))
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
+ image, error = query(prompt, negative_prompt, steps, cfg_scale, sampler, seed, strength, width, height)
 
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)
105
  return send_file(img_bytes, mimetype='image/png')
106
 
107
  if __name__ == "__main__":
108
+ app.run(host='0.0.0.0', port=7860)