AkashKumarave commited on
Commit
c95cf2c
·
verified ·
1 Parent(s): e76633e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -75
app.py CHANGED
@@ -4,119 +4,218 @@ import base64
4
  from pathlib import Path
5
  import jwt
6
  import time
 
7
  import os
8
 
9
- # === Kling AI API configuration ===
 
 
 
 
10
  ACCESS_KEY_ID = "AGBGmadNd9hakFYfahytyQQJtN8CJmDJ"
11
  ACCESS_KEY_SECRET = "dp3pAe4PpdmnAHCAPgEd3PyLmBQrkMde"
12
- API_URL = "https://api-singapore.klingai.com/v1/generate/image"
13
 
14
- # === Generate JWT Token ===
15
  def generate_jwt_token():
 
16
  headers = {
17
  "alg": "HS256",
18
  "typ": "JWT"
19
  }
20
- now = int(time.time())
21
  payload = {
22
  "iss": ACCESS_KEY_ID,
23
- "exp": now + 1800, # valid for 30 mins
24
- "nbf": now - 5
25
  }
26
- return jwt.encode(payload, ACCESS_KEY_SECRET, algorithm="HS256", headers=headers)
27
-
28
- # === Image to Image Generation ===
29
- def generate_image(reference_image, prompt=""):
30
- if not reference_image:
31
- return None, None
32
-
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  try:
34
- with open(reference_image, "rb") as img_file:
35
- reference_base64 = base64.b64encode(img_file.read()).decode("utf-8")
 
36
  except Exception as e:
37
- return None, f"Error reading reference image: {str(e)}"
38
-
 
39
  headers = {
40
  "Authorization": f"Bearer {generate_jwt_token()}",
41
  "Content-Type": "application/json"
42
  }
43
-
44
  payload = {
45
- "reference_image": reference_base64,
46
- "mode": "face", # face reference mode
47
- "prompt": prompt or "Match face with high fidelity",
48
- "strength": 0.97,
49
  "output_format": "png"
50
  }
51
-
52
  try:
53
- # Start generation
54
  response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
55
  response.raise_for_status()
56
  data = response.json()
57
- task_id = data.get("task_id") or data.get("id")
 
 
58
  if not task_id:
59
- return None, f"Error: No task ID returned: {data}"
60
-
61
- # Poll for completion
62
- status_url = f"https://api-singapore.klingai.com/v1/predictions/{task_id}"
63
- for _ in range(60): # up to 5 minutes
 
 
64
  status_response = requests.get(status_url, headers=headers, timeout=30)
65
  status_response.raise_for_status()
66
  status_data = status_response.json()
 
67
  status = status_data.get("status")
68
-
69
  if status == "succeeded":
70
- # Find image URL in all possible keys
71
- image_url = (
72
- status_data.get("image_url")
73
- or status_data.get("result", {}).get("image_url")
74
- or (status_data.get("output")[0] if isinstance(status_data.get("output"), list) else status_data.get("output"))
75
- )
76
  if not image_url:
77
- return None, f"Error: No image URL found in response: {status_data}"
78
-
79
- # Download the generated image
80
- img_resp = requests.get(image_url, timeout=30)
81
- img_resp.raise_for_status()
82
- output_path = Path("output.png")
 
83
  with open(output_path, "wb") as f:
84
- f.write(img_resp.content)
85
-
 
 
 
86
  return str(output_path), None
87
-
88
  elif status == "failed":
89
- return None, "Error: Generation failed."
90
-
 
 
 
91
  time.sleep(5)
92
-
93
- return None, "Error: Timed out."
94
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  except requests.exceptions.RequestException as e:
96
- return None, f"Request error: {str(e)}"
97
-
98
- # === Gradio Interface ===
99
- def process(reference_image, prompt):
100
- image_path, error = generate_image(reference_image, prompt)
 
 
 
 
 
 
 
 
 
 
101
  if error:
 
102
  return None, None, error
103
- download_link = image_path if image_path else None
104
- return image_path, download_link, "✅ Image generated successfully!"
105
-
106
- iface = gr.Interface(
107
- fn=process,
108
- inputs=[
109
- gr.Image(type="filepath", label="Upload Reference Face Image"),
110
- gr.Textbox(lines=2, placeholder="Optional prompt", label="Prompt")
111
- ],
112
- outputs=[
113
- gr.Image(label="Generated Image"),
114
- gr.File(label="Download Image"),
115
- gr.Textbox(label="Status")
116
- ],
117
- title="Kling AI - Single Reference Face Generator",
118
- description="Upload a reference face image. The model will generate an image based on that face with 97% strength."
119
- )
120
-
 
 
 
 
 
 
 
 
 
 
121
  if __name__ == "__main__":
122
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
 
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 (keys hardcoded as requested)
15
  ACCESS_KEY_ID = "AGBGmadNd9hakFYfahytyQQJtN8CJmDJ"
