Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
-
from diffusers import StableDiffusionPipeline
|
| 4 |
from PIL import Image
|
| 5 |
import io
|
| 6 |
import requests
|
|
@@ -11,8 +11,8 @@ import tempfile
|
|
| 11 |
import time
|
| 12 |
import base64
|
| 13 |
|
| 14 |
-
# External OCI API URL
|
| 15 |
-
OCI_API_BASE_URL = "https://yukee1992-oci-
|
| 16 |
|
| 17 |
# Try to import your existing OCI connector for direct access
|
| 18 |
try:
|
|
@@ -23,94 +23,103 @@ except ImportError:
|
|
| 23 |
DIRECT_OCI_ACCESS = False
|
| 24 |
print("β οΈ Direct OCI access not available - using external API endpoint")
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
"""
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
|
|
|
|
|
|
| 31 |
pipe = StableDiffusionPipeline.from_pretrained(
|
| 32 |
-
|
| 33 |
torch_dtype=torch.float32,
|
| 34 |
safety_checker=None,
|
| 35 |
requires_safety_checker=False
|
| 36 |
-
)
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
return pipe
|
| 39 |
except Exception as e:
|
| 40 |
print(f"β Model loading failed: {e}")
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
# Load the model once at startup
|
| 44 |
pipe = load_model()
|
| 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 |
-
if success:
|
| 102 |
-
# Verify the upload actually worked
|
| 103 |
-
print("π Verifying OCI upload...")
|
| 104 |
-
verified, verify_msg = verify_oci_upload(object_name)
|
| 105 |
-
if verified:
|
| 106 |
-
return f"β
{message} | {verify_msg}"
|
| 107 |
-
else:
|
| 108 |
-
return f"β οΈ {message} BUT {verify_msg}"
|
| 109 |
-
else:
|
| 110 |
-
return f"β {message}"
|
| 111 |
-
|
| 112 |
-
except Exception as e:
|
| 113 |
-
return f"β Direct upload failed: {str(e)}"
|
| 114 |
|
| 115 |
def save_to_oci_via_api(image, prompt):
|
| 116 |
"""Save image using the EXTERNAL OCI API endpoint"""
|
|
@@ -123,9 +132,9 @@ def save_to_oci_via_api(image, prompt):
|
|
| 123 |
# Create filename
|
| 124 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 125 |
safe_prompt = "".join(c for c in prompt[:30] if c.isalnum() or c in (' ', '-', '_')).rstrip()
|
| 126 |
-
filename = f"
|
| 127 |
|
| 128 |
-
# Use the EXTERNAL API URL
|
| 129 |
api_url = f"{OCI_API_BASE_URL}/api/upload"
|
| 130 |
|
| 131 |
print(f"π Calling EXTERNAL OCI API: {api_url}")
|
|
@@ -137,15 +146,13 @@ def save_to_oci_via_api(image, prompt):
|
|
| 137 |
|
| 138 |
data = {
|
| 139 |
'project_id': 'storybook-generator',
|
| 140 |
-
'subfolder': '
|
| 141 |
}
|
| 142 |
|
| 143 |
# Make the API request with timeout
|
| 144 |
response = requests.post(api_url, files=files, data=data, timeout=30)
|
| 145 |
|
| 146 |
print(f"π¨ API Response: {response.status_code}")
|
| 147 |
-
if response.text:
|
| 148 |
-
print(f"π¨ API Response Text: {response.text[:200]}...")
|
| 149 |
|
| 150 |
if response.status_code == 200:
|
| 151 |
result = response.json()
|
|
@@ -156,188 +163,133 @@ def save_to_oci_via_api(image, prompt):
|
|
| 156 |
else:
|
| 157 |
return f"β HTTP Error: {response.status_code} - {response.text}"
|
| 158 |
|
| 159 |
-
except requests.exceptions.Timeout:
|
| 160 |
-
return "β API call timed out (30s)"
|
| 161 |
-
except requests.exceptions.ConnectionError:
|
| 162 |
-
return "β Cannot connect to OCI API"
|
| 163 |
except Exception as e:
|
| 164 |
return f"β API upload failed: {str(e)}"
|
| 165 |
|
| 166 |
-
def
|
| 167 |
-
"""
|
| 168 |
-
try:
|
| 169 |
-
# Convert image to base64
|
| 170 |
-
img_bytes = io.BytesIO()
|
| 171 |
-
image.save(img_bytes, format='PNG')
|
| 172 |
-
img_base64 = base64.b64encode(img_bytes.getvalue()).decode('utf-8')
|
| 173 |
-
|
| 174 |
-
# Create filename
|
| 175 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 176 |
-
safe_prompt = "".join(c for c in prompt[:30] if c.isalnum() or c in (' ', '-', '_')).rstrip()
|
| 177 |
-
filename = f"story_{timestamp}_{safe_prompt}.png"
|
| 178 |
-
|
| 179 |
-
# Use the EXTERNAL API text endpoint
|
| 180 |
-
api_url = f"{OCI_API_BASE_URL}/api/upload-text"
|
| 181 |
-
|
| 182 |
-
print(f"π Calling EXTERNAL OCI API (text): {api_url}")
|
| 183 |
-
|
| 184 |
-
# Prepare data for text endpoint
|
| 185 |
-
data = {
|
| 186 |
-
'project_id': 'storybook-generator',
|
| 187 |
-
'subfolder': 'childrens-books',
|
| 188 |
-
'filename': filename,
|
| 189 |
-
'content': img_base64 # Base64 encoded image
|
| 190 |
-
}
|
| 191 |
-
|
| 192 |
-
# Make the API request with timeout
|
| 193 |
-
response = requests.post(api_url, data=data, timeout=30)
|
| 194 |
-
|
| 195 |
-
print(f"π¨ API Response: {response.status_code}")
|
| 196 |
-
if response.text:
|
| 197 |
-
print(f"π¨ API Response Text: {response.text[:200]}...")
|
| 198 |
-
|
| 199 |
-
if response.status_code == 200:
|
| 200 |
-
result = response.json()
|
| 201 |
-
if result['status'] == 'success':
|
| 202 |
-
return f"β
{result['message']}"
|
| 203 |
-
else:
|
| 204 |
-
return f"β API Error: {result.get('message', 'Unknown error')}"
|
| 205 |
-
else:
|
| 206 |
-
return f"β HTTP Error: {response.status_code} - {response.text}"
|
| 207 |
-
|
| 208 |
-
except requests.exceptions.Timeout:
|
| 209 |
-
return "β API call timed out (30s)"
|
| 210 |
-
except requests.exceptions.ConnectionError:
|
| 211 |
-
return "β Cannot connect to OCI API"
|
| 212 |
-
except Exception as e:
|
| 213 |
-
return f"β API upload failed: {str(e)}"
|
| 214 |
-
|
| 215 |
-
def save_to_oci(image, prompt):
|
| 216 |
-
"""Main function to save image to OCI using best available method"""
|
| 217 |
-
print("πΎ Starting OCI save process...")
|
| 218 |
-
if DIRECT_OCI_ACCESS:
|
| 219 |
-
return save_to_oci_direct(image, prompt)
|
| 220 |
-
else:
|
| 221 |
-
# Try regular upload first, fallback to text upload if needed
|
| 222 |
-
result = save_to_oci_via_api(image, prompt)
|
| 223 |
-
if "β" in result and "upload-text" not in result:
|
| 224 |
-
# If regular upload fails, try text endpoint
|
| 225 |
-
print("π Regular upload failed, trying text endpoint...")
|
| 226 |
-
return save_to_oci_via_api_text(image, prompt)
|
| 227 |
-
return result
|
| 228 |
-
|
| 229 |
-
def generate_storybook_image(prompt):
|
| 230 |
-
"""Generate an image from text prompt and save to OCI"""
|
| 231 |
try:
|
| 232 |
if not prompt or not prompt.strip():
|
| 233 |
return None, "β Please enter a scene description"
|
| 234 |
|
| 235 |
-
#
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
-
print(f"π¨ Generating image for prompt: {enhanced_prompt}")
|
|
|
|
| 239 |
|
| 240 |
-
# Generate image
|
| 241 |
image = pipe(
|
| 242 |
-
enhanced_prompt,
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
| 247 |
).images[0]
|
| 248 |
|
| 249 |
-
print("β
Image generated successfully!")
|
| 250 |
|
| 251 |
# Save to OCI
|
| 252 |
-
print("πΎ Saving image to OCI storage...")
|
| 253 |
-
save_status =
|
| 254 |
print(f"Save status: {save_status}")
|
| 255 |
|
| 256 |
return image, save_status
|
| 257 |
|
| 258 |
except Exception as e:
|
| 259 |
-
error_msg = f"β Generation failed: {str(e)}"
|
| 260 |
print(error_msg)
|
| 261 |
import traceback
|
| 262 |
print(f"Traceback: {traceback.format_exc()}")
|
| 263 |
return None, error_msg
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
# Test direct OCI connection
|
| 270 |
-
namespace = oci_connector.config.get('namespace', 'Not set')
|
| 271 |
-
bucket = oci_connector.config.get('bucket_name', 'Not set')
|
| 272 |
-
client_status = "β
Connected" if oci_connector.client else "β Disconnected"
|
| 273 |
-
|
| 274 |
-
return f"""**Direct OCI Connection:**
|
| 275 |
-
- Client: {client_status}
|
| 276 |
-
- Namespace: {namespace}
|
| 277 |
-
- Bucket: {bucket}
|
| 278 |
-
- Initialization Error: {oci_connector.initialization_error or 'None'}"""
|
| 279 |
-
else:
|
| 280 |
-
# Test EXTERNAL API connection
|
| 281 |
-
try:
|
| 282 |
-
api_url = f"{OCI_API_BASE_URL}/api/health"
|
| 283 |
-
print(f"π Testing EXTERNAL API: {api_url}")
|
| 284 |
-
|
| 285 |
-
response = requests.get(api_url, timeout=10)
|
| 286 |
-
if response.status_code == 200:
|
| 287 |
-
result = response.json()
|
| 288 |
-
return f"β
EXTERNAL API Connection: Healthy - {result.get('status', 'No status')}"
|
| 289 |
-
else:
|
| 290 |
-
return f"β EXTERNAL API Connection: HTTP {response.status_code} - {response.text}"
|
| 291 |
-
except requests.exceptions.ConnectionError:
|
| 292 |
-
return "β EXTERNAL API Connection: Cannot connect (ConnectionError)"
|
| 293 |
-
except requests.exceptions.Timeout:
|
| 294 |
-
return "β EXTERNAL API Connection: Timeout after 10 seconds"
|
| 295 |
-
except Exception as e:
|
| 296 |
-
return f"β EXTERNAL API Connection Error: {str(e)}"
|
| 297 |
-
|
| 298 |
-
except Exception as e:
|
| 299 |
-
return f"β Connection check failed: {str(e)}"
|
| 300 |
-
|
| 301 |
-
# Create the Gradio interface
|
| 302 |
-
with gr.Blocks(title="Children's Book Illustrator", theme="soft") as demo:
|
| 303 |
-
gr.Markdown("# π Children's Book Illustrator")
|
| 304 |
-
gr.Markdown("Generate beautiful storybook images and automatically save them to your OCI storage")
|
| 305 |
|
| 306 |
with gr.Row():
|
| 307 |
-
with gr.Column():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
prompt_input = gr.Textbox(
|
| 309 |
label="Scene Description",
|
| 310 |
-
placeholder="Describe
|
| 311 |
lines=3
|
| 312 |
)
|
| 313 |
-
|
|
|
|
| 314 |
|
| 315 |
-
with gr.Column():
|
| 316 |
-
image_output = gr.Image(label="Generated Image", height=
|
| 317 |
status_output = gr.Textbox(label="Status", interactive=False, lines=3)
|
| 318 |
|
| 319 |
-
#
|
| 320 |
-
with gr.Accordion("
|
| 321 |
-
gr.Markdown(
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
-
|
| 326 |
-
-
|
| 327 |
-
""
|
|
|
|
| 328 |
|
| 329 |
-
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
# Connect buttons to functions
|
| 333 |
generate_btn.click(
|
| 334 |
-
fn=
|
| 335 |
-
inputs=prompt_input,
|
| 336 |
outputs=[image_output, status_output]
|
| 337 |
)
|
| 338 |
|
| 339 |
debug_btn.click(
|
| 340 |
-
fn=
|
| 341 |
inputs=None,
|
| 342 |
outputs=debug_output
|
| 343 |
)
|
|
@@ -347,7 +299,8 @@ def get_app():
|
|
| 347 |
return demo
|
| 348 |
|
| 349 |
if __name__ == "__main__":
|
| 350 |
-
print("π Starting Children's Book Illustrator...")
|
| 351 |
-
print(
|
| 352 |
-
|
|
|
|
| 353 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
+
from diffusers import StableDiffusionPipeline, EulerAncestralDiscreteScheduler
|
| 4 |
from PIL import Image
|
| 5 |
import io
|
| 6 |
import requests
|
|
|
|
| 11 |
import time
|
| 12 |
import base64
|
| 13 |
|
| 14 |
+
# External OCI API URL
|
| 15 |
+
OCI_API_BASE_URL = "https://yukee1992-oci-video-storage.hf.space"
|
| 16 |
|
| 17 |
# Try to import your existing OCI connector for direct access
|
| 18 |
try:
|
|
|
|
| 23 |
DIRECT_OCI_ACCESS = False
|
| 24 |
print("β οΈ Direct OCI access not available - using external API endpoint")
|
| 25 |
|
| 26 |
+
# HIGH-QUALITY MODEL SELECTION
|
| 27 |
+
MODEL_CHOICES = {
|
| 28 |
+
"dreamshaper-8": "lykon/dreamshaper-8", # Excellent for fantasy/artistic
|
| 29 |
+
"realistic-vision": "SG161222/Realistic_Vision_V5.1", # Photorealistic
|
| 30 |
+
"anything-v5": "andite/anything-v5.0", # Anime/illustration style
|
| 31 |
+
"openjourney": "prompthero/openjourney", # Artistic/Midjourney style
|
| 32 |
+
"sd-2.1": "stabilityai/stable-diffusion-2-1", # General purpose
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# Initialize the HIGH-QUALITY Stable Diffusion model
|
| 36 |
+
def load_model(model_name="dreamshaper-8"):
|
| 37 |
+
"""Load and return a high-quality Stable Diffusion model"""
|
| 38 |
+
print(f"π Loading {model_name} model...")
|
| 39 |
try:
|
| 40 |
+
model_id = MODEL_CHOICES.get(model_name, "lykon/dreamshaper-8")
|
| 41 |
+
|
| 42 |
pipe = StableDiffusionPipeline.from_pretrained(
|
| 43 |
+
model_id,
|
| 44 |
torch_dtype=torch.float32,
|
| 45 |
safety_checker=None,
|
| 46 |
requires_safety_checker=False
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Use better scheduler for quality
|
| 50 |
+
pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
|
| 51 |
+
pipe = pipe.to("cpu")
|
| 52 |
+
|
| 53 |
+
print(f"β
{model_name} loaded successfully!")
|
| 54 |
return pipe
|
| 55 |
except Exception as e:
|
| 56 |
print(f"β Model loading failed: {e}")
|
| 57 |
+
# Fallback to SD 1.5
|
| 58 |
+
return StableDiffusionPipeline.from_pretrained(
|
| 59 |
+
"runwayml/stable-diffusion-v1-5",
|
| 60 |
+
torch_dtype=torch.float32,
|
| 61 |
+
safety_checker=None,
|
| 62 |
+
requires_safety_checker=False
|
| 63 |
+
).to("cpu")
|
| 64 |
|
| 65 |
# Load the model once at startup
|
| 66 |
pipe = load_model()
|
| 67 |
|
| 68 |
+
# PROFESSIONAL PROMPT ENGINEERING
|
| 69 |
+
def enhance_prompt(prompt, style="childrens_book"):
|
| 70 |
+
"""Transform basic prompts into professional-grade prompts"""
|
| 71 |
+
|
| 72 |
+
style_templates = {
|
| 73 |
+
"childrens_book": [
|
| 74 |
+
"masterpiece, best quality, 4K, ultra detailed, children's book illustration",
|
| 75 |
+
"watercolor painting, whimsical, cute, charming, storybook style",
|
| 76 |
+
"vibrant colors, soft lighting, magical, enchanting, dreamlike",
|
| 77 |
+
"Pixar style, Disney animation, high detail, professional artwork"
|
| 78 |
+
],
|
| 79 |
+
"realistic": [
|
| 80 |
+
"photorealistic, 8K, ultra detailed, professional photography",
|
| 81 |
+
"sharp focus, studio lighting, high resolution, intricate details",
|
| 82 |
+
"realistic textures, natural lighting, cinematic quality"
|
| 83 |
+
],
|
| 84 |
+
"fantasy": [
|
| 85 |
+
"epic fantasy art, digital painting, concept art, trending on artstation",
|
| 86 |
+
"magical, mystical, ethereal, otherworldly, fantasy illustration",
|
| 87 |
+
"dynamic composition, dramatic lighting, highly detailed"
|
| 88 |
+
],
|
| 89 |
+
"anime": [
|
| 90 |
+
"anime style, Japanese animation, high quality, detailed artwork",
|
| 91 |
+
"beautiful anime illustration, vibrant colors, clean lines",
|
| 92 |
+
"studio ghibli style, makoto shinkai, professional anime art"
|
| 93 |
+
]
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
# Choose style template
|
| 97 |
+
templates = style_templates.get(style, style_templates["childrens_book"])
|
| 98 |
+
style_prompt = templates[0] # Use the first template
|
| 99 |
+
|
| 100 |
+
# Enhanced prompt construction
|
| 101 |
+
enhanced = f"{style_prompt}, {prompt}"
|
| 102 |
+
|
| 103 |
+
# Add quality boosters
|
| 104 |
+
quality_boosters = [
|
| 105 |
+
"intricate details", "beautiful composition", "perfect lighting",
|
| 106 |
+
"professional artwork", "award winning", "trending on artstation"
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
# Add 2-3 random quality boosters
|
| 110 |
+
import random
|
| 111 |
+
boosters = random.sample(quality_boosters, 2)
|
| 112 |
+
enhanced += ", " + ", ".join(boosters)
|
| 113 |
+
|
| 114 |
+
# Negative prompt to avoid bad quality
|
| 115 |
+
negative_prompt = (
|
| 116 |
+
"blurry, low quality, low resolution, ugly, deformed, poorly drawn, "
|
| 117 |
+
"bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, "
|
| 118 |
+
"disconnected limbs, mutation, mutated, ugly, disgusting, bad art, "
|
| 119 |
+
"beginner, amateur, distorted, watermark, signature, text, username"
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
return enhanced, negative_prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
def save_to_oci_via_api(image, prompt):
|
| 125 |
"""Save image using the EXTERNAL OCI API endpoint"""
|
|
|
|
| 132 |
# Create filename
|
| 133 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 134 |
safe_prompt = "".join(c for c in prompt[:30] if c.isalnum() or c in (' ', '-', '_')).rstrip()
|
| 135 |
+
filename = f"hq_story_{timestamp}_{safe_prompt}.png"
|
| 136 |
|
| 137 |
+
# Use the EXTERNAL API URL
|
| 138 |
api_url = f"{OCI_API_BASE_URL}/api/upload"
|
| 139 |
|
| 140 |
print(f"π Calling EXTERNAL OCI API: {api_url}")
|
|
|
|
| 146 |
|
| 147 |
data = {
|
| 148 |
'project_id': 'storybook-generator',
|
| 149 |
+
'subfolder': 'high-quality-books'
|
| 150 |
}
|
| 151 |
|
| 152 |
# Make the API request with timeout
|
| 153 |
response = requests.post(api_url, files=files, data=data, timeout=30)
|
| 154 |
|
| 155 |
print(f"π¨ API Response: {response.status_code}")
|
|
|
|
|
|
|
| 156 |
|
| 157 |
if response.status_code == 200:
|
| 158 |
result = response.json()
|
|
|
|
| 163 |
else:
|
| 164 |
return f"β HTTP Error: {response.status_code} - {response.text}"
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
except Exception as e:
|
| 167 |
return f"β API upload failed: {str(e)}"
|
| 168 |
|
| 169 |
+
def generate_high_quality_image(prompt, model_choice="dreamshaper-8", style="childrens_book"):
|
| 170 |
+
"""Generate HIGH-QUALITY image from text prompt"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
try:
|
| 172 |
if not prompt or not prompt.strip():
|
| 173 |
return None, "β Please enter a scene description"
|
| 174 |
|
| 175 |
+
# Reload model if different choice
|
| 176 |
+
global pipe
|
| 177 |
+
if model_choice != "dreamshaper-8": # Default already loaded
|
| 178 |
+
pipe = load_model(model_choice)
|
| 179 |
+
|
| 180 |
+
# PROFESSIONAL PROMPT ENHANCEMENT
|
| 181 |
+
enhanced_prompt, negative_prompt = enhance_prompt(prompt, style)
|
| 182 |
|
| 183 |
+
print(f"π¨ Generating HQ image for prompt: {enhanced_prompt}")
|
| 184 |
+
print(f"π« Negative prompt: {negative_prompt[:100]}...")
|
| 185 |
|
| 186 |
+
# Generate HIGH-QUALITY image with better settings
|
| 187 |
image = pipe(
|
| 188 |
+
prompt=enhanced_prompt,
|
| 189 |
+
negative_prompt=negative_prompt,
|
| 190 |
+
num_inference_steps=30, # More steps = better quality
|
| 191 |
+
guidance_scale=8.5, # Higher guidance = better prompt following
|
| 192 |
+
width=768, # Higher resolution
|
| 193 |
+
height=768,
|
| 194 |
+
generator=torch.Generator(device="cpu").manual_seed(int(time.time())) # Random seed
|
| 195 |
).images[0]
|
| 196 |
|
| 197 |
+
print("β
HQ Image generated successfully!")
|
| 198 |
|
| 199 |
# Save to OCI
|
| 200 |
+
print("πΎ Saving HQ image to OCI storage...")
|
| 201 |
+
save_status = save_to_oci_via_api(image, prompt)
|
| 202 |
print(f"Save status: {save_status}")
|
| 203 |
|
| 204 |
return image, save_status
|
| 205 |
|
| 206 |
except Exception as e:
|
| 207 |
+
error_msg = f"β HQ Generation failed: {str(e)}"
|
| 208 |
print(error_msg)
|
| 209 |
import traceback
|
| 210 |
print(f"Traceback: {traceback.format_exc()}")
|
| 211 |
return None, error_msg
|
| 212 |
|
| 213 |
+
# Create the Gradio interface with QUALITY OPTIONS
|
| 214 |
+
with gr.Blocks(title="Premium Children's Book Illustrator", theme="soft") as demo:
|
| 215 |
+
gr.Markdown("# π¨ Premium Children's Book Illustrator")
|
| 216 |
+
gr.Markdown("Generate **studio-quality** storybook images with professional results")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
with gr.Row():
|
| 219 |
+
with gr.Column(scale=1):
|
| 220 |
+
gr.Markdown("### π― Quality Settings")
|
| 221 |
+
|
| 222 |
+
model_choice = gr.Dropdown(
|
| 223 |
+
label="AI Model",
|
| 224 |
+
choices=list(MODEL_CHOICES.keys()),
|
| 225 |
+
value="dreamshaper-8",
|
| 226 |
+
info="Choose the best model for your style"
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
style_choice = gr.Dropdown(
|
| 230 |
+
label="Art Style",
|
| 231 |
+
choices=["childrens_book", "realistic", "fantasy", "anime"],
|
| 232 |
+
value="childrens_book",
|
| 233 |
+
info="Select the artistic style"
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
prompt_input = gr.Textbox(
|
| 237 |
label="Scene Description",
|
| 238 |
+
placeholder="Describe your scene in detail...\nExample: A friendly dragon reading a giant book under a magical tree with glowing fairies",
|
| 239 |
lines=3
|
| 240 |
)
|
| 241 |
+
|
| 242 |
+
generate_btn = gr.Button("β¨ Generate Premium Image", variant="primary")
|
| 243 |
|
| 244 |
+
with gr.Column(scale=2):
|
| 245 |
+
image_output = gr.Image(label="Generated Image", height=500, show_download_button=True)
|
| 246 |
status_output = gr.Textbox(label="Status", interactive=False, lines=3)
|
| 247 |
|
| 248 |
+
# Examples section
|
| 249 |
+
with gr.Accordion("π‘ Prompt Examples & Tips", open=False):
|
| 250 |
+
gr.Markdown("""
|
| 251 |
+
## π¨ Professional Prompt Examples:
|
| 252 |
+
|
| 253 |
+
**Best Results:**
|
| 254 |
+
- "A cute baby dragon learning to read with an old wise turtle in a magical forest"
|
| 255 |
+
- "Group of animal friends having a picnic under a giant glowing mushroom"
|
| 256 |
+
- "Little girl exploring a castle made of candy with talking animals"
|
| 257 |
+
- "Space adventure with friendly robots and colorful aliens"
|
| 258 |
|
| 259 |
+
## π« Avoid:
|
| 260 |
+
- "dragon" β **"friendly cartoon dragon reading book"**
|
| 261 |
+
- "cat" β **"cute kitten playing with yarn ball"**
|
| 262 |
+
- "tree" β **"magical tree with glowing fairies"**
|
| 263 |
+
|
| 264 |
+
## β‘ Pro Tips:
|
| 265 |
+
1. **Be descriptive** - Add colors, emotions, settings
|
| 266 |
+
2. **Specify style** - "watercolor", "cartoon", "realistic"
|
| 267 |
+
3. **Add details** - "with glowing effects", "in a magical forest"
|
| 268 |
+
4. **Use positive language** - "happy", "friendly", "colorful"
|
| 269 |
+
""")
|
| 270 |
|
| 271 |
+
# Debug section
|
| 272 |
+
with gr.Accordion("π§ Advanced Settings", open=False):
|
| 273 |
+
debug_btn = gr.Button("π Check System Status", variant="secondary")
|
| 274 |
+
debug_output = gr.Textbox(label="System Info", interactive=False, lines=4)
|
| 275 |
+
|
| 276 |
+
def check_system_status():
|
| 277 |
+
"""Check system status"""
|
| 278 |
+
return f"""**System Status:**
|
| 279 |
+
- Model: {model_choice.value}
|
| 280 |
+
- Style: {style_choice.value}
|
| 281 |
+
- OCI API: {OCI_API_BASE_URL}
|
| 282 |
+
- Ready for premium image generation!"""
|
| 283 |
+
|
| 284 |
# Connect buttons to functions
|
| 285 |
generate_btn.click(
|
| 286 |
+
fn=generate_high_quality_image,
|
| 287 |
+
inputs=[prompt_input, model_choice, style_choice],
|
| 288 |
outputs=[image_output, status_output]
|
| 289 |
)
|
| 290 |
|
| 291 |
debug_btn.click(
|
| 292 |
+
fn=check_system_status,
|
| 293 |
inputs=None,
|
| 294 |
outputs=debug_output
|
| 295 |
)
|
|
|
|
| 299 |
return demo
|
| 300 |
|
| 301 |
if __name__ == "__main__":
|
| 302 |
+
print("π Starting Premium Children's Book Illustrator...")
|
| 303 |
+
print("π¨ Loaded with HIGH-QUALITY models:")
|
| 304 |
+
for model in MODEL_CHOICES:
|
| 305 |
+
print(f" - {model}")
|
| 306 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|