imseldrith commited on
Commit
9b82858
·
1 Parent(s): 318f8d9

Create test.py

Browse files
Files changed (1) hide show
  1. test.py +83 -0
test.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, send_file, jsonify
2
+ from imaginepy import AsyncImagine, Style, Ratio
3
+ import os
4
+ import asyncio
5
+
6
+ app = Flask(__name__)
7
+
8
+ @app.route('/')
9
+ def index():
10
+ return render_template('index.html')
11
+
12
+ @app.route('/generate', methods=['POST'])
13
+ def generate_image():
14
+ prompt = request.form['prompt']
15
+ style = request.form['style']
16
+ ratio = request.form['ratio']
17
+
18
+ imagine = AsyncImagine()
19
+
20
+ try:
21
+ img_data = asyncio.run(imagine.sdprem(
22
+ prompt=prompt,
23
+ style=Style[style],
24
+ ratio=Ratio[ratio]
25
+ ))
26
+ except Exception as e:
27
+ return f"An error occurred while generating the image: {e}", 500
28
+
29
+ if img_data is None:
30
+ return "An error occurred while generating the image.", 500
31
+
32
+ img_data = imagine.upscale(image=img_data)
33
+
34
+ if img_data is None:
35
+ return "An error occurred while upscaling the image.", 500
36
+
37
+ imagine.close()
38
+ try:
39
+ with open("static/example.jpeg", mode="wb") as img_file:
40
+ img_file.write(img_data)
41
+ except Exception as e:
42
+ return f"An error occurred while writing the image to file: {e}", 500
43
+
44
+ return render_template('output.html')
45
+
46
+ @app.route('/api/generate', methods=['POST'])
47
+ def api_generate_image():
48
+ data = request.get_json()
49
+ prompt = data['prompt']
50
+ style = data['style']
51
+ ratio = data['ratio']
52
+
53
+ imagine = AsyncImagine()
54
+
55
+ try:
56
+ img_data = asyncio.run(imagine.sdprem(
57
+ prompt=prompt,
58
+ style=Style[style],
59
+ ratio=Ratio[ratio]
60
+ ))
61
+ except Exception as e:
62
+ return jsonify({'error': f"An error occurred while generating the image: {e}"}), 500
63
+
64
+ if img_data is None:
65
+ return jsonify({'error': "An error occurred while generating the image."}), 500
66
+
67
+ img_data = imagine.upscale(image=img_data)
68
+
69
+ if img_data is None:
70
+ return jsonify({'error': "An error occurred while upscaling the image."}), 500
71
+
72
+ imagine.close()
73
+ try:
74
+ image_path = os.path.join(app.root_path, "generated.jpeg")
75
+ with open(image_path, mode="wb") as img_file:
76
+ img_file.write(img_data)
77
+ except Exception as e:
78
+ return jsonify({'error': f"An error occurred while writing the image to file: {e}"}), 500
79
+
80
+ return send_file(image_path, mimetype='image/jpeg', as_attachment=True)
81
+
82
+ if __name__ == "__main__":
83
+ app.run(host="0.0.0.0", port=7860)