AkashKumarave commited on
Commit
97f568a
·
verified ·
1 Parent(s): 1c84264

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -101
app.py CHANGED
@@ -1,121 +1,44 @@
1
- import gradio as gr
 
2
  import requests
3
  import base64
4
- from pathlib import Path
5
- import jwt
6
- import time
7
- import logging
8
-
9
- # ================== CONFIG ==================
10
- ACCESS_KEY_ID = "YOUR_ACCESS_KEY_ID"
11
- ACCESS_KEY_SECRET = "YOUR_ACCESS_KEY_SECRET"
12
- API_URL = "https://api-singapore.klingai.com/v1/images/generations"
13
-
14
- logging.basicConfig(level=logging.DEBUG)
15
- logger = logging.getLogger(__name__)
16
 
 
 
 
17
 
18
- # ================== AUTH ==================
19
  def generate_jwt_token():
20
- headers = {"alg": "HS256", "typ": "JWT"}
21
  payload = {
22
  "iss": ACCESS_KEY_ID,
23
  "exp": int(time.time()) + 1800,
24
  "nbf": int(time.time()) - 5
25
  }
26
- return jwt.encode(payload, ACCESS_KEY_SECRET, headers=headers)
27
-
28
-
29
- # ================== IMAGE GENERATION ==================
30
- def generate_image(image, prompt=""):
31
- if not image:
32
- return None, "Error: Please upload a valid face image."
33
-
34
- try:
35
- with open(image, "rb") as img_file:
36
- image_base64 = base64.b64encode(img_file.read()).decode("utf-8")
37
- except Exception as e:
38
- return None, f"Error reading image: {e}"
39
-
40
  headers = {
41
  "Authorization": f"Bearer {generate_jwt_token()}",
42
  "Content-Type": "application/json"
43
  }
44
 
45
- payload = {
46
- "model_name": "kling-v2-1", # ✅ per docs
47
- "prompt": prompt or "Transform face into artistic style",
48
- "image": image_base64, # base64 only, no prefix
49
  "aspect_ratio": "1:1",
50
- "n": 1, # number of images
51
- "resolution": "1k"
52
  }
53
 
54
- try:
55
- logger.debug(f"POST {API_URL} payload={payload.keys()}")
56
- response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
57
- response.raise_for_status()
58
- data = response.json()
59
-
60
- if data.get("code") != 0:
61
- return None, f"API Error: {data.get('message')}"
62
-
63
- task_id = data["data"]["task_id"]
64
- logger.debug(f"Task ID: {task_id}")
65
-
66
- # Poll task status
67
- status_url = f"{API_URL}/{task_id}"
68
- for _ in range(60): # up to ~5 minutes
69
- time.sleep(5)
70
- status_resp = requests.get(status_url, headers=headers, timeout=30)
71
- status_data = status_resp.json()
72
-
73
- if status_data.get("data", {}).get("task_status") == "succeed":
74
- images = status_data["data"]["task_result"]["images"]
75
- if images:
76
- img_url = images[0]["url"]
77
- img_resp = requests.get(img_url)
78
- img_resp.raise_for_status()
79
- out_path = Path("/tmp/output.png")
80
- with open(out_path, "wb") as f:
81
- f.write(img_resp.content)
82
- return str(out_path), None
83
- else:
84
- return None, "No image returned."
85
-
86
- elif status_data.get("data", {}).get("task_status") == "failed":
87
- return None, f"Generation failed: {status_data['data'].get('task_status_msg')}"
88
-
89
- return None, "Timed out waiting for result."
90
-
91
- except requests.exceptions.HTTPError as e:
92
- return None, f"HTTP Error: {e}"
93
- except Exception as e:
94
- return None, f"Unexpected Error: {e}"
95
-
96
-
97
- # ================== GRADIO UI ==================
98
- def chatbot_interface(image, prompt):
99
- image_path, error = generate_image(image, prompt)
100
- if error:
101
- return None, None, error
102
- return image_path, image_path, None
103
-
104
-
105
- with gr.Blocks() as iface:
106
- gr.Markdown("# Kling AI Image Generator — Official API Format")
107
-
108
- with gr.Row():
109
- with gr.Column():
110
- img_in = gr.Image(type="filepath", label="Upload Image")
111
- prompt_in = gr.Textbox(lines=2, placeholder="Enter prompt", label="Prompt")
112
- btn = gr.Button("Generate")
113
- with gr.Column():
114
- img_out = gr.Image(label="Generated Image")
115
- file_out = gr.File(label="Download Image")
116
- err_out = gr.Textbox(label="Error / Status", interactive=False)
117
-
118
- btn.click(fn=chatbot_interface, inputs=[img_in, prompt_in], outputs=[img_out, file_out, err_out])
119
 
120
  if __name__ == "__main__":
121
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
1
+ import time
2
+ import jwt
3
  import requests
4
  import base64
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ # ---- Your Keys ----
7
+ ACCESS_KEY_ID = "AFyHfnQATghFdCMyAG3gRPbNY4TNKFGB"
8
+ ACCESS_KEY_SECRET = "TTepeLyBterLNM3brYPGmdndBnnyKJBA"
9
 
10
+ # ---- Generate JWT ----
11
  def generate_jwt_token():
 
12
  payload = {
13
  "iss": ACCESS_KEY_ID,
14
  "exp": int(time.time()) + 1800,
15
  "nbf": int(time.time()) - 5
16
  }
17
+ token = jwt.encode(payload, ACCESS_KEY_SECRET, algorithm="HS256")
18
+ if isinstance(token, bytes):
19
+ token = token.decode("utf-8")
20
+ return token
21
+
22
+ # ---- Test API Call ----
23
+ def test_kling_image():
24
+ url = "https://api-singapore.klingai.com/v1/images/generations"
 
 
 
 
 
 
25
  headers = {
26
  "Authorization": f"Bearer {generate_jwt_token()}",
27
  "Content-Type": "application/json"
28
  }
29
 
30
+ # A very simple request (no image-to-image, just text-to-image)
31
+ data = {
32
+ "model": "kolors-v2.1",
33
+ "prompt": "a futuristic city skyline at night",
34
  "aspect_ratio": "1:1",
35
+ "output_format": "png",
36
+ "num_outputs": 1
37
  }
38
 
39
+ resp = requests.post(url, headers=headers, json=data)
40
+ print("Status:", resp.status_code)
41
+ print("Response:", resp.text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  if __name__ == "__main__":
44
+ test_kling_image()