AkashKumarave commited on
Commit
c3f22c6
·
verified ·
1 Parent(s): 85a7fa6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -155
app.py CHANGED
@@ -5,212 +5,110 @@ 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)
 
5
  import jwt
6
  import time
7
  import logging
 
8
 
9
  # Set up logging for debugging
10
  logging.basicConfig(level=logging.DEBUG)
11
  logger = logging.getLogger(__name__)
12
 
13
+ # Kling AI API configuration
14
  ACCESS_KEY_ID = "AFyHfnQATghFdCMyAG3gRPbNY4TNKFGB"
15
  ACCESS_KEY_SECRET = "TTepeLyBterLNM3brYPGmdndBnnyKJBA"
16
+ API_URL = "https://api-singapore.klingai.com/v1/images/generations"
 
 
 
 
17
 
18
  def generate_jwt_token():
19
  """Generate JWT token for Kling AI API authentication."""
 
20
  payload = {
21
  "iss": ACCESS_KEY_ID,
22
  "exp": int(time.time()) + 1800,
23
  "nbf": int(time.time()) - 5
24
  }
25
+ token = jwt.encode(payload, ACCESS_KEY_SECRET, algorithm="HS256")
26
+ return token if isinstance(token, str) else token.decode("utf-8")
 
27
 
28
  def generate_image(image, prompt=""):
29
+ """Call Kling AI API for image-to-image generation."""
 
 
 
 
 
 
 
 
 
30
  if not image:
31
+ return None, "Error: Please upload a valid image."
32
+
 
33
  try:
34
  with open(image, "rb") as img_file:
35
  image_base64 = base64.b64encode(img_file.read()).decode("utf-8")
 
36
  except Exception as e:
37
+ return None, f"Error: Failed to process image. Details: {str(e)}"
38
+
 
39
  headers = {
40
  "Authorization": f"Bearer {generate_jwt_token()}",
41
  "Content-Type": "application/json"
42
  }
43
+
44
  payload = {
45
+ "model": "kolors-v2.1",
 
46
  "prompt": prompt or "Transform the face into a cartoon style while preserving identity",
47
+ "image_base64_list": [image_base64],
48
  "strength": 0.97,
49
  "output_format": "png",
50
+ "num_outputs": 1,
51
  "aspect_ratio": "1:1"
52
  }
53
+
54
+ try:
55
+ logger.debug(f"Sending POST to {API_URL} with payload")
56
+ response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
57
+ response.raise_for_status()
58
+ data = response.json()
59
+ logger.debug(f"API response: {data}")
60
+
61
+ task_id = data.get("data", {}).get("task_id")
62
+ if not task_id:
63
+ return None, "Error: No task ID returned."
64
+
65
+ # Poll task until completion
66
+ status_url = f"https://api-singapore.klingai.com/v1/images/task/{task_id}"
67
+ for _ in range(60): # up to 5 minutes
68
+ status_response = requests.get(status_url, headers=headers, timeout=30)
69
+ status_response.raise_for_status()
70
+ status_data = status_response.json()
71
+ logger.debug(f"Status: {status_data}")
72
+ task_status = status_data.get("data", {}).get("task_status")
73
+ if task_status == "succeed":
74
+ image_url = status_data["data"]["images"][0]["url"]
75
+ img_resp = requests.get(image_url, timeout=30)
76
+ output_path = Path("/tmp/output_image.png")
77
+ with open(output_path, "wb") as f:
78
+ f.write(img_resp.content)
79
+ return str(output_path), None
80
+ elif task_status in ("failed", "canceled"):
81
+ return None, f"Error: Task failed. Details: {status_data}"
82
+ time.sleep(5)
83
+ return None, "Error: Task polling timed out."
84
+
85
+ except requests.exceptions.RequestException as e:
86
+ return None, f"Error: API request failed. Details: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  def chatbot_interface(image, prompt):
 
 
 
 
 
 
 
 
 
 
89
  output_path, error = generate_image(image, prompt)
90
  if error:
 
91
  return None, None, error
 
92
  return output_path, output_path, None
93
 
94
  # Define Gradio interface
95
  with gr.Blocks() as iface:
96
+ gr.Markdown("# Kling AI Image-to-Image Generator")
 
 
 
 
 
 
97
  with gr.Row():
98
  with gr.Column():
99
+ image_input = gr.Image(type="filepath", label="Upload Image")
100
+ prompt_input = gr.Textbox(lines=2, placeholder="Enter prompt", label="Prompt")
101
  generate_button = gr.Button("Generate")
102
  with gr.Column():
103
+ output_image = gr.Image(label="Generated Image")
104
  output_file = gr.File(label="Download Generated Image")
105
  error_message = gr.Textbox(label="Status/Error Message", interactive=False)
106
+
107
  generate_button.click(
108
  fn=chatbot_interface,
109
  inputs=[image_input, prompt_input],
110
  outputs=[output_image, output_file, error_message]
111
  )
112
 
 
113
  if __name__ == "__main__":
114
+ iface.launch(server_name="0.0.0.0", server_port=7860)