Spaces:
Running
Running
File size: 13,684 Bytes
aaa3e82 2ca01e7 aaa3e82 2ca01e7 aaa3e82 2ca01e7 aaa3e82 2ca01e7 aaa3e82 2ca01e7 aaa3e82 2ca01e7 aaa3e82 985dde8 aaa3e82 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
"""
A1D MCP Server - Gradio Application
Universal AI Tools for image and video processing
"""
import gradio as gr
import os
from typing import Optional, Tuple, Union
from utils import A1DAPIClient, validate_url, validate_scale, prepare_request_data, format_response_with_preview
from config import GRADIO_CONFIG, TOOLS_CONFIG
from mcp_handler import get_api_key_from_headers
# Initialize API client
def get_api_client():
"""Get API client with current API key"""
# Try to get API key from multiple sources
api_key = None
# 1. Try from request headers (for MCP clients)
try:
request = gr.request()
if request and hasattr(request, 'headers'):
api_key = get_api_key_from_headers(dict(request.headers))
except:
pass
# 2. Fallback to environment variable
if not api_key:
api_key = os.getenv("A1D_API_KEY")
if not api_key:
raise ValueError(
"API key is required. Set A1D_API_KEY environment variable or provide API_KEY in request headers.")
return A1DAPIClient(api_key)
def remove_bg(image_url: str) -> Tuple[str, Optional[str]]:
"""Remove background from images using AI.
Args:
image_url: The URL of the image to remove background from
Returns:
Tuple of (result_message, media_url_for_preview)
"""
try:
if not validate_url(image_url):
return "β Error: Invalid image URL format", None
client = get_api_client()
data = prepare_request_data("remove_bg", image_url=image_url)
# Use the new method that waits for result
response = client.make_request_with_result(
TOOLS_CONFIG["remove_bg"]["api_endpoint"],
data,
timeout=120 # 2 minutes timeout
)
return format_response_with_preview(response, "remove_bg")
except Exception as e:
return f"β Error: {str(e)}", None
def image_upscaler(image_url: str, scale: int = 2) -> Tuple[str, Optional[str]]:
"""Upscale images using AI with specified scale factor.
Args:
image_url: The URL of the image to upscale
scale: Scale factor for upscaling (2, 4, 8, or 16). Default: 2
Returns:
Tuple of (result_message, media_url_for_preview)
"""
try:
if not validate_url(image_url):
return "β Error: Invalid image URL format", None
if not validate_scale(scale):
return "β Error: Scale must be 2, 4, 8, or 16", None
client = get_api_client()
data = prepare_request_data(
"image_upscaler", image_url=image_url, scale=scale)
response = client.make_request_with_result(
TOOLS_CONFIG["image_upscaler"]["api_endpoint"],
data,
timeout=120
)
return format_response_with_preview(response, "image_upscaler")
except Exception as e:
return f"β Error: {str(e)}", None
def video_upscaler(video_url: str) -> Tuple[str, Optional[str]]:
"""Upscale videos using AI.
Args:
video_url: The URL of the video to upscale
Returns:
Tuple of (result_message, media_url_for_preview)
"""
try:
if not validate_url(video_url):
return "β Error: Invalid video URL format", None
client = get_api_client()
data = prepare_request_data("video_upscaler", video_url=video_url)
response = client.make_request_with_result(
TOOLS_CONFIG["video_upscaler"]["api_endpoint"],
data,
timeout=300 # 5 minutes for video processing
)
return format_response_with_preview(response, "video_upscaler")
except Exception as e:
return f"β Error: {str(e)}", None
def image_vectorization(image_url: str) -> Tuple[str, Optional[str]]:
"""Convert images to vector format using AI.
Args:
image_url: The URL of the image to vectorize
Returns:
Tuple of (result_message, media_url_for_preview)
"""
try:
if not validate_url(image_url):
return "β Error: Invalid image URL format", None
client = get_api_client()
data = prepare_request_data("image_vectorization", image_url=image_url)
response = client.make_request_with_result(
TOOLS_CONFIG["image_vectorization"]["api_endpoint"],
data,
timeout=120
)
return format_response_with_preview(response, "image_vectorization")
except Exception as e:
return f"β Error: {str(e)}", None
def image_extends(image_url: str) -> Tuple[str, Optional[str]]:
"""Extend images using AI.
Args:
image_url: The URL of the image to extend
Returns:
Tuple of (result_message, media_url_for_preview)
"""
try:
if not validate_url(image_url):
return "β Error: Invalid image URL format", None
client = get_api_client()
data = prepare_request_data("image_extends", image_url=image_url)
response = client.make_request_with_result(
TOOLS_CONFIG["image_extends"]["api_endpoint"],
data,
timeout=120
)
return format_response_with_preview(response, "image_extends")
except Exception as e:
return f"β Error: {str(e)}", None
def image_generator(prompt: str) -> Tuple[str, Optional[str]]:
"""Generate images using AI from text prompts.
Args:
prompt: Text prompt to generate image from
Returns:
Tuple of (result_message, media_url_for_preview)
"""
try:
if not prompt or not prompt.strip():
return "β Error: Prompt is required and cannot be empty", None
client = get_api_client()
data = prepare_request_data("image_generator", prompt=prompt.strip())
response = client.make_request_with_result(
TOOLS_CONFIG["image_generator"]["api_endpoint"],
data,
timeout=120
)
return format_response_with_preview(response, "image_generator")
except Exception as e:
return f"β Error: {str(e)}", None
# Wrapper functions for Gradio interface
def remove_bg_wrapper(image_url: str):
"""Wrapper for remove_bg that returns message and media for Gradio
Args:
image_url: The URL of the image to remove background from. Must be a valid HTTP/HTTPS URL pointing to an image file.
Returns:
Tuple of (result_message, media_url_for_preview)
"""
message, media_url = remove_bg(image_url)
return message, media_url if media_url else None
def image_upscaler_wrapper(image_url: str, scale: int):
"""Wrapper for image_upscaler that returns message and media for Gradio
Args:
image_url: The URL of the image to upscale. Must be a valid HTTP/HTTPS URL pointing to an image file.
scale: Scale factor for upscaling. Choose from 2, 4, 8, or 16. Higher values produce larger images but take longer to process.
Returns:
Tuple of (result_message, media_url_for_preview)
"""
message, media_url = image_upscaler(image_url, scale)
return message, media_url if media_url else None
def video_upscaler_wrapper(video_url: str):
"""Wrapper for video_upscaler that returns message and media for Gradio
Args:
video_url: The URL of the video to upscale. Must be a valid HTTP/HTTPS URL pointing to a video file (MP4, AVI, MOV, etc.).
Returns:
Tuple of (result_message, media_url_for_preview)
"""
message, media_url = video_upscaler(video_url)
return message, media_url if media_url else None
def image_vectorization_wrapper(image_url: str):
"""Wrapper for image_vectorization that returns message and media for Gradio
Args:
image_url: The URL of the image to convert to vector format. Must be a valid HTTP/HTTPS URL pointing to an image file.
Returns:
Tuple of (result_message, media_url_for_preview)
"""
message, media_url = image_vectorization(image_url)
return message, media_url if media_url else None
def image_extends_wrapper(image_url: str):
"""Wrapper for image_extends that returns message and media for Gradio
Args:
image_url: The URL of the image to extend. Must be a valid HTTP/HTTPS URL pointing to an image file.
Returns:
Tuple of (result_message, media_url_for_preview)
"""
message, media_url = image_extends(image_url)
return message, media_url if media_url else None
def image_generator_wrapper(prompt: str):
"""Wrapper for image_generator that returns message and media for Gradio
Args:
prompt: Text description of the image to generate. Be descriptive and specific for better results. Example: "A beautiful sunset over mountains with vibrant orange and purple colors".
Returns:
Tuple of (result_message, media_url_for_preview)
"""
message, media_url = image_generator(prompt)
return message, media_url if media_url else None
# Create Gradio interfaces for each tool
def create_gradio_app():
"""Create the main Gradio application with all tools"""
# Create individual interfaces for each tool
remove_bg_interface = gr.Interface(
fn=remove_bg_wrapper,
inputs=[
gr.Textbox(
label="Image URL",
placeholder="https://example.com/image.jpg",
info="Enter the URL of the image to remove background from"
)
],
outputs=[
gr.Textbox(label="Result"),
gr.Image(label="Preview")
],
title="π Background Removal",
description="Remove background from images using AI"
)
image_upscaler_interface = gr.Interface(
fn=image_upscaler_wrapper,
inputs=[
gr.Textbox(
label="Image URL",
placeholder="https://example.com/image.jpg",
info="Enter the URL of the image to upscale"
),
gr.Dropdown(
choices=[2, 4, 8, 16],
value=2,
label="Scale Factor",
info="Choose the upscaling factor"
)
],
outputs=[
gr.Textbox(label="Result"),
gr.Image(label="Preview")
],
title="π Image Upscaler",
description="Upscale images using AI with specified scale factor"
)
video_upscaler_interface = gr.Interface(
fn=video_upscaler_wrapper,
inputs=[
gr.Textbox(
label="Video URL",
placeholder="https://example.com/video.mp4",
info="Enter the URL of the video to upscale"
)
],
outputs=[
gr.Textbox(label="Result"),
gr.Video(label="Preview")
],
title="π¬ Video Upscaler",
description="Upscale videos using AI"
)
image_vectorization_interface = gr.Interface(
fn=image_vectorization_wrapper,
inputs=[
gr.Textbox(
label="Image URL",
placeholder="https://example.com/image.jpg",
info="Enter the URL of the image to convert to vector format"
)
],
outputs=[
gr.Textbox(label="Result"),
gr.Image(label="Preview")
],
title="π Image Vectorization",
description="Convert images to vector format using AI"
)
image_extends_interface = gr.Interface(
fn=image_extends_wrapper,
inputs=[
gr.Textbox(
label="Image URL",
placeholder="https://example.com/image.jpg",
info="Enter the URL of the image to extend"
)
],
outputs=[
gr.Textbox(label="Result"),
gr.Image(label="Preview")
],
title="πΌοΈ Image Extension",
description="Extend images using AI"
)
image_generator_interface = gr.Interface(
fn=image_generator_wrapper,
inputs=[
gr.Textbox(
label="Text Prompt",
placeholder="A beautiful sunset over mountains",
info="Enter a text description to generate an image",
lines=3
)
],
outputs=[
gr.Textbox(label="Result"),
gr.Image(label="Preview")
],
title="π¨ Image Generator",
description="Generate images using AI from text prompts"
)
# Create tabbed interface
demo = gr.TabbedInterface(
[
remove_bg_interface,
image_upscaler_interface,
video_upscaler_interface,
image_vectorization_interface,
image_extends_interface,
image_generator_interface
],
[
"Background Removal",
"Image Upscaler",
"Video Upscaler",
"Image Vectorization",
"Image Extension",
"Image Generator"
],
title=GRADIO_CONFIG["title"],
theme=GRADIO_CONFIG["theme"]
)
return demo
if __name__ == "__main__":
# Check for API key
if not os.getenv("A1D_API_KEY"):
print("β Error: A1D_API_KEY environment variable is required")
print("Please set your API key: export A1D_API_KEY=your_api_key_here")
exit(1)
# Create and launch the app
demo = create_gradio_app()
# Launch the Gradio app
demo.launch(
server_name=GRADIO_CONFIG["server_name"],
server_port=GRADIO_CONFIG["server_port"],
share=GRADIO_CONFIG["share"]
)
|