File size: 5,966 Bytes
3f3fffc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eea0cb
3f3fffc
2eea0cb
 
3f3fffc
2eea0cb
3f3fffc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Deployment Test Script for HuggingFace Spaces
Tests if the app can start without dependency errors
"""

import sys
import subprocess
import importlib
from pathlib import Path

def test_imports():
    """Test that all critical imports work"""
    print("πŸ” Testing critical imports...")

    critical_imports = [
        "gradio",
        "google.genai",
        "reportlab",
        "pypdf",
        "pandas",
        "PIL",
        "dotenv"
    ]

    failed = []
    for module in critical_imports:
        try:
            importlib.import_module(module)
            print(f"  βœ… {module}")
        except ImportError as e:
            print(f"  ❌ {module}: {e}")
            failed.append((module, str(e)))

    if failed:
        print("\n❌ Import test failed!")
        for module, error in failed:
            print(f"  - {module}: {error}")
        return False

    print("βœ… All imports successful!\n")
    return True


def test_gradio_version():
    """Test that Gradio version matches README.md"""
    print("πŸ” Testing Gradio version compatibility...")

    import gradio as gr

    # Read README.md to get expected version
    readme_path = Path(__file__).parent / "README.md"
    expected_version = None

    if readme_path.exists():
        with open(readme_path, 'r') as f:
            for line in f:
                if line.strip().startswith('sdk_version:'):
                    expected_version = line.split(':')[1].strip()
                    break

    actual_version = gr.__version__

    if expected_version:
        print(f"  Expected (README.md): {expected_version}")
        print(f"  Actual (installed):   {actual_version}")

        if actual_version == expected_version:
            print("  βœ… Versions match!")
        else:
            print("  ⚠️  Version mismatch (may still work)")
    else:
        print(f"  ℹ️  Installed version: {actual_version}")

    # Test built-in File component for PDF support
    try:
        test_file = gr.File(label="Test", file_types=[".pdf"])
        print("  βœ… Gradio File component supports PDF files")
    except Exception as e:
        print(f"  ❌ File component error: {e}")
        return False

    print()
    return True


def test_app_syntax():
    """Test that app.py has no syntax errors"""
    print("πŸ” Testing app.py syntax...")

    app_path = Path(__file__).parent / "app.py"

    if not app_path.exists():
        print("  ❌ app.py not found!")
        return False

    try:
        with open(app_path, 'r') as f:
            compile(f.read(), str(app_path), 'exec')
        print("  βœ… No syntax errors\n")
        return True
    except SyntaxError as e:
        print(f"  ❌ Syntax error: {e}\n")
        return False


def test_dependencies():
    """Test that requirements.txt dependencies can be installed"""
    print("πŸ” Testing requirements.txt...")

    req_path = Path(__file__).parent / "requirements.txt"

    if not req_path.exists():
        print("  ❌ requirements.txt not found!")
        return False

    with open(req_path, 'r') as f:
        deps = [line.strip() for line in f if line.strip() and not line.startswith('#')]

    print(f"  Found {len(deps)} dependencies:")
    for dep in deps:
        print(f"    - {dep}")

    print("  βœ… Requirements file valid\n")
    return True


def test_env_vars():
    """Check for required environment variables"""
    print("πŸ” Checking environment setup...")

    import os

    required_vars = ["GEMINI_API_KEY"]
    optional_vars = ["SEARCH_API_KEY", "SEARCH_ENGINE_ID"]

    missing_required = []
    for var in required_vars:
        if os.getenv(var):
            print(f"  βœ… {var} is set")
        else:
            print(f"  ⚠️  {var} NOT set (REQUIRED for app to work)")
            missing_required.append(var)

    for var in optional_vars:
        if os.getenv(var):
            print(f"  βœ… {var} is set")
        else:
            print(f"  ℹ️  {var} not set (optional)")

    if missing_required:
        print(f"\n  ⚠️  Missing required variables: {', '.join(missing_required)}")
        print("  ℹ️  App will fail at runtime without these!")

    print()
    return len(missing_required) == 0


def test_output_directory():
    """Check if output directory exists"""
    print("πŸ” Checking output directory...")

    output_dir = Path(__file__).parent / "output"

    if output_dir.exists():
        print(f"  βœ… Output directory exists: {output_dir}")
    else:
        print(f"  ℹ️  Output directory will be created at runtime")

    print()
    return True


def main():
    """Run all deployment tests"""
    print("=" * 60)
    print("πŸš€ HuggingFace Spaces Deployment Test")
    print("=" * 60)
    print()

    tests = [
        ("Dependencies", test_dependencies),
        ("Python Imports", test_imports),
        ("Gradio Version", test_gradio_version),
        ("App Syntax", test_app_syntax),
        ("Environment Variables", test_env_vars),
        ("Output Directory", test_output_directory),
    ]

    results = []
    for name, test_func in tests:
        try:
            passed = test_func()
            results.append((name, passed))
        except Exception as e:
            print(f"  ❌ {name} test crashed: {e}\n")
            results.append((name, False))

    # Summary
    print("=" * 60)
    print("πŸ“Š Test Summary")
    print("=" * 60)

    passed = sum(1 for _, p in results if p)
    total = len(results)

    for name, result in results:
        status = "βœ… PASS" if result else "❌ FAIL"
        print(f"  {status}: {name}")

    print()
    print(f"Results: {passed}/{total} tests passed")

    if passed == total:
        print("\nπŸŽ‰ All tests passed! Safe to deploy to HuggingFace Spaces.")
        return 0
    else:
        print("\n⚠️  Some tests failed. Fix issues before deploying.")
        return 1


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