Pamudu13's picture
Update app.py
18b7c16 verified
raw
history blame
5.06 kB
from flask import Flask, request, jsonify
import aiohttp
import asyncio
import io
import cloudinary
import cloudinary.uploader
import cloudinary.api
import random
import os
app = Flask(__name__)
# Configure Cloudinary
cloudinary.config(
cloud_name='dpnixluze',
api_key='417356221754679',
api_secret='MjsdHI-8vvYg-yF8p5__aK_8OYs'
)
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0"
HEADERS = {"Authorization": f"Bearer {os.getenv('HUGGING_FACE_API_KEY')}"}
async def query(session, payload):
try:
async with session.post(API_URL, headers=HEADERS, json=payload) as response:
response.raise_for_status()
return await response.read()
except aiohttp.ClientError as e:
print(f"Error during API request: {e}")
return None
async def retry_query(payload, retries=5, delay=30):
async with aiohttp.ClientSession() as session:
for i in range(retries):
image_bytes = await query(session, payload)
if image_bytes:
return image_bytes
print(f"Retrying ({i + 1}/{retries})...")
await asyncio.sleep(delay)
return None
@app.route('/', methods=['POST'])
async def generate_image():
try:
data = request.json # This is synchronous
positive_prompt = data.get('positive_prompt', 'emma stone')
negative_prompt = data.get('negative_prompt', '[deformed | disfigured] , poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers) , blurry,clothes, bad lighting, low-quality, deformed, text, poorly drawn, holding camera, bad art, bad angle, boring, low-resolution, worst quality, bad composition, disfigured')
style = data.get('style','');
if style == "cinematic":
style = "cinematic shot, dynamic lighting, 75mm, Technicolor, Panavision, cinemascope, sharp focus, fine details, 8k, HDR, realism, realistic, key visual, film still, superb cinematic color grading, depth of field"
elif style == "realistic":
style = "realistic style, natural lighting, true-to-life details, high resolution, sharp focus, fine textures, authentic colors, accurate proportions, high dynamic range, clear and photorealistic"
elif style == "sci-fi":
style = "sci-fi style, futuristic technology, cyberpunk cityscape, neon lights, advanced robotics, alien landscapes, holographic interfaces, space exploration, dystopian themes, high-tech machinery"
elif style == "disney":
style = "3d, Disney character style, animated, cartoonish, whimsical, colorful, playful, charming, magical, fantastical, cute, endearing, family-friendly, storybook quality, iconic, expressive, vibrant colors, smooth lines, simple shapes, happy and adventurous"
else:
style = "fantasy style, magical landscapes, mythical creatures, enchanted forests, fairy tale elements, mystical realms, legendary beings, glowing effects, ethereal atmosphere, magical artifacts, ancient ruins"
seed = random.randint(0, 10000)
payload = {
"inputs": f"{positive_prompt}, {style}",
"negative_prompt": negative_prompt,
"options": {
"resolution": "4096×2160",
"quality": "high",
"seed": seed
}
}
image_urls = []
for image_count in range(1): # Generate 3 images
# Retry mechanism with error handling
for attempt in range(3): # Try up to 3 times per image
image_bytes = await retry_query(payload)
if image_bytes:
try:
# Upload image to Cloudinary
upload_response = cloudinary.uploader.upload(io.BytesIO(image_bytes), resource_type="image")
cloudinary_url = upload_response.get('secure_url')
if cloudinary_url:
image_urls.append(cloudinary_url)
break # Break out of retry loop for this image
else:
raise Exception('Failed to upload image to Cloudinary.')
except Exception as upload_exception:
print(f"Upload attempt {attempt + 1} failed: {upload_exception}")
else:
print(f"Image generation attempt {attempt + 1} failed")
if image_urls:
return jsonify({'image_urls': image_urls})
else:
return jsonify({'error': 'Failed to generate and upload images after multiple attempts.'}), 500
except Exception as e:
print(f"Exception occurred: {e}")
return jsonify({'error': 'An unexpected error occurred.'}), 500
if __name__ == '__main__':
app.run(debug=True)
# app.run(host="0.0.0.0", port= 7860, debug= True) I want do generate 3 images at once not same imager three times