AkashKumarave commited on
Commit
0f6d3a6
·
verified ·
1 Parent(s): 6bc6632

Update app.py

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