File size: 10,321 Bytes
6086b2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python3
"""
Startup Fix Script for Dressify
Handles dataset preparation issues and ensures system startup
"""

import os
import sys
import subprocess
import time
from pathlib import Path


def check_dataset_status():
    """Check the current dataset status."""
    print("πŸ” Checking dataset status...")
    
    root = os.path.abspath(os.path.join(os.getcwd(), "data", "Polyvore"))
    
    if not os.path.exists(root):
        print(f"❌ Dataset directory not found: {root}")
        return False
    
    # Check key components
    images_dir = os.path.join(root, "images")
    splits_dir = os.path.join(root, "splits")
    
    has_images = os.path.isdir(images_dir) and any(Path(images_dir).glob("*"))
    has_splits = os.path.isdir(splits_dir) and any(Path(splits_dir).glob("*.json"))
    
    print(f"πŸ“ Dataset root: {root}")
    print(f"πŸ–ΌοΈ Images: {'βœ…' if has_images else '❌'} ({images_dir})")
    print(f"πŸ“Š Splits: {'βœ…' if has_splits else '❌'} ({splits_dir})")
    
    # Check for official splits
    official_splits = []
    for location in ["nondisjoint", "disjoint"]:
        location_path = os.path.join(root, location)
        if os.path.exists(location_path):
            for split in ["train", "valid", "test"]:
                split_file = os.path.join(location_path, f"{split}.json")
                if os.path.exists(split_file):
                    size_mb = os.path.getsize(split_file) / (1024 * 1024)
                    official_splits.append(f"{location}/{split}.json ({size_mb:.1f} MB)")
    
    if official_splits:
        print(f"🎯 Official splits found:")
        for split in official_splits:
            print(f"   βœ… {split}")
    
    if has_images and has_splits:
        print("βœ… Dataset is ready!")
        return True
    elif has_images:
        print("⚠️ Images present but splits missing - will create splits from official data")
        return "needs_splits"
    else:
        print("❌ Dataset incomplete - needs full preparation")
        return False


def prepare_dataset():
    """Prepare the dataset using the improved scripts."""
    print("\nπŸš€ Preparing dataset...")
    
    root = os.path.abspath(os.path.join(os.getcwd(), "data", "Polyvore"))
    
    # First, ensure the data fetcher runs
    try:
        print("πŸ“₯ Running data fetcher...")
        from utils.data_fetch import ensure_dataset_ready
        dataset_root = ensure_dataset_ready()
        
        if not dataset_root:
            print("❌ Data fetcher failed")
            return False
            
        print(f"βœ… Data fetcher completed: {dataset_root}")
        
    except Exception as e:
        print(f"❌ Data fetcher error: {e}")
        return False
    
    # Now run the dataset preparation script (without random splits)
    try:
        print("πŸ”§ Running dataset preparation...")
        
        # Check if prepare_polyvore.py exists
        prep_script = "scripts/prepare_polyvore.py"
        if not os.path.exists(prep_script):
            prep_script = "prepare_polyvore.py"
        
        if not os.path.exists(prep_script):
            print(f"❌ Prepare script not found: {prep_script}")
            return False
        
        # Run the preparation script WITHOUT random splits
        cmd = [
            sys.executable, prep_script,
            "--root", root
            # Note: NOT using --force_random_split
        ]
        
        print(f"πŸ”§ Running: {' '.join(cmd)}")
        print("🎯 This will use official splits from nondisjoint/ and disjoint/ folders")
        
        result = subprocess.run(cmd, capture_output=True, text=True, check=False)
        
        if result.returncode == 0:
            print("βœ… Dataset preparation completed successfully!")
            print("πŸ“ Output:")
            print(result.stdout)
            return True
        else:
            print("❌ Dataset preparation failed!")
            print("πŸ“ Error output:")
            print(result.stderr)
            print("πŸ“ Standard output:")
            print(result.stdout)
            
            # Check if it's because official splits are missing
            if "No official splits found" in result.stderr or "No official splits found" in result.stdout:
                print("\nπŸ”§ Issue: Official splits not found in nondisjoint/ or disjoint/ folders")
                print("πŸ“ Expected structure:")
                print("   data/Polyvore/")
                print("   β”œβ”€β”€ nondisjoint/")
                print("   β”‚   β”œβ”€β”€ train.json")
                print("   β”‚   β”œβ”€β”€ valid.json")
                print("   β”‚   └── test.json")
                print("   β”œβ”€β”€ disjoint/")
                print("   β”‚   β”œβ”€β”€ train.json")
                print("   β”‚   β”œβ”€β”€ valid.json")
                print("   β”‚   └── test.json")
                print("   └── images/")
                
                print("\nπŸ’‘ Solution: The dataset should have been downloaded with official splits.")
                print("   Check if the Hugging Face download completed successfully.")
                
            return False
            
    except Exception as e:
        print(f"❌ Dataset preparation error: {e}")
        return False


