File size: 10,054 Bytes
7248c75 2178647 7248c75 2178647 59d8772 2178647 7248c75 2178647 7248c75 2178647 59d8772 2178647 59d8772 2178647 7248c75 2178647 7248c75 2178647 59d8772 2178647 59d8772 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 2178647 7248c75 |
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 |
#!/usr/bin/env python3
"""
Script to upload PhaseNet-TF model to Hugging Face Hub
"""
import os
import json
from pathlib import Path
from huggingface_hub import HfApi, create_repo, upload_file
from huggingface_hub import hf_hub_download
import torch
import yaml
def create_model_card(version=None):
"""Create a comprehensive model card for PhaseNet-TF"""
title = f"# PhaseNet-TF Alaska"
if version:
title = f"# PhaseNet-TF Alaska - {version}"
return f"""{title}
## Model Description
PhaseNet-TF is an advanced deep learning model for automatic seismic phase picking (P-wave, S-wave, and PS-wave detection) using spectrogram-based image segmentation approaches. The model leverages DeepLabV3Plus architecture to detect seismic arrivals with high accuracy, especially for weak and noisy signals from ocean-bottom seismometers and weak phases such as slab interface refracted PS and SP waves. This Alaska version is specifically trained on the PS_Alaska dataset for P and S phases. For more details, please refer to the paper and the [PhaseNet-TF](https://github.com/swei-seismo/PhaseNet-TF) repository.
## Model Architecture
- **Backbone**: DeepLabV3Plus with ResNet34 encoder
- **Input**: 3-component seismic waveforms converted to 6-channel spectrograms (real + imaginary)
- **Output**: Probability maps for P, S, PS phases and noise
- **Sampling Rate**: 40 Hz (dt_s = 0.025s)
- **Window Length**: 4800 points (120 seconds)
- **Spectrogram Size**: 64 × 4800 (frequency × time)
- **Input Channels**: 6 (3 real + 3 imaginary spectrogram channels)
- **Output Classes**: 4 (noise, P, S, PS)
"""
def create_config_json(model_path, version=None):
"""Create config.json with model metadata"""
config = {
"model_type": "phasenet-tf",
"architecture": "DeepLabV3Plus with ResNet34 encoder",
"input_channels": 6, # 3-component real + 3-component imaginary spectrograms
"output_classes": 4, # noise, P, S, PS
"sampling_rate": 40, # 1/0.025 = 40 Hz
"window_length": 4800, # 120 seconds at 40 Hz
"phases": ["P", "S", "PS"],
"framework": "pytorch",
"license": "mit",
"tags": ["seismic", "earthquake", "phase-picking", "deep-learning", "deeplabv3plus"]
}
if version:
config["version"] = version
config["checkpoint_file"] = f"alaska_{version}.bin"
return config
def create_main_readme():
"""Create a main README that showcases both versions"""
return """---
language: en
tags:
- seismic
- earthquake
- phase-picking
- deep-learning
- pytorch
license: mit
datasets:
- PS_Alaska
metrics:
- f1-score
- precision
- recall
---
# PhaseNet-TF Alaska: Advanced Seismic Arrival Time Detection
## Model Description
PhaseNet-TF is an advanced deep learning model for automatic seismic phase picking (P-wave, S-wave, and PS-wave detection) using spectrogram-based image segmentation approaches. The model leverages DeepLabV3Plus architecture to detect seismic arrivals with high accuracy, especially for weak and noisy signals from ocean-bottom seismometers and weak phases such as slab interface refracted PS and SP waves. This Alaska version is specifically trained on the PS_Alaska dataset for P and S phases.
## Available Versions
This repository contains two versions of the PhaseNet-TF Alaska model:
### 🔄 Iteration 1
- **Model File**: `alaska_iter1.bin`
- **Config**: `config_iter1.json`
- **Documentation**: [README_iter1.md](README_iter1.md)
### 🔄 Iteration 2
- **Model File**: `alaska_iter2.bin`
- **Config**: `config_iter2.json`
- **Documentation**: [README_iter2.md](README_iter2.md)
## Model Architecture
- **Backbone**: DeepLabV3Plus with ResNet34 encoder
- **Input**: 3-component seismic waveforms converted to 6-channel spectrograms (real + imaginary)
- **Output**: Probability maps for P, S, PS phases and noise
- **Sampling Rate**: 40 Hz (dt_s = 0.025s)
- **Window Length**: 4800 points (120 seconds)
- **Spectrogram Size**: 64 × 4800 (frequency × time)
- **Input Channels**: 6 (3 real + 3 imaginary spectrogram channels)
- **Output Classes**: 4 (noise, P, S, PS)
## Citation
If you use this model in your research, please cite:
```bibtex
@article{jie2025background,
title={Background Seismicity and Aftershocks of the 2020-2021 Large Earthquakes at the Alaska Peninsula Revealed by a Deep-learning-based Catalog},
author={Jie, Yaqi and Wei, Songqiao Shawn and Zhu, Weiqiang and Freymueller, Jeffrey Todd and Elliott, Julie},
journal={Authorea Preprints},
year={2025},
publisher={Authorea}
}
```
## License
This model is licensed under the MIT License.
"""
def upload_model_to_hf(
checkpoint_path: str,
config_path: str = None,
repo_name: str = "PhaseNet-TF_Alaska",
username: str = None,
token: str = None,
version: str = None,
upload_main_readme: bool = False
):
"""Upload model to Hugging Face Hub"""
# Initialize API
if token:
api = HfApi(token=token)
else:
api = HfApi()
# Get username if not provided
if username is None:
try:
username = api.whoami()["name"]
print(f"Using logged-in username: {username}")
except Exception as e:
print(f"Error getting username: {e}")
print("Please provide username with --username or login with huggingface-cli login")
return
# Create repository
repo_id = f"{username}/{repo_name}"
try:
if token:
create_repo(repo_id, token=token, exist_ok=True)
else:
create_repo(repo_id, exist_ok=True)
print(f"Repository {repo_id} created/accessed successfully")
except Exception as e:
print(f"Error creating repository: {e}")
return
# Determine file paths based on version
if version:
model_path = f"alaska_{version}.bin"
config_path_in_repo = f"config_{version}.json"
readme_path_in_repo = f"README_{version}.md"
print(f"Uploading version {version} to {repo_id}")
else:
model_path = "alaska.bin"
config_path_in_repo = "config.json"
readme_path_in_repo = "README.md"
print(f"Uploading to {repo_id}")
# Upload checkpoint
print(f"Uploading model checkpoint as {model_path}...")
upload_file(
path_or_fileobj=checkpoint_path,
path_in_repo=model_path,
repo_id=repo_id,
token=token
)
# Upload config if provided
if config_path and os.path.exists(config_path):
config_yaml_path = f"config_{version}.yaml" if version else "config.yaml"
print(f"Uploading config file as {config_yaml_path}...")
upload_file(
path_or_fileobj=config_path,
path_in_repo=config_yaml_path,
repo_id=repo_id,
token=token
)
# Create and upload config.json
config_json = create_config_json(checkpoint_path, version)
config_json_path = "config.json"
with open(config_json_path, 'w') as f:
json.dump(config_json, f, indent=2)
upload_file(
path_or_fileobj=config_json_path,
path_in_repo=config_path_in_repo,
repo_id=repo_id,
token=token
)
# Create and upload README.md
model_card = create_model_card(version)
model_card += """
## Citation
If you use this model in your research, please cite:
```bibtex
@article{jie2025background,
title={Background Seismicity and Aftershocks of the 2020-2021 Large Earthquakes at the Alaska Peninsula Revealed by a Deep-learning-based Catalog},
author={Jie, Yaqi and Wei, Songqiao Shawn and Zhu, Weiqiang and Freymueller, Jeffrey Todd and Elliott, Julie},
journal={Authorea Preprints},
year={2025},
publisher={Authorea}
}
```
## License
This model is licensed under the MIT License.
"""
readme_path = "README.md"
with open(readme_path, 'w') as f:
f.write(model_card)
upload_file(
path_or_fileobj=readme_path,
path_in_repo=readme_path_in_repo,
repo_id=repo_id,
token=token
)
# Upload main README if requested
if upload_main_readme:
print("Uploading main README.md...")
main_readme = create_main_readme()
main_readme_path = "main_README.md"
with open(main_readme_path, 'w') as f:
f.write(main_readme)
upload_file(
path_or_fileobj=main_readme_path,
path_in_repo="README.md",
repo_id=repo_id,
token=token
)
os.remove(main_readme_path)
# Clean up temporary files
os.remove(config_json_path)
os.remove(readme_path)
print(f"Model uploaded successfully to https://huggingface.co/{repo_id}")
if version:
print(f"Files uploaded: {model_path}, {config_path_in_repo}, {readme_path_in_repo}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Upload PhaseNet-TF model to Hugging Face")
parser.add_argument("--checkpoint", required=True, help="Path to model checkpoint (.ckpt)")
parser.add_argument("--config", help="Path to config file (.yaml)")
parser.add_argument("--repo-name", default="PhaseNet-TF_Alaska", help="Repository name")
parser.add_argument("--username", help="Hugging Face username (optional if already logged in)")
parser.add_argument("--token", help="Hugging Face token (optional if already logged in)")
parser.add_argument("--version", help="Version suffix for file naming (e.g., iter1, iter2, v1, v2)")
parser.add_argument("--main-readme", action="store_true", help="Upload main README that showcases both versions")
args = parser.parse_args()
upload_model_to_hf(
checkpoint_path=args.checkpoint,
config_path=args.config,
repo_name=args.repo_name,
username=args.username,
token=args.token,
version=args.version,
upload_main_readme=args.main_readme
) |