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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -172
app.py CHANGED
@@ -4,217 +4,119 @@ import base64
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-singapore.klingai.com/v1/image-to-image"
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"https://api-singapore.klingai.com/v1/predictions/{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."
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 == 401:
126
- if service_code == 1000:
127
- return None, "Error: Authentication failed (1000). Verify API keys are correct."
128
- elif service_code == 1001:
129
- return None, "Error: Authorization empty (1001). Ensure JWT token is included."
130
- elif service_code == 1002:
131
- return None, "Error: Authorization invalid (1002). Check key format."
132
- elif service_code == 1003:
133
- return None, "Error: Authorization not yet valid (1003). Adjust token start time (nbf)."
134
- elif service_code == 1004:
135
- return None, "Error: Authorization expired (1004). Generate a new token."
136
- elif status_code == 429:
137
- if service_code == 1100:
138
- return None, "Error: Account exception (1100). Verify account configuration at https://klingai.com."
139
- elif service_code == 1101:
140
- return None, "Error: Account in arrears (1101). Recharge your account."
141
- elif service_code == 1102:
142
- return None, "Error: Resource pack depleted or expired (1102). Purchase additional resources."
143
- elif service_code in (1302, 1303):
144
- return None, "Error: Rate limit exceeded (1302/1303). Reduce request frequency or contact support."
145
- elif service_code == 1304:
146
- return None, "Error: IP whitelisting issue (1304). Contact Kling AI support."
147
- elif status_code == 403 and service_code == 1103:
148
- return None, "Error: Unauthorized access (1103). Verify account permissions."
149
- elif status_code == 400:
150
- if service_code == 1200:
151
- return None, "Error: Invalid request parameters (1200). Check payload format."
152
- elif service_code == 1201:
153
- return None, "Error: Invalid parameters (1201). Use PNG/JPEG (<10 MB, ≥512x512) with a clear face."
154
- elif service_code == 1300:
155
- return None, "Error: Platform policy triggered (1300). Check input content."
156
- elif service_code == 1301:
157
- return None, "Error: Content security policy triggered (1301). Ensure the image contains a clear face and avoid NSFW content."
158
- elif status_code == 404:
159
- if service_code == 1202:
160
- return None, "Error: Invalid request method (1202). Check https://klingai.com/global/dev for correct endpoint."
161
- elif service_code == 1203:
162
- return None, "Error: Resource does not exist (1203). Verify model or endpoint."
163
- elif status_code in (500, 503, 504):
164
- if service_code == 5000:
165
- return None, "Error: Server internal error (5000). Try again later."
166
- elif service_code == 5001:
167
- return None, "Error: Server unavailable due to maintenance (5001). Try again later."
168
- elif service_code == 5002:
169
- return None, "Error: Server timeout (5002). Try during off-peak hours."
170
- return None, f"Error: API request failed. HTTP {status_code}, Service Code {service_code}. Details: {str(e)}"
171
  except requests.exceptions.RequestException as e:
172
- logger.error(f"Network error: {str(e)}")
173
- return None, f"Error: Network issue. Ensure stable internet, disable VPN, and try again. Details: {str(e)}"
174
-
175
- def chatbot_interface(image, prompt):
176
- """
177
- Gradio interface for single-reference face generation.
178
-
179
- Args:
180
- image: Uploaded image file (containing a face)
181
- prompt (str): Optional text prompt
182
-
183
- Returns:
184
- tuple: (Output image path for display, output image path for download, error message)
185
- """
186
- output_path, error = generate_image(image, prompt)
187
  if error:
188
- logger.debug(f"Error returned: {error}")
189
  return None, None, error
190
- logger.debug(f"Returning image path for display and download: {output_path}")
191
- return output_path, output_path, None
192
-
193
- # Define Gradio interface
194
- with gr.Blocks() as iface:
195
- gr.Markdown(
196
- """
197
- # Kling AI Single-Reference Face Generator
198
- 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.
199
- """
200
- )
201
- with gr.Row():
202
- with gr.Column():
203
- image_input = gr.Image(type="filepath", label="Upload Face Image (PNG/JPEG, <10 MB, ≥512x512)")
204
- prompt_input = gr.Textbox(lines=2, placeholder="Enter an optional prompt (e.g., 'Turn this face into a cartoon')", label="Prompt")
205
- generate_button = gr.Button("Generate")
206
- with gr.Column():
207
- output_image = gr.Image(label="Generated Face Image")
208
- output_file = gr.File(label="Download Generated Image")
209
- error_message = gr.Textbox(label="Status/Error Message", interactive=False)
210
-
211
- generate_button.click(
212
- fn=chatbot_interface,
213
- inputs=[image_input, prompt_input],
214
- outputs=[output_image, output_file, error_message]
215
- )
216
-
217
- # Launch the interface
218
  if __name__ == "__main__":
219
- logger.debug("Launching Gradio interface")
220
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
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)