soiz commited on
Commit
725dd48
1 Parent(s): 2e4ca03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -104
app.py CHANGED
@@ -1,67 +1,3 @@
1
- from flask import Flask, request, jsonify, send_file, render_template_string
2
- import requests
3
- import io
4
- import os
5
- import random
6
- from PIL import Image
7
- from deep_translator import GoogleTranslator
8
-
9
- app = Flask(__name__)
10
-
11
- API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev"
12
- API_TOKEN = os.getenv("HF_READ_TOKEN")
13
- headers = {"Authorization": f"Bearer {API_TOKEN}"}
14
- timeout = 300 # タイムアウトを300秒に設定
15
-
16
- # Function to query the API and return the generated image
17
- def query(prompt, negative_prompt="", steps=35, cfg_scale=7, sampler="DPM++ 2M Karras", seed=-1, strength=0.7, width=1024, height=1024):
18
- if not prompt:
19
- return None, "Prompt is required"
20
-
21
- key = random.randint(0, 999)
22
-
23
- # Translate the prompt from Russian to English if necessary
24
- prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
25
- print(f'Generation {key} translation: {prompt}')
26
-
27
- # Add some extra flair to the prompt
28
- prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
29
- print(f'Generation {key}: {prompt}')
30
-
31
- payload = {
32
- "inputs": prompt,
33
- "is_negative": False,
34
- "steps": steps,
35
- "cfg_scale": cfg_scale,
36
- "seed": seed if seed != -1 else random.randint(1, 1000000000),
37
- "strength": strength,
38
- "parameters": {
39
- "width": width,
40
- "height": height
41
- }
42
- }
43
-
44
- for attempt in range(3): # 最大3回の再試行
45
- try:
46
- response = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
47
- if response.status_code != 200:
48
- return None, f"Error: Failed to get image. Status code: {response.status_code}, Details: {response.text}"
49
-
50
- image_bytes = response.content
51
- image = Image.open(io.BytesIO(image_bytes))
52
- return image, None
53
- except requests.exceptions.Timeout:
54
- if attempt < 2: # 最後の試行でない場合は再試行
55
- print("Timeout occurred, retrying...")
56
- continue
57
- return None, "Error: The request timed out. Please try again."
58
- except requests.exceptions.RequestException as e:
59
- return None, f"Request Exception: {str(e)}"
60
- except Exception as e:
61
- return None, f"Error when trying to open the image: {e}"
62
-
63
- # HTML template for the index page
64
- index_html = """
65
  <!DOCTYPE html>
66
  <html lang="ja">
67
  <head>
@@ -82,14 +18,14 @@ index_html = """
82
  </style>
83
  <script>
84
  let isDrawing = false;
85
- let x = 0;
86
- let y = 0;
87
  let penSize = 5;
88
  let penColor = '#000000';
89
 
90
  function startDrawing(event) {
91
  isDrawing = true;
92
- [x, y] = getMousePos(event);
93
  }
94
 
95
  function draw(event) {
@@ -100,14 +36,14 @@ index_html = """
100
  const [newX, newY] = getMousePos(event);
101
 
102
  ctx.beginPath();
103
- ctx.moveTo(x, y);
104
  ctx.lineTo(newX, newY);
105
  ctx.strokeStyle = penColor;
106
  ctx.lineWidth = penSize;
107
  ctx.stroke();
108
  ctx.closePath();
109
 
110
- [x, y] = [newX, newY];
111
  }
112
 
113
  function stopDrawing() {
@@ -222,7 +158,7 @@ index_html = """
222
  <textarea id="negative_prompt" name="negative_prompt" rows="4" cols="50" placeholder="Enter negative prompt (optional)">(deformed, distorted, disfigured), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, misspellings, typos</textarea><br><br>
223
 
224
  <label for="width">Width:</label>
225
- <input type="number" id="width" name="width" value="1024" min="64" max="2048" step="8" style="width:250px" oninput="syncWidth(this.value)">
226
  <input type="range" id="width-slider" name="width-slider" min="64" max="2048" value="1024" step="8" style="width:250px; display: inline-block;" oninput="updateWidthInput()"><br><br>
227
 
228
  <label for="height">Height:</label>
@@ -279,37 +215,3 @@ index_html = """
279
  </script>
280
  </body>
281
  </html>
282
-
283
- """
284
-
285
- @app.route('/')
286
- def index():
287
- return render_template_string(index_html)
288
-
289
- @app.route('/generate', methods=['GET'])
290
- def generate_image():
291
- # Retrieve query parameters
292
- prompt = request.args.get("prompt", "")
293
- negative_prompt = request.args.get("negative_prompt", "")
294
- steps = int(request.args.get("steps", 35))
295
- cfg_scale = float(request.args.get("cfgs", 7))
296
- sampler = request.args.get("sampler", "DPM++ 2M Karras")
297
- strength = float(request.args.get("strength", 0.7))
298
- seed = int(request.args.get("seed", -1))
299
- width = int(request.args.get("width", 1024))
300
- height = int(request.args.get("height", 1024))
301
-
302
- # Call the query function to generate the image
303
- image, error = query(prompt, negative_prompt, steps, cfg_scale, sampler, seed, strength, width, height)
304
-
305
- if error:
306
- return jsonify({"error": error}), 400
307
-
308
- # Save the image to a BytesIO object and return it
309
- img_bytes = io.BytesIO()
310
- image.save(img_bytes, format='PNG')
311
- img_bytes.seek(0)
312
- return send_file(img_bytes, mimetype='image/png')
313
-
314
- if __name__ == "__main__":
315
- app.run(host='0.0.0.0', port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <!DOCTYPE html>
2
  <html lang="ja">
3
  <head>
 
18
  </style>
19
  <script>
20
  let isDrawing = false;
21
+ let lastX = 0;
22
+ let lastY = 0;
23
  let penSize = 5;
24
  let penColor = '#000000';
25
 
26
  function startDrawing(event) {
27
  isDrawing = true;
28
+ [lastX, lastY] = getMousePos(event);
29
  }
30
 
31
  function draw(event) {
 
36
  const [newX, newY] = getMousePos(event);
37
 
38
  ctx.beginPath();
39
+ ctx.moveTo(lastX, lastY);
40
  ctx.lineTo(newX, newY);
41
  ctx.strokeStyle = penColor;
42
  ctx.lineWidth = penSize;
43
  ctx.stroke();
44
  ctx.closePath();
45
 
46
+ [lastX, lastY] = [newX, newY]; // 新しい位置を保存
47
  }
48
 
49
  function stopDrawing() {
 
158
  <textarea id="negative_prompt" name="negative_prompt" rows="4" cols="50" placeholder="Enter negative prompt (optional)">(deformed, distorted, disfigured), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, misspellings, typos</textarea><br><br>
159
 
160
  <label for="width">Width:</label>
161
+ <input type="number" id="width" name="width" value="1024" min="64" max="2048" step="8">
162
  <input type="range" id="width-slider" name="width-slider" min="64" max="2048" value="1024" step="8" style="width:250px; display: inline-block;" oninput="updateWidthInput()"><br><br>
163
 
164
  <label for="height">Height:</label>
 
215
  </script>
216
  </body>
217
  </html>