epipred2 / deploy_hf.py
mercelv's picture
app
292ca6d verified
Raw
History Blame Contribute Delete
7.28 kB
#!/usr/bin/env python3
"""
Deployment script for Hugging Face Spaces
"""
import os
import shutil
import subprocess
import sys
from pathlib import Path
def check_requirements():
"""Check if required files exist"""
required_files = [
'app_gradio.py',
'model_predictor.py',
'config_hf.py',
'requirements.txt',
'README.md'
]
missing_files = []
for file in required_files:
if not os.path.exists(file):
missing_files.append(file)
if missing_files:
print(f"❌ Missing required files: {', '.join(missing_files)}")
return False
print("βœ… All required files present")
return True
def check_model_files():
"""Check if model files exist"""
model_paths = [
'models/epitope_model.keras',
'models/epitope_model.h5',
'models/epitope_model_savedmodel'
]
model_found = False
for path in model_paths:
if os.path.exists(path):
print(f"βœ… Found model: {path}")
model_found = True
break
if not model_found:
print("⚠️ No model files found - app will run in demo mode")
print("Expected locations:")
for path in model_paths:
print(f" - {path}")
return True # Not critical for deployment
def prepare_deployment():
"""Prepare files for deployment"""
print("πŸ“¦ Preparing deployment files...")
# Create deployment directory
deploy_dir = Path("hf_deploy")
if deploy_dir.exists():
shutil.rmtree(deploy_dir)
deploy_dir.mkdir()
# Copy essential files
files_to_copy = [
'app_gradio.py',
'model_predictor.py',
'config_hf.py',
'requirements.txt',
'README.md',
'.gitignore'
]
for file in files_to_copy:
if os.path.exists(file):
shutil.copy2(file, deploy_dir / file)
print(f"βœ… Copied {file}")
# Copy model files if they exist
models_dir = Path("models")
if models_dir.exists():
deploy_models_dir = deploy_dir / "models"
shutil.copytree(models_dir, deploy_models_dir)
print("βœ… Copied models directory")
# Copy sample files
sample_files = ['test_sequences.fasta', 'sample_input.fasta']
for file in sample_files:
if os.path.exists(file):
shutil.copy2(file, deploy_dir / file)
print(f"βœ… Copied {file}")
print(f"πŸ“¦ Deployment files prepared in {deploy_dir}")
return deploy_dir
def test_gradio_app(deploy_dir):
"""Test the Gradio app"""
print("πŸ§ͺ Testing Gradio app...")
original_dir = os.getcwd()
try:
os.chdir(deploy_dir)
# Test import
result = subprocess.run([
sys.executable, '-c',
'import app_gradio; print("βœ… Gradio app imports successfully")'
], capture_output=True, text=True)
if result.returncode == 0:
print("βœ… Gradio app test passed")
return True
else:
print(f"❌ Gradio app test failed: {result.stderr}")
return False
finally:
os.chdir(original_dir)
def create_space_instructions(deploy_dir):
"""Create instructions for Hugging Face Spaces"""
instructions = """
# πŸš€ Hugging Face Spaces Deployment Instructions
## Files Ready for Deployment
Your EpiPred app is now ready for Hugging Face Spaces! Here's what to do:
### 1. Create a New Space
1. Go to [Hugging Face Spaces](https://huggingface.co/spaces)
2. Click "Create new Space"
3. Fill in the details:
- **Space name**: `epipred` (or your preferred name)
- **License**: MIT
- **SDK**: Gradio
- **Hardware**: CPU Basic (free tier)
### 2. Upload Files
Upload all files from this `hf_deploy` directory to your Space:
```
hf_deploy/
β”œβ”€β”€ app_gradio.py # Main Gradio application
β”œβ”€β”€ model_predictor.py # Model loading and prediction
β”œβ”€β”€ config_hf.py # Configuration for HF Spaces
β”œβ”€β”€ requirements.txt # Python dependencies
β”œβ”€β”€ README.md # Space description with metadata
β”œβ”€β”€ .gitignore # Git ignore file
β”œβ”€β”€ models/ # Model files (if available)
β”œβ”€β”€ test_sequences.fasta # Sample input files
└── sample_input.fasta
```
### 3. Key Files Explained
- **`README.md`**: Contains the Space metadata (title, emoji, SDK, etc.)
- **`app_gradio.py`**: Main application file (specified in README.md as `app_file`)
- **`requirements.txt`**: Dependencies including Gradio and TensorFlow
- **`models/`**: Your trained model files
### 4. Deployment Process
1. **Upload files** to your Space repository
2. **Wait for build** - Hugging Face will automatically install dependencies
3. **Test the app** - Your Space will be available at `https://huggingface.co/spaces/YOUR_USERNAME/epipred`
### 5. Configuration Options
The app is configured for Hugging Face Spaces with:
- **Resource limits**: 25 sequences max, 150K amino acids total
- **Timeout**: 5 minutes per prediction
- **Demo mode**: Fallback if models don't load
- **Responsive design**: Works on mobile and desktop
### 6. Troubleshooting
If the build fails:
1. Check the build logs in your Space
2. Verify all files are uploaded correctly
3. Ensure model files are not too large (>1GB may cause issues)
4. The app will run in demo mode if models fail to load
### 7. Customization
You can customize the app by editing:
- **`config_hf.py`**: Limits, styling, example sequences
- **`app_gradio.py`**: Interface layout and functionality
- **`README.md`**: Space description and metadata
### 8. Success!
Once deployed, your Space will provide:
- βœ… Professional web interface for epitope prediction
- βœ… File upload and text input support
- βœ… Interactive results visualization
- βœ… CSV/JSON download functionality
- βœ… Mobile-responsive design
- βœ… Automatic scaling and hosting
Your EpiPred tool will be publicly available and ready for users! πŸŽ‰
---
**Need help?** Check the [Hugging Face Spaces documentation](https://huggingface.co/docs/hub/spaces) or ask in the community forums.
"""
with open(deploy_dir / "DEPLOYMENT_INSTRUCTIONS.md", "w") as f:
f.write(instructions)
print("πŸ“ Created deployment instructions")
def main():
"""Main deployment preparation function"""
print("πŸš€ EpiPred - Hugging Face Spaces Deployment Preparation")
print("=" * 60)
# Check requirements
if not check_requirements():
sys.exit(1)
# Check model files
check_model_files()
# Prepare deployment
deploy_dir = prepare_deployment()
# Test the app
if not test_gradio_app(deploy_dir):
print("⚠️ App test failed, but deployment files are still prepared")
# Create instructions
create_space_instructions(deploy_dir)
print("\n" + "=" * 60)
print("πŸŽ‰ Deployment preparation complete!")
print(f"πŸ“ Files ready in: {deploy_dir.absolute()}")
print("πŸ“– See DEPLOYMENT_INSTRUCTIONS.md for next steps")
print("\nπŸš€ Ready to deploy to Hugging Face Spaces!")
if __name__ == "__main__":
main()