Update app.py
Browse files
app.py
CHANGED
|
@@ -1,137 +1,164 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import base64
|
| 3 |
-
import json
|
| 4 |
-
from flask import Flask, render_template, request, jsonify
|
| 5 |
-
from flask_cors import CORS
|
| 6 |
-
import requests
|
| 7 |
-
from werkzeug.utils import secure_filename
|
| 8 |
-
import tempfile
|
| 9 |
-
|
| 10 |
-
app = Flask(__name__)
|
| 11 |
-
CORS(app)
|
| 12 |
-
|
| 13 |
-
# Configuration
|
| 14 |
-
app.config['MAX_CONTENT_LENGTH'] = 25 * 1024 * 1024 # 25MB max file size
|
| 15 |
-
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
|
| 16 |
-
|
| 17 |
-
# Get API key from environment variable
|
| 18 |
-
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
|
| 19 |
-
API_BASE_URL = os.environ.get('API_BASE_URL', 'https://api.openai.com/v1')
|
| 20 |
-
|
| 21 |
-
def allowed_file(filename):
|
| 22 |
-
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 23 |
-
|
| 24 |
-
@app.route('/')
|
| 25 |
-
def index():
|
| 26 |
-
return render_template('index.html')
|
| 27 |
-
|
| 28 |
-
@app.route('/generate', methods=['POST'])
|
| 29 |
-
def generate_image():
|
| 30 |
-
try:
|
| 31 |
-
data = request.json
|
| 32 |
-
prompt = data.get('prompt', '')
|
| 33 |
-
|
| 34 |
-
if not prompt:
|
| 35 |
-
return jsonify({'error': 'Prompt is required'}), 400
|
| 36 |
-
|
| 37 |
-
headers = {
|
| 38 |
-
'Content-Type': 'application/json',
|
| 39 |
-
'Authorization': f'Bearer {OPENAI_API_KEY}'
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
payload = {
|
| 43 |
-
'model': 'dall-e-3',
|
| 44 |
-
'prompt': prompt,
|
| 45 |
-
'n': 1,
|
| 46 |
-
'size': data.get('size', '1024x1024'),
|
| 47 |
-
'quality': data.get('quality', 'standard'),
|
| 48 |
-
'style': data.get('style', 'vivid')
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
response = requests.post(
|
| 52 |
-
f'{API_BASE_URL}/images/generations',
|
| 53 |
-
headers=headers,
|
| 54 |
-
json=payload
|
| 55 |
-
)
|
| 56 |
-
|
| 57 |
-
if response.status_code == 200:
|
| 58 |
-
result = response.json()
|
| 59 |
-
# For dall-e-3, the response contains URLs
|
| 60 |
-
image_url = result['data'][0]['url']
|
| 61 |
-
|
| 62 |
-
# Download the image and convert to base64
|
| 63 |
-
image_response = requests.get(image_url)
|
| 64 |
-
if image_response.status_code == 200:
|
| 65 |
-
image_base64 = base64.b64encode(image_response.content).decode('utf-8')
|
| 66 |
-
return jsonify({
|
| 67 |
-
'success': True,
|
| 68 |
-
'image': f'data:image/png;base64,{image_base64}',
|
| 69 |
-
'usage': result.get('usage', {})
|
| 70 |
-
})
|
| 71 |
-
else:
|
| 72 |
-
return jsonify({'error': 'Failed to download generated image'}), 500
|
| 73 |
-
else:
|
| 74 |
-
return jsonify({'error': response.json()}), response.status_code
|
| 75 |
-
|
| 76 |
-
except Exception as e:
|
| 77 |
-
return jsonify({'error': str(e)}), 500
|
| 78 |
-
|
| 79 |
-
@app.route('/edit', methods=['POST'])
|
| 80 |
-
def edit_image():
|
| 81 |
-
try:
|
| 82 |
-
# Check if
|
| 83 |
-
if '
|
| 84 |
-
return jsonify({'error': 'No
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
prompt = request.form.get('prompt', '')
|
| 88 |
-
|
| 89 |
-
if not prompt:
|
| 90 |
-
return jsonify({'error': 'Prompt is required'}), 400
|
| 91 |
-
|
| 92 |
-
if not
|
| 93 |
-
return jsonify({'error': '
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
#
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
app.run(host='0.0.0.0', port=7860, debug=True)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import base64
|
| 3 |
+
import json
|
| 4 |
+
from flask import Flask, render_template, request, jsonify
|
| 5 |
+
from flask_cors import CORS
|
| 6 |
+
import requests
|
| 7 |
+
from werkzeug.utils import secure_filename
|
| 8 |
+
import tempfile
|
| 9 |
+
|
| 10 |
+
app = Flask(__name__)
|
| 11 |
+
CORS(app)
|
| 12 |
+
|
| 13 |
+
# Configuration
|
| 14 |
+
app.config['MAX_CONTENT_LENGTH'] = 25 * 1024 * 1024 # 25MB max file size
|
| 15 |
+
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
|
| 16 |
+
|
| 17 |
+
# Get API key from environment variable
|
| 18 |
+
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
|
| 19 |
+
API_BASE_URL = os.environ.get('API_BASE_URL', 'https://api.openai.com/v1')
|
| 20 |
+
|
| 21 |
+
def allowed_file(filename):
|
| 22 |
+
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 23 |
+
|
| 24 |
+
@app.route('/')
|
| 25 |
+
def index():
|
| 26 |
+
return render_template('index.html')
|
| 27 |
+
|
| 28 |
+
@app.route('/generate', methods=['POST'])
|
| 29 |
+
def generate_image():
|
| 30 |
+
try:
|
| 31 |
+
data = request.json
|
| 32 |
+
prompt = data.get('prompt', '')
|
| 33 |
+
|
| 34 |
+
if not prompt:
|
| 35 |
+
return jsonify({'error': 'Prompt is required'}), 400
|
| 36 |
+
|
| 37 |
+
headers = {
|
| 38 |
+
'Content-Type': 'application/json',
|
| 39 |
+
'Authorization': f'Bearer {OPENAI_API_KEY}'
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
payload = {
|
| 43 |
+
'model': 'dall-e-3',
|
| 44 |
+
'prompt': prompt,
|
| 45 |
+
'n': 1,
|
| 46 |
+
'size': data.get('size', '1024x1024'),
|
| 47 |
+
'quality': data.get('quality', 'standard'),
|
| 48 |
+
'style': data.get('style', 'vivid')
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
response = requests.post(
|
| 52 |
+
f'{API_BASE_URL}/images/generations',
|
| 53 |
+
headers=headers,
|
| 54 |
+
json=payload
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if response.status_code == 200:
|
| 58 |
+
result = response.json()
|
| 59 |
+
# For dall-e-3, the response contains URLs
|
| 60 |
+
image_url = result['data'][0]['url']
|
| 61 |
+
|
| 62 |
+
# Download the image and convert to base64
|
| 63 |
+
image_response = requests.get(image_url)
|
| 64 |
+
if image_response.status_code == 200:
|
| 65 |
+
image_base64 = base64.b64encode(image_response.content).decode('utf-8')
|
| 66 |
+
return jsonify({
|
| 67 |
+
'success': True,
|
| 68 |
+
'image': f'data:image/png;base64,{image_base64}',
|
| 69 |
+
'usage': result.get('usage', {})
|
| 70 |
+
})
|
| 71 |
+
else:
|
| 72 |
+
return jsonify({'error': 'Failed to download generated image'}), 500
|
| 73 |
+
else:
|
| 74 |
+
return jsonify({'error': response.json()}), response.status_code
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return jsonify({'error': str(e)}), 500
|
| 78 |
+
|
| 79 |
+
@app.route('/edit', methods=['POST'])
|
| 80 |
+
def edit_image():
|
| 81 |
+
try:
|
| 82 |
+
# Check if file was uploaded
|
| 83 |
+
if 'image' not in request.files:
|
| 84 |
+
return jsonify({'error': 'No image provided'}), 400
|
| 85 |
+
|
| 86 |
+
image_file = request.files['image']
|
| 87 |
+
prompt = request.form.get('prompt', '')
|
| 88 |
+
|
| 89 |
+
if not prompt:
|
| 90 |
+
return jsonify({'error': 'Prompt is required'}), 400
|
| 91 |
+
|
| 92 |
+
if not image_file or image_file.filename == '':
|
| 93 |
+
return jsonify({'error': 'Image is required'}), 400
|
| 94 |
+
|
| 95 |
+
if not allowed_file(image_file.filename):
|
| 96 |
+
return jsonify({'error': 'Invalid image format'}), 400
|
| 97 |
+
|
| 98 |
+
# Prepare multipart form data
|
| 99 |
+
headers = {
|
| 100 |
+
'Authorization': f'Bearer {OPENAI_API_KEY}'
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
# Read image content
|
| 104 |
+
image_content = image_file.read()
|
| 105 |
+
|
| 106 |
+
# Build files list for multipart upload
|
| 107 |
+
files = {
|
| 108 |
+
'model': (None, 'dall-e-2'),
|
| 109 |
+
'prompt': (None, prompt),
|
| 110 |
+
'n': (None, '1'),
|
| 111 |
+
'size': (None, request.form.get('size', '1024x1024')),
|
| 112 |
+
'image': (image_file.filename, image_content, image_file.content_type)
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
# Add mask if provided
|
| 116 |
+
if 'mask' in request.files:
|
| 117 |
+
mask_file = request.files['mask']
|
| 118 |
+
if mask_file and mask_file.filename != '':
|
| 119 |
+
mask_content = mask_file.read()
|
| 120 |
+
files['mask'] = (mask_file.filename, mask_content, mask_file.content_type)
|
| 121 |
+
|
| 122 |
+
response = requests.post(
|
| 123 |
+
f'{API_BASE_URL}/images/edits',
|
| 124 |
+
headers=headers,
|
| 125 |
+
files=files
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if response.status_code == 200:
|
| 129 |
+
result = response.json()
|
| 130 |
+
# For dall-e-2, the response format depends on response_format parameter
|
| 131 |
+
# Default is URL format
|
| 132 |
+
if 'b64_json' in result['data'][0]:
|
| 133 |
+
image_data = f'data:image/png;base64,{result["data"][0]["b64_json"]}'
|
| 134 |
+
else:
|
| 135 |
+
# Download image from URL
|
| 136 |
+
image_url = result['data'][0]['url']
|
| 137 |
+
image_response = requests.get(image_url)
|
| 138 |
+
if image_response.status_code == 200:
|
| 139 |
+
image_base64 = base64.b64encode(image_response.content).decode('utf-8')
|
| 140 |
+
image_data = f'data:image/png;base64,{image_base64}'
|
| 141 |
+
else:
|
| 142 |
+
return jsonify({'error': 'Failed to download generated image'}), 500
|
| 143 |
+
|
| 144 |
+
return jsonify({
|
| 145 |
+
'success': True,
|
| 146 |
+
'image': image_data,
|
| 147 |
+
'usage': result.get('usage', {})
|
| 148 |
+
})
|
| 149 |
+
else:
|
| 150 |
+
error_msg = 'Request failed'
|
| 151 |
+
try:
|
| 152 |
+
error_data = response.json()
|
| 153 |
+
error_msg = error_data.get('error', {}).get('message', error_msg)
|
| 154 |
+
except:
|
| 155 |
+
error_msg = response.text
|
| 156 |
+
return jsonify({'error': error_msg}), response.status_code
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
+
return jsonify({'error': str(e)}), 500
|
| 160 |
+
|
| 161 |
+
if __name__ == '__main__':
|
| 162 |
+
if not OPENAI_API_KEY:
|
| 163 |
+
print("Warning: OPENAI_API_KEY environment variable not set!")
|
| 164 |
app.run(host='0.0.0.0', port=7860, debug=True)
|