soiz commited on
Commit
1eae35f
1 Parent(s): e58623d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -46
app.py CHANGED
@@ -1,76 +1,112 @@
1
  from flask import Flask, request, jsonify, send_file, render_template_string
 
2
  import io
3
- from PIL import Image, ImageDraw, ImageFont
 
 
4
 
5
  app = Flask(__name__)
6
 
7
- # Function to generate a simple image with text using PIL
8
- def generate_image_with_text(prompt, width, height):
9
- # Create an image with a white background and specified dimensions
10
- img = Image.new('RGB', (width, height), color='white')
11
- draw = ImageDraw.Draw(img)
12
 
13
- # Load a font
14
- try:
15
- font = ImageFont.truetype("arial.ttf", 40) # Use a truetype font
16
- except IOError:
17
- font = ImageFont.load_default() # Use default if arial is not available
18
 
19
- # Draw the prompt text onto the image
20
- draw.text((50, height // 2), prompt, fill="black", font=font)
 
21
 
22
- return img
 
 
23
 
24
- # HTML template for the index page
25
- index_html = """
26
- <!DOCTYPE html>
27
- <html lang="ja">
28
- <head>
29
- <meta charset="UTF-8">
30
- <title>Kawai Diffusion</title>
31
- </head>
32
- <body>
33
- <h1>Kawai Diffusion</h1>
34
- <form action="/generate" method="get">
35
- <input type="text" name="prompt" placeholder="Enter your prompt" required>
36
- <input type="text" name="negative_prompt" placeholder="Enter negative prompt (optional)">
37
- <input type="number" name="steps" placeholder="Steps" value="35">
38
- <input type="number" name="cfgs" placeholder="CFG Scale" value="7" step="0.1">
39
- <input type="text" name="sampler" placeholder="Sampler" value="DPM++ 2M Karras">
40
- <input type="number" name="strength" placeholder="Strength" value="0.7" step="0.1">
41
- <input type="number" name="seed" placeholder="Seed" value="-1">
42
- <input type="number" name="width" placeholder="Width" value="1024">
43
- <input type="number" name="height" placeholder="Height" value="1024">
44
- <button type="submit">Generate Image</button>
45
- </form>
46
- </body>
47
- </html>
48
- """
 
 
 
 
 
 
49
 
50
  @app.route('/')
51
  def index():
52
- return render_template_string(index_html)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  @app.route('/generate', methods=['GET'])
55
  def generate_image():
56
  prompt = request.args.get("prompt", "")
57
  negative_prompt = request.args.get("negative_prompt", "bad hands, low quality, low quality, unnatural, dirty eyes, distorted eyes, low quality eyes, distorted arms, distorted legs, distorted face, 3 legs, 3 hands, anatomically Bad, 6 fingers, 7 fingers, less fingers, more fingers,")
58
  steps = int(request.args.get("steps", 35))
59
- cfg_scale = float(request.args.get("cfgs", 7))
60
- sampler = request.args.get("sampler", "DPM++ 2M Karras")
61
  strength = float(request.args.get("strength", 0.7))
62
  seed = int(request.args.get("seed", -1))
63
  width = int(request.args.get("width", 1024))
64
  height = int(request.args.get("height", 1024))
65
 
66
- # Generate the image with the provided prompt and dimensions
67
- image = generate_image_with_text(prompt, width, height)
 
 
68
 
69
- # Save the image to a bytes buffer
70
  img_bytes = io.BytesIO()
71
  image.save(img_bytes, format='PNG')
72
  img_bytes.seek(0)
73
-
74
  return send_file(img_bytes, mimetype='image/png')
75
 
76
  if __name__ == "__main__":
 
1
  from flask import Flask, request, jsonify, send_file, render_template_string
2
+ import requests
3
  import io
4
+ import random
5
+ from PIL import Image
6
+ from deep_translator import GoogleTranslator
7
 
8
  app = Flask(__name__)
9
 
10
+ API_URL = "https://api-inference.huggingface.co/models/Ojimi/anime-kawai-diffusion"
11
+ timeout = 3000 # Set timeout to 300 seconds
 
 
 
12
 
13
+ def query(prompt, negative_prompt="", steps=35, cfg_scale=7, sampler="DPM++ 2M Karras", seed=-1, strength=0.7, width=1024, height=1024):
14
+ if not prompt:
15
+ return None, "Prompt is required"
 
 
16
 
17
+ # Translate prompt from Russian to English if needed
18
+ prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
19
+ print(f'Translated prompt: {prompt}')
20
 
21
+ # Enhance the prompt
22
+ prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
23
+ print(f'Final prompt: {prompt}')
24
 
25
+ payload = {
26
+ "inputs": prompt,
27
+ "is_negative": False,
28
+ "steps": steps,
29
+ "cfg_scale": cfg_scale,
30
+ "seed": seed if seed != -1 else random.randint(1, 1000000000),
31
+ "strength": strength,
32
+ "parameters": {
33
+ "width": width,
34
+ "height": height
35
+ }
36
+ }
37
+
38
+ for attempt in range(3):
39
+ try:
40
+ response = requests.post(API_URL, json=payload, timeout=timeout)
41
+ if response.status_code != 200:
42
+ return None, f"Error: Failed to get image. Status code: {response.status_code}, Details: {response.text}"
43
+
44
+ image_bytes = response.content
45
+ image = Image.open(io.BytesIO(image_bytes))
46
+ return image, None
47
+ except requests.exceptions.Timeout:
48
+ if attempt < 2:
49
+ print("Timeout occurred, retrying...")
50
+ continue
51
+ return None, "Error: The request timed out. Please try again."
52
+ except requests.exceptions.RequestException as e:
53
+ return None, f"Request Exception: {str(e)}"
54
+ except Exception as e:
55
+ return None, f"Error when trying to open the image: {e}"
56
 
57
  @app.route('/')
58
  def index():
59
+ return render_template_string("""
60
+ <!DOCTYPE html>
61
+ <html lang="ja">
62
+ <head>
63
+ <meta charset="UTF-8">
64
+ <title>Image Generator</title>
65
+ </head>
66
+ <body>
67
+ <h1>Kawaii Diffusion Image Generator</h1>
68
+ <form action="/generate" method="get">
69
+ <label for="prompt">Prompt:</label><br>
70
+ <input type="text" id="prompt" name="prompt" required><br>
71
+ <label for="negative_prompt">Negative Prompt:</label><br>
72
+ <input type="text" id="negative_prompt" name="negative_prompt"><br>
73
+ <label for="steps">Steps:</label><br>
74
+ <input type="number" id="steps" name="steps" value="35"><br>
75
+ <label for="cfg_scale">CFG Scale:</label><br>
76
+ <input type="number" step="0.1" id="cfg_scale" name="cfg_scale" value="7"><br>
77
+ <label for="strength">Strength:</label><br>
78
+ <input type="number" step="0.1" id="strength" name="strength" value="0.7"><br>
79
+ <label for="seed">Seed:</label><br>
80
+ <input type="number" id="seed" name="seed" value="-1"><br>
81
+ <label for="width">Width:</label><br>
82
+ <input type="number" id="width" name="width" value="1024"><br>
83
+ <label for="height">Height:</label><br>
84
+ <input type="number" id="height" name="height" value="1024"><br><br>
85
+ <input type="submit" value="Generate">
86
+ </form>
87
+ </body>
88
+ </html>
89
+ """)
90
 
91
  @app.route('/generate', methods=['GET'])
92
  def generate_image():
93
  prompt = request.args.get("prompt", "")
94
  negative_prompt = request.args.get("negative_prompt", "bad hands, low quality, low quality, unnatural, dirty eyes, distorted eyes, low quality eyes, distorted arms, distorted legs, distorted face, 3 legs, 3 hands, anatomically Bad, 6 fingers, 7 fingers, less fingers, more fingers,")
95
  steps = int(request.args.get("steps", 35))
96
+ cfg_scale = float(request.args.get("cfg_scale", 7))
 
97
  strength = float(request.args.get("strength", 0.7))
98
  seed = int(request.args.get("seed", -1))
99
  width = int(request.args.get("width", 1024))
100
  height = int(request.args.get("height", 1024))
101
 
102
+ image, error = query(prompt, negative_prompt, steps, cfg_scale, seed=seed, strength=strength, width=width, height=height)
103
+
104
+ if error:
105
+ return jsonify({"error": error}), 400
106
 
 
107
  img_bytes = io.BytesIO()
108
  image.save(img_bytes, format='PNG')
109
  img_bytes.seek(0)
 
110
  return send_file(img_bytes, mimetype='image/png')
111
 
112
  if __name__ == "__main__":