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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -156
app.py CHANGED
@@ -5,21 +5,17 @@ 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
15
- ACCESS_KEY_ID = "AGBGmadNd9hakFYfahytyQQJtN8CJmDJ"
16
- ACCESS_KEY_SECRET = "dp3pAe4PpdmnAHCAPgEd3PyLmBQrkMde"
17
- API_URLS = [
18
- "https://api-singapore.klingai.com/v1/images/image2image", # Primary endpoint from your update
19
- "https://api-singapore.klingai.com/v1/images/kolors", # Fallback for Kolors 2.1
20
- "https://api-singapore.klingai.com/v1/images/generations" # Fallback from
21
- ]
22
 
 
23
  def generate_jwt_token():
24
  """Generate JWT token for Kling AI API authentication."""
25
  headers = {"alg": "HS256", "typ": "JWT"}
@@ -29,188 +25,108 @@ def generate_jwt_token():
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)
 
5
  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__)
16
 
 
 
 
 
 
 
 
 
17
 
18
+ # ================== AUTH ==================
19
  def generate_jwt_token():
20
  """Generate JWT token for Kling AI API authentication."""
21
  headers = {"alg": "HS256", "typ": "JWT"}
 
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 ==================
32
  def generate_image(image, prompt=""):
 
 
 
 
 
 
 
 
 
 
33
  if not image:
34
+ return None, "Error: Please upload a valid face image."
35
+
 
36
  try:
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()}",
44
  "Content-Type": "application/json"
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)