Spaces:
Sleeping

File size: 7,046 Bytes
7151903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Request, HTTPException, Depends, Header
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import JSONResponse
import httpx
import json
from datetime import datetime
import os
import logging
from typing import Optional

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

app = FastAPI(title="Embedding Proxy API", version="1.0.0")

# 配置
FDROID_API_URL = os.getenv("EMBEDDING_ENDPOINT", "https://xxxx.com")
PORT = int(os.getenv("PORT", 7860))  # HuggingFace 默认端口
AUTH_TOKEN = os.getenv("AUTH_TOKEN", "your-secret-token-here")  # 从环境变量读取认证令牌

# HTTP Bearer 认证
security = HTTPBearer()

# HTTP 客户端
http_client = httpx.AsyncClient(
    timeout=httpx.Timeout(60.0, connect=10.0),
    limits=httpx.Limits(max_keepalive_connections=5, max_connections=10),
    verify=False
)

# 请求统计
stats = {
    "total_requests": 0,
    "successful_requests": 0,
    "failed_requests": 0,
    "unauthorized_requests": 0
}

def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> bool:
    """验证 Bearer Token"""
    if credentials.credentials != AUTH_TOKEN:
        stats["unauthorized_requests"] += 1
        logger.warning(f"Unauthorized access attempt with token: {credentials.credentials[:10]}...")
        raise HTTPException(
            status_code=401,
            detail="Invalid authentication token",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return True

# 可选:从 Authorization header 直接获取 token
async def get_bearer_token(authorization: Optional[str] = Header(None)) -> str:
    """从 Authorization header 获取 token"""
    if not authorization:
        stats["unauthorized_requests"] += 1
        logger.warning("Missing authorization header")
        raise HTTPException(
            status_code=401,
            detail="Missing authorization header",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    try:
        scheme, token = authorization.split()
        if scheme.lower() != "bearer":
            raise ValueError("Invalid authentication scheme")
    except ValueError:
        stats["unauthorized_requests"] += 1
        logger.warning("Invalid authorization header format")
        raise HTTPException(
            status_code=401,
            detail="Invalid authorization header format",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    if token != AUTH_TOKEN:
        stats["unauthorized_requests"] += 1
        logger.warning(f"Invalid token: {token[:10]}...")
        raise HTTPException(
            status_code=401,
            detail="Invalid authentication token",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    return token

@app.get("/")
async def root():
    """基础信息端点(不需要认证)"""
    return {
        "service": "Embedding Proxy API",
        "status": "running",
        "authentication": "required",
        "endpoint": "/v1/embeddings",
        "stats": stats
    }

@app.get("/health")
async def health_check():
    """健康检查端点(不需要认证)"""
    return {"status": "healthy", "timestamp": datetime.now().isoformat()}

@app.post("/v1/embeddings")
async def proxy_embeddings(
    request: Request,
    token: str = Depends(get_bearer_token)
):
    """代理嵌入请求(需要认证)"""
    stats["total_requests"] += 1
    
    try:
        # 解析请求体
        body = await request.json()
        model = body.get('model', 'unknown')
        
        # 记录请求信息
        input_data = body.get('input', '')
        if isinstance(input_data, str):
            input_info = f"text({len(input_data)} chars)"
        elif isinstance(input_data, list):
            input_info = f"list({len(input_data)} items)"
        else:
            input_info = "unknown"
        
        logger.info(f"Authenticated request: model={model}, input={input_info}")
        
        # 转发请求到目标端点
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "Embedding-Proxy/1.0"
        }
        
        start_time = datetime.now()
        response = await http_client.post(
            FDROID_API_URL,
            headers=headers,
            json=body
        )
        elapsed = (datetime.now() - start_time).total_seconds()
        
        response_data = response.json()
        
        # 记录响应状态
        if response.status_code == 200:
            stats["successful_requests"] += 1
            
            # 获取向量维度
            embedding_dim = 0
            if 'data' in response_data and response_data['data']:
                embedding = response_data['data'][0].get('embedding', [])
                embedding_dim = len(embedding)
            
            logger.info(f"Success: status={response.status_code}, dim={embedding_dim}, time={elapsed:.2f}s")
        else:
            stats["failed_requests"] += 1
            logger.warning(f"Failed: status={response.status_code}, time={elapsed:.2f}s, error={response_data}")
        
        return JSONResponse(
            content=response_data,
            status_code=response.status_code
        )
        
    except httpx.TimeoutException:
        stats["failed_requests"] += 1
        logger.error("Request timeout after 60s")
        raise HTTPException(status_code=504, detail="Gateway timeout")
        
    except httpx.RequestError as e:
        stats["failed_requests"] += 1
        logger.error(f"Request error: {str(e)}")
        raise HTTPException(status_code=502, detail="Bad gateway")
        
    except json.JSONDecodeError as e:
        stats["failed_requests"] += 1
        logger.error(f"Invalid JSON: {str(e)}")
        raise HTTPException(status_code=400, detail="Invalid JSON in request body")
        
    except Exception as e:
        stats["failed_requests"] += 1
        logger.error(f"Internal error: {str(e)}")
        raise HTTPException(status_code=500, detail="Internal server error")

@app.post("/embeddings")
async def proxy_embeddings_alt(
    request: Request,
    token: str = Depends(get_bearer_token)
):
    """兼容路径(需要认证)"""
    return await proxy_embeddings(request, token)

@app.on_event("startup")
async def startup_event():
    """启动事件"""
    logger.info("=" * 50)
    logger.info("Embedding Proxy Service Started")
    logger.info(f"Port: {PORT}")
    logger.info(f"Authentication: Enabled (Bearer Token)")
    logger.info("=" * 50)

@app.on_event("shutdown")
async def shutdown_event():
    """关闭事件"""
    await http_client.aclose()
    logger.info("Service shutdown completed")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=PORT,
        log_level="info"
    )