Geek7 commited on
Commit
49b9fc0
·
verified ·
1 Parent(s): 3c7030b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -22
app.py CHANGED
@@ -6,24 +6,25 @@ from externalmod import gr_Interface_load
6
  import asyncio
7
  import os
8
  from threading import RLock
9
- import io
10
 
11
  app = Flask(__name__)
12
 
13
  lock = RLock()
14
  HF_TOKEN = os.environ.get("HF_TOKEN")
15
 
16
- # Load the models
17
  def load_fn(models):
18
  global models_load
19
  models_load = {}
 
20
  for model in models:
21
  if model not in models_load.keys():
22
  try:
23
  m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
24
  except Exception as error:
25
  print(error)
26
- m = gr.Interface(lambda: None, ['text'], ['image']) # Fallback
27
  models_load.update({model: m})
28
 
29
  load_fn(models)
@@ -33,7 +34,7 @@ MAX_SEED = 3999999999
33
  default_models = models[:num_models]
34
  inference_timeout = 600
35
 
36
- # Async inference function
37
  async def infer(model_str, prompt, seed=1, timeout=inference_timeout):
38
  kwargs = {"seed": seed}
39
  task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, prompt=prompt, **kwargs, token=HF_TOKEN))
@@ -43,34 +44,32 @@ async def infer(model_str, prompt, seed=1, timeout=inference_timeout):
43
  except (Exception, asyncio.TimeoutError) as e:
44
  print(e)
45
  print(f"Task timed out: {model_str}")
46
- if not task.done():
47
  task.cancel()
48
  result = None
49
  if task.done() and result is not None:
50
  with lock:
51
- png_path = "image.png"
52
- result.save(png_path)
53
  return png_path
54
  return None
55
 
56
- # Flask API endpoint
57
- @app.route('/async_infer', methods=['POST'])
58
- def async_infer():
59
  data = request.get_json()
60
- model_str = data.get('model_str')
61
- prompt = data.get('prompt')
62
  seed = data.get('seed', 1)
63
 
64
- # Run the inference
65
- try:
66
- image_path = asyncio.run(infer(model_str, prompt, seed))
67
- if image_path:
68
- return send_file(image_path, mimetype='image/png')
69
- else:
70
- return jsonify({"error": "Image generation failed."}), 500
71
- except Exception as e:
72
- return jsonify({"error": str(e)}), 500
73
 
74
- # Run the Flask app
75
  if __name__ == '__main__':
76
  app.run(debug=True)
 
6
  import asyncio
7
  import os
8
  from threading import RLock
9
+ from PIL import Image
10
 
11
  app = Flask(__name__)
12
 
13
  lock = RLock()
14
  HF_TOKEN = os.environ.get("HF_TOKEN")
15
 
16
+ # Load models
17
  def load_fn(models):
18
  global models_load
19
  models_load = {}
20
+
21
  for model in models:
22
  if model not in models_load.keys():
23
  try:
24
  m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
25
  except Exception as error:
26
  print(error)
27
+ m = gr.Interface(lambda: None, ['text'], ['image'])
28
  models_load.update({model: m})
29
 
30
  load_fn(models)
 
34
  default_models = models[:num_models]
35
  inference_timeout = 600
36
 
37
+ # Gradio inference function
38
  async def infer(model_str, prompt, seed=1, timeout=inference_timeout):
39
  kwargs = {"seed": seed}
40
  task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, prompt=prompt, **kwargs, token=HF_TOKEN))
 
44
  except (Exception, asyncio.TimeoutError) as e:
45
  print(e)
46
  print(f"Task timed out: {model_str}")
47
+ if not task.done():
48
  task.cancel()
49
  result = None
50
  if task.done() and result is not None:
51
  with lock:
52
+ png_path = "generated_image.png"
53
+ result.save(png_path) # Save the result as an image
54
  return png_path
55
  return None
56
 
57
+ # API function to perform inference
58
+ @app.route('/generate-image', methods=['POST'])
59
+ def generate_image():
60
  data = request.get_json()
61
+ model_str = data['model_str']
62
+ prompt = data['prompt']
63
  seed = data.get('seed', 1)
64
 
65
+ # Run Gradio inference
66
+ result_path = asyncio.run(infer(model_str, prompt, seed))
67
+
68
+ if result_path:
69
+ # Send back the generated image file
70
+ return send_file(result_path, mimetype='image/png')
71
+ else:
72
+ return jsonify({"error": "Failed to generate image."}), 500
 
73
 
 
74
  if __name__ == '__main__':
75
  app.run(debug=True)