Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,7 +14,10 @@ logger = logging.getLogger(__name__)
|
|
| 14 |
# Kling AI API configuration (keys hardcoded as requested)
|
| 15 |
ACCESS_KEY_ID = "AGBGmadNd9hakFYfahytyQQJtN8CJmDJ"
|
| 16 |
ACCESS_KEY_SECRET = "dp3pAe4PpdmnAHCAPgEd3PyLmBQrkMde"
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
def generate_jwt_token():
|
| 20 |
"""Generate JWT token for Kling AI API authentication."""
|
|
@@ -64,123 +67,141 @@ def generate_image(image, prompt=""):
|
|
| 64 |
"model_name": "kling-v2-1", # V2.1 model for image-to-image
|
| 65 |
"image": image_base64,
|
| 66 |
"prompt": prompt or "Transform the face into a cartoon style while preserving identity",
|
| 67 |
-
"
|
|
|
|
| 68 |
"output_format": "png",
|
| 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 |
-
logger.
|
| 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 |
-
status_code = e.response.status_code if e.response else None
|
| 129 |
-
error_data = e.response.json() if e.response and e.response.text else {}
|
| 130 |
-
service_code = error_data.get("code", 0)
|
| 131 |
-
error_message = error_data.get("message", str(e))
|
| 132 |
-
logger.error(f"HTTP error: {status_code}, Service Code: {service_code}, Details: {error_message}")
|
| 133 |
-
|
| 134 |
-
if status_code == 404:
|
| 135 |
-
if service_code == 1202:
|
| 136 |
-
return None, "Error: Invalid request method (1202). Check https://app.klingai.com/global/dev for correct endpoint."
|
| 137 |
-
elif service_code == 1203:
|
| 138 |
-
return None, "Error: Resource does not exist (1203). Verify model or endpoint at https://app.klingai.com/global/dev."
|
| 139 |
-
return None, "Error: Endpoint not found (404). Verify https://api.klingai.com/v1/images/image2image at https://app.klingai.com/global/dev or try alternative endpoints like /v1/images/generations."
|
| 140 |
-
elif status_code == 401:
|
| 141 |
-
if service_code == 1000:
|
| 142 |
-
return None, "Error: Authentication failed (1000). Verify API keys are correct."
|
| 143 |
-
elif service_code == 1001:
|
| 144 |
-
return None, "Error: Authorization empty (1001). Ensure JWT token is included."
|
| 145 |
-
elif service_code == 1002:
|
| 146 |
-
return None, "Error: Authorization invalid (1002). Check key format."
|
| 147 |
-
elif service_code == 1003:
|
| 148 |
-
return None, "Error: Authorization not yet valid (1003). Adjust token start time (nbf)."
|
| 149 |
-
elif service_code == 1004:
|
| 150 |
-
return None, "Error: Authorization expired (1004). Generate a new token."
|
| 151 |
-
elif status_code == 429:
|
| 152 |
-
if service_code == 1100:
|
| 153 |
-
return None, "Error: Account exception (1100). Verify account configuration at https://app.klingai.com."
|
| 154 |
-
elif service_code == 1101:
|
| 155 |
-
return None, "Error: Account in arrears (1101). Recharge your account."
|
| 156 |
-
elif service_code == 1102:
|
| 157 |
-
return None, "Error: Resource pack depleted or expired (1102). Purchase additional resources."
|
| 158 |
-
elif service_code in (1302, 1303):
|
| 159 |
-
return None, "Error: Rate limit exceeded (1302/1303). Try during off-peak hours (e.g., 2 AM IST) or contact support."
|
| 160 |
-
elif service_code == 1304:
|
| 161 |
-
return None, "Error: IP whitelisting issue (1304). Contact Kling AI support."
|
| 162 |
-
elif status_code == 403 and service_code == 1103:
|
| 163 |
-
return None, "Error: Unauthorized access (1103). Verify account permissions at https://app.klingai.com."
|
| 164 |
-
elif status_code == 400:
|
| 165 |
-
if service_code == 1200:
|
| 166 |
-
return None, "Error: Invalid request parameters (1200). Check payload format."
|
| 167 |
-
elif service_code == 1201:
|
| 168 |
-
return None, "Error: Invalid parameters (1201). Use PNG/JPEG (<10 MB, ≥512x512) with a clear face."
|
| 169 |
-
elif service_code == 1300:
|
| 170 |
-
return None, "Error: Platform policy triggered (1300). Check input content."
|
| 171 |
-
elif service_code == 1301:
|
| 172 |
-
return None, "Error: Content security policy triggered (1301). Ensure the image contains a clear face and avoid NSFW content."
|
| 173 |
-
elif status_code in (500, 503, 504):
|
| 174 |
-
if service_code == 5000:
|
| 175 |
-
return None, "Error: Server internal error (5000). Try again later."
|
| 176 |
-
elif service_code == 5001:
|
| 177 |
-
return None, "Error: Server unavailable due to maintenance (5001). Try again later."
|
| 178 |
-
elif service_code == 5002:
|
| 179 |
-
return None, "Error: Server timeout (5002). Try during off-peak hours (e.g., 2 AM IST)."
|
| 180 |
-
return None, f"Error: API request failed. HTTP {status_code}, Service Code {service_code}. Details: {error_message}"
|
| 181 |
-
except requests.exceptions.RequestException as e:
|
| 182 |
-
logger.error(f"Network error: {str(e)}")
|
| 183 |
-
return None, f"Error: Network issue. Ensure stable internet, disable VPN, and try again. Details: {str(e)}"
|
| 184 |
|
| 185 |
def chatbot_interface(image, prompt):
|
| 186 |
"""
|
|
@@ -205,8 +226,8 @@ with gr.Blocks() as iface:
|
|
| 205 |
gr.Markdown(
|
| 206 |
"""
|
| 207 |
# Kling AI Single-Reference Face Generator
|
| 208 |
-
Upload a PNG/JPEG image (<10 MB, ≥512x512 pixels) with a clear face to generate a transformed image using Kling AI V2.1 API (
|
| 209 |
-
If errors persist, verify endpoint at https://app.klingai.com/global/dev or contact support via https://app.klingai.com.
|
| 210 |
"""
|
| 211 |
)
|
| 212 |
with gr.Row():
|
|
|
|
| 14 |
# Kling AI API configuration (keys hardcoded as requested)
|
| 15 |
ACCESS_KEY_ID = "AGBGmadNd9hakFYfahytyQQJtN8CJmDJ"
|
| 16 |
ACCESS_KEY_SECRET = "dp3pAe4PpdmnAHCAPgEd3PyLmBQrkMde"
|
| 17 |
+
API_URLS = [
|
| 18 |
+
"https://api.klingai.com/v1/images/generations", # Primary endpoint from search results
|
| 19 |
+
"https://api.klingai.com/v1/images/image2image" # Fallback
|
| 20 |
+
]
|
| 21 |
|
| 22 |
def generate_jwt_token():
|
| 23 |
"""Generate JWT token for Kling AI API authentication."""
|
|
|
|
| 67 |
"model_name": "kling-v2-1", # V2.1 model for image-to-image
|
| 68 |
"image": image_base64,
|
| 69 |
"prompt": prompt or "Transform the face into a cartoon style while preserving identity",
|
| 70 |
+
"image_reference": "face", # Single-reference face generation
|
| 71 |
+
"human_fidelity": 0.97, # High face preservation
|
| 72 |
"output_format": "png",
|
| 73 |
+
"n": 1, # Generate one image
|
| 74 |
+
"aspect_ratio": "1:1" # Default aspect ratio
|
| 75 |
}
|
| 76 |
|
| 77 |
+
for api_url in API_URLS:
|
| 78 |
+
try:
|
| 79 |
+
logger.debug(f"Sending POST request to {api_url} with payload: {payload}")
|
| 80 |
+
response = requests.post(api_url, json=payload, headers=headers, timeout=30)
|
| 81 |
+
response.raise_for_status()
|
| 82 |
+
data = response.json()
|
| 83 |
+
logger.debug(f"API response: {data}")
|
| 84 |
+
|
| 85 |
+
task_id = data.get("task_id") or data.get("taskId") or data.get("id") or data.get("data", {}).get("task_id")
|
| 86 |
+
if not task_id:
|
| 87 |
+
logger.error("No task ID returned in API response")
|
| 88 |
+
return None, "Error: No task ID returned. Check API endpoint or keys at https://app.klingai.com/global/dev."
|
| 89 |
+
|
| 90 |
+
# Poll for task completion
|
| 91 |
+
status_urls = [
|
| 92 |
+
f"https://api.klingai.com/v1/tasks/{task_id}",
|
| 93 |
+
f"https://api.klingai.com/api/v1/task/{task_id}"
|
| 94 |
+
]
|
| 95 |
+
for status_url in status_urls:
|
| 96 |
+
for _ in range(60): # Poll for up to 5 minutes
|
| 97 |
+
logger.debug(f"Polling status at {status_url}")
|
| 98 |
+
status_response = requests.get(status_url, headers=headers, timeout=30)
|
| 99 |
+
if status_response.status_code == 404 and status_url != status_urls[-1]:
|
| 100 |
+
logger.debug(f"Status endpoint {status_url} failed, trying next")
|
| 101 |
+
continue
|
| 102 |
+
status_response.raise_for_status()
|
| 103 |
+
status_data = status_response.json()
|
| 104 |
+
logger.debug(f"Status response: {status_data}")
|
| 105 |
+
status = status_data.get("task_status") or status_data.get("status")
|
| 106 |
+
if status == "succeeded":
|
| 107 |
+
image_url = (status_data.get("image_url") or
|
| 108 |
+
status_data.get("result", {}).get("image_url") or
|
| 109 |
+
status_data.get("output") or
|
| 110 |
+
status_data.get("data", {}).get("image") or
|
| 111 |
+
status_data.get("data", {}).get("images", [{}])[0].get("url"))
|
| 112 |
+
if not image_url:
|
| 113 |
+
logger.error("No image URL in API response")
|
| 114 |
+
return None, "Error: No image URL in API response. Check API documentation at https://app.klingai.com/global/dev."
|
| 115 |
+
# Download the image
|
| 116 |
+
logger.debug(f"Downloading image from {image_url}")
|
| 117 |
+
image_response = requests.get(image_url, timeout=30)
|
| 118 |
+
image_response.raise_for_status()
|
| 119 |
+
output_path = Path("/tmp/output_image.png") # Use /tmp for Spaces compatibility
|
| 120 |
+
with open(output_path, "wb") as f:
|
| 121 |
+
f.write(image_response.content)
|
| 122 |
+
if not output_path.exists():
|
| 123 |
+
logger.error("Output image file not created")
|
| 124 |
+
return None, "Error: Failed to save output image."
|
| 125 |
+
logger.debug(f"Image saved to {output_path}")
|
| 126 |
+
return str(output_path), None
|
| 127 |
+
elif status == "failed":
|
| 128 |
+
logger.error("Image generation failed")
|
| 129 |
+
return None, "Error: Image generation failed. Ensure the image contains a clear face and avoid NSFW or sensitive content."
|
| 130 |
+
elif status == "processing" and status_data.get("progress", 0) >= 0.99:
|
| 131 |
+
logger.error("Generation stuck at 99%")
|
| 132 |
+
return None, "Error: Generation stuck at 99%. Check account credits or upgrade to a paid plan at https://app.klingai.com."
|
| 133 |
+
time.sleep(5)
|
| 134 |
+
|
| 135 |
+
logger.error("Image generation timed out")
|
| 136 |
+
return None, "Error: Image generation timed out. Try during off-peak hours (e.g., 2 AM IST) or check account status."
|
| 137 |
+
|
| 138 |
+
return None, f"Error: All status endpoints failed. Check https://app.klingai.com/global/dev for correct endpoint."
|
| 139 |
|
| 140 |
+
except requests.exceptions.HTTPError as e:
|
| 141 |
+
status_code = e.response.status_code if e.response else None
|
| 142 |
+
error_data = e.response.json() if e.response and e.response.text else {}
|
| 143 |
+
service_code = error_data.get("code", 0)
|
| 144 |
+
error_message = error_data.get("message", str(e))
|
| 145 |
+
logger.error(f"HTTP error: {status_code}, Service Code: {service_code}, Details: {error_message}")
|
| 146 |
+
|
| 147 |
+
if error_message.startswith("Create task failed"):
|
| 148 |
+
logger.error("Create task failed error detected")
|
| 149 |
+
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."
|
| 150 |
+
elif status_code == 404 and api_url != API_URLS[-1]:
|
| 151 |
+
logger.debug(f"Endpoint {api_url} failed with 404, trying next")
|
| 152 |
+
continue
|
| 153 |
+
elif status_code == 404:
|
| 154 |
+
if service_code == 1202:
|
| 155 |
+
return None, "Error: Invalid request method (1202). Check https://app.klingai.com/global/dev for correct endpoint."
|
| 156 |
+
elif service_code == 1203:
|
| 157 |
+
return None, "Error: Resource does not exist (1203). Verify model or endpoint at https://app.klingai.com/global/dev."
|
| 158 |
+
return None, "Error: Endpoint not found (404). Tried https://api.klingai.com/v1/images/generations and https://api.klingai.com/v1/images/image2image. Verify correct endpoint at https://app.klingai.com/global/dev."
|
| 159 |
+
elif status_code == 401:
|
| 160 |
+
if service_code == 1000:
|
| 161 |
+
return None, "Error: Authentication failed (1000). Verify API keys are correct."
|
| 162 |
+
elif service_code == 1001:
|
| 163 |
+
return None, "Error: Authorization empty (1001). Ensure JWT token is included."
|
| 164 |
+
elif service_code == 1002:
|
| 165 |
+
return None, "Error: Authorization invalid (1002). Check key format."
|
| 166 |
+
elif service_code == 1003:
|
| 167 |
+
return None, "Error: Authorization not yet valid (1003). Adjust token start time (nbf)."
|
| 168 |
+
elif service_code == 1004:
|
| 169 |
+
return None, "Error: Authorization expired (1004). Generate a new token."
|
| 170 |
+
elif status_code == 429:
|
| 171 |
+
if service_code == 1100:
|
| 172 |
+
return None, "Error: Account exception (1100). Verify account configuration at https://app.klingai.com."
|
| 173 |
+
elif service_code == 1101:
|
| 174 |
+
return None, "Error: Account in arrears (1101). Recharge your account."
|
| 175 |
+
elif service_code == 1102:
|
| 176 |
+
return None, "Error: Resource pack depleted or expired (1102). Purchase additional resources."
|
| 177 |
+
elif service_code in (1302, 1303):
|
| 178 |
+
return None, "Error: Rate limit exceeded (1302/1303). Try during off-peak hours (e.g., 2 AM IST) or contact support."
|
| 179 |
+
elif service_code == 1304:
|
| 180 |
+
return None, "Error: IP whitelisting issue (1304). Contact Kling AI support."
|
| 181 |
+
elif status_code == 403 and service_code == 1103:
|
| 182 |
+
return None, "Error: Unauthorized access (1103). Verify account permissions at https://app.klingai.com."
|
| 183 |
+
elif status_code == 400:
|
| 184 |
+
if service_code == 1200:
|
| 185 |
+
return None, "Error: Invalid request parameters (1200). Check payload format."
|
| 186 |
+
elif service_code == 1201:
|
| 187 |
+
return None, "Error: Invalid parameters (1201). Use PNG/JPEG (<10 MB, ≥512x512) with a clear face."
|
| 188 |
+
elif service_code == 1300:
|
| 189 |
+
return None, "Error: Platform policy triggered (1300). Check input content."
|
| 190 |
+
elif service_code == 1301:
|
| 191 |
+
return None, "Error: Content security policy triggered (1301). Ensure the image contains a clear face and avoid NSFW content."
|
| 192 |
+
elif status_code in (500, 503, 504):
|
| 193 |
+
if service_code == 5000:
|
| 194 |
+
return None, "Error: Server internal error (5000). Try again later."
|
| 195 |
+
elif service_code == 5001:
|
| 196 |
+
return None, "Error: Server unavailable due to maintenance (5001). Try again later."
|
| 197 |
+
elif service_code == 5002:
|
| 198 |
+
return None, "Error: Server timeout (5002). Try during off-peak hours (e.g., 2 AM IST)."
|
| 199 |
+
return None, f"Error: API request failed. HTTP {status_code}, Service Code {service_code}. Details: {error_message}"
|
| 200 |
+
except requests.exceptions.RequestException as e:
|
| 201 |
+
logger.error(f"Network error: {str(e)}")
|
| 202 |
+
return None, f"Error: Network issue. Ensure stable internet, disable VPN, and try again. Details: {str(e)}"
|
| 203 |
|
| 204 |
+
return None, "Error: All API endpoints failed. Verify correct endpoint at https://app.klingai.com/global/dev."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
def chatbot_interface(image, prompt):
|
| 207 |
"""
|
|
|
|
| 226 |
gr.Markdown(
|
| 227 |
"""
|
| 228 |
# Kling AI Single-Reference Face Generator
|
| 229 |
+
Upload a PNG/JPEG image (<10 MB, ≥512x512 pixels) with a clear face to generate a transformed image using Kling AI V2.1 API (face fidelity 0.97). Avoid NSFW or sensitive content.
|
| 230 |
+
If errors persist, verify endpoint at https://app.klingai.com/global/dev or contact support via https://app.klingai.com or Kling AI Discord.
|
| 231 |
"""
|
| 232 |
)
|
| 233 |
with gr.Row():
|