tmp2
Browse files
app.py
DELETED
@@ -1,91 +0,0 @@
|
|
1 |
-
#!/usr/bin/env python3
|
2 |
-
# -*- coding: utf-8 -*-
|
3 |
-
|
4 |
-
from fastapi import FastAPI, Body, Request, Depends, HTTPException
|
5 |
-
from fastapi.responses import HTMLResponse, ORJSONResponse, FileResponse
|
6 |
-
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
7 |
-
from starlette.status import HTTP_401_UNAUTHORIZED
|
8 |
-
from fastapi.responses import StreamingResponse
|
9 |
-
import collections
|
10 |
-
if not hasattr(collections, "MutableSet"):
|
11 |
-
collections.MutableSet = collections.abc.MutableSet
|
12 |
-
if not hasattr(collections, "MutableMapping"):
|
13 |
-
collections.MutableMapping = collections.abc.MutableMapping
|
14 |
-
import httpx
|
15 |
-
import logging
|
16 |
-
import os
|
17 |
-
|
18 |
-
# ロギング設定を追加
|
19 |
-
logging.basicConfig(
|
20 |
-
level=os.getenv('LOG_LEVEL', 'INFO'),
|
21 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
22 |
-
)
|
23 |
-
logger = logging.getLogger(__name__)
|
24 |
-
|
25 |
-
# HTTPXのログも有効化する場合は以下も追加
|
26 |
-
logging.getLogger("httpx").setLevel(logging.DEBUG)
|
27 |
-
|
28 |
-
app = FastAPI()
|
29 |
-
|
30 |
-
from starlette.middleware.cors import CORSMiddleware
|
31 |
-
app.add_middleware(
|
32 |
-
CORSMiddleware,
|
33 |
-
allow_origins=["https://novelai.net", "https://hisaruki.ddns.net"],
|
34 |
-
allow_credentials=True,
|
35 |
-
allow_methods=["*"],
|
36 |
-
allow_headers=["*"]
|
37 |
-
)
|
38 |
-
|
39 |
-
security = HTTPBasic()
|
40 |
-
|
41 |
-
def authenticate(credentials: HTTPBasicCredentials = Depends(security)):
|
42 |
-
correct_username = "administrator"
|
43 |
-
correct_password = "X2fK9pL7mR3qZ8vY"
|
44 |
-
if not (credentials.username == correct_username and credentials.password == correct_password):
|
45 |
-
raise HTTPException(
|
46 |
-
status_code=HTTP_401_UNAUTHORIZED,
|
47 |
-
detail="認証に失敗しました",
|
48 |
-
headers={"WWW-Authenticate": "Basic"},
|
49 |
-
)
|
50 |
-
return credentials.username
|
51 |
-
@app.get("/authtest", dependencies=[Depends(authenticate)])
|
52 |
-
async def eval(request: Request, body: dict = Body):
|
53 |
-
return HTMLResponse(content="ok.", media_type="text/plain")
|
54 |
-
|
55 |
-
|
56 |
-
@app.post("/unify/chat/completions")
|
57 |
-
async def unify_chat_completions(request: Request, body: dict = Body(...)):
|
58 |
-
headers = {
|
59 |
-
"Authorization": request.headers["authorization"],
|
60 |
-
"Content-Type": "application/json"
|
61 |
-
}
|
62 |
-
endpoint = "https://api.unify.ai/v0/chat/completions"
|
63 |
-
logger.debug(f"リクエストボディ: {body}")
|
64 |
-
logger.debug(f"リクエストヘッダー: {headers}")
|
65 |
-
|
66 |
-
# streamがFalseの場合は通常のレスポンスを返す
|
67 |
-
if not body.get("stream", True):
|
68 |
-
async with httpx.AsyncClient(timeout=600) as client:
|
69 |
-
logger.debug(f"非ストリーミングモードでリクエスト送信: {endpoint}")
|
70 |
-
response = await client.post(endpoint, json=body, headers=headers)
|
71 |
-
logger.debug(f"ステータスコード: {response.status_code}")
|
72 |
-
logger.debug(f"レスポンスヘッダー: {response.headers}")
|
73 |
-
|
74 |
-
if response.status_code != 200:
|
75 |
-
logger.error(f"エラーレスポンス: {response.text}")
|
76 |
-
raise HTTPException(status_code=response.status_code, detail=response.text)
|
77 |
-
|
78 |
-
response_json = response.json()
|
79 |
-
logger.debug(f"レスポンスボディ: {response_json}")
|
80 |
-
return ORJSONResponse(response_json)
|
81 |
-
|
82 |
-
# streamがTrueの場合は既存のストリーミング処理
|
83 |
-
async def stream_response():
|
84 |
-
async with httpx.AsyncClient(timeout=600) as client:
|
85 |
-
async with client.stream("POST", endpoint, json=body, headers=headers) as response:
|
86 |
-
if response.status_code != 200:
|
87 |
-
raise HTTPException(status_code=response.status_code, detail=response.text)
|
88 |
-
async for chunk in response.aiter_bytes():
|
89 |
-
yield chunk
|
90 |
-
return StreamingResponse(stream_response(), media_type="text/event-stream")
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|