Spaces:
Sleeping
Sleeping
Create gradio_mcp_server.py
Browse files- gradio_mcp_server.py +58 -0
gradio_mcp_server.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from mcp.server.fastmcp import FastMCP
|
2 |
+
import json
|
3 |
+
import sys
|
4 |
+
import io
|
5 |
+
import time
|
6 |
+
from gradio_client import Client
|
7 |
+
|
8 |
+
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
9 |
+
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
|
10 |
+
|
11 |
+
mcp = FastMCP("huggingface_spaces_image_display")
|
12 |
+
|
13 |
+
@mcp.tool()
|
14 |
+
async def generate_image(prompt: str, width: int = 512, height: int = 512) -> str:
|
15 |
+
"""Generate an image using SanaSprint model.
|
16 |
+
|
17 |
+
Args:
|
18 |
+
prompt: Text prompt describing the image to generate
|
19 |
+
width: Image width (default: 512)
|
20 |
+
height: Image height (default: 512)
|
21 |
+
"""
|
22 |
+
client = Client("https://ysharma-sanasprint.hf.space/")
|
23 |
+
|
24 |
+
try:
|
25 |
+
result = client.predict(
|
26 |
+
prompt,
|
27 |
+
"0.6B",
|
28 |
+
0,
|
29 |
+
True,
|
30 |
+
width,
|
31 |
+
height,
|
32 |
+
4.0,
|
33 |
+
2,
|
34 |
+
api_name="/infer"
|
35 |
+
)
|
36 |
+
|
37 |
+
if isinstance(result, list) and len(result) >= 1:
|
38 |
+
image_data = result[0]
|
39 |
+
if isinstance(image_data, dict) and "url" in image_data:
|
40 |
+
return json.dumps({
|
41 |
+
"type": "image",
|
42 |
+
"url": image_data["url"],
|
43 |
+
"message": f"Generated image for prompt: {prompt}"
|
44 |
+
})
|
45 |
+
|
46 |
+
return json.dumps({
|
47 |
+
"type": "error",
|
48 |
+
"message": "Failed to generate image"
|
49 |
+
})
|
50 |
+
|
51 |
+
except Exception as e:
|
52 |
+
return json.dumps({
|
53 |
+
"type": "error",
|
54 |
+
"message": f"Error generating image: {str(e)}"
|
55 |
+
})
|
56 |
+
|
57 |
+
if __name__ == "__main__":
|
58 |
+
mcp.run(transport='stdio')
|