soiz commited on
Commit
9cdcff4
1 Parent(s): edd863d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -0
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # Install Flask if not already installed
4
+ return_code = os.system('pip install flask')
5
+ if return_code != 0:
6
+ raise RuntimeError("Failed to install Flask")
7
+
8
+ import gradio as gr
9
+ from random import randint
10
+ from all_models import models
11
+ from flask import Flask, request, send_file
12
+ from io import BytesIO
13
+ from PIL import Image
14
+
15
+ app = Flask(__name__)
16
+
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}')
25
+ models_load[model] = m
26
+ print(f"Loaded model: {model}")
27
+ except Exception as error:
28
+ print(f"Error loading model {model}: {error}")
29
+ m = gr.Interface(lambda txt: None, ['text'], ['image'])
30
+ models_load[model] = m
31
+
32
+ load_fn(models)
33
+
34
+ num_models = 6
35
+ default_models = models[:num_models]
36
+
37
+ def extend_choices(choices):
38
+ return choices + (num_models - len(choices)) * ['NA']
39
+
40
+ def update_imgbox(choices):
41
+ choices_plus = extend_choices(choices)
42
+ return [gr.Image(None, label=m, visible=(m != 'NA')) for m in choices_plus]
43
+
44
+ def gen_fn(model_str, prompt, negative_prompt=None):
45
+ if model_str == 'NA':
46
+ return None
47
+ noise = str('') # Optional: str(randint(0, 99999999999))
48
+ try:
49
+ full_prompt = f'{prompt} {noise}'
50
+ if negative_prompt:
51
+ full_prompt += f' -{negative_prompt}'
52
+ result = models_load[model_str](full_prompt)
53
+ # Check if result is an image or a file path
54
+ if isinstance(result, str): # Assuming result might be a file path
55
+ if os.path.exists(result):
56
+ return Image.open(result)
57
+ else:
58
+ print(f"File path not found: {result}")
59
+ return None
60
+ elif isinstance(result, Image.Image):
61
+ return result
62
+ else:
63
+ print("Result is not an image:", type(result))
64
+ return None
65
+ except Exception as e:
66
+ print("Error generating image:", e)
67
+ return None
68
+
69
+ @app.route('/', methods=['GET'])
70
+ def home():
71
+ prompt = request.args.get('prompt', '')
72
+ model = request.args.get('model', default_models[0] if default_models else 'NA')
73
+ negative_prompt = request.args.get('Nprompt', None)
74
+
75
+ if not model or model not in models_load:
76
+ return f'Invalid model: {model}', 400
77
+
78
+ if prompt:
79
+ # Generate the image
80
+ image = gen_fn(model, prompt, negative_prompt)
81
+ if isinstance(image, Image.Image): # Ensure the result is a PIL image
82
+ # Save image to BytesIO object
83
+ img_io = BytesIO()
84
+ image.save(img_io, format='PNG')
85
+ img_io.seek(0)
86
+ return send_file(img_io, mimetype='image/png', as_attachment=False)
87
+ return 'Failed to generate image.', 500
88
+ return 'Please provide a "prompt" query parameter in the URL.', 400
89
+
90
+ if __name__ == '__main__':
91
+ # Launch Flask app
92
+ app.run(host='0.0.0.0', port=7860) # Run Flask app