File size: 4,952 Bytes
8666ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Simple startup script for debugging Flow2API on HuggingFace Spaces"""

import os
import sys
import time
import asyncio
from pathlib import Path

def debug_environment():
    """Print environment debug information"""
    print("=" * 60)
    print("πŸ” FLOW2API DEBUG STARTUP")
    print("=" * 60)
    print(f"Python version: {sys.version}")
    print(f"Current working directory: {os.getcwd()}")
    print(f"User ID: {os.getuid()}")
    print(f"Group ID: {os.getgid()}")
    print(f"Environment variables:")
    for key, value in sorted(os.environ.items()):
        if key.startswith('FLOW2API') or key in ['HOST', 'PORT', 'HOME', 'PATH']:
            print(f"  {key}: {value}")
    print("=" * 60)

def check_file_permissions():
    """Check critical file permissions"""
    files_to_check = [
        '/app',
        '/app/logs.txt',
        '/app/data',
        '/app/config'
    ]

    print("πŸ“ FILE PERMISSIONS CHECK:")
    for file_path in files_to_check:
        path = Path(file_path)
        if path.exists():
            stat_info = path.stat()
            print(f"  βœ… {file_path}: exists, mode={oct(stat_info.st_mode)}")
            if path.is_file():
                try:
                    # Test write permission
                    with open(path, 'a') as f:
                        f.write("")
                    print(f"  βœ… {file_path}: writable")
                except Exception as e:
                    print(f"  ❌ {file_path}: NOT writable - {e}")
        else:
            print(f"  ❌ {file_path}: does not exist")
    print("=" * 60)

async def test_basic_import():
    """Test if basic modules can be imported"""
    print("πŸ“¦ IMPORT TEST:")
    try:
        import fastapi
        print(f"  βœ… FastAPI: {fastapi.__version__}")
    except Exception as e:
        print(f"  ❌ FastAPI import failed: {e}")

    try:
        import uvicorn
        print(f"  βœ… Uvicorn: available")
    except Exception as e:
        print(f"  ❌ Uvicorn import failed: {e}")

    try:
        import aiosqlite
        print(f"  βœ… aiosqlite: available")
    except Exception as e:
        print(f"  ❌ aiosqlite import failed: {e}")

    print("=" * 60)

async def test_database_connection():
    """Test database creation and connection"""
    print("πŸ’Ύ DATABASE TEST:")
    try:
        import aiosqlite

        # Test database directory creation
        data_dir = Path("/app/data")
        data_dir.mkdir(exist_ok=True)
        print(f"  βœ… Data directory: {data_dir}")

        # Test database connection
        db_path = "/app/data/test.db"
        async with aiosqlite.connect(db_path) as db:
            await db.execute("SELECT 1")
            print(f"  βœ… Database connection: successful")

        # Clean up test file
        os.remove(db_path)
        print(f"  βœ… Test database: cleaned up")

    except Exception as e:
        print(f"  ❌ Database test failed: {e}")
        import traceback
        traceback.print_exc()

    print("=" * 60)

def start_simple_server():
    """Start a simple test server"""
    print("🌐 SIMPLE SERVER TEST:")
    try:
        from fastapi import FastAPI
        import uvicorn

        app = FastAPI()

        @app.get("/")
        async def root():
            return {"message": "Flow2API is running", "status": "ok"}

        @app.get("/health")
        async def health():
            return {"status": "healthy"}

        print("  βœ… Simple FastAPI app created")
        print("  πŸš€ Starting simple server on port 7860...")

        # Start server
        uvicorn.run(
            app,
            host="0.0.0.0",
            port=7860,
            log_level="info"
        )

    except Exception as e:
        print(f"  ❌ Simple server failed: {e}")
        import traceback
        traceback.print_exc()

async def main():
    """Main debugging function"""
    debug_environment()
    check_file_permissions()
    await test_basic_import()
    await test_database_connection()

    print("🎯 STARTING FLOW2API:")
    try:
        # Import and start the main application
        from src.main import app
        print("  βœ… Main app imported successfully")

        # Start with uvicorn directly
        import uvicorn
        print("  πŸš€ Starting main application...")

        uvicorn.run(
            app,
            host="0.0.0.0",
            port=7860,
            log_level="info",
            access_log=True
        )

    except Exception as e:
        print(f"  ❌ Main app startup failed: {e}")
        import traceback
        traceback.print_exc()
        print("πŸ”„ FALLING BACK TO SIMPLE SERVER...")
        start_simple_server()

if __name__ == "__main__":
    print("Starting Flow2API with debug mode...")
    asyncio.run(main())