Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,44 +1,216 @@
|
|
| 1 |
-
import
|
| 2 |
-
import jwt
|
| 3 |
import requests
|
| 4 |
import base64
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
ACCESS_KEY_ID = "AFyHfnQATghFdCMyAG3gRPbNY4TNKFGB"
|
| 8 |
ACCESS_KEY_SECRET = "TTepeLyBterLNM3brYPGmdndBnnyKJBA"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
# ---- Generate JWT ----
|
| 11 |
def generate_jwt_token():
|
|
|
|
|
|
|
| 12 |
payload = {
|
| 13 |
"iss": ACCESS_KEY_ID,
|
| 14 |
"exp": int(time.time()) + 1800,
|
| 15 |
"nbf": int(time.time()) - 5
|
| 16 |
}
|
| 17 |
-
token = jwt.encode(payload, ACCESS_KEY_SECRET,
|
| 18 |
-
|
| 19 |
-
token = token.decode("utf-8")
|
| 20 |
return token
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
headers = {
|
| 26 |
"Authorization": f"Bearer {generate_jwt_token()}",
|
| 27 |
"Content-Type": "application/json"
|
| 28 |
}
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
"
|
| 33 |
-
"prompt": "a
|
| 34 |
-
"
|
| 35 |
"output_format": "png",
|
| 36 |
-
"
|
|
|
|
| 37 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
|
|
|
| 43 |
if __name__ == "__main__":
|
| 44 |
-
|
|
|
|
|
|
| 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 (new keys)
|
| 15 |
ACCESS_KEY_ID = "AFyHfnQATghFdCMyAG3gRPbNY4TNKFGB"
|
| 16 |
ACCESS_KEY_SECRET = "TTepeLyBterLNM3brYPGmdndBnnyKJBA"
|
| 17 |
+
API_URLS = [
|
| 18 |
+
"https://api-singapore.klingai.com/v1/images/image2image", # Primary endpoint
|
| 19 |
+
"https://api-singapore.klingai.com/v1/images/kolors", # Fallback for Kolors 2.1
|
| 20 |
+
"https://api-singapore.klingai.com/v1/images/generations" # Fallback
|
| 21 |
+
]
|
| 22 |
|
|
|
|
| 23 |
def generate_jwt_token():
|
| 24 |
+
"""Generate JWT token for Kling AI API authentication."""
|
| 25 |
+
headers = {"alg": "HS256", "typ": "JWT"}
|
| 26 |
payload = {
|
| 27 |
"iss": ACCESS_KEY_ID,
|
| 28 |
"exp": int(time.time()) + 1800,
|
| 29 |
"nbf": int(time.time()) - 5
|
| 30 |
}
|
| 31 |
+
token = jwt.encode(payload, ACCESS_KEY_SECRET, headers=headers)
|
| 32 |
+
logger.debug(f"Generated JWT token: {token}")
|
|
|
|
| 33 |
return token
|
| 34 |
|
| 35 |
+
def generate_image(image, prompt=""):
|
| 36 |
+
"""
|
| 37 |
+
Call Kling AI API for single-reference face generation.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
image: Uploaded image file (face image)
|
| 41 |
+
prompt (str): Optional text prompt
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
tuple: (Path to generated image or None, error message or None)
|
| 45 |
+
"""
|
| 46 |
+
if not image:
|
| 47 |
+
logger.error("No image uploaded")
|
| 48 |
+
return None, "Error: Please upload a valid face image (PNG/JPEG, <10 MB, ≥512x512 pixels)."
|
| 49 |
+
|
| 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": "kolors-v2.1", # Kolors 2.1 for image-to-image
|
| 65 |
+
"image": image_base64,
|
| 66 |
+
"prompt": prompt or "Transform the face into a cartoon style while preserving identity",
|
| 67 |
+
"strength": 0.97,
|
| 68 |
"output_format": "png",
|
| 69 |
+
"n": 1,
|
| 70 |
+
"aspect_ratio": "1:1"
|
| 71 |
}
|
| 72 |
+
|
| 73 |
+
for api_url in API_URLS:
|
| 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") or data.get("data", {}).get("task_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 at https://klingai.com/global/dev/model/image."
|
| 85 |
+
|
| 86 |
+
status_urls = [
|
| 87 |
+
f"https://api-singapore.klingai.com/v1/tasks/{task_id}",
|
| 88 |
+
f"https://api-singapore.klingai.com/api/v1/task/{task_id}"
|
| 89 |
+
]
|
| 90 |
+
for status_url in status_urls:
|
| 91 |
+
for _ in range(60):
|
| 92 |
+
logger.debug(f"Polling status at {status_url}")
|
| 93 |
+
status_response = requests.get(status_url, headers=headers, timeout=30)
|
| 94 |
+
if status_response.status_code == 404 and status_url != status_urls[-1]:
|
| 95 |
+
logger.debug(f"Status endpoint {status_url} failed, trying next")
|
| 96 |
+
continue
|
| 97 |
+
status_response.raise_for_status()
|
| 98 |
+
status_data = status_response.json()
|
| 99 |
+
logger.debug(f"Status response: {status_data}")
|
| 100 |
+
status = status_data.get("task_status") or status_data.get("status")
|
| 101 |
+
if status in ("succeeded", "completed"):
|
| 102 |
+
image_url = (status_data.get("image_url") or
|
| 103 |
+
status_data.get("result", {}).get("image_url") or
|
| 104 |
+
status_data.get("output") or
|
| 105 |
+
status_data.get("data", {}).get("image") or
|
| 106 |
+
status_data.get("data", {}).get("images", [{}])[0].get("url"))
|
| 107 |
+
if not image_url:
|
| 108 |
+
logger.error("No image URL in API response")
|
| 109 |
+
return None, "Error: No image URL in API response. Check https://klingai.com/global/dev/model/image."
|
| 110 |
+
logger.debug(f"Downloading image from {image_url}")
|
| 111 |
+
image_response = requests.get(image_url, timeout=30)
|
| 112 |
+
image_response.raise_for_status()
|
| 113 |
+
output_path = Path("/tmp/output_image.png")
|
| 114 |
+
with open(output_path, "wb") as f:
|
| 115 |
+
f.write(image_response.content)
|
| 116 |
+
if not output_path.exists():
|
| 117 |
+
logger.error("Output image file not created")
|
| 118 |
+
return None, "Error: Failed to save output image."
|
| 119 |
+
logger.debug(f"Image saved to {output_path}")
|
| 120 |
+
return str(output_path), None
|
| 121 |
+
elif status == "failed":
|
| 122 |
+
logger.error("Image generation failed")
|
| 123 |
+
return None, "Error: Image generation failed. Ensure the image contains a clear face and avoid NSFW content."
|
| 124 |
+
elif status == "processing" and status_data.get("progress", 0) >= 0.99:
|
| 125 |
+
logger.error("Generation stuck at 99%")
|
| 126 |
+
return None, "Error: Generation stuck at 99%. Check account credits at https://app.klingai.com."
|
| 127 |
+
time.sleep(5)
|
| 128 |
+
|
| 129 |
+
logger.error("Image generation timed out")
|
| 130 |
+
return None, "Error: Image generation timed out. Try at 2 AM IST or check account status."
|
| 131 |
+
|
| 132 |
+
return None, f"Error: All status endpoints failed. Check https://klingai.com/global/dev/model/image."
|
| 133 |
+
|
| 134 |
+
except requests.exceptions.HTTPError as e:
|
| 135 |
+
status_code = e.response.status_code if e.response else None
|
| 136 |
+
error_data = e.response.json() if e.response and e.response.text else {}
|
| 137 |
+
service_code = error_data.get("code", 0)
|
| 138 |
+
error_message = error_data.get("message", str(e))
|
| 139 |
+
logger.error(f"HTTP error: {status_code}, Service Code: {service_code}, Details: {error_message}")
|
| 140 |
+
|
| 141 |
+
if error_message.startswith("Create task failed"):
|
| 142 |
+
logger.error("Create task failed error detected")
|
| 143 |
+
return None, "Error: Create task failed. Try at 2 AM IST, verify account at https://app.klingai.com, or join Kling AI Discord."
|
| 144 |
+
elif status_code == 404 and api_url != API_URLS[-1]:
|
| 145 |
+
logger.debug(f"Endpoint {api_url} failed with 404, trying next")
|
| 146 |
+
continue
|
| 147 |
+
elif status_code == 404:
|
| 148 |
+
return None, f"Error: Endpoint not found (404). Tried {', '.join(API_URLS)}. Verify endpoint at https://klingai.com/global/dev/model/image."
|
| 149 |
+
elif status_code == 401:
|
| 150 |
+
if service_code in (1000, 1001, 1002, 1003, 1004):
|
| 151 |
+
return None, f"Error: Authentication failed ({service_code}). Verify API keys or token settings."
|
| 152 |
+
elif status_code == 429:
|
| 153 |
+
if service_code in (1100, 1101, 1102, 1302, 1303, 1304):
|
| 154 |
+
return None, f"Error: Rate limit or account issue ({service_code}). Try at 2 AM IST or check https://app.klingai.com."
|
| 155 |
+
elif status_code == 403 and service_code == 1103:
|
| 156 |
+
return None, "Error: Unauthorized access (1103). Verify account permissions at https://app.klingai.com."
|
| 157 |
+
elif status_code == 400:
|
| 158 |
+
if service_code in (1200, 1201, 1300, 1301):
|
| 159 |
+
return None, f"Error: Invalid parameters ({service_code}). Use PNG/JPEG (<10 MB, ≥512x512) with a clear face."
|
| 160 |
+
elif status_code in (500, 503, 504):
|
| 161 |
+
if service_code in (5000, 5001, 5002):
|
| 162 |
+
return None, f"Error: Server issue ({service_code}). Try at 2 AM IST or contact support."
|
| 163 |
+
return None, f"Error: API request failed. HTTP {status_code}, Service Code {service_code}. Details: {error_message}"
|
| 164 |
+
except requests.exceptions.RequestException as e:
|
| 165 |
+
logger.error(f"Network error: {str(e)}")
|
| 166 |
+
return None, f"Error: Network issue. Ensure stable internet, disable VPN. Details: {str(e)}"
|
| 167 |
+
|
| 168 |
+
return None, f"Error: All API endpoints failed. Verify endpoint at https://klingai.com/global/dev/model/image."
|
| 169 |
+
|
| 170 |
+
def chatbot_interface(image, prompt):
|
| 171 |
+
"""
|
| 172 |
+
Gradio interface for single-reference face generation.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
image: Uploaded image file (containing a face)
|
| 176 |
+
prompt (str): Optional text prompt
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
tuple: (Output image path for display, output image path for download, error message)
|
| 180 |
+
"""
|
| 181 |
+
output_path, error = generate_image(image, prompt)
|
| 182 |
+
if error:
|
| 183 |
+
logger.debug(f"Error returned: {error}")
|
| 184 |
+
return None, None, error
|
| 185 |
+
logger.debug(f"Returning image path for display and download: {output_path}")
|
| 186 |
+
return output_path, output_path, None
|
| 187 |
|
| 188 |
+
# Define Gradio interface
|
| 189 |
+
with gr.Blocks() as iface:
|
| 190 |
+
gr.Markdown(
|
| 191 |
+
"""
|
| 192 |
+
# Kling AI Single-Reference Face Generator
|
| 193 |
+
Upload a PNG/JPEG image (<10 MB, ≥512x512 pixels) with a clear face to generate a transformed image using Kling AI Kolors 2.1 (strength 0.97). Avoid NSFW content.
|
| 194 |
+
If errors persist, verify endpoint at https://klingai.com/global/dev/model/image or contact support at https://app.klingai.com or Kling AI Discord.
|
| 195 |
+
"""
|
| 196 |
+
)
|
| 197 |
+
with gr.Row():
|
| 198 |
+
with gr.Column():
|
| 199 |
+
image_input = gr.Image(type="filepath", label="Upload Face Image (PNG/JPEG, <10 MB, ≥512x512)")
|
| 200 |
+
prompt_input = gr.Textbox(lines=2, placeholder="Enter an optional prompt (e.g., 'Turn this face into a cartoon')", label="Prompt")
|
| 201 |
+
generate_button = gr.Button("Generate")
|
| 202 |
+
with gr.Column():
|
| 203 |
+
output_image = gr.Image(label="Generated Face Image")
|
| 204 |
+
output_file = gr.File(label="Download Generated Image")
|
| 205 |
+
error_message = gr.Textbox(label="Status/Error Message", interactive=False)
|
| 206 |
+
|
| 207 |
+
generate_button.click(
|
| 208 |
+
fn=chatbot_interface,
|
| 209 |
+
inputs=[image_input, prompt_input],
|
| 210 |
+
outputs=[output_image, output_file, error_message]
|
| 211 |
+
)
|
| 212 |
|
| 213 |
+
# Launch the interface
|
| 214 |
if __name__ == "__main__":
|
| 215 |
+
logger.debug("Launching Gradio interface")
|
| 216 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|