Spaces:
Sleeping
Sleeping
File size: 8,169 Bytes
d884bf1 |
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 |
#!/usr/bin/env python3
"""
Deployment script for Hugging Face Spaces
This script helps deploy the MCP server to Hugging Face Spaces.
"""
import os
import shutil
import subprocess
import sys
import argparse
from pathlib import Path
def check_git():
"""Check if git is available."""
try:
subprocess.run(["git", "--version"], capture_output=True, check=True)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
print("β Git is not installed or not available in PATH")
return False
def check_huggingface_hub():
"""Check if huggingface_hub is available."""
try:
import huggingface_hub
return True
except ImportError:
print("β huggingface_hub is not installed")
print("Install it with: pip install huggingface_hub")
return False
def create_space_files(space_dir: Path):
"""Create the necessary files for Hugging Face Spaces."""
# Copy main files
shutil.copy("app.py", space_dir / "app.py")
shutil.copy("requirements.txt", space_dir / "requirements.txt")
# Create README for the space
readme_content = """---
title: MCP Sentiment Analysis Server
emoji: π
colorFrom: blue
colorTo: purple
sdk: gradio
sdk_version: "5.0.0"
app_file: app.py
pinned: false
license: mit
---
# MCP Sentiment Analysis Server
This is a Model Context Protocol (MCP) server that provides sentiment analysis capabilities.
## Features
- Comprehensive sentiment analysis
- Numerical sentiment scoring
- Emotion classification
- Batch text processing
- Full MCP protocol support
## Usage
### Web Interface
Use the interface above to test the sentiment analysis tools.
### MCP Endpoint
Connect your MCP clients to: `https://YOUR_USERNAME-SPACE_NAME.hf.space/gradio_api/mcp/sse`
### Available Tools
- `analyze_sentiment`: Comprehensive sentiment analysis
- `get_sentiment_score`: Numerical sentiment scoring (-1 to 1)
- `classify_emotion`: Basic emotion classification
- `batch_analyze`: Analyze multiple texts at once
## Example with smolagents
```python
from smolagents.mcp_client import MCPClient
with MCPClient(
{"url": "https://YOUR_USERNAME-SPACE_NAME.hf.space/gradio_api/mcp/sse"}
) as tools:
for tool in tools:
print(f"{tool.name}: {tool.description}")
```
## Example with Cursor IDE
Add to your MCP configuration:
```json
{
"mcpServers": {
"sentiment-analysis": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://YOUR_USERNAME-SPACE_NAME.hf.space/gradio_api/mcp/sse",
"--transport",
"sse-only"
]
}
}
}
```
"""
with open(space_dir / "README.md", "w") as f:
f.write(readme_content)
print(f"β
Created space files in {space_dir}")
def deploy_with_git(space_name: str, username: str):
"""Deploy using git commands."""
space_dir = Path(f"./hf_space_{space_name}")
if space_dir.exists():
print(f"Directory {space_dir} already exists. Remove it first or use a different name.")
return False
try:
# Clone the space repository
repo_url = f"https://huggingface.co/spaces/{username}/{space_name}"
print(f"Cloning {repo_url}...")
subprocess.run(["git", "clone", repo_url, str(space_dir)], check=True)
# Create space files
create_space_files(space_dir)
# Git operations
os.chdir(space_dir)
subprocess.run(["git", "add", "."], check=True)
subprocess.run(["git", "commit", "-m", "Deploy MCP sentiment analysis server"], check=True)
subprocess.run(["git", "push"], check=True)
print(f"β
Successfully deployed to {repo_url}")
print(f"π Your space will be available at: https://{username}-{space_name}.hf.space")
print(f"π MCP endpoint: https://{username}-{space_name}.hf.space/gradio_api/mcp/sse")
return True
except subprocess.CalledProcessError as e:
print(f"β Git operation failed: {e}")
return False
except Exception as e:
print(f"β Deployment failed: {e}")
return False
finally:
# Go back to original directory
os.chdir("..")
def deploy_with_hub_api(space_name: str, username: str):
"""Deploy using Hugging Face Hub API."""
try:
from huggingface_hub import HfApi, create_repo
api = HfApi()
# Create the space repository
repo_id = f"{username}/{space_name}"
print(f"Creating space {repo_id}...")
create_repo(
repo_id=repo_id,
repo_type="space",
space_sdk="gradio",
exist_ok=True
)
# Upload files
print("Uploading files...")
api.upload_file(
path_or_fileobj="app.py",
path_in_repo="app.py",
repo_id=repo_id,
repo_type="space"
)
api.upload_file(
path_or_fileobj="requirements.txt",
path_in_repo="requirements.txt",
repo_id=repo_id,
repo_type="space"
)
# Create and upload README
space_dir = Path("./temp_space")
space_dir.mkdir(exist_ok=True)
create_space_files(space_dir)
api.upload_file(
path_or_fileobj=str(space_dir / "README.md"),
path_in_repo="README.md",
repo_id=repo_id,
repo_type="space"
)
# Cleanup
shutil.rmtree(space_dir)
print(f"β
Successfully deployed to https://huggingface.co/spaces/{repo_id}")
print(f"π Your space will be available at: https://{username}-{space_name}.hf.space")
print(f"π MCP endpoint: https://{username}-{space_name}.hf.space/gradio_api/mcp/sse")
return True
except Exception as e:
print(f"β Hub API deployment failed: {e}")
return False
def main():
parser = argparse.ArgumentParser(description="Deploy MCP server to Hugging Face Spaces")
parser.add_argument("space_name", help="Name of the Hugging Face Space")
parser.add_argument("username", help="Your Hugging Face username")
parser.add_argument("--method", choices=["git", "api"], default="git",
help="Deployment method (default: git)")
parser.add_argument("--check-only", action="store_true",
help="Only check prerequisites without deploying")
args = parser.parse_args()
print("π MCP Server Deployment to Hugging Face Spaces")
print("=" * 50)
# Check prerequisites
print("Checking prerequisites...")
if not Path("app.py").exists():
print("β app.py not found in current directory")
return 1
if not Path("requirements.txt").exists():
print("β requirements.txt not found in current directory")
return 1
git_ok = check_git()
hub_ok = check_huggingface_hub()
if args.method == "git" and not git_ok:
print("β Git method selected but git is not available")
return 1
if args.method == "api" and not hub_ok:
print("β API method selected but huggingface_hub is not available")
return 1
if args.check_only:
print("β
All prerequisites check passed")
return 0
# Deploy
print(f"\nDeploying '{args.space_name}' for user '{args.username}' using {args.method} method...")
if args.method == "git":
success = deploy_with_git(args.space_name, args.username)
else:
success = deploy_with_hub_api(args.space_name, args.username)
if success:
print("\nπ Deployment completed successfully!")
print("\nNext steps:")
print("1. Wait a few minutes for the space to build")
print("2. Test the web interface")
print("3. Test the MCP endpoint with your clients")
return 0
else:
print("\nπ₯ Deployment failed!")
return 1
if __name__ == "__main__":
sys.exit(main())
|