Spaces:
Sleeping
Sleeping
File size: 7,406 Bytes
2e342df |
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 86 87 88 89 90 91 92 93 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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
from flask import Flask, request, jsonify, render_template, send_from_directory
import requests
import time
import os
import random
import json
app = Flask(__name__, static_folder='static', template_folder='templates')
# Image generation API functions
def get_common_headers():
return {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Content-Type": "application/json; charset=UTF-8",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"
}
def get_upgraded_prompt(prompt):
url = "https://editor.imagelabs.net/upgrade_prompt"
payload = {"prompt": prompt}
headers = get_common_headers()
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
data = response.json()
return data.get("upgraded_prompt") or data.get("prompt") or prompt
except Exception as e:
print(f"Error upgrading prompt: {e}")
return prompt
def generate_image(prompt, seed, subseed, attention, width, height, tiling, negative_prompt, reference_image, reference_image_type, reference_strength):
url = "https://editor.imagelabs.net/txt2img"
payload = {
"prompt": prompt,
"seed": seed,
"subseed": subseed,
"attention": attention,
"width": width,
"height": height,
"tiling": tiling,
"negative_prompt": negative_prompt,
"reference_image": reference_image,
"reference_image_type": reference_image_type,
"reference_strength": reference_strength
}
headers = get_common_headers()
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
data = response.json()
return data.get("task_id")
except Exception as e:
print(f"Error generating image: {e}")
raise
def poll_progress(task_id):
url = "https://editor.imagelabs.net/progress"
payload = {"task_id": task_id}
headers = get_common_headers()
max_attempts = 15
attempt = 0
while attempt < max_attempts:
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
data = response.json()
final_image_url = data.get("final_image_url")
status = (data.get("status") or "").lower()
if final_image_url:
return final_image_url
if status == "done":
return None
# Wait before next poll
time.sleep(2)
attempt += 1
except Exception as e:
print(f"Error polling progress: {e}")
raise
raise Exception("Polling timed out after 30 seconds")
# Routes
@app.route('/')
def index():
return render_template('index.html')
@app.route('/healthcheck')
def healthcheck():
return "Flask application is running!"
@app.route('/api/upgrade-prompt', methods=['POST'])
def upgrade_prompt():
data = request.json
if not data or 'prompt' not in data or not data['prompt']:
return jsonify({"error": "Invalid prompt. Please provide a text prompt."}), 400
try:
upgraded_prompt = get_upgraded_prompt(data['prompt'])
return jsonify({"upgradedPrompt": upgraded_prompt})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/generate', methods=['POST'])
def api_generate_image():
data = request.json
if not data or 'prompt' not in data or not data['prompt']:
return jsonify({"error": "Invalid prompt. Please provide a text prompt."}), 400
try:
prompt = data['prompt']
seed = data.get('seed', random.randint(0, 999999))
subseed = data.get('subseed', 0)
attention = data.get('attention', 0.5)
width = data.get('width', 512)
height = data.get('height', 512)
tiling = data.get('tiling', False)
negative_prompt = data.get('negative_prompt', "")
reference_image = data.get('reference_image')
reference_image_type = data.get('reference_image_type')
reference_strength = data.get('reference_strength', 0.5)
task_id = generate_image(
prompt, seed, subseed, attention, width, height, tiling,
negative_prompt, reference_image, reference_image_type, reference_strength
)
return jsonify({"taskId": task_id, "status": "processing"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/poll', methods=['POST'])
def api_poll_progress():
data = request.json
if not data or 'taskId' not in data or not data['taskId']:
return jsonify({"error": "Invalid task ID. Please provide a valid task ID."}), 400
try:
task_id = data['taskId']
image_url = poll_progress(task_id)
return jsonify({
"final_image_url": image_url,
"status": "done" if image_url else "processing"
})
except Exception as e:
return jsonify({"error": str(e)}), 500
# Helper route to save image history
@app.route('/api/save-history', methods=['POST'])
def save_history():
data = request.json
try:
history_file = os.path.join(app.static_folder, 'data', 'history.json')
os.makedirs(os.path.dirname(history_file), exist_ok=True)
# Read existing history
history = []
if os.path.exists(history_file):
with open(history_file, 'r') as f:
try:
history = json.load(f)
except:
history = []
# Add new image
if data and isinstance(history, list):
# Set an ID if none exists
if 'id' not in data:
data['id'] = str(int(time.time() * 1000))
# Add to the beginning of the array
history.insert(0, data)
# Keep only the last 20 images
history = history[:20]
with open(history_file, 'w') as f:
json.dump(history, f)
return jsonify({"success": True})
return jsonify({"error": "Invalid data format"}), 400
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/get-history', methods=['GET'])
def get_history():
try:
history_file = os.path.join(app.static_folder, 'data', 'history.json')
if os.path.exists(history_file):
with open(history_file, 'r') as f:
history = json.load(f)
return jsonify({"images": history})
return jsonify({"images": []})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
# Create data directory if it doesn't exist
os.makedirs(os.path.join(app.static_folder, 'data'), exist_ok=True)
app.run(host='0.0.0.0', port=8080, debug=True) |