File size: 7,537 Bytes
63495ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Local Test Script for HuggingFace Spaces App
Tests the app.py before deploying to HuggingFace
"""

import sys
import os

def test_imports():
    """Test if required packages are available"""
    print("="*80)
    print("Testing Package Imports...")
    print("="*80)
    
    required_packages = {
        'gradio': 'Gradio UI Framework',
        'huggingface_hub': 'HuggingFace Hub Client'
    }
    
    all_passed = True
    
    for package, description in required_packages.items():
        try:
            __import__(package)
            print(f"βœ… {description}: INSTALLED")
        except ImportError:
            print(f"❌ {description}: NOT FOUND")
            print(f"   Install with: pip install {package}")
            all_passed = False
    
    return all_passed


def test_app_file():
    """Test if app.py exists and is valid Python"""
    print("\n" + "="*80)
    print("Testing app.py File...")
    print("="*80)
    
    if not os.path.exists('app.py'):
        print("❌ app.py not found in current directory")
        print("   Make sure you're in the correct folder")
        return False
    
    print("βœ… app.py file exists")
    
    # Try to parse it
    try:
        with open('app.py', 'r') as f:
            code = f.read()
        
        compile(code, 'app.py', 'exec')
        print("βœ… app.py is valid Python code")
        
        # Check for key components
        if 'PPTScriptGenerator' in code:
            print("βœ… PPTScriptGenerator class found")
        else:
            print("⚠️  Warning: PPTScriptGenerator class not found")
        
        if 'create_gradio_interface' in code:
            print("βœ… create_gradio_interface function found")
        else:
            print("⚠️  Warning: create_gradio_interface function not found")
        
        if 'InferenceClient' in code:
            print("βœ… InferenceClient usage found")
        else:
            print("⚠️  Warning: InferenceClient not found")
        
        return True
        
    except SyntaxError as e:
        print(f"❌ Syntax error in app.py: {e}")
        return False


def test_requirements():
    """Test if requirements file exists"""
    print("\n" + "="*80)
    print("Testing Requirements File...")
    print("="*80)
    
    req_files = ['requirements_hf.txt', 'requirements.txt']
    found = False
    
    for req_file in req_files:
        if os.path.exists(req_file):
            print(f"βœ… {req_file} found")
            with open(req_file, 'r') as f:
                content = f.read()
            print(f"   Contents:\n{content}")
            found = True
            break
    
    if not found:
        print("❌ No requirements file found")
        print("   Need either requirements_hf.txt or requirements.txt")
        return False
    
    return True


def test_readme():
    """Test if README exists"""
    print("\n" + "="*80)
    print("Testing README File...")
    print("="*80)
    
    readme_files = ['README_HF.md', 'README.md']
    found = False
    
    for readme in readme_files:
        if os.path.exists(readme):
            print(f"βœ… {readme} found")
            with open(readme, 'r') as f:
                first_lines = ''.join(f.readlines()[:10])
            
            if '---' in first_lines and 'title:' in first_lines:
                print("βœ… YAML frontmatter detected")
            else:
                print("⚠️  Warning: YAML frontmatter not found (needed for HF Spaces)")
            
            found = True
            break
    
    if not found:
        print("⚠️  Warning: README file not found (recommended for HF Spaces)")
    
    return True  # Not critical


def test_app_launch():
    """Test if app can be imported and launched"""
    print("\n" + "="*80)
    print("Testing App Launch...")
    print("="*80)
    
    try:
        # Try importing the app
        import app as app_module
        print("βœ… app.py imported successfully")
        
        # Check if it has the expected components
        if hasattr(app_module, 'PPTScriptGenerator'):
            print("βœ… PPTScriptGenerator class accessible")
            
            # Try instantiating
            try:
                generator = app_module.PPTScriptGenerator()
                print("βœ… PPTScriptGenerator instantiated")
            except Exception as e:
                print(f"⚠️  Warning: Could not instantiate PPTScriptGenerator: {e}")
                print("   (This might be okay - could need HF_TOKEN)")
        
        if hasattr(app_module, 'create_gradio_interface'):
            print("βœ… create_gradio_interface function accessible")
        
        return True
        
    except Exception as e:
        print(f"❌ Error importing app.py: {e}")
        return False


def test_gradio_creation():
    """Test if Gradio interface can be created"""
    print("\n" + "="*80)
    print("Testing Gradio Interface Creation...")
    print("="*80)
    
    try:
        import app as app_module
        
        demo = app_module.create_gradio_interface()
        print("βœ… Gradio interface created successfully")
        
        print("\nπŸ’‘ You can now launch the app locally with:")
        print("   python app.py")
        print("\n   Or test in this session:")
        print("   >>> import app")
        print("   >>> demo = app.create_gradio_interface()")
        print("   >>> demo.launch()")
        
        return True
        
    except Exception as e:
        print(f"❌ Error creating Gradio interface: {e}")
        return False


def main():
    """Run all tests"""
    print("\n" + "πŸ” HUGGINGFACE SPACES APP - PRE-DEPLOYMENT TEST")
    print("="*80)
    print("")
    
    results = {
        'imports': test_imports(),
        'app_file': test_app_file(),
        'requirements': test_requirements(),
        'readme': test_readme(),
        'app_launch': test_app_launch(),
        'gradio_creation': test_gradio_creation()
    }
    
    # Summary
    print("\n" + "="*80)
    print("TEST SUMMARY")
    print("="*80)
    
    passed = sum(1 for v in results.values() if v)
    total = len(results)
    
    for test_name, result in results.items():
        status = "βœ… PASSED" if result else "❌ FAILED"
        print(f"{test_name.upper():25s}: {status}")
    
    print("="*80)
    print(f"Results: {passed}/{total} tests passed")
    
    if passed == total:
        print("\nπŸŽ‰ All tests passed! Your app is ready to deploy to HuggingFace Spaces!")
        print("\nπŸ“‹ Next Steps:")
        print("   1. Go to https://huggingface.co/new-space")
        print("   2. Create a new Space with SDK: Gradio")
        print("   3. Upload these files:")
        print("      - app.py")
        print("      - requirements_hf.txt (rename to requirements.txt)")
        print("      - README_HF.md (rename to README.md)")
        print("   4. Wait for build (1-2 minutes)")
        print("   5. Your app will be live!")
        print("\n   See DEPLOYMENT_GUIDE.md for detailed instructions")
    else:
        print("\n⚠️  Some tests failed. Please fix the errors above before deploying.")
        print("   Common fixes:")
        print("   - Install missing packages: pip install gradio huggingface_hub")
        print("   - Ensure app.py is in current directory")
        print("   - Check for syntax errors in app.py")
    
    print("="*80)
    
    return passed == total


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)