def verify_splits():
    """Verify that splits were created successfully."""
    print("\nπŸ” Verifying splits...")
    
    root = os.path.abspath(os.path.join(os.getcwd(), "data", "Polyvore"))
    splits_dir = os.path.join(root, "splits")
    
    if not os.path.exists(splits_dir):
        print("❌ Splits directory not found")
        return False
    
    required_files = [
        "train.json",
        "outfits_train.json", 
        "outfit_triplets_train.json"
    ]
    
    missing_files = []
    for file_name in required_files:
        file_path = os.path.join(splits_dir, file_name)
        if os.path.exists(file_path):
            size_mb = os.path.getsize(file_path) / (1024 * 1024)
            print(f"βœ… {file_name}: {size_mb:.1f} MB")
        else:
            print(f"❌ {file_name}: Missing")
            missing_files.append(file_name)
    
    if missing_files:
        print(f"❌ Missing required files: {missing_files}")
        return False
    
    print("βœ… All required splits verified!")
    return True


def test_training_scripts():
    """Test that training scripts can run without errors."""
    print("\nπŸ§ͺ Testing training scripts...")
    
    # Test ResNet training script
    try:
        print("πŸ”§ Testing ResNet training script...")
        from models.resnet_embedder import ResNetItemEmbedder
        print("βœ… ResNet model imports successfully")
    except Exception as e:
        print(f"❌ ResNet model import failed: {e}")
        return False
    
    # Test ViT training script
    try:
        print("πŸ”§ Testing ViT training script...")
        from models.vit_outfit import OutfitCompatibilityModel
        print("βœ… ViT model imports successfully")
    except Exception as e:
        print(f"❌ ViT model import failed: {e}")
        return False
    
    print("βœ… All training scripts tested successfully!")
    return True


def create_quick_start_script():
    """Create a quick start script for easy testing."""
    script_content = """#!/bin/bash
# Quick Start Script for Dressify
# This script will prepare the dataset and start training

echo "πŸš€ Dressify Quick Start"
echo "========================"

# Check if dataset is ready
if [ -d "data/Polyvore/splits" ] && [ -f "data/Polyvore/splits/train.json" ]; then
    echo "βœ… Dataset is ready!"
else
    echo "πŸ”§ Preparing dataset..."
    python startup_fix.py
fi

# Start quick training
echo "🎯 Starting quick training..."
python train_resnet.py --data_root data/Polyvore --epochs 3 --out models/exports/resnet_quick.pth

echo "πŸŽ‰ Quick start completed!"
echo "πŸ“ Check models/exports/ for trained models"
"""
    
    script_path = "quick_start.sh"
    with open(script_path, "w") as f:
        f.write(script_content)
    
    # Make executable
    os.chmod(script_path, 0o755)
    print(f"πŸ“ Created quick start script: {script_path}")


def main():
    """Main startup fix routine."""
    print("πŸš€ Dressify Startup Fix")
    print("=" * 50)
    
    # Check current status
    status = check_dataset_status()
    
    if status is True:
        print("βœ… System is ready to go!")
        return True
    
    elif status == "needs_splits":
        print("πŸ”§ Dataset needs splits created from official data...")
        if prepare_dataset():
            if verify_splits():
                print("βœ… Dataset preparation completed successfully!")
                return True
            else:
                print("❌ Split verification failed")
                return False
        else:
            print("❌ Dataset preparation failed")
            return False
    
    else:
        print("πŸ”§ Dataset needs full preparation...")
        if prepare_dataset():
            if verify_splits():
                print("βœ… Dataset preparation completed successfully!")
                return True
            else:
                print("❌ Split verification failed")
                return False
        else:
            print("❌ Dataset preparation failed")
            return False


if __name__ == "__main__":
    try:
        success = main()
        
        if success:
            print("\nπŸŽ‰ Startup fix completed successfully!")
            print("πŸš€ Your Dressify system is ready to use!")
            
            # Create quick start script
            create_quick_start_script()
            
            print("\nπŸ“‹ Next steps:")
            print("1. Run: python app.py")
            print("2. Or use: ./quick_start.sh")
            print("3. Check the Advanced Training tab for parameter controls")
            
        else:
            print("\n❌ Startup fix failed!")
            print("πŸ”§ Please check the error messages above")
            print("πŸ“ž Contact support if issues persist")
            
    except KeyboardInterrupt:
        print("\n⏹️ Startup fix interrupted by user")
    except Exception as e:
        print(f"\nπŸ’₯ Unexpected error: {e}")
        import traceback
        traceback.print_exc()