AkashKumarave commited on
Commit
7421e11
·
verified ·
1 Parent(s): 4f1150a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -22
app.py CHANGED
@@ -8,7 +8,7 @@ import time
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/predictions"
12
 
13
  def generate_jwt_token():
14
  """Generate JWT token for Kling AI API authentication."""
@@ -39,7 +39,7 @@ def generate_image(image, prompt=""):
39
  with open(image, "rb") as img_file:
40
  image_base64 = base64.b64encode(img_file.read()).decode("utf-8")
41
  except Exception as e:
42
- return f"Error: Failed to process image. Details: {str(e)}"
43
 
44
  headers = {
45
  "Authorization": f"Bearer {generate_jwt_token()}",
@@ -47,13 +47,10 @@ def generate_image(image, prompt=""):
47
  }
48
 
49
  payload = {
50
- "inputs": [{"name": "input_image", "inputType": "URL", "url": image_base64}],
51
- "arguments": [
52
- {"name": "prompt", "value": prompt or "Transform the image"},
53
- {"name": "strength", "value": "0.7"},
54
- {"name": "output_format", "value": "png"},
55
- {"name": "task_type", "value": "image-to-image"}
56
- ]
57
  }
58
 
59
  try:
@@ -61,9 +58,9 @@ def generate_image(image, prompt=""):
61
  response.raise_for_status()
62
 
63
  data = response.json()
64
- task_id = data.get("task_id") or data.get("taskId")
65
  if not task_id:
66
- return "Error: No task ID returned by the API. Check endpoint or keys."
67
 
68
  # Poll for task completion
69
  status_url = f"https://api-singapore.klingai.com/v1/predictions/{task_id}"
@@ -71,10 +68,11 @@ def generate_image(image, prompt=""):
71
  status_response = requests.get(status_url, headers=headers, timeout=30)
72
  status_response.raise_for_status()
73
  status_data = status_response.json()
74
- if status_data.get("status") == "succeeded":
75
- image_url = status_data.get("image_url") or status_data.get("result", {}).get("image_url")
 
76
  if not image_url:
77
- return "Error: No image URL in API response."
78
  # Download the image
79
  image_response = requests.get(image_url, timeout=30)
80
  image_response.raise_for_status()
@@ -82,23 +80,27 @@ def generate_image(image, prompt=""):
82
  with open(output_path, "wb") as f:
83
  f.write(image_response.content)
84
  return str(output_path)
85
- elif status_data.get("status") == "failed":
86
- return "Error: Image generation failed. Check image content (no NSFW, celebrities, or sensitive topics)."
 
 
87
  time.sleep(5)
88
 
89
- return "Error: Image generation timed out. Try a paid account if using free credits."
90
 
91
  except requests.exceptions.HTTPError as e:
92
  status_code = e.response.status_code
93
  if status_code == 401:
94
- return "Error: Authentication failed. Verify API keys."
95
  elif status_code == 404:
96
- return "Error: API endpoint not found. Check https://klingai.com/global/dev for correct endpoint."
97
  elif status_code == 422:
98
- return "Error: Invalid input. Use PNG/JPEG (<10 MB, ≥512x512 pixels) and a simple prompt."
 
 
99
  return f"Error: API request failed. Details: {str(e)}"
100
  except requests.exceptions.RequestException as e:
101
- return f"Error: Network issue. Ensure internet access and try again. Details: {str(e)}"
102
 
103
  def chatbot_interface(image, prompt):
104
  """
@@ -122,7 +124,7 @@ iface = gr.Interface(
122
  ],
123
  outputs=gr.Image(label="Generated Image"),
124
  title="Kling AI Image-to-Image Generator",
125
- description="Upload a PNG/JPEG image to generate a transformed image using Kling AI API. Ensure image is <10 MB, ≥512x512 pixels, and avoid NSFW or sensitive content."
126
  )
127
 
128
  # Launch the interface
 
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/generate/image"
12
 
13
  def generate_jwt_token():
14
  """Generate JWT token for Kling AI API authentication."""
 
39
  with open(image, "rb") as img_file:
40
  image_base64 = base64.b64encode(img_file.read()).decode("utf-8")
41
  except Exception as e:
42
+ return f"Error: Failed to process image. Ensure it’s a valid PNG/JPEG. Details: {str(e)}"
43
 
44
  headers = {
45
  "Authorization": f"Bearer {generate_jwt_token()}",
 
47
  }
48
 
49
  payload = {
50
+ "image": image_base64,
51
+ "prompt": prompt or "Transform the image into a cartoon style",
52
+ "strength": 0.7, # Controls transformation intensity (0.0 to 1.0)
53
+ "output_format": "png"
 
 
 
54
  }
55
 
56
  try:
 
58
  response.raise_for_status()
59
 
60
  data = response.json()
61
+ task_id = data.get("task_id") or data.get("taskId") or data.get("id")
62
  if not task_id:
63
+ return "Error: No task ID returned. Check API endpoint or keys at https://klingai.com/global/dev."
64
 
65
  # Poll for task completion
66
  status_url = f"https://api-singapore.klingai.com/v1/predictions/{task_id}"
 
68
  status_response = requests.get(status_url, headers=headers, timeout=30)
69
  status_response.raise_for_status()
70
  status_data = status_response.json()
71
+ status = status_data.get("status")
72
+ if status == "succeeded":
73
+ image_url = status_data.get("image_url") or status_data.get("result", {}).get("image_url") or status_data.get("output")
74
  if not image_url:
75
+ return "Error: No image URL in API response. Check API documentation."
76
  # Download the image
77
  image_response = requests.get(image_url, timeout=30)
78
  image_response.raise_for_status()
 
80
  with open(output_path, "wb") as f:
81
  f.write(image_response.content)
82
  return str(output_path)
83
+ elif status == "failed":
84
+ return "Error: Image generation failed. Avoid NSFW, celebrities, or sensitive content (e.g., politics, violence)."
85
+ elif status == "processing" and status_data.get("progress", 0) >= 0.99:
86
+ return "Error: Generation stuck at 99%. Check account credits or upgrade to a paid plan at https://klingai.com."
87
  time.sleep(5)
88
 
89
+ return "Error: Image generation timed out. Try during off-peak hours or check account status."
90
 
91
  except requests.exceptions.HTTPError as e:
92
  status_code = e.response.status_code
93
  if status_code == 401:
94
+ return "Error: Authentication failed. Verify API keys are correct."
95
  elif status_code == 404:
96
+ return "Error: API endpoint not found. Check https://klingai.com/global/dev for correct endpoint (e.g., /v1/predictions)."
97
  elif status_code == 422:
98
+ return "Error: Invalid input. Use PNG/JPEG (<10 MB, ≥512x512 pixels) and a simple prompt (e.g., 'Turn this into a sketch')."
99
+ elif status_code == 500:
100
+ return "Error: Server issue. Try again later or during off-peak hours."
101
  return f"Error: API request failed. Details: {str(e)}"
102
  except requests.exceptions.RequestException as e:
103
+ return f"Error: Network issue. Ensure stable internet, disable VPN, and try again. Details: {str(e)}"
104
 
105
  def chatbot_interface(image, prompt):
106
  """
 
124
  ],
125
  outputs=gr.Image(label="Generated Image"),
126
  title="Kling AI Image-to-Image Generator",
127
+ description="Upload a PNG/JPEG image (<10 MB, ≥512x512 pixels) to generate a transformed image using Kling AI API. Avoid NSFW, celebrities, or sensitive content."
128
  )
129
 
130
  # Launch the interface