File size: 7,280 Bytes
292ca6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()