mateenahmed commited on
Commit
ab856bd
·
verified ·
1 Parent(s): 44b2a9b

Upload upload_model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. upload_model.py +152 -0
upload_model.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Upload ISNet model to Hugging Face Hub for AutoModelForImageSegmentation
4
+ """
5
+ import os
6
+ import torch
7
+ from huggingface_hub import HfApi, login
8
+ from isnet_transformers import ISNetForImageSegmentation, ISNetConfig
9
+
10
+ def prepare_model_for_upload():
11
+ """Prepare the model for Hugging Face upload"""
12
+
13
+ # Find the model file
14
+ model_paths = [
15
+ "supplyswap_isnet.pth",
16
+ "isnet-transformers/supplyswap_isnet.pth",
17
+ "models/supplyswap_isnet.pth"
18
+ ]
19
+
20
+ model_path = None
21
+ for path in model_paths:
22
+ if os.path.exists(path):
23
+ model_path = path
24
+ break
25
+
26
+ if not model_path:
27
+ print("❌ No model file found! Please place your trained model file in the current directory.")
28
+ return None
29
+
30
+ print(f"✅ Found model file: {model_path}")
31
+
32
+ # Create a temporary directory for upload
33
+ upload_dir = "model_for_upload"
34
+ os.makedirs(upload_dir, exist_ok=True)
35
+
36
+ # Create config
37
+ config = ISNetConfig()
38
+ config.save_pretrained(upload_dir)
39
+
40
+ # Load the model
41
+ print("Loading model...")
42
+ state_dict = torch.load(model_path, map_location="cpu")
43
+
44
+ # Create transformers model
45
+ model = ISNetForImageSegmentation(config)
46
+ model.isnet.load_state_dict(state_dict)
47
+ model.eval()
48
+
49
+ # Save in transformers format
50
+ print(f"Saving model to {upload_dir}...")
51
+ model.save_pretrained(upload_dir)
52
+
53
+ # Also save the original weights for compatibility
54
+ torch.save(state_dict, os.path.join(upload_dir, "supplyswap_isnet.pth"))
55
+
56
+ # Create a model card
57
+ model_card_content = """---
58
+ language: en
59
+ tags:
60
+ - image-segmentation
61
+ - background-removal
62
+ - isnet
63
+ license: mit
64
+ model_type: isnet
65
+ ---
66
+
67
+ # ISNet Background Remover
68
+
69
+ This model removes backgrounds from images using the ISNet architecture.
70
+
71
+ ## Usage
72
+
73
+ ```python
74
+ from transformers import AutoModelForImageSegmentation
75
+ from isnet_transformers import ISNetForImageSegmentation
76
+
77
+ # Download and load the model
78
+ model = AutoModelForImageSegmentation.from_pretrained("YOUR_USERNAME/isnet-background-remover")
79
+ # OR
80
+ model = ISNetForImageSegmentation.from_pretrained("YOUR_USERNAME/isnet-background-remover")
81
+ ```
82
+
83
+ ## Features
84
+ - Removes backgrounds from images
85
+ - High-quality segmentation
86
+ - Fast inference
87
+ - Compatible with transformers library
88
+
89
+ ## Model Architecture
90
+ - Based on ISNet (Interactive Image Segmentation Network)
91
+ - Uses U-Net style encoder-decoder architecture
92
+ - Outputs binary masks for background removal
93
+ """
94
+
95
+ with open(os.path.join(upload_dir, "README.md"), "w") as f:
96
+ f.write(model_card_content)
97
+
98
+ print(f"✅ Model prepared in {upload_dir}")
99
+ return upload_dir
100
+
101
+ def upload_to_huggingface(repo_name, upload_dir):
102
+ """Upload the model to Hugging Face Hub"""
103
+
104
+ # Login to Hugging Face
105
+ print("Please enter your Hugging Face token:")
106
+ token = input().strip()
107
+ login(token)
108
+
109
+ api = HfApi()
110
+
111
+ # Create the repository
112
+ print(f"Creating repository: {repo_name}")
113
+ api.create_repo(repo_name, exist_ok=True)
114
+
115
+ # Upload all files
116
+ print("Uploading model files...")
117
+ for root, dirs, files in os.walk(upload_dir):
118
+ for file in files:
119
+ file_path = os.path.join(root, file)
120
+ relative_path = os.path.relpath(file_path, upload_dir)
121
+
122
+ with open(file_path, "rb") as f:
123
+ api.upload_file(
124
+ path_or_fileobj=f,
125
+ path_in_repo=relative_path,
126
+ repo_id=repo_name
127
+ )
128
+ print(f"✅ Uploaded: {relative_path}")
129
+
130
+ print(f"🎉 Model successfully uploaded to: https://huggingface.co/{repo_name}")
131
+
132
+ if __name__ == "__main__":
133
+ print("🚀 Preparing ISNet model for Hugging Face upload...")
134
+
135
+ # Prepare the model
136
+ upload_dir = prepare_model_for_upload()
137
+
138
+ if upload_dir:
139
+ # Get repository name
140
+ print("\nEnter your Hugging Face username:")
141
+ username = input().strip()
142
+ repo_name = f"{username}/isnet-background-remover"
143
+
144
+ # Upload to Hugging Face
145
+ upload_to_huggingface(repo_name, upload_dir)
146
+
147
+ print(f"\n🎯 After upload, users can download your model with:")
148
+ print(f"from transformers import AutoModelForImageSegmentation")
149
+ print(f"model = AutoModelForImageSegmentation.from_pretrained('{repo_name}')")
150
+ print(f"\nOR")
151
+ print(f"from isnet_transformers import ISNetForImageSegmentation")
152
+ print(f"model = ISNetForImageSegmentation.from_pretrained('{repo_name}')")