File size: 8,369 Bytes
18e3b27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Pre-Deployment Validation Script
Run this before deploying to HuggingFace Spaces to ensure everything is ready.
"""

import os
import sys
import yaml
import json
from pathlib import Path

def check_file_exists(filepath, description):
    """Check if a required file exists."""
    if Path(filepath).exists():
        print(f"  ✓ {description}: {filepath}")
        return True
    else:
        print(f"  ✗ {description} MISSING: {filepath}")
        return False

def validate_openenv_yaml():
    """Validate openenv.yaml structure."""
    print("\n" + "="*60)
    print("Validating openenv.yaml")
    print("="*60)
    
    if not Path("openenv.yaml").exists():
        print("  ✗ openenv.yaml not found!")
        return False
    
    with open("openenv.yaml", "r") as f:
        config = yaml.safe_load(f)
    
    required = ["spec_version", "name", "type", "runtime", "app", "port", "tasks", "action_schema", "observation_schema"]
    all_ok = True
    
    for field in required:
        if field in config:
            print(f"  ✓ {field}: present")
        else:
            print(f"  ✗ {field}: MISSING")
            all_ok = False
    
    # Check tasks
    if "tasks" in config:
        task_count = len(config["tasks"])
        if task_count >= 3:
            print(f"  ✓ Tasks: {task_count} defined (>= 3 required)")
        else:
            print(f"  ✗ Tasks: only {task_count} defined (need >= 3)")
            all_ok = False
    
    return all_ok

def validate_dockerfile():
    """Validate Dockerfile."""
    print("\n" + "="*60)
    print("Validating Dockerfile")
    print("="*60)
    
    if not Path("Dockerfile").exists():
        print("  ✗ Dockerfile not found!")
        return False
    
    with open("Dockerfile", "r") as f:
        content = f.read()
    
    checks = [
        ("EXPOSE 7860", "Port 7860 exposed"),
        ("HEALTHCHECK", "Health check configured"),
        ("CMD", "CMD instruction present"),
        ("uvicorn", "Uvicorn server command"),
    ]
    
    all_ok = True
    for pattern, description in checks:
        if pattern in content:
            print(f"  ✓ {description}")
        else:
            print(f"  ✗ {description} MISSING")
            all_ok = False
    
    return all_ok

def validate_project_structure():
    """Validate project structure."""
    print("\n" + "="*60)
    print("Validating Project Structure")
    print("="*60)
    
    required_files = [
        ("pyproject.toml", "Project configuration"),
        ("README.md", "Documentation"),
        ("inference.py", "Inference script"),
        ("models.py", "Data models"),
        ("client.py", "Client implementation"),
        ("server/app.py", "FastAPI application"),
        ("server/my_env_environment.py", "Environment implementation"),
        ("server/tasks.py", "Task definitions"),
        ("graders/__init__.py", "Graders module"),
    ]
    
    all_ok = True
    for filepath, description in required_files:
        if not check_file_exists(filepath, description):
            all_ok = False
    
    return all_ok

def validate_environment_interface():
    """Validate environment implements required interface."""
    print("\n" + "="*60)
    print("Validating Environment Interface")
    print("="*60)
    
    try:
        from server.my_env_environment import QuantumCircuitEnvironment
        from models import QuantumAction, QuantumObservation, ActionType, GateType
        
        env = QuantumCircuitEnvironment(seed=42)
        
        # Test reset
        obs = env.reset(config={"task_id": "easy"})
        assert isinstance(obs, QuantumObservation), "reset() must return QuantumObservation"
        print("  ✓ reset(config) returns QuantumObservation")
        
        # Test step
        action = QuantumAction(action_type=ActionType.ADD, gate=GateType.H, qubits=[0])
        obs = env.step(action)
        assert isinstance(obs, QuantumObservation), "step() must return QuantumObservation"
        assert hasattr(obs, 'reward'), "Observation must have reward"
        assert hasattr(obs, 'done'), "Observation must have done"
        print("  ✓ step(action) returns QuantumObservation with reward and done")
        
        # Test state
        state = env.state
        assert state is not None, "state property must return State"
        print("  ✓ state property returns State")
        
        # Test score range
        assert 0.0 <= obs.score <= 1.0, f"Score out of range: {obs.score}"
        print(f"  ✓ Score in valid range: {obs.score:.4f}")
        
        return True
        
    except Exception as e:
        print(f"  ✗ Environment validation failed: {e}")
        return False

def validate_tasks():
    """Validate all tasks are accessible."""
    print("\n" + "="*60)
    print("Validating Tasks")
    print("="*60)
    
    try:
        from server.my_env_environment import QuantumCircuitEnvironment
        
        env = QuantumCircuitEnvironment(seed=42)
        tasks = ["easy", "medium", "hard", "efficient", "noisy", "budget", "approx"]
        
        for task_id in tasks:
            obs = env.reset(config={"task_id": task_id})
            assert obs.task_id == task_id, f"Task ID mismatch: {obs.task_id} != {task_id}"
            print(f"  ✓ Task '{task_id}': accessible")
        
        print(f"  ✓ All {len(tasks)} tasks validated")
        return True
        
    except Exception as e:
        print(f"  ✗ Task validation failed: {e}")
        return False

def validate_inference_script():
    """Validate inference script structure."""
    print("\n" + "="*60)
    print("Validating Inference Script")
    print("="*60)
    
    if not Path("inference.py").exists():
        print("  ✗ inference.py not found!")
        return False
    
    with open("inference.py", "r") as f:
        content = f.read()
    
    checks = [
        ("from openai import OpenAI", "OpenAI client import"),
        ("API_BASE_URL", "API_BASE_URL variable"),
        ("MODEL_NAME", "MODEL_NAME variable"),
        ("HF_TOKEN", "HF_TOKEN variable"),
        ("[START]", "START log format"),
        ("[STEP]", "STEP log format"),
        ("[END]", "END log format"),
        ("async def main", "Async main function"),
    ]
    
    all_ok = True
    for pattern, description in checks:
        if pattern in content:
            print(f"  ✓ {description}")
        else:
            print(f"  ✗ {description} MISSING")
            all_ok = False
    
    return all_ok

def main():
    """Run all validation checks."""
    print("\n" + "="*60)
    print("PRE-DEPLOYMENT VALIDATION")
    print("="*60)
    
    checks = [
        ("Project Structure", validate_project_structure),
        ("openenv.yaml", validate_openenv_yaml),
        ("Dockerfile", validate_dockerfile),
        ("Environment Interface", validate_environment_interface),
        ("Tasks", validate_tasks),
        ("Inference Script", validate_inference_script),
    ]
    
    results = []
    for name, check_func in checks:
        try:
            result = check_func()
            results.append((name, result))
        except Exception as e:
            print(f"\n  ✗ {name} validation failed with exception: {e}")
            results.append((name, False))
    
    # Summary
    print("\n" + "="*60)
    print("VALIDATION SUMMARY")
    print("="*60)
    
    passed = sum(1 for _, r in results if r)
    total = len(results)
    
    for name, result in results:
        status = "✓ PASS" if result else "✗ FAIL"
        print(f"  {status}: {name}")
    
    print(f"\nTotal: {passed}/{total} checks passed")
    
    if passed == total:
        print("\n" + "="*60)
        print("🎉 READY FOR DEPLOYMENT!")
        print("="*60)
        print("\nNext steps:")
        print("  1. Build Docker image: docker build -t quantum-circuit-opt:latest .")
        print("  2. Test locally: docker run -p 7860:7860 quantum-circuit-opt:latest")
        print("  3. Deploy to HF Spaces: openenv push")
        print("\nSee QUICK_DEPLOY.md for detailed instructions.")
        return 0
    else:
        print("\n" + "="*60)
        print(f"❌ {total - passed} check(s) failed")
        print("="*60)
        print("\nPlease fix the issues above before deploying.")
        return 1

if __name__ == "__main__":
    sys.exit(main())