Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,274 +1,230 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
import os
|
| 3 |
-
import time
|
| 4 |
-
import base64
|
| 5 |
-
import json
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
import gradio as gr
|
| 9 |
import requests
|
|
|
|
|
|
|
| 10 |
import jwt
|
| 11 |
-
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 17 |
-
ACCESS_KEY_ID = os.getenv("KLING_ACCESS_KEY_ID", "AGBGmadNd9hakFYfahytyQQJtN8CJmDJ")
|
| 18 |
-
ACCESS_KEY_SECRET = os.getenv("KLING_ACCESS_KEY_SECRET", "dp3pAe4PpdmnAHCAPgEd3PyLmBQrkMde")
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
payload = {
|
| 32 |
"iss": ACCESS_KEY_ID,
|
| 33 |
-
"exp":
|
| 34 |
-
"nbf":
|
| 35 |
}
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
# HELPERS
|
| 40 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
-
def ensure_image_ok(img_path: str):
|
| 42 |
-
with Image.open(img_path) as im:
|
| 43 |
-
im.verify() # quick integrity check
|
| 44 |
|
| 45 |
-
def
|
| 46 |
-
mime = "image/png" if img_path.lower().endswith(".png") else "image/jpeg"
|
| 47 |
-
with open(img_path, "rb") as f:
|
| 48 |
-
b = base64.b64encode(f.read()).decode("utf-8")
|
| 49 |
-
return f"data:{mime};base64,{b}"
|
| 50 |
-
|
| 51 |
-
def extract_task_id(resp_json: dict) -> str | None:
|
| 52 |
-
# Common shapes seen in the wild
|
| 53 |
-
if not resp_json:
|
| 54 |
-
return None
|
| 55 |
-
for key in ("task_id", "taskId", "id"):
|
| 56 |
-
if key in resp_json:
|
| 57 |
-
return str(resp_json[key])
|
| 58 |
-
data = resp_json.get("data") or {}
|
| 59 |
-
for key in ("task_id", "taskId", "id"):
|
| 60 |
-
if key in data:
|
| 61 |
-
return str(data[key])
|
| 62 |
-
# Sometimes nested deeper (e.g., {"task": {"id": ...}})
|
| 63 |
-
task = resp_json.get("task") or data.get("task") or {}
|
| 64 |
-
if "id" in task:
|
| 65 |
-
return str(task["id"])
|
| 66 |
-
return None
|
| 67 |
-
|
| 68 |
-
def extract_image_urls(resp_json: dict) -> list[str]:
|
| 69 |
-
if not resp_json:
|
| 70 |
-
return []
|
| 71 |
-
data = resp_json.get("data") or {}
|
| 72 |
-
# Typical: data.task_result.images = [{url: "..."}]
|
| 73 |
-
task_result = data.get("task_result") or {}
|
| 74 |
-
images = task_result.get("images") or []
|
| 75 |
-
urls = [img.get("url") for img in images if isinstance(img, dict) and img.get("url")]
|
| 76 |
-
if urls:
|
| 77 |
-
return urls
|
| 78 |
-
# Some variants: output, image_url, result.image_url
|
| 79 |
-
for k in ("output", "image_url"):
|
| 80 |
-
if k in resp_json and isinstance(resp_json[k], str):
|
| 81 |
-
return [resp_json[k]]
|
| 82 |
-
result = resp_json.get("result") or {}
|
| 83 |
-
if isinstance(result, dict) and result.get("image_url"):
|
| 84 |
-
return [result["image_url"]]
|
| 85 |
-
# Works array pattern
|
| 86 |
-
works = resp_json.get("works") or data.get("works") or []
|
| 87 |
-
urls = []
|
| 88 |
-
for w in works:
|
| 89 |
-
if isinstance(w, dict):
|
| 90 |
-
u = w.get("url") or w.get("imageUrl")
|
| 91 |
-
if u:
|
| 92 |
-
urls.append(u)
|
| 93 |
-
return urls
|
| 94 |
-
|
| 95 |
-
def download_to_file(url: str, out_path: Path) -> Path:
|
| 96 |
-
r = requests.get(url, timeout=60)
|
| 97 |
-
r.raise_for_status()
|
| 98 |
-
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 99 |
-
with open(out_path, "wb") as f:
|
| 100 |
-
f.write(r.content)
|
| 101 |
-
return out_path
|
| 102 |
-
|
| 103 |
-
def poll_for_result(task_id: str, headers: dict, timeout_s: int = 300, interval_s: float = 3.0) -> dict:
|
| 104 |
-
"""Poll task endpoint first; fallback to listing."""
|
| 105 |
-
deadline = time.time() + timeout_s
|
| 106 |
-
last_error = None
|
| 107 |
-
|
| 108 |
-
while time.time() < deadline:
|
| 109 |
-
try:
|
| 110 |
-
# Preferred: direct task status
|
| 111 |
-
r = requests.get(ENDPOINT_TASK(task_id), headers=headers, timeout=30)
|
| 112 |
-
if r.status_code == 200:
|
| 113 |
-
j = r.json()
|
| 114 |
-
# Either "status_name":"succeed" or "data.task_status":"succeed"
|
| 115 |
-
status_name = (j.get("status_name")
|
| 116 |
-
or (j.get("data") or {}).get("task_status")
|
| 117 |
-
or (j.get("task") or {}).get("status_name"))
|
| 118 |
-
if isinstance(status_name, dict):
|
| 119 |
-
# Some SDKs wrap status as enum-like
|
| 120 |
-
status_name = status_name.get("value")
|
| 121 |
-
if status_name in ("succeed", "succeeded", "success", "SUCCEED"):
|
| 122 |
-
return j
|
| 123 |
-
if status_name in ("failed", "FAIL", "failed_with_error"):
|
| 124 |
-
return j
|
| 125 |
-
elif r.status_code in (401, 403, 404):
|
| 126 |
-
last_error = r.text
|
| 127 |
-
# Fallback: scan generations list
|
| 128 |
-
r2 = requests.get(ENDPOINT_GENERATIONS, headers=headers, params={"pageSize": 200}, timeout=30)
|
| 129 |
-
if r2.status_code == 200:
|
| 130 |
-
j2 = r2.json()
|
| 131 |
-
for item in (j2.get("data") or []):
|
| 132 |
-
if str(item.get("task_id")) == str(task_id):
|
| 133 |
-
status = item.get("task_status")
|
| 134 |
-
if status in ("succeed", "succeeded", "success"):
|
| 135 |
-
return item
|
| 136 |
-
if status in ("failed",):
|
| 137 |
-
return item
|
| 138 |
-
except requests.RequestException as e:
|
| 139 |
-
last_error = str(e)
|
| 140 |
-
time.sleep(interval_s)
|
| 141 |
-
raise TimeoutError(f"Polling timed out for task_id {task_id}. Last error: {last_error or 'n/a'}")
|
| 142 |
-
|
| 143 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 144 |
-
# CORE CALL β Kolors face reference (single reference, faceStrength=97)
|
| 145 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 146 |
-
def kling_face_reference(image_path: str, prompt: str, face_strength: int = 97, aspect_ratio: str = "1:1") -> tuple[str, str]:
|
| 147 |
"""
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
"""
|
| 150 |
-
if not
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
"
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
"
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
"
|
| 166 |
-
"reference": (None, "face"),
|
| 167 |
-
"faceStrength": (None, str(max(1, min(100, int(face_strength))))),
|
| 168 |
-
"faceNo": (None, "1"), # single face reference
|
| 169 |
-
"imageCount": (None, "1"),
|
| 170 |
-
"aspect_ratio": (None, aspect_ratio),
|
| 171 |
}
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
}
|
| 176 |
-
|
| 177 |
-
# Attempt 1 β multipart
|
| 178 |
try:
|
| 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 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
with gr.Row():
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
|
|
|
|
|
|
| 272 |
if __name__ == "__main__":
|
| 273 |
-
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
+
import base64
|
| 4 |
+
from pathlib import Path
|
| 5 |
import jwt
|
| 6 |
+
import time
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
|
| 10 |
+
# Set up logging for debugging
|
| 11 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 12 |
+
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Kling AI API configuration (keys hardcoded as requested)
|
| 15 |
+
ACCESS_KEY_ID = "AGBGmadNd9hakFYfahytyQQJtN8CJmDJ"
|
| 16 |
+
ACCESS_KEY_SECRET = "dp3pAe4PpdmnAHCAPgEd3PyLmBQrkMde"
|
| 17 |
+
API_URL = "https://api.klingai.com/v1/images/image2image" # Correct endpoint
|
| 18 |
|
| 19 |
+
def generate_jwt_token():
|
| 20 |
+
"""Generate JWT token for Kling AI API authentication."""
|
| 21 |
+
headers = {
|
| 22 |
+
"alg": "HS256",
|
| 23 |
+
"typ": "JWT"
|
| 24 |
+
}
|
| 25 |
payload = {
|
| 26 |
"iss": ACCESS_KEY_ID,
|
| 27 |
+
"exp": int(time.time()) + 1800, # Token expires in 30 minutes
|
| 28 |
+
"nbf": int(time.time()) - 5 # Effective 5 seconds before current time
|
| 29 |
}
|
| 30 |
+
token = jwt.encode(payload, ACCESS_KEY_SECRET, headers=headers)
|
| 31 |
+
logger.debug(f"Generated JWT token: {token}")
|
| 32 |
+
return token
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
def generate_image(image, prompt=""):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
"""
|
| 36 |
+
Call Kling AI API for single-reference face generation.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
image: Uploaded image file (from Gradio, face image)
|
| 40 |
+
prompt (str): Optional text prompt to guide transformation
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
tuple: (Path to generated image or None, error message or None)
|
| 44 |
"""
|
| 45 |
+
if not image:
|
| 46 |
+
logger.error("No image uploaded")
|
| 47 |
+
return None, "Error: Please upload a valid face image (PNG/JPEG, <10 MB, β₯512x512 pixels)."
|
| 48 |
+
|
| 49 |
+
# Convert image to base64
|
| 50 |
+
try:
|
| 51 |
+
with open(image, "rb") as img_file:
|
| 52 |
+
image_base64 = base64.b64encode(img_file.read()).decode("utf-8")
|
| 53 |
+
logger.debug("Image converted to base64 successfully")
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.error(f"Failed to process image: {str(e)}")
|
| 56 |
+
return None, f"Error: Failed to process image. Ensure itβs a valid PNG/JPEG. Details: {str(e)}"
|
| 57 |
+
|
| 58 |
+
headers = {
|
| 59 |
+
"Authorization": f"Bearer {generate_jwt_token()}",
|
| 60 |
+
"Content-Type": "application/json"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
}
|
| 62 |
+
|
| 63 |
+
payload = {
|
| 64 |
+
"model_name": "kling-v2-1", # V2.1 model for image-to-image
|
| 65 |
+
"task_type": "image_generation", # Adapted from video task structure
|
| 66 |
+
"input": {
|
| 67 |
+
"image": image_base64,
|
| 68 |
+
"prompt": prompt or "Transform the face into a cartoon style while preserving identity",
|
| 69 |
+
"strength": 0.97, # High reference strength
|
| 70 |
+
"output_format": "png"
|
| 71 |
+
}
|
| 72 |
}
|
| 73 |
+
|
|
|
|
| 74 |
try:
|
| 75 |
+
logger.debug(f"Sending POST request to {API_URL} with payload: {payload}")
|
| 76 |
+
response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
|
| 77 |
+
response.raise_for_status()
|
| 78 |
+
data = response.json()
|
| 79 |
+
logger.debug(f"API response: {data}")
|
| 80 |
+
|
| 81 |
+
task_id = data.get("task_id") or data.get("taskId") or data.get("id")
|
| 82 |
+
if not task_id:
|
| 83 |
+
logger.error("No task ID returned in API response")
|
| 84 |
+
return None, "Error: No task ID returned. Check API endpoint or keys at https://app.klingai.com/global/dev."
|
| 85 |
+
|
| 86 |
+
# Poll for task completion
|
| 87 |
+
status_url = f"https://api.klingai.com/v1/tasks/{task_id}"
|
| 88 |
+
for _ in range(60): # Poll for up to 5 minutes
|
| 89 |
+
logger.debug(f"Polling status at {status_url}")
|
| 90 |
+
status_response = requests.get(status_url, headers=headers, timeout=30)
|
| 91 |
+
status_response.raise_for_status()
|
| 92 |
+
status_data = status_response.json()
|
| 93 |
+
logger.debug(f"Status response: {status_data}")
|
| 94 |
+
status = status_data.get("status")
|
| 95 |
+
if status == "succeeded":
|
| 96 |
+
image_url = status_data.get("image_url") or status_data.get("result", {}).get("image_url") or status_data.get("output") or status_data.get("data", {}).get("image")
|
| 97 |
+
if not image_url:
|
| 98 |
+
logger.error("No image URL in API response")
|
| 99 |
+
return None, "Error: No image URL in API response. Check API documentation at https://app.klingai.com/global/dev."
|
| 100 |
+
# Download the image
|
| 101 |
+
logger.debug(f"Downloading image from {image_url}")
|
| 102 |
+
image_response = requests.get(image_url, timeout=30)
|
| 103 |
+
image_response.raise_for_status()
|
| 104 |
+
output_path = Path("/tmp/output_image.png") # Use /tmp for Spaces compatibility
|
| 105 |
+
with open(output_path, "wb") as f:
|
| 106 |
+
f.write(image_response.content)
|
| 107 |
+
if not output_path.exists():
|
| 108 |
+
logger.error("Output image file not created")
|
| 109 |
+
return None, "Error: Failed to save output image."
|
| 110 |
+
logger.debug(f"Image saved to {output_path}")
|
| 111 |
+
return str(output_path), None
|
| 112 |
+
elif status == "failed":
|
| 113 |
+
logger.error("Image generation failed")
|
| 114 |
+
return None, "Error: Image generation failed. Ensure the image contains a clear face and avoid NSFW or sensitive content."
|
| 115 |
+
elif status == "processing" and status_data.get("progress", 0) >= 0.99:
|
| 116 |
+
logger.error("Generation stuck at 99%")
|
| 117 |
+
return None, "Error: Generation stuck at 99%. Check account credits or upgrade to a paid plan at https://app.klingai.com."
|
| 118 |
+
time.sleep(5)
|
| 119 |
+
|
| 120 |
+
logger.error("Image generation timed out")
|
| 121 |
+
return None, "Error: Image generation timed out. Try during off-peak hours (e.g., 2 AM IST) or check account status."
|
| 122 |
+
|
| 123 |
+
except requests.exceptions.HTTPError as e:
|
| 124 |
+
status_code = e.response.status_code if e.response else None
|
| 125 |
+
error_data = e.response.json() if e.response and e.response.text else {}
|
| 126 |
+
service_code = error_data.get("code", 0)
|
| 127 |
+
error_message = error_data.get("message", str(e))
|
| 128 |
+
logger.error(f"HTTP error: {status_code}, Service Code: {service_code}, Details: {error_message}")
|
| 129 |
+
|
| 130 |
+
if error_message.startswith("Create task failed"):
|
| 131 |
+
logger.error("Create task failed error detected")
|
| 132 |
+
return None, "Error: Create task failed. Try during off-peak hours (e.g., 2 AM IST), verify account status at https://app.klingai.com, or join Kling AI Discord for support."
|
| 133 |
+
elif status_code == 404:
|
| 134 |
+
if service_code == 1202:
|
| 135 |
+
return None, "Error: Invalid request method (1202). Check https://app.klingai.com/global/dev for correct endpoint."
|
| 136 |
+
elif service_code == 1203:
|
| 137 |
+
return None, "Error: Resource does not exist (1203). Verify model or endpoint."
|
| 138 |
+
return None, f"Error: Endpoint not found (404). Verify https://api.klingai.com/v1/images/image2image at https://app.klingai.com/global/dev."
|
| 139 |
+
elif status_code == 401:
|
| 140 |
+
if service_code == 1000:
|
| 141 |
+
return None, "Error: Authentication failed (1000). Verify API keys are correct."
|
| 142 |
+
elif service_code == 1001:
|
| 143 |
+
return None, "Error: Authorization empty (1001). Ensure JWT token is included."
|
| 144 |
+
elif service_code == 1002:
|
| 145 |
+
return None, "Error: Authorization invalid (1002). Check key format."
|
| 146 |
+
elif service_code == 1003:
|
| 147 |
+
return None, "Error: Authorization not yet valid (1003). Adjust token start time (nbf)."
|
| 148 |
+
elif service_code == 1004:
|
| 149 |
+
return None, "Error: Authorization expired (1004). Generate a new token."
|
| 150 |
+
elif status_code == 429:
|
| 151 |
+
if service_code == 1100:
|
| 152 |
+
return None, "Error: Account exception (1100). Verify account configuration at https://app.klingai.com."
|
| 153 |
+
elif service_code == 1101:
|
| 154 |
+
return None, "Error: Account in arrears (1101). Recharge your account."
|
| 155 |
+
elif service_code == 1102:
|
| 156 |
+
return None, "Error: Resource pack depleted or expired (1102). Purchase additional resources."
|
| 157 |
+
elif service_code in (1302, 1303):
|
| 158 |
+
return None, "Error: Rate limit exceeded (1302/1303). Try during off-peak hours (e.g., 2 AM IST) or contact support."
|
| 159 |
+
elif service_code == 1304:
|
| 160 |
+
return None, "Error: IP whitelisting issue (1304). Contact Kling AI support."
|
| 161 |
+
elif status_code == 403 and service_code == 1103:
|
| 162 |
+
return None, "Error: Unauthorized access (1103). Verify account permissions at https://app.klingai.com."
|
| 163 |
+
elif status_code == 400:
|
| 164 |
+
if service_code == 1200:
|
| 165 |
+
return None, "Error: Invalid request parameters (1200). Check payload format."
|
| 166 |
+
elif service_code == 1201:
|
| 167 |
+
return None, "Error: Invalid parameters (1201). Use PNG/JPEG (<10 MB, β₯512x512) with a clear face."
|
| 168 |
+
elif service_code == 1300:
|
| 169 |
+
return None, "Error: Platform policy triggered (1300). Check input content."
|
| 170 |
+
elif service_code == 1301:
|
| 171 |
+
return None, "Error: Content security policy triggered (1301). Ensure the image contains a clear face and avoid NSFW content."
|
| 172 |
+
elif status_code in (500, 503, 504):
|
| 173 |
+
if service_code == 5000:
|
| 174 |
+
return None, "Error: Server internal error (5000). Try again later."
|
| 175 |
+
elif service_code == 5001:
|
| 176 |
+
return None, "Error: Server unavailable due to maintenance (5001). Try again later."
|
| 177 |
+
elif service_code == 5002:
|
| 178 |
+
return None, "Error: Server timeout (5002). Try during off-peak hours (e.g., 2 AM IST)."
|
| 179 |
+
return None, f"Error: API request failed. HTTP {status_code}, Service Code {service_code}. Details: {error_message}"
|
| 180 |
+
except requests.exceptions.RequestException as e:
|
| 181 |
+
logger.error(f"Network error: {str(e)}")
|
| 182 |
+
return None, f"Error: Network issue. Ensure stable internet, disable VPN, and try again. Details: {str(e)}"
|
| 183 |
+
|
| 184 |
+
def chatbot_interface(image, prompt):
|
| 185 |
+
"""
|
| 186 |
+
Gradio interface for single-reference face generation.
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
image: Uploaded image file (containing a face)
|
| 190 |
+
prompt (str): Optional text prompt
|
| 191 |
+
|
| 192 |
+
Returns:
|
| 193 |
+
tuple: (Output image path for display, output image path for download, error message)
|
| 194 |
+
"""
|
| 195 |
+
output_path, error = generate_image(image, prompt)
|
| 196 |
+
if error:
|
| 197 |
+
logger.debug(f"Error returned: {error}")
|
| 198 |
+
return None, None, error
|
| 199 |
+
logger.debug(f"Returning image path for display and download: {output_path}")
|
| 200 |
+
return output_path, output_path, None
|
| 201 |
+
|
| 202 |
+
# Define Gradio interface
|
| 203 |
+
with gr.Blocks() as iface:
|
| 204 |
+
gr.Markdown(
|
| 205 |
+
"""
|
| 206 |
+
# Kling AI Single-Reference Face Generator
|
| 207 |
+
Upload a PNG/JPEG image (<10 MB, β₯512x512 pixels) with a clear face to generate a transformed image using Kling AI V2.1 API (reference strength 0.97). Avoid NSFW or sensitive content.
|
| 208 |
+
If errors persist, check account status at https://app.klingai.com or join Kling AI Discord for support.
|
| 209 |
+
"""
|
| 210 |
+
)
|
| 211 |
with gr.Row():
|
| 212 |
+
with gr.Column():
|
| 213 |
+
image_input = gr.Image(type="filepath", label="Upload Face Image (PNG/JPEG, <10 MB, β₯512x512)")
|
| 214 |
+
prompt_input = gr.Textbox(lines=2, placeholder="Enter an optional prompt (e.g., 'Turn this face into a cartoon')", label="Prompt")
|
| 215 |
+
generate_button = gr.Button("Generate")
|
| 216 |
+
with gr.Column():
|
| 217 |
+
output_image = gr.Image(label="Generated Face Image")
|
| 218 |
+
output_file = gr.File(label="Download Generated Image")
|
| 219 |
+
error_message = gr.Textbox(label="Status/Error Message", interactive=False)
|
| 220 |
+
|
| 221 |
+
generate_button.click(
|
| 222 |
+
fn=chatbot_interface,
|
| 223 |
+
inputs=[image_input, prompt_input],
|
| 224 |
+
outputs=[output_image, output_file, error_message]
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Launch the interface
|
| 228 |
if __name__ == "__main__":
|
| 229 |
+
logger.debug("Launching Gradio interface")
|
| 230 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|