File size: 7,619 Bytes
1bcce96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2251ba3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bcce96
 
 
 
 
8f0bc94
 
2251ba3
8f0bc94
 
 
 
2251ba3
8f0bc94
 
 
2251ba3
8f0bc94
1bcce96
8f0bc94
1bcce96
8f0bc94
 
1bcce96
 
 
 
 
 
 
8f0bc94
 
 
 
 
 
 
 
 
2251ba3
 
 
 
8f0bc94
2251ba3
8f0bc94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2251ba3
 
 
 
 
 
 
8f0bc94
 
 
1bcce96
 
8f0bc94
 
1bcce96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f0bc94
 
 
1bcce96
 
 
 
 
2251ba3
 
 
 
 
 
1bcce96
8f0bc94
 
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
import shutil
import logging
from pathlib import Path

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Add the backend directory to the Python path
sys.path.append(os.path.abspath("backend"))

# Create necessary directories if they don't exist
os.makedirs("./temp_audio", exist_ok=True)
os.makedirs("./temp", exist_ok=True)
os.makedirs("./static", exist_ok=True)

# Check for index.html and create a simple one if it doesn't exist
static_path = Path("./static")
index_path = static_path / "index.html"
if not index_path.exists():
    logger.warning("index.html not found in static directory, creating a simple one")
    with open(index_path, "w") as f:
        f.write("""<!DOCTYPE html>
<html>
<head>
    <title>PodCraft API</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f8f9fa; }
        .container { max-width: 800px; padding: 2rem; background-color: white; border-radius: 0.5rem; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); }
        h1 { color: #6366F1; }
        pre { background-color: #f5f5f5; padding: 1rem; border-radius: 0.25rem; overflow: auto; }
    </style>
</head>
<body>
    <div class="container">
        <h1>PodCraft API</h1>
        <p>The PodCraft API is running. You can access the API at <a href="/docs">/docs</a>.</p>
        <p>API Status: <a href="/api/status">/api/status</a></p>
    </div>
</body>
</html>""")

# Set environment variables for MongoDB connection timeout
os.environ["MONGODB_CONNECT_TIMEOUT_MS"] = "5000"  # 5 seconds timeout
os.environ["MONGODB_SERVER_SELECTION_TIMEOUT_MS"] = "5000"  # 5 seconds timeout

# Create a FastAPI app - either the main one or an error one
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware

# Check if static directory exists with index.html
static_index_exists = static_path.exists() and index_path.exists()
logger.info(f"Static path exists: {static_path.exists()}")
if static_path.exists():
    logger.info(f"Static directory contents: {os.listdir(static_path)}")
    logger.info(f"Static index exists: {index_path.exists()}")

try:
    # Try to import the main app
    from backend.app.main import app
    
    # Add CORS middleware
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # Add an index route to check if the API is accessible
    @app.get("/api/status")
    async def status():
        return {"status": "ok", "message": "PodCraft API is running"}
    
    # Override the root route to serve the frontend
    @app.get("/", response_class=HTMLResponse)
    async def read_root():
        # If index.html exists, return it directly using FileResponse
        if index_path.exists():
            logger.info(f"Serving index.html from {index_path}")
            return FileResponse(index_path)
        else:
            logger.warning("index.html not found, returning fallback HTML")
            return """
            <html>
                <head>
                    <title>PodCraft API</title>
                    <style>
                        body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f8f9fa; }
                        .container { max-width: 800px; padding: 2rem; background-color: white; border-radius: 0.5rem; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); }
                        h1 { color: #6366F1; }
                        pre { background-color: #f5f5f5; padding: 1rem; border-radius: 0.25rem; overflow: auto; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <h1>PodCraft API</h1>
                        <p>The PodCraft API is running, but the frontend static files were not found.</p>
                        <p>Static directory: <code>./static</code></p>
                        <p>Static directory exists: <code>{static_path.exists()}</code></p>
                        <p>If you need to access the API directly, you can use the following endpoints:</p>
                        <ul>
                            <li><code>/api/status</code> - Check API status</li>
                            <li><code>/docs</code> - API documentation</li>
                        </ul>
                    </div>
                </body>
            </html>
            """
    
    # Mount static files
    # First, make sure we're not serving the root path via StaticFiles
    @app.get("/static/{path:path}")
    async def serve_static(path: str):
        file_path = static_path / path
        if file_path.exists() and file_path.is_file():
            return FileResponse(file_path)
        return {"error": "File not found"}
    
    app_to_run = app
    logger.info("Using main application")

except Exception as e:
    # If there's an error, create a minimal FastAPI app
    logger.error(f"Error initializing main app: {str(e)}")
    error_app = FastAPI()
    
    @error_app.get("/", response_class=HTMLResponse)
    async def root():
        return f"""
        <html>
            <head>
                <title>PodCraft - Error</title>
                <style>
                    body {{ font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f8f9fa; }}
                    .container {{ max-width: 800px; padding: 2rem; background-color: white; border-radius: 0.5rem; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); }}
                    h1 {{ color: #d32f2f; }}
                    pre {{ background-color: #f5f5f5; padding: 1rem; border-radius: 0.25rem; overflow: auto; }}
                </style>
            </head>
            <body>
                <div class="container">
                    <h1>PodCraft Error</h1>
                    <p>An error occurred while starting the application:</p>
                    <pre>{str(e)}</pre>
                    <p>Please check your environment variables and configuration.</p>
                    <p>MongoDB URL format should be: <code>mongodb+srv://username:[email protected]/...</code></p>
                    <p>API keys should be properly formatted and valid.</p>
                    <p>Static directory exists: <code>{static_path.exists()}</code></p>
                    {f"<p>Static directory contents: <code>{os.listdir(static_path)}</code></p>" if static_path.exists() else ""}
                    <p>Static index exists: <code>{static_index_exists}</code></p>
                </div>
            </body>
        </html>
        """
    
    @error_app.get("/static/{path:path}")
    async def serve_static(path: str):
        file_path = static_path / path
        if file_path.exists() and file_path.is_file():
            return FileResponse(file_path)
        return {"error": "File not found"}
    
    app_to_run = error_app
    logger.info("Using error application")

# For Hugging Face Spaces - expose the app
if __name__ == "__main__":
    import uvicorn
    
    port = int(os.environ.get("PORT", 7860))
    host = os.environ.get("HOST", "0.0.0.0")
    
    logger.info(f"Starting server on {host}:{port}")
    uvicorn.run(app_to_run, host=host, port=port)