AkashKumarave commited on
Commit
3a247bc
·
verified ·
1 Parent(s): c8e0e2c

Update app.py

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