16
  ACCESS_KEY_SECRET = "dp3pAe4PpdmnAHCAPgEd3PyLmBQrkMde"
17
+ API_URL = "https://api.klingai.com/v1/predictions" # Updated endpoint
18
 
 
19
  def generate_jwt_token():
20
+ """Generate JWT token for Kling AI API authentication."""
21
  headers = {
22
  "alg": "HS256",
23
  "typ": "JWT"
24
  }
 
25
  payload = {
26
  "iss": ACCESS_KEY_ID,
27
+ "exp": int(time.time()) + 1800, # Token expires in 30 minutes
28
+ "nbf": int(time.time()) - 5 # Effective 5 seconds before current time
29
  }
30
+ token = jwt.encode(payload, ACCESS_KEY_SECRET, headers=headers)
31
+ logger.debug(f"Generated JWT token: {token}")
32
+ return token
33
+
34
+ def generate_image(image, prompt=""):
35
+ """
36
+ Call Kling AI API for single-reference face generation.
37
+
38
+ Args:
39
+ image: Uploaded image file (from Gradio, face image)
40
+ prompt (str): Optional text prompt to guide transformation
41
+
42
+ Returns:
43
+ tuple: (Path to generated image or None, error message or None)
44
+ """
45
+ if not image:
46
+ logger.error("No image uploaded")
47
+ return None, "Error: Please upload a valid face image (PNG/JPEG, <10 MB, ≥512x512 pixels)."
48
+
49
+ # Convert image to base64
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
+ "image": image_base64,
65
+ "prompt": prompt or "Transform the face into a cartoon style while preserving identity",
66
+ "strength": 0.97, # High reference strength for face preservation
 
67
  "output_format": "png"
68
  }
69
+
70
  try:
71
+ logger.debug(f"Sending POST request to {API_URL} with payload: {payload}")
72
  response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
73
  response.raise_for_status()
74
  data = response.json()
75
+ logger.debug(f"API response: {data}")
76
+
77
+ task_id = data.get("task_id") or data.get("taskId") or data.get("id")
78
  if not task_id:
79
+ logger.error("No task ID returned in API response")
80
+ return None, "Error: No task ID returned. Check API endpoint or keys at https://klingai.com/global/dev."
81
+
82
+ # Poll for task completion
83
+ status_url = f"{API_URL}/{task_id}"
84
+ for _ in range(60): # Poll for up to 5 minutes
85
+ logger.debug(f"Polling status at {status_url}")
86
  status_response = requests.get(status_url, headers=headers, timeout=30)
87
  status_response.raise_for_status()
88
  status_data = status_response.json()
89
+ logger.debug(f"Status response: {status_data}")
90
  status = status_data.get("status")
 
91
  if status == "succeeded":
92
+ image_url = status_data.get("image_url") or status_data.get("result", {}).get("image_url") or status_data.get("output") or status_data.get("data", {}).get("image")
 
 
 
 
 
93
  if not image_url:
94
+ logger.error("No image URL in API response")
95
+ return None, "Error: No image URL in API response. Check API documentation at https://klingai.com/global/dev."
96
+ # Download the image
97
+ logger.debug(f"Downloading image from {image_url}")
98
+ image_response = requests.get(image_url, timeout=30)
99
+ image_response.raise_for_status()
100
+ output_path = Path("/tmp/output_image.png") # Use /tmp for Spaces compatibility
101
  with open(output_path, "wb") as f:
102
+ f.write(image_response.content)
103
+ if not output_path.exists():
104
+ logger.error("Output image file not created")
105
+ return None, "Error: Failed to save output image."
106
+ logger.debug(f"Image saved to {output_path}")
107
  return str(output_path), None
 
108
  elif status == "failed":
109
+ logger.error("Image generation failed")
110
+ return None, "Error: Image generation failed. Ensure the image contains a clear face and avoid NSFW or sensitive content."
111
+ elif status == "processing" and status_data.get("progress", 0) >= 0.99:
112
+ logger.error("Generation stuck at 99%")
113
+ return None, "Error: Generation stuck at 99%. Check account credits or upgrade to a paid plan at https://klingai.com."
114
  time.sleep(5)
