AkashKumarave commited on
Commit
1c84264
·
verified ·
1 Parent(s): 85857de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -67
app.py CHANGED
@@ -6,10 +6,10 @@ import jwt
6
  import time
7
  import logging
8
 
9
- # ================== CONFIGURATION ==================
10
- ACCESS_KEY_ID = "AGBGmadNd9hakFYfahytyQQJtN8CJmDJ"
11
- ACCESS_KEY_SECRET = "dp3pAe4PpdmnAHCAPgEd3PyLmBQrkMde"
12
- API_URL = "https://api-singapore.klingai.com/v1/images/generations" # New unified endpoint
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
- token = jwt.encode(payload, ACCESS_KEY_SECRET, headers=headers)
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: Failed to process image. Details: {str(e)}"
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": "kolors-v2.1",
49
- "image_base64": [image_base64], # New format: array of base64 images
50
- "prompt": prompt or "Transform the face into a cartoon style while preserving identity",
51
- "strength": 0.97,
52
- "output_format": "png",
53
- "n": 1,
54
- "aspect_ratio": "1:1"
55
  }
56
 
57
  try:
58
- logger.debug(f"Sending POST request to {API_URL}")
59
  response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
60
  response.raise_for_status()
61
  data = response.json()
62
 
63
- task_id = data.get("task_id") or data.get("data", {}).get("task_id")
64
- if not task_id:
65
- return None, "Error: No task ID returned from API."
66
 
67
- # ================== POLLING ==================
68
- status_url = f"https://api-singapore.klingai.com/v1/tasks/{task_id}"
69
- for _ in range(60):
 
 
 
70
  time.sleep(5)
71
- status_response = requests.get(status_url, headers=headers, timeout=30)
72
- if status_response.status_code == 404:
73
- continue
74
- status_data = status_response.json()
75
- status = status_data.get("task_status") or status_data.get("status")
76
-
77
- if status in ("succeeded", "completed"):
78
- image_url = (
79
- status_data.get("image_url")
80
- or status_data.get("data", {}).get("image")
81
- or status_data.get("data", {}).get("images", [{}])[0].get("url")
82
- )
83
- if not image_url:
84
- return None, "Error: No image URL in API response."
85
-
86
- image_response = requests.get(image_url, timeout=30)
87
- image_response.raise_for_status()
88
- output_path = Path("/tmp/output_image.png")
89
- with open(output_path, "wb") as f:
90
- f.write(image_response.content)
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: {str(e)}"
100
- except requests.exceptions.RequestException as e:
101
- return None, f"Network Error: {str(e)}"
102
 
103
 
104
- # ================== GRADIO INTERFACE ==================
105
  def chatbot_interface(image, prompt):
106
- output_path, error = generate_image(image, prompt)
107
  if error:
108
  return None, None, error
109
- return output_path, output_path, None
110
 
111
 
112
  with gr.Blocks() as iface:
113
- gr.Markdown("# Kling AI Image-to-Image Generator (Kolors v2.1)")
114
 
115
  with gr.Row():
116
  with gr.Column():
117
- image_input = gr.Image(type="filepath", label="Upload Face Image")
118
- prompt_input = gr.Textbox(lines=2, placeholder="Enter prompt", label="Prompt")
119
- generate_button = gr.Button("Generate")
120
  with gr.Column():
121
- output_image = gr.Image(label="Generated Image")
122
- output_file = gr.File(label="Download Image")
123
- error_message = gr.Textbox(label="Status/Error", interactive=False)
124
-
125
- generate_button.click(
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)