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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
import io
|
| 4 |
+
import tempfile
|
| 5 |
+
from PIL import Image, ImageOps
|
| 6 |
+
import base64
|
| 7 |
+
import time
|
| 8 |
+
import json
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def generate_and_download_image():
|
| 12 |
+
image = Image.new("RGB", (256, 256), color=(255, 0, 0))
|
| 13 |
+
|
| 14 |
+
img_byte_arr = io.BytesIO()
|
| 15 |
+
image.save(img_byte_arr, format='PNG')
|
| 16 |
+
img_byte_arr.seek(0)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
return img_byte_arr, "generated_composite_image.png"
|
| 20 |
+
|
| 21 |
+
def load_image_from_url(url):
|
| 22 |
+
try:
|
| 23 |
+
response = requests.get(url)
|
| 24 |
+
response.raise_for_status()
|
| 25 |
+
image = Image.open(io.BytesIO(response.content))
|
| 26 |
+
return image,image,image
|
| 27 |
+
except Exception as e:
|
| 28 |
+
return None, f"Error: {e}"
|
| 29 |
+
|
| 30 |
+
def send_to_api(key, prompt, image_url, mask_url, path_points):
|
| 31 |
+
"""Send the image and mask to the API endpoint."""
|
| 32 |
+
|
| 33 |
+
path_points = path_points.replace("'", '"') # 替换单引号为双引号
|
| 34 |
+
path_points_list = json.loads(path_points)
|
| 35 |
+
|
| 36 |
+
url = "https://api.goapi.ai/api/v1/task"
|
| 37 |
+
payload = {
|
| 38 |
+
"model": "kling",
|
| 39 |
+
"task_type": "video_generation",
|
| 40 |
+
"input": {
|
| 41 |
+
"prompt": prompt,
|
| 42 |
+
"negative_prompt": "",
|
| 43 |
+
"cfg_scale": 0.5,
|
| 44 |
+
"duration": 5,
|
| 45 |
+
"image_url": image_url,
|
| 46 |
+
"image_tail_url": "",
|
| 47 |
+
"mode": "std",
|
| 48 |
+
"version": "1.0",
|
| 49 |
+
"motion_brush": {
|
| 50 |
+
"mask_url": mask_url,
|
| 51 |
+
"static_masks": [{"points": []}],
|
| 52 |
+
"dynamic_masks": [{"points": path_points_list}]
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
headers = {
|
| 58 |
+
"x-api-key": key
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 62 |
+
if response.status_code == 200:
|
| 63 |
+
data = response.json()
|
| 64 |
+
task_id = data.get("data", {}).get("task_id")
|
| 65 |
+
return task_id if task_id else None
|
| 66 |
+
else:
|
| 67 |
+
return f"Request failed, status code: {response.status_code}", None
|
| 68 |
+
|
| 69 |
+
def fetch_api(task_id, key):
|
| 70 |
+
"""Fetch task status and return video URL, retrying every 10 seconds until task is completed."""
|
| 71 |
+
url = f"https://api.goapi.ai/api/v1/task/{task_id}"
|
| 72 |
+
headers = {
|
| 73 |
+
"x-api-key": key
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
while True:
|
| 77 |
+
response = requests.get(url, headers=headers)
|
| 78 |
+
if response.status_code == 200:
|
| 79 |
+
data = response.json()
|
| 80 |
+
status = data.get("data", {}).get("status", "")
|
| 81 |
+
if status == "completed":
|
| 82 |
+
video_url = data.get("data", {}).get("output", {}).get("video_url", "Error video URL")
|
| 83 |
+
return video_url
|
| 84 |
+
if status == "failed":
|
| 85 |
+
video_url = data.get("data", {}).get("output", {}).get("video_url", "Error video URL")
|
| 86 |
+
return ""
|
| 87 |
+
|
| 88 |
+
else:
|
| 89 |
+
print(f"Task status is '{status}'. Retrying in 10 seconds...")
|
| 90 |
+
else:
|
| 91 |
+
return f"Request failed, status code: {response.status_code}", None
|
| 92 |
+
|
| 93 |
+
time.sleep(10)
|
| 94 |
+
|
| 95 |
+
def image_to_base64(image):
|
| 96 |
+
"""Convert a PIL Image to a base64-encoded PNG string."""
|
| 97 |
+
buffered = io.BytesIO()
|
| 98 |
+
image.save(buffered, format="PNG")
|
| 99 |
+
img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 100 |
+
return img_base64
|
| 101 |
+
|
| 102 |
+
def generate_mask_and_path(dynamic_mask_value, static_mask_value, path_points_value, path_direction):
|
| 103 |
+
|
| 104 |
+
dynamic_mask_layers = dynamic_mask_value.get("layers", [])
|
| 105 |
+
static_mask_layers = static_mask_value.get("layers", [])
|
| 106 |
+
path_points_layers = path_points_value.get("layers", [])
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
green_layer = dynamic_mask_layers[0]
|
| 110 |
+
green_rgb = (114, 229, 40)
|
| 111 |
+
|
| 112 |
+
green_mask = ImageOps.colorize(
|
| 113 |
+
ImageOps.grayscale(green_layer), black="black", white=green_rgb
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
black_layer = static_mask_layers[0]
|
| 117 |
+
black_mask = ImageOps.colorize(
|
| 118 |
+
ImageOps.grayscale(green_layer), black="black", white="green"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
width, height = green_mask.size
|
| 122 |
+
composite_image = Image.new("RGBA", (width, height), (255, 255, 255, 0))
|
| 123 |
+
composite_image.paste(green_mask, mask=green_layer)
|
| 124 |
+
composite_image.paste(black_mask, mask=black_layer)
|
| 125 |
+
|
| 126 |
+
path_layer = path_points_layers[0]
|
| 127 |
+
path_array = path_layer.load()
|
| 128 |
+
path_points = []
|
| 129 |
+
|
| 130 |
+
# Generate path points based on selected direction
|
| 131 |
+
if path_direction == "Left to Right":
|
| 132 |
+
for y in range(height):
|
| 133 |
+
for x in range(width):
|
| 134 |
+
if path_array[x, y] == (255, 255, 255, 255):
|
| 135 |
+
path_points.append({"x": x, "y": y})
|
| 136 |
+
path_points.sort(key=lambda point: (point['x'], point['y']))
|
| 137 |
+
elif path_direction == "Right to Left":
|
| 138 |
+
for y in range(height):
|
| 139 |
+
for x in range(width - 1, -1, -1):
|
| 140 |
+
if path_array[x, y] == (255, 255, 255, 255):
|
| 141 |
+
path_points.append({"x": x, "y": y})
|
| 142 |
+
path_points.sort(key=lambda point: (point['x'], point['y']), reverse=True)
|
| 143 |
+
elif path_direction == "Top to Bottom":
|
| 144 |
+
for x in range(width):
|
| 145 |
+
for y in range(height):
|
| 146 |
+
if path_array[x, y] == (255, 255, 255, 255):
|
| 147 |
+
path_points.append({"x": x, "y": y})
|
| 148 |
+
path_points.sort(key=lambda point: (point['y'], point['x']))
|
| 149 |
+
elif path_direction == "Bottom to Top":
|
| 150 |
+
for x in range(width):
|
| 151 |
+
for y in range(height - 1, -1, -1):
|
| 152 |
+
if path_array[x, y] == (255, 255, 255, 255):
|
| 153 |
+
path_points.append({"x": x, "y": y})
|
| 154 |
+
path_points.sort(key=lambda point: (point['y'], point['x']), reverse=True)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
selected_points = []
|
| 158 |
+
|
| 159 |
+
if path_points:
|
| 160 |
+
step = max(len(path_points) // 20, 1)
|
| 161 |
+
selected_points = []
|
| 162 |
+
|
| 163 |
+
selected_points.append(path_points[0])
|
| 164 |
+
|
| 165 |
+
for i in range(1, len(path_points) - 1, step):
|
| 166 |
+
avg_x = sum(point['x'] for point in path_points[i:i+step]) // len(path_points[i:i+step])
|
| 167 |
+
avg_y = sum(point['y'] for point in path_points[i:i+step]) // len(path_points[i:i+step])
|
| 168 |
+
selected_points.append({"x": avg_x, "y": avg_y})
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
print(path_points[-1])
|
| 172 |
+
selected_points.append(path_points[-1])
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
img_byte_arr = io.BytesIO()
|
| 176 |
+
composite_image.save(img_byte_arr, format="PNG")
|
| 177 |
+
img_byte_arr.seek(0)
|
| 178 |
+
|
| 179 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 180 |
+
with open(temp_file.name, "wb") as f:
|
| 181 |
+
f.write(img_byte_arr.read())
|
| 182 |
+
|
| 183 |
+
return temp_file.name, selected_points
|
| 184 |
+
|
| 185 |
+
def generate_video(key, prompt,mask_url, original_image_url,path_points):
|
| 186 |
+
task_id = send_to_api(key, prompt, original_image_url, mask_url, path_points)
|
| 187 |
+
video_url = fetch_api(task_id, key)
|
| 188 |
+
|
| 189 |
+
return task_id, video_url
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
with gr.Blocks() as interface:
|
| 193 |
+
gr.Markdown("# Video Motion Generation Tool")
|
| 194 |
+
|
| 195 |
+
gr.Markdown("---")
|
| 196 |
+
gr.Markdown("### 1. Input Background Image URL")
|
| 197 |
+
with gr.Row():
|
| 198 |
+
url_input = gr.Textbox(label="Input Background Image URL", placeholder="Enter the image URL",value="https://i.ibb.co/VBdYTJC/301649-20200826221337967.jpg" )
|
| 199 |
+
load_image_btn = gr.Button("Load Image")
|
| 200 |
+
|
| 201 |
+
gr.Markdown("---")
|
| 202 |
+
gr.Markdown("### 2. Brush Tool for Editing Image")
|
| 203 |
+
|
| 204 |
+
gr.Markdown("#### 2.1 Dynamic Mask (Required): This mask will generate movement effects.")
|
| 205 |
+
gr.Markdown("In this step, draw on **Layer 1** of imagEedit to create the dynamic mask.")
|
| 206 |
+
|
| 207 |
+
with gr.Row():
|
| 208 |
+
dynamic_mask_editor = gr.ImageEditor(
|
| 209 |
+
type="pil",
|
| 210 |
+
brush=gr.Brush(default_size=20, colors=["#FFFFFF"], color_mode="fixed"),
|
| 211 |
+
layers=True,
|
| 212 |
+
interactive=True,
|
| 213 |
+
label="Drawing Tool to Create Dynamic Mask (Layer 1)",
|
| 214 |
+
height=700,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
gr.Markdown("#### 2.2 Static Mask (Optional): This mask will remain still during the video.")
|
| 219 |
+
gr.Markdown("You can optionally draw on **Layer 1** of imagEedit to create the static mask.")
|
| 220 |
+
|
| 221 |
+
with gr.Row():
|
| 222 |
+
static_mask_editor = gr.ImageEditor(
|
| 223 |
+
type="pil",
|
| 224 |
+
brush=gr.Brush(default_size=20, colors=["#FFFFFF"], color_mode="fixed"),
|
| 225 |
+
layers=True,
|
| 226 |
+
interactive=True,
|
| 227 |
+
label="Drawing Tool to Create Static Mask (Layer 1)",
|
| 228 |
+
height=700,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
gr.Markdown("#### 2.3 Path Points (Required): These points define the direction and flow of the animation.")
|
| 233 |
+
gr.Markdown("Draw on **Layer 1** of imagEedit to create the path points.")
|
| 234 |
+
|
| 235 |
+
with gr.Row():
|
| 236 |
+
path_points_editor = gr.ImageEditor(
|
| 237 |
+
type="pil",
|
| 238 |
+
brush=gr.Brush(default_size=1, colors=["#FFFFFF"], color_mode="fixed"),
|
| 239 |
+
layers=True,
|
| 240 |
+
interactive=True,
|
| 241 |
+
label="Drawing Tool to Create Path Points (Layer 1)",
|
| 242 |
+
height=700,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
with gr.Row():
|
| 246 |
+
direction_input = gr.Dropdown(
|
| 247 |
+
choices=["Left to Right", "Right to Left", "Top to Bottom", "Bottom to Top"],
|
| 248 |
+
label="Select Path Direction"
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
submit_btn = gr.Button("Generate masks and paths")
|
| 252 |
+
|
| 253 |
+
gr.Markdown("Upload the downloaded mask image to a public image hosting service (e.g., [ImageBB](https://imgbb.com/)) and paste the provided link into the `mask_url` field.")
|
| 254 |
+
with gr.Row():
|
| 255 |
+
output_composite_file = gr.File(label="Generated Composite Image")
|
| 256 |
+
output_path_points = gr.Textbox(label="Path Point Data")
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
gr.Markdown("---")
|
| 260 |
+
gr.Markdown("### 3. Configure the Video Settings")
|
| 261 |
+
gr.Markdown("Please provide the necessary details to generate the video. If you don't have an API key, you can [generate one here](https://piapi.ai/workspace/kling).")
|
| 262 |
+
|
| 263 |
+
with gr.Row():
|
| 264 |
+
prompt_input = gr.Textbox(label="Prompt", placeholder="Enter Prompt",value="walk")
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
with gr.Row():
|
| 268 |
+
key_input = gr.Textbox(label="API Key", placeholder="Enter PiAPI Key")
|
| 269 |
+
|
| 270 |
+
with gr.Row():
|
| 271 |
+
mask_input = gr.Textbox(label="Mask Url")
|
| 272 |
+
|
| 273 |
+
with gr.Row():
|
| 274 |
+
generate_btn = gr.Button("Generate Video")
|
| 275 |
+
|
| 276 |
+
gr.Markdown("---")
|
| 277 |
+
gr.Markdown("### 4. Results")
|
| 278 |
+
gr.Markdown("The video generation may take up to **3 minutes**. Please be patient while the system processes the request.")
|
| 279 |
+
with gr.Row():
|
| 280 |
+
output_task_id = gr.Textbox(label="Task ID")
|
| 281 |
+
output_video = gr.Video(label="Generated Video Link")
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
load_image_btn.click(
|
| 285 |
+
fn=load_image_from_url,
|
| 286 |
+
inputs=[url_input],
|
| 287 |
+
outputs=[dynamic_mask_editor,static_mask_editor,path_points_editor],
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
submit_btn.click(
|
| 292 |
+
fn=generate_mask_and_path,
|
| 293 |
+
inputs=[dynamic_mask_editor, static_mask_editor, path_points_editor, direction_input],
|
| 294 |
+
outputs=[output_composite_file, output_path_points],
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
generate_btn.click(
|
| 299 |
+
fn=generate_video,
|
| 300 |
+
inputs=[key_input, prompt_input,mask_input, url_input,output_path_points],
|
| 301 |
+
outputs=[output_task_id, output_video],
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
interface.launch()
|
| 306 |
+
|