Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,10 +6,10 @@ import jwt
|
|
| 6 |
import time
|
| 7 |
import logging
|
| 8 |
|
| 9 |
-
# ==================
|
| 10 |
-
ACCESS_KEY_ID = "
|
| 11 |
-
ACCESS_KEY_SECRET = "
|
| 12 |
-
API_URL = "https://api-singapore.klingai.com/v1/images/generations"
|
| 13 |
|
| 14 |
logging.basicConfig(level=logging.DEBUG)
|
| 15 |
logger = logging.getLogger(__name__)
|
|
@@ -17,15 +17,13 @@ logger = logging.getLogger(__name__)
|
|
| 17 |
|
| 18 |
# ================== AUTH ==================
|
| 19 |
def generate_jwt_token():
|
| 20 |
-
"""Generate JWT token for Kling AI API authentication."""
|
| 21 |
headers = {"alg": "HS256", "typ": "JWT"}
|
| 22 |
payload = {
|
| 23 |
"iss": ACCESS_KEY_ID,
|
| 24 |
"exp": int(time.time()) + 1800,
|
| 25 |
"nbf": int(time.time()) - 5
|
| 26 |
}
|
| 27 |
-
|
| 28 |
-
return token
|
| 29 |
|
| 30 |
|
| 31 |
# ================== IMAGE GENERATION ==================
|
|
@@ -37,7 +35,7 @@ def generate_image(image, prompt=""):
|
|
| 37 |
with open(image, "rb") as img_file:
|
| 38 |
image_base64 = base64.b64encode(img_file.read()).decode("utf-8")
|
| 39 |
except Exception as e:
|
| 40 |
-
return None, f"Error
|
| 41 |
|
| 42 |
headers = {
|
| 43 |
"Authorization": f"Bearer {generate_jwt_token()}",
|
|
@@ -45,88 +43,79 @@ def generate_image(image, prompt=""):
|
|
| 45 |
}
|
| 46 |
|
| 47 |
payload = {
|
| 48 |
-
"model_name": "
|
| 49 |
-
"
|
| 50 |
-
"
|
| 51 |
-
"
|
| 52 |
-
"
|
| 53 |
-
"
|
| 54 |
-
"aspect_ratio": "1:1"
|
| 55 |
}
|
| 56 |
|
| 57 |
try:
|
| 58 |
-
logger.debug(f"
|
| 59 |
response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
|
| 60 |
response.raise_for_status()
|
| 61 |
data = response.json()
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
return None, "Error: No task ID returned from API."
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
| 70 |
time.sleep(5)
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
status_data
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
return str(output_path), None
|
| 92 |
-
|
| 93 |
-
elif status == "failed":
|
| 94 |
-
return None, "Error: Image generation failed."
|
| 95 |
-
|
| 96 |
-
return None, "Error: Image generation timed out."
|
| 97 |
|
| 98 |
except requests.exceptions.HTTPError as e:
|
| 99 |
-
return None, f"HTTP Error: {
|
| 100 |
-
except
|
| 101 |
-
return None, f"
|
| 102 |
|
| 103 |
|
| 104 |
-
# ================== GRADIO
|
| 105 |
def chatbot_interface(image, prompt):
|
| 106 |
-
|
| 107 |
if error:
|
| 108 |
return None, None, error
|
| 109 |
-
return
|
| 110 |
|
| 111 |
|
| 112 |
with gr.Blocks() as iface:
|
| 113 |
-
gr.Markdown("# Kling AI Image
|
| 114 |
|
| 115 |
with gr.Row():
|
| 116 |
with gr.Column():
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
with gr.Column():
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
fn=chatbot_interface,
|
| 127 |
-
inputs=[image_input, prompt_input],
|
| 128 |
-
outputs=[output_image, output_file, error_message]
|
| 129 |
-
)
|
| 130 |
|
| 131 |
if __name__ == "__main__":
|
| 132 |
iface.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 6 |
import time
|
| 7 |
import logging
|
| 8 |
|
| 9 |
+
# ================== CONFIG ==================
|
| 10 |
+
ACCESS_KEY_ID = "YOUR_ACCESS_KEY_ID"
|
| 11 |
+
ACCESS_KEY_SECRET = "YOUR_ACCESS_KEY_SECRET"
|
| 12 |
+
API_URL = "https://api-singapore.klingai.com/v1/images/generations"
|
| 13 |
|
| 14 |
logging.basicConfig(level=logging.DEBUG)
|
| 15 |
logger = logging.getLogger(__name__)
|
|
|
|
| 17 |
|
| 18 |
# ================== AUTH ==================
|
| 19 |
def generate_jwt_token():
|
|
|
|
| 20 |
headers = {"alg": "HS256", "typ": "JWT"}
|
| 21 |
payload = {
|
| 22 |
"iss": ACCESS_KEY_ID,
|
| 23 |
"exp": int(time.time()) + 1800,
|
| 24 |
"nbf": int(time.time()) - 5
|
| 25 |
}
|
| 26 |
+
return jwt.encode(payload, ACCESS_KEY_SECRET, headers=headers)
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
# ================== IMAGE GENERATION ==================
|
|
|
|
| 35 |
with open(image, "rb") as img_file:
|
| 36 |
image_base64 = base64.b64encode(img_file.read()).decode("utf-8")
|
| 37 |
except Exception as e:
|
| 38 |
+
return None, f"Error reading image: {e}"
|
| 39 |
|
| 40 |
headers = {
|
| 41 |
"Authorization": f"Bearer {generate_jwt_token()}",
|
|
|
|
| 43 |
}
|
| 44 |
|
| 45 |
payload = {
|
| 46 |
+
"model_name": "kling-v2-1", # ✅ per docs
|
| 47 |
+
"prompt": prompt or "Transform face into artistic style",
|
| 48 |
+
"image": image_base64, # ✅ base64 only, no prefix
|
| 49 |
+
"aspect_ratio": "1:1",
|
| 50 |
+
"n": 1, # number of images
|
| 51 |
+
"resolution": "1k"
|
|
|
|
| 52 |
}
|
| 53 |
|
| 54 |
try:
|
| 55 |
+
logger.debug(f"POST {API_URL} payload={payload.keys()}")
|
| 56 |
response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
|
| 57 |
response.raise_for_status()
|
| 58 |
data = response.json()
|
| 59 |
|
| 60 |
+
if data.get("code") != 0:
|
| 61 |
+
return None, f"API Error: {data.get('message')}"
|
|
|
|
| 62 |
|
| 63 |
+
task_id = data["data"]["task_id"]
|
| 64 |
+
logger.debug(f"Task ID: {task_id}")
|
| 65 |
+
|
| 66 |
+
# Poll task status
|
| 67 |
+
status_url = f"{API_URL}/{task_id}"
|
| 68 |
+
for _ in range(60): # up to ~5 minutes
|
| 69 |
time.sleep(5)
|
| 70 |
+
status_resp = requests.get(status_url, headers=headers, timeout=30)
|
| 71 |
+
status_data = status_resp.json()
|
| 72 |
+
|
| 73 |
+
if status_data.get("data", {}).get("task_status") == "succeed":
|
| 74 |
+
images = status_data["data"]["task_result"]["images"]
|
| 75 |
+
if images:
|
| 76 |
+
img_url = images[0]["url"]
|
| 77 |
+
img_resp = requests.get(img_url)
|
| 78 |
+
img_resp.raise_for_status()
|
| 79 |
+
out_path = Path("/tmp/output.png")
|
| 80 |
+
with open(out_path, "wb") as f:
|
| 81 |
+
f.write(img_resp.content)
|
| 82 |
+
return str(out_path), None
|
| 83 |
+
else:
|
| 84 |
+
return None, "No image returned."
|
| 85 |
+
|
| 86 |
+
elif status_data.get("data", {}).get("task_status") == "failed":
|
| 87 |
+
return None, f"Generation failed: {status_data['data'].get('task_status_msg')}"
|
| 88 |
+
|
| 89 |
+
return None, "Timed out waiting for result."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
except requests.exceptions.HTTPError as e:
|
| 92 |
+
return None, f"HTTP Error: {e}"
|
| 93 |
+
except Exception as e:
|
| 94 |
+
return None, f"Unexpected Error: {e}"
|
| 95 |
|
| 96 |
|
| 97 |
+
# ================== GRADIO UI ==================
|
| 98 |
def chatbot_interface(image, prompt):
|
| 99 |
+
image_path, error = generate_image(image, prompt)
|
| 100 |
if error:
|
| 101 |
return None, None, error
|
| 102 |
+
return image_path, image_path, None
|
| 103 |
|
| 104 |
|
| 105 |
with gr.Blocks() as iface:
|
| 106 |
+
gr.Markdown("# Kling AI Image Generator — Official API Format")
|
| 107 |
|
| 108 |
with gr.Row():
|
| 109 |
with gr.Column():
|
| 110 |
+
img_in = gr.Image(type="filepath", label="Upload Image")
|
| 111 |
+
prompt_in = gr.Textbox(lines=2, placeholder="Enter prompt", label="Prompt")
|
| 112 |
+
btn = gr.Button("Generate")
|
| 113 |
with gr.Column():
|
| 114 |
+
img_out = gr.Image(label="Generated Image")
|
| 115 |
+
file_out = gr.File(label="Download Image")
|
| 116 |
+
err_out = gr.Textbox(label="Error / Status", interactive=False)
|
| 117 |
+
|
| 118 |
+
btn.click(fn=chatbot_interface, inputs=[img_in, prompt_in], outputs=[img_out, file_out, err_out])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
if __name__ == "__main__":
|
| 121 |
iface.launch(server_name="0.0.0.0", server_port=7860)
|