File size: 2,311 Bytes
f424b43
9b82858
 
 
 
 
 
 
 
 
 
 
6a53e9c
9b82858
 
 
 
 
f424b43
 
6a53e9c
9b82858
 
 
6a53e9c
9b82858
f424b43
 
9b82858
f424b43
9b82858
f424b43
 
 
 
 
9b82858
f424b43
 
 
9b82858
f424b43
9b82858
f424b43
 
9b82858
 
6a53e9c
9b82858
 
 
 
 
 
f424b43
 
6a53e9c
9b82858
 
 
6a53e9c
9b82858
f424b43
 
9b82858
f424b43
9b82858
f424b43
 
9b82858
 
 
 
f424b43
 
 
9b82858
f424b43
9b82858
f424b43
 
9b82858
 
6a53e9c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import asyncio
from flask import Flask, render_template, request, send_file, jsonify
from imaginepy import AsyncImagine, Style, Ratio
import os

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/generate', methods=['POST'])
async def generate_image():
    prompt = request.form['prompt']
    style = request.form['style']
    ratio = request.form['ratio']

    try:
        imagine = AsyncImagine()

        img_data = await imagine.sdprem(
            prompt=prompt,
            style=Style[style],
            ratio=Ratio[ratio]
        )

        if img_data is None:
            return "An error occurred while generating the image.", 500

        img_data = await imagine.upscale(image=img_data)

        if img_data is None:
            return "An error occurred while upscaling the image.", 500

        image_path = os.path.join(app.root_path, "static", "example.jpeg")
        with open(image_path, mode="wb") as img_file:
            img_file.write(img_data)

        return render_template('output.html')

    except Exception as e:
        return f"An error occurred: {e}", 500

    finally:
        await imagine.close()

@app.route('/api/generate', methods=['POST'])
async def api_generate_image():
    data = request.get_json()
    prompt = data['prompt']
    style = data['style']
    ratio = data['ratio']

    try:
        imagine = AsyncImagine()

        img_data = await imagine.sdprem(
            prompt=prompt,
            style=Style[style],
            ratio=Ratio[ratio]
        )

        if img_data is None:
            return jsonify({'error': "An error occurred while generating the image."}), 500

        img_data = await imagine.upscale(image=img_data)

        if img_data is None:
            return jsonify({'error': "An error occurred while upscaling the image."}), 500

        image_path = os.path.join(app.root_path, "generated.jpeg")
        with open(image_path, mode="wb") as img_file:
            img_file.write(img_data)

        return send_file(image_path, mimetype='image/jpeg', as_attachment=True)

    except Exception as e:
        return jsonify({'error': f"An error occurred: {e}"}), 500

    finally:
        await imagine.close()

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)