115
+
116
+ logger.error("Image generation timed out")
117
+ return None, "Error: Image generation timed out. Try during off-peak hours or check account status."
118
+
119
+ except requests.exceptions.HTTPError as e:
120
+ status_code = e.response.status_code if e.response else None
121
+ error_data = e.response.json() if e.response and e.response.text else {}
122
+ service_code = error_data.get("code", 0)
123
+ logger.error(f"HTTP error: {status_code}, Service Code: {service_code}, Details: {str(e)}")
124
+
125
+ if status_code == 404:
126
+ if service_code == 1202:
127
+ return None, "Error: Invalid request method (1202). Check https://klingai.com/global/dev for correct endpoint."
128
+ elif service_code == 1203:
129
+ return None, "Error: Resource does not exist (1203). Verify model or endpoint."
130
+ return None, f"Error: Endpoint not found (404). Try https://api.klingai.com/v1/predictions or check https://klingai.com/global/dev."
131
+ elif status_code == 401:
132
+ if service_code == 1000:
133
+ return None, "Error: Authentication failed (1000). Verify API keys are correct."
134
+ elif service_code == 1001:
135
+ return None, "Error: Authorization empty (1001). Ensure JWT token is included."
136
+ elif service_code == 1002:
137
+ return None, "Error: Authorization invalid (1002). Check key format."
138
+ elif service_code == 1003:
139
+ return None, "Error: Authorization not yet valid (1003). Adjust token start time (nbf)."
140
+ elif service_code == 1004:
141
+ return None, "Error: Authorization expired (1004). Generate a new token."
142
+ elif status_code == 429:
143
+ if service_code == 1100:
144
+ return None, "Error: Account exception (1100). Verify account configuration at https://klingai.com."
145
+ elif service_code == 1101:
146
+ return None, "Error: Account in arrears (1101). Recharge your account."
147
+ elif service_code == 1102:
148
+ return None, "Error: Resource pack depleted or expired (1102). Purchase additional resources."
149
+ elif service_code in (1302, 1303):
150
+ return None, "Error: Rate limit exceeded (1302/1303). Reduce request frequency or contact support."
151
+ elif service_code == 1304:
152
+ return None, "Error: IP whitelisting issue (1304). Contact Kling AI support."
153
+ elif status_code == 403 and service_code == 1103:
154
+ return None, "Error: Unauthorized access (1103). Verify account permissions."
155
+ elif status_code == 400:
156
+ if service_code == 1200:
157
+ return None, "Error: Invalid request parameters (1200). Check payload format."
158
+ elif service_code == 1201:
159
+ return None, "Error: Invalid parameters (1201). Use PNG/JPEG (<10 MB, ≥512x512) with a clear face."
160
+ elif service_code == 1300:
161
+ return None, "Error: Platform policy triggered (1300). Check input content."
162
+ elif service_code == 1301:
163
+ return None, "Error: Content security policy triggered (1301). Ensure the image contains a clear face and avoid NSFW content."
164
+ elif status_code in (500, 503, 504):
165
+ if service_code == 5000:
166
+ return None, "Error: Server internal error (5000). Try again later."
167
+ elif service_code == 5001:
168
+ return None, "Error: Server unavailable due to maintenance (5001). Try again later."
169
+ elif service_code == 5002:
170
+ return None, "Error: Server timeout (5002). Try during off-peak hours."
171
+ return None, f"Error: API request failed. HTTP {status_code}, Service Code {service_code}. Details: {str(e)}"
172
  except requests.exceptions.RequestException as e:
173
+ logger.error(f"Network error: {str(e)}")
174
+ return None, f"Error: Network issue. Ensure stable internet, disable VPN, and try again. Details: {str(e)}"
175
+
176
+ def chatbot_interface(image, prompt):
177
+ """
178
+ Gradio interface for single-reference face generation.
179
+
180
+ Args:
181
+ image: Uploaded image file (containing a face)
182
+ prompt (str): Optional text prompt
183
+
184
+ Returns:
185
+ tuple: (Output image path for display, output image path for download, error message)
186
+ """
187
+ output_path, error = generate_image(image, prompt)
188
  if error:
189
+ logger.debug(f"Error returned: {error}")
190
  return None, None, error
191
+ logger.debug(f"Returning image path for display and download: {output_path}")
192
+ return output_path, output_path, None
193
+
194
+ # Define Gradio interface
195
+ with gr.Blocks() as iface:
196
+ gr.Markdown(
197
+ """
198
+ # Kling AI Single-Reference Face Generator
199
+ Upload a PNG/JPEG image (<10 MB, ≥512x512 pixels) with a clear face to generate a transformed image using Kling AI API (reference strength 0.97). Avoid NSFW or sensitive content.
200
+ """
201
+ )
202
+ with gr.Row():
203
+ with gr.Column():
204
+ image_input = gr.Image(type="filepath", label="Upload Face Image (PNG/JPEG, <10 MB, ≥512x512)")
205
+ prompt_input = gr.Textbox(lines=2, placeholder="Enter an optional prompt (e.g., 'Turn this face into a cartoon')", label="Prompt")
206
+ generate_button = gr.Button("Generate")
207
+ with gr.Column():
208
+ output_image = gr.Image(label="Generated Face Image")
209
+ output_file = gr.File(label="Download Generated Image")
210
+ error_message = gr.Textbox(label="Status/Error Message", interactive=False)
211
+
212
+ generate_button.click(
213
+ fn=chatbot_interface,
214
+ inputs=[image_input, prompt_input],
215
+ outputs=[output_image, output_file, error_message]
216
+ )
217
+
218
+ # Launch the interface
219
  if __name__ == "__main__":
220
+ logger.debug("Launching Gradio interface")
221
+ iface.launch(server_name="0.0.0.0", server_port=7860)