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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -13
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/image-to-image"
12
 
13
  def generate_jwt_token():
14
  """Generate JWT token for Kling AI API authentication."""
@@ -32,7 +32,7 @@ def generate_image(image, prompt=""):
32
  str: Path to the generated image or error message
33
  """
34
  if not image:
35
- return "Error: Please upload a valid image (PNG/JPEG)."
36
 
37
  # Convert image to base64
38
  try:
@@ -47,10 +47,13 @@ def generate_image(image, prompt=""):
47
  }
48
 
49
  payload = {
50
- "image": image_base64,
51
- "prompt": prompt,
52
- "strength": 0.7, # Controls transformation intensity (0.0 to 1.0)
53
- "output_format": "png"
 
 
 
54
  }
55
 
56
  try:
@@ -60,7 +63,7 @@ def generate_image(image, prompt=""):
60
  data = response.json()
61
  task_id = data.get("task_id") or data.get("taskId")
62
  if not task_id:
63
- return "Error: No task ID returned by the API."
64
 
65
  # Poll for task completion
66
  status_url = f"https://api-singapore.klingai.com/v1/predictions/{task_id}"
@@ -80,15 +83,22 @@ def generate_image(image, prompt=""):
80
  f.write(image_response.content)
81
  return str(output_path)
82
  elif status_data.get("status") == "failed":
83
- return "Error: Image generation failed."
84
  time.sleep(5)
85
 
86
- return "Error: Image generation timed out."
87
 
88
  except requests.exceptions.HTTPError as e:
 
 
 
 
 
 
 
89
  return f"Error: API request failed. Details: {str(e)}"
90
  except requests.exceptions.RequestException as e:
91
- return f"Error: Network issue. Details: {str(e)}"
92
 
93
  def chatbot_interface(image, prompt):
94
  """
@@ -107,12 +117,12 @@ def chatbot_interface(image, prompt):
107
  iface = gr.Interface(
108
  fn=chatbot_interface,
109
  inputs=[
110
- gr.Image(type="filepath", label="Upload Image (PNG/JPEG)"),
111
- gr.Textbox(lines=2, placeholder="Enter an optional prompt (e.g., 'Turn this into a painting')", label="Prompt")
112
  ],
113
  outputs=gr.Image(label="Generated Image"),
114
  title="Kling AI Image-to-Image Generator",
115
- description="Upload a PNG/JPEG image to generate a transformed image using Kling AI API."
116
  )
117
 
118
  # 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/predictions"
12
 
13
  def generate_jwt_token():
14
  """Generate JWT token for Kling AI API authentication."""
 
32
  str: Path to the generated image or error message
33
  """
34
  if not image:
35
+ return "Error: Please upload a valid image (PNG/JPEG, <10 MB, ≥512x512 pixels)."
36
 
37
  # Convert image to base64
38
  try:
 
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:
 
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}"
 
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
  """
 
117
  iface = gr.Interface(
118
  fn=chatbot_interface,
119
  inputs=[
120
+ gr.Image(type="filepath", label="Upload Image (PNG/JPEG, <10 MB, ≥512x512)"),
121
+ gr.Textbox(lines=2, placeholder="Enter an optional prompt (e.g., 'Turn this into a cartoon')", label="Prompt")
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