Spaces:
Sleeping
Sleeping
File size: 9,817 Bytes
1a120a0 1548dfa 7dabbf5 a529f2d 13e718d a529f2d 5666458 777c3c3 1548dfa a529f2d 7dabbf5 7c87b1b 64427ba a529f2d ae9d418 a529f2d 6af13dd bee0db3 385a4a1 7c87b1b a529f2d 1548dfa a529f2d 1548dfa a529f2d 1548dfa 29a772a 1548dfa 7c87b1b 807f025 6e015d6 41780be 6e015d6 64427ba 6e015d6 7dabbf5 6e015d6 1548dfa 6e015d6 1548dfa 41780be 64427ba 41780be a529f2d 5cde144 a451d4e 5cde144 7f7fb69 72b59c6 7f7fb69 cca4ee1 a2728af f79ae72 7f7fb69 71e8755 7f7fb69 5cde144 a58eac3 cca4ee1 7f7fb69 a58eac3 7f7fb69 a451d4e 1e28f6f 09f0823 1e28f6f 09f0823 | 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | from fastapi import FastAPI, Request, File, UploadFile, Form
from fastapi.responses import StreamingResponse, JSONResponse
import os
import uuid
import time
import httpx
import json
import numpy as np
import soundfile as sf
import io
import wave
app = FastAPI(
title="OpenAI Compatible API (Mock)",
version="1.0.0"
)
HF_TOKEN = os.getenv("HF_TOKEN")
headers_with_auth = {
"Content-Type": "application/json",
"Authorization": "Bearer " + HF_TOKEN
}
list_models = None
timeout = httpx.Timeout(
connect=5.0,
read=120.0,
write=5.0,
pool=5.0,
)
def log_request(request: Request, body: dict):
print("=" * 80)
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {request.method} {request.url.path}")
print("Headers:")
for k, v in request.headers.items():
print(f" {k}: {v}")
print("Body:")
print(json.dumps(body, indent=2, ensure_ascii=False))
print("=" * 80)
# ------------------------------------------------------------------
# HEALTH CHECK
# ------------------------------------------------------------------
@app.get("/")
async def health_check():
return "Service up and running!"
# ------------------------------------------------------------------
# MODELS
# ------------------------------------------------------------------
@app.get("/v1/models")
async def list_models():
async with httpx.AsyncClient() as client:
upstream_url = "https://ynsbyrm-api-chat-service-models.hf.space/v1/models"
resp = await client.get(upstream_url, headers=headers_with_auth)
response = resp.json()
# model_id -> url map
global MODEL_REGISTRY
MODEL_REGISTRY = {
m["id"]: m["url"]
for m in response
if "id" in m and "url" in m
}
return response
# ------------------------------------------------------------------
# RESPONSES
# ------------------------------------------------------------------
@app.post("/v1/responses")
async def create_response(request: Request):
body = await request.json()
log_request(request, body)
return {
"id": f"resp_{uuid.uuid4().hex}",
"object": "response",
"created": int(time.time()),
"model": body.get("model", "unknown"),
"output": [
{
"id": "msg_1",
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "This is a mock response."
}
]
}
]
}
# ------------------------------------------------------------------
# EMBEDDINGS
# ------------------------------------------------------------------
@app.post("/v1/embeddings")
async def create_embeddings(request: Request):
body = await request.json()
log_request(request, body)
inputs = body.get("input", [])
if not isinstance(inputs, list):
inputs = [inputs]
return {
"object": "list",
"data": [
{
"object": "embedding",
"embedding": [0.0] * 1536,
"index": i
}
for i in range(len(inputs))
],
"model": body.get("model", "text-embedding-3")
}
# ------------------------------------------------------------------
# IMAGES
# ------------------------------------------------------------------
@app.post("/v1/images/generations")
async def generate_image(request: Request):
body = await request.json()
log_request(request, body)
return {
"created": int(time.time()),
"data": [
{
"url": "https://dummyimage.com/1024x1024/000/fff.png&text=mock"
}
]
}
# ------------------------------------------------------------------
# CHAT COMPLETIONS (LEGACY-OLD)
# ------------------------------------------------------------------
@app.post("/v1/chat/completions_old")
async def chat_completions(request: Request):
body = await request.json()
log_request(request, body)
return {
"id": f"chatcmpl_{uuid.uuid4().hex}",
"object": "chat.completion",
"created": int(time.time()),
"model": body.get("model", "gpt-4"),
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "This is a mock chat completion."
},
"finish_reason": "stop"
}
]
}
# ------------------------------------------------------------------
# CHAT COMPLETIONS (New with Streaming)
# ------------------------------------------------------------------
@app.post("/v1/chat/completions")
async def chat_completions(request: Request):
body = await request.json()
log_request(request, body)
messages = body.get("messages", [])
stream = body.get("stream", False)
model_name = body.get("model", "unknown")
if model_name not in MODEL_REGISTRY:
return JSONResponse(
status_code=400,
content={"error": f"Model not found: {model_name}"}
)
upstream_url = MODEL_REGISTRY[model_name] + "/v1/chat/completions"
if body.get("stream", False):
# STREAMING
async def proxy_stream():
async with httpx.AsyncClient(timeout=timeout) as client:
async with client.stream(
"POST",
upstream_url,
json=body,
headers=headers_with_auth,
) as response:
async for chunk in response.aiter_raw():
yield chunk
return StreamingResponse(
proxy_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
else:
# NON-STREAM (opsiyonel)
async with httpx.AsyncClient(timeout=timeout) as client:
resp = await client.post(upstream_url, json=body, headers=headers_with_auth)
return resp.json()
# ------------------------------------------------------------------
# COMPLETIONS (LEGACY)
# ------------------------------------------------------------------
@app.post("/v1/completions")
async def completions(request: Request):
body = await request.json()
log_request(request, body)
return {
"id": f"cmpl_{uuid.uuid4().hex}",
"object": "text_completion",
"created": int(time.time()),
"model": body.get("model", "text-davinci-003"),
"choices": [
{
"text": "This is a mock completion.",
"index": 0,
"finish_reason": "stop"
}
]
}
# ------------------------------------------------------------------
# MODERATIONS
# ------------------------------------------------------------------
@app.post("/v1/moderations")
async def moderations(request: Request):
body = await request.json()
log_request(request, body)
return {
"id": f"modr_{uuid.uuid4().hex}",
"model": body.get("model", "omni-moderation-latest"),
"results": [
{
"flagged": False,
"categories": {},
"category_scores": {}
}
]
}
# ------------------------------------------------------------------
# AUDIO TRANSCRIPTIONS (STT)
# ------------------------------------------------------------------
@app.post("/v1/audio/transcriptions")
async def audio_transcriptions(
file: UploadFile = File(...),
model: str = Form("whisper-1"),
language: str | None = Form(None),
prompt: str | None = Form(None),
response_format: str = Form("json"),
):
print("Request hit /v1/audio/transcriptions")
if model not in MODEL_REGISTRY:
return JSONResponse(
status_code=400,
content={"error": f"Model not found: {model_name}"}
)
upstream_url = MODEL_REGISTRY[model] + "/v1/audio/transcriptions"
file.file.seek(0)
files = {
"file": (
file.filename,
file.file,
file.content_type or "application/octet-stream"
)
}
data = {
"model": model,
"response_format": response_format,
}
if language:
data["language"] = language
if prompt:
data["prompt"] = prompt
safe_headers = {
k: v
for k, v in headers_with_auth.items()
if k.lower() != "content-type"
}
async with httpx.AsyncClient(timeout=timeout) as client:
resp = await client.post(
upstream_url,
files=files,
data=data,
headers=safe_headers
)
return JSONResponse(status_code=resp.status_code, content=resp.json())
# ------------------------------------------------------------------
# AUDIO SPEECH (TTS)
# ------------------------------------------------------------------
@app.post("/v1/audio/speech")
async def text_to_speech(request: Request):
body = await request.json()
log_request(request, body)
model_name = body.get("model", "unknown")
upstream_url = MODEL_REGISTRY[model_name] + "/v1/audio/speech"
async with httpx.AsyncClient(timeout=timeout) as client:
resp = await client.post(
upstream_url,
json=body,
headers=headers_with_auth
)
return StreamingResponse(
resp.aiter_bytes(),
media_type=resp.headers.get("content-type", "audio/wav"),
status_code=resp.status_code
)
|