Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from fastapi import FastAPI, HTTPException
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from transformers import AutoTokenizer, AutoModel
|
| 5 |
+
import torch
|
| 6 |
+
import numpy as np
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from typing import List, Dict, Any
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
# 创建 FastAPI 应用
|
| 12 |
+
app = FastAPI()
|
| 13 |
+
|
| 14 |
+
# 配置 CORS
|
| 15 |
+
app.add_middleware(
|
| 16 |
+
CORSMiddleware,
|
| 17 |
+
allow_origins=["*"],
|
| 18 |
+
allow_credentials=True,
|
| 19 |
+
allow_methods=["*"],
|
| 20 |
+
allow_headers=["*"],
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# 加载模型和分词器
|
| 24 |
+
model_name = "BAAI/bge-m3"
|
| 25 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 26 |
+
model = AutoModel.from_pretrained(model_name)
|
| 27 |
+
model.eval()
|
| 28 |
+
|
| 29 |
+
# OpenAI 兼容的请求模型
|
| 30 |
+
class EmbeddingRequest(BaseModel):
|
| 31 |
+
input: List[str] | str
|
| 32 |
+
model: str | None = model_name
|
| 33 |
+
encoding_format: str | None = "float"
|
| 34 |
+
user: str | None = None
|
| 35 |
+
|
| 36 |
+
# OpenAI 兼容的响应模型
|
| 37 |
+
class EmbeddingResponse(BaseModel):
|
| 38 |
+
object: str = "list"
|
| 39 |
+
data: List[Dict[str, Any]]
|
| 40 |
+
model: str
|
| 41 |
+
usage: Dict[str, int]
|
| 42 |
+
|
| 43 |
+
def get_embedding(text: str) -> List[float]:
|
| 44 |
+
inputs = tokenizer(
|
| 45 |
+
text,
|
| 46 |
+
padding=True,
|
| 47 |
+
truncation=True,
|
| 48 |
+
max_length=512,
|
| 49 |
+
return_tensors="pt"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
with torch.no_grad():
|
| 53 |
+
outputs = model(**inputs)
|
| 54 |
+
embeddings = outputs.last_hidden_state[:, 0, :].numpy()
|
| 55 |
+
|
| 56 |
+
return embeddings[0].tolist()
|
| 57 |
+
|
| 58 |
+
# OpenAI 兼容的 embeddings endpoint
|
| 59 |
+
@app.post("/v1/embeddings", response_model=EmbeddingResponse)
|
| 60 |
+
async def create_embeddings(request: EmbeddingRequest):
|
| 61 |
+
start_time = time.time()
|
| 62 |
+
|
| 63 |
+
# 处理输入
|
| 64 |
+
if isinstance(request.input, str):
|
| 65 |
+
input_texts = [request.input]
|
| 66 |
+
else:
|
| 67 |
+
input_texts = request.input
|
| 68 |
+
|
| 69 |
+
# 获取嵌入向量
|
| 70 |
+
embeddings = []
|
| 71 |
+
total_tokens = 0
|
| 72 |
+
|
| 73 |
+
for text in input_texts:
|
| 74 |
+
# 计算 token 数量
|
| 75 |
+
tokens = tokenizer.encode(text)
|
| 76 |
+
total_tokens += len(tokens)
|
| 77 |
+
|
| 78 |
+
# 获取嵌入向量
|
| 79 |
+
embedding = get_embedding(text)
|
| 80 |
+
|
| 81 |
+
embeddings.append({
|
| 82 |
+
"object": "embedding",
|
| 83 |
+
"embedding": embedding,
|
| 84 |
+
"index": len(embeddings)
|
| 85 |
+
})
|
| 86 |
+
|
| 87 |
+
response = EmbeddingResponse(
|
| 88 |
+
data=embeddings,
|
| 89 |
+
model=request.model or model_name,
|
| 90 |
+
usage={
|
| 91 |
+
"prompt_tokens": total_tokens,
|
| 92 |
+
"total_tokens": total_tokens
|
| 93 |
+
}
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
return response
|
| 97 |
+
|
| 98 |
+
# Gradio 界面
|
| 99 |
+
def gradio_embedding(text: str) -> Dict:
|
| 100 |
+
# 创建与 OpenAI 兼容的请求
|
| 101 |
+
request = EmbeddingRequest(input=text)
|
| 102 |
+
|
| 103 |
+
# 调用 API 处理函数
|
| 104 |
+
response = create_embeddings(request)
|
| 105 |
+
|
| 106 |
+
return response.dict()
|
| 107 |
+
|
| 108 |
+
# 创建 Gradio 界面
|
| 109 |
+
iface = gr.Interface(
|
| 110 |
+
fn=gradio_embedding,
|
| 111 |
+
inputs=gr.Textbox(lines=3, placeholder="输入要进行编码的文本..."),
|
| 112 |
+
outputs=gr.Json(),
|
| 113 |
+
title="BGE-M3 Embeddings (OpenAI 兼容格式)",
|
| 114 |
+
description="输入文本,获取其对应的嵌入向量,返回格式与 OpenAI API 兼容。",
|
| 115 |
+
examples=[
|
| 116 |
+
["这是一个示例文本。"],
|
| 117 |
+
["人工智能正在改变世界。"]
|
| 118 |
+
]
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# 挂载 Gradio 应用到 FastAPI
|
| 122 |
+
app = gr.mount_gradio_app(app, iface, path="/")
|
| 123 |
+
|
| 124 |
+
# 启动服务
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
import uvicorn
|
| 127 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|