File size: 6,670 Bytes
e095c23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01793bc
e095c23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9487a60
e095c23
 
18b7c16
01793bc
e095c23
18b7c16
 
 
e095c23
 
d44ec1e
e095c23
d44ec1e
e095c23
d44ec1e
e095c23
d44ec1e
 
 
 
 
 
 
 
 
 
 
 
 
e095c23
d44ec1e
 
18b7c16
 
 
 
 
 
 
 
 
 
 
 
e095c23
 
 
18b7c16
e095c23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcd107b
18b7c16
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
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" 
        elif style == "ghibli":
             style = "ghibli studio art style, hand-drawn, whimsical, lush environments, soft color palette, dreamlike atmosphere, fantasy elements, vibrant yet gentle, emotional storytelling, childlike wonder, iconic character designs"
        elif style == "dragon_ball_z":
             style = "dragon ball z style, exaggerated muscles, sharp angular lines, intense action scenes, glowing energy auras, dynamic fight sequences, spiky hair, vibrant colors, iconic character designs, powerful transformations"
        elif style == "naruto":
             style = "naruto style, shinobi characters, village environments, hand signs for jutsu, ninja weapons, action-packed sequences, anime-style shading, emotional backstories, vibrant orange hues, iconic character designs, headbands"
        elif style == "bleach":
             style = "bleach style, samurai-inspired outfits, katana weapons, spiritual battles, dark and mysterious tones, hollow masks, high-speed action, supernatural powers, sleek and sharp character designs, dynamic fight scenes"
        elif style == "one_piece":
             style = "one piece style, pirate adventure, exaggerated expressions, unique character designs, bright and colorful, dynamic and fluid action scenes, iconic pirate flags, adventure and treasure hunt themes, larger-than-life abilities"
        elif style == "anime":
             style = "anime style, vibrant colors, exaggerated facial expressions, dynamic action scenes, unique character designs, emotional storytelling, fantasy elements, diverse genres from romance to action"
        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