forked from Kirazul/chat2api-CLI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
121 lines (96 loc) · 3.54 KB
/
app.py
File metadata and controls
121 lines (96 loc) · 3.54 KB
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
import warnings
import sys
import os
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from fastapi.templating import Jinja2Templates
from utils.config import enable_gateway, api_prefix
warnings.filterwarnings("ignore")
log_config = uvicorn.config.LOGGING_CONFIG
default_format = "%(asctime)s | %(levelname)s | %(message)s"
access_format = r'%(asctime)s | %(levelname)s | %(client_addr)s: %(request_line)s %(status_code)s'
log_config["formatters"]["default"]["fmt"] = default_format
log_config["formatters"]["access"]["fmt"] = access_format
app = FastAPI(
docs_url="/docs", # Set Swagger UI documentation path
redoc_url="/redoc", # Set Redoc documentation path
openapi_url="/openapi.json" # Set OpenAPI JSON path
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Add API Key Mapper Middleware
from middleware.apikey_mapper import APIKeyMapperMiddleware
app.add_middleware(APIKeyMapperMiddleware)
# Add middleware to handle double slashes in URLs
from starlette.middleware.base import BaseHTTPMiddleware
class DoubleSlashFixMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
# Fix double slashes in path by normalizing
if '//' in request.url.path:
# Replace multiple slashes with single slash
import re
fixed_path = re.sub(r'/+', '/', request.url.path)
# Update the request scope path
request.scope['path'] = fixed_path
return await call_next(request)
app.add_middleware(DoubleSlashFixMiddleware)
# Handle templates path for both development and PyInstaller bundle
def get_templates_directory():
if getattr(sys, 'frozen', False):
# Running as PyInstaller bundle
return os.path.join(sys._MEIPASS, 'templates')
else:
# Running in development
return "templates"
templates = Jinja2Templates(directory=get_templates_directory())
security_scheme = HTTPBearer()
import api.chat2api
# Import sync API for CLI-to-Server communication
from api.sync import router as sync_router
app.include_router(sync_router)
# Add a simple health check endpoint
@app.get("/")
async def root():
return {"message": "Chat2API Server is running", "status": "healthy", "version": "1.7.1-beta1"}
@app.get("/health")
async def health():
return {"status": "healthy", "message": "Chat2API Server is running"}
@app.get("/test")
async def test():
return {"message": "Test endpoint working", "api_prefix": api_prefix}
if enable_gateway:
import gateway.share
import gateway.login
import gateway.chatgpt
import gateway.gpts
import gateway.admin
import gateway.v1
import gateway.backend
if __name__ == "__main__":
import os
# Get host and port from environment variables
host = os.getenv("HOST", "0.0.0.0")
port = int(os.getenv("PORT", "5005"))
# Production settings
environment = os.getenv("ENVIRONMENT", "development")
print(f"Starting Chat2API server on {host}:{port}")
print(f"Environment: {environment}")
print(f"Gateway enabled: {enable_gateway}")
print(f"API prefix: '{api_prefix}'")
if environment == "production":
uvicorn.run(
"app:app",
host=host,
port=port,
access_log=True,
log_level="info"
)
else:
uvicorn.run("app:app", host=host, port=port)